kallax

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2017 License: MIT Imports: 10 Imported by: 0

README

Kallax - PostgreSQL ORM for Go

Installation

The recommended way to install kallax is:

go get -u github.com/src-d/kallax/...

kallax includes a binary tool used by go generate, please be sure that $GOPATH/bin is on your $PATH

Running tests

For obvious reasons, an instance of PostgreSQL is required to run the tests of this package.

By default, it assumes that an instance exists at 0.0.0.0:5432 with an user, password and database name all equal to testing.

If that is not the case you can set the following environment variables:

  • DBNAME: name of the database
  • DBUSER: database user
  • DBPASS: database user password

License

MIT, see LICENSE

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNonNewDocument non-new documents cannot be inserted
	ErrNonNewDocument = errors.New("kallax: cannot insert a non new document")
	// ErrNewDocument a new documents cannot be updated
	ErrNewDocument = errors.New("kallax: cannot updated a new document")
	// ErrEmptyID a document without ID cannot be used with Save method
	ErrEmptyID = errors.New("kallax: a record without id is not allowed")
	// ErrNoRowUpdate is returned when an update operation does not affect any
	// rows, meaning the model being updated does not exist.
	ErrNoRowUpdate = errors.New("kallax: update affected no rows")
	// ErrNotWritable is returned when a record is not writable.
	ErrNotWritable = errors.New("kallax: record is not writable")
	// ErrStop can be returned inside a ForEach callback to stop iteration.
	ErrStop = errors.New("kallax: stopped ForEach execution")
	// ErrTransactionInsideTransaction is returned when a transaction is run
	// inside a transaction.
	ErrTransactionInsideTransaction = errors.New("kallax: can't start a transaction inside a transaction")
	ErrInvalidTxCallback            = errors.New("kallax: invalid transaction callback given")
)
View Source
var ErrNoMoreRows = errors.New("kallax: there are no more rows in the result set")
View Source
var ErrRawScan = errors.New("kallax: result set comes from raw query, use RawScan instead")

ErrRawScan is an error returned when a the `Scan` method of `ResultSet` is called with a `ResultSet` created as a result of a `RawQuery`, which is not allowed.

Functions

func ColumnNames

func ColumnNames(columns []SchemaField) []string

ColumnNames returns the names of the given schema fields.

func RecordValues

func RecordValues(record Valuer, columns ...string) ([]interface{}, error)

RecordValues returns the values of a record at the given columns in the same order as the columns.

func VirtualColumn added in v0.12.0

func VirtualColumn(col string, r Record) sql.Scanner

Types

type BaseQuery

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

BaseQuery is a generic query builder.

func NewBaseQuery

func NewBaseQuery(schema Schema) *BaseQuery

NewBaseQuery creates a new BaseQuery for querying the given table and the given selected columns.

func (*BaseQuery) AddRelation

func (q *BaseQuery) AddRelation(schema Schema, field string, typ RelationshipType, filter Condition) error

AddRelation adds a relationship if the given to the query, which is present in the given field of the query base schema. A condition to filter can also be passed in the case of one to many relationships.

func (*BaseQuery) BatchSize

func (q *BaseQuery) BatchSize(size uint64)

BatchSize sets the batch size.

func (*BaseQuery) Copy

func (q *BaseQuery) Copy() *BaseQuery

Copy returns an identical copy of the query. BaseQuery is mutable, that is why this method is provided.

func (*BaseQuery) GetBatchSize

func (q *BaseQuery) GetBatchSize() uint64

GetBatchSize returns the number of rows retrieved per batch while retrieving 1:N relationships.

func (*BaseQuery) GetLimit

func (q *BaseQuery) GetLimit() uint64

GetLimit returns the max number of rows to retrieve.

func (*BaseQuery) GetOffset

func (q *BaseQuery) GetOffset() uint64

GetOffset returns the number of rows to skip.

func (*BaseQuery) Limit

func (q *BaseQuery) Limit(n uint64)

Limit sets the max number of rows to retrieve.

func (*BaseQuery) Offset

