Help us shape the future of Go! Take the 2026 Go Developer Survey

duosql

package module
v0.0.0-...-2345a15 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MPL-2.0 Imports: 19 Imported by: 0

README

duosql

duosql is a high-performance Go ORM and query builder engine that unifies PostgreSQL and SQLite with zero boilerplate, builder-first syntax, and modern language idioms.

Usage

1. Connecting to Database
package main

import (
	"context"
	"log"
	"time"

	"github.com/thruqe/duosql"
)

func main() {
	// Connect to SQLite (Pure Go / CGO-free via modernc.org/sqlite)
	db, err := duosql.Open(duosql.DialectSQLite, "app.db?cache=shared",
		duosql.WithMaxOpenConns(25),
		duosql.WithMaxIdleConns(5),
		duosql.WithConnMaxLifetime(30*time.Minute),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Or connect to PostgreSQL via pgx stdlib adapter
	// pgDB, err := duosql.Open(duosql.DialectPostgres, "postgres://user:pass@localhost:5432/appdb")
}
2. DDL Schema Definition
ctx := context.Background()

err := db.Schema().CreateTable("users", func(t *duosql.TableBuilder) {
	t.ID() // BIGSERIAL PRIMARY KEY (PG) or INTEGER PRIMARY KEY AUTOINCREMENT (SQLite)
	t.String("username", 100).NotNull().Unique()
	t.String("email", 255).NotNull()
	t.Int("age").Default(0)
	t.Bool("active").Default(true)
	t.JSON("profile").Nullable()
	t.Timestamp("created_at").NotNull()
}).IfNotExists().Exec(ctx)
3. Entity Models & Mapping
type UserProfile struct {
	Theme string `json:"theme"`
	Role  string `json:"role"`
}

type User struct {
	ID        int64        `duo:"id,pk,auto"`
	Username  string       `duo:"username"`
	Email     string       `duo:"email"`
	Age       int          `duo:"age"`
	Active    bool         `duo:"active"`
	Profile   *UserProfile `duo:"profile,json"`
	CreatedAt time.Time    `duo:"created_at"`
}
4. Insert & UPSERT
// Insert with RETURNING support
user, err := duosql.Insert[User](db).
	Values(&User{
		Username:  "thruqe",
		Email:     "thruqe@example.com",
		Age:       28,
		Active:    true,
		Profile:   &UserProfile{Theme: "matrix", Role: "engineer"},
		CreatedAt: time.Now(),
	}).
	Returning("*").
	One(ctx)

// Upsert: ON CONFLICT DO UPDATE
_, err = duosql.Insert[User](db).
	Values(user).
	OnConflictDoUpdate([]string{"username"}, []string{"email", "age"}).
	Exec(ctx)
5. Queries & Range-Over-Func Streaming Iterators
// Fetch one record
admin, err := duosql.Select[User](db).
	Where(duosql.Col("username").Eq("thruqe")).
	One(ctx)

// Go 1.23+ range-over-func streaming iterators (Zero-allocation row processing)
query := duosql.Select[User](db).
	Where(
		duosql.Gte("age", 18),
		duosql.Eq("active", true),
	).
	OrderBy(duosql.Desc("created_at")).
	Limit(50)

for user, err := range query.Iter(ctx) {
	if err != nil {
		log.Printf("row stream error: %v", err)
		break
	}
	log.Printf("user: %s (%s)", user.Username, user.Email)
}
6. Transactions & Savepoints
err := db.Transaction(ctx, func(tx *duosql.Tx) error {
	_, err := duosql.Insert[User](tx).Values(newUser).Exec(ctx)
	if err != nil {
		return err // Automatically rolls back
	}

	// Nested transactional savepoint
	if err := tx.Savepoint("sp1"); err != nil {
		return err
	}

	if err := riskyOperation(tx); err != nil {
		_ = tx.RollbackTo("sp1") // Reverts only changes made after sp1
	}

	return nil // Automatically commits
})
7. Soft Deletes & Atomic Counter Updates
type Post struct {
	ID        int64      `duo:"id,pk,auto"`
	Title     string     `duo:"title"`
	Likes     int64      `duo:"likes"`
	DeletedAt *time.Time `duo:"deleted_at,soft_delete"`
}

// Atomic increment & decrement without race conditions
_, err = duosql.Update[Post](db).Where(duosql.Eq("id", 1)).Inc("likes", 1).Exec(ctx)

// Soft delete (sets deleted_at = CURRENT_TIMESTAMP under the hood)
_, err = duosql.Delete[Post](db).Where(duosql.Eq("id", 1)).Exec(ctx)

// Standard queries automatically exclude soft-deleted records
// Retrieve soft-deleted records explicitly:
posts, err := duosql.Select[Post](db).WithTrashed().All(ctx)
onlyTrash, err := duosql.Select[Post](db).OnlyTrashed().All(ctx)

// Force permanent deletion:
_, err = duosql.Delete[Post](db).ForceDelete().Where(duosql.Eq("id", 1)).Exec(ctx)
8. Subqueries, Aggregations, & JSON Extraction
// Subqueries
sub := duosql.Select[User](db, "id").Where(duosql.Gt("age", 25))
activeOrders, err := duosql.Select[Order](db).Where(duosql.InSubquery("user_id", sub)).All(ctx)

// Aggregations & Pluck
totalAge, err := duosql.Select[User](db).Sum(ctx, "age")
usernames, err := duosql.Pluck[string](duosql.Select[User](db), ctx, "username")

// JSON Path Filtering (PG `col->>'role'` / SQLite `json_extract(col, '$.role')`)
admins, err := duosql.Select[User](db).
	Where(duosql.JSONExtract("profile", "role").Eq("admin")).
	All(ctx)
9. Automatic Timestamp Defaults & Automatic Upserts
type Article struct {
	ID        int64     `duo:"id,pk,auto"`
	Slug      string    `duo:"slug,unique"`
	Title     string    `duo:"title"`
	CreatedAt time.Time `duo:"created_at"` // Auto-populated if zero during insert
	UpdatedAt time.Time `duo:"updated_at"` // Auto-refreshed on updates & upserts
}

// Full Upsert: Automatically discovers non-conflict columns, preserves created_at, and refreshes updated_at
_, err = duosql.Insert[Article](db).
	Values(&Article{Slug: "go-127", Title: "Go Modernized"}).
	OnConflictDoUpdateAll("slug").
	Exec(ctx)
10. Built-in Model Validation Engine

Zero-dependency, production-grade validation built directly into model lifecycles:

type RegisterRequest struct {
	Username string `validate:"required,min=3,max=30,alphanum"`
	Email    string `validate:"required,email"`
	Role     string `validate:"in=admin|editor|viewer"`
	Age      int    `validate:"min=18,max=120"`
	UUID     string `validate:"uuid"`
	Website  string `validate:"url"`
}

// Direct programmatic validation
if err := duosql.Validate(req); err != nil {
	var ve duosql.ValidationErrors
	if errors.As(err, &ve) {
		log.Println(ve.FieldErrors()) // map[string]string for clean JSON API errors
	}
}

// InsertBuilder automatically intercepts and validates before execution:
_, err = duosql.Insert[RegisterRequest](db).Values(req).Exec(ctx)
// Or bypass explicitly when loading trusted system records:
// duosql.Insert[RegisterRequest](db).Values(req).SkipValidation().Exec(ctx)
11. Native Protobuf Wire Format Support

Seamlessly serialize and deserialize google.golang.org/protobuf/proto.Message instances into BLOB (SQLite) / BYTEA (PostgreSQL) columns:

type SessionState struct {
	ID        int64                   `duo:"id,pk,auto"`
	UserID    string                  `duo:"user_id,index"`
	Payload   *wrapperspb.StringValue `duo:"payload,proto"`
	Timestamp *timestamppb.Timestamp  `duo:"stamp,proto"`
}

// Insert automatically marshals proto wire format
_, err = duosql.Insert[SessionState](db).Values(&SessionState{
	UserID:  "usr_99",
	Payload: wrapperspb.String("active-payload"),
	Timestamp: timestamppb.Now(),
}).Exec(ctx)

// Select automatically unmarshals into concrete protobuf pointers
session, err := duosql.Select[SessionState](db).Where(duosql.Eq("user_id", "usr_99")).One(ctx)
log.Println(session.Payload.Value)
12. Declarative Indexing & Single-Line Model Migration
type CatalogItem struct {
	ID       int64  `duo:"id,pk,auto"`
	SKU      string `duo:"sku,unique"`
	Category string `duo:"category,index"`
	Status   string `duo:"status,index:idx_item_status"`
}

// Generate table, data types, primary keys, and indexes in a single line!
err := duosql.CreateTableFromModel[CatalogItem](ctx, db.Schema(), true)

// Fluent Index Builder & Partial Indexes
err = db.Schema().CreateIndex("idx_catalog_active").
	On("catalog_items", "category").
	Where("status = 'active'").
	Exec(ctx)

// Dialect-aware existence checking & dropping
exists, err := db.Schema().HasIndex(ctx, "catalog_items", "idx_catalog_active")
err = db.Schema().DropIndex("idx_catalog_active").IfExists().Exec(ctx)

Features

  • Unified PostgreSQL & SQLite Dialects ($1 vs ? placeholders, quoting, type coercions)
  • Generic Type-Safe Query Builders (Select[T], Insert[T], Update[T], Delete[T])
  • Go 1.23+ Range-Over-Func Streaming (iter.Seq2[*T, error]) for memory-efficient iteration
  • Full Schema DDL Builder with Migrations, Alterations (AlterTable), Foreign Keys, and Indexes
  • Native UPSERT (ON CONFLICT DO UPDATE / DO NOTHING) across both engines
  • Expression & Predicate Builder (Eq, Neq, Gt, Gte, Lt, Lte, In, NotIn, Between, Like, ILike, And, Or, Not, Raw)
  • Subqueries & Existence Checks (InSubquery, NotInSubquery, ExistsSubquery, NotExistsSubquery)
  • Native JSON Path Extraction (JSONExtract("col", "path").Eq(...)) across PostgreSQL JSONB and SQLite JSON
  • Automatic Soft Deletes (duo:"deleted_at,soft_delete", WithTrashed(), OnlyTrashed(), ForceDelete())
  • Atomic Field Increments & Decrements (Inc, Dec) and Raw Update Expressions
  • Pagination & Chunked Batch Insertions (Paginate(page, size), InsertInBatches(ctx, size))
  • Aggregation Helpers & Value Plucking (Sum, Avg, Min, Max, Pluck[V])
  • Clause-level RETURNING support for SQLite 3.35+ and PostgreSQL
  • Reflection Metadata Cache & Automatic JSON Serialization
  • Atomic Transactions with Automatic Rollback and Named Savepoints
  • Query Telemetry & Middleware Hooks (BeforeQuery, AfterQuery, latency metrics)
  • Pure Go / Zero CGO SQLite support (modernc.org/sqlite) & Native PGX v5 stdlib

Contributions

If you want to help make this project better, please take the time to read this contribution doc and fork this repository. Then open a pull request with your changes.

If you are using any AI agent for assistance, please refer to the AGENTS documentation Guide.

Acknowledgements

duosql wouldn't have been possible without these open source, community and passion-driven projects: modernc.org/sqlite, pgx, and the broader Go ecosystem.

Licensing

This project is open source, see the LICENSE file for full details.

Support this project

If you found this project to be useful in anyway, please consider sending a tip.

Donate ETH 0x76a5307e573401f2b7189fb721a33dc483e985a8

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateTableFromModel

func CreateTableFromModel[T any](ctx context.Context, s *SchemaBuilder, ifNotExists ...bool) error

CreateTableFromModel generates and executes table schema and declared indexes from struct type T.

func Pluck

func Pluck[V any, T any](b *SelectBuilder[T], ctx context.Context, column string) ([]V, error)

Pluck extracts a single column from matching rows into a slice of scalar values.

func ScanModel

func ScanModel[T any](rows *sql.Rows, columns []string, meta *ModelMetadata) (*T, error)

ScanModel scans a single row from *sql.Rows into a fresh instance of T.

func Validate

func Validate(v any) error

Validate inspects a struct instance, evaluating tag-based rules and custom validator interfaces.

func ValidateContext

func ValidateContext(ctx context.Context, v any) error

ValidateContext validates a struct with context propagation for custom contextual hooks.

Types

type AlterTableBuilder

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

AlterTableBuilder manages ALTER TABLE operations.

func (*AlterTableBuilder) AddColumn

func (a *AlterTableBuilder) AddColumn(name string, dt DataType) *ColumnBuilder

AddColumn appends a new column to the table.

func (*AlterTableBuilder) Build

func (a *AlterTableBuilder) Build() ([]string, error)

Build generates the ALTER TABLE SQL statements.

func (*AlterTableBuilder) DropColumn

func (a *AlterTableBuilder) DropColumn(name string) *AlterTableBuilder

DropColumn removes an existing column.

func (*AlterTableBuilder) Exec

func (a *AlterTableBuilder) Exec(ctx context.Context) error

Exec executes all compiled ALTER TABLE statements sequentially.

func (*AlterTableBuilder) RenameColumn

func (a *AlterTableBuilder) RenameColumn(oldName, newName string) *AlterTableBuilder

RenameColumn renames an existing column.

func (*AlterTableBuilder) RenameTable

func (a *AlterTableBuilder) RenameTable(newName string) *AlterTableBuilder

RenameTable renames the table.

type BuildContext

type BuildContext struct {
	Dialect Dialect
	// contains filtered or unexported fields
}

BuildContext tracks compilation state during query rendering, including the target dialect and sequential parameter counter for placeholder mapping.

func NewBuildContext

func NewBuildContext(d Dialect) *BuildContext

NewBuildContext initializes a fresh compilation context for the given dialect.

func (*BuildContext) NextPlaceholder

func (bc *BuildContext) NextPlaceholder() string

NextPlaceholder advances the parameter counter and returns the dialect-appropriate token.

func (*BuildContext) ResetParamCounter

func (bc *BuildContext) ResetParamCounter()

ResetParamCounter resets the parameter index when compiling separate query components.

type ColumnBuilder

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

ColumnBuilder provides a fluent interface for configuring column metadata.

func (*ColumnBuilder) AutoIncrement

func (c *ColumnBuilder) AutoIncrement() *ColumnBuilder

AutoIncrement configures automatic sequence generation for numeric primary keys.

func (*ColumnBuilder) Default

func (c *ColumnBuilder) Default(val any) *ColumnBuilder

Default assigns a constant default value evaluated at insert time.

func (*ColumnBuilder) NotNull

func (c *ColumnBuilder) NotNull() *ColumnBuilder

NotNull enforces a non-nullable constraint on the column.

func (*ColumnBuilder) Nullable

func (c *ColumnBuilder) Nullable() *ColumnBuilder

Nullable explicitly marks the column as nullable.

func (*ColumnBuilder) PrimaryKey

func (c *ColumnBuilder) PrimaryKey() *ColumnBuilder

PrimaryKey marks the column as the primary key of the table.

func (*ColumnBuilder) Unique

func (c *ColumnBuilder) Unique() *ColumnBuilder

Unique attaches a unique constraint to this individual column.

type ColumnDef

type ColumnDef struct {
	Name            string
	DataType        DataType
	Length          int
	IsPrimaryKey    bool
	IsAutoIncrement bool
	IsNullable      bool
	IsUnique        bool
	DefaultVal      any
}

ColumnDef specifies physical properties of a table column.

type ColumnExpr

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

ColumnExpr provides fluent predicate chaining on a target column name.

func Col

func Col(name string) *ColumnExpr

Col begins fluent condition construction for a specific column.

func (*ColumnExpr) Asc

func (c *ColumnExpr) Asc() OrderByExpr

func (*ColumnExpr) Between

func (c *ColumnExpr) Between(min, max any) Predicate

func (*ColumnExpr) Desc

func (c *ColumnExpr) Desc() OrderByExpr

func (*ColumnExpr) Eq

func (c *ColumnExpr) Eq(val any) Predicate

func (*ColumnExpr) Gt

func (c *ColumnExpr) Gt(val any) Predicate

func (*ColumnExpr) Gte

func (c *ColumnExpr) Gte(val any) Predicate

func (*ColumnExpr) ILike

func (c *ColumnExpr) ILike(pattern string) Predicate

func (*ColumnExpr) In

func (c *ColumnExpr) In(vals ...any) Predicate

func (*ColumnExpr) IsNotNull

func (c *ColumnExpr) IsNotNull() Predicate

func (*ColumnExpr) IsNull

func (c *ColumnExpr) IsNull() Predicate

func (*ColumnExpr) Like

func (c *ColumnExpr) Like(pattern string) Predicate

func (*ColumnExpr) Lt

func (c *ColumnExpr) Lt(val any) Predicate

func (*ColumnExpr) Lte

func (c *ColumnExpr) Lte(val any) Predicate

func (*ColumnExpr) Neq

func (c *ColumnExpr) Neq(val any) Predicate

func (*ColumnExpr) NotIn

func (c *ColumnExpr) NotIn(vals ...any) Predicate

type CreateIndexBuilder

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

CreateIndexBuilder compiles index creation statements.

func (*CreateIndexBuilder) Build

func (b *CreateIndexBuilder) Build() (string, error)

Build compiles the CREATE INDEX SQL string.

func (*CreateIndexBuilder) Exec

func (b *CreateIndexBuilder) Exec(ctx context.Context) error

Exec executes the index creation.

func (*CreateIndexBuilder) IfNotExists

func (b *CreateIndexBuilder) IfNotExists() *CreateIndexBuilder

IfNotExists prevents errors if the index already exists.

func (*CreateIndexBuilder) On

func (b *CreateIndexBuilder) On(table string, cols ...string) *CreateIndexBuilder

On binds the target table and columns to index.

func (*CreateIndexBuilder) Unique

Unique marks this index as UNIQUE.

func (*CreateIndexBuilder) Where

func (b *CreateIndexBuilder) Where(condition string) *CreateIndexBuilder

Where specifies a partial index predicate expression.

type CreateTableBuilder

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

CreateTableBuilder compiles and executes table creation DDL.

func (*CreateTableBuilder) Build

func (b *CreateTableBuilder) Build() (string, error)

Build generates the executable DDL statement.

func (*CreateTableBuilder) Exec

func (b *CreateTableBuilder) Exec(ctx context.Context) error

Exec executes the table creation statement against the database and provisions declared indexes.

func (*CreateTableBuilder) IfNotExists

func (b *CreateTableBuilder) IfNotExists() *CreateTableBuilder

IfNotExists adds the IF NOT EXISTS clause to the DDL statement.

type DB

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

DB manages connection pooling, dialect resolution, and transaction lifecycles.

func Open

func Open(kind DialectKind, dsn string, opts ...Option) (*DB, error)

Open initializes a database session for the specified dialect and DSN.

func Wrap

func Wrap(rawDB *sql.DB, dialect Dialect, opts ...Option) *DB

Wrap adopts an existing *sql.DB instance with the designated dialect.

func (*DB) Begin

func (db *DB) Begin(ctx context.Context) (*Tx, error)

Begin begins a new atomic transaction.

func (*DB) Close

func (db *DB) Close() error

Close closes the underlying database pool.

func (*DB) Dialect

func (db *DB) Dialect() Dialect

Dialect returns the database engine compiler.

func (*DB) ExecContext

func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a write command and invokes configured telemetry hooks.

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping verifies connectivity to the database server.

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext executes a read query and invokes configured telemetry hooks.

func (*DB) QueryRowContext

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext executes a single-row query.

func (*DB) SQLDB

func (db *DB) SQLDB() *sql.DB

SQLDB returns the underlying *sql.DB handle.

func (*DB) Schema

func (db *DB) Schema() *SchemaBuilder

Schema returns a DDL schema builder for table management.

func (*DB) Transaction

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

Transaction executes a transactional function, committing on nil return or rolling back automatically if an error or panic occurs.

type DataType

type DataType string

DataType represents standard abstract column data types across database engines.

const (
	TypeSmallInt  DataType = "smallint"
	TypeInt       DataType = "integer"
	TypeBigInt    DataType = "bigint"
	TypeFloat     DataType = "float"
	TypeDouble    DataType = "double"
	TypeBool      DataType = "boolean"
	TypeString    DataType = "string"
	TypeText      DataType = "text"
	TypeTimestamp DataType = "timestamp"
	TypeJSON      DataType = "json"
	TypeUUID      DataType = "uuid"
	TypeBytes     DataType = "bytes"
)

type DeleteBuilder

type DeleteBuilder[T any] struct {
	// contains filtered or unexported fields
}

DeleteBuilder constructs and executes SQL DELETE statements.

func Delete

func Delete[T any](executor ExecExecutor, table ...string) *DeleteBuilder[T]

Delete creates a new DELETE query builder.

func (*DeleteBuilder[T]) All

func (b *DeleteBuilder[T]) All(ctx context.Context) ([]T, error)

All executes the deletion with RETURNING and unmarshals all deleted records.

func (*DeleteBuilder[T]) Build

func (b *DeleteBuilder[T]) Build() (string, []any, error)

Build compiles the DELETE SQL query and returns bound arguments.

func (*DeleteBuilder[T]) Exec

func (b *DeleteBuilder[T]) Exec(ctx context.Context) (int64, error)

Exec executes the deletion statement and returns the number of deleted records. If the target entity defines a soft delete timestamp and ForceDelete() was not requested, an UPDATE is performed stamping the soft delete column with the current timestamp.

func (*DeleteBuilder[T]) ForceDelete

func (b *DeleteBuilder[T]) ForceDelete() *DeleteBuilder[T]

ForceDelete permanently deletes rows even if the model defines a soft delete column.

func (*DeleteBuilder[T]) From

func (b *DeleteBuilder[T]) From(table string) *DeleteBuilder[T]

From explicitly specifies the target table name.

func (*DeleteBuilder[T]) One

func (b *DeleteBuilder[T]) One(ctx context.Context) (*T, error)

One executes the deletion with RETURNING and unmarshals the single deleted record.

func (*DeleteBuilder[T]) Returning

func (b *DeleteBuilder[T]) Returning(cols ...string) *DeleteBuilder[T]

Returning requests specified columns to be returned after the deletion.

func (*DeleteBuilder[T]) Where

func (b *DeleteBuilder[T]) Where(preds ...Predicate) *DeleteBuilder[T]

Where appends filtering predicates to limit deleted rows.

type Dialect

type Dialect interface {
	// Kind returns the dialect identifier.
	Kind() DialectKind

	// Placeholder converts an index (1-based) into the dialect's parameter token.
	// PostgreSQL returns $1, $2, etc., while SQLite returns ? for all indices.
	Placeholder(index int) string

	// QuoteIdentifier escapes identifiers such as table and column names
	// to prevent collision with reserved SQL keywords and preserve case sensitivity.
	QuoteIdentifier(name string) string

	// ColumnTypeSQL maps an internal column definition to the dialect's DDL data type string.
	ColumnTypeSQL(col ColumnDef) string

	// SupportsReturning reports whether the database natively supports RETURNING clauses.
	SupportsReturning() bool

	// HasTableSQL returns the SQL query and parameter to verify table existence.
	HasTableSQL(tableName string) (string, any)

	// FormatILike returns the SQL expression for case-insensitive pattern matching.
	FormatILike(col string, placeholder string) string

	// JSONExtractSQL compiles dialect-specific JSON path extraction expressions.
	JSONExtractSQL(col string, path string) string
}

Dialect abstracts database-specific SQL generation, parameter binding, data type representations, and metadata queries between PostgreSQL and SQLite.

func NewPostgresDialect

func NewPostgresDialect() Dialect

NewPostgresDialect constructs a PostgreSQL dialect compiler.

func NewSQLiteDialect

func NewSQLiteDialect() Dialect

NewSQLiteDialect constructs an SQLite dialect compiler.

type DialectKind

type DialectKind string

DialectKind specifies the target relational database engine.

const (
	DialectPostgres DialectKind = "postgres"
	DialectSQLite   DialectKind = "sqlite"
)

type DropIndexBuilder

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

DropIndexBuilder compiles DROP INDEX statements.

func (*DropIndexBuilder) Build

func (b *DropIndexBuilder) Build() string

Build generates the DROP INDEX SQL statement.

func (*DropIndexBuilder) Cascade

func (b *DropIndexBuilder) Cascade() *DropIndexBuilder

Cascade drops objects that depend on this index (PostgreSQL).

func (*DropIndexBuilder) Exec

func (b *DropIndexBuilder) Exec(ctx context.Context) error

Exec executes index removal.

func (*DropIndexBuilder) IfExists

func (b *DropIndexBuilder) IfExists() *DropIndexBuilder

IfExists prevents errors if the index does not exist.

type DropTableBuilder

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

DropTableBuilder compiles and executes table drop DDL.

func (*DropTableBuilder) Build

func (b *DropTableBuilder) Build() string

Build generates the drop statement string.

func (*DropTableBuilder) Cascade

func (b *DropTableBuilder) Cascade() *DropTableBuilder

Cascade appends CASCADE to clean dependent constraints (Postgres).

func (*DropTableBuilder) Exec

func (b *DropTableBuilder) Exec(ctx context.Context) error

Exec executes the drop table command.

func (*DropTableBuilder) IfExists

func (b *DropTableBuilder) IfExists() *DropTableBuilder

IfExists adds IF EXISTS to the DROP TABLE statement.

type ExecExecutor

type ExecExecutor interface {
	QueryExecutor
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

ExecExecutor extends QueryExecutor with write execution commands.

type FieldInfo

type FieldInfo struct {
	Index         int
	Name          string
	ColumnName    string
	IsPrimaryKey  bool
	IsAuto        bool
	IsJSON        bool
	IsProto       bool
	IsSoftDelete  bool
	IsCreatedAt   bool
	IsUpdatedAt   bool
	IsIndex       bool
	IsUniqueIndex bool
	IndexName     string
	FieldType     reflect.Type
}

FieldInfo stores parsed struct field metadata cached across query executions.

type ForeignKeyBuilder

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

ForeignKeyBuilder configures referential action cascades.

func (*ForeignKeyBuilder) OnDelete

func (f *ForeignKeyBuilder) OnDelete(action string) *ForeignKeyBuilder

OnDelete specifies the referential action triggered when parent rows are deleted.

func (*ForeignKeyBuilder) OnUpdate

func (f *ForeignKeyBuilder) OnUpdate(action string) *ForeignKeyBuilder

OnUpdate specifies the referential action triggered when parent key values change.

type ForeignKeyDef

type ForeignKeyDef struct {
	Column           string
	ReferencedTable  string
	ReferencedColumn string
	OnDeleteAction   string
	OnUpdateAction   string
}

ForeignKeyDef describes a relational constraint pointing to another table.

type InsertBuilder

type InsertBuilder[T any] struct {
	// contains filtered or unexported fields
}

InsertBuilder configures and executes SQL INSERT and upsert operations.

func Insert

func Insert[T any](executor ExecExecutor, table ...string) *InsertBuilder[T]

Insert creates a new insert query builder for entity type T.

func (*InsertBuilder[T]) All

func (b *InsertBuilder[T]) All(ctx context.Context) ([]T, error)

All executes a batch insertion with RETURNING and unmarshals all persisted entities.

func (*InsertBuilder[T]) Build

func (b *InsertBuilder[T]) Build() (string, []any, error)

Build compiles the INSERT SQL statement and extracts bound arguments.

func (*InsertBuilder[T]) Columns

func (b *InsertBuilder[T]) Columns(cols ...string) *InsertBuilder[T]

Columns overrides the column sequence for values insertion.

func (*InsertBuilder[T]) Exec

func (b *InsertBuilder[T]) Exec(ctx context.Context) (sql.Result, error)

Exec executes the insertion command, returning the standard sql.Result.

func (*InsertBuilder[T]) InsertInBatches

func (b *InsertBuilder[T]) InsertInBatches(ctx context.Context, batchSize int) error

InsertInBatches inserts a collection of model entities in chunks of batchSize to avoid database driver parameter limits.

func (*InsertBuilder[T]) Into

func (b *InsertBuilder[T]) Into(table string) *InsertBuilder[T]

Into explicitly designates the target table name.

func (*InsertBuilder[T]) OnConflictDoNothing

func (b *InsertBuilder[T]) OnConflictDoNothing(targets ...string) *InsertBuilder[T]

OnConflictDoNothing appends ON CONFLICT (...) DO NOTHING to skip existing keys.

func (*InsertBuilder[T]) OnConflictDoUpdate

func (b *InsertBuilder[T]) OnConflictDoUpdate(targets []string, updateCols []string) *InsertBuilder[T]

OnConflictDoUpdate configures an upsert to update specified columns when conflict occurs.

func (*InsertBuilder[T]) OnConflictDoUpdateAll

func (b *InsertBuilder[T]) OnConflictDoUpdateAll(targets ...string) *InsertBuilder[T]

OnConflictDoUpdateAll configures an upsert to automatically update all non-conflict columns from the model.

func (*InsertBuilder[T]) OnConflictDoUpdateRaw

func (b *InsertBuilder[T]) OnConflictDoUpdateRaw(targets []string, rawAssignments []string) *InsertBuilder[T]

OnConflictDoUpdateRaw configures an upsert to update using explicit SQL assignment expressions.

func (*InsertBuilder[T]) One

func (b *InsertBuilder[T]) One(ctx context.Context) (*T, error)

One executes the insertion with a RETURNING clause and unmarshals the resulting entity.

func (*InsertBuilder[T]) Returning

func (b *InsertBuilder[T]) Returning(cols ...string) *InsertBuilder[T]

Returning requests specified columns to be returned after insertion.

func (*InsertBuilder[T]) SkipValidation

func (b *InsertBuilder[T]) SkipValidation() *InsertBuilder[T]

SkipValidation disables automatic struct tag and validator hook executions before insert.

func (*InsertBuilder[T]) ValueMap

func (b *InsertBuilder[T]) ValueMap(records ...map[string]any) *InsertBuilder[T]

ValueMap inserts rows using explicit column-to-value keymaps.

func (*InsertBuilder[T]) Values

func (b *InsertBuilder[T]) Values(models ...*T) *InsertBuilder[T]

Values appends one or more model entity instances to be inserted.

type JSONExtractExpr

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

JSONExtractExpr provides JSON path extraction predicates.

func JSONExtract

func JSONExtract(column string, path string) *JSONExtractExpr

JSONExtract initiates fluent JSON field extraction.

func (*JSONExtractExpr) Eq

func (j *JSONExtractExpr) Eq(val any) Predicate

Eq matches extracted JSON value to equal the target value.

func (*JSONExtractExpr) Like

func (j *JSONExtractExpr) Like(pattern string) Predicate

Like evaluates a LIKE pattern against the extracted JSON value.

func (*JSONExtractExpr) Neq

func (j *JSONExtractExpr) Neq(val any) Predicate

Neq matches extracted JSON value to not equal the target value.

type ModelIndex

type ModelIndex struct {
	Name    string
	Columns []string
	Unique  bool
}

ModelIndex specifies an index declared via struct tags.

type ModelMetadata

type ModelMetadata struct {
	Type             reflect.Type
	TableName        string
	Fields           []FieldInfo
	ColumnToIdx      map[string]int
	PKColumn         string
	SoftDeleteColumn string
	CreatedAtCol     string
	UpdatedAtCol     string
	Indexes          []ModelIndex
}

ModelMetadata represents the cached structural blueprint of a Go entity struct.

func GetModelMetadata

func GetModelMetadata[T any]() (*ModelMetadata, error)

GetModelMetadata inspects type T and retrieves cached reflection metadata.

func (*ModelMetadata) ColumnNames

func (m *ModelMetadata) ColumnNames() []string

ColumnNames returns all declared column names in the model.

func (*ModelMetadata) ExtractInsertMap

func (m *ModelMetadata) ExtractInsertMap(val reflect.Value, skipAuto bool) map[string]any

ExtractInsertMap converts a model instance into a map of column names to values, optionally skipping auto-generated columns and automatically populating timestamps.

func (*ModelMetadata) ScanTargets

func (m *ModelMetadata) ScanTargets(val reflect.Value, columns []string) ([]any, []jsonScannerTarget, []protoScannerTarget)

ScanTargets prepares scan destination pointers for the SQL driver's Rows.Scan matching the specific columns returned by the executed query.

type ModelValidator

type ModelValidator interface {
	Validate() error
}

ModelValidator can be implemented by models to run custom programmatic validations.

type ModelValidatorWithContext

type ModelValidatorWithContext interface {
	ValidateContext(ctx context.Context) error
}

ModelValidatorWithContext allows models to perform context-aware validations (e.g. uniqueness checks).

type Option

type Option func(*DB)

Option configures database connection parameters.

func WithConnMaxIdleTime

func WithConnMaxIdleTime(d time.Duration) Option

WithConnMaxIdleTime sets maximum connection idle duration.

func WithConnMaxLifetime

func WithConnMaxLifetime(d time.Duration) Option

WithConnMaxLifetime sets maximum connection lifetime.

func WithHook

func WithHook(hook QueryHook) Option

WithHook attaches a query inspection hook.

func WithMaxIdleConns

func WithMaxIdleConns(n int) Option

WithMaxIdleConns sets maximum idle connections in the pool.

func WithMaxOpenConns

func WithMaxOpenConns(n int) Option

WithMaxOpenConns sets maximum open connection pool limit.

type OrderByExpr

type OrderByExpr interface {
	ToOrderBySQL(ctx *BuildContext) string
}

OrderByExpr represents a sort criteria expression in an ORDER BY clause.

func Asc

func Asc(column string) OrderByExpr

Asc orders results in ascending order.

func Desc

func Desc(column string) OrderByExpr

Desc orders results in descending order.

func RawOrderBy

func RawOrderBy(expr string) OrderByExpr

RawOrderBy creates an OrderByExpr from a raw SQL expression (such as CASE statements).

type Predicate

type Predicate interface {
	ToSQL(ctx *BuildContext) (string, []any, error)
}

Predicate represents a composable boolean SQL condition that compiles into a parameterized clause and slice of execution arguments.

func And

func And(preds ...Predicate) Predicate

And combines multiple predicates with logical AND.

func Between

func Between(column string, lower, upper any) Predicate

Between builds a BETWEEN condition: col BETWEEN lower AND upper.

func Eq

func Eq(column string, value any) Predicate

Eq builds an equality predicate: col = val.

func ExistsSubquery

func ExistsSubquery(sub SubqueryBuilder) Predicate

ExistsSubquery tests if the subquery returns at least one record.

func Gt

func Gt(column string, value any) Predicate

Gt builds a greater-than predicate: col > val.

func Gte

func Gte(column string, value any) Predicate

Gte builds a greater-than-or-equal predicate: col >= val.

func ILike

func ILike(column string, pattern string) Predicate

ILike builds a case-insensitive pattern match predicate, translated cleanly to ILIKE in PostgreSQL and COLLATE NOCASE in SQLite.

func In

func In(column string, values ...any) Predicate

In builds a membership predicate: col IN (...).

func InSubquery

func InSubquery(column string, sub SubqueryBuilder) Predicate

InSubquery tests if a column value matches any record returned by the subquery.

func IsNotNull

func IsNotNull(column string) Predicate

IsNotNull builds an IS NOT NULL condition.

func IsNull

func IsNull(column string) Predicate

IsNull builds an IS NULL condition.

func Like

func Like(column string, pattern string) Predicate

Like builds a pattern match predicate: col LIKE pattern.

func Lt

func Lt(column string, value any) Predicate

Lt builds a less-than predicate: col < val.

func Lte

func Lte(column string, value any) Predicate

Lte builds a less-than-or-equal predicate: col <= val.

func Neq

func Neq(column string, value any) Predicate

Neq builds an inequality predicate: col != val.

func Not

func Not(pred Predicate) Predicate

Not negates the given predicate.

func NotExistsSubquery

func NotExistsSubquery(sub SubqueryBuilder) Predicate

NotExistsSubquery tests if the subquery returns zero records.

func NotIn

func NotIn(column string, values ...any) Predicate

NotIn builds a non-membership predicate: col NOT IN (...).

func NotInSubquery

func NotInSubquery(column string, sub SubqueryBuilder) Predicate

NotInSubquery tests if a column value does not match any record returned by the subquery.

func Or

func Or(preds ...Predicate) Predicate

Or combines multiple predicates with logical OR.

type QueryExecutor

type QueryExecutor interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	Dialect() Dialect
	// contains filtered or unexported methods
}

QueryExecutor defines common read operations over database connections and transactions.

type QueryHook

type QueryHook func(ctx context.Context, query string, args []any, duration time.Duration, err error)

QueryHook allows intercepting executed SQL statements for telemetry, auditing, and logging.

type RawExpr

type RawExpr struct {
	SQL  string
	Args []any
}

RawExpr represents an unescaped SQL fragment with associated parameters.

func Raw

func Raw(sql string, args ...any) *RawExpr

Raw creates an escape hatch for custom SQL expressions and dialect-specific functions.

func (*RawExpr) ToSQL

func (r *RawExpr) ToSQL(ctx *BuildContext) (string, []any, error)

type SchemaBuilder

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

SchemaBuilder provides DDL execution workflows for database migrations.

func NewSchemaBuilder

func NewSchemaBuilder(executor ExecExecutor, dialect Dialect) *SchemaBuilder

NewSchemaBuilder constructs a schema manager bound to an active database session.

func (*SchemaBuilder) AlterTable

func (s *SchemaBuilder) AlterTable(name string, fn func(a *AlterTableBuilder)) *AlterTableBuilder

AlterTable initiates table modification operations.

func (*SchemaBuilder) CreateIndex

func (s *SchemaBuilder) CreateIndex(name string) *CreateIndexBuilder

CreateIndex initiates an index creation statement.

func (*SchemaBuilder) CreateTable

func (s *SchemaBuilder) CreateTable(name string, fn func(t *TableBuilder)) *CreateTableBuilder

CreateTable starts table definition using a declarative builder callback.

func (*SchemaBuilder) CreateTableIfNotExists

func (s *SchemaBuilder) CreateTableIfNotExists(name string, fn func(t *TableBuilder)) *CreateTableBuilder

CreateTableIfNotExists initiates table definition with IF NOT EXISTS automatically enabled.

func (*SchemaBuilder) DropIndex

func (s *SchemaBuilder) DropIndex(name string) *DropIndexBuilder

DropIndex initiates an index removal statement.

func (*SchemaBuilder) DropTable

func (s *SchemaBuilder) DropTable(name string) *DropTableBuilder

DropTable initiates a table removal statement.

func (*SchemaBuilder) HasColumn

func (s *SchemaBuilder) HasColumn(ctx context.Context, tableName, columnName string) (bool, error)

HasColumn reports whether the specified column exists within a database table.

func (*SchemaBuilder) HasIndex

func (s *SchemaBuilder) HasIndex(ctx context.Context, tableName, indexName string) (bool, error)

HasIndex reports whether the specified index exists on the database table.

func (*SchemaBuilder) HasTable

func (s *SchemaBuilder) HasTable(ctx context.Context, tableName string) (bool, error)

HasTable reports whether a table exists in the current database schema.

type SelectBuilder

type SelectBuilder[T any] struct {
	// contains filtered or unexported fields
}

SelectBuilder constructs and executes SELECT queries with generic entity decoding.

func Select

func Select[T any](executor QueryExecutor, cols ...string) *SelectBuilder[T]

Select initializes a generic query builder for model entity type T.

func (*SelectBuilder[T]) All

func (b *SelectBuilder[T]) All(ctx context.Context) ([]T, error)

All executes the query and returns all matching rows as a slice of T entities.

func (*SelectBuilder[T]) As

func (b *SelectBuilder[T]) As(alias string) *SelectBuilder[T]

As sets an alias for the primary table.

func (*SelectBuilder[T]) Asc

func (b *SelectBuilder[T]) Asc(col string) *SelectBuilder[T]

Asc sorts by column in ascending order.

func (*SelectBuilder[T]) Avg

func (b *SelectBuilder[T]) Avg(ctx context.Context, column string) (float64, error)

Avg computes the arithmetic mean of the specified column.

func (*SelectBuilder[T]) Build

func (b *SelectBuilder[T]) Build() (string, []any, error)

Build compiles the configured clauses into a parameterized SQL statement.

func (*SelectBuilder[T]) Count

func (b *SelectBuilder[T]) Count(ctx context.Context) (int64, error)

Count returns the total number of matching rows using a COUNT(*) query wrapper.

func (*SelectBuilder[T]) CrossJoin

func (b *SelectBuilder[T]) CrossJoin(table string) *SelectBuilder[T]

CrossJoin appends a CROSS JOIN clause.

func (*SelectBuilder[T]) Desc

func (b *SelectBuilder[T]) Desc(col string) *SelectBuilder[T]

Desc sorts by column in descending order.

func (*SelectBuilder[T]) Distinct

func (b *SelectBuilder[T]) Distinct() *SelectBuilder[T]

Distinct ensures duplicate rows are eliminated from the result set.

func (*SelectBuilder[T]) Exists

func (b *SelectBuilder[T]) Exists(ctx context.Context) (bool, error)

Exists checks if at least one matching row satisfies the conditions.

func (*SelectBuilder[T]) ForUpdate

func (b *SelectBuilder[T]) ForUpdate() *SelectBuilder[T]

ForUpdate attaches a row lock directive when supported by the database engine.

func (*SelectBuilder[T]) From

func (b *SelectBuilder[T]) From(table string) *SelectBuilder[T]

From sets the primary source table for the query.

func (*SelectBuilder[T]) FullJoin

func (b *SelectBuilder[T]) FullJoin(table string, on Predicate) *SelectBuilder[T]

FullJoin appends a FULL OUTER JOIN clause.

func (*SelectBuilder[T]) GroupBy

func (b *SelectBuilder[T]) GroupBy(cols ...string) *SelectBuilder[T]

GroupBy adds columns to the GROUP BY clause.

func (*SelectBuilder[T]) Having

func (b *SelectBuilder[T]) Having(preds ...Predicate) *SelectBuilder[T]

Having appends aggregation filters to the HAVING clause.

func (*SelectBuilder[T]) Iter

func (b *SelectBuilder[T]) Iter(ctx context.Context) iter.Seq2[*T, error]

Iter yields matching entities as an idiomatic Go range-over-func iterator. Designed for memory-efficient streaming over large datasets without buffering the full result set.

func (*SelectBuilder[T]) Join

func (b *SelectBuilder[T]) Join(table string, on Predicate) *SelectBuilder[T]

Join appends an INNER JOIN clause.

func (*SelectBuilder[T]) LeftJoin

func (b *SelectBuilder[T]) LeftJoin(table string, on Predicate) *SelectBuilder[T]

LeftJoin appends a LEFT OUTER JOIN clause.

func (*SelectBuilder[T]) Limit

func (b *SelectBuilder[T]) Limit(n int) *SelectBuilder[T]

Limit sets the maximum number of records to return.

func (*SelectBuilder[T]) Max

func (b *SelectBuilder[T]) Max(ctx context.Context, column string) (any, error)

Max returns the maximum value of the specified column.

func (*SelectBuilder[T]) Min

func (b *SelectBuilder[T]) Min(ctx context.Context, column string) (any, error)

Min returns the minimum value of the specified column.

func (*SelectBuilder[T]) Offset

func (b *SelectBuilder[T]) Offset(n int) *SelectBuilder[T]

Offset sets the number of records to skip before reading.

func (*SelectBuilder[T]) One

func (b *SelectBuilder[T]) One(ctx context.Context) (*T, error)

One executes the query and unmarshals the first matching row into a newly allocated T. Returns sql.ErrNoRows if zero records match.

func (*SelectBuilder[T]) OnlyTrashed

func (b *SelectBuilder[T]) OnlyTrashed() *SelectBuilder[T]

OnlyTrashed filters the query to only return soft-deleted records.

func (*SelectBuilder[T]) OrderBy

func (b *SelectBuilder[T]) OrderBy(exprs ...OrderByExpr) *SelectBuilder[T]

OrderBy appends ordering criteria.

func (*SelectBuilder[T]) Paginate

func (b *SelectBuilder[T]) Paginate(page int, pageSize int) *SelectBuilder[T]

Paginate calculates LIMIT and OFFSET from 1-based page and pageSize parameters.

func (*SelectBuilder[T]) RightJoin

func (b *SelectBuilder[T]) RightJoin(table string, on Predicate) *SelectBuilder[T]

RightJoin appends a RIGHT OUTER JOIN clause.

func (*SelectBuilder[T]) Sum

func (b *SelectBuilder[T]) Sum(ctx context.Context, column string) (float64, error)

Sum computes the sum of the specified numeric column.

func (*SelectBuilder[T]) Where

func (b *SelectBuilder[T]) Where(preds ...Predicate) *SelectBuilder[T]

Where appends filtering conditions to the WHERE clause.

func (*SelectBuilder[T]) WithTrashed

func (b *SelectBuilder[T]) WithTrashed() *SelectBuilder[T]

WithTrashed instructs the query to include soft-deleted records.

type SubqueryBuilder

type SubqueryBuilder interface {
	Build() (string, []any, error)
}

SubqueryBuilder compiles an executable subquery fragment.

type TableBuilder

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

TableBuilder records column declarations and table-level constraints during DDL construction.

func (*TableBuilder) BigInt

func (t *TableBuilder) BigInt(name string) *ColumnBuilder

BigInt declares a 64-bit signed integer column.

func (*TableBuilder) Bool

func (t *TableBuilder) Bool(name string) *ColumnBuilder

Bool declares a boolean column.

func (*TableBuilder) Bytes

func (t *TableBuilder) Bytes(name string) *ColumnBuilder

Bytes declares a binary data column (PostgreSQL BYTEA, SQLite BLOB).

func (*TableBuilder) Double

func (t *TableBuilder) Double(name string) *ColumnBuilder

Double declares a double-precision floating point column.

func (*TableBuilder) Float

func (t *TableBuilder) Float(name string) *ColumnBuilder

Float declares a single-precision floating point column.

func (*TableBuilder) ForeignKey

func (t *TableBuilder) ForeignKey(col, refTable, refCol string) *ForeignKeyBuilder

ForeignKey adds a referential constraint linking col to refTable(refCol).

func (*TableBuilder) ID

func (t *TableBuilder) ID() *ColumnBuilder

ID creates a conventional 64-bit auto-incrementing primary key named "id".

func (*TableBuilder) Index

func (t *TableBuilder) Index(name string, cols ...string) *TableBuilder

Index registers a named index on the table.

func (*TableBuilder) Int

func (t *TableBuilder) Int(name string) *ColumnBuilder

Int declares a 32-bit signed integer column.

func (*TableBuilder) JSON

func (t *TableBuilder) JSON(name string) *ColumnBuilder

JSON declares a structured JSON column (PostgreSQL JSONB, SQLite TEXT).

func (*TableBuilder) PrimaryKey

func (t *TableBuilder) PrimaryKey(cols ...string)

PrimaryKey registers a multi-column composite primary key constraint.

func (*TableBuilder) Proto

func (t *TableBuilder) Proto(name string) *ColumnBuilder

Proto registers a binary protobuf wire column (PostgreSQL BYTEA, SQLite BLOB).

func (*TableBuilder) SmallInt

func (t *TableBuilder) SmallInt(name string) *ColumnBuilder

SmallInt declares a 16-bit signed integer column.

func (*TableBuilder) String

func (t *TableBuilder) String(name string, length ...int) *ColumnBuilder

String adds a variable-length string column with an optional length specification.

func (*TableBuilder) Text

func (t *TableBuilder) Text(name string) *ColumnBuilder

Text declares an unbounded text column.

func (*TableBuilder) Timestamp

func (t *TableBuilder) Timestamp(name string) *ColumnBuilder

Timestamp declares a timestamp column with timezone awareness when available.

func (*TableBuilder) Timestamps

func (t *TableBuilder) Timestamps()

Timestamps adds standard created_at and updated_at TIMESTAMP columns with CURRENT_TIMESTAMP default.

func (*TableBuilder) UUID

func (t *TableBuilder) UUID(name string) *ColumnBuilder

UUID declares a unique identifier column.

func (*TableBuilder) Unique

func (t *TableBuilder) Unique(cols ...string)

Unique registers a composite unique constraint over the specified columns.

func (*TableBuilder) UniqueIndex

func (t *TableBuilder) UniqueIndex(name string, cols ...string) *TableBuilder

UniqueIndex registers a named unique index on the table.

type Tx

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

Tx wraps an active transaction session.

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit persists changes made in this transaction.

func (*Tx) Dialect

func (tx *Tx) Dialect() Dialect

Dialect returns the database engine compiler.

func (*Tx) ExecContext

func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a write query inside the transaction.

func (*Tx) QueryContext

func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext executes a read query inside the transaction.

func (*Tx) QueryRowContext

func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext executes a single-row query inside the transaction.

func (*Tx) ReleaseSavepoint

func (tx *Tx) ReleaseSavepoint(name string) error

ReleaseSavepoint frees resources allocated to the named savepoint.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback cancels changes made in this transaction.

func (*Tx) RollbackTo

func (tx *Tx) RollbackTo(name string) error

RollbackTo rolls back changes made since the specified savepoint.

func (*Tx) Savepoint

func (tx *Tx) Savepoint(name string) error

Savepoint establishes a transactional savepoint for nested rollbacks.

func (*Tx) Schema

func (tx *Tx) Schema() *SchemaBuilder

Schema returns a DDL schema builder bound to this transaction.

type UpdateBuilder

type UpdateBuilder[T any] struct {
	// contains filtered or unexported fields
}

UpdateBuilder constructs and executes SQL UPDATE statements.

func Update

func Update[T any](executor ExecExecutor, table ...string) *UpdateBuilder[T]

Update creates a new UPDATE query builder.

func (*UpdateBuilder[T]) All

func (b *UpdateBuilder[T]) All(ctx context.Context) ([]T, error)

All executes the update with a RETURNING clause and unmarshals all affected rows.

func (*UpdateBuilder[T]) Build

func (b *UpdateBuilder[T]) Build() (string, []any, error)

func (*UpdateBuilder[T]) Dec

func (b *UpdateBuilder[T]) Dec(column string, amount ...int64) *UpdateBuilder[T]

Dec decrements a numeric column atomically by the specified amount (default 1).

func (*UpdateBuilder[T]) Exec

func (b *UpdateBuilder[T]) Exec(ctx context.Context) (int64, error)

Exec executes the update query and returns the count of affected rows.

func (*UpdateBuilder[T]) Inc

func (b *UpdateBuilder[T]) Inc(column string, amount ...int64) *UpdateBuilder[T]

Inc increments a numeric column atomically by the specified amount (default 1).

func (*UpdateBuilder[T]) One

func (b *UpdateBuilder[T]) One(ctx context.Context) (*T, error)

One executes the update with a RETURNING clause and unmarshals the single affected row.

func (*UpdateBuilder[T]) Returning

func (b *UpdateBuilder[T]) Returning(cols ...string) *UpdateBuilder[T]

Returning requests specified columns to be returned after the update.

func (*UpdateBuilder[T]) Set

func (b *UpdateBuilder[T]) Set(column string, value any) *UpdateBuilder[T]

Set adds a single column update assignment.

func (*UpdateBuilder[T]) SetMap

func (b *UpdateBuilder[T]) SetMap(values map[string]any) *UpdateBuilder[T]

SetMap merges multiple column assignments from a map.

func (*UpdateBuilder[T]) SetModel

func (b *UpdateBuilder[T]) SetModel(model *T, cols ...string) *UpdateBuilder[T]

SetModel applies non-primary key fields from an entity model instance.

func (*UpdateBuilder[T]) SetRaw

func (b *UpdateBuilder[T]) SetRaw(column string, expr string, args ...any) *UpdateBuilder[T]

SetRaw assigns a column to an unescaped SQL expression.

func (*UpdateBuilder[T]) Table

func (b *UpdateBuilder[T]) Table(table string) *UpdateBuilder[T]

Table explicitly specifies the target table name.

func (*UpdateBuilder[T]) Where

func (b *UpdateBuilder[T]) Where(preds ...Predicate) *UpdateBuilder[T]

Where appends filtering conditions to restrict updated rows.

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Rule    string `json:"rule"`
	Param   string `json:"param,omitempty"`
	Message string `json:"message"`
}

ValidationError represents an individual rule violation on a specific struct field.

func (ValidationError) Error

func (e ValidationError) Error() string

Error formats the validation failure into a human-readable string.

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors collects all failures encountered across a model.

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

Error concatenates all error messages into a single string.

func (ValidationErrors) FieldErrors

func (ve ValidationErrors) FieldErrors() map[string]string

FieldErrors returns a mapping of field names to their failure messages for direct API responses.

Jump to

Keyboard shortcuts

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