Documentation ¶
Overview ¶
Package makroud provides a high level SQL Connector. At the moment, only PostgreSQL is supported.
It's an advanced mapper and/or a lightweight ORM that relies on reflection.
For further informations, you can read this documentation: https://github.com/ulule/makroud/blob/master/README.md
Or you can discover makroud with these examples. First, you have to create a driver:
driver, err := makroud.New( makroud.Host(cfg.Host), makroud.Port(cfg.Port), makroud.User(cfg.User), makroud.Password(cfg.Password), makroud.Database(cfg.Name), makroud.SSLMode(cfg.SSLMode), makroud.MaxOpenConnections(cfg.MaxOpenConnections), makroud.MaxIdleConnections(cfg.MaxIdleConnections), )
Then, define a model:
type User struct { ID string `makroud:"column:id,pk:ulid"` Email string `makroud:"column:email"` Password string `makroud:"column:password"` Country string `makroud:"column:country"` Locale string `makroud:"column:locale"` }
Execute an insert:
user := &User{ Email: "gilles@ulule.com", Password: "019a7bdf56b9f48e18096d62b21f", Country: "FR", Locale: "fr", } err := makroud.Save(ctx, driver, user)
Or an update:
user.Email = "gilles.fabio@ulule.com" err := makroud.Save(ctx, driver, user)
Or execute a simple query without model:
import "github.com/ulule/loukoum/v3" list := []string{} stmt := loukoum.Update("users"). Set( loukoum.Pair("updated_at", loukoum.Raw("NOW()")), loukoum.Pair("status", status), ). Where(loukoum.Condition("group_id").Equal(gid)). Returning("id") err := makroud.Exec(ctx, driver, stmt, &list)
Index ¶
- Constants
- Variables
- func Archive(ctx context.Context, driver Driver, model Model) error
- func Count(ctx context.Context, driver Driver, stmt builder.Builder) (int64, error)
- func DebugField(field Field) string
- func DebugTag(tag Tag) string
- func DebugTagProperty(prop TagProperty) string
- func DebugTags(tags Tags) string
- func Delete(ctx context.Context, driver Driver, model Model) error
- func Exec(ctx context.Context, driver Driver, stmt builder.Builder, dest ...interface{}) error
- func FloatCount(ctx context.Context, driver Driver, stmt builder.Builder) (float64, error)
- func GenerateULID(driver Driver) string
- func GenerateUUIDV1(driver Driver) string
- func GenerateUUIDV4(driver Driver) string
- func IsErrNoRows(err error) bool
- func Log(ctx context.Context, driver Driver, query Query, duration time.Duration)
- func Preload(ctx context.Context, driver Driver, out interface{}, ...) error
- func RawExec(ctx context.Context, driver Driver, query string, dest ...interface{}) error
- func RawExecArgs(ctx context.Context, driver Driver, query string, args []interface{}, ...) error
- func Retry(handler func(Driver) error, drivers ...Driver) (err error)
- func Save(ctx context.Context, driver Driver, model Model) error
- func Select(ctx context.Context, driver Driver, dest interface{}, args ...interface{}) error
- func Transaction(ctx context.Context, driver Driver, opts *TxOptions, ...) error
- type AssociationType
- type Client
- func (c *Client) Begin(ctx context.Context, opts ...*TxOptions) (Driver, error)
- func (c *Client) Close() error
- func (c *Client) Commit() error
- func (c *Client) DriverName() string
- func (c *Client) Entropy() io.Reader
- func (c *Client) Exec(ctx context.Context, query string, args ...interface{}) error
- func (c *Client) GetCache() *DriverCache
- func (c *Client) HasCache() bool
- func (c *Client) HasLogger() bool
- func (c *Client) HasObserver() bool
- func (c *Client) Logger() Logger
- func (c *Client) MustExec(ctx context.Context, query string, args ...interface{})
- func (c *Client) MustQuery(ctx context.Context, query string, args ...interface{}) Rows
- func (c *Client) Observer() Observer
- func (c *Client) Ping() error
- func (c *Client) PingContext(ctx context.Context) error
- func (c *Client) Prepare(ctx context.Context, query string) (Statement, error)
- func (c *Client) Query(ctx context.Context, query string, args ...interface{}) (Rows, error)
- func (c *Client) Rollback() error
- func (c *Client) SetCache(cache *DriverCache)
- type ClientOptions
- type Columns
- type Driver
- type DriverCache
- type FKType
- type Field
- func (field Field) ColumnName() string
- func (field Field) ColumnPath() string
- func (field Field) FieldIndex() []int
- func (field Field) FieldName() string
- func (field Field) ForeignKey() string
- func (field Field) HasDefault() bool
- func (field Field) HasRelation() bool
- func (field Field) HasULID() bool
- func (field Field) HasUUIDV1() bool
- func (field Field) HasUUIDV4() bool
- func (field Field) IsAssociation() bool
- func (field Field) IsAssociationType(kind AssociationType) bool
- func (field Field) IsCreatedKey() bool
- func (field Field) IsDeletedKey() bool
- func (field Field) IsExcluded() bool
- func (field Field) IsForeignKey() bool
- func (field Field) IsPrimaryKey() bool
- func (field Field) IsUpdatedKey() bool
- func (field Field) ModelName() string
- func (field Field) RelationName() string
- func (field Field) String() string
- func (field Field) TableName() string
- func (field Field) Type() reflect.Type
- type ForeignKey
- type Logger
- type Mapper
- type Model
- type ModelOpts
- type Node
- type Observer
- type Option
- func ApplicationName(name string) Option
- func Cache(enabled bool) Option
- func ConnectTimeout(timeout int) Option
- func Database(dbname string) Option
- func DisableSSL() Option
- func EnableSSL() Option
- func EnableSavepoint() Option
- func Host(host string) Option
- func MaxIdleConnections(maximum int) Option
- func MaxOpenConnections(maximum int) Option
- func Password(password string) Option
- func Port(port int) Option
- func SSLMode(mode string) Option
- func Timezone(timezone string) Option
- func User(user string) Option
- func WithEntropy(entropy io.Reader) Option
- func WithLogger(logger Logger) Option
- func WithNode(node Node) Option
- func WithObserver(observer Observer) Option
- type PKType
- type PreloadHandler
- type PrimaryKey
- type PrimaryKeyDefault
- type Query
- type Reference
- type ReferenceObject
- func (object ReferenceObject) ColumnName() string
- func (object ReferenceObject) ColumnPath() string
- func (object ReferenceObject) Columns() []string
- func (object ReferenceObject) DeletedKeyName() string
- func (object ReferenceObject) DeletedKeyPath() string
- func (object ReferenceObject) FieldName() string
- func (object ReferenceObject) ForeignKeyType() FKType
- func (object ReferenceObject) HasDeletedKey() bool
- func (object ReferenceObject) IsForeignKey() bool
- func (object ReferenceObject) IsPrimaryKey() bool
- func (object ReferenceObject) Model() Model
- func (object ReferenceObject) ModelName() string
- func (object ReferenceObject) PrimaryKeyType() PKType
- func (object ReferenceObject) Schema() *Schema
- func (object ReferenceObject) TableName() string
- type Row
- type Rows
- type Schema
- func (schema Schema) ColumnPaths() Columns
- func (schema Schema) Columns() Columns
- func (schema Schema) CreatedKeyName() string
- func (schema Schema) CreatedKeyPath() string
- func (schema Schema) DeletedKeyName() string
- func (schema Schema) DeletedKeyPath() string
- func (schema Schema) HasColumn(column string) bool
- func (schema Schema) HasCreatedKey() bool
- func (schema Schema) HasDeletedKey() bool
- func (schema Schema) HasUpdatedKey() bool
- func (schema Schema) Model() Model
- func (schema Schema) ModelName() string
- func (schema Schema) PrimaryKey() PrimaryKey
- func (schema Schema) PrimaryKeyName() string
- func (schema Schema) PrimaryKeyPath() string
- func (schema Schema) ScanRow(row Row, model Model) error
- func (schema Schema) ScanRows(rows Rows, model Model) error
- func (schema Schema) TableName() string
- func (schema Schema) UpdatedKeyName() string
- func (schema Schema) UpdatedKeyPath() string
- type Schemaless
- func (schema Schemaless) Columns() Columns
- func (schema Schemaless) HasColumn(column string) bool
- func (schema Schemaless) Key(column string) (SchemalessKey, bool)
- func (schema Schemaless) Name() string
- func (schema Schemaless) ScanRow(row Row, val interface{}) error
- func (schema Schemaless) ScanRows(rows Rows, val interface{}) error
- func (schema Schemaless) Type() reflect.Type
- type SchemalessKey
- type Selector
- func (selector *Selector) Close() error
- func (selector *Selector) Ping() error
- func (selector *Selector) RetryAliases(handler func(Driver) error, aliases ...string) error
- func (selector *Selector) RetryMaster(handler func(Driver) error) error
- func (selector *Selector) Using(alias string) (Driver, error)
- type SelectorConfigurations
- type Statement
- type Tag
- type TagProperty
- type Tags
- type TagsAnalyzerOption
- type TagsAnalyzerOptions
- type TxOptions
Constants ¶
const ( // FKUnknownType is an unknown foreign key. FKUnknownType = FKType(iota) // FKIntegerType uses an integer as foreign key. FKIntegerType // ForeignKeyString uses a string as foreign key. FKStringType // FKOptionalIntegerType uses an optional integer as foreign key. FKOptionalIntegerType // FKOptionalStringType uses an optional string as foreign key. FKOptionalStringType )
Foreign key types.
const ( AssociationTypeUndefined = AssociationType(iota) AssociationTypeOne AssociationTypeMany )
Association types.
const ( // PKUnknownType is an unknown primary key. PKUnknownType = PKType(iota) // PKIntegerType uses an integer as primary key. PKIntegerType // PrimaryKeyString uses a string as primary key. PKStringType )
Primary key types.
const ( // PrimaryKeyDBDefault uses internal db mechanism to define primary key value. PrimaryKeyDBDefault = PrimaryKeyDefault(iota) // PrimaryKeyULIDDefault uses a ulid generator to define primary key value. PrimaryKeyULIDDefault // PrimaryKeyUUIDV1Default uses a uuid v1 generator to define primary key value. PrimaryKeyUUIDV1Default // PrimaryKeyUUIDV4Default uses a uuid v4 generator to define primary key value. PrimaryKeyUUIDV4Default )
PrimaryKey default types.
const ( // TagName defines makroud tag namespace. TagName = "makroud" // TagNameShort defines makroud tag namespace in short version. TagNameShort = "mk" // TagNameAlt defines sqlx tag namespace for backward compatibility. TagNameAlt = "db" )
const ( TagKeyIgnored = "-" TagKeyDefault = "default" TagKeyColumn = "column" TagKeyColumnShort = "col" TagKeyForeignKey = "fk" TagKeyPrimaryKey = "pk" TagKeyRelation = "relation" TagKeyRelationShort = "rel" TagKeyULID = "ulid" TagKeyUUIDV1 = "uuid-v1" TagKeyUUIDV4 = "uuid-v4" )
Tag modifiers on Model.
const ( LevelDefault = sql.LevelDefault LevelReadUncommitted = sql.LevelReadUncommitted LevelReadCommitted = sql.LevelReadCommitted LevelRepeatableRead = sql.LevelRepeatableRead LevelSerializable = sql.LevelSerializable )
List of supported isolation level for a postgres transaction.
const ClientDriver = "postgres"
ClientDriver defines the driver name used in makroud.
const DefaultSelector = MasterSelector
DefaultSelector defines the default selector alias.
const MasterSelector = "master"
MasterSelector defines the master alias.
const SlaveSelector = "slave"
SlaveSelector defines the slave alias.
Variables ¶
var ( // ErrNoRows is returned when query doesn't return a row. ErrNoRows = fmt.Errorf("no rows in result set") // ErrInvalidDriver is returned when given driver is undefined. ErrInvalidDriver = fmt.Errorf("a makroud driver is required") // ErrPointerRequired is returned when given value is not a pointer. ErrPointerRequired = fmt.Errorf("a pointer is required") // ErrPointerOrSliceRequired is returned when given value is not a pointer or a slice. ErrPointerOrSliceRequired = fmt.Errorf("a pointer or a slice is required") // ErrUnknownPreloadRule is returned when given rule is unknown. ErrUnknownPreloadRule = fmt.Errorf("unknown rule") // ErrStructRequired is returned when given value is not a struct. ErrStructRequired = fmt.Errorf("a struct is required") // ErrModelRequired is returned when given value is not a model. ErrModelRequired = fmt.Errorf("a model is required") // ErrSchemaColumnRequired is returned when we cannot find a column in current schema. ErrSchemaColumnRequired = fmt.Errorf("cannot find column in schema") // ErrSchemaCreatedKey is returned when we cannot find a created key in given schema. ErrSchemaCreatedKey = fmt.Errorf("cannot find created key in schema") // ErrSchemaUpdatedKey is returned when we cannot find a updated key in given schema. ErrSchemaUpdatedKey = fmt.Errorf("cannot find updated key in schema") // ErrSchemaDeletedKey is returned when we cannot find a deleted key in given schema. ErrSchemaDeletedKey = fmt.Errorf("cannot find deleted key in schema") // ErrPreloadInvalidSchema is returned when preload detect an invalid schema from given model. ErrPreloadInvalidSchema = fmt.Errorf("given model has an invalid schema") // ErrPreloadInvalidModel is returned when preload detect an invalid model. ErrPreloadInvalidModel = fmt.Errorf("given model is invalid") // ErrPreloadInvalidPath is returned when preload detect an invalid path. ErrPreloadInvalidPath = fmt.Errorf("given path is invalid") // ErrSelectorNotFoundConnection is returned when the required connection does not exists in selector connections. ErrSelectorNotFoundConnection = fmt.Errorf("cannot find connection in selector") // ErrSelectorMissingRetryConnection is returned when the retry mechanism has no connection available from selector. ErrSelectorMissingRetryConnection = fmt.Errorf("cannot find a healthy connection in selector") // ErrSliceOfScalarMultipleColumns is returned when a query return multiple columns for a slice of scalar. ErrSliceOfScalarMultipleColumns = fmt.Errorf("slice of scalar with multiple columns") // ErrCommitNotInTransaction is returned when using commit outside of a transaction. ErrCommitNotInTransaction = fmt.Errorf("cannot commit outside of a transaction") )
Makroud general errors.
var TagsKeyMapper = map[string]string{ TagKeyColumnShort: TagKeyColumn, TagKeyRelationShort: TagKeyRelation, }
TagsKeyMapper is a mapper that convert tag key to another key (aliasing).
var TagsList = []string{ TagName, TagNameShort, TagNameAlt, }
TagsList is a list of supported tags, this include sqlx and makroud one.
var TagsNameMapper = map[string]string{ TagNameAlt: TagKeyColumn, }
TagsNameMapper is a mapper that convert supported tag name to makroud one (migrate).
Functions ¶
func DebugField ¶
DebugField returns a human readable version of given instance.
func DebugTagProperty ¶
func DebugTagProperty(prop TagProperty) string
DebugTagProperty returns a human readable version of given instance.
func Exec ¶
Exec will execute given query from a Loukoum builder. If an object is given, it will mutate it to match the row values.
func FloatCount ¶
FloatCount will execute given query to return a number (in float) from a aggregate function.
func GenerateUUIDV1 ¶
GenerateUUIDV1 generates a new uuid v1.
func GenerateUUIDV4 ¶
GenerateUUIDV4 generates a new uuid v4.
func IsErrNoRows ¶
IsErrNoRows returns if given error is a "no rows" error.
func Preload ¶
func Preload(ctx context.Context, driver Driver, out interface{}, handlers ...PreloadHandler) error
Preload preloads related fields.
func RawExec ¶
RawExec will execute given query. If an object is given, it will mutate it to match the row values.
func RawExecArgs ¶ added in v0.6.0
func RawExecArgs(ctx context.Context, driver Driver, query string, args []interface{}, dest ...interface{}) error
RawExecArgs will execute given query with given arguments. If an object is given, it will mutate it to match the row values.
Types ¶
type AssociationType ¶
type AssociationType uint8
AssociationType define an association type.
func (AssociationType) String ¶
func (e AssociationType) String() string
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a wrapper that can interact with the database, it's an implementation of Driver.
func NewWithOptions ¶
func NewWithOptions(options *ClientOptions) (*Client, error)
NewWithOptions returns a new Client instance.
func (*Client) Begin ¶
Begin starts a new transaction.
The provided context is used until the transaction is committed or rolled back. If the context is canceled, the driver will roll back the transaction. Commit will return an error if the context provided to Begin is canceled.
The provided TxOptions is optional. If a non-default isolation level is used that the driver doesn't support, an error will be returned. If no option is provided, the default isolation level of the driver will be used.
func (*Client) DriverName ¶
DriverName returns the driver name used by this driver.
func (*Client) Entropy ¶ added in v0.8.0
Entropy returns an entropy source, used for primary key generation (if required).
WARNING: Please, do not use this method unless you know what you are doing.
func (*Client) GetCache ¶ added in v0.8.0
func (c *Client) GetCache() *DriverCache
GetCache returns the driver internal cache.
WARNING: Please, do not use this method unless you know what you are doing: YOU COULD BREAK YOUR DRIVER.
func (*Client) HasObserver ¶ added in v0.8.0
HasObserver returns if the driver has an observer.
func (*Client) Logger ¶ added in v0.8.0
Logger returns the driver logger.
WARNING: Please, do not use this method unless you know what you are doing.
func (*Client) MustExec ¶
MustExec executes a statement using given arguments. If an error has occurred, it panics.
func (*Client) MustQuery ¶
MustQuery executes a statement that returns rows using given arguments. If an error has occurred, it panics.
func (*Client) Observer ¶ added in v0.8.0
Observer returns the driver observer.
WARNING: Please, do not use this method unless you know what you are doing.
func (*Client) PingContext ¶ added in v0.7.0
PingContext verifies that the underlying connection is healthy.
func (*Client) Prepare ¶
Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement.
func (*Client) SetCache ¶ added in v0.8.0
func (c *Client) SetCache(cache *DriverCache)
SetCache replace the driver internal cache by the given one.
WARNING: Please, do not use this method unless you know what you are doing: YOU COULD BREAK YOUR DRIVER.
type ClientOptions ¶
type ClientOptions struct { Port int Host string User string Password string Database string SSLMode string Timezone string MaxOpenConnections int MaxIdleConnections int WithCache bool SavepointEnabled bool ApplicationName string ConnectTimeout int Logger Logger Observer Observer Entropy io.Reader Node Node }
ClientOptions configure a Client instance.
func NewClientOptions ¶
func NewClientOptions() *ClientOptions
NewClientOptions creates a new ClientOptions instance with default options.
func (ClientOptions) String ¶
func (e ClientOptions) String() string
type Columns ¶
type Columns []string
Columns is a list of table columns.
func GetColumns ¶
GetColumns returns a comma-separated string representation of a model's table columns.
type Driver ¶
type Driver interface { // Exec executes a statement using given arguments. Exec(ctx context.Context, query string, args ...interface{}) error // MustExec executes a statement using given arguments. // If an error has occurred, it panics. MustExec(ctx context.Context, query string, args ...interface{}) // Query executes a statement that returns rows using given arguments. Query(ctx context.Context, query string, args ...interface{}) (Rows, error) // MustQuery executes a statement that returns rows using given arguments. // If an error has occurred, it panics. MustQuery(ctx context.Context, query string, args ...interface{}) Rows // Prepare creates a prepared statement for later queries or executions. // Multiple queries or executions may be run concurrently from the returned statement. Prepare(ctx context.Context, query string) (Statement, error) // Close closes the underlying connection. Close() error // Ping verifies that the underlying connection is healthy. Ping() error // DriverName returns the driver name used by this driver. DriverName() string // Begin starts a new transaction. // // The provided context is used until the transaction is committed or rolled back. // If the context is canceled, the driver will roll back the transaction. // Commit will return an error if the context provided to Begin is canceled. // // The provided TxOptions is optional. // If a non-default isolation level is used that the driver doesn't support, an error will be returned. // If no option is provided, the default isolation level of the driver will be used. Begin(ctx context.Context, opts ...*TxOptions) (Driver, error) // Rollback rollbacks the associated transaction. Rollback() error // Commit commits the associated transaction. Commit() error // HasCache returns if current driver has an internal cache. HasCache() bool // GetCache returns the driver internal cache. // // WARNING: Please, do not use this method unless you know what you are doing: // YOU COULD BREAK YOUR DRIVER. GetCache() *DriverCache // SetCache replace the driver internal cache by the given one. // // WARNING: Please, do not use this method unless you know what you are doing: // YOU COULD BREAK YOUR DRIVER. SetCache(cache *DriverCache) // HasLogger returns if the driver has a logger. HasLogger() bool // Logger returns the driver logger. // // WARNING: Please, do not use this method unless you know what you are doing. Logger() Logger // HasObserver returns if the driver has an observer. HasObserver() bool // Observer returns the driver observer. // // WARNING: Please, do not use this method unless you know what you are doing. Observer() Observer // Entropy returns an entropy source, used for primary key generation (if required). // // WARNING: Please, do not use this method unless you know what you are doing. Entropy() io.Reader }
Driver is a high level abstraction of a database connection or a transaction.
type DriverCache ¶ added in v0.8.0
type DriverCache struct {
// contains filtered or unexported fields
}
DriverCache is driver cache used to store Schema and Schemaless information.
func NewDriverCache ¶ added in v0.8.0
func NewDriverCache() *DriverCache
NewDriverCache returns new schema cache instance.
func (*DriverCache) GetSchema ¶ added in v0.8.0
func (c *DriverCache) GetSchema(model Model) *Schema
GetSchema returns the schema associated to given model from cache. If it does not exists, it returns nil.
func (*DriverCache) GetSchemaless ¶ added in v0.8.0
func (c *DriverCache) GetSchemaless(value reflect.Type) *Schemaless
GetSchemaless returns the schemaless associated to type from cache. If it does not exists, it returns nil.
func (*DriverCache) SetSchema ¶ added in v0.8.0
func (c *DriverCache) SetSchema(schema *Schema)
SetSchema caches the given schema.
func (*DriverCache) SetSchemaless ¶ added in v0.8.0
func (c *DriverCache) SetSchemaless(schemaless *Schemaless)
SetSchemaless caches the given schemaless.
type FKType ¶
type FKType uint8
FKType define a foreign key type.
func (FKType) IsCompatible ¶
IsCompatible returns if given primary key is compatible with foreign key.
func (FKType) IsOptional ¶
IsOptional returns if foreign key has an optional type.
type Field ¶
type Field struct {
// contains filtered or unexported fields
}
Field defines the column name, field and options from model.
For example: If we have an User, we could have this primary key defined in User's schema.
Field { ModelName: User, TableName: users, FieldName: AvatarID, ColumnName: avatar_id, ColumnPath: users.avatar_id, }
func NewField ¶
func NewField(driver Driver, schema *Schema, model Model, name string, args ...ModelOpts) (*Field, error)
NewField creates a new field using given model and name.
func (Field) ColumnName ¶
ColumnName returns the field's column name.
func (Field) ColumnPath ¶
ColumnPath returns the field's full column path.
func (Field) FieldIndex ¶
FieldIndex define the struct field index used for this field.
func (Field) ForeignKey ¶
ForeignKey returns the field foreign key's table name.
func (Field) HasDefault ¶
HasDefault returns if the field has a default value and should be in returning statement.
func (Field) HasRelation ¶
HasRelation returns if the field has a explicit relation.
func (Field) IsAssociation ¶
IsAssociation returns if the field is an association.
func (Field) IsAssociationType ¶
func (field Field) IsAssociationType(kind AssociationType) bool
IsAssociationType returns if the field has given association type.
func (Field) IsCreatedKey ¶
IsCreatedKey returns if the field is a created key.
func (Field) IsDeletedKey ¶
IsDeletedKey returns if the field is a deleted key.
func (Field) IsExcluded ¶
IsExcluded returns if the field excluded. (anonymous, private...)
func (Field) IsForeignKey ¶
IsForeignKey returns if the field is a foreign key.
func (Field) IsPrimaryKey ¶
IsPrimaryKey returns if the field is a primary key.
func (Field) IsUpdatedKey ¶
IsUpdatedKey returns if the field is a updated key.
func (Field) RelationName ¶
RelationName returns the field relation name.
type ForeignKey ¶
type ForeignKey struct { Field // contains filtered or unexported fields }
ForeignKey is a composite object that define a foreign key for a model. This foreign key will be used later for Preload...
For example: If we have an User, we could have this primary key defined in User's schema.
ForeignKey { ModelName: User, TableName: users, FieldName: AvatarID, ColumnName: avatar_id, ColumnPath: users.avatar_id, Reference: avatars, Type: int64, }
func NewForeignKey ¶
func NewForeignKey(field *Field) (*ForeignKey, error)
NewForeignKey creates a foreign key from a field instance.
func (ForeignKey) Reference ¶
func (key ForeignKey) Reference() string
Reference returns the foreign key's table name.
type Logger ¶
type Logger interface { // Log push what query was executed and its duration. Log(ctx context.Context, query string, duration time.Duration) }
Logger is an observer that collect queries executed in makroud.
type Mapper ¶
type Mapper map[string]interface{}
Mapper will be used to mutate a Model with row values.
type Node ¶ added in v0.7.0
type Node interface { // Exec executes a statement using given arguments. The query shouldn't return rows. Exec(query string, args ...interface{}) (sql.Result, error) // ExecContext executes a statement using given arguments. The query shouldn't return rows. ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) // Query executes a statement that returns rows using given arguments. Query(query string, args ...interface{}) (*sql.Rows, error) // QueryContext executes a statement that returns rows using given arguments. QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) // QueryRow executes a statement that returns at most one row using given arguments. QueryRow(query string, args ...interface{}) *sql.Row // QueryRowContext executes a statement that returns at most one row using given arguments. QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row // Prepare creates a prepared statement for later queries or executions. // Multiple queries or executions may be run concurrently from the returned statement. Prepare(query string) (*sql.Stmt, error) // PrepareContext creates a prepared statement for later queries or executions. // Multiple queries or executions may be run concurrently from the returned statement. PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) // DriverName returns the driver name used by this connector. DriverName() string // Ping verifies that the underlying connection is healthy. Ping() error // PingContext verifies that the underlying connection is healthy. PingContext(ctx context.Context) error // Close closes the underlying connection. Close() error // SetConnMaxLifetime sets the maximum amount of time a connection may be reused. // Expired connections may be closed lazily before reuse. SetConnMaxLifetime(duration time.Duration) // SetMaxIdleConns sets the maximum number of connections in the idle connection pool. SetMaxIdleConns(number int) // SetMaxOpenConns sets the maximum number of open connections to the database. SetMaxOpenConns(number int) // EnableSavepoint activate PostgreSQL savepoints for nested transactions. EnableSavepoint(enabled bool) // Stats returns database statistics. Stats() sql.DBStats // Begin starts a new transaction. // // The default isolation level is dependent on the driver. Begin() (Node, error) // BeginTx begins a new transaction. // // The provided context is used until the transaction is committed or rolled back. // If the context is canceled, the sql package will roll back the transaction. // Commit will return an error if the context provided to BeginTx is canceled. // // The provided TxOptions is optional and may be nil if defaults should be used. // If a non-default isolation level is used that the driver doesn't support, an error will be returned. BeginTx(ctx context.Context, opts *sql.TxOptions) (Node, error) // Rollback rollbacks the associated transaction. Rollback() error // Commit commits the associated transaction. Commit() error // Tx returns the underlying transaction. Tx() *sql.Tx // DB returns the underlying connection. DB() *sql.DB }
Node is a components that allows to seamlessly create nested transactions and to avoid thinking about whether or not a function is called within a transaction. With this, you can easily create reusable and composable functions that can be called within or out of transactions and that can create transactions themselves.
type Observer ¶ added in v0.8.0
type Observer interface { // OnClose OnClose(err error, flags map[string]string) // OnRollback OnRollback(err error, flags map[string]string) }
Observer is a collector that gathers various runtime error.
type Option ¶
type Option func(*ClientOptions) error
Option is used to define Client configuration.
func ApplicationName ¶ added in v0.8.0
ApplicationName will configure the Client to use given application name.
func ConnectTimeout ¶ added in v0.8.0
ConnectTimeout will configure the Client to wait this maximum number of seconds to obtain a connection. Zero or not specified means wait indefinitely.
func DisableSSL ¶
func DisableSSL() Option
DisableSSL will configure the Client to disable SSL mode.
func EnableSavepoint ¶
func EnableSavepoint() Option
EnableSavepoint will enable the SAVEPOINT postgresql feature.
func MaxIdleConnections ¶
MaxIdleConnections will configure the Client to keep this maximum number of idle connections in the connection pool.
func MaxOpenConnections ¶
MaxOpenConnections will configure the Client to use this maximum number of open connections to the database.
func WithEntropy ¶ added in v0.8.0
WithEntropy will attach a custom entropy source on Client.
func WithNode ¶ added in v0.8.0
WithNode will attach a custom node connector on Client. If you use this option, EnableSavepoint, MaxOpenConnections and MaxIdleConnections will be ignored.
func WithObserver ¶ added in v0.8.0
WithObserver will attach an observer on Client.
type PKType ¶
type PKType uint8
PKType define a primary key type.
func (PKType) IsCompatible ¶
IsCompatible returns if given foreign key is compatible with primary key.
type PreloadHandler ¶
type PreloadHandler struct {
// contains filtered or unexported fields
}
PreloadHandler defines what resources should be preloaded.
func WithPreloadCallback ¶
func WithPreloadCallback(field string, callback func(query builder.Select) builder.Select) PreloadHandler
WithPreloadCallback returns a handler that preload a field with conditions.
func WithPreloadField ¶
func WithPreloadField(field string) PreloadHandler
WithPreloadField returns a handler that preload a field.
func WithUnscopedPreload ¶
func WithUnscopedPreload(handler PreloadHandler) PreloadHandler
WithUnscopedPreload unscopes given preload handler.
type PrimaryKey ¶
type PrimaryKey struct { Field // contains filtered or unexported fields }
PrimaryKey is a composite object that define a primary key for a model.
For example: If we have an User, we could have this primary key defined in User's schema.
PrimaryKey { ModelName: User, TableName: users, FieldName: ID, ColumnName: id, ColumnPath: users.id, Type: int64, Default: db, }
func NewPrimaryKey ¶
func NewPrimaryKey(field *Field) (*PrimaryKey, error)
NewPrimaryKey creates a primary key from a field instance.
func (PrimaryKey) Default ¶
func (key PrimaryKey) Default() PrimaryKeyDefault
Default returns the primary key's default mechanism.
func (PrimaryKey) Value ¶
func (key PrimaryKey) Value(model Model) (interface{}, error)
Value returns the primary key's value, or an error if undefined.
func (PrimaryKey) ValueOpt ¶
func (key PrimaryKey) ValueOpt(model Model) (interface{}, bool)
ValueOpt may returns the primary key's value, if defined.
type PrimaryKeyDefault ¶
type PrimaryKeyDefault uint8
PrimaryKeyDefault define how primary key value is generated.
func (PrimaryKeyDefault) String ¶
func (e PrimaryKeyDefault) String() string
type Query ¶
Query is a query generated by loukoum and makroud.
func NewRawQuery ¶
NewRawQuery creates a new Query instance from given query.
type Reference ¶
type Reference struct { Field // contains filtered or unexported fields }
Reference defines a model relationship.
func NewReference ¶
NewReference creates a reference from a field instance.
func (Reference) IsLocal ¶
IsLocal returns if reference is local from the model, or from another model (remote).
func (Reference) Local ¶
func (reference Reference) Local() ReferenceObject
Local returns the local model.
func (Reference) Remote ¶
func (reference Reference) Remote() ReferenceObject
Remote returns the remote model.
type ReferenceObject ¶
type ReferenceObject struct {
// contains filtered or unexported fields
}
ReferenceObject defines a model used by Reference.
func (ReferenceObject) ColumnName ¶
func (object ReferenceObject) ColumnName() string
ColumnName returns the column name of this reference.
func (ReferenceObject) ColumnPath ¶
func (object ReferenceObject) ColumnPath() string
ColumnPath returns the full column path of this reference.
func (ReferenceObject) Columns ¶
func (object ReferenceObject) Columns() []string
Columns returns this reference columns.
func (ReferenceObject) DeletedKeyName ¶
func (object ReferenceObject) DeletedKeyName() string
DeletedKeyName returns reference schema deleted key column name.
func (ReferenceObject) DeletedKeyPath ¶
func (object ReferenceObject) DeletedKeyPath() string
DeletedKeyPath returns reference schema deleted key column path.
func (ReferenceObject) FieldName ¶
func (object ReferenceObject) FieldName() string
FieldName returns the field name of this reference.
func (ReferenceObject) ForeignKeyType ¶
func (object ReferenceObject) ForeignKeyType() FKType
ForeignKeyType returns this reference foreign key type.
func (ReferenceObject) HasDeletedKey ¶
func (object ReferenceObject) HasDeletedKey() bool
HasDeletedKey returns if an deleted key is defined for this reference.
func (ReferenceObject) IsForeignKey ¶
func (object ReferenceObject) IsForeignKey() bool
IsForeignKey returns if this reference is a foreign key.
func (ReferenceObject) IsPrimaryKey ¶
func (object ReferenceObject) IsPrimaryKey() bool
IsPrimaryKey returns if this reference is a primary key.
func (ReferenceObject) Model ¶
func (object ReferenceObject) Model() Model
Model returns the reference model.
func (ReferenceObject) ModelName ¶
func (object ReferenceObject) ModelName() string
ModelName returns the model name of this reference.
func (ReferenceObject) PrimaryKeyType ¶
func (object ReferenceObject) PrimaryKeyType() PKType
PrimaryKeyType returns this reference primary key type.
func (ReferenceObject) Schema ¶
func (object ReferenceObject) Schema() *Schema
Schema returns the reference schema.
func (ReferenceObject) TableName ¶
func (object ReferenceObject) TableName() string
TableName returns the table name of this reference.
type Row ¶
type Row interface { // Write copies the columns in the current row into the given map. // Use this for debugging or analysis if the results might not be under your control. // Please do not use this as a primary interface! Write(dest map[string]interface{}) error // Columns returns the column names. Columns() ([]string, error) // Scan 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 in Rows. Scan(dest ...interface{}) error }
A Row is a simple row.
type Rows ¶
type Rows interface { // Next prepares the next result row for reading with the MapScan method. // It returns true on success, or false if there is no next result row or an error // happened while preparing it. // Err should be consulted to distinguish between the two cases. // Every call to MapScan, even the first one, must be preceded by a call to Next. Next() bool // Close closes the Rows, preventing further enumeration/iteration. // If Next is called and returns false and there are no further result sets, the Rows are closed automatically // and it will suffice to check the result of Err. Close() error // Err returns the error, if any, that was encountered during iteration. // Err may be called after an explicit or implicit Close. Err() error // Write copies the columns in the current row into the given map. // Use this for debugging or analysis if the results might not be under your control. // Please do not use this as a primary interface! Write(dest map[string]interface{}) error // Columns returns the column names. Columns() ([]string, error) // Scan 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 in Rows. Scan(dest ...interface{}) error }
A Rows is an iteratee of a list of records.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema is a model schema.
func GetSchema ¶
GetSchema returns the schema from given model. If the schema does not exists, it returns an error.
func (Schema) ColumnPaths ¶
ColumnPaths returns schema column with table prefix.
func (Schema) CreatedKeyName ¶
CreatedKeyName returns schema created key column name.
func (Schema) CreatedKeyPath ¶
CreatedKeyPath returns schema created key column path.
func (Schema) DeletedKeyName ¶
DeletedKeyName returns schema deleted key column name.
func (Schema) DeletedKeyPath ¶
DeletedKeyPath returns schema deleted key column path.
func (Schema) HasCreatedKey ¶
HasCreatedKey returns if a created key is defined for current schema.
func (Schema) HasDeletedKey ¶
HasDeletedKey returns if a deleted key is defined for current schema.
func (Schema) HasUpdatedKey ¶
HasUpdatedKey returns if an updated key is defined for current schema.
func (Schema) PrimaryKey ¶
func (schema Schema) PrimaryKey() PrimaryKey
PrimaryKey returns the schema primary key.
func (Schema) PrimaryKeyName ¶ added in v0.8.0
PrimaryKeyName returns schema primary key column name.
func (Schema) PrimaryKeyPath ¶ added in v0.8.0
PrimaryKeyPath returns schema primary key column path.
func (Schema) UpdatedKeyName ¶
UpdatedKeyName returns schema deleted key column name.
func (Schema) UpdatedKeyPath ¶
UpdatedKeyPath returns schema updated key column path.
type Schemaless ¶ added in v0.7.0
type Schemaless struct {
// contains filtered or unexported fields
}
Schemaless is a light version of schema for structs that are not models. It's a simple mapper from column name to struct field, without primary key, associations and so on...
func GetSchemaless ¶ added in v0.7.0
func GetSchemaless(driver Driver, value reflect.Type) (*Schemaless, error)
GetSchemaless returns the schema information from given type that are not models. If no information could be gathered, it returns an error.
func (Schemaless) Columns ¶ added in v0.7.0
func (schema Schemaless) Columns() Columns
Columns returns schema columns.
func (Schemaless) HasColumn ¶ added in v0.7.0
func (schema Schemaless) HasColumn(column string) bool
HasColumn returns if a schema has a column or not.
func (Schemaless) Key ¶ added in v0.7.0
func (schema Schemaless) Key(column string) (SchemalessKey, bool)
Key returns the SchemalessKey instance for given column.
func (Schemaless) Name ¶ added in v0.8.0
func (schema Schemaless) Name() string
Name returns the type's name of the schema.
func (Schemaless) ScanRow ¶ added in v0.7.0
func (schema Schemaless) ScanRow(row Row, val interface{}) error
ScanRow executes a scan from given row into schemaless instance.
func (Schemaless) ScanRows ¶ added in v0.7.0
func (schema Schemaless) ScanRows(rows Rows, val interface{}) error
ScanRows executes a scan from current row into schemaless instance.
func (Schemaless) Type ¶ added in v0.7.0
func (schema Schemaless) Type() reflect.Type
Type returns the reflect's type of the schema.
type SchemalessKey ¶ added in v0.7.0
type SchemalessKey struct {
// contains filtered or unexported fields
}
SchemalessKey is a light version of schema field. It contains the column name and the struct field information.
func (SchemalessKey) ColumnName ¶ added in v0.7.0
func (key SchemalessKey) ColumnName() string
ColumnName returns the column name for this schemaless key.
func (SchemalessKey) FieldIndex ¶ added in v0.7.0
func (key SchemalessKey) FieldIndex() []int
FieldIndex define the struct field index used for this schemaless key.
func (SchemalessKey) FieldName ¶ added in v0.7.0
func (key SchemalessKey) FieldName() string
FieldName define the struct field name used for this schemaless key.
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector contains a pool of drivers indexed by their name.
func NewSelector ¶
func NewSelector(configurations map[string]*ClientOptions) (*Selector, error)
NewSelector returns a new selector containing a pool of drivers with given configuration.
func NewSelectorWithDriver ¶
NewSelectorWithDriver returns a new selector containing the given connection.
func (*Selector) RetryAliases ¶
RetryAliases is an helper calling Retry with a list of aliases.
func (*Selector) RetryMaster ¶
RetryMaster is an helper calling RetryAliases with a slave then a master connection.
type SelectorConfigurations ¶
type SelectorConfigurations map[string]*ClientOptions
SelectorConfigurations define a list of configurations for a pool of drivers.
type Statement ¶
type Statement interface { // Close closes the statement. Close() error // Exec executes this named statement using the struct passed. Exec(ctx context.Context, args ...interface{}) error // QueryRow executes this named statement returning a single row. QueryRow(ctx context.Context, args ...interface{}) (Row, error) // QueryRows executes this named statement returning a list of rows. QueryRows(ctx context.Context, args ...interface{}) (Rows, error) }
A Statement from prepare.
type Tag ¶
type Tag struct {
// contains filtered or unexported fields
}
Tag is tag defined in a model.
func (Tag) Properties ¶
func (tag Tag) Properties() []TagProperty
Properties returns tag properties.
type TagProperty ¶
type TagProperty struct {
// contains filtered or unexported fields
}
TagProperty is a struct tag property.
func (TagProperty) String ¶
func (prop TagProperty) String() string
String returns a human readable version of current instance.
type Tags ¶
type Tags []Tag
Tags is a group of tag defined in a model.
func GetTags ¶
func GetTags(field reflect.StructField, args ...TagsAnalyzerOption) Tags
GetTags returns field tags.
func (*Tags) Set ¶
func (tags *Tags) Set(name string, property TagProperty)
Set sets the given tag into the slice.
type TagsAnalyzerOption ¶
type TagsAnalyzerOption func(*TagsAnalyzerOptions)
TagsAnalyzerOption is a functional option to configure TagsAnalyzerOptions.
func NewOnlyColumnTagsAnalyzerOption ¶ added in v0.7.0
func NewOnlyColumnTagsAnalyzerOption() TagsAnalyzerOption
NewOnlyColumnTagsAnalyzerOption return a new TagsAnalyzerOption instance to only analyzes tag as column. It removes the support of key:value system to analyzes only values. For instance, "mk:column_name" or "makroud:column_name"
type TagsAnalyzerOptions ¶
type TagsAnalyzerOptions struct { // Name defines the default tag name. Name string // Collector defines what tags should be analyzed. Collector []string // NameMapper defines how to convert a supported tag to the default one. NameMapper map[string]string // KeyMapper defines how to convert a tag key tag to another one (aliasing). KeyMapper map[string]string }
TagsAnalyzerOptions defines the tags analyzer behavior.