This commit is contained in:
jeff 2020-07-14 14:59:39 -07:00
parent 27e5214062
commit 9568b3fd69
3 changed files with 45 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
# JetBrains' IDEs
.idea

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.simplesystems.tech/bjj-gym-management/simplesql
go 1.14

40
simplesql.go Normal file
View File

@ -0,0 +1,40 @@
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 := make(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
}