Files
zeekayandGitHub 3206f5140c store: the engine runs on PostgreSQL (hanzo-sql) as well as SQLite (#3)
A host that keeps its stores on a server passes Config.Postgres with the handle it opens.
The engine then writes numbered placeholders, keeps a document's data in JSONB, migrates
in one transaction under an advisory lock (CREATE TABLE IF NOT EXISTS is not safe against
itself), reads the schema from information_schema, and leaves the pragmas and the single
connection to the host. SQLite is unchanged: ? placeholders, a text column, the same DDL.

Both engines use ->> to look inside a document (CAST(data->>? AS TEXT)), where SQLite had
json_extract; times and counters are BIGINT; docstatus filters are typed for the column;
the series upsert names its table (the column was ambiguous); a lock or series key, which
joins its parts with NUL, is stored in hex on PostgreSQL, which cannot hold NUL in text.

Testing: the whole suite runs on both engines. FRAMEWORK_TEST_POSTGRES_DSN names a server;
each test gets a schema of its own. go test ./... passes on SQLite and on a throwaway
PostgreSQL 16, 0 failures on either.
Risk: a custom sort field now orders as text on SQLite too (it was the native JSON type);
doctype, document, naming and lock behaviour is unchanged on SQLite (suite green).
How to revert: git revert this commit.

Claude-Session: https://claude.ai/code/session_015XYKLn69gF4x75RWePpDBV
2026-11-21 00:17:43 -08:00

1011 lines
35 KiB
Go

package framework
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
// github.com/hanzoai/sqlite is the ONE Hanzo SQLite driver: it registers
// the "sqlite" database/sql name under both build tags (cgo →
// mattn+SQLCipher, encrypted at rest; !cgo → pure-Go modernc). Importing
// modernc directly instead would double-register "sqlite" under CGO and
// panic at init. Blank import registers the driver.
"github.com/hanzoai/doctype"
_ "github.com/hanzoai/sqlite"
)
// Store is the framework database. ONE SQLite file ({DataDir}/framework.db) holds
// every org's DocTypes, documents, naming counters, and role assignments; tenant
// isolation is the `org` column, present on EVERY table and EVERY query. This is
// the ONE storage pattern (mirrors clients/crm, clients/cms). MaxOpenConns(1)
// serializes writes against the single-writer SQLite file.
type Store struct {
db *sql.DB
pg bool // the handle is on PostgreSQL (hanzo-sql), else SQLite
}
// bind writes q for the engine the store is on: SQLite reads the ? placeholders as written,
// PostgreSQL the numbered $n.
func (s *Store) bind(q string) string { return bind(s.pg, q) }
func bind(pg bool, q string) string {
if !pg {
return q
}
var b strings.Builder
n := 0
for i := 0; i < len(q); i++ {
if q[i] == '?' {
n++
b.WriteString("$" + strconv.Itoa(n))
continue
}
b.WriteByte(q[i])
}
return b.String()
}
// openStore opens (and migrates) the engine's database. `open` is the host's
// opener — nil means the plain hanzoai/sqlite driver, which is what a
// standalone app or a test wants; Hanzo Cloud injects an encrypted-at-rest one.
func openStore(path string, open OpenDBFunc, pg bool) (*Store, error) {
if open == nil {
open = func(p string) (*sql.DB, error) { return sql.Open("sqlite", p) }
}
db, err := open(path)
if err != nil {
return nil, fmt.Errorf("open %q: %w", path, err)
}
if !pg {
db.SetMaxOpenConns(1)
for _, pragma := range []string{
"PRAGMA busy_timeout=5000",
"PRAGMA journal_mode=WAL",
"PRAGMA foreign_keys=ON",
} {
if _, err := db.Exec(pragma); err != nil {
_ = db.Close()
return nil, fmt.Errorf("pragma %q: %w", pragma, err)
}
}
}
s := &Store{db: db, pg: pg}
if err := s.migrate(); err != nil {
_ = db.Close()
return nil, err
}
return s, nil
}
// migrate brings the database to the current schema: first the upgrade from the
// previous one, then the tables themselves. Idempotent (IF NOT EXISTS), and the
// upgrade is a no-op on a database that never held the old shape.
//
// Every table leads its primary key with `org` so tenant isolation is a physical
// property of the schema, not merely a WHERE clause. A DocType is then keyed by
// (module, name) and a document by (module, doctype, name): the module is half of
// the key, not a column beside it, which is what makes two lanes' "page" two rows
// instead of a collision.
func (s *Store) migrate() error {
if s.pg {
return s.migratePostgres(context.Background())
}
if err := s.upgrade(); err != nil {
return err
}
if _, err := s.db.Exec(s.schema("fw_doctypes", "fw_documents")); err != nil {
return fmt.Errorf("framework migrate: %w", err)
}
return s.widen(context.Background())
}
// migrationLock is the advisory lock a PostgreSQL migration takes, so two pods starting
// together do not race CREATE TABLE IF NOT EXISTS, which is not safe against itself.
const migrationLock = 0x66774d69 // "fwMi"
// migratePostgres creates the schema in one transaction holding migrationLock. A database
// born here never held the SQLite shape upgrade rebuilds, so there is nothing to upgrade.
func (s *Store) migratePostgres(ctx context.Context) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("framework migrate: %w", err)
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, migrationLock); err != nil {
return fmt.Errorf("framework migrate: lock: %w", err)
}
if _, err := tx.ExecContext(ctx, s.schema("fw_doctypes", "fw_documents")); err != nil {
return fmt.Errorf("framework migrate: %w", err)
}
return tx.Commit()
}
// widen adds a column to a table that already exists, which CREATE TABLE IF NOT
// EXISTS cannot. SQLite adds one in place when it carries a default, and
// pragma_table_info says whether it is already there — the same shape signal
// `stale` reads, and what is actually true where a version counter only claims
// it.
func (s *Store) widen(ctx context.Context) error {
for _, add := range []struct{ table, column, ddl string }{
{"fw_doctypes", "immutable", `ALTER TABLE fw_doctypes ADD COLUMN immutable INTEGER NOT NULL DEFAULT 0`},
} {
cols, err := s.columns(ctx, add.table)
if err != nil {
return err
}
if cols[add.column] {
continue
}
if _, err := s.db.ExecContext(ctx, s.bind(add.ddl)); err != nil {
return fmt.Errorf("framework migrate: %s.%s: %w", add.table, add.column, err)
}
}
return nil
}
// columns is a table's column names, empty for a table that does not exist.
func (s *Store) columns(ctx context.Context, table string) (map[string]bool, error) {
q := `SELECT name FROM pragma_table_info(?)`
if s.pg {
q = `SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ?`
}
rows, err := s.db.QueryContext(ctx, s.bind(q), table)
if err != nil {
return nil, fmt.Errorf("read schema: %w", err)
}
defer func() { _ = rows.Close() }()
out := map[string]bool{}
for rows.Next() {
var col string
if err := rows.Scan(&col); err != nil {
return nil, err
}
out[col] = true
}
return out, rows.Err()
}
// The schema, one template per table so the upgrade (upgrade.go) stages the
// SAME definition under a temporary name — a second copy of these columns is
// how a rebuilt table comes to differ from a freshly created one. A document's data
// is JSONB on PostgreSQL, so SQL can look inside it with ->>, and text on SQLite.
const (
doctypesDDL = `
CREATE TABLE IF NOT EXISTS %s (
org TEXT NOT NULL,
name TEXT NOT NULL,
module TEXT NOT NULL,
is_single INTEGER NOT NULL DEFAULT 0,
is_submittable INTEGER NOT NULL DEFAULT 0,
immutable INTEGER NOT NULL DEFAULT 0,
autoname TEXT NOT NULL DEFAULT '',
title_field TEXT NOT NULL DEFAULT '',
fields TEXT NOT NULL DEFAULT '[]',
permissions TEXT NOT NULL DEFAULT '[]',
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
PRIMARY KEY (org, module, name)
);
`
documentsDDL = `
CREATE TABLE IF NOT EXISTS %s (
org TEXT NOT NULL,
module TEXT NOT NULL,
doctype TEXT NOT NULL,
name TEXT NOT NULL,
docstatus INTEGER NOT NULL DEFAULT 0,
data %s NOT NULL DEFAULT '{}',
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
PRIMARY KEY (org, module, doctype, name)
);
`
// The tables nothing re-keyed, plus the one index the address key does not
// already provide as a prefix of itself.
indexDDL = `
CREATE INDEX IF NOT EXISTS ix_fw_documents_updated ON fw_documents(org, module, doctype, updated_at);
CREATE TABLE IF NOT EXISTS fw_series (
org TEXT NOT NULL,
series TEXT NOT NULL,
current BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (org, series)
);
CREATE TABLE IF NOT EXISTS fw_locks (
org TEXT NOT NULL,
lockkey TEXT NOT NULL,
holder TEXT NOT NULL,
expires_at BIGINT NOT NULL, -- unix nanos; a lease auto-expires so a crashed holder never wedges
PRIMARY KEY (org, lockkey)
);
`
)
// dataType is the type of a document's data column on the engine.
func (s *Store) dataType() string {
if s.pg {
return "JSONB"
}
return "TEXT"
}
// tables is the DDL of the two tables under the given names.
func (s *Store) tables(doctypes, documents string) string {
return fmt.Sprintf(doctypesDDL, doctypes) + fmt.Sprintf(documentsDDL, documents, s.dataType())
}
// schema is tables under their own names, and the rest.
func (s *Store) schema(doctypes, documents string) string {
return s.tables(doctypes, documents) + indexDDL
}
// Close closes the underlying database. Idempotent-safe via sql.DB.
func (s *Store) Close() error { return s.db.Close() }
// ---- DocType registry ----
func (s *Store) CreateDocType(ctx context.Context, org string, dt DocType) (DocType, error) {
dt.Normalize()
now := time.Now().Unix()
dt.CreatedAt, dt.UpdatedAt = now, now
fieldsJSON, _ := json.Marshal(dt.Fields)
permsJSON, _ := json.Marshal(dt.Perms)
_, err := s.db.ExecContext(ctx,
s.bind(`INSERT INTO fw_doctypes (org,name,module,is_single,is_submittable,immutable,autoname,title_field,fields,permissions,created_at,updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`),
org, dt.Name, dt.Module, b2i(dt.IsSingle), b2i(dt.IsSubmittable), b2i(dt.Immutable), dt.Autoname, dt.TitleField,
string(fieldsJSON), string(permsJSON), now, now)
if err != nil {
if isUnique(err) {
return DocType{}, ErrConflict
}
return DocType{}, fmt.Errorf("insert doctype: %w", err)
}
return dt, nil
}
// GetDocType resolves a DocType for an org: the definition the org holds, and for a
// DocType a module declares, the module's as it is now.
//
// A module's definition is the module's (an org cannot replace it, see ours), so a
// stored copy is only the module's shape as of the org's install. Resolving the
// stored copy alone held that shape for good, and every field the module added
// since was dropped from each write with no error: an org's crm.lead went on
// discarding program, answers and the campaign tags for weeks. So the copy is
// resolved grown by every field the module now declares and it lacks (the same
// `missing` an install appends), and a DocType a module added after the org
// installed it resolves from the fixture once the org holds any of the module's
// DocTypes. Nothing is written here; an install still persists the grown copy.
func (s *Store) GetDocType(ctx context.Context, org string, id doctype.ID) (DocType, error) {
dt, err := s.stored(ctx, org, id)
if errors.Is(err, ErrNotFound) {
// No stored (per-org) definition. An always-on module's fixture resolves
// virtually so a fresh org uses the lane without a per-org install. Only the
// DocType DEFINITION resolves this way — every document row stays physically
// org-scoped (see always_on_isolation_test.go), so this exposes schema, never
// another org's data.
if fx, ok := doctype.AlwaysOn(id); ok {
return fx, nil
}
if fx, ok := fixture(id); ok {
held, err := s.holds(ctx, org, id.Module)
if err != nil {
return DocType{}, err
}
if held {
return fx, nil
}
}
return DocType{}, ErrNotFound
}
if err != nil {
return DocType{}, err
}
return current(dt), nil
}
// stored is the definition the org's row holds, exactly as written.
func (s *Store) stored(ctx context.Context, org string, id doctype.ID) (DocType, error) {
row := s.db.QueryRowContext(ctx,
s.bind(`SELECT name,module,is_single,is_submittable,immutable,autoname,title_field,fields,permissions,created_at,updated_at
FROM fw_doctypes WHERE org=? AND module=? AND name=?`), org, id.Module, id.Name)
dt, err := scanDocType(row)
if errors.Is(err, sql.ErrNoRows) {
return DocType{}, ErrNotFound
}
if err != nil {
return DocType{}, fmt.Errorf("get doctype: %w", err)
}
return dt, nil
}
// holds reports whether the org has installed the module: it stores at least one
// of the module's DocTypes.
func (s *Store) holds(ctx context.Context, org, module string) (bool, error) {
var one int
err := s.db.QueryRowContext(ctx, s.bind(`SELECT 1 FROM fw_doctypes WHERE org=? AND module=? LIMIT 1`), org, module).Scan(&one)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("module held: %w", err)
}
return true, nil
}
// fixture is the module's declaration of id, stamped with its module and
// normalized, as an install would store it.
func fixture(id doctype.ID) (DocType, bool) {
for _, dt := range doctype.Fixtures(id.Module) {
if dt.Name == id.Name {
dt.Module = id.Module
dt.Fields = append([]DocField(nil), dt.Fields...)
dt.Perms = append([]DocPerm(nil), dt.Perms...)
dt.Normalize()
return dt, true
}
}
return DocType{}, false
}
// current is a stored definition with every field its module now declares and it
// lacks appended. An org's own DocType, which no module declares, is as stored, and
// so is a stored copy of an always-on module's DocType: no install writes one, so it
// is the org's customization and wins whole (always_on_test.go).
func current(dt DocType) DocType {
if _, on := doctype.AlwaysOn(dt.ID()); on {
return dt
}
if fx, ok := fixture(dt.ID()); ok {
if more := missing(dt, fx); len(more) > 0 {
dt.Fields = append(append([]DocField(nil), dt.Fields...), more...)
}
}
return dt
}
func (s *Store) ListDocTypes(ctx context.Context, org string) ([]DocType, error) {
rows, err := s.db.QueryContext(ctx,
s.bind(`SELECT name,module,is_single,is_submittable,immutable,autoname,title_field,fields,permissions,created_at,updated_at
FROM fw_doctypes WHERE org=? ORDER BY name ASC`), org)
if err != nil {
return nil, fmt.Errorf("list doctypes: %w", err)
}
defer func() { _ = rows.Close() }()
out := make([]DocType, 0, 16)
seen := make(map[doctype.ID]bool, 16)
for rows.Next() {
dt, err := scanDocType(rows)
if err != nil {
return nil, fmt.Errorf("scan doctype: %w", err)
}
out = append(out, current(dt))
seen[dt.ID()] = true
}
if err := rows.Err(); err != nil {
return nil, err
}
// A DocType a module declares and the org lacks lists once the org holds the
// module, as GetDocType resolves it.
held := map[string]bool{}
for _, dt := range out {
held[dt.Module] = true
}
for m := range held {
for _, fx := range doctype.Fixtures(m) {
if dt, ok := fixture(doctype.ID{Module: m, Name: fx.Name}); ok && !seen[dt.ID()] {
out = append(out, dt)
seen[dt.ID()] = true
}
}
}
// Union the always-on fixtures this org has NOT customized (a stored row wins), so
// the listing matches GetDocType. Then re-sort by name to preserve the ORDER BY
// name ASC contract across the union.
for _, fx := range doctype.AlwaysOnAll() {
if !seen[fx.ID()] {
out = append(out, fx)
seen[fx.ID()] = true
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out, nil
}
// ReplaceDocType replaces an existing DocType's definition (PUT semantics). The
// documents already stored under it are left intact (a schema change never
// silently drops data); the next write validates against the new schema.
func (s *Store) ReplaceDocType(ctx context.Context, org string, dt DocType) (DocType, error) {
dt.Normalize()
fieldsJSON, _ := json.Marshal(dt.Fields)
permsJSON, _ := json.Marshal(dt.Perms)
now := time.Now().Unix()
res, err := s.db.ExecContext(ctx,
s.bind(`UPDATE fw_doctypes SET module=?,is_single=?,is_submittable=?,immutable=?,autoname=?,title_field=?,fields=?,permissions=?,updated_at=?
WHERE org=? AND module=? AND name=?`),
dt.Module, b2i(dt.IsSingle), b2i(dt.IsSubmittable), b2i(dt.Immutable), dt.Autoname, dt.TitleField,
string(fieldsJSON), string(permsJSON), now, org, dt.Module, dt.Name)
if err != nil {
return DocType{}, fmt.Errorf("update doctype: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return DocType{}, ErrNotFound
}
return s.GetDocType(ctx, org, dt.ID())
}
// DeleteDocType removes a DocType and ALL of its documents in one transaction —
// there are no orphaned documents without a schema. Returns false if absent.
func (s *Store) DeleteDocType(ctx context.Context, org string, id doctype.ID) (bool, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return false, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, s.bind(`DELETE FROM fw_doctypes WHERE org=? AND module=? AND name=?`), org, id.Module, id.Name)
if err != nil {
return false, fmt.Errorf("delete doctype: %w", err)
}
if _, err := tx.ExecContext(ctx, s.bind(`DELETE FROM fw_documents WHERE org=? AND module=? AND doctype=?`), org, id.Module, id.Name); err != nil {
return false, fmt.Errorf("delete documents: %w", err)
}
n, _ := res.RowsAffected()
if err := tx.Commit(); err != nil {
return false, fmt.Errorf("commit: %w", err)
}
return n > 0, nil
}
func scanDocType(sc interface{ Scan(...any) error }) (DocType, error) {
var (
dt DocType
single, submittable, immutable int
fieldsJSON, permsJSON string
)
if err := sc.Scan(&dt.Name, &dt.Module, &single, &submittable, &immutable, &dt.Autoname, &dt.TitleField,
&fieldsJSON, &permsJSON, &dt.CreatedAt, &dt.UpdatedAt); err != nil {
return DocType{}, err
}
dt.IsSingle = single != 0
dt.IsSubmittable = submittable != 0
dt.Immutable = immutable != 0
_ = json.Unmarshal([]byte(fieldsJSON), &dt.Fields)
_ = json.Unmarshal([]byte(permsJSON), &dt.Perms)
if dt.Fields == nil {
dt.Fields = []DocField{}
}
if dt.Perms == nil {
dt.Perms = []DocPerm{}
}
return dt, nil
}
// ---- Documents ----
// Document is a schemaless record: Data holds the validated field values, keyed
// by fieldname. The HTTP layer serializes it via wireDoc (Data + envelope keys),
// so this internal shape is the ONE representation the store works with.
type Document struct {
Name string
DocType doctype.ID
DocStatus int
Data map[string]any
CreatedAt int64
UpdatedAt int64
}
// CreateDocument names and inserts a validated document at docstatus 0. `data`
// is the canonical, already-validated field map (the service calls validateDoc
// first). Naming follows dt.Autoname; series naming increments a per-org counter
// inside the same transaction so concurrent creates never collide.
func (s *Store) CreateDocument(ctx context.Context, org string, dt *DocType, data map[string]any, requestedName string) (Document, error) {
now := time.Now().Unix()
blob, err := json.Marshal(data)
if err != nil {
return Document{}, fmt.Errorf("marshal data: %w", err)
}
insert := func(ctx context.Context, x execer, name string) error {
_, err := x.ExecContext(ctx,
s.bind(`INSERT INTO fw_documents (org,module,doctype,name,docstatus,data,created_at,updated_at) VALUES (?,?,?,?,0,?,?,?)`),
org, dt.Module, dt.Name, name, string(blob), now, now)
return err
}
switch {
case doctype.IsSeries(dt.Autoname):
ser := doctype.ExpandSeries(dt.Autoname, time.Now())
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Document{}, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }()
n, err := s.nextSeries(ctx, tx, org, ser.Key)
if err != nil {
return Document{}, err
}
name := ser.Format(n)
if err := insert(ctx, tx, name); err != nil {
if isUnique(err) {
return Document{}, ErrConflict
}
return Document{}, fmt.Errorf("insert document: %w", err)
}
if err := tx.Commit(); err != nil {
return Document{}, fmt.Errorf("commit: %w", err)
}
return Document{Name: name, DocType: dt.ID(), Data: data, CreatedAt: now, UpdatedAt: now}, nil
default:
name, err := doctype.ResolveName(dt, data, requestedName)
if err != nil {
return Document{}, err
}
if err := insert(ctx, s.db, name); err != nil {
if isUnique(err) {
return Document{}, ErrConflict
}
return Document{}, fmt.Errorf("insert document: %w", err)
}
return Document{Name: name, DocType: dt.ID(), Data: data, CreatedAt: now, UpdatedAt: now}, nil
}
}
// UpsertSingle writes THE single document of a Single DocType (name == doctype
// name), creating or replacing it. A Single never has more than one row per org.
func (s *Store) UpsertSingle(ctx context.Context, org string, dt *DocType, data map[string]any) (Document, error) {
now := time.Now().Unix()
blob, err := json.Marshal(data)
if err != nil {
return Document{}, fmt.Errorf("marshal data: %w", err)
}
_, err = s.db.ExecContext(ctx,
s.bind(`INSERT INTO fw_documents (org,module,doctype,name,docstatus,data,created_at,updated_at) VALUES (?,?,?,?,0,?,?,?)
ON CONFLICT(org,module,doctype,name) DO UPDATE SET data=excluded.data, updated_at=excluded.updated_at`),
org, dt.Module, dt.Name, dt.Name, string(blob), now, now)
if err != nil {
return Document{}, fmt.Errorf("upsert single: %w", err)
}
return s.GetDocument(ctx, org, dt.ID(), dt.Name)
}
func (s *Store) GetDocument(ctx context.Context, org string, id doctype.ID, name string) (Document, error) {
row := s.db.QueryRowContext(ctx,
s.bind(`SELECT name,docstatus,data,created_at,updated_at FROM fw_documents WHERE org=? AND module=? AND doctype=? AND name=?`),
org, id.Module, id.Name, name)
d, err := scanDocument(row, id)
if errors.Is(err, sql.ErrNoRows) {
return Document{}, ErrNotFound
}
if err != nil {
return Document{}, fmt.Errorf("get document: %w", err)
}
return d, nil
}
// ListOpts is a parsed, validated list query. Filters keys are declared field
// names (or the special "name"/"docstatus"); OrderField is a resolved sort key.
type ListOpts struct {
Filters map[string]string
// Among is set membership: each named field must hold one of the values
// named for it. Equality can only ask about one value, so a question about a
// set — the incidents at these sites, in these states — had to be asked once
// per value and the answers merged, which is a window per value rather than
// the caller's own. A field named with an empty set matches nothing.
Among map[string][]string
OrderField string // "" → updated_at
Desc bool
Limit int
// After is a keyset cursor: the last row returned on the previous page, used
// to fetch the page that follows it without repeating or skipping a row. Its
// shape depends on the order key: for the default ordering (updated_at DESC,
// name DESC as tie-break) both fields are set; for name ordering only Name
// is. The zero value means the first page.
After After
}
// After is a keyset cursor: the values of the last row returned on the previous
// page, used to fetch the page that follows it. For the default ordering
// (updated_at DESC, name DESC) it carries both values; for name ordering it
// carries just the name.
type After struct {
UpdatedAt int64
Name string
}
// ListDocuments returns the org's documents of a doctype, applying equality
// filters (via ->>, all values BOUND), an order key, and a bounded
// limit. Every value is a bound parameter and every field name is validated
// against the doctype's schema before it reaches a json path.
func (s *Store) ListDocuments(ctx context.Context, org string, id doctype.ID, opts ListOpts) ([]Document, error) {
q, args, any := listQuery(s.pg, org, id, opts, "name,docstatus,data,created_at,updated_at")
if !any {
return []Document{}, nil
}
rows, err := s.db.QueryContext(ctx, s.bind(q), args...)
if err != nil {
return nil, fmt.Errorf("list documents: %w", err)
}
defer func() { _ = rows.Close() }()
out := make([]Document, 0, 16)
for rows.Next() {
d, err := scanDocument(rows, id)
if err != nil {
return nil, fmt.Errorf("scan document: %w", err)
}
out = append(out, d)
}
return out, rows.Err()
}
// ListNames is the same question asked for identity alone: WHICH documents
// match, without their field data. A caller that needs the set — the sites one
// customer's estate is made of — otherwise pays the JSON of every document to
// learn a name the row carries in a column of its own.
func (s *Store) ListNames(ctx context.Context, org string, id doctype.ID, opts ListOpts) ([]string, error) {
q, args, any := listQuery(s.pg, org, id, opts, "name")
if !any {
return []string{}, nil
}
rows, err := s.db.QueryContext(ctx, s.bind(q), args...)
if err != nil {
return nil, fmt.Errorf("list names: %w", err)
}
defer func() { _ = rows.Close() }()
out := make([]string, 0, 16)
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, fmt.Errorf("scan name: %w", err)
}
out = append(out, name)
}
return out, rows.Err()
}
// status is a docstatus filter value as the column compares it: PostgreSQL will not compare
// an integer column with text, so a value that is not a number matches nothing there, as it
// does on SQLite.
func status(pg bool, v string) (any, bool) {
if !pg {
return v, true
}
n, err := strconv.Atoi(v)
return n, err == nil
}
// listQuery builds one list read over `cols`. It answers false when the query
// can match nothing, which is what a field named with an empty set means.
func listQuery(pg bool, org string, id doctype.ID, opts ListOpts, cols string) (string, []any, bool) {
var (
where = []string{"org=?", "module=?", "doctype=?"}
args = []any{org, id.Module, id.Name}
)
for field, val := range opts.Filters {
switch field {
case "name":
where = append(where, "name=?")
args = append(args, val)
case "docstatus":
v, ok := status(pg, val)
if !ok {
return "", nil, false
}
where = append(where, "docstatus=?")
args = append(args, v)
default:
// The field name is a bound label — no interpolation.
where = append(where, "CAST(data->>? AS TEXT)=?")
args = append(args, field, val)
}
}
// Field names in order, so one question is always one query text; every value
// is bound, exactly as an equality's is.
among := make([]string, 0, len(opts.Among))
for field := range opts.Among {
among = append(among, field)
}
sort.Strings(among)
for _, field := range among {
vals := opts.Among[field]
if len(vals) == 0 {
return "", nil, false
}
marks := strings.TrimSuffix(strings.Repeat("?,", len(vals)), ",")
switch field {
case "name":
where = append(where, "name IN ("+marks+")")
case "docstatus":
where = append(where, "docstatus IN ("+marks+")")
default:
where = append(where, "CAST(data->>? AS TEXT) IN ("+marks+")")
args = append(args, field)
}
for _, v := range vals {
if field == "docstatus" {
n, ok := status(pg, v)
if !ok {
return "", nil, false
}
args = append(args, n)
continue
}
args = append(args, v)
}
}
order := "updated_at, name"
switch opts.OrderField {
case "", "modified", "updated_at":
order = "updated_at, name"
case "creation", "created_at":
order = "created_at, name"
case "name":
order = "name"
case "docstatus":
order = "docstatus"
default:
order = "CAST(data->>? AS TEXT), name"
}
dir := "DESC"
if !opts.Desc {
dir = "ASC"
}
limit := opts.Limit
if limit <= 0 || limit > doctype.MaxLimit {
limit = doctype.DefaultLimit
}
// Keyset paging: only rows strictly before (or after, when ascending) the
// last row of the previous page. Every value is a bound parameter.
if opts.After.UpdatedAt != 0 || opts.After.Name != "" {
switch opts.OrderField {
case "", "modified", "updated_at":
if opts.Desc {
where = append(where, "(updated_at < ? OR (updated_at = ? AND name < ?))")
args = append(args, opts.After.UpdatedAt, opts.After.UpdatedAt, opts.After.Name)
} else {
where = append(where, "(updated_at > ? OR (updated_at = ? AND name > ?))")
args = append(args, opts.After.UpdatedAt, opts.After.UpdatedAt, opts.After.Name)
}
case "name":
if opts.Desc {
where = append(where, "name < ?")
} else {
where = append(where, "name > ?")
}
args = append(args, opts.After.Name)
case "created_at":
if opts.Desc {
where = append(where, "(created_at < ? OR (created_at = ? AND name < ?))")
} else {
where = append(where, "(created_at > ? OR (created_at = ? AND name > ?))")
}
args = append(args, opts.After.UpdatedAt, opts.After.UpdatedAt, opts.After.Name)
case "docstatus":
if opts.Desc {
where = append(where, "docstatus < ?")
} else {
where = append(where, "docstatus > ?")
}
args = append(args, opts.After.UpdatedAt)
}
}
// Apply dir to EVERY order column. `ORDER BY updated_at, name DESC` would
// leave updated_at ascending, which breaks the keyset predicate that assumes
// both columns share the same direction.
orderBy := ""
for i, col := range strings.Split(order, ", ") {
if i > 0 {
orderBy += ", "
}
orderBy += col + " " + dir
}
q := `SELECT ` + cols + ` FROM fw_documents WHERE ` +
strings.Join(where, " AND ") + ` ORDER BY ` + orderBy + ` LIMIT ?`
if strings.Contains(order, "data->>?") {
args = append(args, opts.OrderField)
}
return q, append(args, limit), true
}
// UpdateDocument replaces a document's data. Only a DRAFT (docstatus 0) is
// editable — a submitted/cancelled document is immutable (ErrBadState) so the
// submit lifecycle can't be bypassed by a plain PUT. `data` is already validated.
func (s *Store) UpdateDocument(ctx context.Context, org string, dt *DocType, name string, data map[string]any) (Document, error) {
blob, err := json.Marshal(data)
if err != nil {
return Document{}, fmt.Errorf("marshal data: %w", err)
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Document{}, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }()
var status int
err = tx.QueryRowContext(ctx, s.bind(`SELECT docstatus FROM fw_documents WHERE org=? AND module=? AND doctype=? AND name=?`),
org, dt.Module, dt.Name, name).Scan(&status)
if errors.Is(err, sql.ErrNoRows) {
return Document{}, ErrNotFound
}
if err != nil {
return Document{}, fmt.Errorf("lock document: %w", err)
}
if status != 0 {
return Document{}, ErrBadState
}
now := time.Now().Unix()
if _, err := tx.ExecContext(ctx, s.bind(`UPDATE fw_documents SET data=?, updated_at=? WHERE org=? AND module=? AND doctype=? AND name=?`),
string(blob), now, org, dt.Module, dt.Name, name); err != nil {
return Document{}, fmt.Errorf("update document: %w", err)
}
if err := tx.Commit(); err != nil {
return Document{}, fmt.Errorf("commit: %w", err)
}
return s.GetDocument(ctx, org, dt.ID(), name)
}
// SetDocStatus transitions a document from `from` to `to` atomically, verifying
// the current status equals `from` (else ErrBadState). This is the ONE path for
// submit (0→1) and cancel (1→2); the check-and-set is inside a transaction so two
// concurrent submits can't both win.
func (s *Store) SetDocStatus(ctx context.Context, org string, id doctype.ID, name string, from, to int) (Document, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Document{}, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }()
var status int
err = tx.QueryRowContext(ctx, s.bind(`SELECT docstatus FROM fw_documents WHERE org=? AND module=? AND doctype=? AND name=?`),
org, id.Module, id.Name, name).Scan(&status)
if errors.Is(err, sql.ErrNoRows) {
return Document{}, ErrNotFound
}
if err != nil {
return Document{}, fmt.Errorf("lock document: %w", err)
}
if status != from {
return Document{}, ErrBadState
}
now := time.Now().Unix()
if _, err := tx.ExecContext(ctx, s.bind(`UPDATE fw_documents SET docstatus=?, updated_at=? WHERE org=? AND module=? AND doctype=? AND name=?`),
to, now, org, id.Module, id.Name, name); err != nil {
return Document{}, fmt.Errorf("set docstatus: %w", err)
}
if err := tx.Commit(); err != nil {
return Document{}, fmt.Errorf("commit: %w", err)
}
return s.GetDocument(ctx, org, id, name)
}
// DeleteDocument removes a document by key. Returns false if absent. The service
// enforces the lifecycle guard (a submitted doc must be cancelled first).
func (s *Store) DeleteDocument(ctx context.Context, org string, id doctype.ID, name string) (bool, error) {
res, err := s.db.ExecContext(ctx, s.bind(`DELETE FROM fw_documents WHERE org=? AND module=? AND doctype=? AND name=?`), org, id.Module, id.Name, name)
if err != nil {
return false, fmt.Errorf("delete document: %w", err)
}
n, _ := res.RowsAffected()
return n > 0, nil
}
// CountDocuments returns the org's document count for a doctype (real, per-org).
func (s *Store) CountDocuments(ctx context.Context, org string, id doctype.ID) (int, error) {
var n int
err := s.db.QueryRowContext(ctx, s.bind(`SELECT COUNT(*) FROM fw_documents WHERE org=? AND module=? AND doctype=?`), org, id.Module, id.Name).Scan(&n)
return n, err
}
func scanDocument(sc interface{ Scan(...any) error }, id doctype.ID) (Document, error) {
var (
d Document
blob string
)
if err := sc.Scan(&d.Name, &d.DocStatus, &blob, &d.CreatedAt, &d.UpdatedAt); err != nil {
return Document{}, err
}
d.DocType = id
if err := json.Unmarshal([]byte(blob), &d.Data); err != nil {
return Document{}, fmt.Errorf("unmarshal data: %w", err)
}
if d.Data == nil {
d.Data = map[string]any{}
}
return d, nil
}
// documentExists reports whether (org, doctype, name) exists — the in-org Link
// reference check. table/column are constants; name is a bound parameter.
func (s *Store) documentExists(ctx context.Context, org string, id doctype.ID, name string) (bool, error) {
if name == "" {
return false, nil
}
var one int
err := s.db.QueryRowContext(ctx,
s.bind(`SELECT 1 FROM fw_documents WHERE org=? AND module=? AND doctype=? AND name=?`), org, id.Module, id.Name, name).Scan(&one)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("document exists: %w", err)
}
return true, nil
}
// fieldValueTaken reports whether another document in (org, doctype) already
// carries `value` for `field` — the Unique-field check. `field` is validated
// against the schema before this call and BOUND into the json path; excludeName
// lets an update skip the row being updated.
func (s *Store) fieldValueTaken(ctx context.Context, org string, id doctype.ID, field, value, excludeName string) (bool, error) {
var one int
err := s.db.QueryRowContext(ctx,
s.bind(`SELECT 1 FROM fw_documents WHERE org=? AND module=? AND doctype=? AND name<>? AND CAST(data->>? AS TEXT)=? LIMIT 1`),
org, id.Module, id.Name, excludeName, field, value).Scan(&one)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("unique check: %w", err)
}
return true, nil
}
// ---- Naming series counter ----
// nextSeries atomically increments and returns the per-org counter for a series
// key. Runs inside the caller's create transaction so the counter and the insert
// commit together (no gaps on rollback, no collisions across concurrent creates).
func (s *Store) nextSeries(ctx context.Context, tx *sql.Tx, org, key string) (int64, error) {
key = s.keyed(key)
if _, err := tx.ExecContext(ctx,
s.bind(`INSERT INTO fw_series (org,series,current) VALUES (?,?,1)
ON CONFLICT(org,series) DO UPDATE SET current = fw_series.current + 1`), org, key); err != nil {
return 0, fmt.Errorf("bump series: %w", err)
}
var n int64
if err := tx.QueryRowContext(ctx, s.bind(`SELECT current FROM fw_series WHERE org=? AND series=?`), org, key).Scan(&n); err != nil {
return 0, fmt.Errorf("read series: %w", err)
}
return n, nil
}
// ---- Roles (per-org assignments) ----
// ---- small helpers ----
// execer is the common subset of *sql.DB and *sql.Tx used by insert().
type execer interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
func b2i(b bool) int {
if b {
return 1
}
return 0
}
// isUnique reports whether err is a UNIQUE/primary-key violation: PostgreSQL's SQLSTATE 23505, or
// SQLite's message.
func isUnique(err error) bool {
if err == nil {
return false
}
var pg interface{ SQLState() string }
if errors.As(err, &pg) {
return pg.SQLState() == "23505"
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "unique constraint") || strings.Contains(msg, "constraint failed")
}