@voltro/database 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -39,6 +39,55 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.4.0] — 2026-07-18
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/protocol, @voltro/plugin-rbac, @voltro/runtime** — **Resource-aware declarative guards + one denial tag.** `guards: [{ scope, resource }]` now actually scopes to a resource. Register a resolver — either `setResourceScopeResolver((req) => Effect<boolean>)` from `@voltro/protocol`, or `rbacPlugin({ resolveResourceRoles: (subject, resourceId) => roleSlugs })` — and the framework asks it, per request, whether the caller holds the scope **on the extracted resource** (a team, workspace, document), before the executor runs (mutations: before the transaction opens). A globally-held scope or `admin:full` still short-circuits without a resolver call; a resolver error fails **closed**. With no resolver registered, `resource` stays advisory (global check) exactly as before, so single-tenant apps are unaffected. **BREAKING — `@voltro/plugin-rbac` no longer exports `Forbidden`.** rbac's `permission()` / `assertPermission()` / `anyPermission()` now fail with protocol's `ScopeError` — the SAME typed error the declarative `guards:` enforcement already raised. One denial tag across the framework: a client that matches `_tag === 'ScopeError'` (or `errorTag(err)`) recognizes both a descriptor-guard denial and a `permission()` denial with one branch. The `@voltro/plugin-rbac/errors` subpath is removed. Migration (the `voltro update` codemod rewrites the mechanical part): - `import { Forbidden } from '@voltro/plugin-rbac/errors'` → `import { ScopeError } from '@voltro/protocol'`; `import { Forbidden } from '@voltro/plugin-rbac'` → `import { ScopeError } from '@voltro/plugin-rbac'` (re-exported from the root). - Every `Forbidden` identifier → `ScopeError` (incl. `error: Forbidden` on a descriptor). - By hand: a constructed `new Forbidden({ required, reason })` becomes `new ScopeError({ required, message })` (the field is `message` and is REQUIRED); and any `Effect.catchTag('Forbidden', …)` / `err._tag === 'Forbidden'` string becomes `'ScopeError'`. Guards are normally caught, not constructed, so most apps only need the import rewrite the codemod does. Also note: `requireScope` / declarative `guards:` enforcement is now async-capable (it awaits the resource resolver when one is registered) — no change to handler code, which never called the internal enforcement directly.
47
+ - **@voltro/client, @voltro/plugin-rbac** — **`@voltro/plugin-rbac/web` is removed — the UI permission gate lives in `@voltro/client`.** The framework shipped `useCan` TWICE, with the same name and the same semantics, over two different React contexts. An app that mounted `<PermissionProvider>` and imported the plugin's `useCan` got an empty scope set and silently hid every gated affordance — no error, just a UI where nothing is permitted. One of the two had to go. `@voltro/client` survives because scopes are a FRAMEWORK concept: `@voltro/protocol` owns `ScopeError`, `guards: [{ scope }]` and `ctx.access`, and rbac is only one way to PRODUCE scopes — an app can register its own `setResourceScopeResolver` over its own tables and never install the plugin. The hook consumes scopes, which is generic; producing them is rbac-specific. Keeping the hook behind the plugin would force an rbac dependency on apps that deliberately don't use rbac, purely to gate a button. `@voltro/plugin-rbac` keeps everything that IS rbac: the roles map, role→scope compilation, the `permission()` / `assertPermission()` / `anyPermission()` server guards, the role tables, and `resolveResourceRoles`. The codemod rewrites every mechanical site: `RbacScopeProvider` → `PermissionProvider`, `canFromScopes` → `canCall`, `canAnyFromScopes` → `canCallAny`, and repoints `useCan` / `useCanAny` / `ADMIN_SCOPE` to `@voltro/client`. A raw `useContext(RbacScopeContext)` is ANNOTATED rather than rewritten — the client equivalent is `usePermissions()`, which returns `{ scopes }` instead of the bare array, so a silent rewrite would compile and then hand back the wrong shape.
48
+
49
+ ### Added
50
+
51
+ - **@voltro/runtime, @voltro/cli** — **`read({ where })` on aggregates.** Aggregate reads were all-or-nothing, so every consumer that wanted one slice pulled the whole materialised set over the wire and filtered in the component — the cost scaling with the aggregate, not the slice. `where` entries are ANDed; a scalar means strict equality, an array means IN; filtering runs before `orderBy`/`limit`. Deliberately a data filter over already materialised rows, not a predicate language — aggregates stay aggregates.
52
+ - **@voltro/client** — **Two ergonomics that remove the two most-repeated shapes in a Voltro frontend.** - **`mutate(input, options)` — `onSuccess` / `onError` / `notify`.** Every write site used to re-type `try { await mutate() } catch { toast.error(…) } finally { setSubmitting(false) }`. `pending` already replaced the `finally`; these replace the rest. Load-bearing semantic: supplying an error handler (`onError` or `notify.error`) marks the failure HANDLED — `mutate` resolves with `undefined` instead of rejecting, which is what actually deletes the try/catch. With no handler it rejects exactly as before, so unhandled failures stay loud. `notify` routes to an app-registered sink (`setMutationNotifier`) — the framework stays unbound to any toast library. - **`useSubscription` now returns `loading` and `isEmpty`, and accepts `fallback`.** Call sites branched on `data === undefined`, conflating "no snapshot yet" with "zero rows" — the cause of a flash of empty-state before the first snapshot. They are now distinct, derived once. `fallback` fills `data` while loading without lying about `loading`. Also documented: `error` carries a COLD-START stream failure (check it to avoid an infinite skeleton); a failure after data arrived deliberately does not blank good data — those reach the error bus (`useOnRpcError`).
53
+ - **@voltro/cli** — **Make the client hook surface discoverable — and keep it that way.** A downstream app built its whole frontend on three transport hooks (`useSubscription` / `useMutation` / `useAction`) and hand-rolled forms, tables, upload, permission gates, debounce and pagination, because the agent guide documented ~none of the ~40 client hooks that already ship. Three changes: - **The always-loaded core now carries a "Pick the CLIENT primitive" rubric** — the same decision-rubric treatment the backend primitives get, plus a "you're about to write X → reach for Y" table (per-field `useState` → `useFormBinding`, hand-rolled table → `useDataTable`, `FileReader` → `useUpload`, `useMemo` fan-in → `useDerived`, …). - **The hook reference is complete.** `reference/hooks-overview.md` presented itself as "the client-side hook surface" while documenting 13 of 44 hooks; it now enumerates the schema-driven-UI, files/permissions/utilities, and AI families (en + de). - **A coverage GATE** (`agentsMdTemplate.test.ts`): every exported `use*` hook of `@voltro/client` must appear in the composed agent-docs corpus, or the test fails with the list. Docs can no longer silently fall behind the export surface. Plus **`voltro doctor` now flags hand-rolls**: it scans an app's source for the patterns a shipped primitive covers (hand-rolled form/table, `FileReader` upload, `setTimeout` debounce, `useMemo` fan-in, local Next.js compat shims, hand-rolled presence) and names the primitive to use. Advisory, never fatal — a false-positive lecture must not fail a build.
54
+ - **@voltro/cli** — **Generated `matchError` / `AppError` / `AppErrorTag`.** Codegen now emits a per-app exhaustive error matcher into `rpcGroup.generated.ts`, derived BY REFERENCE from every descriptor's `error:` schema plus the cross-cutting plugin errors. `matchError(err, { [tag]: handler }, fallback?)` dispatches on `_tag` with the handler keys constrained to the app's ACTUAL error tags — so a hand-maintained tag list that silently drifts (dead/renamed tags) is gone; a stale tag is a compile error. Browser-safe (reads `_tag` structurally, no runtime dep). Workflows keep their existing `WorkflowErrors`.
55
+ - **@voltro/cli** — **`voltro doctor` + `voltro update --codemods-only`/`--from`** — two upgrade-path ergonomics from AWB adoption feedback: - **`voltro doctor [app]`** (and **`voltro serve --preflight`**) preflights an API app for production serve: it verifies the precompiled serve bundle exists and, if not, prints the exact fix and exits 1 — so a Dockerfile / CI step catches "prod `voltro serve` with no `voltro build`" at BUILD time instead of at cold-start (0.3.0 made an unbuilt production serve fatal). - **`voltro update --codemods-only` (alias `--run-codemods`) + `--from <version>`** — re-apply the codemods + manual notes for an explicit `[from, to]` delta WITHOUT bumping `package.json` or installing. The recovery path for a hand-edited version bump (`bump package.json` + install first), which otherwise makes `voltro update` report "already on X — nothing to do" and silently skip the codemods. `--from` also overrides the auto-detected source version on a normal update.
56
+ - **@voltro/runtime** — **`encryptField` / `decryptField` — standalone field cipher for raw-SQL paths.** `.encrypted()` columns encrypt/decrypt transparently inside the `ctx.store` middleware, so a code path that reaches the DB by RAW SQL (an auth strategy with no store handle reading/writing a session token, a one-off backfill) bypasses it. `@voltro/runtime` now exposes the SAME registered cipher standalone: `encryptField` encrypts a value; `decryptField` decrypts an `enc:v1:…` value and passes a non-ciphertext value through unchanged (so a raw-SQL path can adopt encryption while pre-existing plaintext rows keep working). Both throw a clear error when no cipher is registered. Encryption stops being all-or-nothing tied to going through `ctx.store`.
57
+ - **@voltro/testing** — **`makeVoltroTestClient` — the missing half of the test story.** The framework shipped a strong BACKEND test story (`makeTestContext`, `mockStore`, `mockAi`, the workflow runner) and nothing for the client. A Voltro frontend is a reactive-data app: with no way to render a component against mocked `useSubscription` / `useMutation` — and to inject a loading state, a stream error, or a failing write — it is structurally untestable, which is why real apps end up with zero frontend tests. `import { makeVoltroTestClient } from '@voltro/testing/client'` returns a `Provider` plus `setSubscription` / `failSubscription` / `resetSubscription` and a `calls` log of every write with its input. A tag ABSENT from the fixture stays in the loading state — the distinction from an empty result is exactly what you want to assert. Deliberately NOT a renderer: it hands you a Provider, so it works with `react-dom/client` + `act`, testing-library, or your own harness, and locks you into none of them.
58
+ - **@voltro/i18n** — **Plurals, Intl formatters, and catalogs a bundler can actually split.** - **`plural(locale, count, forms)` + `usePlural`** — real CLDR categories via `Intl.PluralRules`. Replaces the hardcoded `"{count} epic(s)"` pattern, whose literal `(s)` is simply wrong outside English, and which cannot express languages that distinguish few from many (Polish 2–4 vs 5+). An explicit `zero` form is honoured for exactly 0; ordinals via `{ type: 'ordinal' }`. - **`useFormatDate` / `useRelativeTime` / `useFormatNumber` / `useFormatCurrency` / `useFormatters`** — locale-bound `Intl` wrappers, so an app stops carrying several divergent hand-rolled "X minutes ago" helpers that each round differently. - **`defineCatalogs` + `LazyI18nProvider`** — code-split catalogs. `pickCatalog({ en, de })` is a STATIC import map: every locale is a value-level import, so the bundler must emit them in one chunk and a German-only visitor downloads English too, growing linearly per locale. A map of `() => import()` loaders is the only shape a bundler treats as a chunk boundary. `preload(locale)` before hydration keeps first paint synchronous via `peek()`; the provider's `fallback` is for a locale SWITCH, not first paint. Unknown locales degrade to the base catalog, and a failed chunk load stays retryable.
59
+ - **@voltro/protocol, @voltro/client** — **Nested optimistic: `shapeItem` + bulk (multi-item) targets.** Two additive improvements to path-targeted auto-optimistic: - **`shapeItem`** — the nested counterpart of `shape`, typed to the ITEM of the nested array (not the mutation's output), so a path-target patch reads/returns the item without casting `current`. (Previously the nested shaper was the flat `shape`, pinned to the output row — every adopter had to cast. `shape` stays bound to the output for flat targets; a single field can't be both, so the nested shaper is its own.) - **Bulk `identify`** — a target's `identify` may now return `string[]` to patch/delete MANY items (or top-level rows) in one mutation — the group-drag / batch-edit case where per-item parallel writes used to race. Each patched item keeps its own key. Runtime-compatible: a nested target that still uses `shape` falls back transparently. No codemod — additive.
60
+ - **@voltro/web, @voltro/client** — **Two hooks apps kept hand-rolling, because nothing shipped them.** - **`useTheme` (`@voltro/web`)** — returns `{ theme, resolvedTheme, setTheme }` over the framework's own `voltro:theme` cookie and the `html.dark` class. The bug it removes is specific: an app that hand-rolls a second theme store ends up with two writers on one class, so the toggle's state and the rendered theme can disagree, and the pre-paint script flashes the wrong one. `'system'` resolves through `matchMedia` and tracks live OS changes. - **`useConnectionStatus` (`@voltro/client`)** — `'connected' | 'degraded' | 'offline'`, derived from the only two signals the client honestly has: `navigator.onLine` (browser says the network is gone) and the rpc error bus (a call actually failed). `degraded` means "we saw a failure and no success since"; coming back online clears it, because the failures counted during an offline window ARE that window. Deliberately no polling ping just to colour an indicator.
61
+ - **@voltro/database** — **`.uniqueActive([cols])` now works on mysql / mariadb** (it previously failed loud at migrate — those engines have no partial index). It lowers automatically to a STORED generated column per key column — `CASE WHEN <predicate> THEN CAST(<col> AS CHAR(255)) ELSE NULL END` — plus a UNIQUE over them. NULL-distinct uniqueness means a soft-deleted row's generated columns are all NULL and never collide, so re-creating the key just works — the same resurrection-safe semantics the partial index gives on postgres/sqlite/mssql. The lowering is applied identically on the emit side and the declared-snapshot side, so it round-trips through the declarative differ (verified live on MariaDB: declare→migrate→introspect→re-plan is a no-diff, and a duplicate among active rows is rejected while soft-deleting one frees the key). You write the same `.uniqueActive([...])` on every dialect.
62
+
63
+ ### Fixed
64
+
65
+ - **@voltro/cli** — **Standalone `voltro codegen` now emits the SAME `rpcGroup.generated.ts` as `voltro dev` / `voltro build`.** Previously the standalone command skipped the app's plugins, so it dropped every plugin's cross-cutting error union AND its client RPC routes — an inconsistent generated file (typed plugin errors gone, plugin route tags unresolved) vs the dev/serve boot path. The command now loads `app.config` and gathers the plugins' codegen inputs through the SAME `gatherCodegenPluginImports` the boot path uses (single-sourced, so the three paths can't drift).
66
+ - **@voltro/cli** — **The hook-coverage gate was too weak, and it let dead documentation through.** It asked only whether a hook's NAME appeared in the agent-docs corpus — which a one-line row in a link table satisfies. Ten client hooks had exactly that, and six of those rows linked to a page that never mentions the hook, so a reader following the link learned nothing. Two sharper checks replace it: - **Substance** (`agentsMdTemplate.test.ts`): a hook must appear at least once OUTSIDE a table row, so a bare row no longer counts as documentation. - **Dead references** (`gen-agent-docs.mjs`): a row promising `[`useX`](/docs/…)` must point at a page that actually mentions `useX`. This lives in the generator because that is the only thing which reads the docs tree — and it walks BOTH language trees, since an en-only check leaves every German dead link invisible.
67
+ - **@voltro/cli** — - **Serve bundle: inline the pure-JS SQL drivers (`pg`/`mysql2`/`tedious`) instead of runtime-shimming them.** A production `voltro serve` with a postgres/mysql/mssql store crashed at boot with `Pg.Pool is not a constructor` (and the mysql/mssql equivalents): the driver's `@effect/sql-*` consumer links its leaf as a namespace (`import * as Pg from 'pg'; new Pg.Pool()`), but the native-leaf CJS shim (`module.exports = <leaf>`) did not surface the named members through esbuild's `import * as` interop, so `Pg.Pool` was `undefined`. These drivers are pure JS (no `.node`), so they are now inlined into the serve bundle like the rest of the framework — esbuild links the real module and the namespace resolves correctly. Only genuinely-native leaves (`better-sqlite3`, the turso/libsql addons, `pg-native`) and the dynamically-imported `ioredis`/`nodemailer` still resolve via the runtime shim. Verified end-to-end from a relocated prod tree (a real `POST /rpc` through the inlined `pg`).
68
+
69
+ ---
70
+
71
+ ## [0.3.0] — 2026-07-18
72
+
73
+ ### ⚠ BREAKING
74
+
75
+ - **@voltro/cli** — `voltro build` precompiles the whole serve path (framework + effect + `@voltro` inlined, app modules as lazy chunks) into a single **serve bundle**, and `voltro serve` boots from it in-process — cutting `serve: ready` from ~1000 ms to ~180 ms (5–6×; the win is larger on a cold scale-to-zero container). The app's declared SQL driver is inlined (only the native leaf like `pg` stays external, resolved at runtime so it survives the deploy relocation). **Production now serves ONLY from the bundle and NEVER transpiles on demand:** the bundle build externalises unresolvable optional peers (e.g. `@react-email/render` behind `@voltro/plugin-mail`) so it always builds; a bundle-build failure is **fatal** (`voltro build` exits non-zero); and an unbuilt production `voltro serve` fails loud instead of falling back to tsx. The build toolchain (`tsx`, `esbuild`, `vite`, `@vitejs/plugin-react`, `@tailwindcss/vite` + their native tree: rolldown/lightningcss/postcss/jiti) moves to **`optionalDependencies`** of `@voltro/cli`, so `pnpm --prod --no-optional deploy` yields a serve image with none of it — a prod API image's `node_modules` drops ~305 MB → ~131 MB, structurally, with no fragile prune list. `voltro dev` and a non-production local `voltro serve` are unchanged (still tsx). **Migration:** in production (`NODE_ENV=production`) run `voltro build` before `voltro serve`. The generated Dockerfiles already do; a custom Dockerfile / start script adds a `voltro build .` step before `voltro serve .` (`voltro update` prints this — see the 0.3.0 codemod note).
76
+
77
+ ### Added
78
+
79
+ - **@voltro/protocol, @voltro/runtime, @voltro/plugin-rbac** — Declarative authorization `guards:` on `defineMutation` / `defineQuery` / `defineAction`. The framework enforces the declared scope(s) in the dispatch spine BEFORE the executor (for a mutation, before the transaction opens), fails with a typed `ScopeError`, and auto-merges `ScopeError` into the wire error union so the client decodes the denial typed. Guards are browser-safe DATA (scope strings + a pure `resource: (input) => id` extractor). Checks run against the caller's EFFECTIVE scope set — raw subject scopes ∪ `@voltro/plugin-rbac` role-derived scopes — via a new canonical effective-scope seam in `@voltro/protocol` (`effectiveScopes` / `setEffectiveScopes` / `checkGuards`), which rbac now publishes to (so a role-granted scope satisfies a `guards:` entry and the in-handler `permission()` identically). Adds `ctx.access` (`has` / `hasAny` / `require` / `scopes`) — the cast-free typed authorization slice on every handler context. Enforcement is single-sourced in the shared serve pipeline, so `voltro dev` and `voltro serve` can't drift.
80
+ - **@voltro/protocol, @voltro/client** — Nested / path-targeted auto-optimistic. A mutation `target` can now patch a nested array INSIDE a query's value — a JSON array column (`snapshot.projects`) or a computed/shaped result — at item granularity, via `path` (dot-path to the array), `by` (item key, default `id`), and `match` (a pure predicate that scopes the patch to the entries whose current value satisfies it, preventing a patch bleeding across sibling subscriptions that share a source table). Previously auto-optimistic only patched the flat top-level row array keyed by `id`; nested values needed a hand-written `.withOptimistic` reducer. `path`/`by`/`match` are browser-safe descriptor data (a dot-path string + pure predicate), same discipline as `identify`/`shape`. A path insert is applied even on a computed entry (it targets a known document, not a blind top-level add).
81
+ - **@voltro/runtime** — `ctx.store.applyDefined(input, keys)` (and a standalone `applyDefined` export from `@voltro/runtime`) — builds a partial-update patch keeping only the listed keys whose value the caller actually provided (`!== undefined`; a defined falsy value like `0`/`''`/`false` is kept). Collapses the per-field `if (input.x !== undefined) patch.x = input.x` idiom every partial-update mutation hand-writes.
82
+ - **@voltro/database** — `.uniqueActive([cols], opts?)` on the table builder — a portable partial-UNIQUE constraint that holds only among the rows matching a predicate (default `"deletedAt" IS NULL`, pairing with `.softDelete()`). Emits `CREATE UNIQUE INDEX … WHERE` on postgres / sqlite / mssql, so a soft-deleted row leaves the active set and a NEW row with the same key inserts cleanly — no hand-written `generatedAs("CASE WHEN …")` column and no resurrection footgun. On mysql / mariadb (no partial-index support) it FAILS LOUDLY at migrate time rather than silently emitting a full unique index that would forbid re-creating a soft-deleted key — the generated-STORED-column lowering for those dialects is a follow-up. Kept out of the declarative index snapshot (the incremental planner is predicate-blind and would misclassify a unique+partial index as a full constraint), so the fresh-schema DDL path is its sole emitter and there is no re-diff churn. Live-verified against postgres.
83
+ - **@voltro/cli** — `voltro update` upgrades an app to the latest framework: it bumps every `@voltro/*` dependency, installs with the detected package manager, and runs the codemods shipped with the target version. Codemods are authored with `defineCodemod` + an import-scoped ts-morph helper toolkit (`renameImport`, `renameModuleSpecifier`, `renameJsxProp`, `renameObjectKey`, `add`/`removeImport`, structural `changeCallArgs`/`wrapCall`, `annotate`) and run against the app source; a `manual` kind surfaces written steps for changes that can't be automated. Breaking public-API changes now ship a codemod (or an explicit `codemod: none`), enforced by the changelog gate. Framework-owned `_voltro_*` table changes continue to ride the declarative differ on `voltro db apply` / `voltro dev` boot — `update` does not touch the database.
84
+
85
+ ### Fixed
86
+
87
+ - **@voltro/database** — The core-table registry (`registerCoreTables` / `requireActors` / `requireTenants`) now stores its state on a process-global `Symbol.for` singleton, the same mechanism the main table registry already uses — instead of module-local `let` bindings. Module-local state splits when the `@voltro/database` module is duplicated in a process (e.g. resolved through both the `.` and `./sql` entry points, or a bundled framework copy alongside an externally-resolved one): one instance's `registerCoreTables` becomes invisible to the instance that reads it, surfacing as a spurious `core 'actors' table not registered` at store construction. Pinning it to `globalThis` makes every copy share one store, matching the table registry's already-global behaviour.
88
+
89
+ ---
90
+
42
91
  ## [0.2.2] — 2026-07-17
