@fabrika/db 0.9.0-dev.1 → 0.9.0-dev.10

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 (78) hide show
  1. package/package.json +44 -12
  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 +191 -0
  6. package/src/codegen.ts +170 -28
  7. package/src/database.ts +227 -61
  8. package/src/description.ts +34 -8
  9. package/src/errors.ts +6 -4
  10. package/src/file-columns.ts +36 -9
  11. package/src/framework-tables.ts +28 -8
  12. package/src/framework.ts +14 -5
  13. package/src/guard.ts +8 -0
  14. package/src/index.ts +10 -1
  15. package/src/job-leases.ts +210 -54
  16. package/src/job-wakes.ts +450 -0
  17. package/src/json.ts +124 -0
  18. package/src/links.ts +8 -1
  19. package/src/migrations-sqlite.ts +163 -0
  20. package/src/migrations.ts +25 -0
  21. package/src/nodes.ts +64 -9
  22. package/src/orm-types.ts +5 -5
  23. package/src/orm.ts +94 -37
  24. package/src/policy.ts +17 -2
  25. package/src/postgres.ts +26 -0
  26. package/src/registry.ts +11 -2
  27. package/src/sql.ts +230 -477
  28. package/src/sqlite-bun.ts +149 -0
  29. package/src/sqlite-migrate.ts +242 -0
  30. package/src/sqlite.ts +224 -0
  31. package/src/store.ts +385 -103
  32. package/src/stored-files.ts +188 -52
  33. package/src/tables.ts +16 -0
  34. package/src/temporal.ts +122 -9
  35. package/src/testing-shared.ts +878 -0
  36. package/src/testing-sqlite.ts +570 -0
  37. package/src/testing.ts +255 -482
  38. package/types/src/admissions.d.ts +21 -0
  39. package/types/src/application-rows.d.ts +58 -0
  40. package/types/src/builtins.d.ts +42 -0
  41. package/types/src/capability.d.ts +119 -0
  42. package/types/src/codegen-sqlite.d.ts +13 -0
  43. package/types/src/codegen.d.ts +113 -0
  44. package/types/src/database.d.ts +185 -0
  45. package/types/src/description.d.ts +124 -0
  46. package/types/src/errors.d.ts +98 -0
  47. package/types/src/file-columns.d.ts +39 -0
  48. package/types/src/file-references.d.ts +27 -0
  49. package/types/src/framework-tables.d.ts +59 -0
  50. package/types/src/framework.d.ts +38 -0
  51. package/types/src/guard.d.ts +23 -0
  52. package/types/src/identifier.d.ts +4 -0
  53. package/types/src/index.d.ts +11 -0
  54. package/types/src/job-leases.d.ts +112 -0
  55. package/types/src/job-wakes.d.ts +101 -0
  56. package/types/src/json.d.ts +18 -0
  57. package/types/src/links.d.ts +13 -0
  58. package/types/src/migrations-sqlite.d.ts +4 -0
  59. package/types/src/migrations.d.ts +26 -0
  60. package/types/src/nodes.d.ts +73 -0
  61. package/types/src/orm-types.d.ts +638 -0
  62. package/types/src/orm.d.ts +82 -0
  63. package/types/src/policy.d.ts +358 -0
  64. package/types/src/postgres.d.ts +12 -0
  65. package/types/src/production.d.ts +5 -0
  66. package/types/src/registry.d.ts +43 -0
  67. package/types/src/sql.d.ts +67 -0
  68. package/types/src/sqlite-bun.d.ts +21 -0
  69. package/types/src/sqlite-migrate.d.ts +28 -0
  70. package/types/src/sqlite.d.ts +24 -0
  71. package/types/src/store.d.ts +351 -0
  72. package/types/src/stored-files.d.ts +102 -0
  73. package/types/src/tables.d.ts +21 -0
  74. package/types/src/temporal.d.ts +36 -0
  75. package/types/src/testing-shared.d.ts +250 -0
  76. package/types/src/testing-sqlite.d.ts +22 -0
  77. package/types/src/testing.d.ts +35 -0
  78. package/types/src/vocabulary-tables.d.ts +225 -0
