@atscript/db 0.1.136 → 0.1.137

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.
@@ -1,558 +0,0 @@
1
- import { Ct as TWriteOptions, Ft as AtscriptDbReadable, L as TDbDeleteResult, Pt as BaseDbAdapter, Rt as DbEncryption, S as NullableOptional, T as TCascadeResolver, U as TDbInsertManyResult, Ut as TGenericLogger, W as TDbInsertResult, Z as TDbUpdateResult, _ as DbRow, bt as TTableResolver, h as DbPatch, ht as TReferencingForeignKey, kt as TableMetadata, st as TFkLookupResolver, tt as TDeleteOptions, ut as TIdResolveOptions, wt as TWriteTableResolver, xt as TTouchManyOptions, zt as TDbEncryptionOptions } from "./buckets-y4EzoX7D.mjs";
2
- import { AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryFieldRef as AtscriptQueryFieldRef$1, AtscriptQueryNode, AtscriptQueryNode as AtscriptQueryNode$1, AtscriptRef, FlatOf, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAtscriptAnnotatedType, TAtscriptDataType, Validator } from "@atscript/typescript/utils";
3
- import { FilterExpr } from "@uniqu/core";
4
-
5
- //#region src/strategies/integrity.d.ts
6
- /**
7
- * Strategy for referential integrity enforcement.
8
- * Two implementations: {@link NativeIntegrity} (DB handles FK constraints)
9
- * and `ApplicationIntegrity` (generic layer validates + cascades).
10
- */
11
- declare abstract class IntegrityStrategy {
12
- abstract validateForeignKeys(items: Array<Record<string, unknown>>, meta: TableMetadata, fkLookupResolver: TFkLookupResolver | undefined, writeTableResolver: TWriteTableResolver | undefined, partial?: boolean, excludeTargetTable?: string): Promise<void>;
13
- abstract cascadeBeforeDelete(filter: FilterExpr, tableName: string, meta: TableMetadata, cascadeResolver: TCascadeResolver, translateFilter: (f: FilterExpr) => FilterExpr, adapter: BaseDbAdapter): Promise<void>;
14
- abstract needsCascade(cascadeResolver: TCascadeResolver | undefined): boolean;
15
- }
16
- /**
17
- * Integrity strategy for adapters with native FK support (e.g. SQLite, MySQL).
18
- * All operations are no-ops — the database engine enforces constraints.
19
- */
20
- declare class NativeIntegrity extends IntegrityStrategy {
21
- validateForeignKeys(): Promise<void>;
22
- cascadeBeforeDelete(): Promise<void>;
23
- needsCascade(): boolean;
24
- }
25
- //#endregion
26
- //#region src/table/db-table.d.ts
27
- declare class AtscriptDbTable<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType, DataType = TAtscriptDataType<T>, FlatType = NullableOptional<FlatOf<T>>, A extends BaseDbAdapter = BaseDbAdapter, IdType = PrimaryKeyOf<T>, OwnProps = NullableOptional<OwnPropsOf<T>>, NavType extends Record<string, unknown> = NavPropsOf<T>> extends AtscriptDbReadable<T, DataType, FlatType, A, IdType, OwnProps, NavType> {
28
- protected _cascadeResolver?: TCascadeResolver;
29
- protected _fkLookupResolver?: TFkLookupResolver;
30
- protected readonly _integrity: IntegrityStrategy;
31
- protected readonly validators: Map<string, Validator<T, DataType>>;
32
- private _fromDepthMap?;
33
- constructor(_type: T, adapter: A, logger?: TGenericLogger, _tableResolver?: TTableResolver, _writeTableResolver?: TWriteTableResolver);
34
- /**
35
- * Sets the cascade resolver for application-level cascade deletes.
36
- * Called by DbSpace after table creation.
37
- */
38
- setCascadeResolver(resolver: TCascadeResolver): void;
39
- /**
40
- * Sets the FK lookup resolver for application-level FK validation.
41
- * Called by DbSpace after table creation.
42
- */
43
- setFkLookupResolver(resolver: TFkLookupResolver): void;
44
- /**
45
- * Returns a cached validator for the given purpose.
46
- * Built with adapter plugins from {@link BaseDbAdapter.getValidatorPlugins}.
47
- *
48
- * Standard purposes: `'insert'`, `'update'`, `'patch'`.
49
- * Adapters may define additional purposes.
50
- */
51
- getValidator(purpose: string): Validator<T, DataType>;
52
- /**
53
- * Inserts a single record. Delegates to {@link insertMany} for unified
54
- * nested creation support.
55
- */
56
- insertOne(payload: DbPatch<DataType>, opts?: TWriteOptions<DataType>): Promise<TDbInsertResult>;
57
- /**
58
- * Inserts multiple records with batch-optimized nested creation.
59
- *
60
- * Supports **nested creation**: if payloads include data for navigation
61
- * fields (`@db.rel.to` / `@db.rel.from`), related records are created
62
- * automatically in batches. TO dependencies are batch-created first
63
- * (their PKs become our FKs), FROM dependents are batch-created after
64
- * (they receive our PKs as their FKs). Fully recursive — nested records
65
- * with their own nav data trigger further batch inserts at each level.
66
- * Recursive up to `maxDepth` (default 3).
67
- *
68
- * `opts.guard` (since 0.1.128) runs once inside the transaction, after
69
- * defaults + validation, with the prepared rows — see {@link TWriteOptions}.
70
- */
71
- insertMany(payloads: Array<DbPatch<DataType>>, opts?: TWriteOptions<DataType>): Promise<TDbInsertManyResult>;
72
- /**
73
- * Replaces a single record identified by primary key(s).
74
- * Delegates to {@link bulkReplace} for unified nested relation support.
75
- */
76
- replaceOne(payload: DbRow<DataType>, opts?: TWriteOptions<DataType>): Promise<TDbUpdateResult>;
77
- /**
78
- * Replaces multiple records with deep nested relation support.
79
- *
80
- * Supports all relation types (TO, FROM, VIA). TO dependencies are
81
- * replaced first (their PKs become our FKs), FROM dependents are replaced
82
- * after (they receive our PKs as their FKs), VIA relations clear and
83
- * re-create junction rows. Fully recursive up to `maxDepth` (default 3).
84
- *
85
- * `opts.guard` (since 0.1.128) runs once inside the transaction, after
86
- * `$cas` extraction, defaults + validation — see {@link TWriteOptions}.
87
- */
88
- bulkReplace(payloads: Array<DbRow<DataType>>, opts?: TWriteOptions<DataType>): Promise<TDbUpdateResult>;
89
- /**
90
- * Partially updates a single record identified by primary key(s).
91
- * Delegates to {@link bulkUpdate} for unified nested relation support.
92
- */
93
- updateOne(payload: DbPatch<DataType>, opts?: TWriteOptions<DataType>): Promise<TDbUpdateResult>;
94
- /**
95
- * Partially updates multiple records with deep nested relation support.
96
- *
97
- * Only TO relations (1:1, N:1) are supported for patching. FROM/VIA
98
- * relations will error — use {@link bulkReplace} for those.
99
- * Recursive up to `maxDepth` (default 3).
100
- *
101
- * `opts.guard` (since 0.1.128) runs once inside the transaction, after
102
- * `$cas` extraction and validation, with the patches (identifying fields
103
- * present, `$cas` removed) — see {@link TWriteOptions}.
104
- */
105
- bulkUpdate(payloads: Array<DbPatch<DataType>>, opts?: TWriteOptions<DataType>): Promise<TDbUpdateResult>;
106
- /**
107
- * Batch versioned touch (since 0.1.129): bumps the version of every listed
108
- * row by exactly one, each row guarded by its own expected version. This is
109
- * the batch fence `updateMany(orFilter, {})` used to be before 0.1.128 (an
110
- * empty patch is a no-op since then and takes no lock).
111
- *
112
- * Each key carries the primary key field(s) (composite supported) plus the
113
- * version column and NOTHING else — a touch has no payload. Unique indexes
114
- * do not identify a touch key. `undefined`-valued properties are ignored,
115
- * like in every write payload. Empty `keys` → `{ 0, 0 }` without a statement.
116
- *
117
- * `require: 'all'` (default): one count over the whole key set runs FIRST;
118
- * a stale or missing row throws {@link CasMismatchError} before any write.
119
- * The bumps then run as `updateMany(orFilter, {})` chunks of at most
120
- * {@link TOUCH_MANY_CHUNK} keys inside one adapter transaction; a summed
121
- * `matchedCount` short of `keys.length` (a row moved between the count and
122
- * the bump) throws the same error — SQL engines roll every bump back. The
123
- * pre-count is therefore a deliberate double check on SQL: it is what makes
124
- * the guarantee hold on adapters whose `withTransaction` is a passthrough
125
- * (the memory adapter, a Mongo standalone topology) — there it covers the
126
- * common stale case and the residual race window is accepted.
127
- * `require: 'any'`: no pre-count, the honest summed result is returned.
128
- *
129
- * No `guard`, no `onWrite`; not exposed over HTTP.
130
- */
131
- touchMany(keys: Array<DbPatch<DataType>>, opts?: TTouchManyOptions): Promise<TDbUpdateResult>;
132
- /**
133
- * Deletes a single record by any type-compatible identifier — primary key
134
- * or single-field unique index. Uses the same resolution logic as `findById`.
135
- *
136
- * When the adapter does not support native foreign keys (e.g. MongoDB),
137
- * cascade and setNull actions are applied before the delete.
138
- *
139
- * `opts.guard` (since 0.1.128) runs inside the transaction once the id has
140
- * resolved to a filter, before cascade / delete — see {@link TDeleteOptions}.
141
- * An id that resolves to no filter answers `{ deletedCount: 0 }` without
142
- * calling the guard.
143
- */
144
- deleteOne(id: IdType, opts?: TDeleteOptions<DataType>): Promise<TDbDeleteResult>;
145
- updateMany(filter: FilterExpr<FlatType>, data: DbPatch<DataType>): Promise<TDbUpdateResult>;
146
- replaceMany(filter: FilterExpr<FlatType>, data: DbRow<DataType>): Promise<TDbUpdateResult>;
147
- deleteMany(filter: FilterExpr<FlatType>): Promise<TDbDeleteResult>;
148
- /**
149
- * Synchronizes indexes between Atscript definitions and the database.
150
- */
151
- syncIndexes(): Promise<void>;
152
- /**
153
- * Ensures the table/collection exists in the database.
154
- */
155
- ensureTable(): Promise<void>;
156
- /** Engine-agnostic guard for user-supplied mutation filters (updateMany/deleteMany/…). */
157
- protected _guardMutationFilter(filter: FilterExpr): void;
158
- /**
159
- * Encrypts `@db.encrypted` field values in place on (already validated)
160
- * write payloads — between validation and `prepareForWrite`, so adapters
161
- * only ever see envelope strings.
162
- *
163
- * Parent objects along an encrypted path are shallow-cloned before
164
- * mutation so caller-shared nested objects are never modified.
165
- *
166
- * In `patch` mode, operator objects (`$inc`, `$insert`, …) targeting an
167
- * encrypted field are rejected with `ENC_FIELD_PATCH_OP` — ciphertext is
168
- * opaque; only plain re-assignment (which re-encrypts) is allowed.
169
- */
170
- protected _encryptItems(items: Array<Record<string, unknown>>, mode: "write" | "patch"): Promise<void>;
171
- /**
172
- * Lazy pre-image read for a guard's `current(i)`: `null` when the row has
173
- * no identifying key (e.g. an auto-increment insert) or the key cannot be
174
- * resolved — never throws for a missing key.
175
- * @internal
176
- */
177
- _readPreImage(row: unknown): Promise<DataType | null>;
178
- /**
179
- * Applies `@db.default` values in place to a row's absent fields — the
180
- * defaults pass every insert / replace path runs before validation.
181
- * Static value defaults (`@db.default 'x'`) are filled on EVERY adapter
182
- * (since 0.1.128 — writing the column's own default explicitly is
183
- * equivalent to leaving it to the DDL `DEFAULT`, and write guards see the
184
- * full row). Function defaults (`now` / `uuid` / `increment` / custom) the
185
- * adapter handles natively are NOT filled — the field stays absent so the
186
- * engine's own default applies. The version column is never touched.
187
- */
188
- protected _applyDefaults(data: Record<string, unknown>): Record<string, unknown>;
189
- /**
190
- * The JS value for a `@db.default 'literal'`: strings (including unions of
191
- * string literals) are used as-is, every other design type is parsed as
192
- * JSON — the same value the SQL adapters put into the DDL `DEFAULT` clause.
193
- * A literal that is not valid JSON falls back to the raw string so the
194
- * validator reports it against the field instead of a bare `SyntaxError`.
195
- */
196
- private _parseValueDefault;
197
- /**
198
- * Extracts a record-identifying filter from a payload.
199
- *
200
- * Resolution order:
201
- * 1. Primary key field(s) — if all PK fields are present in the payload.
202
- * 2. Single-field unique index — first `@db.index.unique` field found.
203
- * 3. Compound unique index — first compound unique index whose fields are all present.
204
- *
205
- * Throws when no identifying fields can be found. With `isFieldVisible`
206
- * (since 0.1.134), a unique index over a hidden field is skipped, as if it
207
- * did not exist — see {@link identificationsVisibleTo}.
208
- */
209
- protected _extractRecordFilter(payload: Record<string, unknown>, opts?: TIdResolveOptions): FilterExpr;
210
- private _prepareFilterValue;
211
- /**
212
- * Lazy — builds a `normalized-path → from-depth` map from `this._meta.flatMap`
213
- * on first use. Only paths reachable through an unbroken chain of `db.rel.from`
214
- * nav fields from the root are included (chains crossing `to`/`via` are excluded).
215
- */
216
- private _getFromDepthMap;
217
- /**
218
- * Populate the depth-limit bundle on a `DbValidationContext`. Only the root
219
- * write call (`depth === 0`) enforces — nested re-entries leave `depthCheck`
220
- * unset so the full tree is validated once at the root.
221
- */
222
- private _applyDepthCtx;
223
- /**
224
- * Pre-validate items (type validation + FK constraints) without inserting them.
225
- * Used by parent tables to validate FROM children before the main insert,
226
- * ensuring errors are caught before the parent is committed.
227
- *
228
- * @param opts.excludeFkTargetTable - Skip FK validation to this table (the parent).
229
- */
230
- preValidateItems(items: Array<Record<string, unknown>>, opts?: {
231
- excludeFkTargetTable?: string;
232
- }): Promise<void>;
233
- /**
234
- * Builds a validator for a given purpose with adapter plugins.
235
- *
236
- * Uses annotation-based `replace` callback to make `@meta.id` and
237
- * `@db.default` fields optional — works at all nesting levels
238
- * (including inside nav field target types).
239
- */
240
- protected _buildValidator(purpose: string): Validator<T, DataType>;
241
- }
242
- //#endregion
243
- //#region src/query/query-tree.d.ts
244
- /**
245
- * `true` when a query-tree operand is a field reference (`{ field, type? }`)
246
- * rather than a literal — e.g. the right side of a field-to-field comparison.
247
- * @since 0.1.136
248
- */
249
- declare function isFieldRef(value: unknown): value is AtscriptQueryFieldRef;
250
- /** A single join in a view query plan. */
251
- interface TViewJoin {
252
- targetType: () => TAtscriptAnnotatedType;
253
- targetTable: string;
254
- condition: AtscriptQueryNode;
255
- /**
256
- * `inner` (default) drops entry rows without a match; `left` keeps them
257
- * with the target's columns as NULL. Joins apply in declaration order.
258
- * @since 0.1.136
259
- */
260
- kind: "inner" | "left";
261
- }
262
- /** Resolved view query plan produced by AtscriptDbView. */
263
- interface TViewPlan {
264
- entryType: () => TAtscriptAnnotatedType;
265
- entryTable: string;
266
- joins: TViewJoin[];
267
- filter?: AtscriptQueryNode;
268
- having?: AtscriptQueryNode;
269
- materialized: boolean;
270
- }
271
- /**
272
- * Translates a JS-emitted query tree into a FilterExpr.
273
- * Resolves field references (type + field path) to physical column names
274
- * via the provided resolver function.
275
- */
276
- declare function translateQueryTree(node: AtscriptQueryNode, resolveField: (ref: AtscriptQueryFieldRef) => string): FilterExpr;
277
- //#endregion
278
- //#region src/table/view-source.d.ts
279
- /**
280
- * Where a view reads one logical source path from, in PHYSICAL terms.
281
- *
282
- * Produced by {@link resolveViewSource} — a pure function of the source
283
- * table's annotated type that lays the table out with `TableMetadata`'s
284
- * rules (flattened `__` columns, `@db.column` renames, `@db.json` / array
285
- * JSON columns, document paths on nested-object adapters).
286
- * @since 0.1.136
287
- */
288
- interface TViewSource {
289
- /**
290
- * Physical column (relational) or document path (nested-object adapters).
291
- * For a path inside a JSON column this is the JSON column; for a flattened
292
- * object it is the object's `__` prefix (no such column exists — its leaves do).
293
- */
294
- column: string;
295
- /** Segments inside {@link column} when the path descends into a JSON column (relational only). */
296
- jsonPath?: string[];
297
- /** Design type of the addressed node (`string`, `number`, `object`, `array`, …; `unknown` when undeclared). */
298
- designType: string;
299
- /** Set for a relational object stored as one column per leaf. */
300
- flattened?: true;
301
- /**
302
- * `true` when the value may be absent: the path or an ancestor segment is
303
- * optional, or it reads inside a JSON-stored value.
304
- */
305
- optional: boolean;
306
- }
307
- //#endregion
308
- //#region src/table/db-view.d.ts
309
- /** Primitive result type of a JSON-leaf extraction. */
310
- type TViewJsonType = "string" | "number" | "boolean";
311
- interface TViewColumnMapping {
312
- /**
313
- * The view's own physical column — its `@db.column` / flattened `__` name
314
- * on relational adapters, its document key on nested-object adapters.
315
- */
316
- viewColumn: string;
317
- /**
318
- * Logical view field path (`address.city` for a flattened object leaf) —
319
- * how `@db.view.having` refers to the column.
320
- * @since 0.1.136
321
- */
322
- viewPath: string;
323
- sourceTable: string;
324
- /** Physical source column (or document path). `"*"` for `COUNT(*)`. */
325
- sourceColumn: string;
326
- /**
327
- * Set when the source value may be missing for some row: an optional
328
- * source field, a leaf inside a JSON-stored value, an undeclared path, or a
329
- * column of a left-joined table. Document adapters coalesce such a source
330
- * to `null`; a required source is read as a plain path (index-friendly).
331
- * @since 0.1.136
332
- */
333
- nullable?: true;
334
- /**
335
- * Set when the source is a primitive leaf inside a JSON column
336
- * ({@link sourceColumn}): the path within it and the leaf's declared type.
337
- * @since 0.1.136
338
- */
339
- json?: {
340
- path: string[];
341
- type: TViewJsonType;
342
- };
343
- /**
344
- * Aggregate function name (`sum` | `avg` | `count` | `countDistinct` |
345
- * `min` | `max`) if this is an aggregate column.
346
- */
347
- aggFn?: string;
348
- /** Source field for the aggregate function ('*' for COUNT(*)). */
349
- aggField?: string;
350
- /**
351
- * Row predicate of a conditional aggregate — the `@db.agg.*` 2nd argument:
352
- * only rows where it holds are aggregated. Refs resolve like
353
- * `@db.view.filter` (entry table + joins). @since 0.1.136
354
- */
355
- aggFilter?: AtscriptQueryNode;
356
- }
357
- /**
358
- * Database view abstraction driven by Atscript `@db.view.*` annotations.
359
- *
360
- * Extends {@link AtscriptDbReadable} with view plan resolution — entry table,
361
- * joins, filter, and materialization flag. Read operations are inherited;
362
- * write operations are not available on views.
363
- *
364
- * ```typescript
365
- * const adapter = new SqliteAdapter(db)
366
- * const activeUsers = new AtscriptDbView(ActiveUsersType, adapter)
367
- * const users = await activeUsers.findMany({ filter: {}, controls: {} })
368
- * ```
369
- */
370
- declare class AtscriptDbView<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType, DataType = TAtscriptDataType<T>, FlatType = NullableOptional<FlatOf<T>>, A extends BaseDbAdapter = BaseDbAdapter, IdType = PrimaryKeyOf<T>, OwnProps = NullableOptional<OwnPropsOf<T>>, NavType extends Record<string, unknown> = NavPropsOf<T>> extends AtscriptDbReadable<T, DataType, FlatType, A, IdType, OwnProps, NavType> {
371
- private _viewPlan?;
372
- private _columnMappings?;
373
- get isView(): boolean;
374
- /**
375
- * Whether this is an external view — declared with `@db.view` only,
376
- * without `@db.view.for`. External views reference pre-existing DB views
377
- * and are not managed (created/dropped) by schema sync.
378
- */
379
- get isExternal(): boolean;
380
- /**
381
- * Lazily resolves the view plan from `@db.view.*` metadata.
382
- *
383
- * - `db.view.for` → entry type ref (required)
384
- * - `db.view.joins` → array of `{ target, condition }` (optional, multiple)
385
- * - `db.view.filter` → query tree (optional)
386
- * - `db.view.materialized` → boolean (optional)
387
- */
388
- get viewPlan(): TViewPlan;
389
- /** Whether the adapter stores nested objects natively (document paths, no JSON columns). */
390
- private get _nested();
391
- /**
392
- * Resolves a view query field ref (join condition, `@db.view.filter`,
393
- * conditional-aggregate predicate) to its table name and PHYSICAL source on
394
- * this view's adapter — the column (or document path) with `TableMetadata`'s
395
- * layout rules, the path inside a JSON column, and whether the value may be
396
- * absent. An unqualified ref resolves against the entry table.
397
- * @throws for a ref without storage (`@db.ignore`, navigation relation) or
398
- * inside an `@db.encrypted` field (relational adapters).
399
- * @since 0.1.136
400
- */
401
- resolveRefSource(ref: AtscriptQueryFieldRef): {
402
- table: string;
403
- source: TViewSource;
404
- };
405
- /**
406
- * Resolves a query field ref (join condition, `@db.view.filter`) to a
407
- * quoted `table.column` SQL fragment — the PHYSICAL column (flattened
408
- * `__` name, `@db.column` rename). An unqualified ref
409
- * resolves against the entry table.
410
- *
411
- * @param ref - The field reference from the query tree.
412
- * @param qi - Identifier quoting function (e.g. backtick for MySQL, double-quote for SQLite).
413
- * Defaults to double-quote wrapping for backwards compatibility.
414
- * @throws when the ref reads inside a JSON column (not supported in view conditions).
415
- */
416
- resolveFieldRef(ref: AtscriptQueryFieldRef, qi?: (name: string) => string): string;
417
- /**
418
- * Maps each view column to its source table and PHYSICAL source column.
419
- *
420
- * View fields resolve through their chain ref; fields without a ref read
421
- * the entry table under the same name; aggregates read their `@db.agg.*`
422
- * field from the entry table (or their ref). Source names are
423
- * physical (flattened `__` names, `@db.column`, document paths), `viewColumn`
424
- * is the view's own physical name, an object field whose source is a
425
- * flattened object expands to one mapping per leaf, and a primitive leaf
426
- * inside a JSON column carries `json` (rendered by adapters that support
427
- * JSON extraction).
428
- *
429
- * Computed once per view (the plan and the type are immutable).
430
- *
431
- * @throws for an object field over a JSON column without `@db.json` on the
432
- * view field, a JSON leaf that is not a string / number / boolean, or an
433
- * aggregate other than `count` over `'*'`.
434
- */
435
- getViewColumnMappings(): TViewColumnMapping[];
436
- private _buildColumnMappings;
437
- /** One view column over one physical source (a column or a JSON leaf). */
438
- private _leafMapping;
439
- }
440
- /**
441
- * Structural type guard for views: `true` when the readable reports
442
- * `isView`, whether or not it is an `AtscriptDbView` instance of THIS copy
443
- * of `@atscript/db`. Adapters must use this (or `readable.isView`) instead of
444
- * `instanceof AtscriptDbView` — in a bundle that carries two copies of the
445
- * core (app bundle + external adapter), `instanceof` is false and the adapter
446
- * would create an empty physical table under the view's name.
447
- * @since 0.1.128
448
- */
449
- declare function isAtscriptDbView(readable: AtscriptDbReadable<any, any, any, any, any, any, any>): readable is AtscriptDbView<any, any, any, any, any, any, any>;
450
- //#endregion
451
- //#region src/table/db-space.d.ts
452
- /**
453
- * Adapter factory function. Called once per table/view to create a fresh adapter instance.
454
- * Each readable gets its own adapter (1:1 relationship required by BaseDbAdapter).
455
- */
456
- type TAdapterFactory = () => BaseDbAdapter;
457
- /** Options bag for {@link DbSpace} (second constructor argument). */
458
- interface TDbSpaceOptions {
459
- /** Logger shared by all tables/views in the space. */
460
- logger?: TGenericLogger;
461
- /** Field-level encryption configuration for `@db.encrypted` fields. */
462
- encryption?: TDbEncryptionOptions;
463
- }
464
- /**
465
- * A database space — a registry of tables and views sharing the same adapter type and driver.
466
- *
467
- * `DbSpace` solves the cross-table discovery problem: when table A has a relation
468
- * to table B, it needs to find and query table B. The space acts as the registry
469
- * that makes this possible via the table resolver callback.
470
- *
471
- * Each table/view gets its own adapter instance (created by the factory), but all
472
- * share the same space and can discover each other for `$with` relation loading.
473
- *
474
- * ```typescript
475
- * // SQLite
476
- * const driver = new BetterSqlite3Driver(':memory:')
477
- * const db = new DbSpace(() => new SqliteAdapter(driver))
478
- * const users = db.getTable(UsersType)
479
- * const activeUsers = db.getView(ActiveUsersType)
480
- * ```
481
- */
482
- declare class DbSpace {
483
- protected readonly adapterFactory: TAdapterFactory;
484
- private _readables;
485
- /** All tables created in this space — used for reverse FK lookup during cascade. */
486
- private _allTables;
487
- /** Lazily created adapter for administrative ops (drop table/view) that don't need a registered readable. */
488
- private _adminAdapter?;
489
- protected readonly logger: TGenericLogger;
490
- /** Encryption service for `@db.encrypted` fields — validated eagerly at construction. */
491
- protected readonly _encryption?: DbEncryption;
492
- /**
493
- * @param adapterFactory - Creates a fresh adapter per table/view.
494
- * @param loggerOrOptions - Either a logger (legacy signature) or a
495
- * {@link TDbSpaceOptions} bag carrying `logger` and/or `encryption`.
496
- */
497
- constructor(adapterFactory: TAdapterFactory, loggerOrOptions?: TGenericLogger | TDbSpaceOptions);
498
- /**
499
- * Auto-detects whether the type is a table or view and returns the
500
- * appropriate instance. Uses `@db.view` or `@db.view.for` presence to distinguish.
501
- */
502
- get<T extends TAtscriptAnnotatedType>(type: T, logger?: TGenericLogger): AtscriptDbReadable<T>;
503
- /**
504
- * Returns the table for the given annotated type.
505
- * Creates the table + adapter on first access, caches for subsequent calls.
506
- */
507
- getTable<T extends TAtscriptAnnotatedType>(type: T, logger?: TGenericLogger): AtscriptDbTable<T>;
508
- /**
509
- * Returns the view for the given annotated type.
510
- * Creates the view + adapter on first access, caches for subsequent calls.
511
- */
512
- getView<T extends TAtscriptAnnotatedType>(type: T, logger?: TGenericLogger): AtscriptDbView<T>;
513
- /**
514
- * Returns the adapter for the given annotated type.
515
- * Creates the table/view + adapter on first access if needed.
516
- */
517
- getAdapter(type: TAtscriptAnnotatedType): BaseDbAdapter;
518
- /**
519
- * Drops a table by name. Used by schema sync to remove tables no longer in the schema.
520
- */
521
- dropTableByName(tableName: string): Promise<void>;
522
- /**
523
- * Drops a view by name. Used by schema sync to remove views no longer in the schema.
524
- */
525
- dropViewByName(viewName: string): Promise<void>;
526
- /**
527
- * Drops a group of mutually referencing tables as one operation.
528
- * Used by schema sync to remove a foreign-key cycle no longer in the schema.
529
- * @since 0.1.128
530
- */
531
- dropTablesByName(tableNames: string[]): Promise<void>;
532
- /**
533
- * Live foreign keys referencing `tableName`, or `undefined` when the
534
- * adapter cannot introspect them. Used by schema sync for drop ordering
535
- * and surviving-reference checks of tables without a registered readable.
536
- * @since 0.1.128
537
- */
538
- getReferencingForeignKeys(tableName: string): Promise<TReferencingForeignKey[] | undefined>;
539
- /**
540
- * A factory-fresh adapter with NO registered readable. Only the name-taking
541
- * primitives may run on it (`dropTableByName`, `dropViewByName`,
542
- * `dropTablesByName`, `getReferencingForeignKeys`) — adapters derive the
543
- * schema for those from the driver/connection, not from a bound table.
544
- */
545
- private _getAdminAdapter;
546
- /**
547
- * Finds all child tables with FKs pointing to the given parent table name.
548
- * Accesses `table.foreignKeys` which triggers `_flatten()` if needed.
549
- */
550
- private _getCascadeTargets;
551
- /**
552
- * Resolves a table name to a queryable target for FK validation.
553
- * Searches all registered tables for one with the matching table name.
554
- */
555
- private _getFkLookupTarget;
556
- }
557
- //#endregion
558
- export { IntegrityStrategy as _, TViewColumnMapping as a, AtscriptQueryComparison as c, AtscriptRef as d, TViewJoin as f, AtscriptDbTable as g, translateQueryTree as h, AtscriptDbView as i, AtscriptQueryFieldRef$1 as l, isFieldRef as m, TAdapterFactory as n, TViewJsonType as o, TViewPlan as p, TDbSpaceOptions as r, isAtscriptDbView as s, DbSpace as t, AtscriptQueryNode$1 as u, NativeIntegrity as v };