项目作者: ferdypruis

项目描述 :
Use named parameters with Go's database/sql
高级语言: Go
项目地址: git://github.com/ferdypruis/sqeasy.git
创建时间: 2020-09-30T06:46:46Z
项目社区:https://github.com/ferdypruis/sqeasy

开源协议:MIT License

下载


sqeasy

PkgGoDev

Small wrappers to make usage of Go’s sql-package with a CockroachDB database easier to maintain, by for example
mapping variables to positional arguments.

Examples

Map columns to destination values

Instead of summing all destination variables in Scan(), map the columns onto your variables with sqeasy.SelectColumns
and have them scanned into them.

  1. var db *sql.DB
  2. var (
  3. colA string
  4. timestamp time.Time
  5. count int
  6. )
  7. columns := sqeasy.SelectColumns{
  8. {`a_column`, &colA},
  9. {`"timestamp"`, ×tamp},
  10. {`COUNT(*)`, &count},
  11. }
  12. row := db.QueryRow("SELECT " + columns.ExprList() + " FROM table")
  13. err := columns.Scan(row)

Use named parameters

Instead of the $1, $2, $3 etc positional parameters in your queries, use named ones. Bind values to the names
using sqeasy.NamedParams.

  1. var db *sql.DB
  2. params := sqeasy.NamedParams{
  3. {"colA", "notthis"},
  4. {"timestamp", time.Now()},
  5. }
  6. query := "SELECT * FROM table WHERE a_column != :colA AND timestamp < :timestamp"
  7. row := sqeasy.QueryRow(db, query, params)

The same sqeasy.NamedParams could be used to for example generate INSERT statements.

  1. var db *sql.DB
  2. params := sqeasy.NamedParams{
  3. "a_column": "this",
  4. "timestamp": time.Now(),
  5. }
  6. query := "INSERT INTO table (" + params.ExprList() + ") VALUES (" + params.Params() + ")"
  7. row := sqeasy.QueryRow(db, query, params)