-
-
Save longfellowone/9ce8be1f4ae74bd869ac9d7d447094e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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