uql-orm 0.105.1 → 0.106.1

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 (36) hide show
  1. package/dist/browser/uql-browser.min.js.map +1 -1
  2. package/dist/entity/columnOptionsBuilder.d.ts +3 -3
  3. package/dist/entity/columnOptionsBuilder.js +3 -5
  4. package/dist/entity/decorator/members.d.ts +1 -1
  5. package/dist/entity/metadata/definition.d.ts +5 -3
  6. package/dist/entity/metadata/definition.js +67 -84
  7. package/dist/entity/metadata/schemaFixture/animal.d.ts +17 -5
  8. package/dist/entity/metadata/schemaFixture/author.d.ts +10 -10
  9. package/dist/entity/metadata/schemaFixture/author.js +3 -3
  10. package/dist/entity/metadata/schemaFixture/book.d.ts +20 -20
  11. package/dist/migrate/builder/types.d.ts +5 -7
  12. package/dist/migrate/cli.js +13 -13
  13. package/dist/migrate/generator/definitionToNode.d.ts +1 -1
  14. package/dist/migrate/generator/definitionToNode.js +4 -8
  15. package/dist/mongodb/mongoIntrospector.d.ts +1 -1
  16. package/dist/mongodb/mongoSchemaGenerator.js +4 -7
  17. package/dist/pglite/pgliteQuerierPool.d.ts +2 -2
  18. package/dist/schema/schemaASTBuilder.js +6 -12
  19. package/dist/sqlite/localSqliteQuerierPool.d.ts +3 -2
  20. package/dist/type/column.d.ts +21 -20
  21. package/dist/type/entity.d.ts +51 -64
  22. package/dist/type/index.d.ts +1 -0
  23. package/dist/type/index.js +1 -0
  24. package/dist/type/query.d.ts +1 -1
  25. package/dist/type/schemaEntity.d.ts +42 -45
  26. package/dist/type/standardSchema.d.ts +28 -0
  27. package/dist/type/standardSchema.js +1 -0
  28. package/dist/type/utility.d.ts +21 -32
  29. package/dist/type/vector.d.ts +4 -4
  30. package/dist/util/ddlExpression.util.d.ts +6 -6
  31. package/dist/util/ddlExpression.util.js +11 -5
  32. package/dist/util/fieldOption.util.js +1 -1
  33. package/dist/util/sql.d.ts +1 -3
  34. package/dist/util/sql.js +0 -4
  35. package/package.json +1 -1
  36. package/skills/uql-orm/SKILL.md +25 -10
@@ -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 {};
@@ -22,9 +22,8 @@ export type QueryComparableScalar = string | number | bigint | Date;
22
22
  */
23
23
  export type PrimaryKey = string | number | bigint;
24
24
  /**
25
- * Brands a JSON field, `settings?: Json<{ isArchived?: boolean }>`, so it reads as a field rather than a
26
- * relation; `Json<T>[]` is a list of documents, and a bare `Json` holds any JSON value, under any path. A
27
- * `null` in `T` stays `null`, so a `JsonValue` type that includes it is a field that may be `null`.
25
+ * Brands a JSON field so it reads as a field rather than a relation: `settings?: Json<{ isArchived?: boolean }>`.
26
+ * A bare `Json` holds any JSON value. A `null` in `T` stays `null`, so `Json<X | null>` may be `null`.
28
27
  */
29
28
  export type Json<T extends object | string | number | boolean | null = JsonDocument> = T extends null ? null : T & JsonBrand;
30
29
  /** Any value a JSON column holds, which a bare {@link Json} stands for. */
@@ -36,7 +35,9 @@ declare const json: unique symbol;
36
35
  export interface JsonBrand {
37
36
  readonly [json]?: never;
38
37
  }
39
- /** Whether `T` carries the {@link Json} brand: a primitive matches `Json<infer P>` too, so the key is what tells. */
38
+ /**
39
+ * Whether `T` carries the {@link Json} brand. A primitive matches `Json<infer P>` too, so the key tells.
40
+ */
40
41
  export type IsJson<T> = typeof json extends keyof T ? true : false;
41
42
  export type ExpandScalar<T> = T extends Date ? Date | string : T;
