@fougere/adapter-sql 0.2.0-alpha.2 → 0.4.0-alpha.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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/dist/crud.d.ts +14 -3
  3. package/dist/crud.d.ts.map +1 -1
  4. package/dist/crud.js +33 -4
  5. package/dist/crud.js.map +1 -1
  6. package/dist/ddl.d.ts.map +1 -1
  7. package/dist/ddl.js +2 -2
  8. package/dist/ddl.js.map +1 -1
  9. package/dist/dialect.d.ts +20 -0
  10. package/dist/dialect.d.ts.map +1 -1
  11. package/dist/dialect.js +27 -1
  12. package/dist/dialect.js.map +1 -1
  13. package/dist/diff.d.ts.map +1 -1
  14. package/dist/diff.js +2 -2
  15. package/dist/diff.js.map +1 -1
  16. package/dist/fields.d.ts +22 -0
  17. package/dist/fields.d.ts.map +1 -0
  18. package/dist/fields.js +2 -0
  19. package/dist/fields.js.map +1 -0
  20. package/dist/index.d.ts +6 -3
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +7 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/setup.d.ts +18 -10
  25. package/dist/setup.d.ts.map +1 -1
  26. package/dist/setup.js +10 -23
  27. package/dist/setup.js.map +1 -1
  28. package/dist/sqlite.d.ts +12 -0
  29. package/dist/sqlite.d.ts.map +1 -0
  30. package/dist/sqlite.js +34 -0
  31. package/dist/sqlite.js.map +1 -0
  32. package/dist/step.d.ts +78 -0
  33. package/dist/step.d.ts.map +1 -0
  34. package/dist/step.js +233 -0
  35. package/dist/step.js.map +1 -0
  36. package/dist/table.d.ts +19 -10
  37. package/dist/table.d.ts.map +1 -1
  38. package/dist/table.js +36 -30
  39. package/dist/table.js.map +1 -1
  40. package/package.json +11 -4
  41. package/src/check.ts +76 -0
  42. package/src/crud.ts +570 -0
  43. package/src/ddl.ts +242 -0
  44. package/src/dialect.ts +204 -0
  45. package/src/diff.ts +196 -0
  46. package/src/fields.ts +24 -0
  47. package/src/index.ts +40 -0
  48. package/src/setup.ts +63 -0
  49. package/src/sqlite.ts +43 -0
  50. package/src/step.ts +287 -0
  51. package/src/table.ts +447 -0
  52. package/src/values.ts +105 -0
