Data & infrastructure/Nock Database Toolkit

Nock Database Toolkit

Declarative Go schemas, offline migration generation, pure-Go migrator, and compile-time-typed SQL query builder.

nockgithub.com/fletchhq/fletch/nock· fletch docs show data-and-migrations

On this page

Nock (github.com/fletchhq/fletch/nock) is Fletch’s standalone, pure-Go database toolkit. It combines a declarative Go schema DSL, an offline SQL migration generator, a built-in migrator for SQLite and Postgres, and a compile-time-typed SQL query builder. Nock has zero upward framework dependencies and can be used outside Fletch in any Go project.

Declarative Schema DSL (nock/schema)

Define tables in Go with schema.Table(name, parts...) and schema.Col(name). In a Fletch app, tables live in modules/<name>/schema.go or inside a modules/<name>/schema/ sub-package. Both fletch db generate and fletch gen parse module schemas via the Go AST without compiling or booting the application.

fletch check enforces table ownership boundaries: if another module imports modules/<other>/schema, fletch check fails with W0511.

package billing

import "github.com/fletchhq/fletch/nock/schema"

var Tables = []*schema.TableDef{
	schema.Table("invoices",
		schema.Col("id").UUID().PrimaryKey(),
		schema.Col("org_id").UUID().NotNull().References("orgs.id").OnDelete("CASCADE"),
		schema.Col("number").VarChar(64).NotNull().Unique(),
		schema.Col("status").Text().NotNull().Default("'draft'").Check("status IN ('draft','open','paid','void')"),
		schema.Col("amount_cents").BigInt().NotNull().Check("amount_cents >= 0"),
		schema.Col("tax_rate").Numeric(5, 4).NotNull().Default("0"),
		schema.Col("metadata").JSONB().Null(),
		schema.Col("issued_at").Timestamptz().Null(),
		schema.Timestamps(),
	).
		Index("org_id", "status").
		UniqueNamed("invoices_org_number_uniq", "org_id", "number").
		PartialIndex("invoices_open_org_idx", "status = 'open'", "org_id"),
}

Indexes are methods on the *schema.TableDef that schema.Table returns. Hold the tables in a list such as Tables, as the scaffold does: fletch gen writes the Invoices table descriptor plus InvoicesRow, InvoicesNew, and InvoicesPatch into schema_gen.go in the same package, so a hand-written var Invoices would collide with them. To pick a different generated prefix, chain .GoName("Bill") on the table.

Column Types

Method SQL Type
UUID() UUID column (TEXT on SQLite, UUID on Postgres).
Text() Variable-length unbounded text.
VarChar(n) Length-constrained character string.
Int() / BigInt() / SmallInt() 32-bit, 64-bit, and 16-bit signed integers.
Bool() Boolean column.
Float() Double-precision floating point.
Numeric(p, s) Exact decimal with precision p and scale s.
Timestamp() / Timestamptz() Timestamp without or with time zone.
Date() Calendar date.
JSONB() Structured JSON column.
Bytes() Binary byte slice (BLOB / BYTEA).

Column Modifiers & Table Options

Column modifiers chain directly off schema.Col(name): PrimaryKey(), NotNull(), Null(), Default(expr), Unique(), Check(expr) (column-level CHECK constraint), References(target), and OnDelete(action). schema.Timestamps() appends standard created_at and updated_at columns.

Table-level options configure indexes, constraints, and code generation:

Option Behavior
Index(cols...) Creates a composite or single-column index with an auto-generated name.
Unique(cols...) Creates a unique index with an auto-generated name.
IndexNamed(name, cols...) Creates an index with an explicit SQL identifier.
UniqueNamed(name, cols...) Creates a unique index with an explicit SQL identifier.
PartialIndex(name, whereExpr, cols...) Creates a filtered index matching whereExpr.
UniquePartialIndex(name, whereExpr, cols...) Creates a unique filtered index matching whereExpr.
Table.GoName(name) Overrides the generated Go struct and table identifier when the SQL table name is irregular or awkward.
var TaxData = schema.Table("tax_data",
	schema.Col("id").UUID().PrimaryKey(),
).GoName("TaxDatum")

Migrations (nock/migrate & CLI)

Nock ships a pure-Go offline schema differ and migration runner with no external Atlas or Goose binary required.

Generating Migrations

Run fletch db generate whenever you add or edit a table in modules/*/schema.go or modules/*/schema/:

fletch db generate add_invoices --dialect postgres
fletch db generate rename_invoice_num --rename invoices.num:number
fletch db generate --dry-run --json

fletch db generate [name] [--dialect sqlite|postgres] [--rename table.old:new] [--dry-run] [--json] parses all module schemas, topologically sorts cross-module foreign keys so referenced tables are created first, diffs against database/migrations/snapshot.json, and writes a timestamped SQL file into database/migrations/ containing -- +fletch up and -- +fletch down sections.