func (q *BaseQuery) Offset(n uint64)

Offset sets the number of rows to skip.

func (*BaseQuery) Order

func (q *BaseQuery) Order(cols ...ColumnOrder)

Order adds the given order clauses to the list of columns to order the results by.

func (*BaseQuery) Schema added in v0.12.0

func (q *BaseQuery) Schema() Schema

func (*BaseQuery) Select

func (q *BaseQuery) Select(columns ...SchemaField)

Select adds the given columns to the list of selected columns in the query.

func (*BaseQuery) SelectNot

func (q *BaseQuery) SelectNot(columns ...SchemaField)

SelectNot adds the given columns to the list of excluded columns in the query.

func (*BaseQuery) String

func (q *BaseQuery) String() string

String returns the SQL generated by the

func (*BaseQuery) Where

func (q *BaseQuery) Where(cond Condition)

Where adds a new condition to filter the query. All conditions added are concatenated with "and".

q.Where(Eq(NameColumn, "foo"))
q.Where(Gt(AgeColumn, 18))
// ... WHERE name = "foo" AND age > 18

type BaseResultSet added in v0.12.0

type BaseResultSet struct {
	*sql.Rows
	// contains filtered or unexported fields
}

BaseResultSet is a generic collection of rows.

func NewResultSet

func NewResultSet(rows *sql.Rows, readOnly bool, relationships []Relationship, columns ...string) *BaseResultSet

NewResultSet creates a new result set with the given rows and columns. It is mandatory that all column names are in the same order and are exactly equal to the ones in the query that produced the rows.

func (*BaseResultSet) Get added in v0.12.0

func (rs *BaseResultSet) Get(schema Schema) (Record, error)

Get returns the next record in the schema.

func (*BaseResultSet) RawScan added in v0.12.0

func (rs *BaseResultSet) RawScan(dest ...interface{}) error

RowScan copies the columns in the current row into the values pointed at by dest. The number of values in dest must be the same as the number of columns selected in the query.

func (*BaseResultSet) Scan added in v0.12.0

func (rs *BaseResultSet) Scan(record Record) error

Scan fills the column fields of the given value with the current row.

type BaseSchema

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

BaseSchema is the basic implementation of Schema.

func NewBaseSchema

func NewBaseSchema(table, alias string, id SchemaField, fks ForeignKeys, ctor RecordConstructor, columns ...SchemaField) *BaseSchema

NewBaseSchema creates a new schema with the given table, alias, identifier and columns.

func (*BaseSchema) Alias

func (s *BaseSchema) Alias() string

func (*BaseSchema) Columns

func (s *BaseSchema) Columns() []SchemaField

func (*BaseSchema) ForeignKey

func (s *BaseSchema) ForeignKey(field string) (*ForeignKey, bool)

func (*BaseSchema) ID

func (s *BaseSchema) ID() SchemaField

func (*BaseSchema) New added in v0.12.0

func (s *BaseSchema) New() Record

func (*BaseSchema) Table

func (s *BaseSchema) Table() string

func (*BaseSchema) WithAlias

func (s *BaseSchema) WithAlias(field string) Schema

type BaseSchemaField

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

BaseSchemaField is a basic schema field with name.

func (*BaseSchemaField) QualifiedName

func (f *BaseSchemaField) QualifiedName(schema Schema) string

func (BaseSchemaField) String

func (f BaseSchemaField) String() string

type BatchingResultSet added in v0.12.0

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

BatchingResultSet is a result set that retrieves all the items up to the batch size set in the query. If there are 1:N relationships, it collects all the identifiers of those records, retrieves all the rows matching them in the table of the the N end, and assigns them to their correspondent to the record they belong to. It will continue doing this process until no more rows are returned by the query. This minimizes the number of queries and operations to perform in order to retrieve a set of results and their relationships.

func NewBatchingResultSet added in v0.12.0

func NewBatchingResultSet(runner *batchQueryRunner) *BatchingResultSet

NewBatchingResultSet returns a new result set that performs batching underneath.

