db

package module
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: GPL-3.0 Imports: 12 Imported by: 1

README

db

db is a generic database wrapper around gorm.

Installation

go get crdx.org/db

Usage

Check out the documentation on pkg.go.dev.

Contributions

Open an issue or send a pull request.

Licence

GPLv3.

Documentation

Index

Constants

View Source
const UnknownDatabaseError = 1049

https://dev.mysql.com/doc/mysql-errors/5.7/en/server-error-reference.html#error_er_bad_db_error

Variables

View Source
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 Create

func Create[T any](value *T) *T

Create creates a new model.

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

func CreateFromMap[T any](values map[string]any) *T

CreateFromMap creates a new model from map values.

func CreateFromMapD added in v1.10.0

func CreateFromMapD[T any](values map[string]any) *T

CreateFromMapD creates a new model (in debug mode) from map values.

func CreateInBatches

func CreateInBatches[T any](values []*T, batchSize int) []*T

CreateInBatches creates multiple new models in batches of batchSize.

func CreateInBatchesD added in v1.2.0

func CreateInBatchesD[T any](values []*T, batchSize int) []*T

CreateInBatchesD creates multiple new models (in debug mode) in batches of batchSize.

func Exec

func Exec(sql string, args ...any) int64

Exec executes some raw SQL and returns the number of rows affected.

func ExecD added in v1.2.0

func ExecD(sql string, args ...any) int64

ExecD executes some raw SQL (in debug mode) and returns the number of rows affected.

func First added in v1.3.0

func First[T any](id any) (*T, bool)

First[T] returns *T for the T with the specified ID, and true if it was found.

func FirstD added in v1.3.0

func FirstD[T any](id any) (*T, bool)

FirstD[T] returns *T for the T with the specified ID (in debug mode), and true if it was found.

func FirstOrCreate

func FirstOrCreate[T any](value T) (*T, bool)

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

func FirstOrCreateD[T any](value T) (*T, bool)

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

func FirstOrInit[T any](value T) (*T, bool)

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

func FirstOrInitD[T any](value T) (*T, bool)

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 Init

func Init(config *Config) error

Init initialises the database.

func Instance

func Instance() *gorm.DB

Instance returns the internal instance of *gorm.DB.

func Query

func Query[T any](sql string, args ...any) T

Query executes some raw SQL and returns a scan of the result into T.

func QueryD added in v1.2.0

func QueryD[T any](sql string, args ...any) T

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

func SetInstance(value *gorm.DB)

SetInstance sets the internal instance of *gorm.DB.

Types

type Builder

type Builder[T any] struct {
	// contains filtered or unexported fields
}

func B

func B[T any](args ...any) *Builder[T]

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 For added in v1.3.0

func For[T any](id any) *Builder[T]

For[T] returns a *Builder[T] for the T with the specified ID.

func ForD added in v1.3.0

func ForD[T any](id any) *Builder[T]

ForD[T] returns a *Builder[T] (in debug mode) for the T with the specified ID.

func (*Builder[T]) Count

func (self *Builder[T]) Count() int64

Count returns the number of rows that match the query.

func (*Builder[T]) Debug added in v1.2.0

func (self *Builder[T]) Debug() *Builder[T]

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]) Distinct

func (self *Builder[T]) Distinct() *Builder[T]

Distinct adds an DISTINCT clause to the query.

func (*Builder[T]) Exists

func (self *Builder[T]) Exists() bool

Exists returns whether any rows exist 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

func (self *Builder[T]) First() (*T, bool)

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

func (self *Builder[T]) Last() (*T, bool)

Last returns the last row that matches the query, and true if it was able to find a row.

func (*Builder[T]) Limit

func (self *Builder[T]) Limit(value int) *Builder[T]

Limit adds a LIMIT clause to the query.

func (*Builder[T]) Offset

func (self *Builder[T]) Offset(offset int) *Builder[T]

Offset adds an OFFSET clause to the query.

func (*Builder[T]) Order

func (self *Builder[T]) Order(value any) *Builder[T]

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

func (self *Builder[T]) Unscoped() *Builder[T]

Unscoped ensures queries include soft-deleted rows. This method does not modify the current builder.

func (*Builder[T]) Update

func (self *Builder[T]) Update(values ...any)

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})

func (*Builder[T]) Where

func (self *Builder[T]) Where(query string, args ...any) *Builder[T]

Where adds a WHERE clause to the query.

Examples:

Where("id = ?", 1)
Where("id = ? and name = ?", 1, "John")

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

func (self *Config) FallbackDSN() string

FallbackDSN returns the DSN without the database name specified.

func (*Config) PrimaryDSN

func (self *Config) PrimaryDSN() string

PrimaryDSN returns the DSN with the database name specified.

type Map

type Map = map[string]any

type MigrateFunc added in v1.8.0

type MigrateFunc func(*gorm.DB) error

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

func NewMigrator(db *gorm.DB, migrations []*Migration) *Migrator

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.

Jump to

Keyboard shortcuts

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