orm

package
v6.15.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2018 License: BSD-2-Clause Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PrimaryKeyFlag = uint8(1) << iota
	ForeignKeyFlag
	NotNullFlag
	UniqueFlag
	ArrayFlag
)
View Source
const (
	HasOneRelation = 1 << iota
	BelongsToRelation
	HasManyRelation
	Many2ManyRelation
)
View Source
const (
	AfterQueryHookFlag = uint16(1) << iota
	BeforeSelectQueryHookFlag
	AfterSelectHookFlag
	BeforeInsertHookFlag
	AfterInsertHookFlag
	BeforeUpdateHookFlag
	AfterUpdateHookFlag
	BeforeDeleteHookFlag
	AfterDeleteHookFlag
)

Variables

This section is empty.

Functions

func CreateComposite added in v6.14.4

func CreateComposite(db DB, model interface{}, opt *CreateCompositeOptions) error

func CreateTable

func CreateTable(db DB, model interface{}, opt *CreateTableOptions) error

func Delete

func Delete(db DB, model interface{}) error

func DropComposite added in v6.14.4

func DropComposite(db DB, model interface{}, opt *DropCompositeOptions) error

func DropTable added in v6.1.6

func DropTable(db DB, model interface{}, opt *DropTableOptions) error

func ForceDelete added in v6.14.4

func ForceDelete(db DB, model interface{}) error

func Insert

func Insert(db DB, model ...interface{}) error

func Pagination

func Pagination(values url.Values) func(*Query) (*Query, error)

Pagination is used with Query.Apply to set LIMIT and OFFSET from the URL values:

  • ?limit=10 - sets q.Limit(10), max limit is 1000.
  • ?page=5 - sets q.Offset((page - 1) * limit), max offset is 1000000.

func Q

func Q(query string, params ...interface{}) *queryParamsAppender

func RegisterTable added in v6.12.0

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

func Scan(values ...interface{}) scanValuesModel

func Select

func Select(db DB, model interface{}) error

func SetTableNameInflector added in v6.4.20

func SetTableNameInflector(fn func(string) string)

SetTableNameInflector overrides the default func that pluralizes model name to get table name, e.g. my_article becomes my_articles.

func URLFilters

func URLFilters(urlValues url.Values) func(*Query) (*Query, error)

URLFilters is a shortcut for NewURLFilter(urlValues).Filters.

func Update

func Update(db DB, model interface{}) error

Types

type ColumnScanner

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(colIdx int, colName string, b []byte) error
}

ColumnScanner is used to scan column values.

type CreateCompositeOptions added in v6.14.4

type CreateCompositeOptions struct {
	Varchar int // replaces PostgreSQL data type `text` with `varchar(n)`
}

type CreateTableOptions

type CreateTableOptions struct {
	Temp        bool
	IfNotExists bool
	Varchar     int // replaces PostgreSQL data type `text` with `varchar(n)`

	// FKConstraints causes CreateTable to create foreign key constraints
	// for has one relations. ON DELETE hook can be added using tag
	// `sql:"on_delete:RESTRICT"` on foreign key field.
	FKConstraints bool
}

type DB

