uql-orm 0.105.1 → 0.106.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.
@@ -18,8 +18,8 @@ export const Author = defineEntity({
18
18
  },
19
19
  ],
20
20
  })
21
- .relations((rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }), (rel) => ({
22
- bookCount: () => rel.books.count(),
23
- topStock: () => rel.books.max((book) => book.stock),
21
+ .relations((rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }), (author) => ({
22
+ bookCount: () => author.books.count(),
23
+ topStock: () => author.books.max((book) => book.stock),
24
24
  }));
25
25
  export const label = (author) => `${author.name} (${author.books?.length ?? 0})`;
@@ -30,9 +30,9 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
30
30
  readonly authorId: import("../../../index.js").NumericColumn<{
31
31
  readonly type: NumberConstructor;
32
32
  }, number>;
33
- }> & {
34
- readonly shout?: string | null | undefined;
35
- } & import("../../../index.js").RelationRow<{
33
+ }, object> & {
34
+ readonly shout: string | null;
35
+ } & {} & import("../../../index.js").RelationRow<{
36
36
  readonly author: () => import("../../../index.js").SchemaRelation<object & {
37
37
  id: number;
38
38
  name: string;
@@ -58,7 +58,7 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
58
58
  } & {
59
59
  readonly defaultValue: unknown;
60
60
  }, Date>;
61
- }> & import("../../../index.js").RelationRow<{
61
+ }, object> & import("../../../index.js").RelationRow<{
62
62
  readonly books: () => import("../../../index.js").SchemaRelation<object & {
63
63
  id: number;
64
64
  title: string;
@@ -91,9 +91,9 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
91
91
  readonly authorId: import("../../../index.js").NumericColumn<{
92
92
  readonly type: NumberConstructor;
93
93
  }, number>;
94
- }> & {
95
- readonly shout?: string | null | undefined;
96
- } & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").AggregateRow<{}>, "1m", {
94
+ }, object> & {
95
+ readonly shout: string | null;
96
+ } & {} & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").DerivedRow<{}>, "1m", {
97
97
  id: number;
98
98
  title: string;
99
99
  stock: number;
@@ -101,9 +101,9 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
101
101
  version: number;
102
102
  authorId: number;
103
103
  } & {} & {
104
- readonly shout?: string | null | undefined;
105
- }>;
106
- }> & import("../../../index.js").AggregateRow<{
104
+ readonly shout: string | null;
105
+ } & {}>;
106
+ }> & import("../../../index.js").DerivedRow<{
107
107
  readonly bookCount: () => import("../../../index.js").RelationAggregate<number>;
108
108
  readonly topStock: () => import("../../../index.js").RelationAggregate<number | null>;
109
109
  }>, "m1", object & {
@@ -131,7 +131,7 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
131
131
  } & {
132
132
  readonly defaultValue: unknown;
133
133
  }, Date>;
134
- }> & import("../../../index.js").RelationRow<{
134
+ }, object> & import("../../../index.js").RelationRow<{
135
135
  readonly books: () => import("../../../index.js").SchemaRelation<object & {
136
136
  id: number;
137
137
  title: string;
@@ -164,9 +164,9 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
164
164
  readonly authorId: import("../../../index.js").NumericColumn<{
165
165
  readonly type: NumberConstructor;
166
166
  }, number>;
167
- }> & {
168
- readonly shout?: string | null | undefined;
169
- } & import("../../../index.js").RelationRow<any> & import("../../../index.js").AggregateRow<{}>, "1m", {
167
+ }, object> & {
168
+ readonly shout: string | null;
169
+ } & {} & import("../../../index.js").RelationRow<any> & import("../../../index.js").DerivedRow<{}>, "1m", {
170
170
  id: number;
171
171
  title: string;
172
172
  stock: number;
@@ -174,13 +174,13 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
174
174
  version: number;
175
175
  authorId: number;
176
176
  } & {} & {
177
- readonly shout?: string | null | undefined;
178
- }>;
179
- }> & import("../../../index.js").AggregateRow<{
177
+ readonly shout: string | null;
178
+ } & {}>;
179
+ }> & import("../../../index.js").DerivedRow<{
180
180
  readonly bookCount: () => import("../../../index.js").RelationAggregate<number>;
181
181
  readonly topStock: () => import("../../../index.js").RelationAggregate<number | null>;
182
182
  }>>;
183
- }> & import("../../../index.js").AggregateRow<{}>, number, {
183
+ }> & import("../../../index.js").DerivedRow<{}>, number, {
184
184
  id: number;
185
185
  title: string;
186
186
  stock: number;
@@ -188,5 +188,5 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
188
188
  version: number;
189
189
  authorId: number;
190
190
  } & {} & {
191
- readonly shout?: string | null | undefined;
192
- }, false>;
191
+ readonly shout: string | null;
192
+ } & {}, false>;
@@ -230,9 +230,9 @@ function printDriftGroup(title, drifts, icon, showSuggestion) {
230
230
  }
