README
¶
PostgreSQL client for Golang 
Supports:
- Basic types: integers, floats, string, bool, time.Time, and pointers to these types.
- sql.NullBool, sql.NullString, sql.NullInt64 and sql.Float64.
- sql.Scanner and sql/driver.Valuer interfaces.
- Arrays.
- Partially hstore.
- Transactions.
- Prepared statements.
- Notifications using
LISTEN
andNOTIFY
. - Copying data using
COPY FROM
andCOPY TO
. - Timeouts. Client sends
CancelRequest
message on timeout. - Automatic and safe connection pool.
- Queries retries on network errors.
- PostgreSQL to Go struct mapping.
- Migrations.
- Sharding.
API docs: http://godoc.org/gopkg.in/pg.v3. Examples: http://godoc.org/gopkg.in/pg.v3#pkg-examples.
Installation
Install:
go get gopkg.in/pg.v3
Quickstart
package pg_test
import (
"fmt"
"gopkg.in/pg.v3"
)
type User struct {
Id int64
Name string
Emails []string
}
func CreateUser(db *pg.DB, user *User) error {
_, err := db.QueryOne(user, `
INSERT INTO users (name, emails) VALUES (?name, ?emails)
RETURNING id
`, user)
return err
}
func GetUser(db *pg.DB, id int64) (*User, error) {
var user User
_, err := db.QueryOne(&user, `SELECT * FROM users WHERE id = ?`, id)
return &user, err
}
func GetUsers(db *pg.DB) ([]User, error) {
var users []User
_, err := db.Query(&users, `SELECT * FROM users`)
return users, err
}
func GetUsersByIds(db *pg.DB, ids []int64) ([]User, error) {
var users []User
_, err := db.Query(&users, `SELECT * FROM users WHERE id IN (?)`, pg.Ints(ids))
return users, err
}
func ExampleDB_Query() {
db := pg.Connect(&pg.Options{
User: "postgres",
})
_, err := db.Exec(`CREATE TEMP TABLE users (id serial, name text, emails text[])`)
if err != nil {
panic(err)
}
err = CreateUser(db, &User{
Name: "admin",
Emails: []string{"admin1@admin", "admin2@admin"},
})
if err != nil {
panic(err)
}
err = CreateUser(db, &User{
Name: "root",
Emails: []string{"root1@root", "root2@root"},
})
if err != nil {
panic(err)
}
user, err := GetUser(db, 1)
if err != nil {
panic(err)
}
users, err := GetUsers(db)
if err != nil {
panic(err)
}
fmt.Println(user)
fmt.Println(users[0], users[1])
// Output: &{1 admin [admin1@admin admin2@admin]}
// {1 admin [admin1@admin admin2@admin]} {2 root [root1@root root2@root]}
}
Why not database/sql, lib/pq, or GORM
- No
rows.Close
to manually manage connections. - go-pg can automatically map rows on Go structs.
- go-pg is at least 3x faster than GORM on querying 100 rows from table.
- go-pg supports client-side placeholders that allow you to write complex queries and have full power of SQL.
Benchmark
BenchmarkQueryRowsOptimized-4 10000 154480 ns/op 87789 B/op 624 allocs/op
BenchmarkQueryRowsReflect-4 10000 196261 ns/op 102224 B/op 925 allocs/op
BenchmarkQueryRowsStdlibPq-4 5000 236584 ns/op 166528 B/op 1324 allocs/op
BenchmarkQueryRowsGORM-4 2000 690532 ns/op 399661 B/op 6171 allocs/op
Howto
Please go through examples to get the idea how to use this package.
Documentation
¶
Overview ¶
Package gopkg.in/pg.v3 implements a PostgreSQL client.
Example (QueryTimeout) ¶
Output:
Index ¶
- Variables
- func AppendQ(dst []byte, src string, params ...interface{}) ([]byte, error)
- func Decode(dst interface{}, b []byte) error
- func DecodeValue(v reflect.Value, b []byte) error
- type Collection
- type ColumnLoader
- type DB
- func (db *DB) Begin() (*Tx, error)
- func (db *DB) Close() error
- func (db *DB) CopyFrom(r io.Reader, q string, args ...interface{}) (*Result, error)
- func (db *DB) CopyTo(w io.WriteCloser, q string, args ...interface{}) (*Result, error)
- func (db *DB) Exec(q string, args ...interface{}) (res *Result, err error)
- func (db *DB) ExecOne(q string, args ...interface{}) (*Result, error)
- func (db *DB) Listen(channels ...string) (*Listener, error)
- func (db *DB) Prepare(q string) (*Stmt, error)
- func (db *DB) Query(coll interface{}, q string, args ...interface{}) (res *Result, err error)
- func (db *DB) QueryOne(record interface{}, q string, args ...interface{}) (*Result, error)
- func (db *DB) RunInTransaction(fn func(*Tx) error) error
- func (db *DB) UseTimeout(d time.Duration) *DB
- type Error
- type F
- type IntSet
- type IntegrityError
- type Ints
- type Listener
- type Options
- type Q
- type QueryAppender
- type RawQueryAppender
- type Result
- type Stmt
- func (stmt *Stmt) Close() error
- func (stmt *Stmt) Exec(args ...interface{}) (res *Result, err error)
- func (stmt *Stmt) ExecOne(args ...interface{}) (*Result, error)
- func (stmt *Stmt) Query(coll interface{}, args ...interface{}) (res *Result, err error)
- func (stmt *Stmt) QueryOne(record interface{}, args ...interface{}) (*Result, error)
- type Strings
- type Tx
- func (tx *Tx) Commit() (err error)
- func (tx *Tx) Exec(q string, args ...interface{}) (*Result, error)
- func (tx *Tx) ExecOne(q string, args ...interface{}) (*Result, error)
- func (tx *Tx) Prepare(q string) (*Stmt, error)
- func (tx *Tx) Query(coll interface{}, q string, args ...interface{}) (*Result, error)
- func (tx *Tx) QueryOne(record interface{}, q string, args ...interface{}) (*Result, error)
- func (tx *Tx) Rollback() (err error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrSSLNotSupported = errorf("pg: SSL is not enabled on the server") ErrNoRows = errorf("pg: no rows in result set") ErrMultiRows = errorf("pg: multiple rows in result set") )
var (
// Discard can be used with Query and QueryOne to discard rows.
Discard discardLoader
)
Functions ¶
Types ¶
type Collection ¶
type Collection interface { // NewRecord returns ColumnLoader or struct that are used to scan // columns from the current row. NewRecord() interface{} }
Collection is a set of records mapped to database rows.
type ColumnLoader ¶
type ColumnLoader interface { // Scan assigns a column value from a row. // // An error should be returned if the value can not be stored // without loss of information. // // TODO(vmihailenco): rename to ScanColumn LoadColumn(colIdx int, colName string, b []byte) error }
ColumnLoader is an interface used by LoadColumn.
TODO(vmihailenco): rename to ColumnScanner
func LoadInto ¶
func LoadInto(values ...interface{}) ColumnLoader
LoadInto returns ColumnLoader that copies the columns in the row into the values.
TODO(vmihailenco): rename to Scan
Example ¶
Output: foo bar <nil>
func NewColumnLoader ¶
func NewColumnLoader(dst interface{}) (ColumnLoader, error)
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.
func Connect ¶
Connect connects to a database using provided options.
The returned DB is safe for concurrent use by multiple goroutines and maintains its own connection pool.
Example ¶
Output: <nil>
func (*DB) Close ¶
Close closes the database client, releasing any open resources.
It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines.
func (*DB) Exec ¶
Exec executes a query ignoring returned rows. The args are for any placeholder parameters in the query.
Example ¶
Output: -1 <nil>
func (*DB) ExecOne ¶
ExecOne acts like Exec, but query must affect only one row. It returns ErrNoRows error when query returns zero rows or ErrMultiRows when query returns multiple rows.
func (*DB) Prepare ¶
Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement.
Example ¶
Output: foo bar <nil>
func (*DB) Query ¶
Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.
Example ¶
Output: &{1 admin [admin1@admin admin2@admin]} {1 admin [admin1@admin admin2@admin]} {2 root [root1@root root2@root]}
func (*DB) QueryOne ¶
QueryOne acts like Query, but query must return only one row. It returns ErrNoRows error when query returns zero rows or ErrMultiRows when query returns multiple rows.
Example ¶
Output: 1 {admin}
func (*DB) RunInTransaction ¶
RunInTransaction runs a function in a transaction. If function returns an error transaction is rollbacked, otherwise transaction is committed.
type F ¶
type F string
F is a QueryAppender that represents SQL field, e.g. table or column name.
func (F) AppendQuery ¶
type IntegrityError ¶
type IntegrityError struct {
// contains filtered or unexported fields
}
type Ints ¶
type Ints []int64
Example ¶
Output: [0 1 2 3 4 5 6 7 8 9 10] <nil>
func (Ints) AppendQuery ¶
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Not thread-safe.
Example ¶
Output: mychan "hello world" <nil>
type Options ¶
type Options struct { // The network type, either tcp or unix. // Default is tcp. Network string Host string Port string User string Password string Database string // Whether to use secure TCP/IP connections (TLS). SSL bool // Run-time configuration parameters to be set on connection. Params map[string]interface{} // The deadline for establishing new connections. If reached, // dial will fail with a timeout. // Default is 5 seconds. DialTimeout time.Duration // The timeout for socket reads. If reached, commands will fail // with a timeout error instead of blocking. // Default is no timeout. ReadTimeout time.Duration // The timeout for socket writes. If reached, commands will fail // with a timeout error instead of blocking. // Default is no timeout. WriteTimeout time.Duration // The maximum number of open socket connections. // Default is 10 connections. PoolSize int // The amount of time client waits for free connection if all // connections are busy before returning an error. // Default is 5 seconds. PoolTimeout time.Duration // The amount of time after which client closes idle connections. // Default is to not close idle connections. IdleTimeout time.Duration // The frequency of idle checks. // Default is 1 minute. IdleCheckFrequency time.Duration }
Database connection options.
type Q ¶
type Q string
Q is a QueryAppender that represents safe SQL query.
func MustFormatQ ¶
func (Q) AppendQuery ¶
func (Q) AppendRawQuery ¶
type QueryAppender ¶
type RawQueryAppender ¶
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
A Result summarizes an executed SQL command.
type Stmt ¶
type Stmt struct {
// contains filtered or unexported fields
}
Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
func (*Stmt) ExecOne ¶
ExecOne acts like Exec, but query must affect only one row. It returns ErrNoRows error when query returns zero rows or ErrMultiRows when query returns multiple rows.
type Strings ¶
type Strings []string
Example ¶
Output: [foo bar] <nil>