func (*BatchingResultSet) Close added in v0.12.0

func (rs *BatchingResultSet) Close() error

Close will do nothing, as the internal result sets used by this are closed when the rows at fetched. It will never throw an error.

func (*BatchingResultSet) Get added in v0.12.0

func (rs *BatchingResultSet) Get(_ Schema) (Record, error)

Get returns the next processed record and the last error occurred. Even though it accepts a schema, it is ignored, as the result set is already aware of it. This is here just to be able to imeplement the ResultSet interface.

func (*BatchingResultSet) Next added in v0.12.0

func (rs *BatchingResultSet) Next() bool

Next advances the internal index of the fetched records in one. If there are no fetched records, will fetch the next batch. It will return false when there are no more rows.

func (*BatchingResultSet) RawScan added in v0.12.0

func (rs *BatchingResultSet) RawScan(_ ...interface{}) error

RawScan will always throw an error, as this is not a supported operation of a batching result set.

type ColumnAddresser

type ColumnAddresser interface {
	// ColumnAddress returns a pointer to the object property identified by the
	// column name or an error if that property does not exist
	ColumnAddress(string) (interface{}, error)
}

ColumnAddresser must be implemented by those values that expose their properties under pointers, identified by its property names

type ColumnOrder

type ColumnOrder interface {
	// ToSql returns the SQL representation of the column with its order.
	ToSql(Schema) string
	// contains filtered or unexported methods
}

ColumnOrder is a column name with its order.

func Asc

func Asc(col SchemaField) ColumnOrder

Asc returns a column ordered by ascending order.

func Desc

func Desc(col SchemaField) ColumnOrder

Desc returns a column ordered by descending order.

type Condition

type Condition func(Schema) squirrel.Sqlizer

Condition represents a condition of filtering in a query.

func And

func And(conds ...Condition) Condition

And returns the given conditions joined by logical ands.

func ArrayContainedBy added in v0.12.0

func ArrayContainedBy(col SchemaField, values ...interface{}) Condition

ArrayContainedBy returns a condition that will be true when `col` has all its elements present in the given values.

func ArrayContains added in v0.12.0

func ArrayContains(col SchemaField, values ...interface{}) Condition

ArrayContains returns a condition that will be true when `col` contains all the given values.

func ArrayEq added in v0.12.0

func ArrayEq(col SchemaField, values ...interface{}) Condition

ArrayEq returns a condition that will be true when `col` is equal to an array with the given elements.

func ArrayGt added in v0.12.0

func ArrayGt(col SchemaField, values ...interface{}) Condition

ArrayGt returns a condition that will be true when all elements in `col` are greater or equal than their counterparts in the given values, and one of the elements at least is greater than its counterpart in the given values. For example: for a col with values [1,2,3] and values [1,2,2], it will be true.

func ArrayGtOrEq added in v0.12.0

func ArrayGtOrEq(col SchemaField, values ...interface{}) Condition

ArrayGtOrEq returns a condition that will be true when all elements in `col` are greater or equal than their counterparts in the given values. For example: for a col with values [1,2,2] and values [1,2,2], it will be true.

func ArrayLt added in v0.12.0

func ArrayLt(col SchemaField, values ...interface{}) Condition

ArrayLt returns a condition that will be true when all elements in `col` are lower or equal than their counterparts in the given values, and one of the elements at least is lower than its counterpart in the given values. For example: for a col with values [1,2,2] and values [1,2,3], it will be true.

func ArrayLtOrEq added in v0.12.0

func ArrayLtOrEq(col SchemaField, values ...interface{}) Condition

ArrayLtOrEq returns a condition that will be true when all elements in `col` are lower or equal than their counterparts in the given values. For example: for a col with values [1,2,2] and values [1,2,2], it will be true.

func ArrayNotEq added in v0.12.0

func ArrayNotEq(col SchemaField, values ...interface{}) Condition

ArrayNotEq returns a condition that will be true when `col` is not equal to an array with the given elements.

func ArrayOverlap added in v0.12.0

func ArrayOverlap(col SchemaField, values ...interface{}) Condition