231
231
  function printHelp() {
232
232
  console.log(`
233
- uql-orm/migrate - Database migration tool for uql ORM
233
+ uql-migrate - Database migration tool for uql ORM
234
234
 
235
- Usage: uql-orm/migrate <command> [options]
235
+ Usage: uql-migrate <command> [options]
236
236
 
237
237
  Commands:
238
238
  up Run all pending migrations
@@ -282,16 +282,16 @@ Configuration:
282
282
  };
283
283
 
284
284
  Examples:
285
- uql-orm/migrate up
286
- uql-orm/migrate up --step 1
287
- uql-orm/migrate down
288
- uql-orm/migrate down --step 3
289
- uql-orm/migrate status
290
- uql-orm/migrate generate add_users_table
291
- uql-orm/migrate generate:entities initial_schema
292
- uql-orm/migrate generate:from-db --output ./src/entities
293
- uql-orm/migrate sync --dry-run
294
- uql-orm/migrate sync --pull
295
- uql-orm/migrate drift:check
285
+ uql-migrate up
286
+ uql-migrate up --step 1
287
+ uql-migrate down
288
+ uql-migrate down --step 3
289
+ uql-migrate status
290
+ uql-migrate generate add_users_table
291
+ uql-migrate generate:entities initial_schema
292
+ uql-migrate generate:from-db --output ./src/entities
293
+ uql-migrate sync --dry-run
294
+ uql-migrate sync --pull
295
+ uql-migrate drift:check
296
296
  `);
297
297
  }
@@ -1,10 +1,10 @@
1
1
  import type { PGliteOptions } from '@electric-sql/pglite';
2
2
  import { AbstractSharedHandleQuerierPool } from '../querier/abstractSharedHandleQuerierPool.js';
3
- import type { ExtraOptions } from '../type/index.js';
3
+ import type { Except, ExtraOptions } from '../type/index.js';
4
4
  import { PgliteDialect } from './pgliteDialect.js';
5
5
  import { type PgliteDatabase, PgliteQuerier } from './pgliteQuerier.js';
6
6
  /** PGlite's own options but `dataDir`, the pool's first argument; `extensions: { vector }` enables pgvector. Type-only. */
7
- export type PglitePoolOptions = Omit<PGliteOptions, 'dataDir'>;
7
+ export type PglitePoolOptions = Except<PGliteOptions, 'dataDir'>;
8
8
  /**
9
9
  * A pool for PGlite, Postgres in WASM in this process, on one connection. A second `BEGIN` silently joins
10
10
  * the open transaction, so a unit of work needing its own needs its own pool. Transactions are plain
@@ -1,4 +1,5 @@
1
1
  import { AbstractSharedHandleQuerierPool } from '../querier/abstractSharedHandleQuerierPool.js';
2
+ import type { Except, Merge } from '../type/index.js';
2
3
  import type { SqliteDialect } from './sqliteDialect.js';
3
4
  import { type SqliteDatabase, type SqlitePreparedStatement, SqliteQuerier } from './sqliteQuerier.js';
4
5
  /** What every local SQLite pool accepts on top of its driver's own options. */
@@ -27,9 +28,9 @@ export type LocalSqliteDatabase = {
27
28
  * A `node:sqlite` or `bun:sqlite` handle as a {@link LocalSqliteDatabase}. Neither says whether a statement
28
29
  * reads, so `reads` does: taken by `run()`, a RETURNING statement's rows would be lost, and its ids with them.
29
30
  */
30
- export declare function adaptSqlite<S extends Omit<SqlitePreparedStatement, 'reader'>>(db: Omit<LocalSqliteDatabase, 'prepare'> & {
31
+ export declare function adaptSqlite<S extends Except<SqlitePreparedStatement, 'reader'>>(db: Merge<LocalSqliteDatabase, {
31
32
  prepare(sql: string): S;
32
- }, reads: (stmt: S) => boolean): LocalSqliteDatabase;
33
+ }>, reads: (stmt: S) => boolean): LocalSqliteDatabase;
33
34
  /**
34
35
  * `db` extended past SQLite's own: each loadable extension installed, which `node:sqlite` refuses unless
35
36
  * opened to allow them, and `REGEXP` defined as libSQL builds it in, which SQLite leaves to the application.
@@ -1,8 +1,9 @@
1
1
  import type { ForeignKeyAction } from '../schema/types.js';
2
2
  import type { TYPE_BOUNDS, VALUE_DECIDERS } from '../util/fieldOption.util.js';
3
- import type { BlobColumnType, BooleanColumnType, ColumnType, DateColumnType, DdlDefault, JsonColumnType, NumericColumnType, StringColumnType, VectorColumnType, FieldOptions, HasCompositeKey, IdValue, JsonShape, OnFieldCallback, ShapeValue, StampEvent } from './entity.js';
3
+ import type { BlobColumnType, BooleanColumnType, ColumnType, DateColumnType, DdlDefault, JsonColumnType, NumericColumnType, StringColumnType, VectorColumnType, FieldOptions, HasCompositeKey, IdValue, JoinKind, OnFieldCallback, StampEvent } from './entity.js';
4
4
  import type { QuerySql } from './querySql.js';
5
5
  import type { ReferencedKey } from './schemaEntity.js';
6
+ import type { StandardSchemaV1 } from './standardSchema.js';
6
7
  import type { Type, Json, AbstractType } from './utility.js';
7
8
  import type { VectorDistance } from './vector.js';
8
9
  /** Where a column builder holds its options, so every string key of a builder is a method. */
@@ -199,16 +200,28 @@ export interface VersionColumn<in out O, in out V> extends Column<O, V> {
199
200
  readonly comment: string;
200
201
  }, V>;
201
202
  }