package/src/table.ts ADDED
@@ -0,0 +1,447 @@
1
+ import { Lifecycle, Role } from '@fougere/schema';
2
+ /**
3
+ * Entity → table description, with no SQL in sight.
4
+ *
5
+ * This is the neutral middle term: one projection reads the entity's axes and
6
+ * produces a `TableDef`; a `Dialect` turns that into SQL. Neither half knows the
7
+ * other — the dialect never mentions a field. Adding a dialect touches only the
8
+ * second half.
9
+ *
10
+ * `ColumnDef.stated` is the one member the axes did not produce. It names one engine's
11
+ * column type, so dropping it leaves every column describable.
12
+ */
13
+ import { Anatomy, FieldGroup, Unique, fieldsOf, lowerFirst, schemaOf, type Field, type SchemaView, type SchemaOrCard } from '@fougere/schema';
14
+ import { boundsOf, type ShapeBounds } from './check.js';
15
+ import type { SqlField } from './fields.js';
16
+
17
+ /** The shape keywords a dialect needs to choose a column type. */
18
+ export interface ColumnShape {
19
+ type?: string;
20
+ format?: string;
21
+ maxLength?: number;
22
+ }
23
+
24
+ /** One column, described by the axes — plus, at most, what the entity stated for sql. */
25
+ export interface ColumnDef {
26
+ /** Field key on the entity. */
27
+ field: string;
28
+ /** SQL column name (snake_case). */
29
+ name: string;
30
+ /** The value shape, nullable union already unwrapped. */
31
+ shape?: ColumnShape;
32
+ nullable: boolean;
33
+ primary: boolean;
34
+ /** A literal default (`lifecycle.create.value`), when the field declares one. */
35
+ default?: unknown;
36
+ /** A {@link Unique} of one — realized as a column constraint the database enforces. */
37
+ unique?: boolean;
38
+ /** `role.index` — realized as a separate `CREATE INDEX`, never a constraint. */
39
+ index?: boolean;
40
+ /**
41
+ * What the shape bounds beyond its type — `oneOf`, `min`, `max`. Realized as a
42
+ * `CHECK`, so the rule holds on every write and not only at the façade.
43
+ */
44
+ bounds?: ShapeBounds;
45
+ /** The FK target, from `role.relation` when it's a `ref()` (kind `'one'`). */
46
+ references?: ColumnReference;
47
+ /**
48
+ * What the entity stated for THIS adapter — never an axis. It says how the column is
49
+ * realized here; drop it and the column is still describable.
50
+ */
51
+ stated?: SqlField;
52
+ }
53
+
54
+ export interface ColumnReference {
55
+ table: string;
56
+ column: string;
57
+ onDelete?: 'cascade' | 'restrict' | 'set null';
58
+ }
59
+
60
+ export interface TableDef {
61
+ name: string;
62
+ columns: ColumnDef[];
63
+ /** PK column names when the key is composite — empty for a simple key. */
64
+ compositePrimary: string[];
65
+ /**
66
+ * Column groups unique together, from `entity(fields, { unique: [...] })`.
67
+ * A single-field group is left to the column's own `unique` — this is the
68
+ * table-level form, for facts no column can hold alone.
69
+ */
70
+ uniqueGroups: string[][];
71
+ }
72
+
73
+ /** camelCase → snake_case */
74
+ export function toSnakeCase(str: string): string {
75
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
76
+ }
77
+
78
+ /**
79
+ * A `many` relation owns no column — the join lives on the other side. Every
80
+ * other field becomes exactly one column.
81
+ */
82
+ function isStored(field: Field): boolean {
83
+ return !Role.of(field).isCollection;
84
+ }
85
+
86
+ /**
87
+ * The target's primary key column. A live thunk (an in-process entity) answers
88
+ * for real; a relation reconstructed from a lone `Card` (without a `Bundle`) has lost it to a
89
+ * name stand-in with no `getFields` — the convention there is to assume `id`.
90
+ */
91
+ function primaryColumnOf(target: Partial<SchemaView>): string {
92
+ if (typeof target.getFields !== 'function') return 'id';
93
+ for (const [name, field] of Object.entries(target.getFields())) {
94
+ if (Role.of(field).isPrimary) return toSnakeCase(name);
95
+ }
96
+ return 'id'; // declared no primary() field — defensive, shouldn't happen
97
+ }
98
+
99
+ /**
100
+ * The FK target for a `ref()` field: the table it points at plus its PK column.
101
+ *
102
+ * `tableNameOf` is an identity map — built once per app generation pass, see
103
+ * {@link toTables} — from a LIVE entity class to the table name already resolved
104
+ * for it. Reusing that name (instead of re-deriving one from the class name) is
105
+ * what keeps a custom `tableName` resolver honest: `demos/schema-ecommerce`
106
+ * names `Category`'s table `"categories"` (an irregular plural its resolver
107
+ * special-cases) — re-deriving from `Category.name` through the DEFAULT
108
+ * convention would silently produce `"categorys"` instead.
109
+ *
110
+ * A miss (the target isn't part of this batch — a cross-frond target, or a live
111
+ * class the app substituted for one a package hardcoded — e.g.
112
+ * `@fougere/auth-better`'s `AuthSession` always points at its own default
113
+ * `AuthUser`, never at whatever `opts.user` the app actually registered) falls
114
+ * back to deriving the name from the class — correct when that class follows
115
+ * the default convention, wrong if the app ALSO overrides `tableName` for it.
116
+ */
117
+ function referenceFor(
118
+ field: Field,
119
+ resolve: (name: string) => string,
120
+ tableNameOf?: Map<SchemaOrCard, string>,
121
+ hosted?: HostedNames,
122
+ ): ColumnReference | undefined {
123
+ const relation = Role.of(field).relation;
124
+ if (!relation || relation.kind !== 'one') return undefined;
125
+ const target = relation.to() as Partial<SchemaView> & { name?: string };
126
+ const mapped = tableNameOf?.get(target as SchemaView);
127
+ if (mapped === undefined && hosted !== undefined) {
128
+ // Three answers, and only the first two are ordinary. Two databases share no
129
+ // constraint, so a target that lives in another source gets a column and no
130
+ // foreign key — the relation survives, the pretence does not. A target no source
131
+ // hosts is a mistake, and staying silent would turn a bad registration into what
132
+ // reads exactly like a source boundary.
133
+ //
134
+ // Decided on the NAME and never on object identity: a target reached through two
135
+ // specifiers (`./Subscription.js` from a sibling entity, `Subscription.ts` from
136
+ // the scan) is TWO class objects for one entity, so the identity map misses on an
137
+ // entity that is right there. Measured on a real app, where this threw on
138
+ // `ref(Subscription)` while the table was in the very batch being built. Everything
139
+ // else that resolves a relation target already resolves it by name, for the same
140
+ // reason — a target rebuilt from a card is a `{ name }` stand-in.
141
+ const key = lowerFirst(target.name ?? '');
142
+ if (hosted.elsewhere.has(key)) return undefined;
143
+ if (!hosted.here.has(key)) {
144
+ throw new Error(
145
+ `ref(${target.name ?? '?'}): no source hosts it — it is in neither this batch nor another one. ` +
146
+ `Check the entity is scanned, and that \`sources\` spells its name the same way.`,
147
+ );
148
+ }
149
+ }
150
+ const table = mapped ?? resolve(lowerFirst(target.name ?? ''));
151
+ const column = primaryColumnOf(target);
152
+ return relation.onDelete ? { table, column, onDelete: relation.onDelete } : { table, column };
153
+ }
154
+
155
+ function toColumn(
156
+ fieldName: string,
157
+ field: Field,
158
+ resolve: (name: string) => string,
159
+ tableNameOf?: Map<SchemaOrCard, string>,
160
+ hosted?: HostedNames,
161
+ stated?: SqlField,
162
+ ): ColumnDef {
163
+ // The column type comes from the `shape` axis alone. `anatomy` strips the
164
+ // nullable union so a nullable integer stays an integer instead of falling
165
+ // through to text.
166
+ const { base, nullable } = Anatomy.of(field.shape);
167
+ const lifecycle = Lifecycle.of(field);
168
+ const column: ColumnDef = {
169
+ field: fieldName,
170
+ name: toSnakeCase(fieldName),
171
+ shape: base as ColumnShape | undefined,
172
+ nullable,
173
+ primary: Role.of(field).isPrimary,
174
+ };
175
+ const bounds = boundsOf(base as Record<string, unknown> | undefined);
176
+ if (bounds) column.bounds = bounds;
177
+ const literal = lifecycle.literal;
178
+ if (literal) column.default = literal.value;
179
+ // A primary key is already unique and already indexed — saying it twice would emit a
180
+ // redundant constraint on every engine. So would indexing what `unique` constrains.
181
+ // Only a constraint of ONE becomes a column constraint; a group of several is a table
182
+ // constraint, emitted once from `uniqueGroups` rather than once per member column.
183
+ const soleUnique = FieldGroup.on(field, Unique).some((group) => group.members.length <= 1);
184
+ if (soleUnique && !column.primary) column.unique = true;
185
+ if (Role.of(field).isIndexed && !column.primary && !column.unique) column.index = true;
186
+ const references = referenceFor(field, resolve, tableNameOf, hosted);
187
+ if (references) column.references = references;
188
+ if (stated) column.stated = stated;
189
+ return column;
190
+ }
191
+
192
+ /** How a `ref()` field's target table+column is resolved — see {@link referenceFor}. */
193
+ export interface RelationResolve {
194
+ /** Same resolver used for every entity's own table (default or a custom `tableName`). */
195
+ resolve: (name: string) => string;
196
+ /** Live entity class → its already-resolved table name, reused instead of re-derived. */
197
+ tableNameOf?: Map<SchemaOrCard, string>;
198
+ /** Which entities this batch holds and which live in another source — decided by NAME. */
199
+ hosted?: HostedNames;
200
+ }
201
+
202
+ /** The two name sets a cross-source batch is read against — see {@link referenceFor}. */
203
+ export interface HostedNames {
204
+ /** Registration names in THIS batch. */
205
+ here: ReadonlySet<string>;
206
+ /** Registration names the app hosts in another source — see {@link AppLike.elsewhere}. */
207
+ elsewhere: ReadonlySet<string>;
208
+ }
209
+
210
+ /**
211
+ * Describe one entity as a table — the single reader of the axes.
212
+ *
213
+ * Takes the entity as a live class or as a card. Read ONCE into `fields`: `fieldsOf`
214
+ * reconstructs a descriptor on each call, so re-reading per loop would rebuild the schema
215
+ * as many times as this function iterates.
216
+ *
217
+ * A lone card has no live relation targets, so a `ref()` falls back to the conventions
218
+ * `referenceFor`/`primaryColumnOf` already document (name-derived table, `id` as the key).
219
+ * Pass a descriptor through `Bundle.toSchemas` first when the FKs matter — it resolves the
220
+ * targets, and its output is the live-class case again.
221
+ */
222
+ export function toTable(tableName: string, entity: SchemaOrCard, relations?: RelationResolve): TableDef {
223
+ const resolve = relations?.resolve ?? toTableName;
224
+ const fields = fieldsOf(entity);
225
+ // Read off the entity, since that is where it is declared and addressed by field key.
226
+ const stated = schemaOf(entity).getAdapters()?.sql;
227
+ const columns: ColumnDef[] = [];
228
+ for (const [fieldName, field] of Object.entries(fields)) {
229
+ if (!isStored(field)) continue;
230
+ columns.push(toColumn(fieldName, field, resolve, relations?.tableNameOf, relations?.hosted, stated?.[fieldName]));
231
+ }
232
+ const primaries = columns.filter((column) => column.primary).map((column) => column.name);
233
+ const stored = new Set(columns.map((column) => column.name));
234
+ // Read off the fields, not off `getUnique()`: a card has no entity-level declaration to
235
+ // offer, and the members carry the same fact either way. One reader for both forms.
236
+ //
237
+ // Declared in field names, realized in column names — and a group that names a field the
238
+ // storage does not keep is not enforceable, so it is dropped here rather than emitted
239
+ // against a column that will not exist.
240
+ const groups = new Map<string, string[]>();
241
+ for (const [fieldName, field] of Object.entries(fields)) {
242
+ for (const group of FieldGroup.on(field, Unique)) {
243
+ const members = group.resolvedOn(fieldName).members.map(toSnakeCase);
244
+ if (members.length > 1 && members.every((column) => stored.has(column))) {
245
+ groups.set(members.join(' '), members);
246
+ }
247
+ }
248
+ }
249
+ const uniqueGroups = [...groups.values()];
250
+
251
+ return {
252
+ name: tableName,
253
+ columns,
254
+ compositePrimary: primaries.length > 1 ? primaries : [],
255
+ uniqueGroups,
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Is this column part of a key? MySQL and SQL Server refuse an unbounded text
261
+ * column in a primary key or an index, so the dialect needs to know.
262
+ *
263
+ * `unique` and `index` count, and until they could be declared nothing did but the
264
+ * primary key — the comment above already said "or an index" while the code answered
265
+ * for the key alone, because no vocabulary word produced one to answer for.
266
+ */
267
+ export function isKeyed(table: TableDef, column: ColumnDef): boolean {
268
+ return column.primary
269
+ || column.unique === true
270
+ || column.index === true
271
+ || table.compositePrimary.includes(column.name);
272
+ }
273
+
274
+ // ─── App-wide entity collection — shared by generateSQL and desiredTables ──
275
+
276
+ /** camelCase → snake_case + plural */
277
+ export function toTableName(name: string): string {
278
+ return name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`) + 's';
279
+ }
280
+
281
+ export interface EntityEntry {
282
+ name: string;
283
+ /** A live class in-process, a card from a frond whose class never crossed. */
284
+ entityClass: SchemaOrCard;
285
+ }
286
+
287
+ export interface FrondLike {
288
+ name: string;
289
+ entities: EntityEntry[];
290
+ }
291
+
292
+ export interface AppLike {
293
+ fronds: FrondLike[];
294
+ /** Auth runtime entities are migrated alongside scanned fronds when present. */
295
+ auth?: { entities: Record<string, SchemaOrCard> };
296
+ /**
297
+ * Entities this app hosts in ANOTHER source — named so a miss can be read.
298
+ *
299
+ * Without it every miss looked alike, so a `ref()` fell back to a derived table name
300
+ * and the constraint was emitted against a table that might not exist. Absent means
301
+ * one source, where a miss can only be a mistake.
302
+ */
303
+ elsewhere?: string[];
304
+ /**
305
+ * The DERIVATIONS this app stores — registration names.
306
+ *
307
+ * A derivation makes no table by default: `Post.pick('id','title')` describes an
308
+ * answer, not a place rows live, and one dropped under `entities/` used to get a
309
+ * table of its own — measured on a real app, where a projection of an archived
310
+ * entity created a duplicate in the OTHER database.
311
+ *
312
+ * Naming it in `sources:` is the opt-in, and it changes what the thing is: a stored
313
+ * derivation is a dated COPY, not a projection, and it owes what any copy owes —
314
+ * who fills it, and how old it is.
315
+ */
316
+ materialize?: string[];
317
+ }
318
+
319
+ /**
320
+ * Does this schema come from another one? `Post` answers no, `Post.pick(…)` answers
321
+ * `Post` — a card carries the same origin for every projection. Recognised by that FORM,
322
+ * never by a brand.
323
+ */
324
+ function isDerivation(source: SchemaOrCard): boolean {
325
+ return schemaOf(source).derivation !== undefined;
326
+ }
327
+
328
+ /**
329
+ * A stored derivation must be able to say HOW OLD it is.
330
+ *
331
+ * It is a copy, and a copy read as if it were live is the silent loss this whole
332
+ * design exists to refuse: rows from yesterday typed exactly like rows from now. The
333
+ * vocabulary already carries the answer — a field with `update: 'now'` records when
334
+ * this row last changed HERE, which for a copy is when it was last pulled. So nothing
335
+ * new is declared; what is new is that forgetting it is refused, at boot, by name.
336
+ *
337
+ * An entity is untouched: it is not a copy of anything, and its rows are the truth.
338
+ */
339
+ function refuseUndated(name: string, source: SchemaOrCard): void {
340
+ const dated = Object.values(fieldsOf(source)).some((field) => Lifecycle.of(field).stampedOnUpdate);
341
+ if (dated) return;
342
+ throw new Error(
343
+ `${name} is stored as a derivation but carries no \`updated()\` field — a copy that ` +
344
+ `cannot say when it was pulled reads exactly like live rows. Add one, or drop it from \`sources\`.`,
345
+ );
346
+ }
347
+
348
+ function collectEntities(app: AppLike): EntityEntry[] {
349
+ const stored = new Set((app.materialize ?? []).map((name) => lowerFirst(name)));
350
+ const entries: EntityEntry[] = [];
351
+ for (const frond of app.fronds) {
352
+ for (const entry of frond.entities) {
353
+ if (isDerivation(entry.entityClass)) {
354
+ if (!stored.has(lowerFirst(entry.name))) continue;
355
+ refuseUndated(entry.name, entry.entityClass);
356
+ }
357
+ entries.push(entry);
358
+ }
359
+ }
360
+ if (app.auth?.entities) {
361
+ for (const [name, entityClass] of Object.entries(app.auth.entities)) entries.push({ name, entityClass });
362
+ }
363
+ return entries;
364
+ }
365
+
366
+ /**
367
+ * Every entity an app hosts, as FK-aware tables — the shared middle step behind
368
+ * `generateSQL` (a from-scratch create pass) and `desiredTables` (the diff's
369
+ * target state). Builds the identity map once (see `referenceFor`'s doc) so a
370
+ * `ref()` target reuses the SAME resolved name as the entity's own table.
371
+ */
372
+ export function toTables(app: AppLike, resolve: (name: string) => string): TableDef[] {
373
+ const entries = collectEntities(app);
374
+ const tableNameOf = new Map<SchemaOrCard, string>(entries.map((entry) => [entry.entityClass, resolve(entry.name)]));
375
+ const hosted = app.elsewhere
376
+ ? { here: new Set(entries.map((entry) => lowerFirst(entry.name))), elsewhere: new Set(app.elsewhere.map(lowerFirst)) }
377
+ : undefined;
378
+ return entries.map((entry) => toTable(resolve(entry.name), entry.entityClass, { resolve, tableNameOf, hosted }));
379
+ }
380
+
381
+ // ─── Ordering — a referenced table before its referrer ─────────────────────
382
+
383
+ export interface FkEdge {
384
+ table: TableDef;
385
+ column: ColumnDef;
386
+ }
387
+
388
+ export interface TableOrder {
389
+ /** Tables in dependency order — a `ref()` target always precedes its referrer. */
390
+ ordered: TableDef[];
391
+ /** FK columns whose target could not be ordered first — a cycle. Constrain after creation. */
392
+ deferred: FkEdge[];
393
+ }
394
+
395
+ /**
396
+ * Order a table set so a `ref()`'s target always exists before the table that
397
+ * points at it — required by every engine except SQLite, which resolves FK
398
+ * targets lazily and accepts any order (and has no `ALTER TABLE ADD CONSTRAINT`
399
+ * to close a cycle with — a caller on that dialect skips this function entirely).
400
+ *
401
+ * A cycle (`Post → Author → Post`, legal in the model — role.ts's relation
402
+ * thunk exists precisely so two entities can reference each other) has no such
403
+ * order: the loop is broken by deferring ONE of its edges per remaining cycle —
404
+ * that FK is added after every table exists, instead of inline. A self-reference
405
+ * (`parentId: ref(() => Category)`) is not a cycle here: a table may always
406
+ * reference its own not-yet-populated rows inline, standard support across
407
+ * every engine — so it's excluded from the dependency graph entirely.
408
+ */
409
+ export function orderTables(tables: TableDef[]): TableOrder {
410
+ const byName = new Map(tables.map((table) => [table.name, table]));
411
+ const needs = new Map(
412
+ tables.map((table) => [
413
+ table.name,
414
+ new Set(
415
+ table.columns
416
+ .filter((c) => c.references && c.references.table !== table.name && byName.has(c.references.table))
417
+ .map((c) => c.references!.table),
418
+ ),
419
+ ]),
420
+ );
421
+
422
+ const ordered: TableDef[] = [];
423
+ const deferred: FkEdge[] = [];
424
+ const done = new Set<string>();
425
+
426
+ while (needs.size > 0) {
427
+ const ready = [...needs.keys()].find((name) => [...needs.get(name)!].every((dep) => done.has(dep)));
428
+ if (ready) {
429
+ ordered.push(byName.get(ready)!);
430
+ done.add(ready);
431
+ needs.delete(ready);
432
+ continue;
433
+ }
434
+ // Every table left waits on another table left — a cycle. Break it by
435
+ // deferring one edge: every column of the first remaining table that points
436
+ // at its first unmet dependency.
437
+ const [name, deps] = [...needs.entries()][0];
438
+ const dep = [...deps].find((d) => !done.has(d))!;
439
+ const table = byName.get(name)!;
440
+ for (const column of table.columns) {
441
+ if (column.references?.table === dep) deferred.push({ table, column });
442
+ }
443
+ deps.delete(dep);
444
+ }
445
+
446
+ return { ordered, deferred };
447
+ }
package/src/values.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The values a driver accepts, and the values an entity declares.
3
+ *
4
+ * A driver binds numbers, strings, buffers and null — nothing else. An entity declares
5
+ * booleans, dates, lists and objects. Something has to sit between the two, and until
6
+ * now nothing did: `done: bool()` threw at insert ("SQLite3 can only bind numbers,
7
+ * strings, bigints, buffers, and null"), a `date()` could only be written as the ISO
8
+ * string its own type forbids, and both came back as whatever the column held.
9
+ *
10
+ * The pair below is derived from the column's shape alone — no new declaration, no axis
11
+ * to read. It lives in the storage adapter because that is where the driver's limits are
12
+ * known; the entity keeps saying `boolean` and `Date`.
13
+ *
14
+ * Drivers differ in how much they already do (Postgres hands back real booleans and
15
+ * Dates, SQLite hands back 0/1 and text), so every read guards on what it actually got
16
+ * instead of assuming.
17
+ */
18
+ import type { ColumnShape } from './table.js';
19
+
20
+ export interface ValueCodec {
21
+ /** Entity value → what the driver can bind. */
22
+ write(value: unknown): unknown;
23
+ /** What the driver returned → the value the entity declares. */
24
+ read(value: unknown): unknown;
25
+ }
26
+
27
+ const identity: ValueCodec = { write: (v) => v, read: (v) => v };
28
+
29
+ const boolean: ValueCodec = {
30
+ write: (v) => (v ? 1 : 0),
31
+ read: (v) => Boolean(v),
32
+ };
33
+
34
+ const dateTime: ValueCodec = {
35
+ // A handler may hand over a Date (what the field declares) or an ISO string (what the
36
+ // pre-fix workarounds passed) — both must keep working.
37
+ write: (v) => (v instanceof Date ? v.toISOString() : v),
38
+ read: (v) => (typeof v === 'string' ? new Date(v) : v),
39
+ };
40
+
41
+ const json: ValueCodec = {
42
+ write: (v) => (typeof v === 'string' ? v : JSON.stringify(v)),
43
+ // Already parsed by the driver (Postgres jsonb) → leave it. Text → parse. A column
44
+ // holding invalid JSON is a corrupt row, not a value to guess at: let it throw.
45
+ read: (v) => (typeof v === 'string' ? JSON.parse(v) : v),
46
+ };
47
+
48
+ /**
49
+ * A driver may answer a number as a BigInt — Postgres does it for `count(*)` and for
50
+ * `bigint` columns, DuckDB for every count. The entity declares a number, so that is
51
+ * what comes back.
52
+ *
53
+ * Out of range it REFUSES rather than rounding. `Number(9007199254740993n)` is
54
+ * `9007199254740992` — a wrong answer, silently, and the row would look fine. A value
55
+ * that large is a real identifier somewhere, and its field should say `text()`.
56
+ */
57
+ const numeric: ValueCodec = {
58
+ write: (v) => (typeof v === 'bigint' ? fits(v) : v),
59
+ read: (v) => (typeof v === 'bigint' ? fits(v) : v),
60
+ };
61
+
62
+ function fits(value: bigint): number {
63
+ if (value >= MIN_SAFE && value <= MAX_SAFE) return Number(value);
64
+ throw new Error(
65
+ `${value} does not fit a JavaScript number — declare the field as \`text()\` to keep it whole.`,
66
+ );
67
+ }
68
+
69
+ const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
70
+ const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
71
+
72
+ /** Absent stays absent, null stays null — a codec never invents a value. */
73
+ function nullSafe(codec: ValueCodec): ValueCodec {
74
+ const pass = (fn: (v: unknown) => unknown) => (v: unknown) =>
75
+ v === null || v === undefined ? v : fn(v);
76
+ return { write: pass(codec.write), read: pass(codec.read) };
77
+ }
78
+
79
+ /** The pair a column's shape calls for — identity when the driver already accepts it. */
80
+ export function codecFor(shape?: ColumnShape): ValueCodec {
81
+ switch (shape?.type) {
82
+ case 'boolean':
83
+ return nullSafe(boolean);
84
+ case 'integer':
85
+ case 'number':
86
+ return nullSafe(numeric);
87
+ case 'string':
88
+ return shape.format === 'date-time' ? nullSafe(dateTime) : identity;
89
+ case 'array':
90
+ case 'object':
91
+ return nullSafe(json);
92
+ default:
93
+ return identity;
94
+ }
95
+ }
96
+
97
+ /** Field name → codec, for every column that needs one. Identity columns are omitted. */
98
+ export function codecsOf(columns: { field: string; shape?: ColumnShape }[]): Map<string, ValueCodec> {
99
+ const codecs = new Map<string, ValueCodec>();
100
+ for (const column of columns) {
101
+ const codec = codecFor(column.shape);
102
+ if (codec !== identity) codecs.set(column.field, codec);
103
+ }
104
+ return codecs;
105
+ }