type DB interface {
	Model(model ...interface{}) *Query
	Select(model interface{}) error
	Insert(model ...interface{}) error
	Update(model interface{}) error
	Delete(model interface{}) error
	ForceDelete(model interface{}) error

	Exec(query interface{}, params ...interface{}) (Result, error)
	ExecOne(query interface{}, params ...interface{}) (Result, error)
	Query(coll, query interface{}, params ...interface{}) (Result, error)
	QueryOne(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
	QueryFormatter
}

DB is a common interface for pg.DB and pg.Tx types.

type Discard

type Discard struct {
	// contains filtered or unexported fields
}

func (Discard) AddModel

func (m Discard) AddModel(ColumnScanner) error

func (Discard) AfterDelete

func (Discard) AfterDelete(_ DB) error

func (Discard) AfterInsert

func (Discard) AfterInsert(_ DB) error

func (Discard) AfterQuery

func (Discard) AfterQuery(_ DB) error

func (Discard) AfterSelect

func (Discard) AfterSelect(_ DB) error

func (Discard) AfterUpdate

func (Discard) AfterUpdate(_ DB) error

func (Discard) BeforeDelete

func (Discard) BeforeDelete(_ DB) error

func (Discard) BeforeInsert

func (Discard) BeforeInsert(_ DB) error

func (Discard) BeforeSelectQuery added in v6.14.4

func (Discard) BeforeSelectQuery(db DB, q *Query) (*Query, error)

func (Discard) BeforeUpdate

func (Discard) BeforeUpdate(_ DB) error

func (Discard) Init added in v6.3.3

func (Discard) Init() error

func (Discard) NewModel

func (m Discard) NewModel() ColumnScanner

func (Discard) ScanColumn

func (m Discard) ScanColumn(colIdx int, colName string, b []byte) error

type DropCompositeOptions added in v6.14.4

type DropCompositeOptions struct {
	IfExists bool
	Cascade  bool
}

type DropTableOptions added in v6.1.6

type DropTableOptions struct {
	IfExists bool
	Cascade  bool
}

type Field

type Field struct {
	Field reflect.StructField
	Type  reflect.Type

	GoName   string  // struct field name, e.g. Id
	SQLName  string  // SQL name, .e.g. id
	Column   types.Q // escaped SQL name, e.g. "id"
	SQLType  string
	Index    []int
	Default  types.Q
	OnDelete string
	// contains filtered or unexported fields
}

func (*Field) AppendValue

func (f *Field) AppendValue(b []byte, strct reflect.Value, quote int) []byte

func (*Field) Copy

func (f *Field) Copy() *Field

func (*Field) HasFlag added in v6.1.2

func (f *Field) HasFlag(flag uint8) bool

func (*Field) IsZero added in v6.1.5

func (f *Field) IsZero(strct reflect.Value) bool

func (*Field) OmitZero added in v6.1.5

func (f *Field) OmitZero() bool

func (*Field) ScanValue

func (f *Field) ScanValue(strct reflect.Value, b []byte) error

func (*Field) SetFlag added in v6.1.2

func (f *Field) SetFlag(flag uint8)

func (*Field) Value

func (f *Field) Value(strct reflect.Value) reflect.Value

type FormatAppender

type FormatAppender interface {
	AppendFormat([]byte, QueryFormatter) []byte
}

type Formatter

type Formatter struct {
	// contains filtered or unexported fields
}

func (Formatter) Append

func (f Formatter) Append(dst []byte, src string, params ...interface{}) []byte

func (Formatter) AppendBytes

func (f Formatter) AppendBytes(dst, src []byte, params ...interface{}) []byte

func (Formatter) FormatQuery

func (f Formatter) FormatQuery(dst []byte, query string, params ...interface{}) []byte

func (Formatter) Param added in v6.12.0

func (f Formatter) Param(param string) interface{}

func (*Formatter) SetParam

func (f *Formatter) SetParam(param string, value interface{})

func (Formatter) String

func (f Formatter) String() string

func (*Formatter) WithParam

func (f *Formatter) WithParam(param string, value interface{}) Formatter

type HooklessModel added in v6.6.22

type HooklessModel interface {
	// Init is responsible to initialize/reset model state.
	// It is called only once no matter how many rows
	// were returned by database.
	Init() error

	// NewModel returns ColumnScanner that is used to scan columns
	// from the current row. It is called once for every row.
	NewModel() ColumnScanner

	// AddModel adds ColumnScanner created by NewModel to the Collection.
	AddModel(ColumnScanner) error

	ColumnScanner
}

type Method

type Method struct {
	Index int
	// contains filtered or unexported fields
}

func (*Method) AppendValue

func (m *Method) AppendValue(dst []byte, strct reflect.Value, quote int) []byte

func (*Method) Has

func (m *Method) Has(flag int8) bool

func (*Method) Value

func (m *Method) Value(strct reflect.Value) reflect.Value

type Model

type Model interface {
	HooklessModel

	AfterQuery(DB) error

	BeforeSelectQuery(DB, *Query) (*Query, error)
	AfterSelect(DB) error

	BeforeInsert(DB) error
	AfterInsert(DB) error

	BeforeUpdate(DB) error
	AfterUpdate(DB) error

	BeforeDelete(DB) error
	AfterDelete(DB) error
}

func NewModel

func NewModel(values ...interface{}) (Model, error)

type Pager

type Pager struct {
	Limit  int
	Offset int

	// Default max limit is 1000.
	MaxLimit int
	// Default max offset is 1000000.
	MaxOffset int
	// contains filtered or unexported fields
}

func NewPager

func NewPager(values url.Values) *Pager

func (*Pager) GetLimit added in v6.2.0

func (p *Pager) GetLimit() int

func (*Pager) GetOffset added in v6.2.0

func (p *Pager) GetOffset() int

func (*Pager) GetPage added in v6.2.0

func (p *Pager) GetPage() int

func (*Pager) Paginate

func (p *Pager) Paginate(q *Query) (*Query, error)

func (*Pager) SetPage added in v6.4.7

func (p *Pager) SetPage(page int)

func (*Pager) SetURLValues added in v6.2.0

func (p *Pager) SetURLValues(urlValues url.Values)

type Query

type Query struct {
	// contains filtered or unexported fields
}

func NewQuery

func NewQuery(db DB, model ...interface{}) *Query

func (*Query) AppendQuery added in v6.3.5

func (q *Query) AppendQuery(b []byte) ([]byte, error)

func (*Query) Apply

func (q *Query) Apply(fn func(*Query) (*Query, error)) *Query

Apply calls the fn passing the Query as an argument.

func (*Query) Column

func (q *Query) Column(columns ...string) *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.*.

func (*Query) ColumnExpr

func (q *Query) ColumnExpr(expr string, params ...interface{}) *Query

ColumnExpr adds column expression to the Query.

func (*Query) Copy

func (q *Query) Copy() *Query

Copy returns copy of the Query.

func (*Query) CopyFrom added in v6.4.16

func (q *Query) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (Result, error)

CopyFrom is an alias from DB.CopyFrom.

func (*Query) CopyTo added in v6.4.16

func (q *Query) CopyTo(w io.Writer, query interface{}, params ...interface{}) (Result, error)

CopyTo is an alias from DB.CopyTo.

func (*Query) Count

func (q *Query) Count() (int, error)

Count returns number of rows matching the query using count aggregate function.

func (*Query) CountEstimate

func (q *Query) CountEstimate(threshold int) (int, error)

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 (*Query) CreateTable

func (q *Query) CreateTable(opt *CreateTableOptions) error

func (*Query) DB

func (q *Query) DB(db DB) *Query

func (*Query) Delete

func (q *Query) Delete(values ...interface{}) (Result, error)

Delete deletes the model. When model has deleted_at column the row is soft deleted instead.

func (*Query) Deleted added in v6.14.4

func (q *Query) Deleted() *Query

Deleted adds `WHERE deleted_at IS NOT NULL` clause for soft deleted models.

func (*Query) DropTable added in v6.1.6

func (q *Query) DropTable(opt *DropTableOptions) error

func (*Query) ExcludeColumn added in v6.13.5

func (q *Query) ExcludeColumn(columns ...string) *Query

ExcludeColumn excludes a column from the list of to be selected columns.

func (*Query) Exec added in v6.4.7

func (q *Query) Exec(query interface{}, params ...interface{}) (Result, error)

Exec is an alias for DB.Exec.

func (*Query) ExecOne added in v6.4.7

func (q *Query) ExecOne(query interface{}, params ...interface{}) (Result, error)

ExecOne is an alias for DB.ExecOne.

func (*Query) Exists added in v6.14.3

func (q *Query) Exists() (bool, error)

Exists returns true or false depending if there are any rows matching the query.

func (*Query) First

func (q *Query) First() error

First sorts rows by primary key and selects the first row. It is a shortcut for:

q.OrderExpr("id ASC").Limit(1)

func (*Query) For added in v6.4.22

func (q *Query) For(s string, params ...interface{}) *Query

func (*Query) ForEach added in v6.12.0

func (q *Query) ForEach(fn interface{}) error

ForEach calls the function for each row returned by the query without loading all rows into the memory. Function accepts a struct, pointer to a struct, orm.Model, or values for columns in a row. Function must return an error.

func (*Query) ForceDelete added in v6.14.4

func (q *Query) ForceDelete(values ...interface{}) (Result, error)

Delete forces delete of the model with deleted_at column.

func (*Query) FormatQuery

func (q *Query) FormatQuery(b []byte, query string, params ...interface{}) []byte

func (*Query) Group

func (q *Query) Group(columns ...string) *Query

func (*Query) GroupExpr

func (q *Query) GroupExpr(group string, params ...interface{}) *Query

func (*Query) Having

func (q *Query) Having(having string, params ...interface{}) *Query

func (*Query) Insert

func (q *Query) Insert(values ...interface{}) (Result, error)

Insert inserts the model.

func (*Query) Join

func (q *Query) Join(join string, params ...interface{}) *Query

func (*Query) JoinOn added in v6.11.0

func (q *Query) JoinOn(condition string, params ...interface{}) *Query

JoinOn appends join condition to the last join.

func (*Query) JoinOnOr added in v6.11.0

func (q *Query) JoinOnOr(condition string, params ...interface{}) *Query

func (*Query) Last

func (q *Query) Last() error

Last sorts rows by primary key and selects the last row. It is a shortcut for:

q.OrderExpr("id DESC").Limit(1)

func (*Query) Limit

func (q *Query) Limit(n int) *Query

func (*Query) Model

func (q *Query) Model(model ...interface{}) *Query

func (*Query) New

func (q *Query) New() *Query

New returns new zero Query binded to the current db and model.

func (*Query) Offset

func (q *Query) Offset(n int) *Query

func (*Query) OnConflict

func (q *Query) OnConflict(s string, params ...interface{}) *Query

func (*Query) Order

func (q *Query) Order(orders ...string) *Query

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.

func (*Query) OrderExpr

func (q *Query) OrderExpr(order string, params ...interface{}) *Query

Order adds sort order to the Query.

func (*Query) Query added in v6.4.7

func (q *Query) Query(model, query interface{}, params ...interface{}) (Result, error)

Query is an alias for DB.Query.

func (*Query) QueryOne added in v6.4.7

func (q *Query) QueryOne(model, query interface{}, params ...interface{}) (Result, error)

QueryOne is an alias for DB.QueryOne.

func (*Query) Relation

func (q *Query) Relation(name string, apply ...func(*Query) (*Query, error)) *Query

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.

func (*Query) Returning

func (q *Query) Returning(s string, params ...interface{}) *Query

func (*Query) Select

func (q *Query) Select(values ...interface{}) error

Select selects the model.

func (*Query) SelectAndCount

func (q *Query) SelectAndCount(values ...interface{}) (count int, firstErr error)

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 (*Query) SelectAndCountEstimate

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.

func (*Query) SelectOrInsert

func (q *Query) SelectOrInsert(values ...interface{}) (inserted bool, _ error)

SelectOrInsert selects the model inserting one if it does not exist. It returns true when model was inserted.

func (*Query) Set

func (q *Query) Set(set string, params ...interface{}) *Query

func (*Query) Table

func (q *Query) Table(tables ...string) *Query

func (*Query) TableExpr

func (q *Query) TableExpr(expr string, params ...interface{}) *Query

func (*Query) Update

func (q *Query) Update(scan ...interface{}) (Result, error)

Update updates the model.

func (*Query) UpdateNotNull added in v6.6.1

func (q *Query) UpdateNotNull(scan ...interface{}) (Result, error)

Update updates the model omitting null columns.

func (*Query) Value added in v6.9.3

func (q *Query) Value(column string, value string, params ...interface{}) *Query

Value overwrites model value for the column in INSERT and UPDATE queries.

func (*Query) Where

func (q *Query) Where(condition string, params ...interface{}) *Query

func (*Query) WhereGroup added in v6.2.2

func (q *Query) WhereGroup(fn func(*Query) (*Query, error)) *Query

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)