42
43
  /**
@@ -54,44 +55,32 @@ export type IsEqual<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => (T e
54
55
  export type Writable<T> = {
55
56
  -readonly [K in keyof T]: T[K];
56
57
  };
57
- /**
58
- * `Omit` whose key has to exist, which distributes over a union rather than flattening it, and removes
59
- * a key from a type with an index signature.
60
- *
61
- * `Omit<T, K>` is `Pick<T, Exclude<keyof T, K>>`; its `K extends keyof any` admits any string, so a typo
62
- * (`Omit<Post, 'titl'>`) compiles and silently drops nothing. `Except` requires `K extends keyof T`, so a
63
- * misspelled key is a compile error the instant it is written.
64
- *
65
- * Beyond the key check, the two differ structurally. `Omit` computes `keyof (A | B)` (the common keys),
66
- * then `Pick`s from that flat set, so `Omit<A | B, 'x'>` loses every key unique to one arm. `Except` is a
67
- * homomorphic mapped type over `T`, which TypeScript distributes over unions: `Except<A | B, 'x'>` is
68
- * `Except<A, 'x'> | Except<B, 'x'>`, each arm keeping its own keys. It also preserves index signatures
69
- * and property modifiers that `Pick` over a computed key set drops.
70
- */
58
+ /** `Omit` whose key must exist and that distributes over unions. See architecture/type-helpers.md. */
71
59
  export type Except<T, K extends keyof T> = {
72
60
  [P in keyof T as P extends K ? never : P]: T[P];
73
61
  };
62
+ /** `T` with each key of `B` replaced by `B`'s: `Except` on the keys both share, then `B` added. */
63
+ export type Merge<A, B> = Except<A, keyof A & keyof B> & B;
64
+ /** Every key any member of a union has, where `keyof` keeps only the ones they share. */
65
+ type KeysOfUnion<T> = T extends unknown ? keyof T : never;
74
66
  /**
75
67
  * Exactly one key of `T` with its value; every other key is forbidden (`never`). `Pick`, not `Record`,
76
- * so the chosen key stays linked to `T`'s own property and renames follow it through.
68
+ * so the chosen key stays linked to `T`'s own property and renames follow it through. Distributes over a
69
+ * union, so each arm keeps its own keys and forbids the others'.
77
70
  */
78
- export type ExactlyOne<T> = {
79
- [K in keyof T]: Readonly<Pick<T, K>> & Partial<Readonly<Record<Exclude<keyof T, K>, never>>>;
80
- }[keyof T];
71
+ export type ExactlyOne<T> = ExactlyOneOf<T, KeysOfUnion<T>>;
72
+ type ExactlyOneOf<T, Keys extends PropertyKey> = T extends unknown ? {
73
+ [K in keyof T]: Readonly<Pick<T, K>> & Partial<Readonly<Record<Exclude<Keys, K>, never>>>;
74
+ }[keyof T] : never;
81
75
  /**
82
76
  * At least one key of `T` with its value, the rest optional: the looser sibling of {@link ExactlyOne},
83
77
  * for options that combine but cannot all be left out. `Pick`, so every key stays linked to `T`'s own
84
- * property and renames follow it through.
78
+ * property and renames follow it through. Distributes over a union for the same reason.
85
79
  */
86
- export type AtLeastOne<T> = Partial<T> & {
87
- [K in keyof T]: Pick<T, K>;
88
- }[keyof T];
80
+ export type AtLeastOne<T> = T extends unknown ? {
81
+ [K in keyof T]-?: Required<Pick<T, K>>;
82
+ }[keyof T] & Partial<T> : never;
89
83
  export type Unpacked<T> = T extends readonly (infer U)[] ? U : T extends (...args: unknown[]) => infer U ? U : T extends Promise<infer U> ? U : T;
90
- /**
91
- * Whether the value a property holds is many rather than one: a to-many relation, a scalar array, a
92
- * vector. Every array test in the type layer goes through this, because writing one by hand gets some
93
- * part of it wrong in ways nothing reports. `isMany.test-d.ts` has one case per part, and says what
94
- * each is load-bearing for.
95
- */
84
+ /** Whether a property holds many values, not one. See architecture/type-helpers.md. */
96
85
  export type IsMany<V> = [NonNullable<V>] extends [readonly unknown[]] ? true : false;
97
86
  export {};
