Documentation ¶
Index ¶
- Constants
- Variables
- func Create[T any](value *T) *T
- func CreateD[T any](value *T) *T
- func CreateFromMap[T any](values map[string]any) *T
- func CreateFromMapD[T any](values map[string]any) *T
- func CreateInBatches[T any](values []*T, batchSize int) []*T
- func CreateInBatchesD[T any](values []*T, batchSize int) []*T
- func Exec(sql string, args ...any) int64
- func ExecD(sql string, args ...any) int64
- func First[T any](id any) (*T, bool)
- func FirstD[T any](id any) (*T, bool)
- func FirstOrCreate[T any](value T) (*T, bool)
- func FirstOrCreateD[T any](value T) (*T, bool)
- func FirstOrInit[T any](value T) (*T, bool)
- func FirstOrInitD[T any](value T) (*T, bool)
- func Init(config *Config) error
- func Instance() *gorm.DB
- func Query[T any](sql string, args ...any) T
- func QueryD[T any](sql string, args ...any) T
- func Save[T any](model *T) *T
- func SaveD[T any](model *T) *T
- func SetErrorHandler(f func(err error))
- func SetInstance(value *gorm.DB)
- type Builder
- func (self *Builder[T]) Count() int64
- func (self *Builder[T]) Debug() *Builder[T]
- func (self *Builder[T]) Delete()
- func (self *Builder[T]) Distinct() *Builder[T]
- func (self *Builder[T]) Exists() bool
- func (self *Builder[T]) Find() []*T
- func (self *Builder[T]) First() (*T, bool)
- func (self *Builder[T]) HardDelete()
- func (self *Builder[T]) Last() (*T, bool)
- func (self *Builder[T]) Limit(value int) *Builder[T]
- func (self *Builder[T]) Offset(offset int) *Builder[T]
- func (self *Builder[T]) Order(value any) *Builder[T]
- func (self *Builder[T]) Unscoped() *Builder[T]
- func (self *Builder[T]) Update(values ...any)
- func (self *Builder[T]) Where(query string, args ...any) *Builder[T]
- type Config
- type Map
- type MigrateFunc
- type Migration
- type MigrationType
- type Migrator
- type Model
- type QueryBuilder
Constants ¶
const UnknownDatabaseError = 1049
https://dev.mysql.com/doc/mysql-errors/5.7/en/server-error-reference.html#error_er_bad_db_error
Variables ¶
var ( ErrMissingAutoMigrateFunc = errors.New("missing autoMigrate func") ErrMissingMigrationID = func(i int) error { return fmt.Errorf("missing migration ID at index: %d", i) } ErrMissingMigrationType = func(id string) error { return fmt.Errorf("missing migration type for ID: %s", id) } ErrReservedMigration = func(id string) error { return fmt.Errorf("reserved migration ID: %s", id) } ErrDuplicateMigration = func(id string) error { return fmt.Errorf("duplicate migration ID: %s", id) } )
Functions ¶
func CreateD ¶ added in v1.2.0
func CreateD[T any](value *T) *T
CreateD creates a new model (in debug mode).
func CreateFromMap ¶ added in v1.10.0
CreateFromMap creates a new model from map values.
func CreateFromMapD ¶ added in v1.10.0
CreateFromMapD creates a new model (in debug mode) from map values.
func CreateInBatches ¶
CreateInBatches creates multiple new models in batches of batchSize.
func CreateInBatchesD ¶ added in v1.2.0
CreateInBatchesD creates multiple new models (in debug mode) in batches of batchSize.
func ExecD ¶ added in v1.2.0
ExecD executes some raw SQL (in debug mode) and returns the number of rows affected.
func First ¶ added in v1.3.0
First[T] returns *T for the T with the specified ID, and true if it was found.
func FirstD ¶ added in v1.3.0
FirstD[T] returns *T for the T with the specified ID (in debug mode), and true if it was found.
func FirstOrCreate ¶
FirstOrCreate returns the first row that matches the query, or creates and returns a new instance of T, as well as true if a row was found.
func FirstOrCreateD ¶ added in v1.2.0
FirstOrCreateD returns the first row that matches the query (in debug mode), or creates and returns a new instance of T, as well as true if a row was found.
func FirstOrInit ¶
FirstOrInit returns the first row that matches the query, or a new prepared instance of T, as well as true if a row was found.
func FirstOrInitD ¶ added in v1.2.0
FirstOrInitD returns the first row that matches the query (in debug mode), or a new prepared instance of T, as well as true if a row was found.
func QueryD ¶ added in v1.2.0
QueryD executes some raw SQL (in debug mode) and returns a scan of the result into T.
func Save ¶
func Save[T any](model *T) *T
Save updates an existing model, or inserts it if it doesn't already exist.
func SaveD ¶ added in v1.2.0
func SaveD[T any](model *T) *T
SaveD updates an existing model (in debug mode), or inserts it if it doesn't already exist.
func SetErrorHandler ¶
func SetErrorHandler(f func(err error))
SetErrorHandler sets a function to be called if any database operations fail. Set to nil to use the default (panic).
func SetInstance ¶ added in v1.11.0
SetInstance sets the internal instance of *gorm.DB.
Types ¶
type Builder ¶
type Builder[T any] struct { // contains filtered or unexported fields }
func B ¶
B returns a new *Builder prepared for model T.
The builder can be initialised with a where query by passing in a string followed by (optional) args.
Examples:
db.B[Model]() db.B[Model]("id = ?", 1) db.B[Model]("id = ? and name = ?", 1, "John")
func ForD ¶ added in v1.3.0
ForD[T] returns a *Builder[T] (in debug mode) for the T with the specified ID.
func (*Builder[T]) Debug ¶ added in v1.2.0
Debug ensures queries from this builder always log to the terminal. This method does not modify the current builder.
func (*Builder[T]) Delete ¶
func (self *Builder[T]) Delete()
Delete soft-deletes all rows that match the query.
func (*Builder[T]) Find ¶
func (self *Builder[T]) Find() []*T
Find returns all rows that match the query.
func (*Builder[T]) First ¶
First returns the first row that matches the query, and true if it was able to find a row.
func (*Builder[T]) HardDelete ¶
func (self *Builder[T]) HardDelete()
HardDelete hard-deletes all rows that match the query.
func (*Builder[T]) Last ¶
Last returns the last row that matches the query, and true if it was able to find a row.
func (*Builder[T]) Order ¶
Order adds an ORDER BY clause to the query.
Examples:
Order("id ASC") Order("id DESC")
func (*Builder[T]) Unscoped ¶ added in v1.12.0
Unscoped ensures queries include soft-deleted rows. This method does not modify the current builder.
func (*Builder[T]) Update ¶
Update updates the value(s) of column(s) for the rows that match the query. The values parameter can take many forms.
Sequence of key/value pairs (like in slog):
Update("foo", "bar", "n", 123)
Slice of sequence of key/value pairs:
updates := []any{"foo", "bar", "n", 123} Update(updates...) Update(updates)
Map of map[string]any (aliased to db.Map):
Update(db.Map{"foo": "bar", "n": 123})
Model (only updates non-zero fields):
Update(m.Model{Foo: "bar", N: 123})
type Config ¶
type Config struct { Name string // The database name. User string // The database username. Pass string // The database password. Host string // The database hostname. Socket string // The database socket path. CharSet string // The database character set. TimeZone string // The database timezone. Models []Model // A list of models to migrate. Migrations []*Migration // A list of manual migrations to run. Debug bool // Whether to log queries. Colour bool // Whether to display colour in debugging output. Fresh bool // Whether to drop and recreate the database (for tests). ErrorHandler func(err error) // A function to run if a database error occurs. SlowThreshold time.Duration // Threshold for queries to be considered slow. Seed func() error }
func (*Config) FallbackDSN ¶
FallbackDSN returns the DSN without the database name specified.
func (*Config) PrimaryDSN ¶
PrimaryDSN returns the DSN with the database name specified.
type MigrateFunc ¶ added in v1.8.0
type Migration ¶ added in v1.8.0
type Migration struct { // ID of the migration. Must be unique. ID string // When to run the migration. "Pre" migrations run before the database schema is updated // (automigrated) to match any changes to the model structs, "Post" migrations run afterwards, // and "Schema" migrations run afterwards but with the difference that they will also run after // the schema is created for the first time. The decision as to which one to use depends on the // purpose of the migration. // // If a struct field is renamed then the next time the database is automigrated a duplicate // column will be added. A pre migration to rename the column will prevent this. // // If a struct field is added but needs to be set to some default value then a post migration // would be appropriate. // // If database constraints are added then these will need to be added to existing databases but // also freshly created ones, so a schema migration would be appropriate. Type MigrationType // The function to run to migrate the database. Run MigrateFunc }
type MigrationType ¶ added in v1.8.0
type MigrationType int
const ( // Pre migrations run before the database schema is updated (automigrated) to match any // changes to the model structs. MigrationTypePre MigrationType = iota + 1 // Post migrations run after the database schema is updated (automigrated) to match any // changes to the model structs. MigrationTypePost // Schema migrations run after the database schema is updated (automigrated) to match any // changes to the model structs. They will always run, even after the schema is created for the // first time MigrationTypeSchema )
type Migrator ¶ added in v1.8.0
type Migrator struct {
// contains filtered or unexported fields
}
func NewMigrator ¶ added in v1.8.0
NewMigrator returns a new instance of Migrator.
func (*Migrator) Migrate ¶ added in v1.8.0
func (self *Migrator) Migrate(autoMigrate MigrateFunc) error
Migrate migrates the database schema using autoMigrate to run the automigrations.
type Model ¶ added in v1.4.0
type Model interface { Update(...any) Delete() }
Interface Model represents an instance of a model object. These will normally be implemented by calling the Builder method on db.For[T](self.ID), but Delete may also do other work to maintain referential integrity.
type QueryBuilder ¶ added in v1.7.0
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder allows building up a query string piecemeal while still providing the safety of prepared statements.
func Q ¶ added in v1.7.0
func Q(query string) *QueryBuilder
Q returns a new *QueryBuilder with the initial query set to query.
func (*QueryBuilder) And ¶ added in v1.7.0
func (self *QueryBuilder) And(condition string, args ...any)
And adds an AND condition to the query if a WHERE clause already exists, otherwise adds a WHERE clause.
func (*QueryBuilder) Append ¶ added in v1.7.0
func (self *QueryBuilder) Append(s string, args ...any)
Append adds a string to the query.
func (*QueryBuilder) Args ¶ added in v1.7.0
func (self *QueryBuilder) Args() []any
Args returns the number of arguments that correspond to the number of placeholders in the query.
func (*QueryBuilder) Or ¶ added in v1.7.0
func (self *QueryBuilder) Or(condition string, args ...any)
And adds an OR condition to the query if a WHERE clause already exists, otherwise adds a WHERE clause.
func (*QueryBuilder) Query ¶ added in v1.7.0
func (self *QueryBuilder) Query() string
Query returns the query as a string.