Pkg.go.dev is a new destination for Go discovery & docs. Check it out at pkg.go.dev/github.com/vmihailenco/pg and share your feedback.

package pg

import "github.com/vmihailenco/pg"

pg provides PostgreSQL client.

Example (Placeholders) go-pg recognizes `?` in queries as placeholders and replaces them with parameters when queries are executed. `?` can be escaped with backslash. Parameters are escaped before replacing according to PostgreSQL rules. Specifically: - all parameters are properly quoted against SQL injections; - null byte is removed; - JSON/JSONB gets `\u0000` escaped as `\\u0000`. Code: package main import ( "fmt" "github.com/go-pg/pg/v10" ) type Params struct { X int Y int } func (p *Params) Sum() int { return p.X + p.Y } // go-pg recognizes `?` in queries as placeholders and replaces them // with parameters when queries are executed. `?` can be escaped with backslash. // Parameters are escaped before replacing according to PostgreSQL rules. // Specifically: // - all parameters are properly quoted against SQL injections; // - null byte is removed; // - JSON/JSONB gets `\u0000` escaped as `\\u0000`. func main() { var num int // Simple params. _, err := pgdb.Query(pg.Scan(&num), "SELECT ?", 42) if err != nil { panic(err) } fmt.Println("simple:", num) // Indexed params. _, err = pgdb.Query(pg.Scan(&num), "SELECT ?0 + ?0", 1) if err != nil { panic(err) } fmt.Println("indexed:", num) // Named params. params := &Params{ X: 1, Y: 1, } _, err = pgdb.Query(pg.Scan(&num), "SELECT ?x + ?y + ?Sum", params) if err != nil { panic(err) } fmt.Println("named:", num) // Global params. _, err = pgdb.WithParam("z", 1).Query(pg.Scan(&num), "SELECT ?x + ?y + ?z", params) if err != nil { panic(err) } fmt.Println("global:", num) // Model params. var tableName, tableAlias, tableColumns, columns string _, err = pgdb.Model(&Params{}).Query( pg.Scan(&tableName, &tableAlias, &tableColumns, &columns), "SELECT '?TableName', '?TableAlias', '?TableColumns', '?Columns'", ) if err != nil { panic(err) } fmt.Println("table name:", tableName) fmt.Println("table alias:", tableAlias) fmt.Println("table columns:", tableColumns) fmt.Println("columns:", columns) }

base.go db.go doc.go error.go hook.go listener.go messages.go options.go pg.go result.go stmt.go tx.go

❖ var Discard orm.Discard

Discard is used with Query and QueryOne to discard rows.

❖ var ErrMultiRows = internal.ErrMultiRows

ErrMultiRows is returned by QueryOne and ExecOne when query returned multiple rows but exactly one row is expected.

❖ var ErrNoRows = internal.ErrNoRows

ErrNoRows is returned by QueryOne and ExecOne when query returned zero rows but at least one row is expected.

❖ var ErrTxDone = errors.New("pg: transaction has already been committed or rolled back")

ErrTxDone is returned by any operation that is performed on a transaction that has already been committed or rolled back.

Array accepts a slice and returns a wrapper for working with PostgreSQL array data type.

For struct fields you can use array tag:

Emails []string `pg:",array"`

Example Code: src := []string{"one@example.com", "two@example.com"} var dst []string _, err := pgdb.QueryOne(pg.Scan(pg.Array(&dst)), `SELECT ?`, pg.Array(src)) panicIf(err) fmt.Println(dst) Output: [one@example.com two@example.com]

Hstore accepts a map and returns a wrapper for working with hstore data type. Supported map types are:

- map[string]string

For struct fields you can use hstore tag:

Attrs map[string]string `pg:",hstore"`

Example Code: src := map[string]string{"hello": "world"} var dst map[string]string _, err := pgdb.QueryOne(pg.Scan(pg.Hstore(&dst)), `SELECT ?`, pg.Hstore(src)) if err != nil { panic(err) } fmt.Println(dst) Output: map[hello:world]

