uql-orm 0.106.1 → 0.107.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 (32) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/uql-browser.min.js.map +1 -1
  3. package/dist/dialect/abstractSqlDialect.js +3 -3
  4. package/dist/entity/decorator/bag.d.ts +1 -1
  5. package/dist/entity/metadata/{schemaFixture → definedFixture}/animal.d.ts +2 -2
  6. package/dist/entity/metadata/{schemaFixture → definedFixture}/author.d.ts +2 -2
  7. package/dist/entity/metadata/{schemaFixture → definedFixture}/book.d.ts +4 -4
  8. package/dist/entity/metadata/definition.d.ts +18 -8
  9. package/dist/entity/metadata/definition.js +59 -38
  10. package/dist/migrate/codegen/fieldOptionsSource.js +8 -1
  11. package/dist/mongodb/mongoDialect.d.ts +0 -1
  12. package/dist/mongodb/mongoDialect.js +4 -7
  13. package/dist/mssql/mssqlDialect.js +5 -5
  14. package/dist/querier/abstractSqlQuerier.js +3 -3
  15. package/dist/schema/declaredColumn.d.ts +1 -1
  16. package/dist/schema/declaredColumn.js +1 -1
  17. package/dist/schema/schemaASTBuilder.js +3 -3
  18. package/dist/sqlite/sqliteQuerier.d.ts +1 -1
  19. package/dist/type/column.d.ts +3 -3
  20. package/dist/type/{schemaEntity.d.ts → definedEntity.d.ts} +45 -45
  21. package/dist/type/entity.d.ts +9 -7
  22. package/dist/type/index.d.ts +1 -1
  23. package/dist/type/index.js +1 -1
  24. package/dist/type/query.d.ts +1 -1
  25. package/dist/util/field.util.d.ts +4 -6
  26. package/dist/util/field.util.js +5 -9
  27. package/package.json +7 -7
  28. package/skills/uql-orm/SKILL.md +42 -6
  29. /package/dist/entity/metadata/{schemaFixture → definedFixture}/animal.js +0 -0
  30. /package/dist/entity/metadata/{schemaFixture → definedFixture}/author.js +0 -0
  31. /package/dist/entity/metadata/{schemaFixture → definedFixture}/book.js +0 -0
  32. /package/dist/type/{schemaEntity.js → definedEntity.js} +0 -0
@@ -4,6 +4,7 @@ import { AGGREGATE_VALUE_ALIAS, REL_NESTED_KEY, REL_FIELD_PREFIX, relTempField,
4
4
  import { betweenBounds, inOperands, GROUP_OPS, groupClauses, isGroupOp, LIKE_OPS, likeRegex, whereOperators, sizeComparisons, } from '../dialect/operators.js';
5
5
  import { aggregateColumnField, groupPathField, resolveGroupJoins, relationSortTerms, resolveQueryJoins, resolveSortableJoin, } from '../dialect/queryJoins.js';
6
6
  import { assertSoleId, fieldOf, getMeta, relationOf, soleIdOf } from '../entity/index.js';
7
+ import { referenceKeys } from '../entity/metadata/definition.js';
7
8
  import { COUNT_RESULT_KEY } from '../type/query.js';
8
9
  import { QuerySql } from '../type/querySql.js';
9
10
  import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, foldJson, writesKeys, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetJoins, textSortOf, indexedDistance, vectorDistanceOf, vectorCandidates, populatesRelations, cachedIn, } from '../util/index.js';
@@ -1085,12 +1086,8 @@ export class MongoDialect extends AbstractDialect {
1085
1086
  meta: getMeta(relation.entity()),
1086
1087
  })));
1087
1088
  }
