Documentation
¶
Index ¶
- Variables
- func ApplySort(q *gorm.DB, req PageRequest, allowedSorts map[string]string) *gorm.DB
- func EnsurePostgresDatabase(ctx context.Context, cfg PostgresConfig, opts ...Option) error
- func Exec(ctx context.Context, db *gorm.DB, sql string, args ...any) error
- func NewTxContext(ctx context.Context, tx *gorm.DB) context.Context
- func Transaction(ctx context.Context, db *gorm.DB, fn func(tx *gorm.DB) error) error
- func TxFromContext(ctx context.Context) (*gorm.DB, bool)
- type Database
- type DatabaseConfig
- type JSONB
- type MySQL
- type MySQLConfigdeprecated
- type Option
- type PageRequest
- type PageResult
- type Postgres
- type PostgresConfig
- type TxManager
Constants ¶
This section is empty.
Variables ¶
var ErrJSONBNull = errors.New("jsonb: column is null")
ErrJSONBNull is returned by callers that explicitly want to reject NULL.
Functions ¶
func EnsurePostgresDatabase ¶ added in v0.1.1
func EnsurePostgresDatabase(ctx context.Context, cfg PostgresConfig, opts ...Option) error
EnsurePostgresDatabase creates the configured target database if it does not already exist. It connects to cfg.MaintenanceDB, defaulting to "postgres".
func Transaction ¶
Transaction wraps gorm.Transaction with a context-bound db.
Types ¶
type Database ¶ added in v0.1.1
type Database interface {
// GORM returns the underlying *gorm.DB for query building.
GORM() *gorm.DB
// SQL returns the underlying *sql.DB for ping/close/pool control.
SQL() *sql.DB
// Driver returns the configured driver name, e.g. "mysql" or "postgres".
Driver() string
// Ping runs a health-check against the underlying connection.
Ping(ctx context.Context) error
// Close releases the underlying connection pool.
Close() error
}
Database is the backend-agnostic interface every concrete driver (MySQL, Postgres, ...) must satisfy. Runtime holds this interface and downstream code should depend on it, not on *MySQL or *Postgres directly.
func NewDatabase ¶ added in v0.1.1
NewDatabase is the backend-agnostic factory. It dispatches to NewMySQL or NewPostgres based on cfg.Driver and returns a Database interface.
type DatabaseConfig ¶ added in v0.1.1
type DatabaseConfig struct {
Driver string `json:"driver" yaml:"driver"`
DSN string `json:"dsn" yaml:"dsn"`
MaxOpenConns int `json:"max_open_conns" yaml:"max_open_conns"`
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns"`
ConnMaxLifetime string `json:"conn_max_lifetime" yaml:"conn_max_lifetime"`
SlowThreshold string `json:"slow_threshold" yaml:"slow_threshold"`
LogLevel string `json:"log_level" yaml:"log_level"`
// AutoCreateDatabase creates the target PostgreSQL database when it does not
// exist. It is intentionally implemented only for Postgres because MySQL DSN
// permissions and creation semantics vary widely between deployments.
AutoCreateDatabase bool `json:"auto_create_database" yaml:"auto_create_database"`
// AutoCreate is a legacy alias used by older Hub configs.
AutoCreate bool `json:"autoCreate" yaml:"autoCreate"`
// MaintenanceDB is the database used to run CREATE DATABASE for Postgres.
// Defaults to "postgres".
MaintenanceDB string `json:"maintenance_db" yaml:"maintenance_db"`
// Postgres-only options. Ignored when Driver != postgres.
// SearchPath is encoded into the connection DSN via the Postgres "options"
// runtime parameter so every pooled connection receives the same setting.
// Leave empty to use the server/default schema resolution, usually public.
SearchPath string `json:"search_path" yaml:"search_path"`
// SSLMode overrides the sslmode query-param. Only applied when the DSN does
// not already contain sslmode. Common values: disable, require, verify-ca,
// verify-full. Defaults to "disable" for dev convenience.
SSLMode string `json:"ssl_mode" yaml:"ssl_mode"`
}
DatabaseConfig is the backend-agnostic configuration. It is field-compatible with the legacy MySQLConfig so existing YAML/env still parses; new fields are added for postgres-specific options.
Driver selects the underlying gorm dialect. Supported values:
- "" / "mysql" -> gorm.io/driver/mysql
- "postgres" / "postgresql" / "pgx" -> gorm.io/driver/postgres
The DSN format follows the chosen driver's convention:
- mysql: "user:pass@tcp(host:3306)/dbname?charset=utf8mb4&parseTime=True"
- postgres: "host=localhost user=postgres password=postgres dbname=aihub port=5432 sslmode=disable" or a URL: "postgres://user:pass@host:5432/dbname?sslmode=disable"
func (DatabaseConfig) Normalize ¶ added in v0.1.1
func (c DatabaseConfig) Normalize() (string, error)
Normalize validates the driver name and returns the canonical form.
type JSONB ¶ added in v0.1.1
type JSONB[T any] struct { Data T // Null indicates whether the column value was SQL NULL on scan. // Set to true by Scan when the database returns NULL. Setting // Null=true before insert/updated causes GORM to write NULL. Null bool }
JSONB is a generic column type that marshals/unmarshals any Go value to/from a JSON column. It works with both Postgres JSONB and MySQL JSON columns.
Usage with GORM:
type Doc struct {
ID string `gorm:"primaryKey"`
Blob db.JSONB[Payload] `gorm:"type:jsonb"`
}
JSONB is safe to embed by value; do not embed by pointer unless you want the column to be NULL-able. An empty JSONB[T]{} marshals to the JSON literal `null`.
func (JSONB[T]) MarshalJSON ¶ added in v0.1.1
MarshalJSON returns the underlying value's JSON encoding.
func (JSONB[T]) MustGet ¶ added in v0.1.1
MustGet returns the underlying value or ErrJSONBNull when the column was NULL.
func (*JSONB[T]) UnmarshalJSON ¶ added in v0.1.1
UnmarshalJSON delegates to the underlying value.
type MySQL ¶
MySQL wraps a *gorm.DB opened against a MySQL backend.
It satisfies the Database interface so callers can keep using the concrete type or migrate to the interface uniformly.
func NewMySQL ¶
NewMySQL opens a MySQL connection via gorm.io/driver/mysql.
Behavior is unchanged from v0.1.0: cfg.Driver must be empty or "mysql", otherwise an error is returned. Use NewDatabase for driver dispatch.
type MySQLConfig
deprecated
type MySQLConfig = DatabaseConfig
MySQLConfig is retained for backward compatibility. It is now an alias for DatabaseConfig so existing YAML and code paths keep working.
Deprecated: prefer DatabaseConfig (which is the same type under a clearer name) for new code. New postgres-specific fields are accessible through the alias as well.
type Option ¶
type Option func(*options)
Option configures a Database constructor.
func WithMetrics ¶
WithMetrics attaches a metrics recorder for dependency observations.
type PageRequest ¶
type PageRequest struct {
Page int
PageSize int
// Sort is kept for trusted internal callers only. Do not pass raw HTTP input
// into Sort. Prefer SortBy + SortOrder with an allowed-column map.
Sort string
// SortBy is a logical external sort key, resolved through an allowlist.
SortBy string
// SortOrder supports "asc" or "desc". Any other value is treated as asc.
SortOrder string
}
func NormalizePage ¶
func NormalizePage(req PageRequest) PageRequest
type PageResult ¶
type PageResult[T any] struct { Items []T `json:"items"` Total int64 `json:"total"` Page int `json:"page"` PageSize int `json:"page_size"` }
func Paginate ¶
func Paginate[T any](query *gorm.DB, req PageRequest) (PageResult[T], error)
func PaginateSafe ¶ added in v0.1.1
func PaginateSafe[T any](query *gorm.DB, req PageRequest, allowedSorts map[string]string) (PageResult[T], error)
PaginateSafe applies sorting only when req.SortBy is present in allowedSorts. allowedSorts maps API-level sort keys to database column names, for example: map[string]string{"created_at": "created_at", "name": "name"}.
type Postgres ¶ added in v0.1.1
Postgres wraps a *gorm.DB opened against a Postgres backend.
func NewPostgres ¶ added in v0.1.1
NewPostgres opens a Postgres connection via gorm.io/driver/postgres (which itself uses jackc/pgx under the hood).
type PostgresConfig ¶ added in v0.1.1
type PostgresConfig = DatabaseConfig
PostgresConfig is an alias for DatabaseConfig with postgres semantics.