In accepts a slice and returns a wrapper that can be used with PostgreSQL IN operator:

Where("id IN (?)", pg.In([]int{1, 2, 3, 4}))

produces

WHERE id IN (1, 2, 3, 4)

InMulti accepts multiple values and returns a wrapper that can be used with PostgreSQL IN operator:

Where("(id1, id2) IN (?)", pg.InMulti([]int{1, 2}, []int{3, 4}))

produces

WHERE (id1, id2) IN ((1, 2), (3, 4))

Model returns new query for the optional model.

❖ func ModelContext(c context.Context, model ...interface{}) *orm.Query

ModelContext returns a new query for the optional model with a context.

❖ func SafeQuery(query string, params ...interface{}) *orm.SafeQueryAppender

SafeQuery replaces any placeholders found in the query.

Scan returns ColumnScanner that copies the columns in the row into the values.

Example Code: var s1, s2 string _, err := pgdb.QueryOne(pg.Scan(&s1, &s2), `SELECT ?, ?`, "foo", "bar") panicIf(err) fmt.Println(s1, s2) Output: foo bar

SetLogger sets the logger to the given one.

❖ type AfterDeleteHook = orm.AfterDeleteHook

❖ type AfterInsertHook = orm.AfterInsertHook

❖ type AfterScanHook = orm.AfterScanHook

❖ type AfterSelectHook = orm.AfterSelectHook

❖ type AfterUpdateHook = orm.AfterUpdateHook

❖ type BeforeDeleteHook = orm.BeforeDeleteHook

❖ type BeforeInsertHook = orm.BeforeInsertHook

❖ type BeforeScanHook = orm.BeforeScanHook

❖ type BeforeUpdateHook = orm.BeforeUpdateHook

❖ type Conn struct { // contains filtered or unexported fields }

Conn represents a single database connection rather than a pool of database connections. Prefer running queries from DB unless there is a specific need for a continuous single database connection.

A Conn must call Close to return the connection to the database pool and may do so concurrently with a running query.

After a call to Close, all operations on the connection fail.

AddQueryHook adds a hook into query processing.

Begin starts a transaction. Most callers should use RunInTransaction instead.

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.

Context returns DB context.

❖ func (db Conn) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (res Result, err error)

CopyFrom copies data from reader to a table.

❖ func (db Conn) CopyTo(w io.Writer, query interface{}, params ...interface{}) (res Result, err error)

CopyTo copies data from a table to writer.

❖ func (db Conn) Exec(query interface{}, params ...interface{}) (res Result, err error)

Exec executes a query ignoring returned rows. The params are for any placeholders in the query.

❖ func (db Conn) ExecContext(c context.Context, query interface{}, params ...interface{}) (Result, error)

❖ func (db Conn) ExecOne(query interface{}, params ...interface{}) (Result, error)

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 Conn) ExecOneContext(ctx context.Context, query interface{}, params ...interface{}) (Result, error)

Model returns new query for the model.

❖ func (db Conn) ModelContext(c context.Context, model ...interface{}) *orm.Query

Param returns value for the param.

Ping verifies a connection to the database is still alive, establishing a connection if necessary.

PoolStats returns connection pool stats.

Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement.

❖ func (db Conn) Query(model, query interface{}, params ...interface{}) (res Result, err error)

Query executes a query that returns rows, typically a SELECT. The params are for any placeholders in the query.

❖ func (db Conn) QueryContext(c context.Context, model, query interface{}, params ...interface{}) (Result, error)

❖ func (db Conn) QueryOne(model, query interface{}, params ...interface{}) (Result, error)

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.

❖ func (db Conn) QueryOneContext( ctx context.Context, model, query interface{}, params ...interface{}, ) (Result, error)

❖ func (db Conn) RunInTransaction(ctx context.Context, fn func(*Tx) error) error

RunInTransaction runs a function in a transaction. If function returns an error transaction is rolled back, otherwise transaction is committed.

WithContext returns a copy of the DB that uses the ctx.

