Documentation ¶
Index ¶
- func New(cfg *config.Config, logger func() *slog.Logger) (*gorm.DB, error)
- func NewFromDialector(cfg *config.Config, logger func() *slog.Logger, dialector gorm.Dialector) (*gorm.DB, error)
- func RegisterDialect(name, template string, initializer DialectorInitializer)
- type DialectorInitializer
- type Factory
- type Logger
- func (l Logger) Error(ctx context.Context, msg string, data ...any)
- func (l Logger) Info(ctx context.Context, msg string, data ...any)
- func (l *Logger) LogMode(_ logger.LogLevel) logger.Interface
- func (l Logger) Trace(ctx context.Context, begin time.Time, ...)
- func (l Logger) Warn(ctx context.Context, msg string, data ...any)
- type Paginator
- type PaginatorDTO
- type TimeoutPlugin
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func New ¶
New create a new connection pool using the settings defined in the given configuration.
In order to use a specific driver / dialect ("mysql", "sqlite3", ...), you must not forget to blank-import it in your main file.
import _ "goyave.dev/goyave/v5/database/dialect/mysql" import _ "goyave.dev/goyave/v5/database/dialect/postgres" import _ "goyave.dev/goyave/v5/database/dialect/sqlite" import _ "goyave.dev/goyave/v5/database/dialect/mssql" import _ "goyave.dev/goyave/v5/database/dialect/clickhouse"
func NewFromDialector ¶
func NewFromDialector(cfg *config.Config, logger func() *slog.Logger, dialector gorm.Dialector) (*gorm.DB, error)
NewFromDialector create a new connection pool from a gorm dialector and using the settings defined in the given configuration.
This can be used in tests to create a mock connection pool.
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}
Types ¶
type DialectorInitializer ¶
DialectorInitializer function initializing a GORM Dialector using the given data source name (DSN).
type Factory ¶
Factory an object used to generate records or seed the database.
func NewFactory ¶
NewFactory create a new Factory. The given generator function will be used to generate records.
type Logger ¶
type Logger struct { // SlowThreshold defines the minimum query execution time to be considered "slow". // If a query takes more time than `SlowThreshold`, the query will be logged at the WARN level. // If 0, disables query execution time checking. SlowThreshold time.Duration // contains filtered or unexported fields }
Logger adapter between `*slog.Logger` and GORM's logger.
func NewLogger ¶
NewLogger create a new `Logger` adapter between GORM and `*slog.Logger`. Use a `SlowThreshold` of 200ms.
func (*Logger) LogMode ¶
LogMode returns a copy of this logger. The level argument actually has no effect as it is handled by the underlying `*slog.Logger`.
type Paginator ¶
type Paginator[T any] struct { DB *gorm.DB `json:"-"` Records *[]T `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.
func NewPaginator ¶
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 := db.Where("title LIKE ?", "%"+sqlutil.EscapeLike(search)+"%") paginator := database.NewPaginator(tx, page, pageSize, &articles) err := paginator.Find() if response.WriteDBError(err) { return } response.JSON(http.StatusOK, paginator)
func (*Paginator[T]) Find ¶
Find requests page information (total records and max page) if not already fetched using `UpdatePageInfo()` and executes the query. The `Paginator` struct is updated automatically, as well as the destination slice given in `NewPaginator()`.
The two queries are executed inside a transaction.
func (*Paginator[T]) Raw ¶
func (p *Paginator[T]) Raw(query string, vars []any, countQuery string, countVars []any) *Paginator[T]
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[T]) UpdatePageInfo ¶
UpdatePageInfo executes count request to calculate the `Total` and `MaxPage`. When calling this function manually, it is advised to use a transaction that is calling `Find()` too, to avoid inconsistencies.
type PaginatorDTO ¶
type PaginatorDTO[T any] struct { Records []T `json:"records"` MaxPage int64 `json:"maxPage"` Total int64 `json:"total"` PageSize int `json:"pageSize"` CurrentPage int `json:"currentPage"` }
PaginatorDTO structure sent to clients as a response.
type TimeoutPlugin ¶
TimeoutPlugin GORM plugin adding a default timeout to SQL queries if none is applied on the statement already. It works by replacing the statement's context with a child context having the configured timeout. The context is replaced in a "before" callback on all GORM operations. In a "after" callback, the new context is canceled.
The `ReadTimeout` is applied on the `Query` and `Raw` GORM callbacks. The `WriteTimeout` is applied on the rest of the callbacks.
Supports all GORM operations except `Scan()`.
A timeout duration inferior or equal to 0 disables the plugin for the relevant operations.
func (*TimeoutPlugin) Initialize ¶
func (p *TimeoutPlugin) Initialize(db *gorm.DB) error
Initialize registers the callbacks for all operations.
func (*TimeoutPlugin) Name ¶
func (p *TimeoutPlugin) Name() string
Name returns the name of the plugin