Documentation ¶
Overview ¶
Kallax is a PostgreSQL typesafe ORM for the Go language.
Kallax aims to provide a way of programmatically write queries and interact with a PostgreSQL database without having to write a single line of SQL, use strings to refer to columns and use values of any type in queries. For that reason, the first priority of kallax is to provide type safety to the data access layer. Another of the goals of kallax is make sure all models are, first and foremost, Go structs without having to use database-specific types such as, for example, `sql.NullInt64`. Support for arrays of all basic Go types and all JSON and arrays operators is provided as well.
Index ¶
- Variables
- func ApplyAfterEvents(r Record, wasPersisted bool) error
- func ApplyBeforeEvents(r Record) error
- func ColumnNames(columns []SchemaField) []string
- func RecordValues(record Valuer, columns ...string) ([]interface{}, error)
- func StoreFrom(to, from GenericStorer)
- func VirtualColumn(col string, r Record, id Identifier) sql.Scanner
- type AfterDeleter
- type AfterInserter
- type AfterSaver
- type AfterUpdater
- type ArraySchemaField
- type BaseQuery
- func (q *BaseQuery) AddRelation(schema Schema, field string, typ RelationshipType, filter Condition) error
- func (q *BaseQuery) BatchSize(size uint64)
- func (q *BaseQuery) Copy() *BaseQuery
- func (q *BaseQuery) GetBatchSize() uint64
- func (q *BaseQuery) GetLimit() uint64
- func (q *BaseQuery) GetOffset() uint64
- func (q *BaseQuery) Limit(n uint64)
- func (q *BaseQuery) Offset(n uint64)
- func (q *BaseQuery) Order(cols ...ColumnOrder)
- func (q *BaseQuery) Schema() Schema
- func (q *BaseQuery) Select(columns ...SchemaField)
- func (q *BaseQuery) SelectNot(columns ...SchemaField)
- func (q *BaseQuery) String() string
- func (q *BaseQuery) Where(cond Condition)
- type BaseResultSet
- type BaseSchema
- func (s *BaseSchema) Alias() string
- func (s *BaseSchema) Columns() []SchemaField
- func (s *BaseSchema) ForeignKey(field string) (*ForeignKey, bool)
- func (s *BaseSchema) ID() SchemaField
- func (s *BaseSchema) New() Record
- func (s *BaseSchema) Table() string
- func (s *BaseSchema) WithAlias(field string) Schema
- type BaseSchemaField
- type BatchingResultSet
- type BeforeDeleter
- type BeforeInserter
- type BeforeSaver
- type BeforeUpdater
- type ColumnAddresser
- type ColumnOrder
- type Condition
- func And(conds ...Condition) Condition
- func ArrayContainedBy(col SchemaField, values ...interface{}) Condition
- func ArrayContains(col SchemaField, values ...interface{}) Condition
- func ArrayEq(col SchemaField, values ...interface{}) Condition
- func ArrayGt(col SchemaField, values ...interface{}) Condition
- func ArrayGtOrEq(col SchemaField, values ...interface{}) Condition
- func ArrayLt(col SchemaField, values ...interface{}) Condition
- func ArrayLtOrEq(col SchemaField, values ...interface{}) Condition
- func ArrayNotEq(col SchemaField, values ...interface{}) Condition
- func ArrayOverlap(col SchemaField, values ...interface{}) Condition
- func Eq(col SchemaField, value interface{}) Condition
- func Gt(col SchemaField, value interface{}) Condition
- func GtOrEq(col SchemaField, value interface{}) Condition
- func In(col SchemaField, values ...interface{}) Condition
- func JSONContainedBy(col SchemaField, elem interface{}) Condition
- func JSONContains(col SchemaField, elem interface{}) Condition
- func JSONContainsAllKeys(col SchemaField, keys ...string) Condition
- func JSONContainsAny(col SchemaField, elems ...interface{}) Condition
- func JSONContainsAnyKey(col SchemaField, keys ...string) Condition
- func JSONIsArray(col SchemaField) Condition
- func JSONIsObject(col SchemaField) Condition
- func Lt(col SchemaField, value interface{}) Condition
- func LtOrEq(col SchemaField, value interface{}) Condition
- func MatchRegex(col SchemaField, pattern string) Condition
- func MatchRegexCase(col SchemaField, pattern string) Condition
- func Neq(col SchemaField, value interface{}) Condition
- func Not(cond Condition) Condition
- func NotIn(col SchemaField, values ...interface{}) Condition
- func NotMatchRegex(col SchemaField, pattern string) Condition
- func NotMatchRegexCase(col SchemaField, pattern string) Condition
- func Or(conds ...Condition) Condition
- type ForeignKey
- type ForeignKeys
- type GenericStorer
- type Identifiable
- type Identifier
- type JSONKeyType
- type JSONSchemaArray
- type JSONSchemaKey
- type Model
- type NumericID
- type Persistable
- type Query
- type Record
- type RecordConstructor
- type RecordWithSchema
- type Relationable
- type Relationship
- type RelationshipType
- type ResultSet
- type ScalarCond
- type Schema
- type SchemaField
- type Store
- func (s *Store) Count(q Query) (count int64, err error)
- func (s *Store) Delete(schema Schema, record Record) error
- func (s *Store) Find(q Query) (ResultSet, error)
- func (s *Store) Insert(schema Schema, record Record) error
- func (s *Store) MustCount(q Query) int64
- func (s *Store) MustFind(q Query) ResultSet
- func (s *Store) RawExec(sql string, params ...interface{}) (int64, error)
- func (s *Store) RawQuery(sql string, params ...interface{}) (ResultSet, error)
- func (s *Store) Reload(schema Schema, record Record) error
- func (s *Store) Save(schema Schema, record Record) (updated bool, err error)
- func (s *Store) Transaction(callback func(*Store) error) error
- func (s *Store) Update(schema Schema, record Record, cols ...SchemaField) (int64, error)
- type Timestamps
- type ULID
- func (id ULID) Equals(other Identifier) bool
- func (id ULID) IsEmpty() bool
- func (id ULID) MarshalText() ([]byte, error)
- func (id ULID) Raw() interface{}
- func (id *ULID) Scan(src interface{}) error
- func (id ULID) String() string
- func (u *ULID) UnmarshalText(text []byte) (err error)
- func (id ULID) Value() (driver.Value, error)
- type UUID
- type Valuer
- type VirtualColumnContainer
- type Writable
Constants ¶
This section is empty.
Variables ¶
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") // ErrInvalidTxCallback is returned when a nil callback is passed. ErrInvalidTxCallback = errors.New("kallax: invalid transaction callback given") // ErrNotFound is returned when a certain entity is not found. ErrNotFound = errors.New("kallax: entity not found") // ErrCantSetID is returned when a model is inserted and it does not have // neither an autoincrement primary key nor implements the IDSetter // interface. ErrCantSetID = errors.New("kallax: model does not have an auto incrementable primary key, it needs to implement IDSetter interface") )
var ( // ErrManyToManyNotSupported is returned when a many to many relationship // is added to a query. ErrManyToManyNotSupported = errors.New("kallax: many to many relationships are not supported") )
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.
var ErrRawScanBatching = errors.New("kallax: cannot perform a raw scan on a batching result set")
ErrRawScanBatching is an error returned when the `RawScan` method is used with a batching result set.
Functions ¶
func ApplyAfterEvents ¶
ApplyAfterEvents calls all the update, insert or save after events of the record. Save events are always called after the insert or update event.
func ApplyBeforeEvents ¶
ApplyBeforeEvents calls all the update, insert or save before events of the record. Save events are always called before the insert or update event.
func ColumnNames ¶
func ColumnNames(columns []SchemaField) []string
ColumnNames returns the names of the given schema fields.
func RecordValues ¶
RecordValues returns the values of a record at the given columns in the same order as the columns.
func StoreFrom ¶ added in v1.1.0
func StoreFrom(to, from GenericStorer)
StoreFrom sets the generic store of `from` in `to`.
func VirtualColumn ¶
func VirtualColumn(col string, r Record, id Identifier) sql.Scanner
VirtualColumn returns a sql.Scanner that will scan the given column as a virtual column in the given record.
Types ¶
type AfterDeleter ¶
type AfterDeleter interface { // AfterDelete will do some operations after being deleted. If an error is // returned, it will cause the delete to be rolled back. AfterDelete() error }
AfterDeleter will do some operations after being deleted.
type AfterInserter ¶
type AfterInserter interface { // AfterInsert will do some operations after being inserted. If an error is // returned, it will cause the insert to be rolled back. AfterInsert() error }
AfterInserter will do some operations after being inserted.
type AfterSaver ¶
type AfterSaver interface { // AfterSave will do some operations after being inserted or updated. If an // error is returned, it will cause the insert or update to be rolled back. AfterSave() error }
AfterSaver will do some operations after being inserted or updated.
type AfterUpdater ¶
type AfterUpdater interface { // AfterUpdate will do some operations after being updated. If an error is // returned, it will cause the update to be rolled back. AfterUpdate() error }
AfterUpdater will do some operations after being updated.
type ArraySchemaField ¶
type ArraySchemaField interface { SchemaField // contains filtered or unexported methods }
ArraySchemaField is an interface that defines if a field is a JSON array.
type BaseQuery ¶
type BaseQuery struct {
// contains filtered or unexported fields
}
BaseQuery is a generic query builder to build queries programmatically.
func NewBaseQuery ¶
NewBaseQuery creates a new BaseQuery for querying the table of the given schema.
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) Copy ¶
Copy returns an identical copy of the query. BaseQuery is mutable, that is why this method is provided.
func (*BaseQuery) GetBatchSize ¶
GetBatchSize returns the number of rows retrieved per batch while retrieving 1:N relationships.
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) 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.
type BaseResultSet ¶
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 ¶
func (rs *BaseResultSet) Get(schema Schema) (Record, error)
Get returns the next record in the schema.
func (*BaseResultSet) RawScan ¶
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 ¶
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, autoIncr bool, 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 ¶
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 ¶
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 ¶
func NewBatchingResultSet(runner *batchQueryRunner) *BatchingResultSet
NewBatchingResultSet returns a new result set that performs batching underneath.
func (*BatchingResultSet) Close ¶
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 ¶
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 ¶
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 ¶
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 BeforeDeleter ¶
type BeforeDeleter interface { // BeforeDelete will do some operations before being deleted. If an error is // returned, it will prevent the delete from happening. BeforeDelete() error }
BeforeDeleter will do some operations before being deleted.
type BeforeInserter ¶
type BeforeInserter interface { // BeforeInsert will do some operations before being inserted. If an error is // returned, it will prevent the insert from happening. BeforeInsert() error }
BeforeInserter will do some operations before being inserted.
type BeforeSaver ¶
type BeforeSaver interface { // BeforeSave will do some operations before being updated or inserted. If an // error is returned, it will prevent the update or insert from happening. BeforeSave() error }
BeforeSaver will do some operations before being updated or inserted.
type BeforeUpdater ¶
type BeforeUpdater interface { // BeforeUpdate will do some operations before being updated. If an error is // returned, it will prevent the update from happening. BeforeUpdate() error }
BeforeUpdater will do some operations before being updated.
type ColumnAddresser ¶
type ColumnAddresser interface { // ColumnAddress returns the pointer to the column value of the given // column name, or an error if it does not exist in the model. ColumnAddress(string) (interface{}, error) }
ColumnAddresser provides the pointer addresses of columns.
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 represents a column name with its order.
func Desc ¶
func Desc(col SchemaField) ColumnOrder
Desc returns a column ordered by descending order.
type Condition ¶
Condition represents a condition of filtering in a query.
func ArrayContainedBy ¶
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 ¶
func ArrayContains(col SchemaField, values ...interface{}) Condition
ArrayContains returns a condition that will be true when `col` contains all the given values.
func ArrayEq ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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, value interface{}) Condition
Gt returns a condition that will be true when `col` is greater than `value`.
func GtOrEq ¶
func GtOrEq(col SchemaField, value 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 JSONContainedBy ¶
func JSONContainedBy(col SchemaField, elem interface{}) Condition
JSONContainedBy returns a condition that will be true when `col` is contained by the given element converted to JSON.
func JSONContains ¶
func JSONContains(col SchemaField, elem interface{}) Condition
JSONContains returns a condition that will be true when `col` contains the given element converted to JSON.
func JSONContainsAllKeys ¶
func JSONContainsAllKeys(col SchemaField, keys ...string) Condition
JSONContainsAllKeys returns a condition that will be true when `col` contains all the given keys. Will also match elements if the column is an array.
func JSONContainsAny ¶
func JSONContainsAny(col SchemaField, elems ...interface{}) Condition
JSONContainsAny returns a condition that will be true when `col` contains any of the given elements converted to json. Giving no elements will cause an error to be returned when the condition is evaluated.
func JSONContainsAnyKey ¶
func JSONContainsAnyKey(col SchemaField, keys ...string) Condition
JSONContainsAnyKey returns a condition that will be true when `col` contains any of the given keys. Will also match elements if the column is an array.
func JSONIsArray ¶
func JSONIsArray(col SchemaField) Condition
JSONIsArray returns a condition that will be true when `col` is a JSON array.
func JSONIsObject ¶
func JSONIsObject(col SchemaField) Condition
JSONIsObject returns a condition that will be true when `col` is a JSON object.
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, value interface{}) Condition
LtOrEq returns a condition that will be true when `col` is lower than `value` or equal.
func MatchRegex ¶ added in v1.1.0
func MatchRegex(col SchemaField, pattern string) Condition
MatchRegex returns a condition that will be true when `col` matches the given POSIX regex. Match is case insensitive.
func MatchRegexCase ¶ added in v1.1.0
func MatchRegexCase(col SchemaField, pattern string) Condition
MatchRegexCase returns a condition that will be true when `col` matches the given POSIX regex. Match is case sensitive.
func Neq ¶
func Neq(col SchemaField, value interface{}) Condition
Neq returns a condition that will be true when `col` is not `value`.
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 NotMatchRegex ¶ added in v1.1.0
func NotMatchRegex(col SchemaField, pattern string) Condition
NotMatchRegex returns a condition that will be true when `col` does not match the given POSIX regex. Match is case insensitive.
func NotMatchRegexCase ¶ added in v1.1.0
func NotMatchRegexCase(col SchemaField, pattern string) Condition
NotMatchRegexCase returns a condition that will be true when `col` does not match the given POSIX regex. Match is case sensitive.
type ForeignKey ¶
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 ¶
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 GenericStorer ¶ added in v1.1.0
type GenericStorer interface { // GenericStore returns the generic store in this type. GenericStore() *Store // SetGenericStore sets the generic store for this type. SetGenericStore(*Store) }
GenericStorer is a type that contains a generic store and has methods to retrieve it and set it.
type Identifiable ¶
type Identifiable interface { // GetID returns the ID. GetID() Identifier }
Identifiable must be implemented by those values that can be identified by an ID.
type Identifier ¶
type Identifier interface { sql.Scanner driver.Valuer // Equals reports whether the identifier and the given one are equal. Equals(Identifier) bool // IsEmpty returns whether the ID is empty or not. IsEmpty() bool // Raw returns the internal value of the identifier. Raw() interface{} }
Identifier is a type used to identify a model.
type JSONKeyType ¶
type JSONKeyType string
JSONKeyType is the type of an object key in a JSON.
const ( // JSONAny represents a type that can't be casted. JSONAny JSONKeyType = "" // JSONText is a text json type. JSONText JSONKeyType = "text" // JSONInt is a numeric json type. JSONInt JSONKeyType = "bigint" // JSONFloat is a floating point json type. JSONFloat JSONKeyType = "decimal" // JSONBool is a boolean json type. JSONBool JSONKeyType = "bool" )
type JSONSchemaArray ¶
type JSONSchemaArray struct {
// contains filtered or unexported fields
}
JSONSchemaArray is a SchemaField that represents a JSON array.
func NewJSONSchemaArray ¶
func NewJSONSchemaArray(field string, paths ...string) *JSONSchemaArray
NewJSONSchemaArray creates a new SchemaField that is a json array.
func (*JSONSchemaArray) QualifiedName ¶
func (f *JSONSchemaArray) QualifiedName(schema Schema) string
func (*JSONSchemaArray) String ¶
func (f *JSONSchemaArray) String() string
type JSONSchemaKey ¶
type JSONSchemaKey struct {
// contains filtered or unexported fields
}
JSONSchemaKey is a SchemaField that represents a key in a JSON object.
func NewJSONSchemaKey ¶
func NewJSONSchemaKey(typ JSONKeyType, field string, paths ...string) *JSONSchemaKey
NewJSONSchemaKey creates a new SchemaField that is a json key.
func (*JSONSchemaKey) QualifiedName ¶
func (f *JSONSchemaKey) QualifiedName(schema Schema) string
func (*JSONSchemaKey) String ¶
func (f *JSONSchemaKey) String() string
type Model ¶
type Model struct {
// contains filtered or unexported fields
}
Model contains all the basic fields that make something a model, that is, the ID and some internal data used by kallax. To make a struct a model, it only needs to have Model embedded.
type MyModel struct { kallax.Model Foo string }
Custom name for the table can be specified using the struct tag `table` when embedding the Model.
type MyModel struct { kallax.Model `table:"custom_name"` }
Otherwise, the default name of the table is the name of the model converted to lower snake case. E.g: MyModel => my_model. No pluralization is done right now, but might be done in the future, so please, set the name of the tables yourself.
func NewModel ¶
func NewModel() Model
NewModel creates a new Model that is writable and not persisted.
func (*Model) AddVirtualColumn ¶
func (m *Model) AddVirtualColumn(name string, v Identifier)
AddVirtualColumn adds a new virtual column with the given name and value. This method is only intended for internal use. It is only exposed for technical reasons.
func (*Model) ClearVirtualColumns ¶
func (m *Model) ClearVirtualColumns()
ClearVirtualColumns clears all the previous virtual columns. This method is only intended for internal use. It is only exposed for technical reasons.
func (*Model) IsPersisted ¶
IsPersisted returns whether the Model has already been persisted to the database or not.
func (*Model) IsWritable ¶
IsWritable returns whether this Model can be saved into the database. For example, a model with partially retrieved data is not writable, so it is not saved by accident and the data is corrupted. For example, if you select only 2 columns out of all the ones the table has, it will not be writable.
func (*Model) VirtualColumn ¶
func (m *Model) VirtualColumn(name string) Identifier
VirtualColumn returns the value of the virtual column with the given column name. This method is only intended for internal use. It is only exposed for technical reasons.
type NumericID ¶
type NumericID int64
NumericID is a wrapper for int64 that implements the Identifier interface. You don't need to actually use this as a type in your model. They will be automatically converted to and from in the generated code.
func (NumericID) Equals ¶
func (id NumericID) Equals(other Identifier) bool
Equals reports whether the ID and the given one are equals.
func (NumericID) IsEmpty ¶
IsEmpty returns whether the ID is empty or not. An empty ID means it has not been set yet.
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 is the common interface all queries must satisfy. The basic abilities of a query are compiling themselves to something executable and return some query settings.
type Record ¶
type Record interface { Identifiable Persistable Writable Relationable ColumnAddresser Valuer VirtualColumnContainer }
Record is something that can be stored as a row in the database.
type RecordConstructor ¶
type RecordConstructor func() Record
RecordConstructor is a function that creates a record.
type RecordWithSchema ¶
RecordWithSchema is a structure that contains both a record and its schema. Only for internal purposes.
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 ¶
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 ScalarCond ¶
type ScalarCond func(col SchemaField, value interface{}) Condition
ScalarCond returns a kallax.Condition that compares a property with the passed values, considering its scalar values (eq, gt, gte, lt, lte, neq)
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 // contains filtered or unexported methods }
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 AtJSONPath ¶
func AtJSONPath(field SchemaField, typ JSONKeyType, path ...string) SchemaField
AtJSONPath returns the schema field to query an arbitrary JSON element at the given path.
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 (*Store) Delete ¶
Delete removes the record from the table. A non-new record with non-empty ID is required.
func (*Store) Insert ¶
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 ¶
MustCount returns the number of rows selected by the given query. It panics if the query fails.
func (*Store) MustFind ¶
MustFind performs a query and returns a result set with the results. It panics if the query fails.
func (*Store) RawExec ¶
RawExec executes a raw SQL query with the given parameters and returns the number of affected rows.
func (*Store) RawQuery ¶
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 ¶
Reload refreshes the record with the data in the database and makes the record writable.
func (*Store) Transaction ¶
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. If a transaction is already opened in this store, instead of opening a new one, the other will be reused.
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 }
Timestamps contains the dates of the last time the model was created or deleted. Because this is such a common functionality in models, it is provided by default by the library. It is intended to be embedded in the model.
type MyModel struct { kallax.Model kallax.Timestamps Foo string }
func (*Timestamps) BeforeSave ¶
func (t *Timestamps) BeforeSave() error
BeforeSave updates the last time the model was updated every single time the model is saved, and the last time the model was created only if the model has no date of creation yet.
type ULID ¶
ULID is an ID type provided by kallax that is a lexically sortable UUID. The internal representation is an ULID (https://github.com/oklog/ulid). It already implements sql.Scanner and driver.Valuer, so it's perfectly safe for database usage.
func NewULIDFromText ¶ added in v1.0.4
NewULIDFromText creates a new ULID from its string representation. Will return an error if the text is not a valid ULID.
func (ULID) Equals ¶
func (id ULID) Equals(other Identifier) bool
Equals reports whether the ID and the given one are equals.
func (ULID) IsEmpty ¶
IsEmpty returns whether the ID is empty or not. An empty ID means it has not been set yet.
func (ULID) MarshalText ¶ added in v1.0.3
func (*ULID) UnmarshalText ¶ added in v1.0.2
UnmarshalText implements the encoding.TextUnmarshaler interface. Following formats are supported: "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" Implements the exact same code as the UUID UnmarshalText removing the version check.
type UUID ¶
UUID is a wrapper type for uuid.UUID that implements the Identifier interface. You don't need to actually use this as a type in your model. They will be automatically converted to and from in the generated code.
func (UUID) Equals ¶
func (id UUID) Equals(other Identifier) bool
Equals reports whether the ID and the given one are equals.
func (UUID) IsEmpty ¶
IsEmpty returns whether the ID is empty or not. An empty ID means it has not been set yet.
type Valuer ¶
type Valuer interface { // Value returns the value of the given column, or an error if it does not // exist in the model. Value(string) (interface{}, error) }
Valuer provides the values for columns.
type VirtualColumnContainer ¶
type VirtualColumnContainer interface { // ClearVirtualColumns removes all virtual columns. ClearVirtualColumns() // AddVirtualColumn adds a new virtual column with the given name and value AddVirtualColumn(string, Identifier) // VirtualColumn returns the virtual column with the given column name. VirtualColumn(string) Identifier }
VirtualColumnContainer contains a collection of virtual columns and manages them.
type Writable ¶
type Writable interface { // IsWritable returns whether this Model can be saved into the database. 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.
Source Files ¶
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. |
Package generator implements the processor of source code and generator of kallax models based on Go source code.
|
Package generator implements the processor of source code and generator of kallax models based on Go source code. |
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. |
Package types provides implementation of some wrapper SQL types.
|
Package types provides implementation of some wrapper SQL types. |