43
92
 
44
93
  ### Added
@@ -530,6 +530,30 @@ var r = class e {
530
530
  ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
531
531
  });
532
532
  }),
533
+ uniqueActive: ((...t) => {
534
+ let n, r, i, a = Array.isArray(t[0]);
535
+ if (a ? (r = t[0], i = t[1], n = z(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`uniqueActive '${n}' on table '${e.tableName}' has no fields — a partial UNIQUE must cover at least one column.`);
536
+ if (y(e.tableName, n, a, r), e.appliedIndexes.some((e) => e.name === n)) throw Error(`duplicate index '${n}' on table '${e.tableName}': each index name must be unique within a table (uniqueActive shares the index namespace).`);
537
+ let o = i?.where ?? "\"deletedAt\" IS NULL";
538
+ return V({
539
+ tableName: e.tableName,
540
+ fields: e.fields,
541
+ isReactive: e.isReactive,
542
+ appliedMixins: e.appliedMixins,
543
+ appliedIndexes: [...e.appliedIndexes, {
544
+ name: n,
545
+ fields: [...r],
546
+ where: o,
547
+ unique: !0
548
+ }],
549
+ appliedUniques: e.appliedUniques,
550
+ appliedFullText: e.appliedFullText,
551
+ appliedChecks: e.appliedChecks,
552
+ appliedPrimaryKey: e.appliedPrimaryKey,
553
+ ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
554
+ ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
555
+ });
556
+ }),
533
557
  check: ((t, n) => {
534
558
  if (n.trim().length === 0) throw Error(`CHECK '${t}' on table '${e.tableName}' has an empty expression.`);
535
559
  if (y(e.tableName, t, !1, []), e.appliedChecks.some((e) => e.name === t)) throw Error(`duplicate CHECK '${t}' on table '${e.tableName}': each constraint name must be unique within a table.`);
package/dist/index.d.ts CHANGED
@@ -4532,6 +4532,37 @@ export declare interface Table<Name extends string, Fields extends Record<string
4532
4532
  dedup?: TableUnique['dedup'];
4533
4533
  }): Table<Name, Fields, Reactive, IxNames>;
4534
4534
  };
4535
+ /**
4536
+ * Declare a **partial UNIQUE** constraint that holds only among the rows
4537
+ * matching a predicate — the portable answer to "unique among the rows that
4538
+ * aren't soft-deleted". Emits a `CREATE UNIQUE INDEX … WHERE` on postgres /
4539
+ * sqlite / mssql.
4540
+ *
4541
+ * ```ts
4542
+ * table('project_roadmaps', { id, projectId, year, deletedAt, ... })
4543
+ * .softDelete()
4544
+ * .uniqueActive(['projectId', 'year']) // one ACTIVE roadmap per (project, year)
4545
+ * ```
4546
+ *
4547
+ * By default the predicate is `"deletedAt" IS NULL` (pairs with
4548
+ * `.softDelete()`); override with `{ where }` for a custom active-set
4549
+ * (`"status" = 'open'`). A soft-deleted row leaves the active set, so a NEW
4550
+ * row with the same key is allowed — no hand-written
4551
+ * `generatedAs("CASE WHEN …")` column, no resurrection footgun.
4552
+ *
4553
+ * **mysql / mariadb:** these engines have no partial-index support, so
4554
+ * `.uniqueActive()` FAILS LOUDLY at migrate time (a full unique index would
4555
+ * silently forbid re-creating a soft-deleted row). Use a generated STORED
4556
+ * column + `.unique()` there until the framework lowers it for you.
4557
+ */
4558
+ uniqueActive: {
4559
+ <const F extends readonly [keyof Fields & string, ...Array<keyof Fields & string>]>(fields: F, options?: {
4560
+ where?: string;
4561
+ }): Table<Name, Fields, Reactive, IxNames>;
4562
+ <const IxName extends string, const F extends readonly [keyof Fields & string, ...Array<keyof Fields & string>]>(name: IxName, fields: F, options?: {
4563
+ where?: string;
4564
+ }): Table<Name, Fields, Reactive, IxNames | IxName>;
4565
+ };
4535
4566
  /**
4536
4567
  * Declare a named table-level `CHECK` constraint — a DB-ENFORCED
4537
4568
  * invariant that holds regardless of which client writes the row
@@ -4700,6 +4731,20 @@ export declare interface TableIndex {
4700
4731
  * efConstruction, opclass}`). Ignored for kinds that don't read it.
4701
4732
  */
4702
4733
  readonly kindOptions?: IndexKindOptions;
4734
+ /**
4735
+ * UNIQUE partial index — set ONLY by `.uniqueActive(...)`. Emits
4736
+ * `CREATE UNIQUE INDEX … WHERE <where>` on postgres / sqlite / mssql, so
4737
+ * uniqueness holds only among rows matching `where` (e.g. the non-soft-
4738
+ * deleted rows). Distinct from `.index(..., { where })` (non-unique) and
4739
+ * from `.unique(...)` (a full constraint with no predicate). Because a
4740
+ * unique+partial index has no `information_schema` constraint form and the
4741
+ * declarative planner is predicate-blind, these are emitted by the
4742
+ * fresh-schema DDL path (like every partial predicate) and kept OUT of the
4743
+ * declarative index snapshot. mysql/mariadb have no partial-index support —
4744
+ * `.uniqueActive()` fails loudly there (use a generated column) rather than
4745
+ * silently dropping the predicate into a full unique index.
4746
+ */
4747
+ readonly unique?: boolean;
4703
4748
  }
4704
4749
 
4705
4750
  export declare interface TableLike {
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as e, A as t, B as n, C as r, Ct as i, D as a, Dt as o, E as s, Et as c, F as l, G as u, H as d, I as f, J as p, K as m, L as h, M as g, N as _, O as ee, Ot as v, P as y, Q as b, R as x, S as te, St as S, T as C, Tt as ne, U as re, V as ie, W as ae, X as oe, Y as se, Z as ce, _ as le, _t as ue, a as de, at as fe, b as pe, bt as me, c as he, ct as ge, d as _e, dt as ve, et as ye, f as be, ft as xe, g as Se, gt as Ce, h as we, ht as Te, i as w, it as Ee, j as De, k as Oe, kt as ke, l as Ae, lt as je, m as Me, mt as Ne, n as Pe, nt as Fe, o as Ie, ot as Le, p as Re, pt as ze, q as Be, r as Ve, rt as He, s as Ue, st as We, t as Ge, tt as Ke, u as qe, ut as Je, v as Ye, vt as T, w as Xe, wt as Ze, x as Qe, xt as E, y as $e, yt as D, z as et } from "./fileBased-cc9IzIjU.js";
1
+ import { $ as e, A as t, B as n, C as r, Ct as i, D as a, Dt as o, E as s, Et as c, F as l, G as u, H as d, I as f, J as p, K as m, L as h, M as g, N as _, O as ee, Ot as v, P as y, Q as b, R as x, S as te, St as S, T as C, Tt as ne, U as re, V as ie, W as ae, X as oe, Y as se, Z as ce, _ as le, _t as ue, a as de, at as fe, b as pe, bt as me, c as he, ct as ge, d as _e, dt as ve, et as ye, f as be, ft as xe, g as Se, gt as Ce, h as we, ht as Te, i as w, it as Ee, j as De, k as Oe, kt as ke, l as Ae, lt as je, m as Me, mt as Ne, n as Pe, nt as Fe, o as Ie, ot as Le, p as Re, pt as ze, q as Be, r as Ve, rt as He, s as Ue, st as We, t as Ge, tt as Ke, u as qe, ut as Je, v as Ye, vt as T, w as Xe, wt as Ze, x as Qe, xt as E, y as $e, yt as D, z as et } from "./fileBased-CRXgPJkv.js";
2
2
  import { Chunk as tt, Data as nt, Effect as rt, Option as O, Stream as it } from "effect";
3
3
  import { ansi as k } from "@voltro/logger";
4
4
  //#region src/arrayCodec.ts
package/dist/sql.d.ts CHANGED
@@ -594,7 +594,7 @@ declare type ColumnType = 'id' | 'text' | 'integer' | 'real' | 'decimal' | 'bigi
594
594
  * declared + framework). The fingerprint over this snapshot is what the
595
595
  * boot-time prod check compares against `_voltro_migration_plans`.
596
596
  */
597
- export declare const declaredSnapshot: (tables: ReadonlyArray<TableLike>) => SchemaSnapshot;
597
+ export declare const declaredSnapshot: (tables: ReadonlyArray<TableLike>, dialect?: DialectId) => SchemaSnapshot;
598
598
 
599
599
  export declare const defaultClause: (column: ColumnDefinition<unknown>, dialect: DialectId) => string | null;
600
600
 
@@ -1754,6 +1754,37 @@ declare interface Table<Name extends string, Fields extends Record<string, Colum
1754
1754
  dedup?: TableUnique['dedup'];
1755
1755
  }): Table<Name, Fields, Reactive, IxNames>;
1756
1756
  };
1757
+ /**
1758
+ * Declare a **partial UNIQUE** constraint that holds only among the rows
1759
+ * matching a predicate — the portable answer to "unique among the rows that
1760
+ * aren't soft-deleted". Emits a `CREATE UNIQUE INDEX … WHERE` on postgres /
1761
+ * sqlite / mssql.
1762
+ *
1763
+ * ```ts
1764
+ * table('project_roadmaps', { id, projectId, year, deletedAt, ... })
1765
+ * .softDelete()
1766
+ * .uniqueActive(['projectId', 'year']) // one ACTIVE roadmap per (project, year)
1767
+ * ```
1768
+ *
1769
+ * By default the predicate is `"deletedAt" IS NULL` (pairs with
1770
+ * `.softDelete()`); override with `{ where }` for a custom active-set
1771
+ * (`"status" = 'open'`). A soft-deleted row leaves the active set, so a NEW
1772
+ * row with the same key is allowed — no hand-written
1773
+ * `generatedAs("CASE WHEN …")` column, no resurrection footgun.
1774
+ *
1775
+ * **mysql / mariadb:** these engines have no partial-index support, so
1776
+ * `.uniqueActive()` FAILS LOUDLY at migrate time (a full unique index would
1777
+ * silently forbid re-creating a soft-deleted row). Use a generated STORED
1778
+ * column + `.unique()` there until the framework lowers it for you.
1779
+ */
1780
+ uniqueActive: {
1781
+ <const F extends readonly [keyof Fields & string, ...Array<keyof Fields & string>]>(fields: F, options?: {
1782
+ where?: string;
1783
+ }): Table<Name, Fields, Reactive, IxNames>;
1784
+ <const IxName extends string, const F extends readonly [keyof Fields & string, ...Array<keyof Fields & string>]>(name: IxName, fields: F, options?: {
1785
+ where?: string;
1786
+ }): Table<Name, Fields, Reactive, IxNames | IxName>;
1787
+ };
1757
1788
  /**
1758
1789
  * Declare a named table-level `CHECK` constraint — a DB-ENFORCED
1759
1790
  * invariant that holds regardless of which client writes the row
@@ -1920,6 +1951,20 @@ declare interface TableIndex {
1920
1951
  * efConstruction, opclass}`). Ignored for kinds that don't read it.
1921
1952
  */
1922
1953
  readonly kindOptions?: IndexKindOptions;
1954
+ /**
1955
+ * UNIQUE partial index — set ONLY by `.uniqueActive(...)`. Emits
1956
+ * `CREATE UNIQUE INDEX … WHERE <where>` on postgres / sqlite / mssql, so
1957
+ * uniqueness holds only among rows matching `where` (e.g. the non-soft-
1958
+ * deleted rows). Distinct from `.index(..., { where })` (non-unique) and
1959
+ * from `.unique(...)` (a full constraint with no predicate). Because a
1960
+ * unique+partial index has no `information_schema` constraint form and the
1961
+ * declarative planner is predicate-blind, these are emitted by the
1962
+ * fresh-schema DDL path (like every partial predicate) and kept OUT of the
1963
+ * declarative index snapshot. mysql/mariadb have no partial-index support —
1964
+ * `.uniqueActive()` fails loudly there (use a generated column) rather than
1965
+ * silently dropping the predicate into a full unique index.
1966
+ */
1967
+ readonly unique?: boolean;
1923
1968
  }
1924
1969
 
1925
1970
  declare interface TableLike {