1088
- referenceKeys(meta) {
1089
- return cachedIn(this.#referenceKeys, meta, () => getKeys(meta.fields).filter((key) => meta.fields[key]?.references));
1090
- }
1091
1089
  // Keyed by the meta object itself; entity metadata is immutable once defined.
1092
1090
  #renamedColumns = new WeakMap();
1093
- #referenceKeys = new WeakMap();
1094
1091
  #relationReads = new WeakMap();
1095
1092
  normalizeIds(meta, docs) {
1096
1093
  return docs.map((doc) => this.normalizeId(meta, doc));
@@ -1118,7 +1115,7 @@ export class MongoDialect extends AbstractDialect {
1118
1115
  }
1119
1116
  }
1120
1117
  // After the rename, so a renamed reference is converted under the name the code reads.
1121
- for (const key of this.referenceKeys(meta)) {
1118
+ for (const key of referenceKeys(meta)) {
1122
1119
  if (res[key] !== undefined) {
1123
1120
  res[key] = this.fromWireId(res[key]);
1124
1121
  }
@@ -1161,7 +1158,7 @@ export class MongoDialect extends AbstractDialect {
1161
1158
  }
1162
1159
  /** Whether `key` holds ids the driver stores as `ObjectId`s: the entity's own `_id`, or a reference to one. */
1163
1160
  holdsKeys(meta, key) {
1164
- return this.pathOf(meta, key) === ID_KEY || !!meta.fields[key]?.references;
1161
+ return this.pathOf(meta, key) === ID_KEY || referenceKeys(meta).has(key);
1165
1162
  }
1166
1163
  /** Converts every operand `ops` compares a key against with {@link toWireId}, including inside a `$not`. */
1167
1164
  toWireOperands(ops) {
@@ -1241,7 +1238,7 @@ export class MongoDialect extends AbstractDialect {
1241
1238
  const field = fieldOf(meta, key);
1242
1239
  const value = it[key];
1243
1240
  assertNoRaw(value, 'a write');
1244
- doc[this.resolveColumnName(key, field)] = field.references ? this.toWireId(value) : value;
1241
+ doc[this.resolveColumnName(key, field)] = referenceKeys(meta).has(key) ? this.toWireId(value) : value;
1245
1242
  }
1246
1243
  // Keyed by column, which the driver's types read as `E`'s keys: they name the same fields.
1247
1244
  return doc;
@@ -4,12 +4,12 @@ import { BYTES_PREFIX } from '../dialect/hydrateColumn.js';
4
4
  import { skippablePath, jsonArraySlotArgs, jsonPath, jsonSlotArgs, } from '../dialect/jsonSql.js';
5
5
  import { MergeSqlDialect } from '../dialect/mergeSqlDialect.js';
6
6
  import { getMeta } from '../entity/index.js';
7
- import { soleId } from '../entity/metadata/definition.js';
7
+ import { generatesKey, soleId } from '../entity/metadata/definition.js';
8
8
  import { canonicalToSql, resolveColumnCanonicalType } from '../schema/canonicalType.js';
9
9
  import { QuerySql } from '../type/index.js';
10
10
  import { parseQueryLock } from '../type/index.js';
11
11
  import { bytesToHex } from '../util/bytes.js';
12
- import { isAutoIncrement, isExactDecimal, jsonPathKeys } from '../util/field.util.js';
12
+ import { isExactDecimal, jsonPathKeys } from '../util/field.util.js';
13
13
  import { assertNonNegativeInteger, isOperatorMap, RETURNED_ID } from '../util/index.js';
14
14
  import { escapeSingleQuotes } from '../util/sqlLiteral.js';
15
15
  import { UqlUsageError } from '../util/uqlError.js';
@@ -149,12 +149,12 @@ export class MsSqlDialect extends MergeSqlDialect {
149
149
  }
150
150
  /** The table to toggle, or nothing when no record writes a key the engine would have generated. */
151
151
  identityInsertTarget(meta, payload) {
152
- const id = soleId(meta);
153
- if (!id || !isAutoIncrement(id.field, true)) {
152
+ if (!generatesKey(meta)) {
154
153
  return undefined;
155
154
  }
155
+ const [idKey] = meta.ids;
156
156
  const records = Array.isArray(payload) ? payload : [payload];
157
- const stated = records.some((record) => record[id.key] !== undefined);
157
+ const stated = records.some((record) => record[idKey] !== undefined);
158
158
  return stated ? this.escapedTableName(meta) : undefined;
159
159
  }
160
160
  /** An exact decimal, converted before it crosses the wire, where `tedious` would round it. */
@@ -1,7 +1,7 @@
1
1
  import { AGGREGATE_VALUE_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
2
2
  import { getMeta } from '../entity/index.js';
3
- import { soleId } from '../entity/metadata/definition.js';
4
- import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf, isAutoIncrement, upsertKeepsOwnKey, } from '../util/index.js';
3
+ import { generatesKey, soleId } from '../entity/metadata/definition.js';
4
+ import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf, upsertKeepsOwnKey, } from '../util/index.js';
5
5
  import { statementOf } from '../util/sql.js';
6
6
  import { UqlUsageError } from '../util/uqlError.js';
7
7
  import { AbstractQuerier } from './abstractQuerier.js';
@@ -265,7 +265,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
265
265
  // already carry every column of it. `sole` is what keeps every id path off such a key.
266
266
  const [idKey] = meta.ids;
267
267
  const sole = soleId(meta);
268
- const generatedKey = !!sole && isAutoIncrement(sole.field, true);
268
+ const generatedKey = generatesKey(meta);
269
269
  // Per group, not per batch: the two carry different columns - one names the key, one does not - so a budget
270
270
  // taken over their union would under-fill the statement that is missing one. Header ids are only sound where
271
271
  // every row of a statement left its key to the database, so a supplied id cannot void the others.
@@ -2,7 +2,7 @@ import type { Except, FieldMeta, QuerySql } from '../type/index.js';
2
2
  import type { ColumnNode } from './types.js';
3
3
  /**
4
4
  * The column a field's options declare, whether an entity's table or a migration holds it: `soleKey` says whether it
5
- * is its table's only key, which a numeric one auto-increments as, and `compile` renders its SQL.
5
+ * is its table's whole and own key, which a numeric one auto-increments as, and `compile` renders its SQL.
6
6
  */
7
7
  export declare function declaredColumn(field: FieldMeta, { name, soleKey, compile, }: {
8
8
  readonly name: string;
@@ -3,7 +3,7 @@ import { resolveColumnCanonicalType } from './canonicalType.js';
3
3
  import { schemaDefault } from './sqlExpression.js';
4
4
  /**
5
5
  * The column a field's options declare, whether an entity's table or a migration holds it: `soleKey` says whether it
6
- * is its table's only key, which a numeric one auto-increments as, and `compile` renders its SQL.
6
+ * is its table's whole and own key, which a numeric one auto-increments as, and `compile` renders its SQL.
7
7
  */
8
8
  export function declaredColumn(field, { name, soleKey, compile, }) {
9
9
  return {
@@ -1,7 +1,7 @@
1
- import { fieldOf, foreignKeysOf, getMeta } from '../entity/metadata/definition.js';
1
+ import { fieldOf, foreignKeysOf, getMeta, ownsSoleKey } from '../entity/metadata/definition.js';
2
2
  import { declaredIndexes, enumCheck, ownedCheck, renderIndex } from '../util/ddlExpression.util.js';
3
3
  import { fulltextWeights, textWeightSteps } from '../util/dialect.util.js';
4
- import { isInlinedExpression, isSoleIdField } from '../util/field.util.js';
4
+ import { isInlinedExpression } from '../util/field.util.js';
5
5
  import { entryColumn, entryColumns, renamedEntry } from '../util/indexEntry.util.js';
6
6
  import { definedEntries, entityName } from '../util/object.util.js';
7
7
  import { derivedForeignKeyName, derivedIndexName } from '../util/sql.util.js';
@@ -68,7 +68,7 @@ function addTableFromEntity(ctx, meta) {
68
68
  const column = {
69
69
  ...declaredColumn(field, {
70
70
  name: columnName,
71
- soleKey: isSoleIdField(meta, field),
71
+ soleKey: ownsSoleKey(meta, key),
72
72
  compile: (sql) => ctx.compileDdl(sql, meta.entity),
73
73
  }),
74
74
  ...(notNull.has(key) && { nullable: false }),
@@ -38,8 +38,8 @@ export declare class SqliteQuerier extends AbstractSqlQuerier {
38
38
  protected get connection(): object;
39
39
  /** `reader` picks the call: `run()` would discard the rows of a statement that reads, RETURNING included. */
40
40
  protected execute(sql: string, values?: unknown[]): Promise<{
41
- changes?: undefined;
42
41
  rows: RawRow[];
42
+ changes?: undefined;
43
43
  } | {
44
44
  rows: never[];
45
45
  changes: number;
@@ -1,8 +1,8 @@
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 { ReferencedKey } from './definedEntity.js';
3
4
  import type { BlobColumnType, BooleanColumnType, ColumnType, DateColumnType, DdlDefault, JsonColumnType, NumericColumnType, StringColumnType, VectorColumnType, FieldOptions, HasCompositeKey, IdValue, JoinKind, OnFieldCallback, StampEvent } from './entity.js';
4
5
  import type { QuerySql } from './querySql.js';
5
- import type { ReferencedKey } from './schemaEntity.js';
6
6
  import type { StandardSchemaV1 } from './standardSchema.js';
7
7
  import type { Type, Json, AbstractType } from './utility.js';
8
8
  import type { VectorDistance } from './vector.js';
@@ -62,7 +62,7 @@ interface Builders<O, V> {
62
62
  readonly json: ColumnBuilder<O, V, 'json'>;
63
63
  readonly blob: ColumnBuilder<O, V, 'blob'>;
64
64
  readonly vector: VectorColumn<O, V>;
65
- /** A column whose family is known only at run time: a foreign key's is its target key's, a runtime schema's its data's. */
65
+ /** A column whose family is known only at run time: a foreign key's is its target key's, an entity defined at run time, its data's. */
66
66
  readonly any: ColumnBuilder<O, V, 'any'>;
67
67
  }
68
68
  type Family = keyof Builders<unknown, unknown>;
@@ -317,7 +317,7 @@ export type ColumnFactory = {
317
317
  column(type: BlobColumnType): ColumnBuilder<{
318
318
  readonly type: BlobColumnType;
319
319
  }, Uint8Array, 'blob'>;
320
- /** A column whose type is data, as a schema built at run time declares one. */
320
+ /** A column whose type is data, as an entity defined at run time declares one. */
321
321
  column(type: ColumnType): ColumnBuilder<{
322
322
  readonly type: ColumnType;
323
323
  }, unknown, 'any'>;
@@ -3,11 +3,11 @@ import type { BrandNames, CheckSection, FilterSection, filledKey, HookContext, H
3
3
  import type { QuerySql, RelationAggregate } from './querySql.js';
4
4
  import type { Type, AbstractType } from './utility.js';
5
5
  /**
6
- * A schema entity's columns, each an `f` builder. A foreign key's target is a relation in `.relations()`, read lazily:
6
+ * A defined entity's columns, each an `f` builder. A foreign key's target is a relation in `.relations()`, read lazily:
7
7
  * a column naming its target here would read it while it is still being inferred. A computed column is declared in
8
8
  * `.computed()`, where its row is read-only.
9
9
  */
10
- export type SchemaFields = {
10
+ export type DefinedFields = {
11
11
  readonly [key: string]: Column<{
12
12
  readonly references?: undefined;
13
13
  readonly computed?: undefined;
@@ -15,9 +15,9 @@ export type SchemaFields = {
15
15
  readonly [key: string]: unknown;
16
16
  }>;
17
17
  };
18
- /** The key a class holds: carried beside a schema's, so a cycle never reads its row; read off a decorated one's. */
18
+ /** The key a class holds: carried beside a defined one's, so a cycle never reads its row; read off a decorated one's. */
19
19
  export type ReferencedKey<C> = C extends {
20
- readonly [schemaShape]?: {
20
+ readonly [definedShape]?: {
21
21
  readonly key: infer K;
22
22
  };
23
23
  } ? unknown extends K ? RowKey<C> : K : RowKey<C>;
@@ -48,13 +48,13 @@ type IsEager<F> = F extends RelationAggregate<unknown> ? true : ColumnOptionsOf<
48
48
  readonly eager: false;
49
49
  } ? false : true;
50
50
  /** What `.computed()` returns: columns the database computes, `f.string().as(sql`...`)`. */
51
- type SchemaComputed = {
51
+ type DefinedComputed = {
52
52
  readonly [key: string]: Column<{
53
53
  readonly computed: QuerySql;
54
54
  }>;
55
55
  };
56
- /** A relation as a schema declares it: what `rel.*` returns, its target carried for the row. */
57
- export type SchemaRelation<T = object, C extends RelationCardinality = RelationCardinality, Columns = T> = {
56
+ /** A relation as a defined entity declares it: what `rel.*` returns, its target carried for the row. */
57
+ export type DefinedRelation<T = object, C extends RelationCardinality = RelationCardinality, Columns = T> = {
58
58
  readonly target: Type<T>;
59
59
  readonly cardinality: C;
60
60
  /** Checked by the builder's signature, so held erased: the registry reads them back as any relation's options. */
@@ -69,7 +69,7 @@ type AggregateRefs<R> = {
69
69
  readonly columns?: infer Columns;
70
70
  } ? RelationRef<Columns> : never;
71
71
  };
72
- type RelationValue<P> = P extends () => SchemaRelation<infer T, infer C, unknown> ? C extends '1m' | 'mm' ? T[] : T : never;
72
+ type RelationValue<P> = P extends () => DefinedRelation<infer T, infer C, unknown> ? C extends '1m' | 'mm' ? T[] : T : never;
73
73
  /** A relation's derived field as its callback declares it: a thunk, so it is read lazily like a relation is. */
74
74
  export type DerivedFields = {
75
75
  readonly [key: string]: () => RelationAggregate<unknown> | Column<{
@@ -80,7 +80,7 @@ export type DerivedFields = {
80
80
  export type DerivedRow<A> = {
81
81
  readonly [K in keyof A]-?: A[K] extends () => infer F ? FieldValue<F> : never;
82
82
  };
83
- /** The relations as a row reads them; exported, as a schema's emitted declaration names it. */
83
+ /** The relations as a row reads them; exported, as a defined entity's emitted declaration names it. */
84
84
  export type RelationRow<R> = {
85
85
  -readonly [K in keyof R]?: RelationValue<R[K]>;
86
86
  };
@@ -101,32 +101,32 @@ type VersionKeyOf<F> = FlagKeys<F, Column<{
101
101
  readonly version: true;
102
102
  }>>;
103
103
  type FilledKeyOf<F> = Exclude<FlagKeys<F, Column<FilledOptions>>, IdKeyOf<F>>;
104
- /** The relation constructors a schema's `relations` receives, typed by the columns of the entity declaring them. */
104
+ /** The relation constructors a defined entity's `relations` receives, typed by the columns of the entity declaring them. */
105
105
  export type RelationBuilder<O> = {
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'>;
107
- manyToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & SchemaShape<K, Columns>, opts: RelationOwnerOptions<T, O, SchemaJoins<T, O, K, Columns>>): SchemaRelation<T, 'm1'>;
106
+ oneToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & DefinedShape<K, Columns>, opts: RelationOwnerOptions<T, O, DefinedJoins<T, O, K, Columns>> | RelationInverseOptions<T, DefinedJoins<T, O, K, Columns>>): DefinedRelation<T, '11'>;
107
+ manyToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & DefinedShape<K, Columns>, opts: RelationOwnerOptions<T, O, DefinedJoins<T, O, K, Columns>>): DefinedRelation<T, 'm1'>;
108
108
  /** With no options, it is mapped by the one many-to-one of its target pointing back. */
109
- oneToMany<T extends object, Columns = T>(target: Type<T> & SchemaShape<unknown, Columns>, opts?: RelationInverseOptions<T, SchemaJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, SchemaJoins<T, O, unknown, Columns>>): SchemaRelation<T, '1m', Columns>;
110
- manyToMany<T extends object, Columns = T>(target: Type<T> & SchemaShape<unknown, Columns>, opts: RelationInverseOptions<T, SchemaJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, SchemaJoins<T, O, unknown, Columns>>): SchemaRelation<T, 'mm', Columns>;
109
+ oneToMany<T extends object, Columns = T>(target: Type<T> & DefinedShape<unknown, Columns>, opts?: RelationInverseOptions<T, DefinedJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, DefinedJoins<T, O, unknown, Columns>>): DefinedRelation<T, '1m', Columns>;
110
+ manyToMany<T extends object, Columns = T>(target: Type<T> & DefinedShape<unknown, Columns>, opts: RelationInverseOptions<T, DefinedJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, DefinedJoins<T, O, unknown, Columns>>): DefinedRelation<T, 'mm', Columns>;
111
111
  };
112
112
  /**
113
- * A schema's joins: a foreign key and paired columns checked by type, off the target's carried key and columns;
113
+ * A defined entity's joins: a foreign key and paired columns checked by type, off the target's carried key and columns;
114
114
  * `mappedBy` by key alone, its kind checked on first read.
115
115
  */
116
- type SchemaJoins<T, O, K = unknown, Columns = T> = {
116
+ type DefinedJoins<T, O, K = unknown, Columns = T> = {
117
117
  readonly key: KeyHolding<O, K>;
118
- readonly pairs: readonly SchemaJoinPair<O, Columns>[];
118
+ readonly pairs: readonly DefinedJoinPair<O, Columns>[];
119
119
  readonly mappedBy: keyof T;
120
120
  };
121
121
  /** One pair of join columns, the local one holding what the target's column does. */
122
- type SchemaJoinPair<O, Columns> = {
122
+ type DefinedJoinPair<O, Columns> = {
123
123
  readonly [F in keyof Columns]-?: {
124
124
  readonly local: KeyHolding<O, NonNullable<Columns[F]>>;
125
125
  readonly foreign: F;
126
126
  };
127
127
  }[keyof Columns];
128
- /** What the first call of a schema states: the class, its table and its columns. */
129
- export type SchemaEntityOptions<F extends SchemaFields, B = object, BK = unknown, BC = unknown> = {
128
+ /** What the first call of `defineEntity` states: the class, its table and its columns. */
129
+ export type DefineEntityOptions<F extends DefinedFields, B = object, BK = unknown, BC = unknown> = {
130
130
  /** The class's name, which a naming strategy derives the table's from, as it does a decorated class's. */
131
131
  readonly name: string;
132
132
  /** The table, exactly as the database names it, where it is not derived from `name`. */
@@ -136,56 +136,56 @@ export type SchemaEntityOptions<F extends SchemaFields, B = object, BK = unknown
136
136
  /** A base that is never a table: the entities extending it take what it declares. */
137
137
  readonly abstract?: true;
138
138
  /** The entity it inherits from, which the declared class extends, so its methods and `super` work. */
139
- readonly extends?: SchemaClass<B, BK, BC, boolean>;
139
+ readonly extends?: DefinedClass<B, BK, BC, boolean>;
140
140
  readonly fields: F;
141
141
  };
142
- /** A hook a schema runs on a row; a promise it returns is awaited. */
143
- type SchemaHook<Row> = (row: Row, ctx: HookContext) => unknown;
142
+ /** A hook a defined entity runs on a row; a promise it returns is awaited. */
143
+ type DefinedHook<Row> = (row: Row, ctx: HookContext) => unknown;
144
144
  /**
145
- * What a schema declares after its columns, each section typed by the columns now fixed, so none is inferred
145
+ * What a defined entity declares after its columns, each section typed by the columns now fixed, so none is inferred
146
146
  * again. `relations` comes last but for `filters`, which reads the row they complete.
147
147
  */
148
- type SchemaSections<Row, Key, Columns, B, Abstract> = {
148
+ type DefinedSections<Row, Key, Columns, B, Abstract> = {
149
149
  /** Columns the database computes off the stored ones, `(post) => ({ slug: f.string().as(sql`...`) })`. */
150
- computed<const C extends SchemaComputed>(computed: (refs: RefMap<Columns>) => C): SchemaEntity<Row & ReadRow<C>, Key, Columns & ReadRow<C>, B, Abstract>;
151
- indexes(indexes: IndexSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
152
- checks(checks: CheckSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
153
- triggers(triggers: TriggerSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
154
- filters(filters: FilterSection<Row>): SchemaEntity<Row, Key, Columns, B, Abstract>;
150
+ computed<const C extends DefinedComputed>(computed: (refs: RefMap<Columns>) => C): DefinedEntity<Row & ReadRow<C>, Key, Columns & ReadRow<C>, B, Abstract>;
151
+ indexes(indexes: IndexSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
152
+ checks(checks: CheckSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
153
+ triggers(triggers: TriggerSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
154
+ filters(filters: FilterSection<Row>): DefinedEntity<Row, Key, Columns, B, Abstract>;
155
155
  /** Functions each lifecycle event runs on the row, in order, given the querier writing it. */
156
156
  hooks(hooks: {
157
- readonly [E in HookEvent]?: readonly SchemaHook<Row>[];
158
- }): SchemaEntity<Row, Key, Columns, B, Abstract>;
157
+ readonly [E in HookEvent]?: readonly DefinedHook<Row>[];
158
+ }): DefinedEntity<Row, Key, Columns, B, Abstract>;
159
159
  /**
160
160
  * The relations, each read lazily so entities pointing at each other declare in either order, and the values
161
161
  * read over the to-many ones, its base's too: `(author) => ({ postCount: () => author.posts.count() })`.
162
162
  */
163
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>;
164
164
  };
165
- /** A schema entity's class once its relations are in: its filters may follow, and read through them. */
166
- export type RelatedEntity<Row, Key, Columns, Abstract = false> = SchemaClass<Row, Key, Columns, Abstract> & {
167
- filters(filters: FilterSection<Row>): SchemaClass<Row, Key, Columns, Abstract>;
165
+ /** A defined entity's class once its relations are in: its filters may follow, and read through them. */
166
+ export type RelatedEntity<Row, Key, Columns, Abstract = false> = DefinedClass<Row, Key, Columns, Abstract> & {
167
+ filters(filters: FilterSection<Row>): DefinedClass<Row, Key, Columns, Abstract>;
168
168
  };
169
- /** A schema entity's class while its sections may still be declared. */
170
- export type SchemaEntity<Row, Key, Columns, B, Abstract = false> = SchemaClass<Row, Key, Columns, Abstract> & SchemaSections<Row, Key, Columns, B, Abstract>;
171
- /** The class a schema declares, to use as it is or to extend with behaviour; abstract for a base never a table. */
172
- export type SchemaClass<Row, Key = unknown, Columns = unknown, Abstract = false> = (Abstract extends true ? abstract new () => Row : new () => Row) & SchemaShape<Key, Columns>;
173
- declare const schemaShape: unique symbol;
169
+ /** A defined entity's class while its sections may still be declared. */
170
+ export type DefinedEntity<Row, Key, Columns, B, Abstract = false> = DefinedClass<Row, Key, Columns, Abstract> & DefinedSections<Row, Key, Columns, B, Abstract>;
171
+ /** The class `defineEntity` declares, to use as it is or to extend with behaviour; abstract for a base never a table. */
172
+ export type DefinedClass<Row, Key = unknown, Columns = unknown, Abstract = false> = (Abstract extends true ? abstract new () => Row : new () => Row) & DefinedShape<Key, Columns>;
173
+ declare const definedShape: unique symbol;
174
174
  /**
175
- * What a relation or an aggregate pointing at a schema reads of it, its key's type and its columns, carried beside
175
+ * What a relation or an aggregate pointing at a defined entity reads of it, its key's type and its columns, carried beside
176
176
  * its class rather than read off its row: the columns alone settle both while the row is still being inferred.
177
177
  */
178
- type SchemaShape<Key, Columns = unknown> = {
179
- readonly [schemaShape]?: {
178
+ type DefinedShape<Key, Columns = unknown> = {
179
+ readonly [definedShape]?: {
180
180
  readonly key: Key;
181
181
  readonly columns: Columns;
182
182
  };
183
183
  };
184
184
  /**
185
185
  * The key's type: its own column's, else the base's it inherits, `never` for a composite, which no one column can
186
- * reference, and anything for a schema built from data, whose columns are known only at run time.
186
+ * reference, and anything for an entity defined from data, whose columns are known only at run time.
187
187
  */
188
- export type SchemaKey<F, Inherited = unknown> = string extends keyof F ? unknown : FlagKeys<F, Column<{
188
+ export type DefinedKey<F, Inherited = unknown> = string extends keyof F ? unknown : FlagKeys<F, Column<{
189
189
  readonly isId: true;
190
190
  }>> extends infer K extends keyof F ? [K] extends [never] ? Inherited : true extends IsUnion<K> ? never : ColumnValueOf<F[K]> : never;
191
191
  export {};
@@ -354,7 +354,7 @@ export type OnFieldCallback<V = unknown> = V | QuerySql | (() => V | QuerySql);
354
354
  export type DdlDefault<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonDdlDefault : [TsTypeOf<FieldType>] extends [T] ? JsonDdlDefault | T : T;
355
355
  /** What a JSON column, and the field-less `FieldOptions`, may default to: a document, a list included, or its text. */
356
356
  type JsonDdlDefault = Scalar | Record<string, unknown> | readonly unknown[];
357
- /** The TypeScript type a declared `type` implies: a decorator checks the property against it, a schema derives it. */
357
+ /** The TypeScript type a declared `type` implies: a decorator checks the property against it, a defined entity derives it. */
358
358
  export type TsTypeOf<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BigIntConstructor ? bigint : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends StringColumnType | TimeColumnType | DecimalColumnType ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? JsonBrand | readonly JsonBrand[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
359
359
  /** The entity a relation points at: `Company` for `company?: Company` and `companies?: Company[]` alike. */
360
360
  export type RelationTarget<V> = Extract<Unpacked<V>, object>;
@@ -428,7 +428,7 @@ export type RelationRegistration = Merge<RelationOptions<object>, {
428
428
  /**
429
429
  * What a relation's join callbacks answer, `E` its target and `O` the entity declaring it: one foreign key, pairs of
430
430
  * columns, or the target's member mapping it. Each form states its own: a decorated class checks each member's
431
- * kind, a schema reads keys alone, since its target's types are still being inferred.
431
+ * kind, a defined entity reads keys alone, since its target's types are still being inferred.
432
432
  */
433
433
  export type RelationJoins = {
434
434
  readonly key: unknown;
@@ -548,7 +548,7 @@ export type RelationManyToOneOptions<E, O = unknown> = RelationOwnerSide & Parti
548
548
  export type RelationManyToManyOptions<E, O = unknown> = RelationJoinOptions<E, O, DecoratedJoins<E, O>> | RelationInverseOptions<E, DecoratedJoins<E, O>>;
549
549
  /** The lifecycle events. An upsert has its own pair: which branch a row takes is the database's to decide. */
550
550
  export type HookEvent = 'beforeInsert' | 'afterInsert' | 'beforeUpdate' | 'afterUpdate' | 'beforeUpsert' | 'afterUpsert' | 'beforeDelete' | 'afterDelete' | 'afterLoad';
551
- /** A hook as declared: the entity's method a decorator names, or the function a schema runs on the row. */
551
+ /** A hook as declared: the entity's method a decorator names, or the function a defined entity runs on the row. */
552
552
  export type HookDeclaration = {
553
553
  readonly methodName: string;
554
554
  } | {
@@ -567,7 +567,7 @@ export type HookContext = {
567
567
  readonly querier: Querier;
568
568
  readonly onCommit: Querier['onCommit'];
569
569
  };
570
- /** A schema entity's hook, bivariant in its row, so one typed by its row registers. */
570
+ /** A defined entity's hook, bivariant in its row, so one typed by its row registers. */
571
571
  export type HookFunction = {
572
572
  run(row: object, ctx: HookContext): unknown;
573
573
  }['run'];
@@ -755,7 +755,7 @@ export type EntityMeta<E> = {
755
755
  } & {
756
756
  [key: string]: RelationMeta | undefined;
757
757
  };
758
- /** The indexes `@Entity({ indexes })` or a schema's `indexes` declare. */
758
+ /** The indexes `@Entity({ indexes })` or `defineEntity`'s `.indexes()` declare. */
759
759
  indexes?: EntityIndexMeta<E>[];
760
760
  /** `CHECK` constraints, compiled when the schema is built. */
761
761
  checks?: EntityCheckMeta<E>[];
@@ -764,13 +764,15 @@ export type EntityMeta<E> = {
764
764
  /** Triggers the database runs, compiled when the schema is built. */
765
765
  triggers?: EntityTriggerMeta<E>[];
766
766
  /**
767
- * How far the registry finalized it: `'declared'` while a schema takes sections and is not registered, unset
768
- * once registered, `'settled'` once its schemas' relations, its bases' included, are in, and `'resolved'`
767
+ * How far the registry finalized it: `'declared'` while a defined entity takes sections and is not registered, unset
768
+ * once registered, `'settled'` once its `defineEntity` relations, its bases' included, are in, and `'resolved'`
769
769
  * once `getMeta` joined them too, which makes each step idempotent and re-entrant.
770
770
  */
771
771
  stage?: 'declared' | 'settled' | 'resolved';
772
772
  /** The fields a read answers with where it names none, set once resolved: see `defaultReadKeys`. */
773
773
  readKeys?: readonly FieldKey<E>[];
774
+ /** The fields holding another entity's key, set once resolved: see `referenceKeys`. */
775
+ referenceKeys?: ReadonlySet<string>;
774
776
  };
775
777
  /** When the database writes a stamp: as the row is inserted, as it is updated, or both. */
776
778
  export type StampEvent = 'insert' | 'update';
@@ -11,7 +11,7 @@ export * from './query.js';
11
11
  export * from './queryAggregate.js';
12
12
  export * from './queryLock.js';
13
13
  export * from './querySql.js';
14
- export * from './schemaEntity.js';
14
+ export * from './definedEntity.js';
15
15
  export * from './queryWhere.js';
16
16
  export * from './universalQuerier.js';
17
17
  export * from './standardSchema.js';
@@ -11,7 +11,7 @@ export * from './query.js';
11
11
  export * from './queryAggregate.js';
12
12
  export * from './queryLock.js';
13
13
  export * from './querySql.js';
14
- export * from './schemaEntity.js';
14
+ export * from './definedEntity.js';
15
15
  export * from './queryWhere.js';
16
16
  export * from './universalQuerier.js';
17
17
  export * from './standardSchema.js';
@@ -100,7 +100,7 @@ export type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined)
100
100
  */
101
101
  export type FilterOnMissing = 'skip' | 'throw';
102
102
  /**
103
- * Authoring shape for `@Entity({ filters })` and a schema's `filters`.
103
+ * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.
104
104
  */
105
105
  export type FilterOptions<E = unknown> = {
106
106
  readonly where: FilterWhere<E>;
@@ -38,14 +38,12 @@ export declare function aggregateField(aggregate: RelationAggregate): FieldOptio
38
38
  * computed column *is* a real column, read like one, but writing to it is an error on every engine.
39
39
  */
40
40
  export declare function isDatabaseWritten(field: FieldOptions): boolean;
41
- /** Whether the field is the whole primary key, the only kind a serial stands for and a column may declare. */
42
- export declare function isSoleIdField<E>(meta: EntityMeta<E>, field: FieldOptions): boolean;
43
41
  /**
44
- * Whether the database generates this column's value: a numeric key nothing else fills. `onInsert` fills
45
- * it from the application and `references` from the row it shares its key with; a `columnType` only
46
- * states its width. The one answer the create statement and the diff both read.
42
+ * Whether the database generates this column's value: its table's whole and own key (see `ownsSoleKey`), numeric,
43
+ * that the application does not fill `onInsert`; a `columnType` only states its width. The one answer the create
44
+ * statement and the diff both read.
47
45
  */
48
- export declare function isAutoIncrement(field: FieldOptions, isPrimaryKey: boolean): boolean;
46
+ export declare function isAutoIncrement(field: FieldOptions, soleKey: boolean): boolean;
49
47
  /** The column family of a field, from its `columnType` if set, else from its `type`. */
50
48
  export declare function fieldFamily(field: FieldOptions): ColumnFamily | undefined;
51
49
  /** Whether the column is NOT NULL: every column is, a key included, unless it declares `nullable()`. */
@@ -83,19 +83,15 @@ export function aggregateField(aggregate) {
83
83
  export function isDatabaseWritten(field) {
84
84
  return field.computed !== undefined;
85
85
  }
86
- /** Whether the field is the whole primary key, the only kind a serial stands for and a column may declare. */
87
- export function isSoleIdField(meta, field) {
88
- return field.isId === true && meta.ids.length === 1;
89
- }
90
86
  /**
91
- * Whether the database generates this column's value: a numeric key nothing else fills. `onInsert` fills
92
- * it from the application and `references` from the row it shares its key with; a `columnType` only
93
- * states its width. The one answer the create statement and the diff both read.
87
+ * Whether the database generates this column's value: its table's whole and own key (see `ownsSoleKey`), numeric,
88
+ * that the application does not fill `onInsert`; a `columnType` only states its width. The one answer the create
89
+ * statement and the diff both read.
94
90
  */
95
- export function isAutoIncrement(field, isPrimaryKey) {
91
+ export function isAutoIncrement(field, soleKey) {
96
92
  if (field.autoIncrement !== undefined)
97
93
  return field.autoIncrement;
98
- return isPrimaryKey && columnFamily(field.type) === 'numeric' && !field.onInsert && !field.references;
94
+ return soleKey && columnFamily(field.type) === 'numeric' && !field.onInsert;
99
95
  }
100
96
  /** The column family of a field, from its `columnType` if set, else from its `type`. */
101
97
  export function fieldFamily(field) {
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.106.1",
6
+ "version": "0.107.1",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -123,13 +123,13 @@
123
123
  }
124
124
  },
125
125
  "devDependencies": {
126
- "@electric-sql/pglite": "0.5.11",
127
- "@electric-sql/pglite-pgvector": "0.0.12",
126
+ "@electric-sql/pglite": "0.5.13",
127
+ "@electric-sql/pglite-pgvector": "0.0.14",
128
128
  "@libsql/client": "^0.18.0",
129
129
  "@neondatabase/serverless": "^1.2.0",
130
- "@nestjs/common": "^12.2.0",
131
- "@nestjs/core": "^12.2.0",
132
- "@nestjs/testing": "^12.2.0",
130
+ "@nestjs/common": "^12.3.2",
131
+ "@nestjs/core": "^12.3.2",
132
+ "@nestjs/testing": "^12.3.2",
133
133
  "@tursodatabase/database": "^0.8.3",
134
134
  "@tursodatabase/serverless": "^1.4.1",
135
135
  "@types/better-sqlite3": "^9.6.0",
@@ -141,7 +141,7 @@
141
141
  "express": "^5.3.0",
142
142
  "mariadb": "^3.5.4",
143
143
  "mongodb": "^7.7.0",
144
- "mssql": "^12.7.11",
144
+ "mssql": "^12.7.13",
145
145
  "mysql2": "^3.24.6",
146
146
  "pg": "^8.23.1",
147
147
  "pg-query-stream": "^4.17.1",