#sqlx
Package sqlx is the work of GitHub user jmoiron
. I forked github.com/jmoiron/sqlx on January the 23rd, 2015.
My modified version of sqlx avoids using panic(s). Panics should in my opinon only be used by runtimes to signal fatal events, like fx. fatal programming errors.
Instead of recovering from a panic, you absolutely must take action on every non-nil error that had been returned from this package. You should do that for any non-nil error anyway.
Functions and methods that had been deleted, because it panics:
- Function sqlx.MustOpen
- Method sqlx.DB.MustBegin
- Method sqlx.DB.MustExec
- Method sqlx.Stmt.MustExec
- Function sqlx.MustConnect
- Function sqlx.MustExec
- Method sqlx.NamedStmt.MustExec
- Function sqlx.reflectx.mustBe
- Method sqlx.Tx.MustExec
The private function sqlx.reflectx.mustBe with this signature:
func mustBe(v Kinder, expected reflect.Kind)
had been replaced by sqlx.reflectx.isKind with this signature:
func isKind(v Kinder, expected reflect.Kind) (ok bool, err error)
The following list are the names of methods that had been changed because of the change from mustBe to isKind with 2 return values.
- sqlx.reflectx.Mapper.FieldMap
- sqlx.reflectx.Mapper.FieldByName
- sqlx.reflectx.Mapper.FieldsByName
- sqlx.reflectx.Mapper.TraversalsByName
- sqlx.Rows.StructScan changed because of changes to sqlx.reflectx.Mapper.TraversalsByName
- sqlx.bindArgs changed because of changes to sqlx.reflectx.Mapper.TransversalsByName
- sqlx.scanAny changed because of changes to sqlx.reflectx.Mapper.TransversalsByName
- sqlx.scanAll changed because of changes to sqlx.reflectx.Mapper.TransversalsByName
Package sqlx is a library, which provides a set of extensions on go's standard
database/sql
library. The sqlx versions of sql.DB
, sql.TX
, sql.Stmt
,
et al. all leave the underlying interfaces untouched, so that their interfaces
are a superset on the standard ones. This makes it relatively painless to
integrate existing codebases using database/sql with sqlx.
Major additional concepts are:
- Marshal rows into structs (with embedded struct support), maps, and slices
- Named parameter support including prepared statements
Get
andSelect
to go quickly from query to struct/sliceLoadFile
for executing statements from a file
jmoiron has a fairly comprehensive documentation for sqlx. Just renember that if you use github.com/larsth/sqlx, then all Must... functions and methods does not exists.
You can also read the usage below for a quick sample on how sqlx works, or check out the API documentation on godoc.
go get github.com/larsth/sqlx
Row headers can be ambiguous (SELECT 1 AS a, 2 AS a
), and the result of
Columns()
can have duplicate names on queries like:
SELECT a.id, a.name, b.id, b.name FROM foos AS a JOIN foos AS b ON a.parent = b.id;
making a struct or map destination ambiguous. Use AS
in your queries
to give rows distinct names, rows.Scan
to scan them manually, or
SliceScan
to get a slice of results.
FIXME(larsth): needs cleanup (Must...-methods and functions -> Non-Must functions and methods)
Below is an example which shows some common use cases for sqlx. Check sqlx_test.go for more usage.
package main
import (
_ "github.com/lib/pq"
"database/sql"
"github.com/larsth/sqlx"
"log"
)
var schema = `
CREATE TABLE person (
first_name text,
last_name text,
email text
);
CREATE TABLE place (
country text,
city text NULL,
telcode integer
)`
type Person struct {
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string
}
type Place struct {
Country string
City sql.NullString
TelCode int
}
func main() {
// this connects & tries a simple 'SELECT 1', panics on error
// use sqlx.Open() for sql.Open() semantics
db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
if err != nil {
log.Fatalln(err)
}
// exec the schema or fail; multi-statement Exec behavior varies between
// database drivers; pq will exec them all, sqlite3 won't, ymmv
db.MustExec(schema)
tx, err := db.Begin()
if err != nil {
log.Fatalln(err.Error())
}
tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "Jason", "Moiron", "[email protected]")
tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "John", "Doe", "[email protected]")
tx.MustExec("INSERT INTO place (country, city, telcode) VALUES ($1, $2, $3)", "United States", "New York", "1")
tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Hong Kong", "852")
tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Singapore", "65")
// Named queries can use structs, so if you have an existing struct (i.e. person := &Person{}) that you have populated, you can pass it in as &person
tx.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "[email protected]"})
tx.Commit()
// Query the database, storing results in a []Person (wrapped in []interface{})
people := []Person{}
db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC")
jason, john := people[0], people[1]
fmt.Printf("%#v\n%#v", jason, john)
// Person{FirstName:"Jason", LastName:"Moiron", Email:"[email protected]"}
// Person{FirstName:"John", LastName:"Doe", Email:"[email protected]"}
// You can also get a single result, a la QueryRow
jason = Person{}
err = db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason")
fmt.Printf("%#v\n", jason)
// Person{FirstName:"Jason", LastName:"Moiron", Email:"[email protected]"}
// if you have null fields and use SELECT *, you must use sql.Null* in your struct
places := []Place{}
err = db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC")
if err != nil {
fmt.Println(err)
return
}
usa, singsing, honkers := places[0], places[1], places[2]
fmt.Printf("%#v\n%#v\n%#v\n", usa, singsing, honkers)
// Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1}
// Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65}
// Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852}
// Loop through rows using only one struct
place := Place{}
rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
err := rows.StructScan(&place)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("%#v\n", place)
}
// Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1}
// Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852}
// Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65}
// Named queries, using `:name` as the bindvar. Automatic bindvar support
// which takes into account the dbtype based on the driverName on sqlx.Open/Connect
_, err = db.NamedExec(`INSERT INTO person (first_name,last_name,email) VALUES (:first,:last,:email)`,
map[string]interface{}{
"first": "Bin",
"last": "Smuth",
"email": "[email protected]",
})
// Selects Mr. Smith from the database
rows, err = db.NamedQuery(`SELECT * FROM person WHERE first_name=:fn`, map[string]interface{}{"fn": "Bin"})
// Named queries can also use structs. Their bind names follow the same rules
// as the name -> db mapping, so struct fields are lowercased and the `db` tag
// is taken into consideration.
rows, err = db.NamedQuery(`SELECT * FROM person WHERE first_name=:first_name`, jason)
}
Get and Select are able to take base types, so the following is now possible:
var name string
db.Get(&name, "SELECT first_name FROM person WHERE id=$1", 10)
var ids []int64
db.Select(&ids, "SELECT id FROM person LIMIT 20;")
This can get complicated with destination types which are structs, like sql.NullString
. Because of this, straightforward rules for scannability had to be developed. Iff something is "Scannable", then it is used directly in rows.Scan
; if it's not, then the standard sqlx struct rules apply.
Something is scannable if any of the following are true:
- It is not a struct, ie.
reflect.ValueOf(v).Kind() != reflect.Struct
- It implements the
sql.Scanner
interface - It has no exported fields (eg.
time.Time
)
Scan targets obey Go attribute rules directly, including nested embedded structs. Older versions of sqlx would attempt to also descend into non-embedded structs, but this is no longer supported.
Go makes accessing 'ambiguous selectors' a compile time error, defining structs with ambiguous selectors is legal. Sqlx will decide which field to use on a struct based on a breadth first search of the struct and any structs it embeds, as specified by the order of the fields as accessible by reflect
, which generally means in source-order. This means that sqlx chooses the outer-most, top-most matching name for targets, even when the selector might technically be ambiguous.
By default, scanning into structs requires the structs to have fields for all of the columns in the query. This was done for a few reasons:
- A mistake in naming during development could lead you to believe that data is being written to a field when actually it can't be found and it is being dropped
- This behavior mirrors the behavior of the Go compiler with respect to unused variables
- Selecting more data than you need is wasteful (more data on the wire, more time marshalling, etc)
Unlike Marshallers in the stdlib, the programmer scanning an sql result into a struct will generally have a full understanding of what the underlying data model is and full control over the SQL statement.
Despite this, there are use cases where it's convenient to be able to ignore unknown
columns. In most of these cases, you might be better off with ScanSlice
, but where
you want to still use structs, there is now the Unsafe
method. Its usage is most
simply shown in an example:
db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
if err != nil {
log.Fatal(err)
}
type Person {
Name string
}
var p Person
// This fails, because there is no destination for location in Person
err = db.Get(&p, "SELECT name, location FROM person LIMIT 1")
udb := db.Unsafe()
// This succeeds and just sets `Name` in the p struct
err = udb.Get(&p, "SELECT name, location FROM person LIMIT 1")
The Unsafe
method is implemented on Tx
, DB
, and Stmt
. When you use an unsafe
Tx
or DB
to create a new Tx
or Stmt
, those inherit its lack of safety.