Maintain a library of prepared SQL statements (*sql.Stmt)
This repository has been moved to github.com/lestrrat-go/sqllib. This repository exists so that libraries pointing to this URL will keep functioning, but this repository will NOT be updated in the future. Please use the new import path.
import (
"github.com/lestrrat/go-sqllib"
"github.com/pkg/errors"
)
var lib *sqllib.Library
var db *sql.DB
func InitializeDB() {
db, _ = sql.Open(...)
lib = sqllib.New(db)
// Register some SQL queries by name
lib.Register("Simple Select", "SELECT foo FROM bar WHERE a = ?")
}
func SomeFunc(tx *sql.Tx, arg string) error {
// When you access the SQL query again, you can ask for an
// already prepared statement.
stmt, err := lib.GetStmt("Simple Select")
if err != nil {
return errors.Wrap(err, "failed to get statement")
}
// Don't forget to call (*sql.Tx).Stmt on it to make a
// transaction-specific statement
rows, err := tx.Stmt(stmt).Query(arg)
...
}
Using prepared statements repeatedly is usually better for performance.
Keeping prepared statements around for reuse is fairly painful. This library is a very small utility to store SQL queries and refer to them by name to get back already prepared statement.