db

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrJSONBNull = errors.New("jsonb: column is null")

ErrJSONBNull is returned by callers that explicitly want to reject NULL.

Functions

func ApplySort added in v0.1.1

func ApplySort(q *gorm.DB, req PageRequest, allowedSorts map[string]string) *gorm.DB

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 Exec

func Exec(ctx context.Context, db *gorm.DB, sql string, args ...any) error

func NewTxContext

func NewTxContext(ctx context.Context, tx *gorm.DB) context.Context

func Transaction

func Transaction(ctx context.Context, db *gorm.DB, fn func(tx *gorm.DB) error) error

Transaction wraps gorm.Transaction with a context-bound db.

func TxFromContext

func TxFromContext(ctx context.Context) (*gorm.DB, bool)

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

func NewDatabase(ctx context.Context, cfg DatabaseConfig, opts ...Option) (Database, error)

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

func (j JSONB[T]) MarshalJSON() ([]byte, error)

MarshalJSON returns the underlying value's JSON encoding.

func (JSONB[T]) MustGet added in v0.1.1

func (j JSONB[T]) MustGet() (T, error)

MustGet returns the underlying value or ErrJSONBNull when the column was NULL.

func (*JSONB[T]) Scan added in v0.1.1

func (j *JSONB[T]) Scan(src any) error

Scan implements sql.Scanner.

func (*JSONB[T]) UnmarshalJSON added in v0.1.1

func (j *JSONB[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON delegates to the underlying value.

func (JSONB[T]) Value added in v0.1.1

func (j JSONB[T]) Value() (driver.Value, error)

Value implements driver.Valuer.

type MySQL

type MySQL struct {
	DB    *gorm.DB
	SQLDB *sql.DB
	// contains filtered or unexported fields
}

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

func NewMySQL(ctx context.Context, cfg MySQLConfig, opts ...Option) (*MySQL, error)

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.

func (*MySQL) Close

func (m *MySQL) Close() error

Close releases the underlying connection pool.

func (*MySQL) Driver added in v0.1.1

func (m *MySQL) Driver() string

Driver returns "mysql".

func (*MySQL) GORM added in v0.1.1

func (m *MySQL) GORM() *gorm.DB

GORM returns the underlying *gorm.DB.

func (*MySQL) Ping

func (m *MySQL) Ping(ctx context.Context) error

Ping runs a health-check.

func (*MySQL) SQL added in v0.1.1

func (m *MySQL) SQL() *sql.DB

SQL returns the underlying *sql.DB.

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 WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger attaches a slog logger.

func WithMetrics

func WithMetrics(m *metrics.Metrics) Option

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

type Postgres struct {
	DB    *gorm.DB
	SQLDB *sql.DB
	// contains filtered or unexported fields
}

Postgres wraps a *gorm.DB opened against a Postgres backend.

func NewPostgres added in v0.1.1

func NewPostgres(ctx context.Context, cfg PostgresConfig, opts ...Option) (*Postgres, error)

NewPostgres opens a Postgres connection via gorm.io/driver/postgres (which itself uses jackc/pgx under the hood).

func (*Postgres) Close added in v0.1.1

func (p *Postgres) Close() error

Close releases the underlying connection pool.

func (*Postgres) Driver added in v0.1.1

func (p *Postgres) Driver() string

Driver returns "postgres".

func (*Postgres) GORM added in v0.1.1

func (p *Postgres) GORM() *gorm.DB

GORM returns the underlying *gorm.DB.

func (*Postgres) Ping added in v0.1.1

func (p *Postgres) Ping(ctx context.Context) error

Ping runs a health-check.

func (*Postgres) SQL added in v0.1.1

func (p *Postgres) SQL() *sql.DB

SQL returns the underlying *sql.DB.

type PostgresConfig added in v0.1.1

type PostgresConfig = DatabaseConfig

PostgresConfig is an alias for DatabaseConfig with postgres semantics.

type TxManager

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

func NewTxManager

func NewTxManager(db *gorm.DB, logger *slog.Logger) *TxManager

func (*TxManager) DB

func (m *TxManager) DB(ctx context.Context) *gorm.DB

func (*TxManager) WithTx

func (m *TxManager) WithTx(ctx context.Context, fn func(ctx context.Context, tx *gorm.DB) error) error

Jump to

Keyboard shortcuts

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