@voltro/database 0.11.0 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -82,6 +82,9 @@ export declare interface AnnClause {
82
82
 
83
83
  export declare type AnyMixin = MixinDefinition<Record<string, ColumnDefinition<unknown>>>;
84
84
 
85
+ /** Any table — the loose shape these helpers accept structurally. */
86
+ declare type AnyTable = Table<string, Record<string, ColumnDefinition<unknown>>, boolean, string>;
87
+
85
88
  /**
86
89
  * Array column — wraps another column constructor to declare an
87
90
  * array of that element type. Postgres-native (`text[]`, `integer[]`,
@@ -173,6 +176,18 @@ export declare const auditAllTableIndexes: (tables: ReadonlyArray<Table<string,
173
176
  */
174
177
  export declare const auditTableIndexes: (table: Table<string, Record<string, ColumnDefinition<unknown>>, boolean, string>) => ReadonlyArray<IndexAuditIssue>;
175
178
 
179
+ /** Columns the framework fills on write (auto-id floor + tenant/audit mixins),
180
+ * so an insert need not supply them. Name-based on purpose: a hand-declared
181
+ * `createdAt` with no default reads as optional here (the lenient direction —
182
+ * never rejects valid code), while the mixin-managed ones are always filled.
183
+ * Runtime tuple + the type derived from it, so a consumer that must skip these
184
+ * at runtime (e.g. `@voltro/testing`'s `fixtureRow`, which fills only
185
+ * caller-owned required columns) reads the SAME list the insert-row type uses —
186
+ * no second copy to drift. */
187
+ export declare const AUTO_FILLED_COLUMNS: readonly ["id", "tenantId", "createdAt", "updatedAt", "createdBy", "updatedBy", "deletedAt", "deletedBy"];
188
+
189
+ declare type AutoFilledColumn = (typeof AUTO_FILLED_COLUMNS)[number];
190
+
176
191
  export declare const avg: (column: string, alias?: string) => AggregateColumn;
177
192
 
178
193
  export declare const avgOver: (column: string, alias?: string) => WindowBuilder;
@@ -223,7 +238,7 @@ export declare interface BackfillSpec<TsType = unknown> {
223
238
  * bytesStored: bigint().default('0'),
224
239
  * ```
225
240
  */
226
- export declare const bigint: () => ColumnBuilder<string, "bigint">;
241
+ export declare const bigint: () => ColumnBuilder<string, "bigint", boolean>;
227
242
 
228
243
  /**
229
244
  * Bind the request to the store for the subject's home region. `stores` is the
@@ -238,7 +253,7 @@ export declare const bindResidentStore: <S>(subject: ResidencySubject, config: R
238
253
  readonly placement: ResidentPlacement;
239
254
  };
240
255
 
241
- export declare const boolean: () => ColumnBuilder<boolean, "boolean">;
256
+ export declare const boolean: () => ColumnBuilder<boolean, "boolean", boolean>;
242
257
 
243
258
  export declare type BranchEvent = 'provision' | 'provisioned' | 'fail' | 'destroy' | 'destroyed';
244
259
 
@@ -387,7 +402,7 @@ export declare class BranchTransitionInvalid extends Error {
387
402
  * (mysql/mariadb) / `VARBINARY(MAX)` (mssql). Values round-trip as
388
403
  * `Uint8Array`. Use for storing bytes IN the database (e.g. the
389
404
  * `database` storage provider); keep large blobs in object storage. */
390
- export declare const bytes: () => ColumnBuilder<Uint8Array<ArrayBufferLike>, "bytes">;
405
+ export declare const bytes: () => ColumnBuilder<Uint8Array<ArrayBufferLike>, "bytes", boolean>;
391
406
 
392
407
  export declare type CaughtUpVerdict = 'caught-up' | 'behind';
393
408
 
@@ -504,9 +519,9 @@ export declare const collectSubqueries: (predicate: Predicate) => Generator<{
504
519
  */
505
520
  export declare const column: <T = string | number | boolean | Date | null>(columnName: string, alias?: string) => AggregateColumn<T>;
506
521
 
507
- export declare class ColumnBuilder<TsType, Type extends ColumnType> {
522
+ export declare class ColumnBuilder<TsType, Type extends ColumnType, HasDefault extends boolean = boolean> {
508
523
  private readonly definition;
509
- constructor(definition: ColumnDefinition<TsType, Type>);
524
+ constructor(definition: ColumnDefinition<TsType, Type, HasDefault>);
510
525
  /**
511
526
  * `raw(ddl)` columns reject any modifier that would add a second
512
527
  * source of truth for nullability / default / uniqueness. The DDL
@@ -516,7 +531,7 @@ export declare class ColumnBuilder<TsType, Type extends ColumnType> {
516
531
  * the error site is the schema file.
517
532
  */
518
533
  private rejectIfRaw;
519
- nullable(): ColumnBuilder<TsType | null, Type>;
534
+ nullable(): ColumnBuilder<TsType | null, Type, HasDefault>;
520
535
  /**
521
536
  * Encrypt this column's value at rest (AES-256-GCM). The runtime
522
537
  * store middleware transparently encrypts on write + decrypts on
@@ -601,7 +616,7 @@ export declare class ColumnBuilder<TsType, Type extends ColumnType> {
601
616
  * SQL-side fill (legacy seeds, raw inserts); factory wins for
602
617
  * framework-routed inserts.
603
618
  */
604
- default(value: TsType | 'now' | (() => TsType)): this;
619
+ default(value: TsType | 'now' | (() => TsType)): ColumnBuilder<TsType, Type, true>;
605
620
  /**
606
621
  * Mark this column as computed from other row fields. The function
607
622
  * runs on INSERT AFTER defaults are applied, and again on every
@@ -657,7 +672,7 @@ export declare class ColumnBuilder<TsType, Type extends ColumnType> {
657
672
  */
658
673
  generatedAs(expr: string, options?: {
659
674
  stored?: boolean;
660
- }): this;
675
+ }): ColumnBuilder<TsType, Type, true>;
661
676
  /**
662
677
  * Migration backfill. Tells the planner how to populate existing rows
663
678
  * when this column is added as NOT NULL to a populated table — without
@@ -754,7 +769,7 @@ export declare class ColumnBuilder<TsType, Type extends ColumnType> {
754
769
  * Pass `as const` or a `const`-typed array — the TS inference
755
770
  * preserves the literals only when the array is a tuple of literals.
756
771
  */
757
- oneOf<const Values extends readonly [string, ...string[]]>(this: ColumnBuilder<TsType, 'text'>, values: Values): ColumnBuilder<null extends TsType ? Values[number] | null : Values[number], 'text'>;
772
+ oneOf<const Values extends readonly [string, ...string[]]>(this: ColumnBuilder<TsType, 'text', HasDefault>, values: Values): ColumnBuilder<null extends TsType ? Values[number] | null : Values[number], 'text', HasDefault>;
758
773
  /**
759
774
  * Cap a text column's length → `VARCHAR(n)` (postgres / mysql / mariadb) /
760
775
  * `NVARCHAR(n)` (mssql), instead of the unbounded `LONGTEXT` / `TEXT`
@@ -777,7 +792,7 @@ export declare class ColumnBuilder<TsType, Type extends ColumnType> {
777
792
  * Method only resolves on `text()` builders (the `Type extends 'text'`
778
793
  * guard), like `oneOf`. `n` is a character count.
779
794
  */
780
- maxLength(this: ColumnBuilder<TsType, 'text'>, n: number): ColumnBuilder<TsType, 'text'>;
795
+ maxLength(this: ColumnBuilder<TsType, 'text', HasDefault>, n: number): ColumnBuilder<TsType, 'text', HasDefault>;
781
796
  /**
782
797
  * Attach a raw SQL `CHECK` to this column — a DB-ENFORCED invariant
783
798
  * that holds regardless of which client writes the row (defense-in-
@@ -804,11 +819,12 @@ export declare class ColumnBuilder<TsType, Type extends ColumnType> {
804
819
  __definition(): ColumnDefinition<TsType, Type>;
805
820
  }
806
821
 
807
- export declare interface ColumnDefinition<TsType, Type extends ColumnType = ColumnType> {
822
+ export declare interface ColumnDefinition<TsType, Type extends ColumnType = ColumnType, HasDefault extends boolean = boolean> {
808
823
  readonly type: Type;
809
824
  readonly nullable: boolean;
810
825
  readonly unique: boolean;
811
826
  readonly hasDefault: boolean;
827
+ /* Excluded from this release type: __hasDefault */
812
828
  readonly defaultValue?: unknown;
813
829
  /**
814
830
  * Application-side default factory. When set, the MutationStore
@@ -1128,6 +1144,15 @@ export declare interface ColumnDefinition<TsType, Type extends ColumnType = Colu
1128
1144
  readonly __tsType?: TsType;
1129
1145
  }
1130
1146
 
1147
+ /** `true` when the column's declared default flag is `true` (`.default()` narrows
1148
+ * it; a plain column reads `boolean`, which is NOT `[true]`). Tuple-wrapped so
1149
+ * `boolean` does not distribute. */
1150
+ declare type ColumnHasDefault<D> = D extends ColumnDefinition<unknown, ColumnType, infer HD> ? ([HD] extends [true] ? true : false) : false;
1151
+
1152
+ /** A column may be omitted from an insert when it is auto-filled, has a default,
1153
+ * or is nullable. */
1154
+ declare type ColumnOptionalForInsert<K extends PropertyKey, D> = K extends AutoFilledColumn ? true : ColumnHasDefault<D> extends true ? true : null extends InferColumn<D> ? true : false;
1155
+
1131
1156
  /**
1132
1157
  * The per-column mapping, over a column DEFINITION — what `table.fields` holds.
1133
1158
  *
@@ -1562,7 +1587,7 @@ export declare interface DataStore {
1562
1587
  }
1563
1588
 
1564
1589
  /** Calendar date without time. */
1565
- export declare const date: () => ColumnBuilder<Date, "date">;
1590
+ export declare const date: () => ColumnBuilder<Date, "date", boolean>;
1566
1591
 
1567
1592
  export declare const dbEnum: <const Values extends ReadonlyArray<string>>(name: string, values: Values) => DbEnumHandle<Values>;
1568
1593
 
@@ -1670,7 +1695,17 @@ export declare const decodeRowsFromSchema: <T extends Record<string, unknown>>(r
1670
1695
  * through untouched, so turning encryption on doesn't break reads of
1671
1696
  * rows written before it. Operates per-row on shallow copies.
1672
1697
  */
1673
- export declare const decryptFieldsOnRead: (rows: ReadonlyArray<Row>, table: TableLike | undefined, cipher: FieldCipher | undefined) => ReadonlyArray<Row>;
1698
+ export declare const decryptFieldsOnRead: (rows: ReadonlyArray<Row>, table: TableLike | undefined, cipher: FieldCipher | undefined, options?: {
1699
+ /** Default `'throw'` — see `OnDecryptError`. */
1700
+ readonly onError?: OnDecryptError;
1701
+ /** Called once per undecryptable column when `onError: 'null'`, so the
1702
+ * degraded read leaves a trace naming the `table.column`. */
1703
+ readonly warn?: (info: {
1704
+ readonly table: string;
1705
+ readonly column: string;
1706
+ readonly reason: string;
1707
+ }) => void;
1708
+ }) => ReadonlyArray<Row>;
1674
1709
 
1675
1710
  export declare const defineMigration: (input: MigrationDefinitionInput) => MigrationDefinition;
1676
1711
 
@@ -2002,8 +2037,31 @@ export declare interface FieldCipher {
2002
2037
  readonly decrypt: (ciphertext: string) => string;
2003
2038
  }
2004
2039
 
2040
+ /**
2041
+ * An `.encrypted()` column could not be decrypted with the ACTIVE cipher —
2042
+ * almost always a value encrypted under a DIFFERENT key (a prod/staging snapshot
2043
+ * restored into a dev DB whose key differs). Typed and `_tag`-carrying (the same
2044
+ * shape `storeErrors.ts` uses, deliberately NOT `Data.TaggedError` — that trips
2045
+ * TS2742 on the `.d.ts` and drags `effect/Cause` into this browser-safe codec) so
2046
+ * it is `catchTag`-matchable and, above all, READABLE: the message names the
2047
+ * `table.column` and the reason instead of surfacing a raw
2048
+ * `field cipher: malformed ciphertext` with no context. The ciphertext itself is
2049
+ * NEVER included.
2050
+ */
2051
+ export declare class FieldDecryptionError extends Error {
2052
+ readonly _tag = "FieldDecryptionError";
2053
+ readonly table: string;
2054
+ readonly column: string;
2055
+ readonly reason: string;
2056
+ constructor(info: {
2057
+ readonly table: string;
2058
+ readonly column: string;
2059
+ readonly reason: string;
2060
+ });
2061
+ }
2062
+
2005
2063
  export declare type FieldDefinitions<F extends FieldsInput> = {
2006
- [K in keyof F]: F[K] extends ColumnBuilder<infer T, infer Type> ? ColumnDefinition<T, Type> : never;
2064
+ [K in keyof F]: F[K] extends ColumnBuilder<infer T, infer Type, infer HD> ? ColumnDefinition<T, Type, HD> : never;
2007
2065
  };
2008
2066
 
2009
2067
  export declare type FieldsInput = Record<string, ColumnBuilder<unknown, ColumnType>>;
@@ -2069,6 +2127,11 @@ export declare interface FileMigrationContext {
2069
2127
  readonly appliedAt: string;
2070
2128
  }
2071
2129
 
2130
+ /** Flatten an intersection into a single object type for readable errors/hovers. */
2131
+ declare type Flatten<O> = {
2132
+ [K in keyof O]: O[K];
2133
+ };
2134
+
2072
2135
  /**
2073
2136
  * Multi-line pretty block for the terminal. Tries to teach, not just
2074
2137
  * complain — labels every section (`table` / `redundant` / `covered
@@ -2218,7 +2281,7 @@ export declare interface HybridSearchOptions {
2218
2281
  * `row.id`; for `numeric` the key is omitted so the dialect's
2219
2282
  * SERIAL/AUTO_INCREMENT/IDENTITY clause fires.
2220
2283
  */
2221
- export declare const id: (options?: IdSchemeInput) => ColumnBuilder<string, "id">;
2284
+ export declare const id: (options?: IdSchemeInput) => ColumnBuilder<string, "id", boolean>;
2222
2285
 
2223
2286
  /**
2224
2287
  * Fully-resolved scheme stored on the `id` column definition AFTER
@@ -2390,6 +2453,12 @@ export declare const inferForeignKey: (target: TableLike, sourceTableName: strin
2390
2453
  */
2391
2454
  export declare type InferIndexNames<T> = T extends Table<string, Record<string, ColumnDefinition<unknown>>, boolean, infer N> ? N : never;
2392
2455
 
2456
+ export declare type InferInsertRow<T> = T extends Table<string, infer F, boolean, string> ? Flatten<{
2457
+ readonly [K in keyof F as ColumnOptionalForInsert<K, F[K]> extends true ? never : K]: InferColumn<F[K]>;
2458
+ } & {
2459
+ readonly [K in keyof F as ColumnOptionalForInsert<K, F[K]> extends true ? K : never]?: InferColumn<F[K]>;
2460
+ }> : never;
2461
+
2393
2462
  /** Row type for the table — useful for typing application code. */
2394
2463
  export declare type InferRow<T> = T extends Table<string, infer F, boolean, string> ? InferRowFromFields<F> : never;
2395
2464
 
@@ -2400,11 +2469,18 @@ export declare type InferRowFromFields<F extends Record<string, ColumnDefinition
2400
2469
  /** Row type for a view — mirrors `InferRow` for tables. */
2401
2470
  export declare type InferViewRow<V> = V extends View<string, infer F> ? InferRowFromFields<F> : never;
2402
2471
 
2472
+ /**
2473
+ * Insert a row, typed against the table: the payload must carry every required
2474
+ * column (NOT NULL, no default, not auto-filled) or it is a compile error.
2475
+ * Returns the stored row typed as `InferRow<T>`.
2476
+ */
2477
+ export declare const insertRow: <T extends AnyTable>(store: TypedInsertStore, table: T, row: InferInsertRow<T>) => Promise<InferRow<T>>;
2478
+
2403
2479
  export declare const inSet: <RowOf = Record<string, unknown>, K extends keyof RowOf & string = keyof RowOf & string>(column: K, values: ReadonlyArray<RowOf[K]>) => PredicateLeaf;
2404
2480
 
2405
2481
  export declare const inSubquery: <RowOf = Record<string, unknown>, K extends keyof RowOf & string = keyof RowOf & string>(column: K, subquery: QueryWithDescriptor | QueryDescriptor) => SubqueryInPredicate;
2406
2482
 
2407
- export declare const integer: () => ColumnBuilder<number, "integer">;
2483
+ export declare const integer: () => ColumnBuilder<number, "integer", boolean>;
2408
2484
 
2409
2485
  /** `INTERSECT` — rows present in EVERY input. */
2410
2486
  export declare const intersect: (...queries: ReadonlyArray<QueryWithDescriptorAny>) => Query<Row, string>;
@@ -2419,7 +2495,7 @@ export declare const intersect: (...queries: ReadonlyArray<QueryWithDescriptorAn
2419
2495
  * slaDeadline: interval()
2420
2496
  * ```
2421
2497
  */
2422
- export declare const interval: () => ColumnBuilder<string, "interval">;
2498
+ export declare const interval: () => ColumnBuilder<string, "interval", boolean>;
2423
2499
 
2424
2500
  /** Is this namespace one of ours? (so a teardown sweep never touches a real
2425
2501
  * tenant namespace). */
@@ -2427,6 +2503,8 @@ export declare const isBranchNamespace: (namespace: string) => boolean;
2427
2503
 
2428
2504
  export declare const isEncrypted: (value: unknown) => value is string;
2429
2505
 
2506
+ export declare const isFieldDecryptionError: (e: unknown) => e is FieldDecryptionError;
2507
+
2430
2508
  /** Type-guard for the discovery walker. */
2431
2509
  export declare const isFileMigration: (value: unknown) => value is FileMigration;
2432
2510
 
@@ -2494,7 +2572,7 @@ export declare const isView: (t: TableLike) => t is View<string, Record<string,
2494
2572
  export declare type JoinsMap = Record<string, Record<string, unknown>>;
2495
2573
 
2496
2574
  /** Typed JSON column. Pass the type parameter to record the expected shape. */
2497
- export declare const json: <T = unknown>() => ColumnBuilder<T, "json">;
2575
+ export declare const json: <T = unknown>() => ColumnBuilder<T, "json", boolean>;
2498
2576
 
2499
2577
  export declare const jsonField: (column: string, ...path: ReadonlyArray<string | number>) => JsonFieldFilter;
2500
2578
 
@@ -2760,6 +2838,21 @@ export declare interface MigrationStepContext {
2760
2838
 
2761
2839
  export declare const min: (column: string, alias?: string) => AggregateColumn;
2762
2840
 
2841
+ /**
2842
+ * The `conflictColumns` an upsert names that are absent from its payload. An
2843
+ * upsert keyed on a column the row doesn't set can't match a conflict target —
2844
+ * the dialect fails obscurely (or worse, inserts a duplicate). Naming it at the
2845
+ * call is the difference between a one-line fix and reading a driver error.
2846
+ */
2847
+ export declare const missingConflictColumns: (conflictColumns: ReadonlyArray<string>, row: Row) => ReadonlyArray<string>;
2848
+
2849
+ /**
2850
+ * Columns the row must carry but doesn't. Empty when the row is complete.
2851
+ * `null` counts as missing for a NOT NULL column — the dialect would reject it
2852
+ * just the same, and a clear message beats a driver error either way.
2853
+ */
2854
+ export declare const missingRequiredColumns: (table: TableLike, row: Row) => ReadonlyArray<string>;
2855
+
2763
2856
  export declare const mixin: <const Input extends FieldsInput>(options: MixinOptions<Input>) => MixinDefinition<MaterializedMixinFields<Input>>;
2764
2857
 
2765
2858
  export declare interface MixinDefinition<F extends Record<string, ColumnDefinition<unknown>>> {
@@ -2887,6 +2980,17 @@ export declare interface NotPredicate {
2887
2980
  */
2888
2981
  export declare const numeric: (precision: number, scale?: number) => ColumnBuilder<string, "decimal">;
2889
2982
 
2983
+ /**
2984
+ * What a decrypt failure does. `'throw'` (default, and the ONLY safe production
2985
+ * behaviour) surfaces a typed `FieldDecryptionError`. `'null'` degrades the one
2986
+ * unreadable column to `null` and warns — for DEV / a data migration where a
2987
+ * snapshot carries ciphertext bound to another key: one undecryptable row must
2988
+ * not nuke every read (and its siblings that WOULD decrypt), it should surface as
2989
+ * "re-enter this credential", not a 500. Never enable `'null'` in production — it
2990
+ * silently hides a real key mismatch.
2991
+ */
2992
+ export declare type OnDecryptError = 'throw' | 'null';
2993
+
2890
2994
  export declare const one: (target: TableRef, options?: {
2891
2995
  readonly foreignKey?: string;
2892
2996
  readonly sourceKey?: string;
@@ -3867,7 +3971,7 @@ declare interface RawSqlFragment {
3867
3971
  * mssql `FLOAT`, sqlite `REAL`. Drivers return JS numbers — no codec. Use for
3868
3972
  * fractional values (ratings, percentages, measurements) where `integer()`
3869
3973
  * would truncate. */
3870
- export declare const real: () => ColumnBuilder<number, "real">;
3974
+ export declare const real: () => ColumnBuilder<number, "real", boolean>;
3871
3975
 
3872
3976
  /**
3873
3977
  * Foreign-key reference to another table's id column.
@@ -5061,9 +5165,9 @@ export declare class TenantResidencyUnresolved extends Error {
5061
5165
  constructor(message: string);
5062
5166
  }
5063
5167
 
5064
- export declare const text: () => ColumnBuilder<string, "text">;
5168
+ export declare const text: () => ColumnBuilder<string, "text", boolean>;
5065
5169
 
5066
- export declare const timestamp: () => ColumnBuilder<Date, "timestamp">;
5170
+ export declare const timestamp: () => ColumnBuilder<Date, "timestamp", boolean>;
5067
5171
 
5068
5172
  /**
5069
5173
  * The timestamp mapping as a STANDALONE field schema: `Date` in the
@@ -5106,6 +5210,19 @@ export declare const timestampMs: Schema.Schema<Date, number>;
5106
5210
  */
5107
5211
  export declare const timestampMsOrNull: Schema.Schema<Date | null, number | null>;
5108
5212
 
5213
+ /** The minimal store surface `insertRow` needs — satisfied by `ctx.store`. */
5214
+ export declare interface TypedInsertStore {
5215
+ readonly insert: (table: string, row: Row) => Promise<Row>;
5216
+ }
5217
+
5218
+ /** The minimal store surface `upsertRow` needs. */
5219
+ export declare interface TypedUpsertStore {
5220
+ readonly upsert: (table: string, row: Row, options: {
5221
+ conflictColumns: ReadonlyArray<string>;
5222
+ update?: ReadonlyArray<string> | ((existing: Row) => Readonly<Record<string, unknown>>);
5223
+ }) => Promise<Row>;
5224
+ }
5225
+
5109
5226
  /**
5110
5227
  * `(SELECT ...) UNION (SELECT ...) ...` — dedup-merge. Q6.
5111
5228
  *
@@ -5139,6 +5256,15 @@ export declare interface UniqueSpec {
5139
5256
  readonly dedup?: 'fail' | 'suffix-counter' | Statement.Fragment;
5140
5257
  }
5141
5258
 
5259
+ /**
5260
+ * Upsert a row, typed the same way. `conflictColumns` is constrained to the
5261
+ * table's own column names, so a typo'd conflict key is a compile error too.
5262
+ */
5263
+ export declare const upsertRow: <T extends AnyTable>(store: TypedUpsertStore, table: T, row: InferInsertRow<T>, options: {
5264
+ readonly conflictColumns: ReadonlyArray<keyof InferRow<T> & string>;
5265
+ readonly update?: ReadonlyArray<keyof InferRow<T> & string> | ((existing: InferRow<T>) => Readonly<Partial<InferRow<T>>>);
5266
+ }) => Promise<InferRow<T>>;
5267
+
5142
5268
  /**
5143
5269
  * Validate one column-name key on a table's fields map. Throws on
5144
5270
  * empty / invalid characters / > 63 bytes. Records a WARN above 50.