For Postgres extensions, custom triggers, views, or data backfills that sit outside table definitions, scaffold a manual migration:

fletch make migration enable_pg_trgm --sql

Running Migrations from the CLI

fletch db migrate [--dsn ...] [--json]
fletch db rollback [--dsn ...] [--json]
fletch db status [--dsn ...] [--json]
fletch db fresh [--dsn ...] [--json]
fletch db seed [--dsn ...] [--json]

The migrator acquires an advisory lock on Postgres (or transaction lock on SQLite) before applying files and stores a SHA-256 checksum per migration to detect edited history.

Programmatic Migrator (nock/migrate)

Run migrations directly from Go code or test suites with migrate.New:

m := migrate.New(
	db.Database, // the *nock.Database inside a *sqlite.DB or *postgres.DB
	migrationsFS,
	migrate.WithTable("schema_migrations"),
	migrate.WithLockKey(4242),
)

applied, err := m.Up(ctx)
if err != nil {
	return err
}

The migrator exposes Up, Down, Status, Fresh, and Seed. Up returns the migrations it applied. By default it refuses to run when an applied migration’s checksum no longer matches its file; pass migrate.WithAllowDrift() to permit that.

Opening Databases

SQLite (nock/sqlite)

db, err := sqlite.Open("file:app.db?_pragma=busy_timeout(5000)")

In tests, use sqlite.Memory(t) for an isolated in-memory database tied to t.Cleanup, or sqlite.NewTemplate(ctx, migrations) to migrate once and clone fast per-test SQLite instances.

Postgres (nock/postgres)

postgres.Open wraps a native pgx/v5 pool with production options and optional read replicas:

db, err := postgres.Open(
	ctx,
	cfg.Database.URL,
	postgres.WithMaxConns(25),
	postgres.WithMinConns(5),
	postgres.WithMaxConnLifetime(30*time.Minute),
	postgres.WithAcquireTimeout(5*time.Second),
	postgres.WithStatementTimeout(10*time.Second),
	postgres.WithReplica(cfg.Database.ReplicaURL),
	postgres.WithObserver(queryObserver),
	postgres.WithTxHook(txHook),
)

Use postgres.SetLocal inside a transaction to set transaction-scoped Postgres GUCs (such as row-level security tenant IDs), and postgres.StatementTimeout to tighten timeouts for specific queries.

When read replicas are configured, call nock.OnPrimary(ctx) to force a read query onto the primary database (for example, immediately after a write to avoid replication lag).

If you already hold a *sql.DB managed by another library, adapt it with nock.Wrap.

Compile-Time-Typed Query Builder

Run fletch gen to generate schema_gen.go alongside each module’s schema. The generated code exposes typed table descriptors, column fields, row structs, and New / Patch input types without reflection.

Select, Joins, CTEs, and Mutations

Builders describe a query; the package-level generic functions run it. nock.All[T] returns every row, nock.One[T] returns one row or nock.ErrNotFound, nock.Scalar[T] returns a single value, and nock.Exec runs a statement and returns its sql.Result. Each takes any nock.Executor: a database or a transaction.

q := nock.Select(Invoices.AllColumns()...).
	From(Invoices).
	LeftJoin(Orgs, Invoices.OrgID.EqCol(Orgs.ID)).
	Where(
		Invoices.Status.Eq("open"),
		nock.When(filterOrg != "", Invoices.OrgID.Eq(filterOrg)),
	).
	OrderBy(Invoices.CreatedAt.Desc()).
	Limit(50).
	Offset(0)

rows, err := nock.All[InvoicesRow](ctx, db, q)

The builder supports these statements and clauses. For SQL outside this list (window functions, UNION, vendor-specific syntax), write it with nock.Raw, which is also a query on its own:

  • Queries and CTEs: nock.Select, With (CTEs), Join, LeftJoin, RightJoin, Where, GroupBy, Having, OrderBy, Limit, Offset, ForUpdate, SkipLocked.
  • Mutations: nock.Insert, Update, Delete, Returning, OnConflict.
  • Conditional and raw expressions: nock.When(cond, expr) (omits the predicate when cond is false), colA.EqCol(colB) for column-to-column comparisons, nock.Raw(sql, args...).
  • Inspection: sql, args, err := q.ToSQL(dialect) renders the parameterized SQL string and argument slice for nock.SQLite or nock.Postgres (db.Dialect() returns the one in use).

Unscoped Mutation Guard

Running Update or Delete without a Where clause fails immediately with nock.ErrUnscopedMutation before touching the database. When a table-wide mutation is genuinely intended, opt in explicitly with .AllowUnscoped().

