README
¶
PostgreSQL client and ORM for Golang
Features:
- Basic types: integers, floats, string, bool, time.Time, net.IP, net.IPNet.
- sql.NullBool, sql.NullString, sql.NullInt64, sql.NullFloat64 and pg.NullTime.
- sql.Scanner and sql/driver.Valuer interfaces.
- Structs, maps and arrays are marshalled as JSON by default.
- PostgreSQL multidimensional Arrays using array tag and Array wrapper.
- Hstore using hstore tag and Hstore wrapper.
- All struct fields are nullable by default and zero values (empty string, 0, zero time) are marshalled as SQL
NULL
.sql:",notnull"
tag is used to reverse this behaviour. - Transactions.
- Prepared statements.
- Notifications using
LISTEN
andNOTIFY
. - Copying data using
COPY FROM
andCOPY TO
. - Timeouts.
- Automatic connection pooling with circuit breaker support.
- Queries retries on network errors.
- Working with models using ORM and SQL.
- Scanning variables using ORM and SQL.
- SelectOrInsert using on-conflict.
- INSERT ... ON CONFLICT DO UPDATE using ORM.
- Bulk/batch inserts and updates.
- Common table expressions using WITH and WrapWith.
- CountEstimate using
EXPLAIN
to get estimated number of matching rows. - ORM supports has one, belongs to, has many, and many to many with composite/multi-column primary keys.
- Creating tables from structs.
- Pagination and URL filters helpers.
- Migrations.
- Sharding.
Get Started
Look & Feel
package pg_test
import (
"fmt"
"github.com/go-pg/pg"
)
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
AuthorId int64
Author *User
}
func (s Story) String() string {
return fmt.Sprintf("Story<%d %s %s>", s.Id, s.Title, s.Author)
}
func ExampleDB_Model() {
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.Insert(user1)
if err != nil {
panic(err)
}
err = db.Insert(&User{
Name: "root",
Emails: []string{"root1@root", "root2@root"},
})
if err != nil {
panic(err)
}
story1 := &Story{
Title: "Cool story",
AuthorId: user1.Id,
}
err = db.Insert(story1)
if err != nil {
panic(err)
}
// Select user by primary key.
user := User{Id: user1.Id}
err = db.Select(&user)
if err != nil {
panic(err)
}
// Select all users.
var users []User
err = db.Model(&users).Select()
if err != nil {
panic(err)
}
// Select story and associated author in one query.
var story Story
err = db.Model(&story).
Column("story.*", "Author").
Where("story.id = ?", story1.Id).
Select()
if err != nil {
panic(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 createSchema(db *pg.DB) error {
for _, model := range []interface{}{&User{}, &Story{}} {
err := db.CreateTable(model, nil)
if err != nil {
return err
}
}
return nil
}
See also
Documentation
¶
Overview ¶
Package github.com/go-pg/pg implements a 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`.
Output: simple: 42 indexed: 2 named: 4 global: 3 table name: "params" table alias: "params" columns: "x", "y"
Index ¶
- Variables
- func Array(v interface{}) *types.Array
- func F(field string) types.ValueAppender
- func Hstore(v interface{}) *types.Hstore
- func In(slice interface{}) types.ValueAppender
- func Model(model ...interface{}) *orm.Query
- func Q(query string, params ...interface{}) types.ValueAppender
- 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) Context() context.Context
- func (db *DB) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (orm.Result, error)
- func (db *DB) CopyTo(w io.Writer, query interface{}, params ...interface{}) (orm.Result, error)
- func (db *DB) CreateTable(model interface{}, opt *orm.CreateTableOptions) error
- func (db *DB) Delete(model interface{}) error
- func (db *DB) DropTable(model interface{}, opt *orm.DropTableOptions) error
- func (db *DB) Exec(query interface{}, params ...interface{}) (res orm.Result, err error)
- func (db *DB) ExecOne(query interface{}, params ...interface{}) (orm.Result, error)
- func (db *DB) FormatQuery(dst []byte, query string, params ...interface{}) []byte
- func (db *DB) Insert(model ...interface{}) error
- func (db *DB) Listen(channels ...string) *Listener
- func (db *DB) Model(model ...interface{}) *orm.Query
- func (db *DB) OnQueryProcessed(fn func(*QueryProcessedEvent))
- func (db *DB) Options() *Options
- func (db *DB) PoolStats() *PoolStats
- func (db *DB) Prepare(q string) (*Stmt, error)
- func (db *DB) Query(model, query interface{}, params ...interface{}) (res orm.Result, err error)
- func (db *DB) QueryOne(model, query interface{}, params ...interface{}) (orm.Result, error)
- func (db *DB) RunInTransaction(fn func(*Tx) error) error
- func (db *DB) Select(model interface{}) error
- func (db *DB) String() string
- func (db *DB) Update(model ...interface{}) error
- func (db *DB) WithContext(ctx context.Context) *DB
- func (db *DB) WithParam(param string, value interface{}) *DB
- func (db *DB) WithTimeout(d time.Duration) *DB
- type Error
- type IntSet
- func (IntSet) AddModel(_ orm.ColumnScanner) error
- func (IntSet) AfterDelete(_ orm.DB) error
- func (IntSet) AfterInsert(_ orm.DB) error
- func (IntSet) AfterQuery(_ orm.DB) error
- func (IntSet) AfterSelect(_ orm.DB) error
- func (IntSet) AfterUpdate(_ orm.DB) error
- func (IntSet) BeforeDelete(_ orm.DB) error
- func (IntSet) BeforeInsert(_ orm.DB) error
- func (IntSet) BeforeUpdate(_ orm.DB) error
- func (set *IntSet) Init() error
- func (set *IntSet) NewModel() orm.ColumnScanner
- func (setptr *IntSet) ScanColumn(colIdx int, colName string, b []byte) error
- type Ints
- func (Ints) AddModel(_ orm.ColumnScanner) error
- func (Ints) AfterDelete(_ orm.DB) error
- func (Ints) AfterInsert(_ orm.DB) error
- func (Ints) AfterQuery(_ orm.DB) error
- func (Ints) AfterSelect(_ orm.DB) error
- func (Ints) AfterUpdate(_ orm.DB) error
- func (ints Ints) AppendValue(dst []byte, quote int) ([]byte, error)
- func (Ints) BeforeDelete(_ orm.DB) error
- func (Ints) BeforeInsert(_ orm.DB) error
- func (Ints) BeforeUpdate(_ orm.DB) error
- func (ints *Ints) Init() error
- func (ints *Ints) NewModel() orm.ColumnScanner
- func (ints *Ints) ScanColumn(colIdx int, colName string, b []byte) error
- type Listener
- func (ln *Listener) Channel() <-chan *Notification
- func (ln *Listener) Close() error
- func (ln *Listener) Listen(channels ...string) error
- func (ln *Listener) Receive() (channel string, payload string, err error)
- func (ln *Listener) ReceiveTimeout(timeout time.Duration) (channel, payload string, err error)
- type Notification
- type NullTime
- type Options
- type PoolStats
- type QueryProcessedEvent
- type Stmt
- func (stmt *Stmt) Close() error
- func (stmt *Stmt) Exec(params ...interface{}) (res orm.Result, err error)
- func (stmt *Stmt) ExecOne(params ...interface{}) (orm.Result, error)
- func (stmt *Stmt) Query(model interface{}, params ...interface{}) (res orm.Result, err error)
- func (stmt *Stmt) QueryOne(model interface{}, params ...interface{}) (orm.Result, error)
- type Strings
- func (Strings) AddModel(_ orm.ColumnScanner) error
- func (Strings) AfterDelete(_ orm.DB) error
- func (Strings) AfterInsert(_ orm.DB) error
- func (Strings) AfterQuery(_ orm.DB) error
- func (Strings) AfterSelect(_ orm.DB) error
- func (Strings) AfterUpdate(_ orm.DB) error
- func (strings Strings) AppendValue(dst []byte, quote int) ([]byte, error)
- func (Strings) BeforeDelete(_ orm.DB) error
- func (Strings) BeforeInsert(_ orm.DB) error
- func (Strings) BeforeUpdate(_ orm.DB) error
- func (strings *Strings) Init() error
- func (strings *Strings) NewModel() orm.ColumnScanner
- func (strings *Strings) ScanColumn(colIdx int, _ string, b []byte) error
- type Tx
- func (tx *Tx) Begin() (*Tx, error)
- func (tx *Tx) Commit() error
- func (tx *Tx) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (orm.Result, error)
- func (tx *Tx) CopyTo(w io.Writer, query interface{}, params ...interface{}) (orm.Result, error)
- func (tx *Tx) CreateTable(model interface{}, opt *orm.CreateTableOptions) error
- func (tx *Tx) Delete(model interface{}) error
- func (tx *Tx) DropTable(model interface{}, opt *orm.DropTableOptions) error
- func (tx *Tx) Exec(query interface{}, params ...interface{}) (orm.Result, error)
- func (tx *Tx) ExecOne(query interface{}, params ...interface{}) (orm.Result, error)
- func (tx *Tx) FormatQuery(dst []byte, query string, params ...interface{}) []byte
- func (tx *Tx) Insert(model ...interface{}) error
- 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{}) (orm.Result, error)
- func (tx *Tx) QueryOne(model interface{}, query interface{}, params ...interface{}) (orm.Result, error)
- func (tx *Tx) Rollback() error
- func (tx *Tx) RunInTransaction(fn func(*Tx) error) error
- func (tx *Tx) Select(model interface{}) error
- func (tx *Tx) Stmt(stmt *Stmt) *Stmt
- func (tx *Tx) Update(model ...interface{}) error
Examples ¶
- Package (Placeholders)
- Array
- Connect
- DB (JsonUseNumber)
- DB.Begin
- DB.CopyFrom
- DB.CreateTable
- DB.Delete
- DB.Delete (MultipleRows)
- DB.Exec
- DB.Insert
- DB.Insert (BulkInsert)
- DB.Insert (BulkInsertSlice)
- DB.Insert (OnConflictDoNothing)
- DB.Insert (OnConflictDoUpdate)
- DB.Insert (SelectOrInsert)
- DB.Model
- DB.Model (BelongsTo)
- DB.Model (Count)
- DB.Model (CountEstimate)
- DB.Model (HasMany)
- DB.Model (HasManySelf)
- DB.Model (HasOne)
- DB.Model (HstoreStructTag)
- DB.Model (ManyToMany)
- DB.Model (NullEmptyValue)
- DB.Model (PostgresArrayStructTag)
- DB.Model (SelectAndCount)
- DB.Prepare
- DB.Query
- DB.QueryOne
- DB.QueryOne (Returning_id)
- DB.RunInTransaction
- DB.Select
- DB.Select (AllColumns)
- DB.Select (ApplyFunc)
- DB.Select (FirstRow)
- DB.Select (GroupBy)
- DB.Select (LastRow)
- DB.Select (SomeColumns)
- DB.Select (SomeColumnsIntoVars)
- DB.Select (SqlExpression)
- DB.Select (WhereGroup)
- DB.Select (WhereIn)
- DB.Select (With)
- DB.Select (WrapWith)
- DB.Update
- DB.Update (BulkUpdate)
- DB.Update (BulkUpdateSlice)
- DB.Update (NotNull)
- DB.Update (SetValues)
- DB.Update (SomeColumns)
- DB.Update (SomeColumns2)
- DB.WithTimeout
- F
- Hstore
- Ints
- Listener
- Q
- Scan
- Strings
Constants ¶
This section is empty.
Variables ¶
var Discard orm.Discard
Discard is used with Query and QueryOne to discard rows.
var ErrMultiRows = internal.ErrMultiRows
var ErrNoRows = internal.ErrNoRows
Functions ¶
func Array ¶
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 ¶
Output: [one@example.com two@example.com]
func F ¶
func F(field string) types.ValueAppender
F quotes a SQL identifier such as a table or column name replacing any placeholders found in the field.
Example ¶
Output: Book<Id=1 Title="book 1">
func Hstore ¶
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 ¶
Output: map[hello:world]
func In ¶
func In(slice interface{}) types.ValueAppender
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}))
func Q ¶
func Q(query string, params ...interface{}) types.ValueAppender
Q replaces any placeholders found in the query.
Example ¶
Output: Book<Id=1 Title="book 1">
func Scan ¶
func Scan(values ...interface{}) orm.ColumnScanner
Scan returns ColumnScanner that copies the columns in the row into the values.
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.
Example (JsonUseNumber) ¶
Output: json.Number
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.
func (*DB) Begin ¶
Begin starts a transaction. Most callers should use RunInTransaction instead.
Example ¶
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) CreateTable ¶
func (db *DB) CreateTable(model interface{}, opt *orm.CreateTableOptions) error
CreateTable creates table for the model. It recognizes following field tags:
- notnull - sets NOT NULL constraint.
- unique - sets UNIQUE constraint.
- default:value - sets default value.
Example ¶
Output: [{id bigint} {name text}]
func (*DB) Delete ¶
Delete deletes the model by primary key.
Example ¶
Output: pg: no rows in result set
Example (MultipleRows) ¶
Output: deleted 3 left 0
func (*DB) DropTable ¶
func (db *DB) DropTable(model interface{}, opt *orm.DropTableOptions) error
DropTable drops table for the model.
func (*DB) Exec ¶
Exec executes a query ignoring returned rows. The params are for any placeholders in the query.
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) Insert ¶
Insert inserts the model updating primary keys if they are empty.
Example ¶
Output: Book<Id=4 Title="new book">
Example (BulkInsert) ¶
Output: Book<Id=4 Title="new book 1"> Book<Id=5 Title="new book 2">
Example (BulkInsertSlice) ¶
Output: [Book<Id=4 Title="new book 1"> Book<Id=5 Title="new book 2">]
Example (OnConflictDoNothing) ¶
Output: created did nothing
Example (OnConflictDoUpdate) ¶
Output: Book<Id=100 Title="title version #0"> Book<Id=100 Title="title version #1">
Example (SelectOrInsert) ¶
Output: true Author<ID=2 Name="R. Scott Bakker">
func (*DB) Model ¶
Model returns new query for the model.
Example ¶
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]>>
Example (BelongsTo) ¶
Output: 2 results 1 user 1 &{1 en 1} 2 user 2 &{2 ru 2}
Example (Count) ¶
Output: 3
Example (CountEstimate) ¶
Output: 3
Example (HasMany) ¶
Output: 1 user 1 &{1 en true 1} &{2 ru true 1}
Example (HasManySelf) ¶
Output: Item 1 Subitems 2 3
Example (HasOne) ¶
Output: 2 results 1 user 1 &{1 en} 2 user 2 &{2 ru}
Example (HstoreStructTag) ¶
Output: {1 map[hello:world]}
Example (ManyToMany) ¶
Output: Item 1 Subitems 2 3
Example (NullEmptyValue) ¶
Output: false
Example (PostgresArrayStructTag) ¶
Output: {1 [one@example.com two@example.com] [[1 2] [3 4]]}
Example (SelectAndCount) ¶
Output: 3 [Book<Id=1 Title="book 1"> Book<Id=2 Title="book 2">]
func (*DB) OnQueryProcessed ¶
func (db *DB) OnQueryProcessed(fn func(*QueryProcessedEvent))
OnQueryProcessed calls the fn with QueryProcessedEvent when query is processed.
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
func (*DB) Query ¶
Query executes a query that returns rows, typically a SELECT. The params are for any placeholders in the query.
Example ¶
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 (Returning_id) ¶
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 ¶
Output: 1
func (*DB) Select ¶
Select selects the model by primary key.
Example ¶
Output: Book<Id=1 Title="book 1">
Example (AllColumns) ¶
Output: Book<Id=1 Title="book 1"> 1
Example (ApplyFunc) ¶
Output: [Book<Id=1 Title="book 1"> Book<Id=2 Title="book 2">]
Example (FirstRow) ¶
Output: Book<Id=1 Title="book 1">
Example (GroupBy) ¶
Output: len 2 author 1 has 2 books author 11 has 1 books
Example (LastRow) ¶
Output: Book<Id=3 Title="book 3">
Example (SomeColumns) ¶
Output: Book<Id=1 Title="book 1">
Example (SomeColumnsIntoVars) ¶
Output: 1 book 1
Example (SqlExpression) ¶
Output: [1 2 3]
Example (WhereGroup) ¶
Output: [Book<Id=1 Title="book 1"> Book<Id=2 Title="book 2">]
Example (WhereIn) ¶
Output: [Book<Id=1 Title="book 1"> Book<Id=2 Title="book 2">]
Example (With) ¶
Output: [Book<Id=1 Title="book 1"> Book<Id=2 Title="book 2">]
Example (WrapWith) ¶
Output: [Book<Id=1 Title="book 1"> Book<Id=2 Title="book 2">]
func (*DB) Update ¶
Update updates the model by primary key.
Example ¶
Output: Book<Id=1 Title="updated book 1">
Example (BulkUpdate) ¶
Output: [Book<Id=1 Title="updated book 1"> Book<Id=2 Title="updated book 2"> Book<Id=3 Title="book 3">]
Example (BulkUpdateSlice) ¶
Output: [Book<Id=1 Title="updated book 1"> Book<Id=2 Title="updated book 2"> Book<Id=3 Title="book 3">]
Example (NotNull) ¶
Output: Book<Id=1 Title="updated book 1">
Example (SetValues) ¶
Output: Book<Id=1 Title="prefix book 1 suffix">
Example (SomeColumns) ¶
Output: Book<Id=1 Title="updated book 1"> 1
Example (SomeColumns2) ¶
Output: Book<Id=1 Title="updated book 1"> 1
type IntSet ¶
type IntSet map[int64]struct{}
func (*IntSet) NewModel ¶
func (set *IntSet) NewModel() orm.ColumnScanner
type Ints ¶
type Ints []int64
func (*Ints) NewModel ¶
func (ints *Ints) NewModel() orm.ColumnScanner
type Listener ¶
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.
func (*Listener) Channel ¶
func (ln *Listener) Channel() <-chan *Notification
Channel returns a channel for concurrently receiving notifications. The channel is closed with Listener.
type Notification ¶
A notification received with LISTEN command.
type NullTime ¶
NullTime is a time.Time wrapper that marshals zero time as JSON null and PostgreSQL NULL.
func (NullTime) MarshalJSON ¶
func (*NullTime) UnmarshalJSON ¶
type Options ¶
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(network, addr string) (net.Conn, error) // Hook that is called when new connection is established. OnConnect func(*DB) error User string Password string Database string // TLS config for secure connections. TLSConfig *tls.Config // 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 // 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 socket connections. // Default is 10 connections per every CPU as reported by runtime.NumCPU. PoolSize int // Time for which client waits for free connection if all // connections are busy before returning an error. // Default is 5 seconds. PoolTimeout time.Duration // Time after which client closes idle connections. // Default is to not close idle connections. IdleTimeout time.Duration // Connection age at which client retires (closes) the connection. // Primarily useful with proxies like HAProxy. // Default is to not close aged connections. MaxAge time.Duration // Frequency of idle checks. // Default is 1 minute. IdleCheckFrequency time.Duration }
Database connection options.
type QueryProcessedEvent ¶
type QueryProcessedEvent struct { StartTime time.Time Func string File string Line int DB orm.DB Query interface{} Params []interface{} Attempt int Result orm.Result Error error }
func (*QueryProcessedEvent) FormattedQuery ¶
func (ev *QueryProcessedEvent) FormattedQuery() (string, error)
func (*QueryProcessedEvent) UnformattedQuery ¶
func (ev *QueryProcessedEvent) UnformattedQuery() (string, error)
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
func (Strings) AppendValue ¶
func (*Strings) NewModel ¶
func (strings *Strings) NewModel() orm.ColumnScanner
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is an in-progress database transaction.
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.
func (*Tx) CreateTable ¶
func (tx *Tx) CreateTable(model interface{}, opt *orm.CreateTableOptions) error
CreateTable is an alias for DB.CreateTable.
func (*Tx) DropTable ¶
func (tx *Tx) DropTable(model interface{}, opt *orm.DropTableOptions) error
DropTable is an alias for DB.DropTable.
func (*Tx) FormatQuery ¶
func (*Tx) Prepare ¶
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) Query ¶
func (tx *Tx) Query(model interface{}, query interface{}, params ...interface{}) (orm.Result, error)
Query is an alias for DB.Query.
func (*Tx) QueryOne ¶
func (tx *Tx) QueryOne(model interface{}, query interface{}, params ...interface{}) (orm.Result, error)
QueryOne is an alias for DB.QueryOne.
func (*Tx) RunInTransaction ¶
RunInTransaction runs a function in the transaction. If function returns an error transaction is rollbacked, otherwise transaction is committed.