202
- /** A key's kind as a join compares it: a number and a bigint both integers, so a BIGINT column holds either key. */
203
- type ValueKind<T> = T extends number | bigint ? number | bigint : T;
204
203
  /** Refuses a target whose key is another kind of value than the column holds, which no join matches. */
205
- type HoldsKey<C, V> = [ValueKind<NonNullable<ReferencedKey<C>>>] extends [ValueKind<V>] ? unknown : {
204
+ type HoldsKey<C, V> = [JoinKind<NonNullable<ReferencedKey<C>>>] extends [JoinKind<V>] ? unknown : {
206
205
  readonly __columnMustHoldReferencedKey: ReferencedKey<C>;
207
206
  };
208
207
  /** The column types holding an exact decimal, read as its text: a JS number would round it. */
209
208
  type DecimalType = 'decimal' | 'numeric';
210
- /** What a JSON column holds: its shape's payload, or any document. */
211
- type JsonValue<S> = [S] extends [never] ? Json : ShapeValue<S> extends infer P extends object | string | number | boolean ? Json<P> : Json;
209
+ /** A JSON column of `T`, typed by the payload its schema validates to, or any document with none. */
210
+ type JsonColumn<T extends 'json' | 'jsonb'> = {
211
+ (): ColumnBuilder<{
212
+ readonly type: T;
213
+ }, Json, 'json'>;
214
+ <S extends StandardSchemaV1>(schema: S): ColumnBuilder<{
215
+ readonly type: T;
216
+ readonly schema: S;
217
+ }, JsonOutput<PayloadOf<S['~standard']['types']>>, 'json'>;
218
+ };
219
+ /** A schema's output as a JSON column holds it: a document, or the primitive a payload may be. */
220
+ type JsonOutput<O> = O extends object | string | number | boolean | null ? Json<O> : Json;
221
+ /** The output a schema's `types` states, `unknown` where it states none: `never` would type the column as nothing. */
222
+ type PayloadOf<T> = NonNullable<T> extends infer N ? [N] extends [never] ? unknown : N extends {
223
+ readonly output: infer O;
224
+ } ? O : unknown : never;
212
225
  /** The key a column referencing `C` holds, or a named complaint for a composite one, which no one column holds. */
213
226
  type ReferenceValue<C> = C extends AbstractType<infer E> ? HasCompositeKey<E> extends true ? {
214
227
  readonly __compositeKeyNeedsAColumnPerKey: true;
@@ -249,20 +262,8 @@ export type ColumnFactory = {
249
262
  date(): DateColumn<{
250
263
  readonly type: DateConstructor;
251
264
  }, Date>;
252
- json(): ColumnBuilder<{
253
- readonly type: 'json';
254
- }, Json, 'json'>;
255
- json<const S extends JsonShape>(shape: S): ColumnBuilder<{
256
- readonly type: 'json';
257
- readonly shape: S;
258
- }, JsonValue<S>, 'json'>;
259
- jsonb(): ColumnBuilder<{
260
- readonly type: 'jsonb';
261
- }, Json, 'json'>;
262
- jsonb<const S extends JsonShape>(shape: S): ColumnBuilder<{
263
- readonly type: 'jsonb';
264
- readonly shape: S;
265
- }, JsonValue<S>, 'json'>;
265
+ json: JsonColumn<'json'>;
266
+ jsonb: JsonColumn<'jsonb'>;
266
267
  vector(dimensions: number): VectorColumn<{
267
268
  readonly type: 'vector';
268
269
  readonly dimensions: number;
@@ -4,7 +4,8 @@ import type { Querier } from './querier.js';
4
4
  import type { FilterOptions, RelationQuery } from './query.js';
5
5
  import type { ColumnRef, JsonPathRef, QuerySql, SqlFor, RelationAggregate } from './querySql.js';
6
6
  import type { QueryWhere } from './queryWhere.js';
7
- import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsJson, JsonBrand, IsMany, Json, JsonScalar, Scalar, Type, AbstractType, Unpacked, Writable } from './utility.js';
7
+ import type { StandardSchemaV1 } from './standardSchema.js';
8
+ import type { AtLeastOne, Except, ExactlyOne, IsEqual, Merge, IsJson, JsonBrand, IsMany, Json, JsonScalar, Scalar, Type, AbstractType, Unpacked, Writable } from './utility.js';
8
9
  import type { VectorDistance, VectorIndexOptions, VectorIndexType } from './vector.js';
9
10
  /** Brands the property an entity is identified by, where it is not `id`, `_id` or `uuid`. */
10
11
  export declare const idKey: unique symbol;
@@ -16,11 +17,9 @@ export declare const idKey: unique symbol;
16
17
  export declare const versionKey: unique symbol;
17
18
  /** Brands the fields an insert may leave out, which a default fills, `[filledKey]?: 'units' | 'createdAt'`; each stays present on every read. */
18
19
  export declare const filledKey: unique symbol;
19
- type EntityBrand = typeof idKey | typeof versionKey | typeof filledKey;
20
+ export type EntityBrand = typeof idKey | typeof versionKey | typeof filledKey;
20
21
  /** The names an entity's brand `B` lists, `never` where it declares none. */
21
- type BrandNames<E, B extends EntityBrand> = E extends {
22
- readonly [K in B]?: infer N;
23
- } ? N : never;
22
+ export type BrandNames<E, B extends EntityBrand> = B extends keyof E ? NonNullable<E[B]> : never;
24
23
  /**
25
24
  * A brand naming a key that is no field, which each reader would drop silently: refused where an entity
26
25
  * registers, `@Entity()`, by a member the class lacks that names the typo. A class with no
@@ -258,24 +257,6 @@ type TimeColumnType = 'time';
258
257
  /** A numeric column holding an exact decimal, read as its text: a JS number would round it. */
259
258
  type DecimalColumnType = 'decimal' | 'numeric';
260
259
  export type JsonColumnType = ColumnTypeOf<'json'>;
261
- /**
262
- * A JSON column's payload described as data, in a field's vocabulary: a value's type (`String`), an object of
263
- * shapes, a key ending in `?` for an optional member, and `[shape]` for an array of it.
264
- * @example `{ theme: String, 'nickname?': String, tags: [String], billing: { plan: String } }`
265
- */
266
- export type JsonShape = JsonLeaf | readonly [JsonShape] | {
267
- readonly [key: string]: JsonShape;
268
- };
269
- /** The values a JSON document holds at a leaf. */
270
- type JsonLeaf = StringConstructor | NumberConstructor | BooleanConstructor;
271
- /** The payload a {@link JsonShape} describes. */
272
- export type ShapeValue<S> = S extends readonly [infer E] ? ShapeValue<E>[] : S extends JsonLeaf ? TsTypeOf<S> : [Extract<keyof S, `${string}?`>] extends [never] ? {
273
- -readonly [K in keyof S]: ShapeValue<S[K]>;
274
- } : {
275
- -readonly [K in keyof S as K extends `${string}?` ? never : K]: ShapeValue<S[K]>;
276
- } & {
277
- -readonly [K in keyof S as K extends `${infer N}?` ? N : never]?: ShapeValue<S[K]>;
278
- };
279
260
  export type BlobColumnType = ColumnTypeOf<'blob'>;
280
261
  export type BooleanColumnType = ColumnTypeOf<'boolean'>;
281
262
  export type VectorColumnType = ColumnTypeOf<'vector'>;
@@ -309,8 +290,8 @@ export type FieldOptions<V = unknown> = {
309
290
  readonly onDelete?: ForeignKeyAction;
310
291
  /** The values the column accepts, `f.enum(['draft', 'paid'])`: a `CHECK (col IN (...))` on every SQL engine. */
311
292
  readonly enum?: EnumValues;
312
- /** A JSON column's payload, which a schema entity's row reads it as: `shape: { theme: String, tags: [String] }`. */
313
- readonly shape?: JsonShape;
293
+ /** A JSON column's payload as a Standard Schema, `f.json(schema)`, typed by its output and never read at run time. */
294
+ readonly schema?: StandardSchemaV1;
314
295
  /**
315
296
  * An expression the database computes, never written: spliced into each read, or with `stored` a generated
316
297
  * column, `.as(sql`${user.first} || ' ' || ${user.last}`)`. A relation aggregate, `user.resources.count()`,
@@ -414,11 +395,11 @@ type RelationActions = {
414
395
  readonly onUpdate?: ForeignKeyAction;
415
396
  };
416
397
  /** The one column of `O` that can be a foreign key to `E`: a field holding `E`'s key, which has to be a single one. */
417
- type ForeignKey<O, E> = HasCompositeKey<E> extends true ? never : FieldKeyHolding<O, IdValue<E>>;
398
+ type ForeignKey<O, E> = HasCompositeKey<E> extends true ? never : KeyHolding<O, IdValue<E>>;
418
399
  /** One pair of join columns, each a field read off its entity's key map, the local one holding the foreign's value. */
419
400
  export type RelationReference<O, E> = {
420
401
  readonly [F in keyof E]-?: {
421
- readonly local: FieldKeyHolding<O, E[F]>;
402
+ readonly local: KeyHolding<O, E[F]>;
422
403
  readonly foreign: F;
423
404
  };
424
405
  }[FieldKey<E>];
@@ -426,22 +407,24 @@ export type RelationReference<O, E> = {
426
407
  export type FieldKeyOf<E, T> = {
427
408
  readonly [K in FieldKey<E>]-?: [NonNullable<E[K]>] extends [T] ? K : never;
428
409
  }[FieldKey<E>];
429
- /** The fields of `O` that can hold any value `V` takes. */
430
- type FieldKeyHolding<O, V> = {
431
- readonly [K in keyof O]-?: [NonNullable<V>] extends [NonNullable<O[K]>] ? K : never;
410
+ /** A value's kind as a join compares it: a number and a bigint are one kind, which BIGINT widens. */
411
+ export type JoinKind<T> = T extends number | bigint ? number : T;
412
+ /** The fields of `O` that can hold a key of `V`'s kind, compared as a join compares it at run time. */
413
+ export type KeyHolding<O, V> = [V] extends [never] ? never : {
414
+ readonly [K in keyof O]-?: [JoinKind<NonNullable<V>>] extends [JoinKind<NonNullable<O[K]>>] ? K : never;
432
415
  }[FieldKey<O>];
433
416
  /** A relation once `getMeta` resolved it: `references` settled into pairs and `mappedBy` a name. */
434
- export type RelationMeta = Omit<RelationRegistration, 'references'> & {
417
+ export type RelationMeta = Merge<RelationRegistration, {
435
418
  references: RelationReferences;
436
- };
419
+ }>;
437
420
  /**
438
421
  * A relation as the registry takes it: `mappedBy` and `references` read down to names, `references` a
439
422
  * single column until `getMeta` pairs it with the target's key.
440
423
  */
441
- export type RelationRegistration = Omit<RelationOptions<object>, 'mappedBy' | 'references'> & {
424
+ export type RelationRegistration = Merge<RelationOptions<object>, {
442
425
  mappedBy?: string;
443
426
  references?: RelationReferences | string;
444
- };
427
+ }>;
445
428
  /**
446
429
  * What a relation's join callbacks answer, `E` its target and `O` the entity declaring it: one foreign key, pairs of
447
430
  * columns, or the target's member mapping it. Each form states its own: a decorated class checks each member's
@@ -870,11 +853,11 @@ export type TriggerOptions<E = unknown> = {
870
853
  * A trigger as entity metadata keeps it: the column callback resolved to keys, and a body widened to
871
854
  * take both rows, which the renderer passes whatever the event, each body reading only its own.
872
855
  */
873
- export type EntityTriggerMeta<E = object> = Except<TriggerOptions<E>, 'of' | 'where' | 'run'> & {
856
+ export type EntityTriggerMeta<E = object> = Merge<TriggerOptions<E>, {
874
857
  readonly of?: readonly string[];
875
858
  readonly where?: TriggerPredicate<E, TriggerUpdateEvent> | TriggerMetaBody<E>;
876
859
  readonly run: TriggerMetaBody<E> | Readonly<Partial<Record<SqlDialectName, TriggerMetaBody<E>>>>;
877
- };
860
+ }>;
878
861
  /**
879
862
  * A body as the renderer calls it, with both rows whatever the event. Bivariant,
880
863
  * so a body typing the row its event lacks as `never` is still held here.
@@ -939,14 +922,14 @@ export type IndexOptions = Except<EntityIndexMeta, 'entries' | 'where'> & {
939
922
  readonly where?: QuerySql;
940
923
  };
941
924
  /** {@link IndexOptions} on an entity, `include` and `where` read off the section's refs as its columns are. */
942
- export type EntityIndexOptions<E> = Except<IndexOptions, 'include' | 'where'> & {
925
+ export type EntityIndexOptions<E> = Merge<IndexOptions, {
943
926
  readonly include?: readonly ColumnRef<FieldKey<E>>[];
944
927
  /**
945
928
  * Partial-index predicate, written as the predicate the query passes: a planner matches the two by
946
929
  * shape, so a hand-written `sql` that means the same thing leaves the index unused.
947
930
  */
948
931
  readonly where?: EntityPredicate<E> | QuerySql;
949
- };
932
+ }>;
950
933
  /** An index as registration reads it: its columns, read off the refs, and its options. */
951
934
  export type EntityIndexInput<E> = EntityIndexOptions<E> & {
952
935
  readonly columns: readonly EntityIndexColumnInput[];
@@ -14,6 +14,7 @@ export * from './querySql.js';
14
14
  export * from './schemaEntity.js';
15
15
  export * from './queryWhere.js';
16
16
  export * from './universalQuerier.js';
17
+ export * from './standardSchema.js';
17
18
  export * from './utility.js';
18
19
  export * from './vector.js';
19
20
  export * from './wire.js';
@@ -14,6 +14,7 @@ export * from './querySql.js';
14
14
  export * from './schemaEntity.js';
15
15
  export * from './queryWhere.js';
16
16
  export * from './universalQuerier.js';
17
+ export * from './standardSchema.js';
17
18
  export * from './utility.js';
18
19
  export * from './vector.js';
19
20
  export * from './wire.js';
@@ -450,7 +450,7 @@ type MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick
450
450
  /** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */
451
451
  type WholeRow<E, Q> = Q extends {
452
452
  readonly $populate: infer M;
453
- } ? Omit<E, keyof M & keyof E> & MethodMask<E> : DataRow<E>;
453
+ } ? Except<E, keyof M & keyof E> & MethodMask<E> : DataRow<E>;
454
454
  /** The populated relations, and the `_count` a query asked for. */
455
455
  type RelatedRows<E, Q> = Q extends {
456
456
  readonly $populate: infer M;
@@ -1,12 +1,11 @@
1
- import type { ForeignKeyAction } from '../schema/types.js';
2
1
  import type { Column, ColumnOptionsOf, ColumnValueOf, FilledOptions, NullOf } from './column.js';
3
- import type { CheckSection, FilterSection, filledKey, HookContext, HookEvent, idKey, IdValue, IndexSection, IsUnion, RefMap, RelationCardinality, RelationInverseOptions, RelationJoinOptions, RelationOwnerOptions, RelationRef, ToManyRefs, ToManyRelationKey, TriggerSection, versionKey } from './entity.js';
2
+ import type { BrandNames, CheckSection, FilterSection, filledKey, HookContext, HookEvent, idKey, IdValue, IndexSection, IsUnion, KeyHolding, RefMap, RelationCardinality, RelationInverseOptions, RelationJoinOptions, RelationOwnerOptions, RelationRef, ToManyRefs, ToManyRelationKey, TriggerSection, versionKey } from './entity.js';
4
3
  import type { QuerySql, RelationAggregate } from './querySql.js';
5
4
  import type { Type, AbstractType } from './utility.js';
6
5
  /**
7
- * A schema entity's columns, each an `f` builder. A foreign key is declared in `.references()`, once every entity
8
- * exists: one written here would read its target while that target's own type is still being inferred. A computed
9
- * column is declared in `.computed()`, where its row is read-only.
6
+ * A schema entity's columns, each an `f` builder. A foreign key's target is a relation in `.relations()`, read lazily:
7
+ * a column naming its target here would read it while it is still being inferred. A computed column is declared in
8
+ * `.computed()`, where its row is read-only.
10
9
  */
11
10
  export type SchemaFields = {
12
11
  readonly [key: string]: Column<{
@@ -38,10 +37,16 @@ export type ColumnRow<F, Nullable extends keyof F = FlagKeys<F, Column<{
38
37
  } & {
39
38
  -readonly [K in Nullable]?: ColumnValueOf<F[K]> | null;
40
39
  };
41
- /** The computed columns as a row reads them, never written. */
42
- type ComputedRow<C> = {
43
- readonly [K in keyof C]?: ColumnValueOf<C[K]> | NullOf<ColumnOptionsOf<C[K]>>;
40
+ /** A map of fields as a row reads them, never written: required, except an `eager(false)` column, which may be absent. */
41
+ type ReadRow<M> = {
42
+ readonly [K in keyof M as IsEager<M[K]> extends true ? K : never]-?: FieldValue<M[K]>;
43
+ } & {
44
+ readonly [K in keyof M as IsEager<M[K]> extends true ? never : K]?: FieldValue<M[K]>;
44
45
  };
46
+ type FieldValue<F> = F extends RelationAggregate<infer V> ? V : ColumnValueOf<F> | NullOf<ColumnOptionsOf<F>>;
47
+ type IsEager<F> = F extends RelationAggregate<unknown> ? true : ColumnOptionsOf<F> extends {
48
+ readonly eager: false;
49
+ } ? false : true;
45
50
  /** What `.computed()` returns: columns the database computes, `f.string().as(sql`...`)`. */
46
51
  type SchemaComputed = {
47
52
  readonly [key: string]: Column<{
@@ -64,27 +69,38 @@ type AggregateRefs<R> = {
64
69
  readonly columns?: infer Columns;
65
70
  } ? RelationRef<Columns> : never;
66
71
  };
67
- /** The aggregates as a row reads them, each a computed column typed by the value it reads, never written. */
68
- export type AggregateRow<A> = {
69
- readonly [K in keyof A]?: A[K] extends () => RelationAggregate<infer V> ? V : never;
70
- };
71
72
  type RelationValue<P> = P extends () => SchemaRelation<infer T, infer C, unknown> ? C extends '1m' | 'mm' ? T[] : T : never;
73
+ /** A relation's derived field as its callback declares it: a thunk, so it is read lazily like a relation is. */
74
+ export type DerivedFields = {
75
+ readonly [key: string]: () => RelationAggregate<unknown> | Column<{
76
+ readonly computed: QuerySql;
77
+ }>;
78
+ };
79
+ /** The derived fields a `relations` callback declares, as a row reads them, never written. */
80
+ export type DerivedRow<A> = {
81
+ readonly [K in keyof A]-?: A[K] extends () => infer F ? FieldValue<F> : never;
82
+ };
72
83
  /** The relations as a row reads them; exported, as a schema's emitted declaration names it. */
73
84
  export type RelationRow<R> = {
74
85
  -readonly [K in keyof R]?: RelationValue<R[K]>;
75
86
  };
76
- /** The brands the type level reads keys off, derived from the columns rather than written by hand. */
77
- export type Brands<F> = {
78
- readonly [idKey]?: FlagKeys<F, Column<{
79
- readonly isId: true;
80
- }>>;
81
- readonly [versionKey]?: FlagKeys<F, Column<{
82
- readonly version: true;
83
- }>>;
84
- readonly [filledKey]?: Exclude<FlagKeys<F, Column<FilledOptions>>, FlagKeys<F, Column<{
85
- readonly isId: true;
86
- }>>>;
87
+ /**
88
+ * The brands the type level reads keys off, derived from the columns rather than written by hand. A subtype's
89
+ * brands add to its base's, since an intersection with them would narrow each to what the subtype declares.
90
+ */
91
+ export type Brands<F, B = object> = {
92
+ readonly [idKey]?: IdKeyOf<F> | BrandNames<B, typeof idKey>;
93
+ readonly [versionKey]?: VersionKeyOf<F> | BrandNames<B, typeof versionKey>;
94
+ readonly [filledKey]?: FilledKeyOf<F> | BrandNames<B, typeof filledKey>;
87
95
  };
96
+ /** The keys of `F` a brand marks, read off its columns: the id, the version, and the fields a default fills. */
97
+ type IdKeyOf<F> = FlagKeys<F, Column<{
98
+ readonly isId: true;
99
+ }>>;
100
+ type VersionKeyOf<F> = FlagKeys<F, Column<{
101
+ readonly version: true;
102
+ }>>;
103
+ type FilledKeyOf<F> = Exclude<FlagKeys<F, Column<FilledOptions>>, IdKeyOf<F>>;
88
104
  /** The relation constructors a schema's `relations` receives, typed by the columns of the entity declaring them. */
89
105
  export type RelationBuilder<O> = {
90
106
  oneToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & SchemaShape<K, Columns>, opts: RelationOwnerOptions<T, O, SchemaJoins<T, O, K, Columns>> | RelationInverseOptions<T, SchemaJoins<T, O, K, Columns>>): SchemaRelation<T, '11'>;
@@ -125,26 +141,13 @@ export type SchemaEntityOptions<F extends SchemaFields, B = object, BK = unknown
125
141
  };
126
142
  /** A hook a schema runs on a row; a promise it returns is awaited. */
127
143
  type SchemaHook<Row> = (row: Row, ctx: HookContext) => unknown;
128
- /**
129
- * Each foreign key column's target, `{ authorId: () => Author }`, or with its delete action. The getter is typed as
130
- * returning nothing: typing its target would read an entity referencing itself while it is inferred, so the key's
131
- * kind is checked on first read.
132
- */
133
- type SchemaReferences<Columns> = {
134
- readonly [K in keyof Columns]?: LazyTarget | {
135
- readonly entity: LazyTarget;
136
- readonly onDelete?: ForeignKeyAction;
137
- };
138
- };
139
- /** The entity a foreign key points at, read once every entity exists. */
140
- type LazyTarget = () => void;
141
144
  /**
142
145
  * What a schema declares after its columns, each section typed by the columns now fixed, so none is inferred
143
146
  * again. `relations` comes last but for `filters`, which reads the row they complete.
144
147
  */
145
148
  type SchemaSections<Row, Key, Columns, B, Abstract> = {
146
149
  /** Columns the database computes off the stored ones, `(post) => ({ slug: f.string().as(sql`...`) })`. */
147
- computed<const C extends SchemaComputed>(computed: (refs: RefMap<Columns>) => C): SchemaEntity<Row & ComputedRow<C>, Key, Columns & ComputedRow<C>, B, Abstract>;
150
+ computed<const C extends SchemaComputed>(computed: (refs: RefMap<Columns>) => C): SchemaEntity<Row & ReadRow<C>, Key, Columns & ReadRow<C>, B, Abstract>;
148
151
  indexes(indexes: IndexSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
149
152
  checks(checks: CheckSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
150
153
  triggers(triggers: TriggerSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
@@ -153,13 +156,11 @@ type SchemaSections<Row, Key, Columns, B, Abstract> = {
153
156
  hooks(hooks: {
154
157
  readonly [E in HookEvent]?: readonly SchemaHook<Row>[];
155
158
  }): SchemaEntity<Row, Key, Columns, B, Abstract>;
156
- /** The foreign keys no relation joins on, each column's target: `{ authorId: () => Author }`. */
157
- references(references: SchemaReferences<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
158
159
  /**
159
160
  * The relations, each read lazily so entities pointing at each other declare in either order, and the values
160
- * read over the to-many ones, its base's too: `(agg) => ({ postCount: () => agg.posts.count() })`.
161
+ * read over the to-many ones, its base's too: `(author) => ({ postCount: () => author.posts.count() })`.
161
162
  */
162
- relations<const R, const A = {}>(relations: (rel: RelationBuilder<Columns>) => R, aggregates?: (agg: AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): RelatedEntity<Row & RelationRow<R> & AggregateRow<A>, Key, Columns, Abstract>;
163
+ relations<const R, const A extends DerivedFields = {}>(relations: (rel: RelationBuilder<Columns>) => R, derived?: (refs: RefMap<Columns> & AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): RelatedEntity<Row & RelationRow<R> & DerivedRow<A>, Key, Columns, Abstract>;
163
164
  };
164
165
  /** A schema entity's class once its relations are in: its filters may follow, and read through them. */
165
166
  export type RelatedEntity<Row, Key, Columns, Abstract = false> = SchemaClass<Row, Key, Columns, Abstract> & {
@@ -187,8 +188,4 @@ type SchemaShape<Key, Columns = unknown> = {
187
188
  export type SchemaKey<F, Inherited = unknown> = string extends keyof F ? unknown : FlagKeys<F, Column<{
188
189
  readonly isId: true;
189
190
  }>> extends infer K extends keyof F ? [K] extends [never] ? Inherited : true extends IsUnion<K> ? never : ColumnValueOf<F[K]> : never;
190
- /** The columns of `O` holding a `V`: a foreign key to a key of that type. */
191
- type KeyHolding<O, V> = {
192
- [K in keyof O]-?: NonNullable<O[K]> extends V ? K : never;
193
- }[keyof O];
194
191
  export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The Standard Schema interface (standardschema.dev, v1), vendored as types so no schema library is a dependency. Zod,
3
+ * Valibot and ArkType implement it, and a payload is typed by its output.
4
+ */
5
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
6
+ readonly '~standard': {
7
+ readonly version: 1;
8
+ readonly vendor: string;
9
+ readonly validate: (value: unknown) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>;
10
+ readonly types?: {
11
+ readonly input: Input;
12
+ readonly output: Output;
13
+ } | undefined;
14
+ };
15
+ }
16
+ /** A validation's outcome: the value it accepts, or the issues it found. */
17
+ export type StandardSchemaV1Result<Output> = {
18
+ readonly value: Output;
19
+ readonly issues?: undefined;
20
+ } | {
21
+ readonly issues: readonly StandardSchemaV1Issue[];
22
+ };
23
+ export interface StandardSchemaV1Issue {
24
+ readonly message: string;
25
+ readonly path?: readonly (PropertyKey | {
26
+ readonly key: PropertyKey;
27
+ })[] | undefined;
28
+ }
@@ -0,0 +1 @@
1
+ export {};