PATCH Updates with Optional[T]

Partial updates need three states per field: omitted (do not touch the column), explicit SQL NULL, or a concrete value. Nock’s Optional[T] encodes all three states cleanly:

type PatchInvoice struct {
	Status   nock.Optional[string]
	IssuedAt nock.Optional[time.Time]
}

patch := PatchInvoice{
	Status:   nock.Some("void"),
	IssuedAt: nock.Null[time.Time](),
}

_, err := nock.Exec(ctx, db, nock.Update(Invoices).
	Set(
		Invoices.Status.SetOptional(patch.Status),
		Invoices.IssuedAt.SetOptional(patch.IssuedAt),
	).
	Where(Invoices.ID.Eq(id)))

Unset Optional[T] fields produce no SQL assignment. nock.Some(v) sets the column to v, and nock.Null[T]() sets it to NULL. The generated InvoicesPatch type has an Optional[T] field per column, so nock.Update(Invoices).Patch(p) applies one directly.

Counts & Aggregates

Build aggregate queries or derive a count query directly from an existing Select:

q := nock.Select(Invoices.AllColumns()...).
	From(Invoices).
	Where(Invoices.OrgID.Eq(orgID))

total, err := nock.Count(ctx, db, q)
countSQL, args, err := q.CountQuery().ToSQL(db.Dialect())

Aggregate expression builders include nock.CountAll(), nock.CountCol(e), nock.CountDistinct(e), nock.Sum(e), nock.Avg(e), nock.Min(e), nock.Max(e), and nock.Coalesce(es...).

Safe LIKE, Prefix, and Contains Matching

Raw Like and ILike pass patterns directly to SQL and do not escape % or _ characters in user input. Whenever matching user-supplied search text, use the escaping helpers instead:

Method / Function Behavior
nock.EscapeLike(s) Escapes %, _, and the escape character in s.
col.Contains(s) / col.ContainsFold(s) Escaped substring match (case-sensitive / case-insensitive).
col.HasPrefix(s) / col.HasPrefixFold(s) Escaped prefix match (case-sensitive / case-insensitive).
col.HasSuffix(s) / col.HasSuffixFold(s) Escaped suffix match (case-sensitive / case-insensitive).
q := nock.Select(Invoices.AllColumns()...).
	From(Invoices).
	Where(Invoices.Number.ContainsFold(searchQuery))

Pagination & Safe Sorting

nock.Paginate[T](ctx, ex, q, page, perPage) executes the count query and paged fetch, returning PageResult[T] containing Items and PageMeta. You can also apply q.Page(page, perPage) directly or normalize bounds manually with nock.ClampPage and nock.NewPageMeta.

Map untrusted query-string sort parameters to explicit column expressions using nock.SortMap:

var invoiceSort = nock.SortMap{
	"newest": Invoices.CreatedAt.Desc(),
	"oldest": Invoices.CreatedAt.Asc(),
	"amount": Invoices.AmountCents.Desc(),
}

q := nock.Select(Invoices.AllColumns()...).
	From(Invoices).
	OrderBy(invoiceSort.Orders(r.URL.Query().Get("sort"), Invoices.CreatedAt.Desc())...)

res, err := nock.Paginate[InvoicesRow](ctx, db, q, page, 25)

Orders(param, fallback...) ignores unknown sort keys and applies the fallback ordering, preventing arbitrary column injection.

SQLite Timestamps

SQLite stores timestamps as TEXT (often RFC3339 strings), while Postgres returns native time.Time values for timestamptz. Use nock.Time, nock.NullTime, and nock.ScanTime so the same row scanning code works identically across both dialects.

Explicit Preloading

Nock never triggers lazy queries during field access. Load related records in a bounded number of batch queries with nock.Preload:

err := nock.Preload(
	ctx,
	db,
	invoices,
	nock.BelongsTo(/* org relation */),
	nock.HasMany(/* line items relation */),
)

Transactions & Sentinel Errors

Wrap multi-statement writes in nock.Tx and consistent multi-query reads in nock.ReadOnlyTx:

err := nock.Tx(ctx, db, func(tx nock.Executor) error {
	if _, err := nock.Exec(ctx, tx, nock.Insert(Invoices).Row(inv)); err != nil { // inv is an InvoicesNew
		return err
	}
	return nil
})

Database driver errors are normalized to package-level sentinels so calling code can check them with errors.Is:

Error Condition
nock.ErrNotFound Single-row query returned zero rows.
nock.ErrUniqueViolation Insert or update violated a UNIQUE or primary key constraint.
nock.ErrForeignKey Insert, update, or delete violated a foreign key constraint.
nock.ErrUnscopedMutation Update or Delete was executed without Where or .AllowUnscoped().