ArrayOverlap returns a condition that will be true when `col` has elements in common with an array formed by the given values.

func Eq

func Eq(col SchemaField, value interface{}) Condition

Eq returns a condition that will be true when `col` is equal to `value`.

func Gt

func Gt(col SchemaField, n interface{}) Condition

Gt returns a condition that will be true when `col` is greater than `value`.

func GtOrEq

func GtOrEq(col SchemaField, n interface{}) Condition

GtOrEq returns a condition that will be true when `col` is greater than `value` or equal.

func In

func In(col SchemaField, values ...interface{}) Condition

In returns a condition that will be true when `col` is equal to any of the passed `values`.

func Lt

func Lt(col SchemaField, value interface{}) Condition

Lt returns a condition that will be true when `col` is lower than `value`.

func LtOrEq

func LtOrEq(col SchemaField, n interface{}) Condition

LtOrEq returns a condition that will be true when `col` is lower than `value` or equal.

func Neq

func Neq(col SchemaField, n interface{}) Condition

Neq returns a condition that will be true when `col` is not `value`.

func Not

func Not(cond Condition) Condition

Not returns the given condition negated.

func NotIn

func NotIn(col SchemaField, values ...interface{}) Condition

NotIn returns a condition that will be true when `col` is distinct to all of the passed `values`.

func Or

func Or(conds ...Condition) Condition

Or returns the given conditions joined by logical ors.

type ForeignKey added in v0.12.0

type ForeignKey struct {
	*BaseSchemaField
	Inverse bool
}

ForeignKey contains the schema field of the foreign key and if it is an inverse foreign key or not.

func NewForeignKey added in v0.12.0

func NewForeignKey(name string, inverse bool) *ForeignKey

NewForeignKey creates a new Foreign key with the given name.

type ForeignKeys

type ForeignKeys map[string]*ForeignKey

ForeignKeys is a mapping between relationships and their foreign key field.

type ID

type ID uuid.UUID

ID is the Kallax identifier type.

func NewID

func NewID() ID

NewID returns a new kallax ID.

func (ID) IsEmpty

func (id ID) IsEmpty() bool

IsEmpty returns true if the ID is not set

func (*ID) Scan

func (id *ID) Scan(src interface{}) error

Scan implements the Scanner interface.

func (ID) String

func (id ID) String() string

func (ID) Value

func (id ID) Value() (driver.Value, error)

Value implements the Valuer interface.

type Identifiable

type Identifiable interface {
	// GetID returns the ID.
	GetID() ID
	// SetID overrides the ID.
	SetID(id ID)
}

Identifiable must be implemented by those values that can be identified by an ID

type Model

type Model struct {
	ID ID
	// contains filtered or unexported fields
}

Model is the base type of the items that are stored

func NewModel

func NewModel() Model

NewModel creates and return a new Model

func (*Model) AddVirtualColumn added in v0.12.0

func (m *Model) AddVirtualColumn(name string, v interface{})

AddVirtualColumn adds a new virtual column with the given name and value.

func (*Model) ClearVirtualColumns added in v0.12.0

func (m *Model) ClearVirtualColumns()

ClearVirtualColumns clears all the previous virtual columns.

func (*Model) GetID

func (m *Model) GetID() ID

GetID returns the ID.

func (*Model) IsPersisted

func (m *Model) IsPersisted() bool

IsPersisted returns whether this Model is new in the store or not.

func (*Model) IsWritable

func (m *Model) IsWritable() bool

IsWritable returns whether this Model can be sent back to the database to be stored with its changes.

func (*Model) SetID

func (m *Model) SetID(id ID)

SetID overrides the ID. The ID should not be modified once it has been set and stored in the DB WARNING: Not to be used by final users!

func (*Model) VirtualColumn added in v0.12.0

func (m *Model) VirtualColumn(name string) interface{}

VirtualColumn returns the value of the virtual column with the given column name.

type Persistable

type Persistable interface {
	// IsPersisted returns whether this Model is new in the store or not.
	IsPersisted() bool
	// contains filtered or unexported methods
}