func (*Query) WhereIn

func (q *Query) WhereIn(where string, values ...interface{}) *Query

WhereIn is a shortcut for Where and pg.In to work with IN operator:

WhereIn("id IN (?)", 1, 2, 3)

func (*Query) WhereOr

func (q *Query) WhereOr(condition string, params ...interface{}) *Query

func (*Query) WhereOrGroup added in v6.4.24

func (q *Query) WhereOrGroup(fn func(*Query) (*Query, error)) *Query

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)

func (*Query) WherePK added in v6.6.18

func (q *Query) WherePK() *Query

WherePK adds condition based on the model primary key. Typically it is the same as:

Where("id = ?id")

func (*Query) With

func (q *Query) With(name string, subq *Query) *Query

With adds subq as common table expression with the given name.

func (*Query) WrapWith

func (q *Query) WrapWith(name string) *Query

WrapWith creates new Query and adds to it current query as common table expression with the given name.

type QueryAppender

type QueryAppender interface {
	Copy() QueryAppender
	Query() *Query
	AppendQuery(dst []byte) ([]byte, error)
}

type QueryFormatter

type QueryFormatter interface {
	FormatQuery(b []byte, query string, params ...interface{}) []byte
}

type Relation

type Relation struct {
	Type        int
	Field       *Field
	JoinTable   *Table
	FKs         []*Field
	Polymorphic *Field
	FKValues    []*Field

	M2MTableName  types.Q
	M2MTableAlias types.Q
	BaseFKs       []string
	JoinFKs       []string
}

func (*Relation) String added in v6.13.2

func (r *Relation) String() string

type Result

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
}

A Result summarizes an executed SQL command.

type Table

type Table struct {
	Type reflect.Type

	TypeName       string
	Name           types.Q
	NameForSelects types.Q
	Alias          types.Q
	ModelName      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
	// contains filtered or unexported fields
}

Table represents a SQL table created from Go struct.

func GetTable added in v6.12.0

func GetTable(typ reflect.Type) *Table

GetTable returns a Table for a struct type.

func (*Table) AddField

func (t *Table) AddField(field *Field)

func (*Table) AppendParam

func (t *Table) AppendParam(b []byte, strct reflect.Value, name string) ([]byte, bool)

func (*Table) GetField

func (t *Table) GetField(fieldName string) (*Field, error)

func (*Table) HasField

func (t *Table) HasField(field string) bool

func (*Table) HasFlag added in v6.1.2

func (t *Table) HasFlag(flag uint16) bool

func (*Table) RemoveField added in v6.6.20

func (t *Table) RemoveField(field *Field)

func (*Table) SetFlag added in v6.1.2

func (t *Table) SetFlag(flag uint16)

func (*Table) String added in v6.9.1

func (t *Table) String() string

type URLFilter added in v6.13.6

type URLFilter struct {
	// contains filtered or unexported fields
}