@@ -45,13 +45,13 @@ export declare function unsupportedVectorMetric(engine: EngineName, distance: Ve
45
45
  */
46
46
  export type VectorIndexOptions = {
47
47
  /** Distance metric for vector indexes - maps to operator class. */
48
- distance?: VectorDistance;
48
+ readonly distance?: VectorDistance;
49
49
  /** HNSW: max connections per node. */
50
- m?: number;
50
+ readonly m?: number;
51
51
  /** HNSW: construction search depth. */
52
- efConstruction?: number;
52
+ readonly efConstruction?: number;
53
53
  /** IVFFlat: number of inverted lists. */
54
- lists?: number;
54
+ readonly lists?: number;
55
55
  };
56
56
  /** The metric a search or an index measures by where nothing names one: every engine with vectors has it. */
57
57
  export declare const DEFAULT_VECTOR_DISTANCE: VectorDistance;
@@ -1,5 +1,5 @@
1
1
  import type { CheckSchema, EnumValues } from '../schema/types.js';
2
- import type { EntityIndexMeta, EntityMeta, IndexEntry, QuerySql } from '../type/index.js';
2
+ import type { EntityIndexMeta, EntityMeta, IndexEntry, IndexKnobs, IndexSchema, QuerySql } from '../type/index.js';
3
3
  /**
4
4
  * Every index an entity declares: each `index()` or `unique()` column as the one-column
5
5
  * index it is, then its `indexes`. A unique column is a unique index, the one spelling of uniqueness
@@ -7,13 +7,13 @@ import type { EntityIndexMeta, EntityMeta, IndexEntry, QuerySql } from '../type/
7
7
  */
8
8
  export declare function declaredIndexes<E>(meta: EntityMeta<E>): EntityIndexMeta<E>[];
9
9
  /**
10
- * An index's rendered predicate and the name it is created by, settled together: `render` gets the name without the
10
+ * An index as the schema holds it, its entries' SQL rendered by `renderSql`. `renderWhere` gets the name without the
11
11
  * predicate's hash to label its errors, then the name takes the hash of what it rendered.
12
12
  */
13
- export declare function namedIndex(name: string | undefined, table: string, entries: readonly IndexEntry<unknown>[], render: (label: string) => string | undefined, unique?: boolean): {
14
- readonly name: string;
15
- readonly where: string | undefined;
16
- };
13
+ export declare function renderIndex(table: string, { entries, unique, ...index }: IndexKnobs & {
14
+ readonly entries: readonly IndexEntry[];
15
+ readonly include?: readonly string[];
16
+ }, renderSql: (sql: QuerySql) => string, renderWhere: (label: string) => string | undefined, uniqueName?: boolean): IndexSchema;
17
17
  /**
18
18
  * The name an index is created and read by: its own, else one derived from its table, entries, uniqueness and
19
19
  * rendered predicate. A caller renders the predicate first, since an unnamed partial index's name carries its hash.
@@ -1,4 +1,4 @@
1
- import { indexEntryNamePart } from './indexEntry.util.js';
1
+ import { indexEntryNamePart, renderIndexColumn } from './indexEntry.util.js';
2
2
  import { definedEntries } from './object.util.js';
3
3
  import { sql } from './sql.js';
4
4
  import { derivedIndexName, ownedName } from './sql.util.js';
@@ -20,12 +20,18 @@ export function declaredIndexes(meta) {
20
20
  return [...fieldIndexes, ...(meta.indexes ?? [])];
21
21
  }
22
22
  /**
23
- * An index's rendered predicate and the name it is created by, settled together: `render` gets the name without the
23
+ * An index as the schema holds it, its entries' SQL rendered by `renderSql`. `renderWhere` gets the name without the
24
24
  * predicate's hash to label its errors, then the name takes the hash of what it rendered.
25
25
  */
26
- export function namedIndex(name, table, entries, render, unique) {
27
- const where = render(declaredIndexName(name, table, entries, { unique }));
28
- return { name: declaredIndexName(name, table, entries, { unique, where }), where };
26
+ export function renderIndex(table, { entries, unique = false, ...index }, renderSql, renderWhere, uniqueName) {
27
+ const where = renderWhere(declaredIndexName(index.name, table, entries, { unique: uniqueName }));
28
+ return {
29
+ ...index,
30
+ name: declaredIndexName(index.name, table, entries, { unique: uniqueName, where }),
31
+ where,
32
+ entries: entries.map((entry) => renderIndexColumn(entry, renderSql)),
33
+ unique,
34
+ };
29
35
  }
30
36
  /**
31
37
  * The name an index is created and read by: its own, else one derived from its table, entries, uniqueness and
@@ -16,7 +16,7 @@ const FIELD_OPTION_FAMILY = {
16
16
  references: '*',
17
17
  onDelete: '*',
18
18
  enum: '*',
19
- shape: 'json',
19
+ schema: 'json',
20
20
  computed: '*',
21
21
  stored: '*',
22
22
  updatable: '*',
@@ -1,4 +1,4 @@
1
- import { ColumnRef, type IndexRefMap, QuerySql, type QuerySqlFn, type ComputedRefs, type RefMap, type RelationRef, type SqlArg, type SqlStatement, type SqlValueName, type TriggerRowName, type AbstractType } from '../type/index.js';
1
+ import { ColumnRef, type IndexRefMap, QuerySql, type QuerySqlFn, type ComputedRefs, type RefMap, type SqlArg, type SqlStatement, type SqlValueName, type TriggerRowName, type AbstractType } from '../type/index.js';
2
2
  /**
3
3
  * Raw SQL, where an interpolated value binds, a `refs` field renders its column, and a `sql` renders
4
4
  * in place: `sql`GREATEST(0, ${user.credits} - ${amount})``. A callback writes whatever it writes, so
@@ -43,8 +43,6 @@ export declare function refs<E>(entity: AbstractType<E>): RefMap<E>;
43
43
  * sees no class, so these name no entity and resolve against the one rendering them.
44
44
  */
45
45
  export declare function memberRefs<E>(): ComputedRefs<E>;
46
- /** Each to-many as a schema's aggregates read it, by key: the same refs {@link memberRefs} gives a decorated entity. */
47
- export declare function relationRefs(): Readonly<Record<string, RelationRef<object>>>;
48
46
  /**
49
47
  * The refs an index's callbacks read: each field's column, a JSON one also read into along its paths,
50
48
  * `(user) => [user.settings.theme]`. Named for no entity, as {@link memberRefs} are.
package/dist/util/sql.js CHANGED
@@ -105,10 +105,6 @@ function refMap(ref) {
105
105
  export function memberRefs() {
106
106
  return refMap(memberRef);
107
107
  }
108
- /** Each to-many as a schema's aggregates read it, by key: the same refs {@link memberRefs} gives a decorated entity. */
109
- export function relationRefs() {
110
- return refMap(memberRef);
111
- }
112
108
  /**
113
109
  * The refs an index's callbacks read: each field's column, a JSON one also read into along its paths,
114
110
  * `(user) => [user.settings.theme]`. Named for no entity, as {@link memberRefs} are.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.105.1",
6
+ "version": "0.106.1",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -77,9 +77,9 @@ export class Post {
77
77
  }
78
78
  ```
79
79
 
80
- - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal()`, `f.decimal(precision)`, `f.decimal(precision, scale)`, `f.boolean()`, `f.date()`, `f.json(shape?)`, `f.jsonb(shape?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other column type, and `f.references(() => Target)` for a foreign key, which takes the target's key type. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A bound holds in either order around `.columnType('char')`, but not around a `sql` type, which carries its own.
80
+ - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal()`, `f.decimal(precision)`, `f.decimal(precision, scale)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other column type, and `f.references(() => Target)` for a foreign key, which takes the target's key type. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A bound holds in either order around `.columnType('char')`, but not around a `sql` type, which carries its own.
81
81
  - A column is NOT NULL unless `.nullable()`; its property then admits `null` (`title?: string | null`).
82
- - Declare a NOT NULL column with `!` (`email!: string`). Declare `?` for anything else an insert may omit: nullable, `.eager(false)`, computed fields and relations. uql fills a single-column key and a version.
82
+ - Declare a NOT NULL column with `!` (`email!: string`). Declare `?` for anything else an insert may omit: nullable columns, `.eager(false)` fields, and relations. A computed field is present on a default read, so it is not optional. uql fills a single-column key and a version.
83
83
  - A NOT NULL field a default fills (`.default()`, `.onInsert()`) is `!` and listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
84
84
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included.
85
85
  - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring indexes, filters, checks or triggers but no table is `@Entity({ abstract: true, ... }) abstract class`, or a schema's `abstract: true`. A query or write on one does not compile: query the entities extending it.
@@ -99,17 +99,30 @@ The same entities declared as data, the row type derived:
99
99
 
100
100
  ```ts
101
101
  import { defineEntity, f, sql } from 'uql-orm';
102
+ import { z } from 'zod';
103
+
104
+ // Any Standard Schema types the payload: a Zod schema here.
105
+ const Settings = z.object({ theme: z.string(), bio: z.string().optional() });
102
106
 
103
107
  export const Author = defineEntity({
104
108
  name: 'Author',
105
109
  fields: {
106
110
  id: f.number().id(),
107
111
  name: f.string(),
108
- settings: f.json({ theme: String, 'bio?': String }).nullable(),
112
+ settings: f.json(Settings).nullable(),
109
113
  },
110
114
  }).relations(
111
115
  (rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }),
112
- (agg) => ({ bookCount: () => agg.books.count(), topStock: () => agg.books.max((book) => book.stock) }),
116
+ (author) => ({
117
+ bookCount: () => author.books.count(),
118
+ topStock: () => author.books.max((book) => book.stock),
119
+ // A derived field may also combine its own columns with an aggregate in one expression.
120
+ stockGap: () =>
121
+ f
122
+ .number()
123
+ .nullable()
124
+ .as(sql`${author.books.max((book) => book.stock)} - ${author.id}`),
125
+ }),
113
126
  );
114
127
  export type Author = InstanceType<typeof Author>;
115
128
 
@@ -126,16 +139,18 @@ export const Book = defineEntity({
126
139
  .computed((book) => ({ shout: f.string().as(sql`upper(${book.title})`) }))
127
140
  .indexes((book, index) => [index([book.title])])
128
141
  .hooks({ beforeInsert: [(book) => void (book.stock ??= 0)] })
129
- .references({ editorId: { entity: () => Author, onDelete: 'SET NULL' } })
130
- .relations((rel) => ({ author: () => rel.manyToOne(Author, { references: (book) => book.authorId }) }));
142
+ .relations((rel) => ({
143
+ author: () => rel.manyToOne(Author, { references: (book) => book.authorId }),
144
+ editor: () => rel.manyToOne(Author, { references: (book) => book.editorId, onDelete: 'SET NULL' }),
145
+ }));
131
146
  ```
132
147
 
133
148
  - Each field is a column builder, as in the decorated form. The row follows from them: a key, a version and a NOT NULL column are always present, a `.nullable()` one reads `| null`; a default (`.default()`, `.onInsert()`, `.autoIncrement()`) makes it optional on insert; `f.enum()` gives the literal union. No `!`, `?` or brands to write.
134
- - The other options are sections chained after `defineEntity`, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters` and `hooks` read the columns; `references` points a foreign key with no relation at its target; `relations` comes last, but for a `filters` that reads through them: `.relations(...).filters({ byActiveAuthor: { where: { author: { active: true } } } })`. `defineEntity` itself takes `name` (the class name, which a naming strategy derives the table from), `table`, `schema`, `extends` and `fields`.
135
- - Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. `manyToOne` names its `references`; `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
136
- - `relations`' second callback reads values over a to-many as columns: `(agg) => ({ bookCount: () => agg.books.count() })`.
149
+ - The other options are sections chained after `defineEntity`, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters` and `hooks` read the columns; `relations` comes last, but for a `filters` that reads through them: `.relations(...).filters({ byActiveAuthor: { where: { author: { active: true } } } })`. `defineEntity` itself takes `name` (the class name, which a naming strategy derives the table from), `table`, `schema`, `extends` and `fields`.
150
+ - Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. A schema's foreign key is a relation: `manyToOne` names its `references` column, whose type is checked against the target's key; the column itself stays a plain field. `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
151
+ - `relations`' second callback declares the derived fields: each value is a thunk, read lazily, of an aggregate over a to-many (`() => author.books.count()`) or a column expression. The callback's refs are the entity's own columns and its relations, so one expression can combine them.
137
152
  - A hook is a function of the row and `{ querier, onCommit }`.
138
- - A JSON column's payload is its shape, `f.json(shape)`: `String`, `Number` or `Boolean`, an object of shapes, `[shape]` for an array, `'key?'` for an optional member. Without one, any path reads.
153
+ - A JSON column's payload is a Standard Schema, `f.json(schema)`, typed by its output: any library's schema (Zod, Valibot, ArkType), or a hand-written `StandardSchemaV1`. Without one, any path reads. The schema types the column; uql never runs it, so a write is not validated.
139
154
  - Behaviour is a function of the row, `label(author: Author)`: a row reads back as a plain object, so a method would never be there.
140
155
 
141
156
  ## Queries