Skip to content

Instantly share code, notes, and snippets.

@longfellowone
Created March 8, 2019 03:44
Show Gist options
  • Save longfellowone/9ce8be1f4ae74bd869ac9d7d447094e1 to your computer and use it in GitHub Desktop.
Save longfellowone/9ce8be1f4ae74bd869ac9d7d447094e1 to your computer and use it in GitHub Desktop.
const (
stmtCreateUser = iota
stmtGetUser
stmtUpdateUser
)
var stmtPairs = []struct {
id int
stmt string
}{
{stmtGetUser, `SELECT u.email, u.data
FROM user u
WHERE u.id=$1
FOR UPDATE`},
{stmtUpdateUser, `UPDATE user SET data=$1
WHERE id=$2`},
}
func (d *DB) prepareStmts() error {
for _, stmtPair := range stmtPairs {
st, err := d.DB.Prepare(stmtPair.stmt)
if err != nil {
return fmt.Errorf("Failed to prepare statement %s: %s", stmtPair.stmt, err.Error())
}
d.stmts[stmtPair.id] = st
}
return nil
}
// NewDB creates new Postgres connection
func NewDB(dataSource string) (*DB, error) {
db, err := sql.Open("postgres", dataSource)
if err != nil {
return nil, err
}
res := &DB{DB: db, stmts: map[int]*sql.Stmt{}}
if err := res.prepareStmts(); err != nil {
return nil, err
}
return res, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment