database

package
v4.4.11 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2023 License: MIT Imports: 13 Imported by: 7

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddInitializer

func AddInitializer(initializer Initializer)

AddInitializer adds a database connection initializer function. Initializer functions are meant to modify a connection settings at the global scope when it's created.

Initializer functions are called in order, meaning that functions added last can override settings defined by previous ones.

func ClearInitializers

func ClearInitializers()

ClearInitializers remove all database connection initializer functions.

func ClearRegisteredModels

func ClearRegisteredModels()

ClearRegisteredModels unregister all models.

func Close

func Close() error

Close the database connections if they exist.

func Conn

func Conn() *gorm.DB

Conn alias for GetConnection.

func GetConnection

func GetConnection() *gorm.DB

GetConnection returns the global database connection pool. Creates a new connection pool if no connection is available.

The connections will be closed automatically on server shutdown so you don't need to call "Close()" when you're done with the database.

func GetRegisteredModels

func GetRegisteredModels() []interface{}

GetRegisteredModels get the registered models. The returned slice is a copy of the original, so it cannot be modified.

func Migrate

func Migrate()

Migrate migrates all registered models.

func RegisterDialect

func RegisterDialect(name, template string, initializer DialectorInitializer)

RegisterDialect registers a connection string template for the given dialect.

You cannot override a dialect that already exists.

Template format accepts the following placeholders, which will be replaced with the corresponding configuration entries automatically:

  • "{username}"
  • "{password}"
  • "{host}"
  • "{port}"
  • "{name}"
  • "{options}"

Example template for the "mysql" dialect:

{username}:{password}@({host}:{port})/{name}?{options}

func RegisterModel

func RegisterModel(model interface{})

RegisterModel registers a model for auto-migration. When writing a model file, you should always register it in the init() function.

 func init() {
		database.RegisterModel(&MyModel{})
 }

func SetConnection added in v4.1.0

func SetConnection(dialector gorm.Dialector) (*gorm.DB, error)

SetConnection manually replace the automatic DB connection. If a connection already exists, closes it before discarding it. This can be used to create a mock DB in tests. Using this function is not recommended outside of tests. Prefer using a custom dialect.

Types

type DialectorInitializer

type DialectorInitializer func(dsn string) gorm.Dialector

DialectorInitializer function initializing a GORM Dialector using the given data source name (DSN).

type Factory

type Factory struct {
	// contains filtered or unexported fields
}

Factory an object used to generate records or seed the database.

func NewFactory

func NewFactory(generator Generator) *Factory

NewFactory create a new Factory. The given generator function will be used to generate records.

func (*Factory) Generate

func (f *Factory) Generate(count int) interface{}

Generate a number of records using the given factory. Returns a slice of the actual type of the generated records, meaning you can type-assert safely.

factory.Generate(5).([]*User)

func (*Factory) Override

func (f *Factory) Override(override interface{}) *Factory

Override set an override model for generated records. Values present in the override model will replace the ones in the generated records. This function expects a struct pointer as parameter. Returns the same instance of `Factory` so this method can be chained.

func (*Factory) Save

func (f *Factory) Save(count int) interface{}

Save generate a number of records using the given factory, insert them in the database and return the inserted records. The returned slice is a slice of the actual type of the generated records, meaning you can type-assert safely.

factory.Save(5).([]*User)

type Generator

type Generator func() interface{}

Generator a generator function generates a single record.

type IView added in v4.2.0

type IView interface {
	IsView() bool
}

IView models implementing this interface are identified as SQL views if IsView() returns true. Because records cannot be deleted from views, this is useful in test suites so `ClearDatabase()` doesn't try (and fails) to delete the records.

type Initializer

type Initializer func(*gorm.DB)

Initializer is a function meant to modify a connection settings at the global scope when it's created.

Use `db.InstantSet()` and not `db.Set()`, since the latter clones the gorm.DB instance instead of modifying it.

type Paginator

type Paginator struct {
	DB *gorm.DB `json:"-"`

	Records interface{} `json:"records"`

	MaxPage     int64 `json:"maxPage"`
	Total       int64 `json:"total"`
	PageSize    int   `json:"pageSize"`
	CurrentPage int   `json:"currentPage"`
	// contains filtered or unexported fields
}

Paginator structure containing pagination information and result records. Can be sent to the client directly.

func NewPaginator

func NewPaginator(db *gorm.DB, page, pageSize int, dest interface{}) *Paginator

NewPaginator create a new Paginator.

Given DB transaction can contain clauses already, such as WHERE, if you want to filter results.

articles := []model.Article{}
tx := database.Conn().Where("title LIKE ?", "%"+sqlutil.EscapeLike(search)+"%")
paginator := database.NewPaginator(tx, page, pageSize, &articles)
result := paginator.Find()
if response.HandleDatabaseError(result) {
    response.JSON(http.StatusOK, paginator)
}

func (*Paginator) Find

func (p *Paginator) Find() *gorm.DB

Find requests page information (total records and max page) and executes the transaction. The Paginate struct is updated automatically, as well as the destination slice given in NewPaginator().

func (*Paginator) Raw added in v4.1.0

func (p *Paginator) Raw(query string, vars []interface{}, countQuery string, countVars []interface{}) *Paginator

Raw set a raw SQL query and count query. The Paginator will execute the raw queries instead of automatically creating them. The raw query should not contain the "LIMIT" and "OFFSET" clauses, they will be added automatically. The count query should return a single number (`COUNT(*)` for example).

func (*Paginator) UpdatePageInfo

func (p *Paginator) UpdatePageInfo()

UpdatePageInfo executes count request to calculate the `Total` and `MaxPage`.

type View added in v4.2.0

type View struct{}

View helper implementing IView. Useful for composition inside models rather than implementing IView manually.

func (View) IsView added in v4.2.0

func (v View) IsView() bool

IsView always returns true.

Directories

Path Synopsis
dialect

Jump to

Keyboard shortcuts

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