Documentation
¶
Index ¶
- func EagerLoadMany[T any, R any](ctx context.Context, kn *KintsNorm, parents []*T, getParentID func(*T) any, ...) error
- func LazyLoadMany[R any](ctx context.Context, kn *KintsNorm, parentID any, childForeignKey string) ([]*R, error)
- func QuoteIdentifier(identifier string) string
- type AfterCreate
- type AfterDelete
- type AfterPurgeTrashed
- type AfterRestore
- type AfterSoftDelete
- type AfterUpdate
- type AfterUpsert
- type BeforeCreate
- type BeforeDelete
- type BeforePurgeTrashed
- type BeforeRestore
- type BeforeSoftDelete
- type BeforeUpdate
- type BeforeUpsert
- type Cache
- type Condition
- func And(conds ...Condition) Condition
- func Between(col string, start any, end any) Condition
- func DateRange(col string, from, to time.Time) Condition
- func Eq(col string, v any) Condition
- func Ge(col string, v any) Condition
- func Gt(col string, v any) Condition
- func In(col string, vals []any) Condition
- func Le(col string, v any) Condition
- func Lt(col string, v any) Condition
- func Ne(col string, v any) Condition
- func OnDate(col string, day time.Time) Condition
- func Or(conds ...Condition) Condition
- func RawCond(expr string, args ...any) Condition
- type Config
- type ErrorCode
- type ExpvarMetrics
- type Field
- type KintsNorm
- func (kn *KintsNorm) AutoMigrate(models ...any) error
- func (kn *KintsNorm) AutoMigrateWithOptions(ctx context.Context, opts migration.ApplyOptions, models ...any) error
- func (kn *KintsNorm) Close() error
- func (kn *KintsNorm) Health(ctx context.Context) error
- func (kn *KintsNorm) MigrateDownDir(ctx context.Context, dir string, steps int) error
- func (kn *KintsNorm) MigrateUpDir(ctx context.Context, dir string) error
- func (kn *KintsNorm) Model(model any) *QueryBuilder
- func (kn *KintsNorm) Pool() *pgxpool.Pool
- func (kn *KintsNorm) Query() *QueryBuilder
- func (kn *KintsNorm) QueryRead() *QueryBuilder
- func (kn *KintsNorm) ReadPool() *pgxpool.Pool
- func (kn *KintsNorm) SetManualMigrationOptions(opts migration.ManualOptions)
- func (kn *KintsNorm) Tx() TxManager
- type LogMode
- type Logger
- type Metrics
- type NoopCache
- type NoopLogger
- type NoopMetrics
- type ORMError
- type Option
- func WithCache(c Cache) Option
- func WithLogContextFields(fn func(ctx context.Context) []Field) Option
- func WithLogMode(mode LogMode) Option
- func WithLogParameterMasking(mask bool) Option
- func WithLogger(l Logger) Option
- func WithMetrics(m Metrics) Option
- func WithSlowQueryThreshold(threshold time.Duration) Option
- type Page
- type PageRequest
- type QueryBuilder
- func (qb *QueryBuilder) After(column string, value any) *QueryBuilder
- func (qb *QueryBuilder) Before(column string, value any) *QueryBuilder
- func (qb *QueryBuilder) CrossJoin(table string) *QueryBuilder
- func (qb *QueryBuilder) Debug() *QueryBuilder
- func (qb *QueryBuilder) Delete(ctx context.Context) (int64, error)
- func (qb *QueryBuilder) DoUpdateSet(setExpr string, args ...any) *QueryBuilder
- func (qb *QueryBuilder) Exec(ctx context.Context) error
- func (qb *QueryBuilder) ExecInsert(ctx context.Context, dest any) (int64, error)
- func (qb *QueryBuilder) ExecUpdate(ctx context.Context, dest any) (int64, error)
- func (qb *QueryBuilder) Find(ctx context.Context, dest any) error
- func (qb *QueryBuilder) First(ctx context.Context, dest any) error
- func (qb *QueryBuilder) FullJoin(table, on string) *QueryBuilder
- func (qb *QueryBuilder) HardDelete() *QueryBuilder
- func (qb *QueryBuilder) InnerJoin(table, on string) *QueryBuilder
- func (qb *QueryBuilder) Insert(columns ...string) *QueryBuilder
- func (qb *QueryBuilder) InsertStruct(ctx context.Context, entity any) (int64, error)
- func (qb *QueryBuilder) Join(table, on string) *QueryBuilder
- func (qb *QueryBuilder) Last(ctx context.Context, dest any) error
- func (qb *QueryBuilder) LeftJoin(table, on string) *QueryBuilder
- func (qb *QueryBuilder) Limit(n int) *QueryBuilder
- func (qb *QueryBuilder) Model(model any) *QueryBuilder
- func (qb *QueryBuilder) Offset(n int) *QueryBuilder
- func (qb *QueryBuilder) OnConflict(cols ...string) *QueryBuilder
- func (qb *QueryBuilder) OnlyTrashed() *QueryBuilder
- func (qb *QueryBuilder) OrderBy(ob string) *QueryBuilder
- func (qb *QueryBuilder) Raw(sql string, args ...any) *QueryBuilder
- func (qb *QueryBuilder) RawNamed(sql string, namedArgs map[string]any) *QueryBuilder
- func (qb *QueryBuilder) Returning(cols ...string) *QueryBuilder
- func (qb *QueryBuilder) RightJoin(table, on string) *QueryBuilder
- func (qb *QueryBuilder) Select(columns ...string) *QueryBuilder
- func (qb *QueryBuilder) SelectQ(columns ...string) *QueryBuilder
- func (qb *QueryBuilder) SelectQI(columns ...string) *QueryBuilder
- func (qb *QueryBuilder) Set(setExpr string, args ...any) *QueryBuilder
- func (qb *QueryBuilder) Table(name string) *QueryBuilder
- func (qb *QueryBuilder) TableQ(name string) *QueryBuilder
- func (qb *QueryBuilder) Unscoped() *QueryBuilder
- func (qb *QueryBuilder) UpdateStructByPK(ctx context.Context, entity any, pkColumn string) (int64, error)
- func (qb *QueryBuilder) UsePrimary() *QueryBuilder
- func (qb *QueryBuilder) UseReadPool() *QueryBuilder
- func (qb *QueryBuilder) Values(values ...any) *QueryBuilder
- func (qb *QueryBuilder) ValuesRows(rows [][]any) *QueryBuilder
- func (qb *QueryBuilder) Where(condition string, args ...any) *QueryBuilder
- func (qb *QueryBuilder) WhereCond(c Condition) *QueryBuilder
- func (qb *QueryBuilder) WhereNamed(condition string, namedArgs map[string]any) *QueryBuilder
- func (qb *QueryBuilder) WithCacheKey(key string, ttl time.Duration) *QueryBuilder
- func (qb *QueryBuilder) WithInvalidateKeys(keys ...string) *QueryBuilder
- func (qb *QueryBuilder) WithTrashed() *QueryBuilder
- type Repository
- type StdLogger
- type Transaction
- type TxManager
- type TxOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func EagerLoadMany ¶
func EagerLoadMany[T any, R any](ctx context.Context, kn *KintsNorm, parents []*T, getParentID func(*T) any, childForeignKey string, set func(parent *T, children []*R)) error
EagerLoadMany loads related rows of type R for the given parents of type T using childForeignKey. getParentID extracts the parent id used to match against childForeignKey. It groups children by childForeignKey matching each parent's id and invokes set(parent, children).
func LazyLoadMany ¶
func LazyLoadMany[R any](ctx context.Context, kn *KintsNorm, parentID any, childForeignKey string) ([]*R, error)
LazyLoadMany loads children by a single parent ID via childForeignKey
func QuoteIdentifier ¶
QuoteIdentifier safely quotes a SQL identifier by wrapping in double quotes and escaping embedded quotes
Types ¶
type AfterCreate ¶
AfterCreate can be implemented by a model to run logic after insert
type AfterPurgeTrashed ¶
type AfterSoftDelete ¶
type AfterUpdate ¶
AfterUpdate can be implemented by a model to run logic after update
type AfterUpsert ¶
AfterUpsert can be implemented by a model to run logic after upsert
type BeforeCreate ¶
BeforeCreate can be implemented by a model to run logic before insert
type BeforeDelete ¶
Delete hooks
type BeforePurgeTrashed ¶
PurgeTrashed hooks
type BeforeRestore ¶
Restore hooks
type BeforeSoftDelete ¶
SoftDelete hooks
type BeforeUpdate ¶
BeforeUpdate can be implemented by a model to run logic before update
type BeforeUpsert ¶
BeforeUpsert can be implemented by a model to run logic before upsert
type Cache ¶
type Cache interface { Get(ctx context.Context, key string) ([]byte, bool, error) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error Invalidate(ctx context.Context, keys ...string) error }
Cache provides optional read-through/write-through hooks
type Condition ¶
type Config ¶
type Config struct { Host string Port int Database string Username string Password string SSLMode string MaxConnections int32 MinConnections int32 MaxConnLifetime time.Duration MaxConnIdleTime time.Duration HealthCheckPeriod time.Duration ConnectTimeout time.Duration ApplicationName string ReadOnlyConnString string // optional DSN for read replica(s) RetryAttempts int // transient error retries (default 0 = no retry) RetryBackoff time.Duration // backoff between retries StatementCacheCapacity int // pgx per-conn statement cache capacity (0 = default) // Circuit breaker CircuitBreakerEnabled bool CircuitFailureThreshold int // consecutive failures to open the circuit (default 5 if 0) CircuitOpenTimeout time.Duration // how long to stay open before half-open trial (default 30s if 0) CircuitHalfOpenMaxCalls int // allowed concurrent trial calls in half-open (default 1 if 0) }
Config holds database and runtime configuration for Kints-Norm
func (*Config) ConnString ¶
ConnString returns a PostgreSQL connection string compatible with pgx
type ExpvarMetrics ¶
type ExpvarMetrics struct{}
ExpvarMetrics is a simple stdlib adapter using expvar to expose counters/gauges It is intended as a minimal example adapter; for production use prefer Prometheus/OpenTelemetry. Avoids extra dependencies.
func (ExpvarMetrics) CircuitStateChanged ¶
func (ExpvarMetrics) CircuitStateChanged(state string)
func (ExpvarMetrics) ConnectionCount ¶
func (ExpvarMetrics) ConnectionCount(active, idle int32)
func (ExpvarMetrics) ErrorCount ¶
func (ExpvarMetrics) ErrorCount(errorType string)
func (ExpvarMetrics) QueryDuration ¶
func (ExpvarMetrics) QueryDuration(duration time.Duration, _ string)
type KintsNorm ¶
type KintsNorm struct {
// contains filtered or unexported fields
}
KintsNorm is the main ORM entry point
func NewWithConnString ¶
NewWithConnString creates a new KintsNorm instance from a full pgx connection string
func (*KintsNorm) AutoMigrate ¶
AutoMigrate runs schema migrations for given models
func (*KintsNorm) AutoMigrateWithOptions ¶
func (kn *KintsNorm) AutoMigrateWithOptions(ctx context.Context, opts migration.ApplyOptions, models ...any) error
AutoMigrateWithOptions allows enabling destructive ops (e.g., drop columns)
func (*KintsNorm) MigrateDownDir ¶
MigrateDownDir rolls back the last N migrations using .down.sql files
func (*KintsNorm) MigrateUpDir ¶
MigrateUpDir applies pending .up.sql migrations from a directory
func (*KintsNorm) Model ¶
func (kn *KintsNorm) Model(model any) *QueryBuilder
Model initializes a new query builder and sets its table name inferred from the provided model type. Usage: kn.Model(&User{}).Where("id = ?", 1).First(ctx, &u)
func (*KintsNorm) Query ¶
func (kn *KintsNorm) Query() *QueryBuilder
Query creates a new query builder
func (*KintsNorm) QueryRead ¶
func (kn *KintsNorm) QueryRead() *QueryBuilder
QueryRead uses the read pool for building queries (falls back to primary)
func (*KintsNorm) ReadPool ¶
ReadPool exposes the read-only replica pool if configured, otherwise returns the primary pool
func (*KintsNorm) SetManualMigrationOptions ¶
func (kn *KintsNorm) SetManualMigrationOptions(opts migration.ManualOptions)
SetManualMigrationOptions configures safety gates for manual file-based migrations
type LogMode ¶
type LogMode int
LogMode controls verbosity of ORM logging
const ( // LogSilent disables all logs unless a chain explicitly enables debug LogSilent LogMode = iota // LogError logs only errors LogError // LogWarn logs warnings and errors (unused for now but reserved) LogWarn // LogInfo logs queries and errors LogInfo // LogDebug logs everything at debug level LogDebug )
type NoopCache ¶
type NoopCache struct{}
NoopCache is a default no-op cache implementation
func (NoopCache) Invalidate ¶
type NoopLogger ¶
type NoopLogger struct{}
NoopLogger is a default no-op logger
func (NoopLogger) Debug ¶
func (NoopLogger) Debug(msg string, fields ...Field)
func (NoopLogger) Error ¶
func (NoopLogger) Error(msg string, fields ...Field)
func (NoopLogger) Info ¶
func (NoopLogger) Info(msg string, fields ...Field)
func (NoopLogger) Warn ¶
func (NoopLogger) Warn(msg string, fields ...Field)
type NoopMetrics ¶
type NoopMetrics struct{}
NoopMetrics is a default no-op metrics collector
func (NoopMetrics) CircuitStateChanged ¶
func (NoopMetrics) CircuitStateChanged(state string)
func (NoopMetrics) ConnectionCount ¶
func (NoopMetrics) ConnectionCount(active, idle int32)
func (NoopMetrics) ErrorCount ¶
func (NoopMetrics) ErrorCount(errorType string)
func (NoopMetrics) QueryDuration ¶
func (NoopMetrics) QueryDuration(duration time.Duration, query string)
type Option ¶
type Option func(*options)
func WithLogContextFields ¶
WithLogContextFields registers a function to derive structured log fields from context (e.g. correlation/request IDs)
func WithLogMode ¶
WithLogMode sets global logging mode similar to GORM's LogMode
func WithLogParameterMasking ¶
WithLogParameterMasking masks SQL parameters in logs (hides args and avoids inlining into stmt)
func WithLogger ¶
func WithMetrics ¶
func WithSlowQueryThreshold ¶
WithSlowQueryThreshold enables slow query logging when duration exceeds threshold
type PageRequest ¶
type PageRequest struct { Limit int Offset int OrderBy string // e.g., "id ASC" or "created_at DESC" }
PageRequest describes pagination and ordering
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder provides a fluent API for building SQL queries
func (*QueryBuilder) After ¶
func (qb *QueryBuilder) After(column string, value any) *QueryBuilder
Keyset pagination helpers
func (*QueryBuilder) Before ¶
func (qb *QueryBuilder) Before(column string, value any) *QueryBuilder
func (*QueryBuilder) CrossJoin ¶
func (qb *QueryBuilder) CrossJoin(table string) *QueryBuilder
CrossJoin appends a CROSS JOIN clause (no ON condition)
func (*QueryBuilder) Debug ¶
func (qb *QueryBuilder) Debug() *QueryBuilder
Debug enables debug logging for this builder chain regardless of global LogMode
func (*QueryBuilder) Delete ¶
func (qb *QueryBuilder) Delete(ctx context.Context) (int64, error)
Delete executes a DELETE FROM ... WHERE ... and returns rows affected
func (*QueryBuilder) DoUpdateSet ¶
func (qb *QueryBuilder) DoUpdateSet(setExpr string, args ...any) *QueryBuilder
func (*QueryBuilder) Exec ¶
func (qb *QueryBuilder) Exec(ctx context.Context) error
Exec executes a raw statement
func (*QueryBuilder) ExecInsert ¶
func (*QueryBuilder) ExecUpdate ¶
func (*QueryBuilder) Find ¶
func (qb *QueryBuilder) Find(ctx context.Context, dest any) error
Find runs the query and scans into dest (slice pointer)
func (*QueryBuilder) First ¶
func (qb *QueryBuilder) First(ctx context.Context, dest any) error
First applies LIMIT 1 and scans the first row into dest (pointer to struct or *[]map[string]any with length 1)
func (*QueryBuilder) FullJoin ¶
func (qb *QueryBuilder) FullJoin(table, on string) *QueryBuilder
FullJoin appends a FULL JOIN clause
func (*QueryBuilder) HardDelete ¶
func (qb *QueryBuilder) HardDelete() *QueryBuilder
HardDelete opts into hard delete for this builder chain
func (*QueryBuilder) InnerJoin ¶
func (qb *QueryBuilder) InnerJoin(table, on string) *QueryBuilder
InnerJoin appends an INNER JOIN clause (alias of Join)
func (*QueryBuilder) Insert ¶
func (qb *QueryBuilder) Insert(columns ...string) *QueryBuilder
Insert builder
func (*QueryBuilder) InsertStruct ¶
InsertStruct inserts a struct using its `db` tags. Zero values with default: tag are skipped to allow DB defaults
func (*QueryBuilder) Join ¶
func (qb *QueryBuilder) Join(table, on string) *QueryBuilder
func (*QueryBuilder) Last ¶
func (qb *QueryBuilder) Last(ctx context.Context, dest any) error
Last requires an explicit OrderBy to be set; applies LIMIT 1 and returns the last row per ordering
func (*QueryBuilder) LeftJoin ¶
func (qb *QueryBuilder) LeftJoin(table, on string) *QueryBuilder
LeftJoin appends a LEFT JOIN clause
func (*QueryBuilder) Limit ¶
func (qb *QueryBuilder) Limit(n int) *QueryBuilder
func (*QueryBuilder) Model ¶
func (qb *QueryBuilder) Model(model any) *QueryBuilder
Model sets the table name by inferring it from a provided model type/value. It follows the same convention used by the repository: snake_case(type name) + "s". Examples:
qb.Model(&User{}) qb.Model(User{})
func (*QueryBuilder) Offset ¶
func (qb *QueryBuilder) Offset(n int) *QueryBuilder
func (*QueryBuilder) OnConflict ¶
func (qb *QueryBuilder) OnConflict(cols ...string) *QueryBuilder
func (*QueryBuilder) OnlyTrashed ¶
func (qb *QueryBuilder) OnlyTrashed() *QueryBuilder
OnlyTrashed restricts to only soft-deleted rows (deleted_at IS NOT NULL)
func (*QueryBuilder) OrderBy ¶
func (qb *QueryBuilder) OrderBy(ob string) *QueryBuilder
func (*QueryBuilder) Raw ¶
func (qb *QueryBuilder) Raw(sql string, args ...any) *QueryBuilder
func (*QueryBuilder) RawNamed ¶
func (qb *QueryBuilder) RawNamed(sql string, namedArgs map[string]any) *QueryBuilder
RawNamed sets a raw SQL with :name placeholders
func (*QueryBuilder) Returning ¶
func (qb *QueryBuilder) Returning(cols ...string) *QueryBuilder
func (*QueryBuilder) RightJoin ¶
func (qb *QueryBuilder) RightJoin(table, on string) *QueryBuilder
RightJoin appends a RIGHT JOIN clause
func (*QueryBuilder) Select ¶
func (qb *QueryBuilder) Select(columns ...string) *QueryBuilder
func (*QueryBuilder) SelectQ ¶
func (qb *QueryBuilder) SelectQ(columns ...string) *QueryBuilder
SelectQ appends quoted column identifiers
func (*QueryBuilder) SelectQI ¶
func (qb *QueryBuilder) SelectQI(columns ...string) *QueryBuilder
SelectQI appends fully quoted identifiers as-is (does not split on '.') Useful for columns that themselves contain dots in their names
func (*QueryBuilder) Set ¶
func (qb *QueryBuilder) Set(setExpr string, args ...any) *QueryBuilder
Update builder (simple form): provide SET expr and args
func (*QueryBuilder) Table ¶
func (qb *QueryBuilder) Table(name string) *QueryBuilder
func (*QueryBuilder) TableQ ¶
func (qb *QueryBuilder) TableQ(name string) *QueryBuilder
TableQ sets the table using quoted identifier(s) (supports schema-qualified like schema.table)
func (*QueryBuilder) Unscoped ¶
func (qb *QueryBuilder) Unscoped() *QueryBuilder
Unscoped is an alias of WithTrashed (GORM-compatible naming)
func (*QueryBuilder) UpdateStructByPK ¶
func (qb *QueryBuilder) UpdateStructByPK(ctx context.Context, entity any, pkColumn string) (int64, error)
UpdateStructByPK updates a row by its primary key using `db` tags
func (*QueryBuilder) UsePrimary ¶
func (qb *QueryBuilder) UsePrimary() *QueryBuilder
UsePrimary routes subsequent calls (Query/Find/First/Last) through the primary pool (overrides auto read routing)
func (*QueryBuilder) UseReadPool ¶
func (qb *QueryBuilder) UseReadPool() *QueryBuilder
UseReadPool forces using the read pool for reads even if no auto routing is enabled Note: Do not use this for writes; Exec/insert/update/delete should go to primary
func (*QueryBuilder) Values ¶
func (qb *QueryBuilder) Values(values ...any) *QueryBuilder
func (*QueryBuilder) ValuesRows ¶
func (qb *QueryBuilder) ValuesRows(rows [][]any) *QueryBuilder
func (*QueryBuilder) Where ¶
func (qb *QueryBuilder) Where(condition string, args ...any) *QueryBuilder
func (*QueryBuilder) WhereCond ¶
func (qb *QueryBuilder) WhereCond(c Condition) *QueryBuilder
WhereCond adds a typed Condition built by helpers in conditions.go
func (*QueryBuilder) WhereNamed ¶
func (qb *QueryBuilder) WhereNamed(condition string, namedArgs map[string]any) *QueryBuilder
WhereNamed adds a WHERE clause with named parameters, converting :name to $n and appending args by map order
func (*QueryBuilder) WithCacheKey ¶
func (qb *QueryBuilder) WithCacheKey(key string, ttl time.Duration) *QueryBuilder
WithCacheKey enables read-through caching for Find/First on this builder. TTL<=0 means no Set.
func (*QueryBuilder) WithInvalidateKeys ¶
func (qb *QueryBuilder) WithInvalidateKeys(keys ...string) *QueryBuilder
WithInvalidateKeys sets keys to invalidate after write operations (Exec/Insert/Update/Delete)
func (*QueryBuilder) WithTrashed ¶
func (qb *QueryBuilder) WithTrashed() *QueryBuilder
WithTrashed includes soft-deleted rows (deleted_at IS NOT NULL or NULL) in results
type Repository ¶
type Repository[T any] interface { Create(ctx context.Context, entity *T) error CreateBatch(ctx context.Context, entities []*T) error GetByID(ctx context.Context, id any) (*T, error) Update(ctx context.Context, entity *T) error UpdatePartial(ctx context.Context, id any, fields map[string]any) error Delete(ctx context.Context, id any) error SoftDelete(ctx context.Context, id any) error SoftDeleteAll(ctx context.Context) (int64, error) Restore(ctx context.Context, id any) error PurgeTrashed(ctx context.Context) (int64, error) Find(ctx context.Context, conditions ...Condition) ([]*T, error) FindOne(ctx context.Context, conditions ...Condition) (*T, error) Count(ctx context.Context, conditions ...Condition) (int64, error) Exists(ctx context.Context, conditions ...Condition) (bool, error) WithTrashed() Repository[T] OnlyTrashed() Repository[T] FindPage(ctx context.Context, page PageRequest, conditions ...Condition) (Page[T], error) CreateCopyFrom(ctx context.Context, entities []*T, columns ...string) (int64, error) Upsert(ctx context.Context, entity *T, conflictCols []string, updateCols []string) error }
Repository defines generic CRUD operations for type T
func NewRepository ¶
func NewRepository[T any](kn *KintsNorm) Repository[T]
NewRepository creates a new generic repository
func NewRepositoryWithExecutor ¶
func NewRepositoryWithExecutor[T any](kn *KintsNorm, exec dbExecuter) Repository[T]
NewRepositoryWithExecutor creates a repository bound to a specific executor (pool or tx)
type Transaction ¶
type Transaction interface { Commit(ctx context.Context) error Rollback(ctx context.Context) error Repository() Repository[map[string]any] Exec() dbExecuter Query() *QueryBuilder }
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
blog
command
|
|
composite_unique
command
|
|
decimal
command
|
|
fk_actions
command
|
|
ignore_field
command
|
|
index_partial
command
|
|
keyset_pagination
command
|
|
observability
command
|
|
soft_delete
command
|
|
tx
command
|
|
uuid
command
|
|
internal
|
|