Persistable must be implemented by those values that can be persisted

type Query

type Query interface {

	// Schema returns the schema of the query model.
	Schema() Schema
	// GetOffset returns the number of skipped rows in the query.
	GetOffset() uint64
	// GetLimit returns the max number of rows retrieved by the query.
	GetLimit() uint64
	// GetBatchSize returns the number of rows retrieved by the store per
	// batch. This is only used and has effect on queries with 1:N
	// relationships.
	GetBatchSize() uint64
	// contains filtered or unexported methods
}

Query returns information about some query settings and compiles the query.

type Record

Record is the interface that must be implemented by models that can be stored.

type RecordConstructor added in v0.12.0

type RecordConstructor func() Record

RecordConstructor is a function that creates a record.

type RecordWithSchema added in v0.12.0

type RecordWithSchema struct {
	Schema Schema
	Record Record
}

RecordWithSchema is a structure that contains both a record and its schema.

type Relationable

type Relationable interface {
	// NewRelationshipRecord returns a new Record for the relationship at the
	// given field.
	NewRelationshipRecord(string) (Record, error)
	// SetRelationship sets the relationship value at the given field.
	SetRelationship(string, interface{}) error
}

Relationable can perform operations related to relationships of a record.

type Relationship

type Relationship struct {
	// Type is the kind of relationship this is.
	Type RelationshipType
	// Field is the field in the record where the relationship is.
	Field string
	// Schema is the schema of the relationship.
	Schema Schema
	// Filter establishes the filter to be applied when retrieving rows of the
	// relationships.
	Filter Condition
}

Relationship is a relationship with its schema and the field of te relation in the record.

type RelationshipType added in v0.12.0

type RelationshipType byte

RelationshipType describes the type of the relationship.

const (
	// OneToOne is a relationship between one record in a table and another in
	// another table.
	OneToOne RelationshipType = iota
	// OneToMany is a relationship between one record in a table and multiple
	// in another table.
	OneToMany
	// ManyToMany is a relationship between many records on both sides of the
	// relationship.
	// NOTE: It is not supported yet.
	ManyToMany
)

type ResultSet

type ResultSet interface {
	// RawScan allows for raw scanning of fields in a result set.
	RawScan(...interface{}) error
	// Next moves the pointer to the next item in the result set and returns
	// if there was any.
	Next() bool
	// Get returns the next record of the given schema.
	Get(Schema) (Record, error)
	io.Closer
}

ResultSet is the common interface all result sets need to implement.

type Schema

type Schema interface {
	// Alias returns the name of the alias used in queries for this schema.
	Alias() string
	// Table returns the table name.
	Table() string
	// ID returns the name of the identifier of the table.
	ID() SchemaField
	// Columns returns the list of columns in the schema.
	Columns() []SchemaField
	// ForeignKey returns the name of the foreign key of the given model field.
	ForeignKey(string) (*ForeignKey, bool)
	// WithAlias returns a new schema with the given string added to the
	// default alias.
	// Calling WithAlias on a schema returned by WithAlias not return a
	// schema based on the child, but another based on the parent.
	WithAlias(string) Schema
	// New creates a new record with the given schema.
	New() Record
}

Schema represents a table schema in the database. Contains some information like the table name, its columns, its identifier and so on.

type SchemaField

type SchemaField interface {

	// String returns the string representation of the field. That is, its name.
	String() string
	// QualifiedString returns the name of the field qualified by the alias of
	// the given schema.
	QualifiedName(Schema) string
	// contains filtered or unexported methods
}

SchemaField is a named field in the table schema.

func NewSchemaField

func NewSchemaField(name string) SchemaField

NewSchemaField creates a new schema field with the given name.

type Store

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

Store is a structure capable of retrieving records from a concrete table in the database.

func NewStore

func NewStore(db *sql.DB) *Store

NewStore returns a new Store instance.

func (*Store) Count

func (s *Store) Count(q Query) (count int64, err error)

Count returns the number of rows selected by the given query.

