import "github.com/go-pg/pg/orm"
The API in this package is not stable and may change without any notice.
composite.go composite_create.go composite_drop.go composite_parser.go count_estimate.go delete.go field.go format.go hook.go insert.go join.go model.go model_discard.go model_func.go model_map.go model_map_slice.go model_scan.go model_slice.go model_table.go model_table_m2m.go model_table_many.go model_table_slice.go model_table_struct.go msgpack.go orm.go query.go relation.go result.go select.go table.go table_create.go table_drop.go table_params.go tables.go types.go update.go util.go
const ( PrimaryKeyFlag = uint8(1) << iota ForeignKeyFlag NotNullFlag UseZeroFlag UniqueFlag ArrayFlag )
const ( InvalidRelation = iota HasOneRelation BelongsToRelation HasManyRelation Many2ManyRelation )
func RegisterTable(strct interface{})
RegisterTable registers a struct as SQL table. It is usually used to register intermediate table in many to many relationship.
func Scan(values ...interface{}) scanValuesModel
nolint
SetTableNameInflector overrides the default func that pluralizes model name to get table name, e.g. my_article becomes my_articles.
type ColumnScanner 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. ScanColumn(col types.ColumnInfo, rd types.Reader, n int) error }
ColumnScanner is used to scan column values.
type CreateCompositeOptions struct { Varchar int // replaces PostgreSQL data type `text` with `varchar(n)` }
type CreateCompositeQuery struct {
// contains filtered or unexported fields
}
func NewCreateCompositeQuery(q *Query, opt *CreateCompositeOptions) *CreateCompositeQuery
func (q *CreateCompositeQuery) AppendQuery(fmter QueryFormatter, b []byte) ([]byte, error)
func (q *CreateCompositeQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *CreateCompositeQuery) Clone() QueryCommand
func (q *CreateCompositeQuery) Operation() QueryOp
func (q *CreateCompositeQuery) Query() *Query
func (q *CreateCompositeQuery) String() string
type CreateTableOptions struct { Varchar int // replaces PostgreSQL data type `text` with `varchar(n)` Temp bool IfNotExists bool // FKConstraints causes CreateTable to create foreign key constraints // for has one relations. ON DELETE hook can be added using tag // `pg:"on_delete:RESTRICT"` on foreign key field. ON UPDATE hook can be added using tag // `pg:"on_update:CASCADE"` FKConstraints bool }
type CreateTableQuery struct {
// contains filtered or unexported fields
}
func NewCreateTableQuery(q *Query, opt *CreateTableOptions) *CreateTableQuery
func (q *CreateTableQuery) AppendQuery(fmter QueryFormatter, b []byte) (_ []byte, err error)
func (q *CreateTableQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *CreateTableQuery) Clone() QueryCommand
func (q *CreateTableQuery) Operation() QueryOp
func (q *CreateTableQuery) Query() *Query
func (q *CreateTableQuery) String() string
type DB interface { Model(model ...interface{}) *Query ModelContext(c context.Context, model ...interface{}) *Query Exec(query interface{}, params ...interface{}) (Result, error) ExecContext(c context.Context, query interface{}, params ...interface{}) (Result, error) ExecOne(query interface{}, params ...interface{}) (Result, error) ExecOneContext(c context.Context, query interface{}, params ...interface{}) (Result, error) Query(model, query interface{}, params ...interface{}) (Result, error) QueryContext(c context.Context, model, query interface{}, params ...interface{}) (Result, error) QueryOne(model, query interface{}, params ...interface{}) (Result, error) QueryOneContext(c context.Context, model, query interface{}, params ...interface{}) (Result, error) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (Result, error) CopyTo(w io.Writer, query interface{}, params ...interface{}) (Result, error) Context() context.Context Formatter() QueryFormatter }
DB is a common interface for pg.DB and pg.Tx types.
type DeleteQuery struct {
// contains filtered or unexported fields
}
func NewDeleteQuery(q *Query) *DeleteQuery
func (q *DeleteQuery) AppendQuery(fmter QueryFormatter, b []byte) (_ []byte, err error)
func (q *DeleteQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *DeleteQuery) Clone() QueryCommand
func (q *DeleteQuery) Operation() QueryOp
func (q *DeleteQuery) Query() *Query
func (q *DeleteQuery) String() string
type Discard struct {
// contains filtered or unexported fields
}
func (m Discard) AddColumnScanner(ColumnScanner) error
func (m Discard) NextColumnScanner() ColumnScanner
type DropCompositeQuery struct {
// contains filtered or unexported fields
}
func NewDropCompositeQuery(q *Query, opt *DropCompositeOptions) *DropCompositeQuery
func (q *DropCompositeQuery) AppendQuery(fmter QueryFormatter, b []byte) ([]byte, error)
func (q *DropCompositeQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *DropCompositeQuery) Clone() QueryCommand
func (q *DropCompositeQuery) Operation() QueryOp
func (q *DropCompositeQuery) Query() *Query
func (q *DropCompositeQuery) String() string
type DropTableQuery struct {
// contains filtered or unexported fields
}
func NewDropTableQuery(q *Query, opt *DropTableOptions) *DropTableQuery
func (q *DropTableQuery) AppendQuery(fmter QueryFormatter, b []byte) (_ []byte, err error)
func (q *DropTableQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *DropTableQuery) Clone() QueryCommand
func (q *DropTableQuery) Operation() QueryOp
func (q *DropTableQuery) Query() *Query
func (q *DropTableQuery) String() string
type Field struct { Field reflect.StructField Type reflect.Type Index []int GoName string // struct field name, e.g. Id SQLName string // SQL name, .e.g. id Column types.Safe // escaped SQL name, e.g. "id" SQLType string UserSQLType string Default types.Safe OnDelete string OnUpdate string // contains filtered or unexported fields }
type Formatter struct {
// contains filtered or unexported fields
}
func (f *Formatter) WithTableModel(model TableModel) *Formatter
type HooklessModel interface { // Init is responsible to initialize/reset model state. // It is called only once no matter how many rows were returned. Init() error // NextColumnScanner returns a ColumnScanner that is used to scan columns // from the current row. It is called once for every row. NextColumnScanner() ColumnScanner // AddColumnScanner adds the ColumnScanner to the model. AddColumnScanner(ColumnScanner) error }
type InsertQuery struct {
// contains filtered or unexported fields
}
func NewInsertQuery(q *Query) *InsertQuery
func (q *InsertQuery) AppendQuery(fmter QueryFormatter, b []byte) (_ []byte, err error)
func (q *InsertQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *InsertQuery) Clone() QueryCommand
func (q *InsertQuery) Operation() QueryOp
func (q *InsertQuery) Query() *Query
func (q *InsertQuery) String() string
type Model interface { HooklessModel AfterScanHook AfterSelectHook BeforeInsertHook AfterInsertHook BeforeUpdateHook AfterUpdateHook BeforeDeleteHook AfterDeleteHook }
type Query struct {
// contains filtered or unexported fields
}
AllWithDeleted changes query to return all rows including soft deleted ones.
Apply calls the fn passing the Query as an argument.
Clone clones the Query.
Column adds a column to the Query quoting it according to PostgreSQL rules. Does not expand params like ?TableAlias etc. ColumnExpr can be used to bypass quoting restriction or for params expansion. Column name can be:
- column_name, - table_alias.column_name, - table_alias.*.
ColumnExpr adds column expression to the Query.
CopyFrom is an alias from DB.CopyFrom.
CopyTo is an alias from DB.CopyTo.
Count returns number of rows matching the query using count aggregate function.
CountEstimate uses EXPLAIN to get estimated number of rows returned the query. If that number is bigger than the threshold it returns the estimation. Otherwise it executes another query using count aggregate function and returns the result.
Based on https://wiki.postgresql.org/wiki/Count_estimate
func (q *Query) CreateComposite(opt *CreateCompositeOptions) error
func (q *Query) CreateTable(opt *CreateTableOptions) error
Delete deletes the model. When model has deleted_at column the row is soft deleted instead.
Deleted adds `WHERE deleted_at IS NOT NULL` clause for soft deleted models.
func (q *Query) DropComposite(opt *DropCompositeOptions) error
func (q *Query) DropTable(opt *DropTableOptions) error
ExcludeColumn excludes a column from the list of to be selected columns.
Exec is an alias for DB.Exec.
ExecOne is an alias for DB.ExecOne.
Exists returns true or false depending if there are any rows matching the query.
First sorts rows by primary key and selects the first row. It is a shortcut for:
q.OrderExpr("id ASC").Limit(1)
ForEach calls the function for each row returned by the query without loading all rows into the memory.
Function can accept a struct, a pointer to a struct, an orm.Model, or values for the columns in a row. Function must return an error.
Delete forces delete of the model with deleted_at column.
Insert inserts the model.
JoinOn appends join condition to the last join.
Last sorts rows by primary key and selects the last row. It is a shortcut for:
q.OrderExpr("id DESC").Limit(1)
New returns new zero Query bound to the current db.
Order adds sort order to the Query quoting column name. Does not expand params like ?TableAlias etc. OrderExpr can be used to bypass quoting restriction or for params expansion.
Order adds sort order to the Query.
Query is an alias for DB.Query.
QueryOne is an alias for DB.QueryOne.
Relation adds a relation to the query. Relation name can be:
- RelationName to select all columns, - RelationName.column_name, - RelationName._ to join relation without selecting relation columns.
Returning adds a RETURNING clause to the query.
`Returning("NULL")` can be used to suppress default returning clause generated by go-pg for INSERT queries to get values for null columns.
Select selects the model.
SelectAndCount runs Select and Count in two goroutines, waits for them to finish and returns the result. If query limit is -1 it does not select any data and only counts the results.
func (q *Query) SelectAndCountEstimate(threshold int, values ...interface{}) (count int, firstErr error)
SelectAndCountEstimate runs Select and CountEstimate in two goroutines, waits for them to finish and returns the result. If query limit is -1 it does not select any data and only counts the results.
SelectOrInsert selects the model inserting one if it does not exist. It returns true when model was inserted.
func (q *Query) TableModel() TableModel
Update updates the model.
Update updates the model omitting fields with zero values such as:
- empty string, - 0, - zero time, - empty map or slice, - byte array with all zeroes, - nil ptr, - types with method `IsZero() == true`.
Value overwrites model value for the column in INSERT and UPDATE queries.
WhereGroup encloses conditions added in the function in parentheses.
q.Where("TRUE"). WhereGroup(func(q *orm.Query) (*orm.Query, error) { q = q.WhereOr("FALSE").WhereOr("TRUE"). return q, nil })
generates
WHERE TRUE AND (FALSE OR TRUE)
WhereIn is a shortcut for Where and pg.In.
WhereInMulti is a shortcut for Where and pg.InMulti.
WhereGroup encloses conditions added in the function in parentheses.
q.Where("TRUE"). WhereNotGroup(func(q *orm.Query) (*orm.Query, error) { q = q.WhereOr("FALSE").WhereOr("TRUE"). return q, nil })
generates
WHERE TRUE AND NOT (FALSE OR TRUE)
WhereOrGroup encloses conditions added in the function in parentheses.
q.Where("TRUE"). WhereOrGroup(func(q *orm.Query) (*orm.Query, error) { q = q.Where("FALSE").Where("TRUE"). return q, nil })
generates
WHERE TRUE OR (FALSE AND TRUE)
WhereOrGroup encloses conditions added in the function in parentheses.
q.Where("TRUE"). WhereOrGroup(func(q *orm.Query) (*orm.Query, error) { q = q.Where("FALSE").Where("TRUE"). return q, nil })
generates
WHERE TRUE OR NOT (FALSE AND TRUE)
WherePK adds condition based on the model primary keys. Usually it is the same as:
Where("id = ?id")
With adds subq as common table expression with the given name.
WrapWith creates new Query and adds to it current query as common table expression with the given name.
type QueryAppender interface { AppendQuery(fmter QueryFormatter, b []byte) ([]byte, error) }
type QueryCommand interface { QueryAppender TemplateAppender String() string Operation() QueryOp Clone() QueryCommand Query() *Query }
type QueryFormatter interface { FormatQuery(b []byte, query string, params ...interface{}) []byte }
const ( SelectOp QueryOp = "SELECT" InsertOp QueryOp = "INSERT" UpdateOp QueryOp = "UPDATE" DeleteOp QueryOp = "DELETE" CreateTableOp QueryOp = "CREATE TABLE" DropTableOp QueryOp = "DROP TABLE" CreateCompositeOp QueryOp = "CREATE COMPOSITE" DropCompositeOp QueryOp = "DROP COMPOSITE" )
type Relation struct { Type int Field *Field JoinTable *Table BaseFKs []*Field JoinFKs []*Field Polymorphic *Field M2MTableName types.Safe M2MTableAlias types.Safe M2MBaseFKs []string M2MJoinFKs []string }
type Result interface { Model() Model // RowsAffected returns the number of rows affected by SELECT, INSERT, UPDATE, // or DELETE queries. It returns -1 if query can't possibly affect any rows, // e.g. in case of CREATE or SHOW queries. RowsAffected() int // RowsReturned returns the number of rows returned by the query. RowsReturned() int }
Result summarizes an executed SQL command.
type SafeQueryAppender struct {
// contains filtered or unexported fields
}
func SafeQuery(query string, params ...interface{}) *SafeQueryAppender
nolint
func (q *SafeQueryAppender) AppendQuery(fmter QueryFormatter, b []byte) ([]byte, error)
func (q *SafeQueryAppender) Value() types.Safe
type SelectQuery struct {
// contains filtered or unexported fields
}
func NewSelectQuery(q *Query) *SelectQuery
func (q *SelectQuery) AppendQuery(fmter QueryFormatter, b []byte) (_ []byte, err error)
func (q *SelectQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *SelectQuery) Clone() QueryCommand
func (q *SelectQuery) Operation() QueryOp
func (q *SelectQuery) Query() *Query
func (q *SelectQuery) String() string
type Table struct { Type reflect.Type TypeName string Alias types.Safe ModelName string SQLName types.Safe SQLNameForSelects types.Safe Tablespace types.Safe PartitionBy string Fields []*Field // PKs + DataFields PKs []*Field DataFields []*Field FieldsMap map[string]*Field Methods map[string]*Method Relations map[string]*Relation Unique map[string][]*Field SoftDeleteField *Field SetSoftDeleteField func(fv reflect.Value) error // contains filtered or unexported fields }
Table represents a SQL table created from Go struct.
GetTable returns a Table for a struct type.
type TableModel interface { Model IsNil() bool Table() *Table Relation() *Relation AppendParam(QueryFormatter, []byte, string) ([]byte, bool) Join(string, func(*Query) (*Query, error)) *join GetJoin(string) *join GetJoins() []join AddJoin(join) *join Root() reflect.Value Index() []int ParentIndex() []int Mount(reflect.Value) Kind() reflect.Kind Value() reflect.Value // contains filtered or unexported methods }
type UpdateQuery struct {
// contains filtered or unexported fields
}
func NewUpdateQuery(q *Query, omitZero bool) *UpdateQuery
func (q *UpdateQuery) AppendQuery(fmter QueryFormatter, b []byte) (_ []byte, err error)
func (q *UpdateQuery) AppendTemplate(b []byte) ([]byte, error)
func (q *UpdateQuery) Clone() QueryCommand
func (q *UpdateQuery) Operation() QueryOp
func (q *UpdateQuery) Query() *Query
func (q *UpdateQuery) String() string
Package orm imports 24 packages (graph) and is imported by 110 packages. Updated 2020-11-23. Refresh now. Tools for package owners.