❖ func (db *Conn) WithParam(param string, value interface{}) *Conn

WithParam returns a copy of the DB that replaces the param with the value in queries.

WithTimeout returns a copy of the DB that uses d as the read/write timeout.

❖ 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.

Example (ArrayValueScanner) Code: var dst MyArrayValueScanner _, err := pgdb.QueryOne(pg.Scan(pg.Array(&dst)), `SELECT array_agg(id) from generate_series(0, 10) AS id`) panicIf(err) fmt.Println(dst.sum) Output: 55 Example (JsonUseNumber) Code: type Event struct { Id int Data map[string]interface{} `pg:",json_use_number"` } db := pg.Connect(pgOptions()) defer db.Close() err := db.Model((*Event)(nil)).CreateTable(&orm.CreateTableOptions{ Temp: true, }) if err != nil { panic(err) } event := &Event{ Data: map[string]interface{}{ "price": 1.23, }, } _, err = db.Model(event).Insert() if err != nil { panic(err) } event2 := new(Event) err = db.Model(event2).Where("id = ?", event.Id).Select() if err != nil { panic(err) } // Check that price is decoded as json.Number. fmt.Printf("%T", event2.Data["price"]) Output: json.Number

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 Code: db := pg.Connect(&pg.Options{ User: "postgres", Password: "", Database: "postgres", }) defer db.Close() var n int _, err := db.QueryOne(pg.Scan(&n), "SELECT 1") panicIf(err) fmt.Println(n) Output: 1

AddQueryHook adds a hook into query processing.

Begin starts a transaction. Most callers should use RunInTransaction instead.

Example Code: db := txExample() incrInTx := func(db *pg.DB) error { tx, err := db.Begin() if err != nil { return err } // Rollback tx on error. defer tx.Rollback() var counter int _, err = tx.QueryOne( pg.Scan(&counter), `SELECT counter FROM tx_test FOR UPDATE`) if err != nil { return err } counter++ _, err = tx.Exec(`UPDATE tx_test SET counter = ?`, counter) if err != nil { return err } return tx.Commit() } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() err := incrInTx(db) panicIf(err) }() } wg.Wait() var counter int _, err := db.QueryOne(pg.Scan(&counter), `SELECT counter FROM tx_test`) panicIf(err) fmt.Println(counter) Output: 10

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.

Conn returns a single connection from the connection pool. Queries run on the same Conn will be run in the same database session.

Every Conn must be returned to the database pool after use by calling Conn.Close.

Context returns DB context.

❖ func (db DB) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (res Result, err error)

CopyFrom copies data from reader to a table.

Example Code: _, err := pgdb.Exec(`CREATE TEMP TABLE words(word text, len int)`) panicIf(err) r := strings.NewReader("hello,5

foo,3

") _, err = pgdb.CopyFrom(r, `COPY words FROM STDIN WITH CSV`) panicIf(err) var buf bytes.Buffer _, err = pgdb.CopyTo(&buf, `COPY words TO STDOUT WITH CSV`) panicIf(err) fmt.Println(buf.String()) Output: hello,5 foo,3

❖ func (db DB) CopyTo(w io.Writer, query interface{}, params ...interface{}) (res Result, err error)

CopyTo copies data from a table to writer.

❖ func (db DB) Exec(query interface{}, params ...interface{}) (res Result, err error)

Exec executes a query ignoring returned rows. The params are for any placeholders in the query.

Example Code: res, err := pgdb.Exec(`CREATE TEMP TABLE test()`) panicIf(err) fmt.Println(res.RowsAffected()) Output: -1

❖ func (db DB) ExecContext(c context.Context, query interface{}, params ...interface{}) (Result, error)

❖ func (db DB) ExecOne(query interface{}, params ...interface{}) (Result, error)

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 DB) ExecOneContext(ctx context.Context, query interface{}, params ...interface{}) (Result, error)

❖ func (db *DB) Listen(ctx context.Context, channels ...string) *Listener

Listen listens for notifications sent with NOTIFY command.

Model returns new query for the model.

❖ func (db DB) ModelContext(c context.Context, model ...interface{}) *orm.Query

Options returns read-only Options that were used to connect to the DB.

Param returns value for the param.

Ping verifies a connection to the database is still alive, establishing a connection if necessary.

PoolStats returns connection pool stats.

Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement.

Example Code: stmt, err := pgdb.Prepare(`SELECT $1::text, $2::text`) panicIf(err) var s1, s2 string _, err = stmt.QueryOne(pg.Scan(&s1, &s2), "foo", "bar") panicIf(err) fmt.Println(s1, s2) Output: foo bar

❖ func (db DB) Query(model, query interface{}, params ...interface{}) (res Result, err error)

Query executes a query that returns rows, typically a SELECT. The params are for any placeholders in the query.

Example Code: db := pg.Connect(&pg.Options{ User: "postgres", }) err := createSchema(db) panicIf(err) user1 := &User{ Name: "admin", Emails: []string{"admin1@admin", "admin2@admin"}, } err = CreateUser(db, user1) panicIf(err) err = CreateUser(db, &User{ Name: "root", Emails: []string{"root1@root", "root2@root"}, }) panicIf(err) story1 := &Story{ Title: "Cool story", AuthorId: user1.Id, } err = CreateStory(db, story1) panicIf(err) user, err := GetUser(db, user1.Id) panicIf(err) users, err := GetUsers(db) panicIf(err) story, err := GetStory(db, story1.Id) panicIf(err) fmt.Println(user) fmt.Println(users) 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 DB) QueryContext(c context.Context, model, query interface{}, params ...interface{}) (Result, error)

