Documentation
¶
Index ¶
- Variables
- func RegisterSchema[T any](schema Schema[T])
- func ResolveColumnNames(args []clause.Columnar) []string
- type AfterCreateInterface
- type AfterDeleteInterface
- type AfterUpdateInterface
- type BeforeCreateInterface
- type BeforeDeleteInterface
- type BeforeUpdateInterface
- type Dialect
- type Executor
- type JSON
- type Metrics
- type MySQLDialect
- type ObservabilityConfig
- type OrderBuilder
- type PK
- type PostgreSQLDialect
- type QueryBuilder
- func (q *QueryBuilder[T]) Avg(ctx context.Context, column clause.Columnar) (float64, error)
- func (q *QueryBuilder[T]) Count(ctx context.Context) (int64, error)
- func (q *QueryBuilder[T]) Find(ctx context.Context) ([]*T, error)
- func (q *QueryBuilder[T]) First(ctx context.Context) (*T, error)
- func (q *QueryBuilder[T]) GroupBy(columns ...clause.Columnar) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Having(expr clause.Expression) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Join(table string, on clause.Expression) *QueryBuilder[T]
- func (q *QueryBuilder[T]) LeftJoin(table string, on clause.Expression) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Limit(n uint64) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Max(ctx context.Context, column clause.Columnar) (any, error)
- func (q *QueryBuilder[T]) Min(ctx context.Context, column clause.Columnar) (any, error)
- func (q *QueryBuilder[T]) Offset(n uint64) *QueryBuilder[T]
- func (q *QueryBuilder[T]) OrderBy(orders ...OrderBuilder) *QueryBuilder[T]
- func (q *QueryBuilder[T]) RightJoin(table string, on clause.Expression) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Scan(ctx context.Context, dest any) error
- func (q *QueryBuilder[T]) Select(columns ...clause.Columnar) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Sum(ctx context.Context, column clause.Columnar) (float64, error)
- func (q *QueryBuilder[T]) Where(expr clause.Expression) *QueryBuilder[T]
- func (q *QueryBuilder[T]) WithBuilder(fn func(b sq.SelectBuilder) sq.SelectBuilder) *QueryBuilder[T]
- type Repository
- func (r *Repository[T]) BatchCreate(ctx context.Context, models []*T) error
- func (r *Repository[T]) Create(ctx context.Context, model *T) error
- func (r *Repository[T]) Delete(ctx context.Context, id any) error
- func (r *Repository[T]) DeleteModel(ctx context.Context, model *T) error
- func (r *Repository[T]) FindOne(ctx context.Context, id any) (*T, error)
- func (r *Repository[T]) Query() *QueryBuilder[T]
- func (r *Repository[T]) Update(ctx context.Context, model *T) error
- func (r *Repository[T]) UpdateColumns(ctx context.Context, id any, assignments ...clause.Assignment) error
- func (r *Repository[T]) Upsert(ctx context.Context, model *T, opts ...UpsertOption) error
- func (r *Repository[T]) Where(conds ...clause.Expression) *Repository[T]
- type SQLiteDialect
- type Schema
- type Session
- func (s *Session) Begin(ctx context.Context) (*Session, error)
- func (s *Session) Commit() error
- func (s *Session) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (s *Session) Get(ctx context.Context, dest any, query string, args ...any) error
- func (s *Session) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (s *Session) QueryRow(ctx context.Context, query string, args ...any) *sql.Row
- func (s *Session) Rollback() error
- func (s *Session) Select(ctx context.Context, dest any, query string, args ...any) error
- func (s *Session) Transaction(ctx context.Context, fn func(txSession *Session) error) (err error)
- type SessionOption
- func WithDefaultMeter() SessionOption
- func WithDefaultTracer() SessionOption
- func WithLogger(logger *slog.Logger) SessionOption
- func WithMeter(meter metric.Meter) SessionOption
- func WithQueryLogging(enabled bool) SessionOption
- func WithSlowQueryThreshold(d time.Duration) SessionOption
- func WithTracer(tracer trace.Tracer) SessionOption
- type UpsertOption
Constants ¶
This section is empty.
Variables ¶
var ErrNotFound = errors.New("orm: record not found")
Functions ¶
func RegisterSchema ¶
func ResolveColumnNames ¶
ResolveColumnNames extracts column names from types implementing clause.Columnar.
Types ¶
type AfterCreateInterface ¶
type AfterDeleteInterface ¶
type AfterUpdateInterface ¶
type BeforeCreateInterface ¶
Lifecycle Interfaces
type BeforeDeleteInterface ¶
type BeforeUpdateInterface ¶
type Dialect ¶
type Dialect interface {
Name() string
PlaceholderFormat() sq.PlaceholderFormat
UpsertClause(tableName string, conflictCols []string, updateCols []string) string
}
Dialect abstracts database-specific SQL features
type Executor ¶
type Executor interface {
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
SelectContext(ctx context.Context, dest any, query string, args ...any) error
GetContext(ctx context.Context, dest any, query string, args ...any) error
}
Executor defines the common database operations for both DB and Tx
type JSON ¶
type JSON[T any] struct { Data T }
JSON is a generic wrapper for handling JSON fields in database. It implements sql.Scanner and driver.Valuer.
Usage:
type User struct {
Metadata sqlc.JSON[UserMetadata] `db:"metadata"`
}
// Access data
user.Metadata.Data.Initial = "V"
func (JSON[T]) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*JSON[T]) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type Metrics ¶
type Metrics struct {
QueryCount metric.Int64Counter
QueryDuration metric.Float64Histogram
QueryErrors metric.Int64Counter
}
Metrics holds the OpenTelemetry metric instruments
type MySQLDialect ¶
type MySQLDialect struct{}
func (*MySQLDialect) Name ¶
func (d *MySQLDialect) Name() string
func (*MySQLDialect) PlaceholderFormat ¶
func (d *MySQLDialect) PlaceholderFormat() sq.PlaceholderFormat
func (*MySQLDialect) UpsertClause ¶
func (d *MySQLDialect) UpsertClause(tableName string, conflictCols []string, updateCols []string) string
type ObservabilityConfig ¶
type ObservabilityConfig struct {
Logger *slog.Logger
Tracer trace.Tracer
Meter metric.Meter
Metrics *Metrics
SlowQueryThreshold time.Duration
LogQueries bool // Log all queries (debug mode)
}
ObservabilityConfig holds logging, tracing, and metrics configuration
type OrderBuilder ¶
type OrderBuilder interface {
Build() string
}
type PostgreSQLDialect ¶
type PostgreSQLDialect struct{}
func (*PostgreSQLDialect) Name ¶
func (d *PostgreSQLDialect) Name() string
func (*PostgreSQLDialect) PlaceholderFormat ¶
func (d *PostgreSQLDialect) PlaceholderFormat() sq.PlaceholderFormat
func (*PostgreSQLDialect) UpsertClause ¶
func (d *PostgreSQLDialect) UpsertClause(tableName string, conflictCols []string, updateCols []string) string
type QueryBuilder ¶
type QueryBuilder[T any] struct { // contains filtered or unexported fields }
QueryBuilder is a generic SQL builder for model T
func Query ¶
func Query[T any](session *Session) *QueryBuilder[T]
func (*QueryBuilder[T]) GroupBy ¶
func (q *QueryBuilder[T]) GroupBy(columns ...clause.Columnar) *QueryBuilder[T]
GroupBy adds GROUP BY clause arguments must implement clause.Columnar (e.g. field.Field, clause.Column)
func (*QueryBuilder[T]) Having ¶
func (q *QueryBuilder[T]) Having(expr clause.Expression) *QueryBuilder[T]
Having adds HAVING clause
func (*QueryBuilder[T]) Join ¶
func (q *QueryBuilder[T]) Join(table string, on clause.Expression) *QueryBuilder[T]
Join adds an INNER JOIN
func (*QueryBuilder[T]) LeftJoin ¶
func (q *QueryBuilder[T]) LeftJoin(table string, on clause.Expression) *QueryBuilder[T]
LeftJoin adds a LEFT JOIN
func (*QueryBuilder[T]) Limit ¶
func (q *QueryBuilder[T]) Limit(n uint64) *QueryBuilder[T]
func (*QueryBuilder[T]) Offset ¶
func (q *QueryBuilder[T]) Offset(n uint64) *QueryBuilder[T]
func (*QueryBuilder[T]) OrderBy ¶
func (q *QueryBuilder[T]) OrderBy(orders ...OrderBuilder) *QueryBuilder[T]
func (*QueryBuilder[T]) RightJoin ¶
func (q *QueryBuilder[T]) RightJoin(table string, on clause.Expression) *QueryBuilder[T]
RightJoin adds a RIGHT JOIN
func (*QueryBuilder[T]) Scan ¶
func (q *QueryBuilder[T]) Scan(ctx context.Context, dest any) error
Scan executes the query and scans the results into a custom destination. dest can be a pointer to a struct or a pointer to a slice of structs. This is useful for partial selections or joins mapping to DTOs.
func (*QueryBuilder[T]) Select ¶
func (q *QueryBuilder[T]) Select(columns ...clause.Columnar) *QueryBuilder[T]
Select replaces the selected columns arguments must implement clause.Columnar (e.g. field.Field, clause.Column)
func (*QueryBuilder[T]) Where ¶
func (q *QueryBuilder[T]) Where(expr clause.Expression) *QueryBuilder[T]
func (*QueryBuilder[T]) WithBuilder ¶
func (q *QueryBuilder[T]) WithBuilder(fn func(b sq.SelectBuilder) sq.SelectBuilder) *QueryBuilder[T]
WithBuilder allow users to manipulate the underlying squirrel.SelectBuilder. This provides an escape hatch for complex queries (Joins, CTEs, Window functions) that are not directly supported by the simplified ORM API.
type Repository ¶
type Repository[T any] struct { // contains filtered or unexported fields }
Repository manages CRUD operations for a model T
func NewRepository ¶
func NewRepository[T any](session *Session) *Repository[T]
func (*Repository[T]) BatchCreate ¶
func (r *Repository[T]) BatchCreate(ctx context.Context, models []*T) error
BatchCreate inserts multiple records in a single statement
func (*Repository[T]) DeleteModel ¶
func (r *Repository[T]) DeleteModel(ctx context.Context, model *T) error
DeleteModel deletes a record by model instance, triggering lifecycle hooks.
func (*Repository[T]) FindOne ¶
func (r *Repository[T]) FindOne(ctx context.Context, id any) (*T, error)
func (*Repository[T]) Query ¶
func (r *Repository[T]) Query() *QueryBuilder[T]
func (*Repository[T]) UpdateColumns ¶
func (r *Repository[T]) UpdateColumns(ctx context.Context, id any, assignments ...clause.Assignment) error
UpdateColumns updates specific columns for a record identified by id. This allows for partial updates without loading the entire record.
func (*Repository[T]) Upsert ¶
func (r *Repository[T]) Upsert(ctx context.Context, model *T, opts ...UpsertOption) error
Upsert inserts or updates a record. By default, it uses the Primary Key as the conflict target and updates all other columns. You can customize this utilizing OnConflict() and DoUpdate() options.
func (*Repository[T]) Where ¶
func (r *Repository[T]) Where(conds ...clause.Expression) *Repository[T]
Where returns a new Repository instance with the given conditions appended. This allows for method chaining, e.g. repo.Where(cond).Update(...)
type SQLiteDialect ¶
type SQLiteDialect struct{}
func (*SQLiteDialect) Name ¶
func (d *SQLiteDialect) Name() string
func (*SQLiteDialect) PlaceholderFormat ¶
func (d *SQLiteDialect) PlaceholderFormat() sq.PlaceholderFormat
func (*SQLiteDialect) UpsertClause ¶
func (d *SQLiteDialect) UpsertClause(tableName string, conflictCols []string, updateCols []string) string
type Schema ¶
type Schema[T any] interface { // Table Metadata TableName() string // Read Operations SelectColumns() []string // Write Operations InsertRow(*T) ([]string, []any) // Update Operations UpdateMap(*T) map[string]any // Primary Key PK(*T) PK SetPK(m *T, val int64) AutoIncrement() bool }
TableSchema defines how to map a model to a table and back
func LoadSchema ¶
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session manages the database connection and current transaction
func NewSession ¶
func NewSession(db *sql.DB, dialect Dialect, opts ...SessionOption) *Session
func (*Session) QueryRow ¶
QueryRow executes a query that returns at most one row. Note: Full observability (metrics, duration) is not available because the actual execution happens when Scan() is called on the returned Row.
type SessionOption ¶
type SessionOption func(*Session)
SessionOption configures a Session
func WithDefaultMeter ¶
func WithDefaultMeter() SessionOption
WithDefaultMeter uses the global OpenTelemetry meter
func WithDefaultTracer ¶
func WithDefaultTracer() SessionOption
WithDefaultTracer uses the global OpenTelemetry tracer
func WithLogger ¶
func WithLogger(logger *slog.Logger) SessionOption
WithLogger sets the logger for the session
func WithMeter ¶
func WithMeter(meter metric.Meter) SessionOption
WithMeter sets the OpenTelemetry meter for metrics
func WithQueryLogging ¶
func WithQueryLogging(enabled bool) SessionOption
WithQueryLogging enables logging of all queries
func WithSlowQueryThreshold ¶
func WithSlowQueryThreshold(d time.Duration) SessionOption
WithSlowQueryThreshold sets the slow query threshold for logging
func WithTracer ¶
func WithTracer(tracer trace.Tracer) SessionOption
WithTracer sets the OpenTelemetry tracer for the session
type UpsertOption ¶
type UpsertOption func(*upsertConfig)
func DoUpdate ¶
func DoUpdate(columns ...clause.Columnar) UpsertOption
DoUpdate specifies which columns to update when a conflict occurs. If not specified, all model columns (except conflict columns) are updated.
func OnConflict ¶
func OnConflict(columns ...clause.Columnar) UpsertOption
OnConflict specifies the columns to check for conflict (e.g., PRIMARY KEY or UNIQUE constraints)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
sqlcli
command
|
|
|
blog/cmd/complete_demo
command
|
|
|
blog/cmd/field_demo
command
|
|
|
json_ops
command
|
|