Documentation
¶
Overview ¶
Package pop wraps the absolutely amazing https://github.com/jmoiron/sqlx library. It cleans up some of the common patterns and workflows usually associated with dealing with databases in Go.
Pop makes it easy to do CRUD operations, run migrations, and build/execute queries. Is Pop an ORM? I'll leave that up to you, the reader, to decide.
Pop, by default, follows conventions that were defined by the ActiveRecord Ruby gem, http://www.rubyonrails.org. What does this mean?
Tables must have an "id" column and a corresponding "ID" field on the `struct` being used. If there is a timestamp column named "created_at", "CreatedAt" on the `struct`, it will be set with the current time when the record is created. If there is a timestamp column named "updated_at", "UpdatedAt" on the `struct`, it will be set with the current time when the record is updated.
Default databases are lowercase, underscored versions of the `struct` name. Examples: User{} is "users", FooBar{} is "foo_bars", etc...
Index ¶
- Constants
- Variables
- func AddLookupPaths(paths ...string) error
- func CanonicalDialect(synonym string) string
- func CreateDB(c *Connection) error
- func CreateSchemaMigrations(c *Connection) error
- func DialectSupported(d string) bool
- func DropDB(c *Connection) error
- func IsZeroOfUnderlyingType(x any) bool
- func LoadConfigFile() error
- func LoadFrom(r io.Reader) error
- func LookupPaths() []string
- func MigrationContent(mf Migration, c *Connection, r io.Reader, usingTemplate bool) (string, error)
- func ParseConfig(r io.Reader) (map[string]*ConnectionDetails, error)
- func SetEagerMode(eagerMode EagerMode)
- func SetLogger(logger func(level logging.Level, s string, args ...any))
- func SetNowFunc(f func() time.Time)
- func SetTxLogger(logger func(level logging.Level, anon any, s string, args ...any))
- type AfterCreateable
- type AfterDestroyable
- type AfterEagerFindable
- type AfterFindable
- type AfterSaveable
- type AfterUpdateable
- type AssociationMetaInfo
- type BeforeCreateable
- type BeforeDestroyable
- type BeforeSaveable
- type BeforeUpdateable
- type BeforeValidateable
- type Connection
- func (c *Connection) All(models any) error
- func (c *Connection) BelongsTo(model any) *Query
- func (c *Connection) BelongsToAs(model any, as string) *Query
- func (c *Connection) BelongsToThrough(bt, thru any) *Query
- func (c *Connection) Close() error
- func (c *Connection) Context() context.Context
- func (c *Connection) Count(model any) (int, error)
- func (c *Connection) Create(model any, excludeColumns ...string) error
- func (c *Connection) Destroy(model any) error
- func (c *Connection) Eager(fields ...string) *Connection
- func (c *Connection) EagerPreload(fields ...string) *Query
- func (c *Connection) Find(model, id any) error
- func (c *Connection) First(model any) error
- func (c *Connection) Last(model any) error
- func (c *Connection) Limit(limit int) *Query
- func (c *Connection) Load(model any, fields ...string) error
- func (c *Connection) MigrationTableName() string
- func (c *Connection) MigrationURL() string
- func (c *Connection) NewTransaction() (*Connection, error)
- func (c *Connection) NewTransactionContext(ctx context.Context) (*Connection, error)
- func (c *Connection) NewTransactionContextOptions(ctx context.Context, options *sql.TxOptions) (*Connection, error)
- func (c *Connection) Open() error
- func (c *Connection) Order(stmt string, args ...any) *Query
- func (c *Connection) Paginate(page, perPage int) *Query
- func (c *Connection) PaginateFromParams(params PaginationParams) *Query
- func (c *Connection) Q() *Query
- func (c *Connection) RawQuery(stmt string, args ...any) *Query
- func (c *Connection) Reload(model any) error
- func (c *Connection) Rollback(fn func(tx *Connection)) error
- func (c *Connection) Save(model any, excludeColumns ...string) error
- func (c *Connection) Scope(sf ScopeFunc) *Query
- func (c *Connection) Select(fields ...string) *Query
- func (c *Connection) String() string
- func (c *Connection) Transaction(fn func(tx *Connection) error) error
- func (c *Connection) TruncateAll() error
- func (c *Connection) URL() string
- func (c *Connection) Update(model any, excludeColumns ...string) error
- func (c *Connection) UpdateColumns(model any, columnNames ...string) error
- func (c *Connection) ValidateAndCreate(model any, excludeColumns ...string) (*validate.Errors, error)
- func (c *Connection) ValidateAndSave(model any, excludeColumns ...string) (*validate.Errors, error)
- func (c *Connection) ValidateAndUpdate(model any, excludeColumns ...string) (*validate.Errors, error)
- func (c *Connection) Where(stmt string, args ...any) *Query
- func (c *Connection) WithContext(ctx context.Context) *Connection
- type ConnectionDetails
- type DownMigrations
- type EagerMode
- type FileMigrator
- type GroupClause
- type HavingClause
- type Match
- type Migration
- type MigrationBox
- type Migrations
- type Migrator
- func (m Migrator) CreateSchemaMigrations() error
- func (m Migrator) Down(step int) error
- func (m Migrator) DumpMigrationSchema() error
- func (m Migrator) Reset() error
- func (m Migrator) Status(out io.Writer) error
- func (m Migrator) Up() error
- func (m Migrator) UpLogOnly() error
- func (m Migrator) UpTo(step int) (applied int, err error)
- type Model
- type ModelMetaInfo
- type PaginationParams
- type Paginator
- type Query
- func (q *Query) All(models any) error
- func (q *Query) BelongsTo(model any) *Query
- func (q *Query) BelongsToAs(model any, as string) *Query
- func (q *Query) BelongsToThrough(bt, thru any) *Query
- func (q *Query) Clone(targetQ *Query)
- func (q Query) Count(model any) (int, error)
- func (q Query) CountByField(model any, field string) (int, error)
- func (q *Query) Delete(model any) error
- func (q *Query) Eager(fields ...string) *Query
- func (q *Query) EagerPreload(fields ...string) *Query
- func (q *Query) Exec() error
- func (q *Query) ExecWithCount() (int, error)
- func (q *Query) Exists(model any) (bool, error)
- func (q *Query) Find(model, id any) error
- func (q *Query) First(model any) error
- func (q *Query) GroupBy(field string, fields ...string) *Query
- func (q *Query) Having(condition string, args ...any) *Query
- func (q *Query) InnerJoin(table, on string, args ...any) *Query
- func (q *Query) Join(table, on string, args ...any) *Query
- func (q *Query) Last(model any) error
- func (q *Query) LeftJoin(table, on string, args ...any) *Query
- func (q *Query) LeftOuterJoin(table, on string, args ...any) *Query
- func (q *Query) Limit(limit int) *Query
- func (q *Query) Order(stmt string, args ...any) *Query
- func (q *Query) Paginate(page, perPage int) *Query
- func (q *Query) PaginateFromParams(params PaginationParams) *Query
- func (q *Query) RawQuery(stmt string, args ...any) *Query
- func (q *Query) RightJoin(table, on string, args ...any) *Query
- func (q *Query) RightOuterJoin(table, on string, args ...any) *Query
- func (q *Query) Scope(sf ScopeFunc) *Query
- func (q *Query) Select(fields ...string) *Query
- func (q Query) ToSQL(model *Model, addColumns ...string) (string, []any)
- func (q *Query) UpdateQuery(model any, columnNames ...string) (int64, error)
- func (q *Query) Where(stmt string, args ...any) *Query
- type ScopeFunc
- type TableNameAble
- type TableNameAbleWithContext
- type Tx
- func (tx *Tx) Close() error
- func (tx *Tx) NamedQueryContext(ctx context.Context, query string, arg any) (*sqlx.Rows, error)
- func (tx *Tx) Transaction() (*Tx, error)
- func (tx *Tx) TransactionContext(_ context.Context) (*Tx, error)
- func (tx *Tx) TransactionContextOptions(_ context.Context, _ *sql.TxOptions) (*Tx, error)
- type UpMigrations
- type Value
Constants ¶
const ( // Select is the default operation for a query. Select operation = "SELECT" // Delete is the operation for a delete query. Delete operation = "DELETE" )
Variables ¶
var AvailableDialects []string
AvailableDialects lists the available database dialects
var Color = true
Color mode, to toggle colored logs
var ConfigName = "database.yml"
ConfigName is the name of the YAML databases config file
var Connections = map[string]*Connection{}
Connections contains all available connections
var Debug = false
Debug mode, to toggle verbose log traces
var ErrConfigFileNotFound = errors.New("unable to find pop config file")
ErrConfigFileNotFound is returned when the pop config file can't be found, after looking for it.
var PaginatorPageKey = "page"
PaginatorPageKey is the query parameter holding the current page index
var PaginatorPerPageDefault = 20
PaginatorPerPageDefault is the amount of results per page
var PaginatorPerPageKey = "per_page"
PaginatorPerPageKey is the query parameter holding the amount of results per page to override the default one
Functions ¶
func AddLookupPaths ¶
AddLookupPaths add paths to the current lookup paths list
func CanonicalDialect ¶ added in v6.0.5
CanonicalDialect checks if the given synonym (could be a valid dialect too) is a registered synonym and returns the canonical dialect for the synonym. Otherwise, it returns the lowercase value of the given synonym.
Note that it does not check if the return value is a valid (supported) dialect so you need to check it with `DialectSupported()`.
func CreateDB ¶
func CreateDB(c *Connection) error
CreateDB creates a database, given a connection definition
func CreateSchemaMigrations ¶
func CreateSchemaMigrations(c *Connection) error
CreateSchemaMigrations sets up a table to track migrations. This is an idempotent operation.
func DialectSupported ¶
DialectSupported checks support for the given database dialect
func DropDB ¶
func DropDB(c *Connection) error
DropDB drops an existing database, given a connection definition
func IsZeroOfUnderlyingType ¶
IsZeroOfUnderlyingType will check if the value of anything is the equal to the Zero value of that type.
func LoadConfigFile ¶
func LoadConfigFile() error
LoadConfigFile loads a POP config file from the configured lookup paths
func LookupPaths ¶
func LookupPaths() []string
LookupPaths returns the current configuration lookup paths
func MigrationContent ¶
MigrationContent returns the content of a migration.
func ParseConfig ¶
func ParseConfig(r io.Reader) (map[string]*ConnectionDetails, error)
ParseConfig reads the pop config from the given io.Reader and returns the parsed ConnectionDetails map.
func SetEagerMode ¶
func SetEagerMode(eagerMode EagerMode)
SetEagerMode changes overall mode when eager loading. this will change the default loading associations strategy for all Eager queries. This will affect all queries when eager loading is used.
func SetNowFunc ¶ added in v6.0.3
SetNowFunc allows an override of time.Now for customizing CreatedAt/UpdatedAt
Types ¶
type AfterCreateable ¶
type AfterCreateable interface {
AfterCreate(conn *Connection) error
}
AfterCreateable callback will be called after a record is created in the database.
type AfterDestroyable ¶
type AfterDestroyable interface {
AfterDestroy(conn *Connection) error
}
AfterDestroyable callback will be called after a record is destroyed in the database.
type AfterEagerFindable ¶ added in v6.1.1
type AfterEagerFindable interface {
AfterEagerFind(con *Connection) error
}
AfterEagerFindable callback will be called after a record, or records, has been retrieved from the database and their associations have been eagerly loaded.
type AfterFindable ¶
type AfterFindable interface {
AfterFind(con *Connection) error
}
AfterFindable callback will be called after a record, or records, has been retrieved from the database.
type AfterSaveable ¶
type AfterSaveable interface {
AfterSave(conn *Connection) error
}
AfterSaveable callback will be called after a record is either created or updated in the database.
type AfterUpdateable ¶
type AfterUpdateable interface {
AfterUpdate(conn *Connection) error
}
AfterUpdateable callback will be called after a record is updated in the database.
type AssociationMetaInfo ¶
AssociationMetaInfo a type to abstract all field information regarding to an association. An association is a field that has defined a tag like 'has_many', 'belongs_to', 'many_to_many' and 'has_one'.
func NewAssociationMetaInfo ¶
func NewAssociationMetaInfo(fi *reflectx.FieldInfo) *AssociationMetaInfo
NewAssociationMetaInfo creates the meta info details for the passed association.
type BeforeCreateable ¶
type BeforeCreateable interface {
BeforeCreate(conn *Connection) error
}
BeforeCreateable callback will be called before a record is created in the database.
type BeforeDestroyable ¶
type BeforeDestroyable interface {
BeforeDestroy(conn *Connection) error
}
BeforeDestroyable callback will be called before a record is destroyed in the database.
type BeforeSaveable ¶
type BeforeSaveable interface {
BeforeSave(conn *Connection) error
}
BeforeSaveable callback will be called before a record is either created or updated in the database.
type BeforeUpdateable ¶
type BeforeUpdateable interface {
BeforeUpdate(conn *Connection) error
}
BeforeUpdateable callback will be called before a record is updated in the database.
type BeforeValidateable ¶
type BeforeValidateable interface {
BeforeValidate(conn *Connection) error
}
BeforeValidateable callback will be called before a record is validated during ValidateAndCreate, ValidateAndUpdate, or ValidateAndSave
type Connection ¶
type Connection struct {
ID string
Store store
Dialect dialect
Elapsed int64
TX *Tx
// contains filtered or unexported fields
}
Connection represents all necessary details to talk with a datastore
func Connect ¶
func Connect(e string) (*Connection, error)
Connect takes the name of a connection, default is "development", and will return that connection from the available `Connections`. If a connection with that name can not be found an error will be returned. If a connection is found, and it has yet to open a connection with its underlying datastore, a connection to that store will be opened.
func NewConnection ¶
func NewConnection(deets *ConnectionDetails) (*Connection, error)
NewConnection creates a new connection, and sets it's `Dialect` appropriately based on the `ConnectionDetails` passed into it.
func (*Connection) All ¶
func (c *Connection) All(models any) error
All retrieves all of the records in the database that match the query.
c.All(&[]User{})
func (*Connection) BelongsTo ¶
func (c *Connection) BelongsTo(model any) *Query
BelongsTo adds a "where" clause based on the "ID" of the "model" passed into it.
func (*Connection) BelongsToAs ¶
func (c *Connection) BelongsToAs(model any, as string) *Query
BelongsToAs adds a "where" clause based on the "ID" of the "model" passed into it using an alias.
func (*Connection) BelongsToThrough ¶
func (c *Connection) BelongsToThrough(bt, thru any) *Query
BelongsToThrough adds a "where" clause that connects the "bt" model through the associated "thru" model.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close destroys an active datasource connection
func (*Connection) Context ¶
func (c *Connection) Context() context.Context
Context returns the connection's context set by "Context()" or context.TODO() if no context is set.
func (*Connection) Count ¶
func (c *Connection) Count(model any) (int, error)
Count the number of records in the database.
c.Count(&User{})
func (*Connection) Create ¶
func (c *Connection) Create(model any, excludeColumns ...string) error
Create add a new given entry to the database, excluding the given columns. It updates `created_at` and `updated_at` columns automatically.
If model is a slice, each item of the slice is created in the database.
Create support two modes: * Flat (default): Associate existing nested objects only. NO creation or update of nested objects. * Eager: Associate existing nested objects and create non-existent objects. NO change to existing objects.
func (*Connection) Destroy ¶
func (c *Connection) Destroy(model any) error
Destroy deletes a given entry from the database.
If model is a slice, each item of the slice is deleted from the database.
func (*Connection) Eager ¶
func (c *Connection) Eager(fields ...string) *Connection
Eager will enable associations loading of the model. by defaults loads all the associations on the model, but can take a variadic list of associations to load.
c.Eager().Find(model, 1) // will load all associations for model.
c.Eager("Books").Find(model, 1) // will load only Book association for model.
Eager also enable nested models creation:
model := Parent{Child: Child{}, Parent: &Parent{}}
c.Eager().Create(&model) // will create all associations for model.
c.Eager("Child").Create(&model) // will only create the Child association for model.
func (*Connection) EagerPreload ¶
func (c *Connection) EagerPreload(fields ...string) *Query
EagerPreload activates preload eager Mode automatically.
func (*Connection) Find ¶
func (c *Connection) Find(model, id any) error
Find the first record of the model in the database with a particular id.
c.Find(&User{}, 1)
func (*Connection) First ¶
func (c *Connection) First(model any) error
First record of the model in the database that matches the query.
c.First(&User{})
func (*Connection) Last ¶
func (c *Connection) Last(model any) error
Last record of the model in the database that matches the query.
c.Last(&User{})
func (*Connection) Limit ¶
func (c *Connection) Limit(limit int) *Query
Limit will create a query and add a limit clause to it.
c.Limit(10)
func (*Connection) Load ¶
func (c *Connection) Load(model any, fields ...string) error
Load loads all association or the fields specified in params for an already loaded model.
tx.First(&u) tx.Load(&u)
func (*Connection) MigrationTableName ¶
func (c *Connection) MigrationTableName() string
MigrationTableName returns the name of the table to track migrations
func (*Connection) MigrationURL ¶
func (c *Connection) MigrationURL() string
MigrationURL returns the datasource connection string used for running the migrations
func (*Connection) NewTransaction ¶
func (c *Connection) NewTransaction() (*Connection, error)
NewTransaction starts a new transaction on the connection
func (*Connection) NewTransactionContext ¶ added in v6.0.4
func (c *Connection) NewTransactionContext(ctx context.Context) (*Connection, error)
NewTransactionContext starts a new transaction on the connection using the provided context
func (*Connection) NewTransactionContextOptions ¶ added in v6.0.4
func (c *Connection) NewTransactionContextOptions(ctx context.Context, options *sql.TxOptions) (*Connection, error)
NewTransactionContextOptions starts a new transaction on the connection using the provided context and transaction options
func (*Connection) Open ¶
func (c *Connection) Open() error
Open creates a new datasource connection
func (*Connection) Order ¶
func (c *Connection) Order(stmt string, args ...any) *Query
Order will append an order clause to the query.
c.Order("name desc")
func (*Connection) Paginate ¶
func (c *Connection) Paginate(page, perPage int) *Query
Paginate records returned from the database.
q := c.Paginate(2, 15)
q.All(&[]User{})
q.Paginator
func (*Connection) PaginateFromParams ¶
func (c *Connection) PaginateFromParams(params PaginationParams) *Query
PaginateFromParams paginates records returned from the database.
q := c.PaginateFromParams(req.URL.Query())
q.All(&[]User{})
q.Paginator
func (*Connection) Q ¶
func (c *Connection) Q() *Query
Q creates a new "empty" query for the current connection.
func (*Connection) RawQuery ¶
func (c *Connection) RawQuery(stmt string, args ...any) *Query
RawQuery will override the query building feature of Pop and will use whatever query you want to execute against the `Connection`. You can continue to use the `?` argument syntax.
c.RawQuery("select * from foo where id = ?", 1)
func (*Connection) Reload ¶
func (c *Connection) Reload(model any) error
Reload fetch fresh data for a given model, using its ID.
func (*Connection) Rollback ¶
func (c *Connection) Rollback(fn func(tx *Connection)) error
Rollback will open a new transaction and automatically rollback that transaction when the inner function returns, regardless. This can be useful for tests, etc...
func (*Connection) Save ¶
func (c *Connection) Save(model any, excludeColumns ...string) error
Save wraps the Create and Update methods. It executes a Create if no ID is provided with the entry; or issues an Update otherwise.
If model is a slice, each item of the slice is saved in the database.
func (*Connection) Scope ¶
func (c *Connection) Scope(sf ScopeFunc) *Query
Scope the query by using a `ScopeFunc`
func ByName(name string) ScopeFunc {
return func(q *Query) *Query {
return q.Where("name = ?", name)
}
}
func WithDeleted(q *pop.Query) *pop.Query {
return q.Where("deleted_at is null")
}
c.Scope(ByName("mark)).Scope(WithDeleted).First(&User{})
func (*Connection) Select ¶
func (c *Connection) Select(fields ...string) *Query
Select allows to query only fields passed as parameter. c.Select("field1", "field2").All(&model) => SELECT field1, field2 FROM models
func (*Connection) String ¶
func (c *Connection) String() string
func (*Connection) Transaction ¶
func (c *Connection) Transaction(fn func(tx *Connection) error) error
Transaction will start a new transaction on the connection. If the inner function returns an error then the transaction will be rolled back, otherwise the transaction will automatically commit at the end.
func (*Connection) TruncateAll ¶
func (c *Connection) TruncateAll() error
TruncateAll truncates all data from the datasource
func (*Connection) URL ¶
func (c *Connection) URL() string
URL returns the datasource connection string
func (*Connection) Update ¶
func (c *Connection) Update(model any, excludeColumns ...string) error
Update writes changes from an entry to the database, excluding the given columns. It updates the `updated_at` column automatically.
If model is a slice, each item of the slice is updated in the database.
func (*Connection) UpdateColumns ¶
func (c *Connection) UpdateColumns(model any, columnNames ...string) error
UpdateColumns writes changes from an entry to the database, including only the given columns or all columns if no column names are provided. It updates the `updated_at` column automatically if you include `updated_at` in columnNames.
If model is a slice, each item of the slice is updated in the database.
func (*Connection) ValidateAndCreate ¶
func (c *Connection) ValidateAndCreate(model any, excludeColumns ...string) (*validate.Errors, error)
ValidateAndCreate applies validation rules on the given entry, then creates it if the validation succeed, excluding the given columns.
If model is a slice, each item of the slice is validated then created in the database.
func (*Connection) ValidateAndSave ¶
ValidateAndSave applies validation rules on the given entry, then save it if the validation succeed, excluding the given columns.
If model is a slice, each item of the slice is validated then saved in the database.
func (*Connection) ValidateAndUpdate ¶
func (c *Connection) ValidateAndUpdate(model any, excludeColumns ...string) (*validate.Errors, error)
ValidateAndUpdate applies validation rules on the given entry, then update it if the validation succeed, excluding the given columns.
If model is a slice, each item of the slice is validated then updated in the database.
func (*Connection) Where ¶
func (c *Connection) Where(stmt string, args ...any) *Query
Where will append a where clause to the query. You may use `?` in place of arguments.
c.Where("id = ?", 1)
q.Where("id in (?)", 1, 2, 3)
func (*Connection) WithContext ¶
func (c *Connection) WithContext(ctx context.Context) *Connection
WithContext returns a copy of the connection, wrapped with a context.
type ConnectionDetails ¶
type ConnectionDetails struct {
// Dialect is the pop dialect to use. Example: "postgres" or "sqlite3" or "mysql"
Dialect string
// Driver specifies the database driver to use (optional)
Driver string
// The name of your database. Example: "foo_development"
Database string
// The host of your database. Example: "127.0.0.1"
Host string
// The port of your database. Example: 1234
// Will default to the "default" port for each dialect.
Port string
// The username of the database user. Example: "root"
User string
// The password of the database user. Example: "password"
Password string
// The encoding to use to create the database and communicate with it.
Encoding string
// Instead of specifying each individual piece of the
// connection you can instead just specify the URL of the
// database. Example: "postgres://postgres:postgres@localhost:5432/pop_test?sslmode=disable"
URL string
// Defaults to 0 "unlimited". See https://golang.org/pkg/database/sql/#DB.SetMaxOpenConns
Pool int
// Defaults to 2. See https://golang.org/pkg/database/sql/#DB.SetMaxIdleConns
IdlePool int
// Defaults to 0 "unlimited". See https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime
ConnMaxLifetime time.Duration
// Defaults to 0 "unlimited". See https://golang.org/pkg/database/sql/#DB.SetConnMaxIdleTime
ConnMaxIdleTime time.Duration
// Defaults to `false`. See https://godoc.org/github.com/jmoiron/sqlx#DB.Unsafe
Unsafe bool
// Options stores Connection Details options
Options map[string]string
// Query string encoded options from URL. Example: "sslmode=disable"
RawOptions string
// UseInstrumentedDriver if set to true uses a wrapper for the underlying driver which exposes tracing
// information in the Open Tracing, Open Census, Google, and AWS Xray format. This is useful when using
// tracing with Jaeger, DataDog, Zipkin, or other tracing software.
UseInstrumentedDriver bool
// InstrumentedDriverOptions sets the options for the instrumented driver. These options are empty by default
// meaning that instrumentation is disabled.
//
// For more information check out the docs at https://github.com/luna-duclos/instrumentedsql. If you use Open
// Tracing, these options could looks as follows:
//
// InstrumentedDriverOptions: []instrumentedsql.Opt{instrumentedsql.WithTracer(opentracing.NewTracer(true))}
//
// It is also recommended to include `instrumentedsql.WithOmitArgs()` which prevents SQL arguments (e.g. passwords)
// from being traced or logged.
InstrumentedDriverOptions []instrumentedsql.Opt
// contains filtered or unexported fields
}
ConnectionDetails stores the data needed to connect to a datasource
func (*ConnectionDetails) Finalize ¶
func (cd *ConnectionDetails) Finalize() error
Finalize cleans up the connection details by normalizing names, filling in default values, etc...
func (*ConnectionDetails) MigrationTableName ¶
func (cd *ConnectionDetails) MigrationTableName() string
MigrationTableName returns the name of the table to track migrations
func (*ConnectionDetails) OptionsString ¶
func (cd *ConnectionDetails) OptionsString(s string) string
OptionsString returns URL parameter encoded string from options.
func (*ConnectionDetails) RetryLimit ¶
func (cd *ConnectionDetails) RetryLimit() int
RetryLimit returns the maximum number of accepted connection retries
func (*ConnectionDetails) RetrySleep ¶
func (cd *ConnectionDetails) RetrySleep() time.Duration
RetrySleep returns the amount of time to wait between two connection retries
type DownMigrations ¶
type DownMigrations struct {
Migrations
}
DownMigrations is used to sort down migrations in reverse order.
func (DownMigrations) Less ¶
func (mfs DownMigrations) Less(i, j int) bool
Less is used to sort down migrations in reverse order.
type EagerMode ¶
type EagerMode uint8
EagerMode type for all eager modes supported in pop.
const ( // EagerDefault is the current implementation, the default // behavior of pop. This one introduce N+1 problem and will be used as // default value for backward compatibility. EagerDefault EagerMode // EagerPreload mode works similar to Preload mode used in Rails ActiveRecord. // Avoid N+1 problem by reducing the number of hits to the database but // increase memory use to process and link associations to parent. EagerPreload // EagerInclude This mode works similar to Include mode used in rails ActiveRecord. // Use Left Join clauses to load associations. Not working yet. EagerInclude )
type FileMigrator ¶
FileMigrator is a migrator for SQL and Fizz files on disk at a specified path.
func NewFileMigrator ¶
func NewFileMigrator(path string, c *Connection) (FileMigrator, error)
NewFileMigrator for a path and a Connection
type GroupClause ¶
type GroupClause struct {
Field string
}
GroupClause holds the field to apply the GROUP clause on
func (GroupClause) String ¶
func (c GroupClause) String() string
type HavingClause ¶
HavingClause defines a condition and its arguments for a HAVING clause
func (HavingClause) String ¶
func (c HavingClause) String() string
type Match ¶
Match holds the information parsed from a migration filename.
func ParseMigrationFilename ¶
ParseMigrationFilename parses a migration filename.
type Migration ¶
type Migration struct {
// Path to the migration (./migrations/123_create_widgets.up.sql)
Path string
// Version of the migration (123)
Version string
// Name of the migration (create_widgets)
Name string
// Direction of the migration (up)
Direction string
// Type of migration (sql)
Type string
// DB type (all|postgres|mysql...)
DBType string
// Runner function to run/execute the migration
Runner func(Migration, *Connection) error
}
Migration handles the data for a given database migration
func (Migration) Run ¶
func (mf Migration) Run(c *Connection) error
Run the migration. Returns an error if there is no mf.Runner defined.
type MigrationBox ¶
MigrationBox is a wrapper around fs.FS and Migrator. This will allow you to run migrations from a fs.FS inside of a compiled binary.
func NewMigrationBox ¶
func NewMigrationBox(fsys fs.FS, c *Connection) (MigrationBox, error)
NewMigrationBox from a fs.FS and a Connection.
type Migrations ¶
type Migrations []Migration
Migrations is a collection of Migration
func (*Migrations) Filter ¶
func (mfs *Migrations) Filter(f func(mf Migration) bool)
Filter filters the migrations in place based on the provided function.
func (Migrations) Len ¶
func (mfs Migrations) Len() int
Len returns the number of migrations in the collection.
func (Migrations) Swap ¶
func (mfs Migrations) Swap(i, j int)
Swap swaps the position of two migrations in the collection.
type Migrator ¶
type Migrator struct {
Connection *Connection
SchemaPath string
UpMigrations UpMigrations
DownMigrations DownMigrations
}
Migrator forms the basis of all migrations systems. It does the actual heavy lifting of running migrations. When building a new migration system, you should embed this type into your migrator.
func NewMigrator ¶
func NewMigrator(c *Connection) Migrator
NewMigrator returns a new "blank" migrator. It is recommended to use something like MigrationBox or FileMigrator. A "blank" Migrator should only be used as the basis for a new type of migration system.
func (Migrator) CreateSchemaMigrations ¶
CreateSchemaMigrations sets up a table to track migrations. This is an idempotent operation.
func (Migrator) Down ¶
Down runs pending "down" migrations and rolls back the database by the specified number of steps.
func (Migrator) DumpMigrationSchema ¶
DumpMigrationSchema will generate a file of the current database schema based on the value of Migrator.SchemaPath
func (Migrator) Reset ¶
Reset the database by running the down migrations followed by the up migrations.
type Model ¶
Model is used throughout Pop to wrap the end user interface that is passed in to many functions.
func (*Model) Alias ¶
Alias returns the alias of the model if it is set, otherwise it returns the table name.
func (*Model) Columns ¶
Columns returns the columns of the underlying database table for a given `Model`.
func (*Model) ID ¶
ID returns the ID of the Model. All models must have an `ID` field this is of type `int`,`int64` or of type `uuid.UUID`.
func (*Model) IDField ¶
IDField returns the name of the DB field used for the ID. By default, it will return "id".
func (*Model) PrimaryKeyType ¶
PrimaryKeyType gives the primary key type of the `Model`.
func (*Model) TableName ¶
TableName returns the corresponding name of the underlying database table for a given `Model`. See also `TableNameAble` to change the default name of the table.
func (*Model) WhereID ¶
WhereID returns a string with the format "alias.id = ?" where alias is the alias of the model and id is the name of the ID field.
func (*Model) WhereNamedID ¶
WhereNamedID returns a string with the format "alias.id = :id" where alias is the alias of the model and id is the name of the ID field.
type ModelMetaInfo ¶
type ModelMetaInfo struct {
*reflectx.StructMap
Model *Model
// contains filtered or unexported fields
}
ModelMetaInfo a type to abstract all fields information regarding to a model. A model is representation of a table in the database.
func NewModelMetaInfo ¶
func NewModelMetaInfo(model *Model) *ModelMetaInfo
NewModelMetaInfo creates the meta info details for the model passed as a parameter.
type PaginationParams ¶
PaginationParams is a parameters provider interface to get the pagination params from
type Paginator ¶
type Paginator struct {
// Current page you're on
Page int `json:"page"`
// Number of results you want per page
PerPage int `json:"per_page"`
// Page * PerPage (ex: 2 * 20, Offset == 40)
Offset int `json:"offset"`
// Total potential records matching the query
TotalEntriesSize int `json:"total_entries_size"`
// Total records returns, will be <= PerPage
CurrentEntriesSize int `json:"current_entries_size"`
// Total pages
TotalPages int `json:"total_pages"`
}
Paginator is a type used to represent the pagination of records from the database.
func NewPaginator ¶
NewPaginator returns a new `Paginator` value with the appropriate defaults set.
func NewPaginatorFromParams ¶
func NewPaginatorFromParams(params PaginationParams) *Paginator
NewPaginatorFromParams takes an interface of type `PaginationParams`, the `url.Values` type works great with this interface, and returns a new `Paginator` based on the params or `PaginatorPageKey` and `PaginatorPerPageKey`. Defaults are `1` for the page and PaginatorPerPageDefault for the per page value.
type Query ¶
type Query struct {
RawSQL *clause
Paginator *Paginator
Connection *Connection
Operation operation
// contains filtered or unexported fields
}
Query is the main value that is used to build up a query to be executed against the `Connection`.
func Q ¶
func Q(c *Connection) *Query
Q will create a new "empty" query from the current connection.
func (*Query) All ¶
All retrieves all of the records in the database that match the query.
q.Where("name = ?", "mark").All(&[]User{})
func (*Query) BelongsTo ¶
BelongsTo adds a "where" clause based on the "ID" of the "model" passed into it.
func (*Query) BelongsToAs ¶
BelongsToAs adds a "where" clause based on the "ID" of the "model" passed into it, using an alias.
func (*Query) BelongsToThrough ¶
BelongsToThrough adds a "where" clause that connects the "bt" model through the associated "thru" model.
func (*Query) Clone ¶
Clone will fill targetQ query with the connection used in q, if targetQ is not empty, Clone will override all the fields.
func (Query) Count ¶
Count the number of records in the database.
q.Where("name = ?", "mark").Count(&User{})
func (Query) CountByField ¶
CountByField counts the number of records in the database, for a given field.
q.Where("sex = ?", "f").Count(&User{}, "name")
func (*Query) Eager ¶
Eager will enable load associations of the model. by defaults loads all the associations on the model, but can take a variadic list of associations to load.
q.Eager().Find(model, 1) // will load all associations for model.
q.Eager("Books").Find(model, 1) // will load only Book association for model.
func (*Query) EagerPreload ¶
EagerPreload activates preload eager Mode automatically.
func (*Query) ExecWithCount ¶
ExecWithCount runs the given query, and returns the amount of affected rows.
func (*Query) Exists ¶
Exists returns true/false if a record exists in the database that matches the query.
q.Where("name = ?", "mark").Exists(&User{})
func (*Query) Find ¶
Find the first record of the model in the database with a particular id.
q.Find(&User{}, 1)
func (*Query) First ¶
First record of the model in the database that matches the query.
q.Where("name = ?", "mark").First(&User{})
func (*Query) Last ¶
Last record of the model in the database that matches the query.
q.Where("name = ?", "mark").Last(&User{})
func (*Query) LeftOuterJoin ¶
LeftOuterJoin will append a LEFT OUTER JOIN clause to the query
func (*Query) Paginate ¶
Paginate records returned from the database.
q = q.Paginate(2, 15)
q.All(&[]User{})
q.Paginator
func (*Query) PaginateFromParams ¶
func (q *Query) PaginateFromParams(params PaginationParams) *Query
PaginateFromParams paginates records returned from the database.
q = q.PaginateFromParams(req.URL.Query())
q.All(&[]User{})
q.Paginator
func (*Query) RawQuery ¶
RawQuery will override the query building feature of Pop and will use whatever query you want to execute against the `Connection`. You can continue to use the `?` argument syntax.
q.RawQuery("select * from foo where id = ?", 1)
func (*Query) RightOuterJoin ¶
RightOuterJoin will append a RIGHT OUTER JOIN clause to the query
func (*Query) Scope ¶
Scope the query by using a `ScopeFunc`
func ByName(name string) ScopeFunc {
return func(q *Query) *Query {
return q.Where("name = ?", name)
}
}
func WithDeleted(q *pop.Query) *pop.Query {
return q.Where("deleted_at is null")
}
c.Scope(ByName("mark)).Scope(WithDeleted).First(&User{})
func (*Query) Select ¶
Select allows to query only fields passed as parameter. c.Select("field1", "field2").All(&model) => SELECT field1, field2 FROM models
func (Query) ToSQL ¶
ToSQL will generate SQL and the appropriate arguments for that SQL from the `Model` passed in.
func (*Query) UpdateQuery ¶ added in v6.0.3
UpdateQuery updates all rows matched by the query. The new values are read from the first argument, which must be a struct. The column names to be updated must be listed explicitly in subsequent arguments. The ID and CreatedAt columns are never updated. The UpdatedAt column is updated automatically.
UpdateQuery does not execute (before|after)(Create|Update|Save) callbacks.
Calling UpdateQuery with no columnNames will result in only the UpdatedAt column being updated.
type TableNameAble ¶
type TableNameAble interface {
TableName() string
}
TableNameAble interface allows for the customize table mapping between a name and the database. For example the value `User{}` will automatically map to "users". Implementing `TableNameAble` would allow this to change to be changed to whatever you would like.
type TableNameAbleWithContext ¶
TableNameAbleWithContext is equal to TableNameAble but will be passed the queries' context. Useful in cases where the table name depends on e.g.
type Tx ¶
Tx stores a transaction with an ID to keep track.
func (*Tx) NamedQueryContext ¶ added in v6.1.2
NamedQueryContext binds a named query and then runs Query on the result using the Transaction. It works with both structs and with map[string]any types.
func (*Tx) Transaction ¶
Transaction simply returns the current transaction, this is defined so it implements the `Store` interface.
func (*Tx) TransactionContext ¶
TransactionContext simply returns the current transaction, this is defined so it implements the `Store` interface.
type UpMigrations ¶
type UpMigrations struct {
Migrations
}
UpMigrations is used to sort up migrations in order.
func (UpMigrations) Less ¶
func (mfs UpMigrations) Less(i, j int) bool
Less is used to sort up migrations.
Source Files
¶
- belongs_to.go
- callbacks.go
- clause.go
- commands.go
- config.go
- connection.go
- connection_details.go
- connection_instrumented.go
- db.go
- dialect.go
- dialect_cockroach.go
- dialect_common.go
- dialect_mariadb.go
- dialect_mysql.go
- dialect_postgresql.go
- dialect_sqlite.go
- doc.go
- executors.go
- file_migrator.go
- finders.go
- group.go
- having.go
- join.go
- logger.go
- match.go
- migration_box.go
- migration_content.go
- migration_info.go
- migrator.go
- model.go
- paginator.go
- pop.go
- preload_associations.go
- query.go
- query_groups.go
- query_having.go
- query_joins.go
- schema_migrations.go
- scopes.go
- sql_builder.go
- store.go
- tx.go
- validations.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package associations provides types and functions for defining and working with model associations in the pop package.
|
Package associations provides types and functions for defining and working with model associations in the pop package. |
|
Package columns provides types and functions for working with SQL table columns in the context of the pop package.
|
Package columns provides types and functions for working with SQL table columns in the context of the pop package. |
|
Package fix provides functions for updating old migration files to the newer formats.
|
Package fix provides functions for updating old migration files to the newer formats. |
|
genny
|
|
|
config
Package config provides a generator for creating database configuration files (e.g., database.yml) based on templates.
|
Package config provides a generator for creating database configuration files (e.g., database.yml) based on templates. |
|
fizz/cempty
Package cempty provides a generator for creating empty migration files in either SQL or Fizz format, depending on the specified options.
|
Package cempty provides a generator for creating empty migration files in either SQL or Fizz format, depending on the specified options. |
|
fizz/ctable
Package ctable provides a generator for creating migration files that define new database tables.
|
Package ctable provides a generator for creating migration files that define new database tables. |
|
model
Package model provides a generator for creating new models in a Buffalo application.
|
Package model provides a generator for creating new models in a Buffalo application. |
|
internal
|
|
|
randx
Package randx provides functions for generating random data.
|
Package randx provides functions for generating random data. |
|
Package logging provides types for logging levels used in the pop package.
|
Package logging provides types for logging levels used in the pop package. |
|
Package slices provides types and functions for working with slices of various data types when interacting with databases.
|
Package slices provides types and functions for working with slices of various data types when interacting with databases. |
|
Package main is the entry point for the soda command-line tool, which is used for database management tasks such as migrations and seeding in the Buffalo framework.
|
Package main is the entry point for the soda command-line tool, which is used for database management tasks such as migrations and seeding in the Buffalo framework. |
|
cmd
Package cmd contains the command-line interface (CLI) commands for the soda tool, which is used for managing databases with pop.
|
Package cmd contains the command-line interface (CLI) commands for the soda tool, which is used for managing databases with pop. |
|
cmd/generate
Package generate provides commands for generating various files related to the pop package.
|
Package generate provides commands for generating various files related to the pop package. |
|
cmd/schema
Package schema provides a command for interacting with the database schema, including dumping and loading the schema.
|
Package schema provides a command for interacting with the database schema, including dumping and loading the schema. |
