Documentation ¶
Overview ¶
Package gopkg.in/pg.v4 implements a PostgreSQL client.
Index ¶
- Variables
- func Array(v interface{}) *types.Array
- func F(field string, params ...interface{}) types.F
- func Q(query string, params ...interface{}) types.Q
- func Scan(values ...interface{}) orm.ColumnScanner
- func SetLogger(logger *log.Logger)
- type DB
- func (db *DB) Begin() (*Tx, error)
- func (db *DB) Close() error
- func (db *DB) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (*types.Result, error)
- func (db *DB) CopyTo(w io.WriteCloser, query interface{}, params ...interface{}) (*types.Result, error)
- func (db *DB) Create(model interface{}) error
- func (db *DB) Delete(model interface{}) error
- func (db *DB) Exec(query interface{}, params ...interface{}) (res *types.Result, err error)
- func (db *DB) ExecOne(query interface{}, params ...interface{}) (*types.Result, error)
- func (db *DB) FormatQuery(dst []byte, query string, params ...interface{}) []byte
- func (db *DB) Listen(channels ...string) (*Listener, error)
- func (db *DB) Model(model interface{}) *orm.Query
- func (db *DB) Options() *Options
- func (db *DB) Prepare(q string) (*Stmt, error)
- func (db *DB) Query(model, query interface{}, params ...interface{}) (res *types.Result, err error)
- func (db *DB) QueryOne(model, query interface{}, params ...interface{}) (*types.Result, error)
- func (db *DB) RunInTransaction(fn func(*Tx) error) error
- func (db *DB) Update(model interface{}) error
- func (db *DB) WithTimeout(d time.Duration) *DB
- type Error
- type IntSet
- type Ints
- type Listener
- type Options
- type Stmt
- func (stmt *Stmt) Close() error
- func (stmt *Stmt) Exec(params ...interface{}) (res *types.Result, err error)
- func (stmt *Stmt) ExecOne(params ...interface{}) (*types.Result, error)
- func (stmt *Stmt) Query(model interface{}, params ...interface{}) (res *types.Result, err error)
- func (stmt *Stmt) QueryOne(model interface{}, params ...interface{}) (*types.Result, error)
- type Strings
- type Tx
- func (tx *Tx) Commit() (err error)
- func (tx *Tx) CopyFrom(r io.Reader, query string, params ...interface{}) (*types.Result, error)
- func (tx *Tx) Create(model interface{}) error
- func (tx *Tx) Delete(model interface{}) error
- func (tx *Tx) Exec(query interface{}, params ...interface{}) (*types.Result, error)
- func (tx *Tx) ExecOne(query interface{}, params ...interface{}) (*types.Result, error)
- func (tx *Tx) FormatQuery(dst []byte, query string, params ...interface{}) []byte
- func (tx *Tx) Model(model interface{}) *orm.Query
- func (tx *Tx) Prepare(q string) (*Stmt, error)
- func (tx *Tx) Query(model interface{}, query interface{}, params ...interface{}) (*types.Result, error)
- func (tx *Tx) QueryOne(model interface{}, query interface{}, params ...interface{}) (*types.Result, error)
- func (tx *Tx) Rollback() (err error)
- func (tx *Tx) Update(model interface{}) error
Examples ¶
- Array
- Connect
- DB.Begin
- DB.CopyFrom
- DB.Create
- DB.Create (OnConflict)
- DB.Create (SelectOrCreate)
- DB.Delete
- DB.Delete (MultipleRows)
- DB.Exec
- DB.Model (CountRows)
- DB.Model (FirstRow)
- DB.Model (HasMany)
- DB.Model (HasOne)
- DB.Model (LastRow)
- DB.Model (ManyToMany)
- DB.Model (NullEmptyValue)
- DB.Model (PostgresArrayStructTag)
- DB.Model (SelectAllColumns)
- DB.Model (SelectSomeColumns)
- DB.Prepare
- DB.Query
- DB.QueryOne
- DB.QueryOne (Returning_id)
- DB.RunInTransaction
- DB.Update
- DB.Update (MultipleRows)
- DB.Update (SomeColumns)
- DB.Update (UsingSqlFunction)
- DB.WithTimeout
- F
- Ints
- Ints (In)
- Listener
- Q
- Scan
- Strings
Constants ¶
This section is empty.
Variables ¶
var ( ErrNoRows = internal.ErrNoRows ErrMultiRows = internal.ErrMultiRows )
var Discard orm.Discard
Discard is used with Query and QueryOne to discard rows.
Functions ¶
func Array ¶
Array returns an Array type that represents PostgreSQL array of any type.
Example ¶
src := []string{"one@example.com", "two@example.com"} var dst []string _, err := db.QueryOne(pg.Scan(pg.Array(&dst)), `SELECT ?`, pg.Array(src)) if err != nil { panic(err) } fmt.Println(dst)
Output: [one@example.com two@example.com]
func F ¶
F returns a ValueAppender that represents SQL identifier, e.g. table or column name.
Example ¶
db := modelDB() var book Book err := db.Model(&book).Where("? = ?", pg.F("id"), 1).Select() if err != nil { panic(err) } fmt.Println(book)
Output: Book<Id=1 Title="book 1">
func Q ¶
Q returns a ValueAppender that represents safe SQL query.
Example ¶
db := modelDB() var maxId int err := db.Model(Book{}).Column(pg.Q("max(id)")).Select(&maxId) if err != nil { panic(err) } fmt.Println(maxId)
Output: 3
func Scan ¶
func Scan(values ...interface{}) orm.ColumnScanner
Scan returns ColumnScanner that copies the columns in the row into the values.
Example ¶
var s1, s2 string _, err := db.QueryOne(pg.Scan(&s1, &s2), `SELECT ?, ?`, "foo", "bar") fmt.Println(s1, s2, err)
Output: foo bar <nil>
Types ¶
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 ¶
db := pg.Connect(&pg.Options{ User: "postgres", }) err := db.Close() fmt.Println(err)
Output: <nil>
func (*DB) Begin ¶
Begin starts a transaction. Most callers should use RunInTransaction instead.
Example ¶
db := txExample() tx, err := db.Begin() if err != nil { panic(err) } var counter int _, err = tx.QueryOne(pg.Scan(&counter), `SELECT counter FROM tx_test`) if err != nil { tx.Rollback() panic(err) } counter++ _, err = tx.Exec(`UPDATE tx_test SET counter = ?`, counter) if err != nil { tx.Rollback() panic(err) } err = tx.Commit() if err != nil { panic(err) } fmt.Println(counter)
Output: 1
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) CopyFrom ¶
func (db *DB) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (*types.Result, error)
CopyFrom copies data from reader to a table.
Example ¶
_, err := db.Exec(`CREATE TEMP TABLE words(word text, len int)`) if err != nil { panic(err) } r := strings.NewReader("hello,5\nfoo,3\n") _, err = db.CopyFrom(r, `COPY words FROM STDIN WITH CSV`) if err != nil { panic(err) } buf := &bytes.Buffer{} _, err = db.CopyTo(&NopWriteCloser{buf}, `COPY words TO STDOUT WITH CSV`) if err != nil { panic(err) } fmt.Println(buf.String())
Output: hello,5 foo,3
func (*DB) CopyTo ¶
func (db *DB) CopyTo(w io.WriteCloser, query interface{}, params ...interface{}) (*types.Result, error)
CopyTo copies data from a table to writer.
func (*DB) Create ¶
Create inserts the model into database.
Example ¶
db := modelDB() book := Book{ Title: "new book", AuthorID: 1, } err := db.Create(&book) if err != nil { panic(err) } fmt.Println(book)
Output: Book<Id=4 Title="new book">
Example (OnConflict) ¶
db := modelDB() book := Book{ Id: 100, Title: "book 100", } for i := 0; i < 2; i++ { res, err := db.Model(&book).OnConflict("DO NOTHING").Create() if err != nil { panic(err) } if res.Affected() > 0 { fmt.Println("created") } else { fmt.Println("did nothing") } } err := db.Delete(&book) if err != nil { panic(err) }
Output: created did nothing
Example (SelectOrCreate) ¶
db := modelDB() author := Author{ Name: "R. Scott Bakker", } created, err := db.Model(&author). Column("id"). Where("name = ?name"). OnConflict("DO NOTHING"). Returning("id"). SelectOrCreate() if err != nil { panic(err) } fmt.Println(created, author)
Output: true Author<ID=2 Name="R. Scott Bakker">
func (*DB) Delete ¶
Delete deletes the model from database.
Example ¶
db := modelDB() book := Book{ Title: "title 1", AuthorID: 1, } err := db.Create(&book) if err != nil { panic(err) } err = db.Delete(book) if err != nil { panic(err) } err = db.Delete(book) fmt.Println(err)
Output: pg: no rows in result set
Example (MultipleRows) ¶
db := modelDB() ids := pg.Ints{1, 2, 3} res, err := db.Model(Book{}).Where("id IN (?)", ids).Delete() if err != nil { panic(err) } fmt.Println("deleted", res.Affected()) count, err := db.Model(Book{}).Count() if err != nil { panic(err) } fmt.Println("left", count)
Output: deleted 3 left 0
func (*DB) Exec ¶
Exec executes a query ignoring returned rows. The params are for any placeholder parameters in the query.
Example ¶
res, err := db.Exec(`CREATE TEMP TABLE test()`) fmt.Println(res.Affected(), err)
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) FormatQuery ¶
func (*DB) Model ¶
Model returns new query for the model.
Example (CountRows) ¶
db := modelDB() count, err := db.Model(Book{}).Count() if err != nil { panic(err) } fmt.Println(count)
Output: 3
Example (FirstRow) ¶
db := modelDB() var firstBook Book err := db.Model(&firstBook).First() if err != nil { panic(err) } fmt.Println(firstBook)
Output: Book<Id=1 Title="book 1">
Example (HasMany) ¶
db := modelDB() var author Author err := db.Model(&author).Column("author.*", "Books").First() if err != nil { panic(err) } fmt.Println(author.Books[0], author.Books[1])
Output: Book<Id=1 Title="book 1"> Book<Id=2 Title="book 2">
Example (HasOne) ¶
db := modelDB() var book Book err := db.Model(&book).Column("book.*", "Author").First() if err != nil { panic(err) } fmt.Println(book, book.Author)
Output: Book<Id=1 Title="book 1"> Author<ID=1 Name="author 1">
Example (LastRow) ¶
db := modelDB() var lastBook Book err := db.Model(&lastBook).Last() if err != nil { panic(err) } fmt.Println(lastBook)
Output: Book<Id=3 Title="book 3">
Example (ManyToMany) ¶
db := modelDB() var book Book err := db.Model(&book).Column("book.*", "Genres").First() if err != nil { panic(err) } fmt.Println(book.Genres[0], book.Genres[1])
Output: Genre<Id=1 Name="genre 1"> Genre<Id=2 Name="genre 2">
Example (NullEmptyValue) ¶
type Example struct { Hello string `sql:",null"` } var str sql.NullString _, err := db.QueryOne(pg.Scan(&str), "SELECT ?hello", Example{Hello: ""}) if err != nil { panic(err) } fmt.Println(str.Valid)
Output: false
Example (PostgresArrayStructTag) ¶
type Item struct { Id int64 Emails []string `pg:",array"` // marshalled as PostgreSQL array Numbers []int `pg:",array"` // marshalled as PostgreSQL array } _, err := db.Exec(`CREATE TEMP TABLE items (id serial, emails text[], numbers int[])`) if err != nil { panic(err) } item1 := Item{ Id: 1, Emails: []string{"one@example.com", "two@example.com"}, Numbers: []int{123, 321}, } if err := db.Create(&item1); err != nil { panic(err) } var item Item err = db.Model(&item).Where("id = ?", 1).Select() if err != nil { panic(err) } fmt.Println(item)
Output: {1 [one@example.com two@example.com] [123 321]}
Example (SelectAllColumns) ¶
db := modelDB() var book Book err := db.Model(&book).Column("book.*").First() if err != nil { panic(err) } fmt.Println(book, book.AuthorID)
Output: Book<Id=1 Title="book 1"> 1
Example (SelectSomeColumns) ¶
db := modelDB() var book Book err := db.Model(&book). Column("book.id"). First() if err != nil { panic(err) } fmt.Println(book)
Output: Book<Id=1 Title="">
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 ¶
stmt, err := db.Prepare(`SELECT $1::text, $2::text`) if err != nil { panic(err) } var s1, s2 string _, err = stmt.QueryOne(pg.Scan(&s1, &s2), "foo", "bar") fmt.Println(s1, s2, err)
Output: foo bar <nil>
func (*DB) Query ¶
Query executes a query that returns rows, typically a SELECT. The params are for any placeholder parameters in the query.
Example ¶
package main import ( "fmt" "gopkg.in/pg.v4" ) type User struct { Id int64 Name string Emails []string } func (u User) String() string { return fmt.Sprintf("User<%d %s %v>", u.Id, u.Name, u.Emails) } type Story struct { Id int64 Title string UserId int64 User *User } func (s Story) String() string { return fmt.Sprintf("Story<%d %s %s>", s.Id, s.Title, s.User) } func createSchema(db *pg.DB) error { queries := []string{ `CREATE TEMP TABLE users (id serial, name text, emails jsonb)`, `CREATE TEMP TABLE stories (id serial, title text, user_id bigint)`, } for _, q := range queries { _, err := db.Exec(q) if err != nil { return err } } return nil } func main() { db := pg.Connect(&pg.Options{ User: "postgres", }) err := createSchema(db) if err != nil { panic(err) } user1 := &User{ Name: "admin", Emails: []string{"admin1@admin", "admin2@admin"}, } err = db.Create(user1) if err != nil { panic(err) } err = db.Create(&User{ Name: "root", Emails: []string{"root1@root", "root2@root"}, }) if err != nil { panic(err) } story1 := &Story{ Title: "Cool story", UserId: user1.Id, } err = db.Create(story1) if err != nil { panic(err) } var user User err = db.Model(&user).Where("id = ?", user1.Id).Select() if err != nil { panic(err) } var users []User err = db.Model(&users).Select() if err != nil { panic(err) } var story Story err = db.Model(&story). Column("story.*", "User"). Where("story.id = ?", story1.Id). Select() if err != nil { panic(err) } fmt.Println(user) fmt.Println(users[0], users[1]) fmt.Println(story) }
Output: User<1 admin [admin1@admin admin2@admin]> User<1 admin [admin1@admin admin2@admin]> User<2 root [root1@root root2@root]> Story<1 Cool story User<1 admin [admin1@admin admin2@admin]>>
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 ¶
var user struct { Name string } res, err := db.QueryOne(&user, ` WITH users (name) AS (VALUES (?)) SELECT * FROM users `, "admin") if err != nil { panic(err) } fmt.Println(res.Affected()) fmt.Println(user)
Output: 1 {admin}
Example (Returning_id) ¶
_, err := db.Exec(`CREATE TEMP TABLE users(id serial, name varchar(500))`) if err != nil { panic(err) } var user struct { Id int32 Name string } user.Name = "admin" _, err = db.QueryOne(&user, ` INSERT INTO users (name) VALUES (?name) RETURNING id `, user) if err != nil { panic(err) } fmt.Println(user)
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.
Example ¶
db := txExample() var counter int // Transaction is automatically rollbacked on error. err := db.RunInTransaction(func(tx *pg.Tx) error { _, err := tx.QueryOne(pg.Scan(&counter), `SELECT counter FROM tx_test`) if err != nil { return err } counter++ _, err = tx.Exec(`UPDATE tx_test SET counter = ?`, counter) return err }) if err != nil { panic(err) } fmt.Println(counter)
Output: 1
func (*DB) Update ¶
Update updates the model in database.
Example ¶
db := modelDB() err := db.Update(&Book{ Id: 1, Title: "updated book 1", }) if err != nil { panic(err) } var book Book err = db.Model(&book).Where("id = ?", 1).Select() if err != nil { panic(err) } fmt.Println(book)
Output: Book<Id=1 Title="updated book 1">
Example (MultipleRows) ¶
db := modelDB() ids := pg.Ints{1, 2} data := map[string]interface{}{ "title": pg.Q("concat(?, title, ?)", "prefix ", " suffix"), } var books []Book _, err := db.Model(&books). Where("id IN (?)", ids). Returning("*"). UpdateValues(data) if err != nil { panic(err) } fmt.Println(books[0], books[1])
Output: Book<Id=1 Title="prefix book 1 suffix"> Book<Id=2 Title="prefix book 2 suffix">
Example (SomeColumns) ¶
db := modelDB() book := Book{ Id: 1, Title: "updated book 1", AuthorID: 2, // this column will not be updated } _, err := db.Model(&book).Column("title").Returning("*").Update() if err != nil { panic(err) } fmt.Println(book, book.AuthorID)
Output: Book<Id=1 Title="updated book 1"> 1
Example (UsingSqlFunction) ¶
db := modelDB() id := 1 data := map[string]interface{}{ "title": pg.Q("concat(?, title, ?)", "prefix ", " suffix"), } var book Book _, err := db.Model(&book). Where("id = ?", id). Returning("*"). UpdateValues(data) if err != nil { panic(err) } fmt.Println(book)
Output: Book<Id=1 Title="prefix book 1 suffix">
func (*DB) WithTimeout ¶
WithTimeout returns a DB that uses d as the read/write timeout.
Example ¶
var count int // Use bigger timeout since this query is known to be slow. _, err := db.WithTimeout(time.Minute).QueryOne(pg.Scan(&count), ` SELECT count(*) FROM big_table `) if err != nil { panic(err) }
Output:
type IntSet ¶
type IntSet map[int64]struct{}
func (*IntSet) NewModel ¶
func (set *IntSet) NewModel() orm.ColumnScanner
type Ints ¶
type Ints []int64
Example ¶
var nums pg.Ints _, err := db.Query(&nums, `SELECT generate_series(0, 10)`) fmt.Println(nums, err)
Output: [0 1 2 3 4 5 6 7 8 9 10] <nil>
Example (In) ¶
ids := pg.Ints{1, 2, 3} q := pg.Q(`SELECT * FROM table WHERE id IN (?)`, ids) fmt.Println(string(q))
Output: SELECT * FROM table WHERE id IN (1,2,3)
func (*Ints) NewModel ¶
func (ints *Ints) NewModel() orm.ColumnScanner
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Not thread-safe.
Example ¶
ln, err := db.Listen("mychan") if err != nil { panic(err) } wait := make(chan struct{}, 2) go func() { wait <- struct{}{} channel, payload, err := ln.Receive() fmt.Printf("%s %q %v", channel, payload, err) wait <- struct{}{} }() <-wait db.Exec("NOTIFY mychan, ?", "hello world") <-wait
Output: mychan "hello world" <nil>
type Options ¶
type Options struct { // The network type, either tcp or unix. // Default is tcp. Network string // TCP host:port or Unix socket depending on Network. Addr string User string Password string Database string // Whether to use secure TCP/IP connections (TLS). SSL bool // PostgreSQL run-time configuration parameters to be set on connection. Params map[string]interface{} // The maximum number of retries before giving up. // Default is to not retry failed queries. MaxRetries int // 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 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 ¶
var strs pg.Strings _, err := db.Query( &strs, `WITH users AS (VALUES ('foo'), ('bar')) SELECT * FROM users`) fmt.Println(strs, err)
Output: [foo bar] <nil>
func (Strings) AppendValue ¶
func (*Strings) NewModel ¶
func (strings *Strings) NewModel() orm.ColumnScanner
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Not thread-safe.
func (*Tx) 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 (*Tx) FormatQuery ¶
func (*Tx) Query ¶
func (tx *Tx) Query(model interface{}, query interface{}, params ...interface{}) (*types.Result, error)
Query executes a query with the given parameters in a transaction.