❖ func (db DB) QueryOne(model, query interface{}, params ...interface{}) (Result, error)

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 Code: var user struct { Name string } res, err := pgdb.QueryOne(&user, ` WITH users (name) AS (VALUES (?)) SELECT * FROM users `, "admin") panicIf(err) fmt.Println(res.RowsAffected()) fmt.Println(user) Output: 1 {admin}

❖ func (db DB) QueryOneContext( ctx context.Context, model, query interface{}, params ...interface{}, ) (Result, error)

❖ func (db DB) RunInTransaction(ctx context.Context, fn func(*Tx) error) error

RunInTransaction runs a function in a transaction. If function returns an error transaction is rolled back, otherwise transaction is committed.

Example Code: db := txExample() incrInTx := func(db *pg.DB) error { // Transaction is automatically rolled back on error. return db.RunInTransaction(ctx, func(tx *pg.Tx) error { var counter int _, err := tx.QueryOne( pg.Scan(&counter), `SELECT counter FROM tx_test FOR UPDATE`) if err != nil { return err } counter++ _, err = tx.Exec(`UPDATE tx_test SET counter = ?`, counter) return err }) } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() err := incrInTx(db) panicIf(err) }() } wg.Wait() var counter int _, err := db.QueryOne(pg.Scan(&counter), `SELECT counter FROM tx_test`) panicIf(err) fmt.Println(counter) Output: 10

WithContext returns a copy of the DB that uses the ctx.

❖ func (db *DB) WithParam(param string, value interface{}) *DB

WithParam returns a copy of the DB that replaces the param with the value in queries.

WithTimeout returns a copy of the DB that uses d as the read/write timeout.

Example Code: var count int // Use bigger timeout since this query is known to be slow. _, err := pgdb.WithTimeout(time.Minute).QueryOne(pg.Scan(&count), ` SELECT count(*) FROM big_table `) panicIf(err)

❖ type Error interface { error // Field returns a string value associated with an error field. // // https://www.postgresql.org/docs/10/static/protocol-error-fields.html Field (field byte) string // IntegrityViolation reports whether an error is a part of // Integrity Constraint Violation class of errors. // // https://www.postgresql.org/docs/10/static/errcodes-appendix.html IntegrityViolation () bool }

Error represents an error returned by PostgreSQL server using PostgreSQL ErrorResponse protocol.

https://www.postgresql.org/docs/10/static/protocol-message-formats.html

Example Code: flight := &Flight{ Id: 123, } _, err := pgdb.Model(flight).Insert() panicIf(err) _, err = pgdb.Model(flight).Insert() if err != nil { pgErr, ok := err.(pg.Error) if ok && pgErr.IntegrityViolation() { fmt.Println("flight already exists:", err) } else { panic(err) } } Output: flight already exists: ERROR #23505 duplicate key value violates unique constraint "flights_pkey"

❖ type Ident = types.Ident

Ident represents a SQL identifier, e.g. table or column name.

Example Code: db := modelDB() var book Book err := db.Model(&book).Where("? = 1", pg.Ident("id")).Select() if err != nil { panic(err) } fmt.Println(book) Output: Book<Id=1 Title="book 1">

❖ type IntSet map[int64]struct{}

IntSet is a set of int64 values.

AddColumnScanner ...

Init initializes the IntSet.

NextColumnScanner ...

❖ func (set *IntSet) ScanColumn(col types.ColumnInfo, rd types.Reader, n int) error

ScanColumn scans the columns and appends them to `IntSet`.

❖ type Ints []int64

Ints is a type alias for a slice of int64 values.

Example Code: var nums pg.Ints _, err := pgdb.Query(&nums, `SELECT generate_series(0, 10)`) panicIf(err) fmt.Println(nums) Output: [0 1 2 3 4 5 6 7 8 9 10]

AddColumnScanner ...

❖ func (ints Ints) AppendValue(dst []byte, quote int) ([]byte, error)

AppendValue appends the values from `ints` to the given byte slice.

Init initializes the Int slice.

NewColumnScanner ...

❖ func (ints *Ints) ScanColumn(col types.ColumnInfo, rd types.Reader, n int) error

ScanColumn scans the columns and appends them to `ints`.

❖ type Listener struct { // contains filtered or unexported fields }

Listener listens for notifications sent with NOTIFY command. It's NOT safe for concurrent use by multiple goroutines except the Channel API.

Example Code: ln := pgdb.Listen(ctx, "mychan") defer ln.Close() ch := ln.Channel() go func() { time.Sleep(time.Millisecond) _, err := pgdb.Exec("NOTIFY mychan, ?", "hello world") panicIf(err) }() notif := <-ch fmt.Println(notif) Output: {mychan hello world}

Channel returns a channel for concurrently receiving notifications. It periodically sends Ping notification to test connection health.

The channel is closed with Listener. Receive* APIs can not be used after channel is created.

ChannelSize is like Channel, but creates a Go channel with specified buffer size.

Close closes the listener, releasing any open resources.

❖ func (ln *Listener) Listen(ctx context.Context, channels ...string) error

Listen starts listening for notifications on channels.

❖ func (ln *Listener) Receive(ctx context.Context) (channel string, payload string, err error)

Receive indefinitely waits for a notification. This is low-level API and in most cases Channel should be used instead.

❖ func (ln *Listener) ReceiveTimeout( ctx context.Context, timeout time.Duration, ) (channel, payload string, err error)

ReceiveTimeout waits for a notification until timeout is reached. This is low-level API and in most cases Channel should be used instead.

❖ func (ln *Listener) Unlisten(ctx context.Context, channels ...string) error

Unlisten stops listening for notifications on channels.

❖ type Notification struct { Channel string Payload string }

Notification which is received with LISTEN command.

❖ type NullTime = types.NullTime

NullTime is a time.Time wrapper that marshals zero time as JSON null and PostgreSQL NULL.

❖ type Options struct { // Network type, either tcp or unix. // Default is tcp. Network string // TCP host:port or Unix socket depending on Network. Addr string // Dialer creates new network connection and has priority over // Network and Addr options. Dialer func(ctx context.Context, network, addr string) (net.Conn, error) // Hook that is called after new connection is established // and user is authenticated. OnConnect func(ctx context.Context, cn *Conn) error User string Password string Database string // ApplicationName is the application name. Used in logs on Pg side. // Only available from pg-9.0. ApplicationName string // TLS config for secure connections. TLSConfig *tls.Config // Dial timeout for establishing new connections. // Default is 5 seconds. DialTimeout time.Duration // Timeout for socket reads. If reached, commands will fail // with a timeout instead of blocking. ReadTimeout time.Duration // Timeout for socket writes. If reached, commands will fail // with a timeout instead of blocking. WriteTimeout time.Duration // Maximum number of retries before giving up. // Default is to not retry failed queries. MaxRetries int // Whether to retry queries cancelled because of statement_timeout. RetryStatementTimeout bool // Minimum backoff between each retry. // Default is 250 milliseconds; -1 disables backoff. MinRetryBackoff time.Duration // Maximum backoff between each retry. // Default is 4 seconds; -1 disables backoff. MaxRetryBackoff time.Duration // Maximum number of socket connections. // Default is 10 connections per every CPU as reported by runtime.NumCPU. PoolSize int // Minimum number of idle connections which is useful when establishing // new connection is slow. MinIdleConns int // Connection age at which client retires (closes) the connection. // It is useful with proxies like PgBouncer and HAProxy. // Default is to not close aged connections. MaxConnAge time.Duration // Time for which client waits for free connection if all // connections are busy before returning an error. // Default is 30 seconds if ReadTimeOut is not defined, otherwise, // ReadTimeout + 1 second. PoolTimeout time.Duration // Amount of time after which client closes idle connections. // Should be less than server's timeout. // Default is 5 minutes. -1 disables idle timeout check. IdleTimeout time.Duration // Frequency of idle checks made by idle connections reaper. // Default is 1 minute. -1 disables idle connections reaper, // but idle connections are still discarded by the client // if IdleTimeout is set. IdleCheckFrequency time.Duration }

Options contains database connection options.

ParseURL parses an URL into options that can be used to connect to PostgreSQL.

❖ type PoolStats pool.Stats

PoolStats contains the stats of a connection pool.

❖ type QueryEvent struct { StartTime time.Time DB orm.DB Model interface{} Query interface{} Params []interface{} Result Result Err error Stash map[interface{}]interface{} // contains filtered or unexported fields }

QueryEvent ...

FormattedQuery returns the formatted query of a query event. The query is only valid until the query Result is returned to the user.

UnformattedQuery returns the unformatted query of a query event. The query is only valid until the query Result is returned to the user.

❖ type QueryHook interface { BeforeQuery (context.Context, *QueryEvent) (context.Context, error) AfterQuery (context.Context, *QueryEvent) error }

QueryHook ...

❖ type Result = orm.Result

Result summarizes an executed SQL command.

❖ type Safe = types.Safe

Safe represents a safe SQL query.

Example Code: db := modelDB() cond := fmt.Sprintf("id = %d", 1) var book Book err := db.Model(&book).Where("?", pg.Safe(cond)).Select() if err != nil { panic(err) } fmt.Println(book) Output: Book<Id=1 Title="book 1">

❖ type Stmt struct { // contains filtered or unexported fields }

Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.

Close closes the statement.

Exec executes a prepared statement with the given parameters.

❖ func (stmt *Stmt) ExecContext(c context.Context, params ...interface{}) (Result, error)

ExecContext executes a prepared statement with the given parameters.

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 (stmt *Stmt) ExecOneContext(c context.Context, params ...interface{}) (Result, error)

ExecOneContext acts like ExecOne but additionally receives a context.

❖ func (stmt *Stmt) Query(model interface{}, params ...interface{}) (Result, error)

Query executes a prepared query statement with the given parameters.

❖ func (stmt *Stmt) QueryContext(c context.Context, model interface{}, params ...interface{}) (Result, error)

QueryContext acts like Query but additionally receives a context.

❖ func (stmt *Stmt) QueryOne(model interface{}, params ...interface{}) (Result, error)

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.

❖ func (stmt *Stmt) QueryOneContext(c context.Context, model interface{}, params ...interface{}) (Result, error)

QueryOneContext acts like QueryOne but additionally receives a context.

❖ type Strings []string

Strings is a type alias for a slice of strings.

Example Code: var strs pg.Strings _, err := pgdb.Query(&strs, ` WITH users AS (VALUES ('foo'), ('bar')) SELECT * FROM users `) panicIf(err) fmt.Println(strs) Output: [foo bar]

AddColumnScanner ...

❖ func (strings Strings) AppendValue(dst []byte, quote int) ([]byte, error)

AppendValue appends the values from `strings` to the given byte slice.

Init initializes the Strings slice.

NextColumnScanner ...

❖ func (strings *Strings) ScanColumn(col types.ColumnInfo, rd types.Reader, n int) error

ScanColumn scans the columns and appends them to `strings`.

❖ type Tx struct { // contains filtered or unexported fields }

Tx is an in-progress database transaction. It is safe for concurrent use by multiple goroutines.

A transaction must end with a call to Commit or Rollback.

After a call to Commit or Rollback, all operations on the transaction fail with ErrTxDone.

The statements prepared for a transaction by calling the transaction's Prepare or Stmt methods are closed by the call to Commit or Rollback.

Begin returns current transaction. It does not start new transaction.

Close calls Rollback if the tx has not already been committed or rolled back.

Commit commits the transaction.

Context returns the context.Context of the transaction.

❖ func (tx *Tx) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (res Result, err error)

CopyFrom is an alias for DB.CopyFrom.

❖ func (tx *Tx) CopyTo(w io.Writer, query interface{}, params ...interface{}) (res Result, err error)

CopyTo is an alias for DB.CopyTo.

❖ func (tx *Tx) Exec(query interface{}, params ...interface{}) (Result, error)

Exec is an alias for DB.Exec.

❖ func (tx *Tx) ExecContext(c context.Context, query interface{}, params ...interface{}) (Result, error)

ExecContext acts like Exec but additionally receives a context.

❖ func (tx *Tx) ExecOne(query interface{}, params ...interface{}) (Result, error)

ExecOne is an alias for DB.ExecOne.

❖ func (tx *Tx) ExecOneContext(c context.Context, query interface{}, params ...interface{}) (Result, error)

ExecOneContext acts like ExecOne but additionally receives a context.

Formatter is an alias for DB.Formatter.

Model is an alias for DB.Model.

❖ func (tx *Tx) ModelContext(c context.Context, model ...interface{}) *orm.Query

ModelContext acts like Model but additionally receives a context.

Prepare creates a prepared statement for use within a transaction.

The returned statement operates within the transaction and can no longer be used once the transaction has been committed or rolled back.

To use an existing prepared statement on this transaction, see Tx.Stmt.

❖ func (tx *Tx) Query(model interface{}, query interface{}, params ...interface{}) (Result, error)

Query is an alias for DB.Query.

❖ func (tx *Tx) QueryContext( c context.Context, model interface{}, query interface{}, params ...interface{}, ) (Result, error)

QueryContext acts like Query but additionally receives a context.

❖ func (tx *Tx) QueryOne(model interface{}, query interface{}, params ...interface{}) (Result, error)

QueryOne is an alias for DB.QueryOne.

❖ func (tx *Tx) QueryOneContext( c context.Context, model interface{}, query interface{}, params ...interface{}, ) (Result, error)

QueryOneContext acts like QueryOne but additionally receives a context.

Rollback aborts the transaction.

❖ func (tx *Tx) RunInTransaction(ctx context.Context, fn func(*Tx) error) error

RunInTransaction runs a function in the transaction. If function returns an error transaction is rolled back, otherwise transaction is committed.

Stmt returns a transaction-specific prepared statement from an existing statement.

Path Synopsis internal internal is a private internal package. internal/parser internal/pool orm The API in this package is not stable and may change without any notice. pgext pgjson types The API in this package is not stable and may change without any notice.