diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9053ee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# JetBrains' IDEs +.idea diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4ad9e28 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.simplesystems.tech/bjj-gym-management/simplesql + +go 1.14 diff --git a/simplesql.go b/simplesql.go new file mode 100644 index 0000000..cfc0a51 --- /dev/null +++ b/simplesql.go @@ -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 +}