@@ -0,0 +1,101 @@
1
+ import type { LeaseFence } from './capability';
2
+ import { type Session } from './database';
3
+ import type { JobOutcome, LeaseProjection } from './job-leases';
4
+ import type { DataLayerRuntime } from './store';
5
+ export declare const WAKE_REASONS: readonly ["cron", "kick", "claim", "retry"];
6
+ export type WakeReason = (typeof WAKE_REASONS)[number];
7
+ export interface NewWake {
8
+ readonly job: string;
9
+ readonly reason: WakeReason;
10
+ readonly dueAt: Date;
11
+ /** Wakes under one key are one row: `cron:<job>:<expr>`, `claim:<job>`, `kick:<job>:<due second>`. */
12
+ readonly dedupe?: string;
13
+ }
14
+ export interface Wake {
15
+ readonly id: string;
16
+ readonly job: string;
17
+ readonly reason: WakeReason;
18
+ readonly dueAt: Date;
19
+ /** How many failed runs moved this wake (`retry`). */
20
+ readonly attempt: number;
21
+ readonly dedupe: string | null;
22
+ /** Taken by the run that holds its job's lease, when that run took it: that run's finish consumes or retries it. */
23
+ readonly owned: boolean;
24
+ }
25
+ /**
26
+ * What a run's finish does with the wakes it owned (those due when it took the lease), applied in the finish's
27
+ * transaction and only when the finish still held the lease. Without one, a success is `completed` and a failure
28
+ * leaves the wakes as they are.
29
+ */
30
+ export type FinishWakes =
31
+ /** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
32
+ {
33
+ readonly kind: 'completed';
34
+ readonly nextCron?: {
35
+ readonly expression: string;
36
+ readonly dueAt: Date;
37
+ };
38
+ }
39
+ /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
40
+ | {
41
+ readonly kind: 'retry';
42
+ readonly at: Date;
43
+ };
44
+ export interface JobWakes {
45
+ /**
46
+ * Records a pending wake, in `using` when given (the transaction of the write it belongs to). A key already pending
47
+ * keeps one row at the earlier due time: a later wake never postpones an earlier one. A merge takes the row from the
48
+ * run that owns it, except a cron wake's, whose next fire that run's finish schedules. Answers the row that holds it;
49
+ * a key another job holds is refused.
50
+ */
51
+ schedule(wake: NewWake, using?: Session): Promise<Wake>;
52
+ /** The pending wakes of `job`, earliest first. */
53
+ pending(job: string): Promise<readonly Wake[]>;
54
+ /**
55
+ * When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
56
+ * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given.
57
+ */
58
+ next(using?: Session): Promise<Date | null>;
59
+ /** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
60
+ untilNext(using?: Session): Promise<number | null>;
61
+ /** The database's clock, read in `using` when given: a wake due now is due by it. */
62
+ now(using?: Session): Promise<Date>;
63
+ /**
64
+ * Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
65
+ * each declared job's cron wake whose key names another expression; answers how many it deleted.
66
+ */
67
+ reconcile(declared: readonly DeclaredJob[]): Promise<number>;
68
+ /**
69
+ * The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
70
+ * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
71
+ */
72
+ hasten(ids: readonly string[]): Promise<number>;
73
+ /**
74
+ * The jobs whose lease a run holds past its expiry, declared or not: a removed job's crashed holder still arms the
75
+ * alarm through `next` until someone reaps it.
76
+ */
77
+ expiredHolders(): Promise<readonly string[]>;
78
+ }
79
+ /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
80
+ export interface DeclaredJob {
81
+ readonly job: string;
82
+ readonly expression: string;
83
+ }
84
+ /**
85
+ * A finish's instruction checked before its statement runs, with the default filled in: `null` leaves the wakes. The
86
+ * lease store calls it, so a malformed instruction refuses the finish and leaves the lease held.
87
+ */
88
+ export declare function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined): FinishWakes | null;
89
+ /**
90
+ * The lease store's projection, all in the lease statement's transaction: a taken lease marks the wakes its run owns, a
91
+ * fenced finish applies its wake instruction to them, a finish or a reap leaves none owned, and every lease change then
92
+ * runs the runtime's projection.
93
+ */
94
+ export declare function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjection;
95
+ /**
96
+ * Sets the claim wake of `fence`'s job to `dueAt`, or removes it for `null`, in `transaction`: the claim's fenced
97
+ * transaction, so the re-arm commits with the rows it leased. The attempt's first claim replaces what an earlier run
98
+ * left; each later claim keeps the earliest re-arm of the attempt.
99
+ */
100
+ export declare function rearmClaim(runtime: DataLayerRuntime, transaction: Session, fence: LeaseFence, dueAt: Date | null): Promise<void>;
101
+ export declare function jobWakes(runtime: () => DataLayerRuntime): JobWakes;
@@ -0,0 +1,18 @@
1
+ /** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
2
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
3
+ readonly [key: string]: JsonValue | undefined;
4
+ };
5
+ /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
6
+ export type JsonColumnValue = Exclude<JsonValue, null>;
7
+ /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
8
+ export declare const MAX_JSON_DEPTH = 64;
9
+ /**
10
+ * A written JSON column value as the text the layer binds: plain objects and arrays, strings, finite numbers, booleans
11
+ * and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
12
+ */
13
+ export declare function jsonInput(value: unknown, where: string): string;
14
+ /**
15
+ * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
16
+ * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
17
+ */
18
+ export declare function sqliteJson(value: unknown, where: string): unknown;
@@ -0,0 +1,13 @@
1
+ import type { OperationNode } from 'kysely';
2
+ import type { RefGrant } from './capability';
3
+ import type { Container } from './policy';
4
+ export interface LinkValue {
5
+ readonly link: Container;
6
+ readonly value: string;
7
+ }
8
+ /**
9
+ * The column values a Ref addresses over `links`: the first link takes the Ref's id, every other link a value
10
+ * from its chain. A chain entry no link covers cannot be enforced, so it is refused rather than ignored.
11
+ */
12
+ export declare function linkValues(table: string, links: readonly Container[], grant: RefGrant): readonly LinkValue[];
13
+ export declare function linksPredicate(table: string, values: readonly LinkValue[]): OperationNode;
@@ -0,0 +1,4 @@
1
+ import { type FrameworkMigration } from './migrations';
2
+ /** The `strftime` format of a stored timestamp; `strftime(SQLITE_NOW_FORMAT, 'now')` is the database's clock. */
3
+ export declare const SQLITE_NOW_FORMAT = "%Y-%m-%dT%H:%M:%fZ";
4
+ export declare const SQLITE_FRAMEWORK_MIGRATIONS: readonly FrameworkMigration[];
@@ -0,0 +1,26 @@
1
+ /** Migration identity of the framework's tables in every application schema: bundle `fabrika`, same ledger. */
2
+ export declare const FRAMEWORK_MIGRATION_BUNDLE = "fabrika";
3
+ export declare const WEBHOOK_BINDINGS_TABLE = "fabrika_webhook_bindings";
4
+ export declare const WEBHOOK_DELIVERIES_TABLE = "fabrika_webhook_deliveries";
5
+ export declare const JOB_LEASES_TABLE = "fabrika_job_leases";
6
+ export declare const JOB_KICKS_TABLE = "fabrika_job_kicks";
7
+ export declare const JOB_WAKES_TABLE = "fabrika_wakes";
8
+ export declare const FORM_ADMISSIONS_TABLE = "fabrika_form_admissions";
9
+ export declare const FORM_CHALLENGES_TABLE = "fabrika_form_challenges";
10
+ export declare const FORM_FILES_TABLE = "fabrika_form_files";
11
+ export declare const FORM_BYTES_TABLE = "fabrika_form_bytes";
12
+ export declare const FILES_TABLE = "fabrika_files";
13
+ export declare const FILE_DELETIONS_TABLE = "fabrika_file_deletions";
14
+ /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
15
+ export declare const FILES_RELEASE_FUNCTION = "fabrika_files_release";
16
+ /**
17
+ * The function an adoption migration calls right before it reads a collection's table: it copies the rows an older
18
+ * instance wrote since 0008 ran, so each one it adopts has its `fabrika_files` row. Idempotent.
19
+ */
20
+ export declare const FILES_COPY_FUNCTION = "fabrika_files_copy_legacy";
21
+ export interface FrameworkMigration {
22
+ /** Ordered by name; an applied one is immutable, like an application's. */
23
+ readonly name: string;
24
+ readonly sql: string;
25
+ }
26
+ export declare const FRAMEWORK_MIGRATIONS: readonly FrameworkMigration[];
@@ -0,0 +1,73 @@
1
+ import { type DeleteQueryNode, type InsertQueryNode, type OperationNode, ReferenceNode, ReturningNode, type SelectQueryNode, type UpdateQueryNode, WhereNode } from 'kysely';
2
+ import { type NameSet } from './builtins';
3
+ import type { SqlDialect } from './database';
4
+ import type { Condition, Primitive, SelectState } from './description';
5
+ export declare function column(table: string, name: string): ReferenceNode;
6
+ export declare function equals(table: string, name: string, value: Primitive): OperationNode;
7
+ export declare function allOf(nodes: readonly OperationNode[]): OperationNode;
8
+ /** One node, or the OR of several in a parenthesis: inside an AND, `a and b or c` would read as `(a and b) or c`. */
9
+ export declare function anyOf(nodes: readonly OperationNode[]): OperationNode;
10
+ export declare function inList(table: string, name: string, values: readonly string[]): OperationNode;
11
+ /** The scope of a `Within` that is not limited to scope values. */
12
+ export declare function everything(): OperationNode;
13
+ /** LIKE treats `\` as its escape character by default, so the text matches literally. */
14
+ export declare function containsPattern(text: string): string;
15
+ /**
16
+ * The caller's conditions go inside an explicit parenthesis and the scope is the top-level right conjunct, so
17
+ * `x or true` cannot escape it. The guard checks this shape.
18
+ */
19
+ export declare function scopedWhere(conditions: OperationNode | undefined, scope: OperationNode): WhereNode;
20
+ /** `returning key as id[, version as version]`: a mutation's acknowledgement, never row data. */
21
+ export declare function acknowledgement(table: string, key: string, version: string | undefined): ReturningNode;
22
+ /** `after` is a keyset page's position, ANDed to the caller's conditions inside their parenthesis. */
23
+ export declare function selectNode(state: SelectState, visible: readonly string[], scope: OperationNode, after?: OperationNode, days?: NameSet, dialect?: SqlDialect): SelectQueryNode;
24
+ export interface AggregateColumns {
25
+ readonly groupBy: readonly string[];
26
+ readonly count: boolean;
27
+ readonly sum: readonly string[];
28
+ readonly min: readonly string[];
29
+ readonly max: readonly string[];
30
+ }
31
+ export declare function aggregateNode(table: string, columns: AggregateColumns, conditions: readonly Condition[], scope: OperationNode, days?: NameSet): SelectQueryNode;
32
+ /** `conflict` names the columns of a unique index the insert does nothing on: `on conflict (<columns>) do nothing`. */
33
+ export declare function insertNode(table: string, values: ReadonlyMap<string, Primitive | null>, answer: ReturningNode, conflict?: readonly string[]): InsertQueryNode;
34
+ export declare function updateNode(table: string, values: ReadonlyMap<string, Primitive | null>, bump: string | undefined, where: WhereNode, answer: ReturningNode): UpdateQueryNode;
35
+ export declare function deleteNode(table: string, where: WhereNode, key: string): DeleteQueryNode;
36
+ /** `select key from table where (conditions) and scope limit 1`: does the scoped object exist? */
37
+ export declare function existsNode(table: string, key: string, scope: OperationNode, conditions?: OperationNode): SelectQueryNode;
38
+ /** `select key as id, version as version from table where (conditions) and scope limit 1`: an update that sets nothing. */
39
+ export declare function acknowledgementNode(table: string, key: string, version: string | undefined, where: WhereNode): SelectQueryNode;
40
+ /** `select columns from table where scope limit 1`: the containment columns of one object, for the framework's locator. */
41
+ export declare function locateNode(table: string, columns: readonly string[], scope: OperationNode): SelectQueryNode;
42
+ /**
43
+ * The same check, locked: `for share` keeps the row from moving until the transaction that checked it ends, `for
44
+ * update` also keeps every other writer and locker of it waiting.
45
+ */
46
+ export declare function lockNode(table: string, key: string, scope: OperationNode, lock?: 'share' | 'update'): SelectQueryNode;
47
+ /** The alias a keyset page's position column is selected under; a column name holds no dot, so none collides. */
48
+ export declare function cursorAlias(index: number): string;
49
+ /** `select …, cast(<column> as text) as "keyset.c<n>"`: each order column's exact value, which a Date would round. */
50
+ export declare function withCursorColumns(node: SelectQueryNode, table: string, columns: readonly string[]): SelectQueryNode;
51
+ /**
52
+ * A queue claim's lease: `select <columns> from table where (<conditions> and (<due> is not null and <due> <= $now and
53
+ * <attempts> < $max)) and scope order by <due>, <key> limit $n for update skip locked`. A row another claim holds is
54
+ * skipped, never waited for.
55
+ */
56
+ export declare function claimNode(state: SelectState, columns: readonly string[], due: {
57
+ readonly due: string;
58
+ readonly attempts: string;
59
+ readonly now: Date;
60
+ readonly maxAttempts: number;
61
+ }, scope: OperationNode, days: NameSet, dialect?: SqlDialect): SelectQueryNode;
62
+ /**
63
+ * When the same claim next finds a row: `select <due> from table where (<conditions> and (<due> > $now and <attempts> <
64
+ * $max)) and scope order by <due> limit 1`, with `state` the claim's conditions ordered by `<due>`, limited to one.
65
+ */
66
+ export declare function nextClaimNode(state: SelectState, due: {
67
+ readonly due: string;
68
+ readonly attempts: string;
69
+ readonly now: Date;
70
+ readonly maxAttempts: number;
71
+ }, scope: OperationNode, days: NameSet, dialect?: SqlDialect): SelectQueryNode;
72
+ /** `select <columns> from table where scope for update`: a mutation's precondition read of its own target. */
73
+ export declare function lockedSelectNode(table: string, columns: readonly string[], scope: OperationNode, days?: NameSet): SelectQueryNode;