41 lines
991 B
Go
41 lines
991 B
Go
package simplesql
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
// StmtKey is the simplest map key to use for mapping to a sql.Stmt, or a string statement.
|
|
// It is up to the user to properly map StmtKeys to the right statement.
|
|
type StmtKey int
|
|
|
|
// Stmts is the type that will be used to prepare and close sql.Stmts.
|
|
type Stmts map[StmtKey]*sql.Stmt
|
|
|
|
// Close will close all prepared statements.
|
|
// This should be called after all statements are done.
|
|
func (s *Stmts) Close() {
|
|
for _, stmt := range *s {
|
|
_ = stmt.Close()
|
|
}
|
|
}
|
|
|
|
// New will create a Stmts from the pass queries. Each string query will be prepared
|
|
// and mapped to the same key.
|
|
func New(ctx context.Context, db *sql.DB, sqlStmts map[StmtKey]string) (Stmts, error) {
|
|
s := Stmts{}
|
|
|
|
// Iterate through SQL statements and prepare them
|
|
for key, q := range sqlStmts {
|
|
ps, err := db.PrepareContext(ctx, q)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("preparing statement: %w", err)
|
|
}
|
|
|
|
s[key] = ps
|
|
}
|
|
|
|
return s, nil
|
|
}
|