URLFilter is used with Query.Apply to add WHERE clauses from the URL values:

  • ?foo=bar - Where(`"foo" = 'bar'`)
  • ?foo=hello&foo=world - Where(`"foo" IN ('hello','world')`)
  • ?foo__exclude=bar - Where(`"foo" != 'bar'`)
  • ?foo__ieq=bar - Where(`"foo" ILIKE 'bar'`)
  • ?foo__match=bar - Where(`"foo" SIMILAR TO 'bar'`)
  • ?foo__gt=42 - Where(`"foo" > 42`)
  • ?foo__gte=42 - Where(`"foo" >= 42`)
  • ?foo__lt=42 - Where(`"foo" < 42`)
  • ?foo__lte=42 - Where(`"foo" <= 42`)

func NewURLFilter added in v6.13.6

func NewURLFilter(values url.Values) *URLFilter

func (*URLFilter) Allow added in v6.13.6

func (f *URLFilter) Allow(filters ...string)

func (*URLFilter) Filters added in v6.13.6

func (f *URLFilter) Filters(q *Query) (*Query, error)

func (*URLFilter) Values added in v6.13.6

func (f *URLFilter) Values() URLValues

Values returns URL values.

type URLValues added in v6.13.6

type URLValues map[string][]string

func (URLValues) Bool added in v6.14.4

func (v URLValues) Bool(name string) (bool, error)

func (URLValues) Duration added in v6.13.6

func (v URLValues) Duration(name string) (time.Duration, error)

func (URLValues) Has added in v6.13.6

func (v URLValues) Has(name string) bool

func (URLValues) Int added in v6.13.6

func (v URLValues) Int(name string) (int, error)

func (URLValues) Int64 added in v6.13.6

func (v URLValues) Int64(name string) (int64, error)

func (URLValues) MaybeBool added in v6.15.1

func (v URLValues) MaybeBool(name string) bool

func (URLValues) MaybeDuration added in v6.13.6

func (v URLValues) MaybeDuration(name string) time.Duration

func (URLValues) MaybeInt added in v6.13.6

func (v URLValues) MaybeInt(name string) int

func (URLValues) MaybeInt64 added in v6.13.6

func (v URLValues) MaybeInt64(name string) int64

func (URLValues) MaybeTime added in v6.13.6

func (v URLValues) MaybeTime(name string) time.Time

func (URLValues) Pager added in v6.13.6

func (v URLValues) Pager() *Pager

func (URLValues) SetDefault added in v6.13.6

func (v URLValues) SetDefault(name string, values ...string)

func (URLValues) String added in v6.13.6

func (v URLValues) String(name string) string

func (URLValues) Strings added in v6.13.6

func (v URLValues) Strings(name string) []string

func (URLValues) Time added in v6.13.6

func (v URLValues) Time(name string) (time.Time, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL