@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.5

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.
Files changed (63) hide show
  1. package/package.json +34 -3
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/capability.ts +5 -0
  5. package/src/codegen-sqlite.ts +154 -0
  6. package/src/codegen.ts +59 -9
  7. package/src/database.ts +227 -61
  8. package/src/errors.ts +2 -2
  9. package/src/file-columns.ts +4 -1
  10. package/src/framework-tables.ts +28 -8
  11. package/src/framework.ts +14 -5
  12. package/src/guard.ts +8 -0
  13. package/src/index.ts +9 -1
  14. package/src/job-leases.ts +210 -54
  15. package/src/job-wakes.ts +450 -0
  16. package/src/links.ts +8 -1
  17. package/src/migrations-sqlite.ts +163 -0
  18. package/src/migrations.ts +25 -0
  19. package/src/nodes.ts +64 -9
  20. package/src/orm-types.ts +2 -2
  21. package/src/orm.ts +68 -35
  22. package/src/policy.ts +8 -2
  23. package/src/postgres.ts +26 -0
  24. package/src/registry.ts +11 -2
  25. package/src/sql.ts +216 -473
  26. package/src/sqlite-bun.ts +122 -0
  27. package/src/sqlite-migrate.ts +242 -0
  28. package/src/sqlite.ts +224 -0
  29. package/src/store.ts +362 -93
  30. package/src/stored-files.ts +188 -52
  31. package/src/tables.ts +16 -0
  32. package/src/temporal.ts +115 -9
  33. package/src/testing-shared.ts +733 -0
  34. package/src/testing-sqlite.ts +513 -0
  35. package/src/testing.ts +169 -482
  36. package/types/src/application-rows.d.ts +58 -0
  37. package/types/src/capability.d.ts +5 -0
  38. package/types/src/codegen-sqlite.d.ts +6 -0
  39. package/types/src/codegen.d.ts +30 -0
  40. package/types/src/database.d.ts +81 -20
  41. package/types/src/errors.d.ts +2 -2
  42. package/types/src/framework.d.ts +11 -5
  43. package/types/src/index.d.ts +1 -1
  44. package/types/src/job-leases.d.ts +32 -4
  45. package/types/src/job-wakes.d.ts +101 -0
  46. package/types/src/migrations-sqlite.d.ts +4 -0
  47. package/types/src/migrations.d.ts +1 -0
  48. package/types/src/nodes.d.ts +13 -2
  49. package/types/src/orm-types.d.ts +2 -2
  50. package/types/src/policy.d.ts +4 -0
  51. package/types/src/postgres.d.ts +12 -0
  52. package/types/src/registry.d.ts +10 -2
  53. package/types/src/sql.d.ts +29 -21
  54. package/types/src/sqlite-bun.d.ts +13 -0
  55. package/types/src/sqlite-migrate.d.ts +28 -0
  56. package/types/src/sqlite.d.ts +24 -0
  57. package/types/src/store.d.ts +26 -9
  58. package/types/src/stored-files.d.ts +6 -2
  59. package/types/src/tables.d.ts +10 -0
  60. package/types/src/temporal.d.ts +21 -0
  61. package/types/src/testing-shared.d.ts +201 -0
  62. package/types/src/testing-sqlite.d.ts +22 -0
  63. package/types/src/testing.d.ts +2 -93
@@ -2,6 +2,7 @@ import type { Admissions } from './admissions';
2
2
  import type { Session } from './database';
3
3
  import type { WebhookTables } from './framework-tables';
4
4
  import type { JobLeases } from './job-leases';
5
+ import type { JobWakes } from './job-wakes';
5
6
  import type { DataAccess } from './orm';
6
7
  import type { DataLayerRuntime, TableContext, TableProbe } from './store';
7
8
  import type { StoredFiles } from './stored-files';
@@ -14,14 +15,21 @@ export type Locator = (dimension: string, id: string, using?: Session) => Promis
14
15
  export interface FrameworkTables {
15
16
  readonly webhooks: WebhookTables;
16
17
  readonly jobs: JobLeases;
18
+ /** A job's durable pending work (`fabrika_wakes`), which follows its lease, and the scheduler's next wake over both. */
19
+ readonly wakes: JobWakes;
17
20
  /** A procedure's admission buckets, the challenge tokens it accepted and its byte budget. */
18
21
  readonly admissions: Admissions;
19
22
  /** Every stored file (`fabrika_files`): staged before its object, claimed at its first reference, swept unreferenced. */
20
23
  readonly files: StoredFiles;
21
24
  }
25
+ /** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
26
+ export interface ProvisionalBinding {
27
+ readonly locate: Locator;
28
+ release(): void;
29
+ }
22
30
  export interface FrameworkSide {
23
- /** Connects the layer once and answers its locator; a second call throws. */
24
- bind(runtime: DataLayerRuntime): Locator;
31
+ /** Connects the layer once and answers its binding; a call while one is connected throws. */
32
+ bind(runtime: DataLayerRuntime): ProvisionalBinding;
25
33
  readonly framework: FrameworkTables;
26
34
  /** The untyped handle over one table that `@fabrika/db/testing` hands the isolation tests. */
27
35
  probe(table: string): TableProbe;
@@ -2,8 +2,15 @@ import { z } from 'zod/v4';
2
2
  import { type Session } from './database';
3
3
  /** What a site declares: `'read'` runs queries only, `'write'` also `INSERT`, `UPDATE` and `DELETE`. */
4
4
  export type SqlMode = 'read' | 'write';
5
- /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers (an array). */
5
+ /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers. */
6
6
  export type SqlValue = string | number | boolean | bigint | Date | null | readonly (string | number)[];
7
+ /** The database a statement is classified for: Postgres in the application's schema, or a Durable Object's SQLite. */
8
+ export type SqlDatabase = {
9
+ readonly dialect: 'postgres';
10
+ readonly schema: string;
11
+ } | {
12
+ readonly dialect: 'sqlite';
13
+ };
7
14
  /** One test of a capability's scope on a table: the column holds the value, or one of the list. */
8
15
  export interface ScopeTest {
9
16
  readonly column: string;
@@ -11,21 +18,20 @@ export interface ScopeTest {
11
18
  }
12
19
  /** A capability's predicate on one table: every row (`'all'`), or an OR of AND groups; no group matches nothing. */
13
20
  export type ScopeTerms = 'all' | readonly (readonly ScopeTest[])[];
14
- /** What a fragment's table is to its statement: read, or the target of its UPDATE or DELETE. */
21
+ /** What a fragment's table is to its statement, as its author states it: read, or the target of an UPDATE or DELETE. */
15
22
  export type ScopeUse = 'read' | 'update' | 'delete';
23
+ /** The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not reach it. */
24
+ export type ScopeOf = (capability: unknown, table: string, use: ScopeUse) => ScopeTerms;
25
+ /** The third argument of `ctx.sql.scope`: the table's alias in the statement, and what the statement does with it. */
26
+ export interface SqlScopeOptions {
27
+ /** The table's name in the statement; the table's own name by default. */
28
+ readonly alias?: string;
29
+ /** `'update'` or `'delete'` where the statement writes the table, which needs that operation's action; `'read'` by default. */
30
+ readonly use?: ScopeUse;
31
+ }
16
32
  /**
17
- * The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not
18
- * reach it for that use. `assigned` is the columns an UPDATE's SET names (none when the SET cannot be read with
19
- * certainty), and `undefined` before a statement is known.
20
- */
21
- export type ScopeOf = (capability: unknown, table: string, use: ScopeUse, assigned?: readonly string[]) => ScopeTerms;
22
- /** The operation a write statement performs on one of its targets. */
23
- export type WriteOperation = 'insert' | 'update' | 'delete';
24
- /** Throws for a table no statement may write with `operation`: a reference table. */
25
- export type WriteTarget = (table: string, operation: WriteOperation) => void;
26
- /**
27
- * `ctx.sql.scope(capability, table, alias?)`: the capability's whole predicate on one table, as SQL with bound values.
28
- * A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
33
+ * `ctx.sql.scope(capability, table, { alias, use })`: the capability's whole predicate on one table, as SQL with bound
34
+ * values. A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
29
35
  * methods captured at load, so no object an application builds or changes is ever taken for one.
30
36
  */
31
37
  export interface SqlScope {
@@ -34,7 +40,7 @@ export interface SqlScope {
34
40
  /** `ctx.sql(Row)`: the tag for rows of `Row`, and `scope` for the capability's predicate inside its text. */
35
41
  export interface SqlTag {
36
42
  <S extends z.core.$ZodType>(row: S): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<z.output<S>[]>;
37
- scope(capability: unknown, table: string, alias?: string): SqlScope;
43
+ scope(capability: unknown, table: string, options?: SqlScopeOptions): SqlScope;
38
44
  }
39
45
  /** The site a tag is made for: its mode, its binding to the invocation, and the session its statements run in. */
40
46
  export interface SqlSite {
@@ -46,14 +52,16 @@ export interface SqlSite {
46
52
  fail(): void;
47
53
  }
48
54
  /**
49
- * The SQL `parts` make, with `$1…$n` for the values, or a `QueryRefusedError` that names what is refused: more than
50
- * one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for `'write'`), a nested statement of
51
- * another kind, a qualified name outside `schema`, a `fabrika_*` or `pg_*` name, a function call outside the reviewed
52
- * built-ins, and a value placed where it would not be bound.
55
+ * The SQL `parts` make, with a bound placeholder for each value, or a `QueryRefusedError` that names what is refused.
56
+ * On both dialects: more than one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for
57
+ * `'write'`), a `'read'` statement that writes or locks, a value placed where it would not be bound, and a `fabrika_*`
58
+ * name. On Postgres also a nested statement of another kind, `SELECT … INTO`, a `U&` name, a `pg_*` name, a qualified
59
+ * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
60
+ * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
53
61
  */
54
- export declare function classifySql(parts: readonly string[], mode: SqlMode, schema: string): string;
62
+ export declare function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase): string;
55
63
  /**
56
64
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
57
65
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
58
66
  */
59
- export declare function sqlTag(site: SqlSite, schema: string | undefined, termsOf: ScopeOf, writeTarget: WriteTarget): SqlTag;
67
+ export declare function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf): SqlTag;
@@ -0,0 +1,13 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import type { SqliteStorage } from './sqlite';
3
+ export interface BunSqliteStorage extends SqliteStorage {
4
+ /** Runs `fn` in one transaction of its own, as a Durable Object's `storage.transactionSync` does. */
5
+ transactionSync<T>(fn: () => T): T;
6
+ }
7
+ /**
8
+ * `database` (a fresh `:memory:` one by default) with foreign keys enforced, as a Durable Object enforces them. One
9
+ * `transaction` runs at a time; one started inside a callback nests in a savepoint, as workerd nests it, and its
10
+ * siblings wait for each other. A statement outside one runs at once. A text of several statements runs whole when its
11
+ * first statement answers no rows, as a migration's does; otherwise only its first statement runs.
12
+ */
13
+ export declare function bunSqliteStorage(database?: Database): BunSqliteStorage;
@@ -0,0 +1,28 @@
1
+ /** What the runner needs of the database; a Durable Object's `storage.sql.exec` and `storage.transactionSync` fit it. */
2
+ export interface SqliteMigrationTarget {
3
+ /** Runs `query`, which may hold several statements, and answers the rows of the last one. */
4
+ exec(query: string, ...bindings: (string | number | null)[]): {
5
+ toArray(): Record<string, unknown>[];
6
+ };
7
+ /** Runs `fn` in one transaction: commits when it returns, rolls back when it throws. */
8
+ transactionSync<T>(fn: () => T): T;
9
+ }
10
+ export interface SqliteMigrationBundle {
11
+ readonly bundle: string;
12
+ readonly migrations: readonly {
13
+ readonly name: string;
14
+ readonly sql: string;
15
+ }[];
16
+ }
17
+ export declare class SqliteMigrationError extends Error {
18
+ readonly name = "SqliteMigrationError";
19
+ }
20
+ /**
21
+ * Applies every migration the ledger does not record, each in its own transaction together with its ledger row, so a
22
+ * failing one leaves nothing of itself and keeps the ones before it. A bundle's digest is recorded in the transaction
23
+ * of its last file, or alone when nothing of it was pending; while every bundle matches its digest, the ledger is not
24
+ * read. Answers the identities it applied.
25
+ */
26
+ export declare function migrateSqlite(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<{
27
+ readonly applied: readonly string[];
28
+ }>;
@@ -0,0 +1,24 @@
1
+ import { Database } from './database';
2
+ /** A value `sql.exec` binds and answers; a Durable Object's `SqlStorageValue`. */
3
+ export type SqliteValue = ArrayBuffer | string | number | null;
4
+ export interface SqliteCursor {
5
+ toArray(): Record<string, SqliteValue>[];
6
+ readonly rowsWritten: number;
7
+ }
8
+ /** What the engine needs of a Durable Object's `ctx.storage`; `DurableObjectStorage` is assignable to it. */
9
+ export interface SqliteStorage {
10
+ readonly sql: {
11
+ exec(query: string, ...bindings: SqliteValue[]): SqliteCursor;
12
+ };
13
+ /** Commits when `closure` resolves, rolls back when it rejects; the object serves no other event meanwhile. */
14
+ transaction<T>(closure: () => Promise<T>): Promise<T>;
15
+ /** Runs `closure` in one transaction of its own, nested in a savepoint inside an open one; rolls back when it throws. */
16
+ transactionSync<T>(closure: () => T): T;
17
+ }
18
+ /**
19
+ * The data layer's database over a Durable Object's storage. A read-only transaction opens no storage transaction,
20
+ * which would hold back every other event of the object across the work's awaits: each of its statements runs in one
21
+ * of its own, so two of them may see different committed states, as under Postgres's READ COMMITTED. The idle timeout
22
+ * has no SQLite form.
23
+ */
24
+ export declare function openSqlite(storage: SqliteStorage): Database;
@@ -1,18 +1,24 @@
1
1
  import { type OperationNode, type ReturningNode } from 'kysely';
2
2
  import { type NameSet } from './builtins';
3
3
  import { type AppGrant, type CapabilityAuthority, type Ref, type RefGrant, type Within, type WithinGrant } from './capability';
4
- import { type Database, type Session } from './database';
5
- import { type NoColumns, type Primitive, type ScopedSelect, type TableShape } from './description';
4
+ import { type Database, type Session, type SqlDialect } from './database';
5
+ import { type Compare, type Contains, type NoColumns, type Primitive, type ScopedSelect, type TableShape } from './description';
6
6
  import { type FileBinding } from './file-columns';
7
7
  import type { ForeignKeyPair, GuardContext, RootKind } from './guard';
8
8
  import { type Acknowledgement, type ActionOf, type ChildTableName, type Container, type ContainerOf, type DimensionOf, type DimensionTableName, type InsertValues, type JoinableChildren, type ListDimensionOf, type MoveAcknowledgement, type Operation, type ParentOf, type PolicyRow, type TableModel, type TableModels, type Tables, type UpdateValues, type VersionArguments } from './policy';
9
9
  import type { ScopeTerms, ScopeUse } from './sql';
10
10
  import { type TablePolicies } from './tables';
11
+ import { type RowColumns } from './temporal';
11
12
  export interface DataLayerRuntime {
12
13
  readonly database: Database;
13
14
  readonly capabilities: CapabilityAuthority;
14
15
  /** Whether the request running now may only read (an export's); its every statement then runs `READ ONLY`. */
15
16
  readonly readOnly?: () => boolean;
17
+ /**
18
+ * Runs inside the transaction of every change of a job's wakes or lease, after the change: the Cloudflare driver arms
19
+ * the alarm from `wakes.next(transaction)` there, so the alarm commits with the change. A throw rolls the change back.
20
+ */
21
+ readonly projectWakes?: (transaction: Session) => Promise<void>;
16
22
  }
17
23
  /** Empty until the framework connects the layer at boot; every table handle of one `scoped` call shares it. */
18
24
  export interface Connection {
@@ -25,8 +31,18 @@ export interface TableContext {
25
31
  readonly destination: TableModel | undefined;
26
32
  readonly shape: TableShape;
27
33
  readonly joins: Readonly<Record<string, readonly ForeignKeyPair[]>>;
34
+ /** The model of each child a select may join, by its table name. */
35
+ readonly children: Readonly<Record<string, TableModel>>;
28
36
  readonly connection: Connection;
29
37
  }
38
+ /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
39
+ export declare function dialectOf(context: TableContext): SqlDialect;
40
+ /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
41
+ export declare function rowColumnsOf(model: TableModel): RowColumns;
42
+ /** The values a write binds: on SQLite each timestamp as its stored UTC text, so text order is time order. */
43
+ export declare function boundValues(context: TableContext, values: ReadonlyMap<string, Primitive | null>): ReadonlyMap<string, Primitive | null>;
44
+ /** A list's terms over `model`'s columns, as `boundTerm` binds each. */
45
+ export declare function boundTerms(context: TableContext, model: TableModel, terms: readonly (Compare | Contains)[]): readonly (Compare | Contains)[];
30
46
  export declare function runtimeOf(connection: Connection): DataLayerRuntime;
31
47
  export interface DimensionScopeModel {
32
48
  readonly dimension: string;
@@ -68,12 +84,13 @@ export declare function reachPredicate(context: TableContext, capability: unknow
68
84
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
69
85
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
70
86
  * its read action for a `Within`, an action `ctx.db.app` lists it for with an `app` capability, and its read action
71
- * for a scoped site's read of an application table. A fragment on the statement's UPDATE or DELETE target needs that
72
- * operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's column
73
- * and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container grant on
74
- * its own column, or every row for `all`); an `app` capability, and a scoped read of an application table, every row.
87
+ * for a scoped site's read of an application table. A fragment its author marks `use: 'update'` or `'delete'` needs
88
+ * that operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's
89
+ * column and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container
90
+ * grant on its own column, or every row for `all`); an `app` capability, and a scoped read of an application table,
91
+ * every row.
75
92
  */
76
- export declare function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse, assigned?: readonly string[]): ScopeTerms;
93
+ export declare function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse): ScopeTerms;
77
94
  /**
78
95
  * A `Ref` of `dimension` whose action updates columns of the table: its update action, or a column's own write action.
79
96
  * Which columns it updates follows from the action (`updatableBy`).
@@ -153,7 +170,7 @@ export declare function versionArgument(context: TableContext, options: readonly
153
170
  export declare function selectOne<O>(context: TableContext, run: Runner, scope: OperationNode, visible?: readonly string[], action?: string): Promise<O>;
154
171
  export declare function answer(context: TableContext): ReturningNode;
155
172
  export declare function keyOf(model: TableModel): string;
156
- export declare function insertRow<O>(context: TableContext, run: Runner, values: ReadonlyMap<string, Primitive | null>, destination: RefGrant | undefined): Promise<O>;
173
+ export declare function insertRow<O>(context: TableContext, run: Runner, given: ReadonlyMap<string, Primitive | null>, destination: RefGrant | undefined): Promise<O>;
157
174
  /**
158
175
  * `insert(values, { onConflict: { columns, do } })`: on a conflict of `columns` (a unique index of the table), `nothing`
159
176
  * writes nothing and `update` sets the columns the table's update action writes, from `updates`.
@@ -181,7 +198,7 @@ export interface Addressed {
181
198
  * Zero changed rows → one follow-up read in the same transaction → 404 when the object is gone, else 409. An update
182
199
  * that sets no column writes nothing, not even the version: it reads the acknowledgement under the same conditions.
183
200
  */
184
- export declare function updateRow<O>(context: TableContext, run: Runner, target: Addressed, changes: ReadonlyMap<string, Primitive | null>, expectedVersion: OperationNode | undefined, destination?: RefGrant): Promise<O>;
201
+ export declare function updateRow<O>(context: TableContext, run: Runner, target: Addressed, given: ReadonlyMap<string, Primitive | null>, expectedVersion: OperationNode | undefined, destination?: RefGrant): Promise<O>;
185
202
  /** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
186
203
  export declare function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void>;
187
204
  type Columns<Row> = keyof Row & string;
@@ -74,9 +74,13 @@ export interface StoredFiles {
74
74
  promote(id: string, sha256: string, version: string): Promise<boolean>;
75
75
  deferScan(id: string, attempts: number, after: Date): Promise<boolean>;
76
76
  reject(id: string): Promise<boolean>;
77
- /** Objects whose rows a sweep deleted and whose own deletion it did not finish. */
78
- unfinishedDeletions(limit: number): Promise<readonly string[]>;
77
+ /** At most `limit` queued object keys recorded at or before `cutoff` (equality is due), oldest first. */
78
+ dueDeletions(limit: number, cutoff: Date): Promise<readonly string[]>;
79
+ /** Takes a due key out of the queue before its object is deleted; `false` when a cancel or a requeue got there first. */
80
+ claimDeletion(objectKey: string, cutoff: Date): Promise<boolean>;
79
81
  forgetDeletion(objectKey: string): Promise<void>;
82
+ /** Takes `objectKeys` out of the queue, so their objects stay: a restore's rows reference them again. The number taken. */
83
+ cancelDeletions(objectKeys: readonly string[]): Promise<number>;
80
84
  /** Clears the legacy marker of every migrated file that one of `columns` references: it is an ordinary file now. */
81
85
  adoptReferenced(columns: readonly FileColumnRef[]): Promise<number>;
82
86
  /** At most `limit` files past the grace that no column of `columns` references (pending ones included), oldest first. */
@@ -1,10 +1,20 @@
1
1
  import type { TablePolicyArtifact } from '@fabrika/auth-core';
2
+ import { type ApplicationRowsPlan } from './application-rows';
2
3
  import { type Tables } from './policy';
4
+ export { applicationRowRefusalText } from './application-rows';
5
+ export type { ApplicationRowRefusal, ApplicationRowsPlan } from './application-rows';
3
6
  export { PolicyError } from './errors';
4
7
  export type { FileReference } from './file-references';
5
8
  export type { AnyDbIndex, ApplicationRows, ApplicationTables, AppRecordRows, ChildRows, ClaimedRow, ClaimedRowHandle, ClaimOptions, ContainedRows, CountOptions, DataKind, DbIndex, FragmentTable, IndexedTable, InsertConflict, InsertMethod, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, PublicApplicationRows, PublicApplicationTables, PublicInsertMethod, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, RowOf, Saved, ScopedApplicationRows, ScopedApplicationTables, ScopeTarget, TableNameOf, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
6
9
  export { type ApplicationPolicy, type ApplicationScope, type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type FilePolicies, isTables, type QueuePolicy, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type TableAction, type TableActions, type TableInsert, Tables, type TableUpdate, type VersionColumn, type VocabularyTables, } from './policy';
7
10
  export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
11
+ /**
12
+ * The plan of seeding one row of each application table `rows` names (table → column → value), as an endpoint access
13
+ * case seeds its `appRows`: the order, the foreign keys that link one given row to another, and every refusal.
14
+ * `@fabrika/check` reports the refusals from source; `@fabrika/db/testing` throws the first, both in the words of
15
+ * `applicationRowRefusalText`.
16
+ */
17
+ export declare function applicationRowsPlan<DB, P>(tables: Tables<DB, P>, rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>): ApplicationRowsPlan;
8
18
  /** Every table's policy in the form the contract artifact carries, by table name. */
9
19
  export type TablePolicies = Readonly<Record<string, TablePolicyArtifact>>;
10
20
  /** The artifact form of every policy `defineTables` (or `readTables`) checked. */
@@ -1,4 +1,5 @@
1
1
  import { type NameSet } from './builtins';
2
+ import type { SqlDialect } from './database';
2
3
  /**
3
4
  * A day as the layer answers it: the database's `YYYY-MM-DD` text, or a decoded `Date` that is exactly a UTC midnight
4
5
  * in 0001–9999 — the only `Date` `Bun.SQL` decodes correctly from a `date`, whatever the process's time zone.
@@ -10,3 +11,23 @@ export declare function answerDays<R>(table: string, days: NameSet, rows: R[]):
10
11
  export declare function dayInput(value: string, where: string): string;
11
12
  /** A timestamp a write binds as text: strict ISO 8601 with `Z` or an offset, every field in range. */
12
13
  export declare function timestampInput(value: string, where: string): string;
14
+ /**
15
+ * What a write or a comparison binds for a timestamp on SQLite: the instant of a `Date`, or of the text `timestampInput`
16
+ * admits, as stored text. Digits past the millisecond are dropped; an instant outside the years 0000–9999 UTC is
17
+ * refused, since its text would not sort.
18
+ */
19
+ export declare function storedTimestamp(value: string | Date, where: string): string;
20
+ /** The columns of a read's rows the layer answers in a form of its own, by the name each arrives under. */
21
+ export interface RowColumns {
22
+ /** `date` columns: `YYYY-MM-DD` text. */
23
+ readonly days: NameSet;
24
+ /** Timestamps: a `Date` (SQLite answers its stored text). */
25
+ readonly timestamps: NameSet;
26
+ /** Booleans: `true` or `false` (SQLite answers 1 or 0). */
27
+ readonly booleans: NameSet;
28
+ }
29
+ /**
30
+ * Every row of a read as the layer answers it, in place: each day as `YYYY-MM-DD` text, and on SQLite each timestamp as
31
+ * a `Date` and each boolean as `true` or `false`, so a handler reads the same values on both dialects.
32
+ */
33
+ export declare function answerRows<R>(dialect: SqlDialect, table: string, columns: RowColumns, rows: R[]): R[];
@@ -0,0 +1,201 @@
1
+ import type { Database } from './database';
2
+ import type { Primitive } from './description';
3
+ import { type Tables } from './policy';
4
+ import type { TableProbe } from './store';
5
+ /** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
6
+ export type SampleValue = Primitive | null;
7
+ /** One seeded row and where it lies. */
8
+ export interface WorldRow {
9
+ /** The row's key: the dimension value of a dimension table's row, a child's own key. */
10
+ readonly key: string;
11
+ /** A child row's parent key; `null` for a dimension table. */
12
+ readonly parent: string | null;
13
+ /** The value of the grant dimension the row lies in (`IsolationWorlds.dimension`). */
14
+ readonly scope: string;
15
+ /**
16
+ * Every dimension value the row lies in: a dimension table's own first, then each container, innermost first. A
17
+ * share link's chain is this list.
18
+ */
19
+ readonly chain: readonly {
20
+ readonly type: string;
21
+ readonly value: string;
22
+ }[];
23
+ /** The row's values of the policy's update columns, as seeded. */
24
+ readonly updates: Readonly<Record<string, SampleValue>>;
25
+ /**
26
+ * The distinct value written into every text column the fixture filled itself, in this row and in its containers.
27
+ * Each occurs in no other fixture, so one found in an answer to another scope is a leaked row.
28
+ */
29
+ readonly markers: readonly string[];
30
+ }
31
+ /** One seeded row of an application table, which lies in no dimension. */
32
+ export interface ApplicationRow {
33
+ readonly key: string;
34
+ /** The row's values of the policy's update columns, as seeded. */
35
+ readonly updates: Readonly<Record<string, SampleValue>>;
36
+ /** The distinct value written into every text column the fixture filled itself. */
37
+ readonly markers: readonly string[];
38
+ }
39
+ /** Rows of application tables seeded together for one case, and their removal once the case is over. */
40
+ export interface SeededApplicationRows {
41
+ /** Each table's row key, by table. */
42
+ readonly keys: Readonly<Record<string, string>>;
43
+ /**
44
+ * Deletes the rows, the rows their required foreign keys and file columns made the fixture insert, and every row
45
+ * that refers to one of them, however deep (what the case's handler wrote about them), in one transaction, so rows
46
+ * that refer to each other go together. A row already gone is skipped.
47
+ */
48
+ remove(): Promise<void>;
49
+ }
50
+ /** A row seeded under another: its key, and the distinct value written into every text column the fixture filled. */
51
+ export interface SeededRow {
52
+ readonly key: string;
53
+ readonly markers: readonly string[];
54
+ }
55
+ /**
56
+ * What the isolation fixture cannot seed for a schema: a CHECK its values fail, a required foreign key to a scoped table
57
+ * outside the containment chain. It is a limit of the generator, named with the constraint or the column, never a
58
+ * failure of the handler or the policy a case is about.
59
+ */
60
+ export declare class SeedLimitError extends Error {
61
+ readonly name = "SeedLimitError";
62
+ }
63
+ /** One row of a table in each of two containment chains that share no value. */
64
+ export interface IsolationWorlds {
65
+ /**
66
+ * The dimension a caller's grants are scoped by: a dimension table's container, or its own dimension when it has
67
+ * none; a child table's parent's.
68
+ */
69
+ readonly dimension: string;
70
+ readonly own: WorldRow;
71
+ readonly other: WorldRow;
72
+ /**
73
+ * Deletes both rows of the table and every row that refers to them, however deep; the containers stay. A case whose
74
+ * rows hold pinned values removes them, so the next case can pin the same values again under a unique index.
75
+ */
76
+ readonly remove: () => Promise<void>;
77
+ }
78
+ /** What a test kit seeds through, over its migrated schema. */
79
+ export interface TestSeeding {
80
+ /**
81
+ * Seeds one row of `table` in each of two fresh chains, with every container row a table owns. `values` (column →
82
+ * value) are written into both rows of `table`: the state an endpoint's precondition needs. A text column keeps its
83
+ * marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
84
+ * `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
85
+ * counts among the other row's markers, so a leak of it is still found. A pin of a column that places the row, or of
86
+ * no text column, throws.
87
+ */
88
+ seedWorlds<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>, pins?: Readonly<Record<string, string>>): Promise<IsolationWorlds>;
89
+ /**
90
+ * Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
91
+ * as given, a text column too, every other column sampled. A value for a stamped column or a file column throws.
92
+ */
93
+ seedRow<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>): Promise<ApplicationRow>;
94
+ /**
95
+ * Seeds one row of each application table `rows` names (table → column → value), as `seedRow` does, in foreign-key
96
+ * order: a foreign key from one of them to another holds that row's key unless the values give it. Every table's
97
+ * values are checked before the first insert, and a table that fails removes the rows seeded before it. `remove`
98
+ * deletes them, the rows a required foreign key of theirs made it insert, and every row that refers to any of them,
99
+ * so the next case starts without them.
100
+ */
101
+ seedApplicationRows<DB, P>(tables: Tables<DB, P>, rows: Readonly<Record<string, Readonly<Record<string, SampleValue>>>>): Promise<SeededApplicationRows>;
102
+ /**
103
+ * Seeds one row of `table`, a child or dimension table that lies in the object of `under` (a row `seedWorlds`
104
+ * seeded), placed in that row's chain: the row a fixture names by id, such as a note's comment. Answers its key and
105
+ * the markers it holds.
106
+ */
107
+ seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: WorldRow): Promise<SeededRow>;
108
+ /** Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file column a seeded file. */
109
+ sampleInsert<DB, P>(tables: Tables<DB, P>, table: string): Promise<Readonly<Record<string, SampleValue>>>;
110
+ /**
111
+ * The object key of every file the fixture seeded into a file column, oldest first. Each stands for an empty object,
112
+ * which a test's object store holds when a handler serves or opens the file.
113
+ */
114
+ seededObjects(): readonly string[];
115
+ }
116
+ export interface TestDatabase extends TestSeeding {
117
+ /** The connection `boot` binds the data layer to: on Postgres the runtime role on the migrated schema; on SQLite the database itself. */
118
+ readonly database: Database;
119
+ /** The migrated schema: `app_test_<hex>` on Postgres, `main` on SQLite. */
120
+ readonly schema: string;
121
+ /** Closes the connections and drops the schema and its roles (on SQLite: closes the in-memory database). */
122
+ close(): Promise<void>;
123
+ }
124
+ /** A column of the migrated schema, as the seeding reads it. */
125
+ export interface SeedColumn {
126
+ readonly table: string;
127
+ readonly name: string;
128
+ /** The type as the database names it, for a message. */
129
+ readonly type: string;
130
+ readonly nullable: boolean;
131
+ /** The database fills it when an insert leaves it out: a default, an identity, a generated column. */
132
+ readonly defaulted: boolean;
133
+ /** A text type that is no enum: where nothing else fills it, the fixture writes a marker into it. */
134
+ readonly text: boolean;
135
+ /** A uuid type: a key or containment column of it holds a random uuid as its scope value. */
136
+ readonly uuid: boolean;
137
+ /** A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it cannot fill. */
138
+ readonly sample: () => Primitive;
139
+ }
140
+ /** A CHECK constraint of the schema, by the columns it names. */
141
+ export interface CheckConstraint {
142
+ readonly name: string;
143
+ readonly table: string;
144
+ readonly columns: readonly string[];
145
+ /** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
146
+ readonly values: readonly string[];
147
+ }
148
+ /** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it. */
149
+ export interface SeededFile {
150
+ readonly id: string;
151
+ readonly kind: string;
152
+ readonly objectKey: string;
153
+ readonly sha256: string;
154
+ readonly objectVersion: string;
155
+ }
156
+ /** A row the fixture inserted, found again by `match` (column → value): what a removal deletes. */
157
+ export interface InsertedRow {
158
+ readonly table: string;
159
+ readonly match: ReadonlyMap<string, SampleValue>;
160
+ }
161
+ /** How many rows one removal deletes, referring rows included, before it gives up. */
162
+ export declare const MAX_REMOVED_ROWS = 10000;
163
+ /** The seed limit of a removal that reaches more than `MAX_REMOVED_ROWS` rows. */
164
+ export declare function removalLimit(): SeedLimitError;
165
+ /** What a kit gives the seeding: its schema's columns and CHECK constraints, and the statements it runs. */
166
+ export interface SeedingBackend {
167
+ readonly columns: readonly SeedColumn[];
168
+ /** Every CHECK constraint of the schema's tables; read once, on the first column that needs them. */
169
+ checks(): Promise<readonly CheckConstraint[]>;
170
+ /** Inserts one row and answers it as stored; a CHECK or foreign key it fails is a `SeedLimitError` (`checkLimit`, `foreignKeyLimit`). */
171
+ insert(table: string, values: ReadonlyMap<string, SampleValue>): Promise<Readonly<Record<string, unknown>>>;
172
+ /** One row of `table`, of `columns`, or `undefined` when it has none. */
173
+ firstRow(table: string, columns: readonly string[]): Promise<Readonly<Record<string, unknown>> | undefined>;
174
+ insertFile(file: SeededFile): Promise<void>;
175
+ /**
176
+ * Deletes `rows` (each found by its `match`; one already gone is skipped) and every row that refers to one of them,
177
+ * however deep, in one transaction whose foreign keys are checked once all are gone, so rows that refer to each other
178
+ * go together. No write moves or adds a referring row between finding the rows and deleting them.
179
+ */
180
+ remove(rows: readonly InsertedRow[]): Promise<void>;
181
+ }
182
+ /** The seed limit of a CHECK a seeded row fails. */
183
+ export declare function checkLimit(constraint: string, table: string): SeedLimitError;
184
+ /** The seed limit of a foreign key a seeded row breaks. */
185
+ export declare function foreignKeyLimit(constraint: string, table: string): SeedLimitError;
186
+ /** The seed limit of a required column whose type the fixture has no sample of. */
187
+ export declare function typeLimit(table: string, column: string, type: string): SeedLimitError;
188
+ export declare function randomHex(): string;
189
+ /**
190
+ * The object version a seeded file was scanned at: whoever stocks its empty object (`seededObjects`) stores it under
191
+ * this version, so a file of a scanning kind is served as a live one is, by its scanned version.
192
+ */
193
+ export declare const SEEDED_OBJECT_VERSION = "\"seeded\"";
194
+ /** The isolation fixtures over the schema `backend` describes. */
195
+ export declare function testSeeding(backend: SeedingBackend): TestSeeding;
196
+ /**
197
+ * The untyped handle over one table of the data layer `scoped(tables)` created; it reaches the database once `boot`
198
+ * has bound that layer. Every runtime check of a store applies: kind, dimension, action and the request's authority.
199
+ * `module` is the kit's, which refuses a production process.
200
+ */
201
+ export declare function probeTable(module: string, layer: unknown, table: string): TableProbe;
@@ -0,0 +1,22 @@
1
+ import type { TableProbe } from './store';
2
+ import { type TestDatabase } from './testing-shared';
3
+ export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store';
4
+ export { type ApplicationRow, type IsolationWorlds, type SampleValue, SEEDED_OBJECT_VERSION, type SeededApplicationRows, type SeededRow, SeedLimitError, type TestDatabase, type WorldRow, } from './testing-shared';
5
+ export interface TestDatabaseOptions {
6
+ /** The application's `db/migrations/` directory. */
7
+ readonly migrations: string | URL;
8
+ /** The test file. `@fabrika/db/testing` names it when it skips; this kit never skips. */
9
+ readonly label: string;
10
+ }
11
+ /**
12
+ * A fresh in-memory database with the framework's and the application's migrations applied by the runner a Durable
13
+ * Object boots with (`@fabrika/db/sqlite-migrate`), opened with its engine (`@fabrika/db/sqlite`). Never `null`: it
14
+ * needs no backend, so it never skips; its type is still assignable to `@fabrika/db/testing`'s, so a generated test
15
+ * that checks for `null` compiles against both kits.
16
+ */
17
+ export declare function testDatabase(options: TestDatabaseOptions): Promise<TestDatabase>;
18
+ /**
19
+ * The untyped handle over one table of the data layer `scoped(tables)` created; it reaches the database once `boot`
20
+ * has bound that layer. Every runtime check of a store applies: kind, dimension, action and the request's authority.
21
+ */
22
+ export declare function tableProbe(layer: unknown, table: string): TableProbe;