func (*Store) Delete

func (s *Store) Delete(schema Schema, record Record) error

Delete removes the record from the table. A non-new record with non-empty ID is required.

func (*Store) Find

func (s *Store) Find(q Query) (ResultSet, error)

Find performs a query and returns a result set with the results.

func (*Store) Insert

func (s *Store) Insert(schema Schema, record Record) error

Insert insert the given record in the table, returns error if no-new record is given. The record id is set if it's empty.

func (*Store) MustCount

func (s *Store) MustCount(q Query) int64

MustCount returns the number of rows selected by the given query. It panics if the query fails.

func (*Store) MustFind

func (s *Store) MustFind(q Query) ResultSet

MustFind performs a query and returns a result set with the results. It panics if the query fails.

func (*Store) RawExec

func (s *Store) RawExec(sql string, params ...interface{}) (int64, error)

RawExec executes a raw SQL query with the given parameters and returns the number of affected rows.

func (*Store) RawQuery

func (s *Store) RawQuery(sql string, params ...interface{}) (ResultSet, error)

RawQuery performs a raw SQL query with the given parameters and returns a result set with the results. WARNING: A result set created from a raw query can only be scanned using the RawScan method of ResultSet, instead of Scan.

func (*Store) Reload

func (s *Store) Reload(schema Schema, record Record) error

Reload refreshes the record with the data in the database and makes the record writable.

func (*Store) Save

func (s *Store) Save(schema Schema, record Record) (updated bool, err error)

Save inserts or updates the given record in the table. It requires a record with non empty ID.

func (*Store) Transaction

func (s *Store) Transaction(callback func(*Store) error) error

Transaction executes the given callback in a transaction and rollbacks if an error is returned. The transaction is only open in the store passed as a parameter to the callback.

func (*Store) Update

func (s *Store) Update(schema Schema, record Record, cols ...SchemaField) (int64, error)

Update updates the given fields of a record in the table. All fields are updated if no fields are provided. For an update to take place, the record is required to have a non-empty ID and not to be a new record. Returns the number of updated rows and an error, if any.

type Timestamps

type Timestamps struct {
	// CreatedAt is the time where the object was created.
	CreatedAt time.Time
	// UpdatedAt is the time where the object was updated.
	UpdatedAt time.Time
	// contains filtered or unexported fields
}

Timestamp modelates an object that knows about when was created and updated.

func (*Timestamps) BeforeSave added in v0.12.0

func (t *Timestamps) BeforeSave() error

BeforeSave updates the UpdatedAt and creates a new CreatedAt if it does not exist.

func (*Timestamps) Timestamp

func (t *Timestamps) Timestamp()

Timestamp updates the UpdatedAt and creates a new CreatedAt if it does not exist.

type Valuer

type Valuer interface {
	// Value returns the value under the object property identified by the passed
	// string or an error if that property does not exist
	Value(string) (interface{}, error)
}

Valuer must be implemented by those object that expose their properties identified by its property names

type VirtualColumnContainer added in v0.12.0

type VirtualColumnContainer interface {
	// ClearVirtualColumns removes all virtual columns.
	ClearVirtualColumns()
	// AddVirtualColumn adds a new virtual column with the given name and value
	AddVirtualColumn(string, interface{})
	// VirtualColumn returns the virtual column with the given column name.
	VirtualColumn(string) interface{}
}

VirtualColumnContainer contains a collection of virtual columns and manages them.

type Writable

type Writable interface {
	// IsWritable returns whether this Model can be sent back to the database
	// to be stored with its changes.
	IsWritable() bool
	// contains filtered or unexported methods
}

Writable must be implemented by those values that defines internally if they can be sent back to the database to be stored with its changes.

Directories

Path Synopsis
IMPORTANT! This is auto generated code by https://github.com/src-d/go-kallax Please, do not touch the code below, and if you do, do it under your own risk.
IMPORTANT! This is auto generated code by https://github.com/src-d/go-kallax Please, do not touch the code below, and if you do, do it under your own risk.

Jump to

Keyboard shortcuts

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