uql-orm 0.99.0 → 0.100.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.
Files changed (174) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +1 -1
  3. package/dist/browser/uql-browser.min.js +2 -2
  4. package/dist/browser/uql-browser.min.js.map +5 -5
  5. package/dist/bunSql/bunSql.util.js +2 -2
  6. package/dist/bunSql/bunSqlQuerier.js +0 -1
  7. package/dist/bunSql/bunSqlQuerierPool.js +1 -1
  8. package/dist/cockroachdb/cockroachDialect.js +1 -0
  9. package/dist/context/context.browser.d.ts +5 -0
  10. package/dist/context/context.browser.js +21 -11
  11. package/dist/context/context.d.ts +5 -0
  12. package/dist/context/context.js +8 -3
  13. package/dist/dialect/abstractDialect.js +4 -2
  14. package/dist/dialect/abstractSqlDialect.d.ts +5 -5
  15. package/dist/dialect/abstractSqlDialect.js +26 -18
  16. package/dist/dialect/aliases.d.ts +0 -2
  17. package/dist/dialect/aliases.js +0 -2
  18. package/dist/dialect/hydrateColumn.d.ts +3 -3
  19. package/dist/dialect/hydrateColumn.js +1 -0
  20. package/dist/dialect/index.js +0 -2
  21. package/dist/dialect/jsonSql.d.ts +2 -3
  22. package/dist/dialect/jsonSql.js +4 -6
  23. package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -1
  24. package/dist/dialect/mysqlLikeSqlDialect.js +5 -3
  25. package/dist/dialect/operators.d.ts +2 -3
  26. package/dist/dialect/operators.js +3 -4
  27. package/dist/dialect/pgLikeSqlDialect.js +12 -12
  28. package/dist/entity/decorator/members.d.ts +4 -12
  29. package/dist/entity/metadata/definition.js +8 -5
  30. package/dist/http/handler.d.ts +6 -6
  31. package/dist/http/handler.js +20 -5
  32. package/dist/index.d.ts +6 -5
  33. package/dist/index.js +6 -5
  34. package/dist/{maria → mariadb}/mariadbQuerier.js +1 -1
  35. package/dist/migrate/builder/columnBuilder.d.ts +3 -3
  36. package/dist/migrate/builder/columnBuilder.js +1 -1
  37. package/dist/migrate/builder/index.d.ts +0 -3
  38. package/dist/migrate/builder/index.js +0 -3
  39. package/dist/migrate/builder/migrationBuilder.d.ts +6 -6
  40. package/dist/migrate/builder/migrationBuilder.js +7 -7
  41. package/dist/migrate/builder/tableBuilder.d.ts +25 -25
  42. package/dist/migrate/builder/tableBuilder.js +5 -5
  43. package/dist/migrate/builder/types.d.ts +37 -37
  44. package/dist/migrate/cli-config.d.ts +9 -0
  45. package/dist/migrate/cli-config.js +14 -4
  46. package/dist/migrate/cli.js +9 -18
  47. package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
  48. package/dist/migrate/codegen/migrationFile.d.ts +7 -7
  49. package/dist/migrate/codegen/migrationFile.js +11 -12
  50. package/dist/migrate/ddl/indexCapabilities.d.ts +2 -0
  51. package/dist/migrate/ddl/indexCapabilities.js +6 -0
  52. package/dist/migrate/ddl/indexDdl.d.ts +8 -0
  53. package/dist/migrate/ddl/indexDdl.js +22 -6
  54. package/dist/migrate/generator/definitionToNode.d.ts +1 -1
  55. package/dist/migrate/generator/definitionToNode.js +1 -1
  56. package/dist/migrate/index.d.ts +1 -3
  57. package/dist/migrate/index.js +0 -3
  58. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +11 -15
  59. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +13 -15
  60. package/dist/migrate/introspection/mssqlIntrospector.d.ts +5 -5
  61. package/dist/migrate/introspection/mssqlIntrospector.js +24 -28
  62. package/dist/migrate/introspection/mysqlIntrospector.d.ts +5 -5
  63. package/dist/migrate/introspection/mysqlIntrospector.js +31 -37
  64. package/dist/migrate/introspection/postgresIntrospector.d.ts +13 -13
  65. package/dist/migrate/introspection/postgresIntrospector.js +35 -39
  66. package/dist/migrate/introspection/registry.js +1 -1
  67. package/dist/migrate/introspection/sqliteIntrospector.d.ts +6 -4
  68. package/dist/migrate/introspection/sqliteIntrospector.js +15 -12
  69. package/dist/migrate/migrationLock.d.ts +38 -0
  70. package/dist/migrate/migrationLock.js +103 -0
  71. package/dist/migrate/migrationTarget.d.ts +6 -2
  72. package/dist/migrate/migrationTarget.js +30 -14
  73. package/dist/migrate/migrator.d.ts +39 -23
  74. package/dist/migrate/migrator.js +110 -74
  75. package/dist/migrate/schemaGenerator.d.ts +3 -1
  76. package/dist/migrate/schemaGenerator.js +14 -5
  77. package/dist/migrate/storage/databaseStorage.d.ts +28 -20
  78. package/dist/migrate/storage/databaseStorage.js +36 -54
  79. package/dist/migrate/storage/index.d.ts +0 -1
  80. package/dist/migrate/storage/index.js +0 -1
  81. package/dist/{mongo → mongodb}/index.d.ts +0 -1
  82. package/dist/{mongo → mongodb}/index.js +0 -1
  83. package/dist/{mongo → mongodb}/mongoCommand.d.ts +17 -1
  84. package/dist/{mongo → mongodb}/mongoCommand.js +15 -2
  85. package/dist/{mongo → mongodb}/mongoDialect.js +8 -12
  86. package/dist/{mongo → mongodb}/mongoIntrospector.js +12 -3
  87. package/dist/{mongo → mongodb}/mongoMigrationStorage.d.ts +5 -5
  88. package/dist/{mongo → mongodb}/mongoMigrationStorage.js +8 -12
  89. package/dist/{mongo → mongodb}/mongoQuerier.d.ts +3 -1
  90. package/dist/{mongo → mongodb}/mongoSchemaGenerator.d.ts +11 -1
  91. package/dist/{mongo → mongodb}/mongoSchemaGenerator.js +56 -11
  92. package/dist/{mongo → mongodb}/mongodbQuerier.d.ts +7 -18
  93. package/dist/{mongo → mongodb}/mongodbQuerier.js +44 -78
  94. package/dist/mssql/mssqlDialect.d.ts +6 -4
  95. package/dist/mssql/mssqlDialect.js +20 -10
  96. package/dist/mssql/mssqlQuerier.d.ts +2 -2
  97. package/dist/mssql/mssqlQuerier.js +3 -3
  98. package/dist/mssql/mssqlQuerierPool.d.ts +1 -1
  99. package/dist/mssql/mssqlQuerierPool.js +2 -2
  100. package/dist/mysql/mysql2Querier.js +1 -5
  101. package/dist/namingStrategy/defaultNamingStrategy.d.ts +0 -1
  102. package/dist/namingStrategy/defaultNamingStrategy.js +0 -3
  103. package/dist/pglite/pgliteDialect.d.ts +3 -0
  104. package/dist/pglite/pgliteDialect.js +3 -1
  105. package/dist/pglite/pgliteQuerier.d.ts +2 -0
  106. package/dist/pglite/pgliteQuerier.js +4 -0
  107. package/dist/postgres/postgresDialect.d.ts +3 -4
  108. package/dist/postgres/postgresDialect.js +5 -6
  109. package/dist/querier/abstractQuerier.d.ts +119 -36
  110. package/dist/querier/abstractQuerier.js +465 -161
  111. package/dist/querier/abstractQuerierPool.d.ts +5 -6
  112. package/dist/querier/abstractQuerierPool.js +20 -6
  113. package/dist/querier/abstractSqlQuerier.d.ts +15 -10
  114. package/dist/querier/abstractSqlQuerier.js +54 -47
  115. package/dist/querier/abstractSqlQuerierPool.d.ts +5 -3
  116. package/dist/querier/abstractSqlQuerierPool.js +7 -4
  117. package/dist/querier/transaction.d.ts +46 -0
  118. package/dist/querier/transaction.js +56 -0
  119. package/dist/schema/canonicalType.js +2 -2
  120. package/dist/schema/schemaASTDiffer.d.ts +11 -3
  121. package/dist/schema/schemaASTDiffer.js +20 -8
  122. package/dist/sqlite/nodeSqliteQuerierPool.d.ts +1 -1
  123. package/dist/sqlite/nodeSqliteQuerierPool.js +1 -1
  124. package/dist/sqlite/sqliteDialect.d.ts +1 -1
  125. package/dist/sqlite/sqliteDialect.js +3 -1
  126. package/dist/sqlite/sqliteQuerier.d.ts +2 -0
  127. package/dist/sqlite/sqliteQuerier.js +4 -0
  128. package/dist/sqlite/sqliteQuerierPool.d.ts +4 -4
  129. package/dist/sqlite/sqliteQuerierPool.js +1 -1
  130. package/dist/type/dialect.d.ts +16 -2
  131. package/dist/type/entity.d.ts +32 -32
  132. package/dist/type/migration.d.ts +10 -27
  133. package/dist/type/namingStrategy.d.ts +0 -4
  134. package/dist/type/querier.d.ts +18 -10
  135. package/dist/type/query.d.ts +7 -22
  136. package/dist/type/queryRaw.d.ts +11 -6
  137. package/dist/type/queryRaw.js +2 -3
  138. package/dist/type/universalQuerier.d.ts +26 -28
  139. package/dist/type/utility.d.ts +7 -2
  140. package/dist/util/dialect.util.d.ts +2 -2
  141. package/dist/util/dialect.util.js +4 -1
  142. package/dist/util/field.util.d.ts +12 -0
  143. package/dist/util/field.util.js +24 -0
  144. package/dist/util/hook.util.d.ts +3 -2
  145. package/dist/util/query.util.d.ts +5 -0
  146. package/dist/util/query.util.js +34 -1
  147. package/dist/util/raw.d.ts +8 -2
  148. package/dist/util/raw.js +22 -0
  149. package/dist/util/relationQuery.util.d.ts +2 -0
  150. package/dist/util/relationQuery.util.js +4 -0
  151. package/dist/util/sql.util.d.ts +0 -5
  152. package/dist/util/sql.util.js +3 -9
  153. package/dist/util/uqlError.d.ts +0 -6
  154. package/dist/util/uqlError.js +0 -5
  155. package/package.json +20 -26
  156. package/skills/uql-orm/SKILL.md +13 -10
  157. package/dist/migrate/storage/jsonStorage.d.ts +0 -14
  158. package/dist/migrate/storage/jsonStorage.js +0 -33
  159. /package/dist/{maria → mariadb}/index.d.ts +0 -0
  160. /package/dist/{maria → mariadb}/index.js +0 -0
  161. /package/dist/{maria → mariadb}/mariaDialect.d.ts +0 -0
  162. /package/dist/{maria → mariadb}/mariaDialect.js +0 -0
  163. /package/dist/{maria → mariadb}/mariadbQuerier.d.ts +0 -0
  164. /package/dist/{maria → mariadb}/mariadbQuerierPool.d.ts +0 -0
  165. /package/dist/{maria → mariadb}/mariadbQuerierPool.js +0 -0
  166. /package/dist/{mongo → mongodb}/mongoDialect.d.ts +0 -0
  167. /package/dist/{mongo → mongodb}/mongoIntrospector.d.ts +0 -0
  168. /package/dist/{mongo → mongodb}/mongoQuerier.js +0 -0
  169. /package/dist/{mongo → mongodb}/mongodbQuerierPool.d.ts +0 -0
  170. /package/dist/{mongo → mongodb}/mongodbQuerierPool.js +0 -0
  171. /package/dist/{mongo → mongodb}/textLanguage.d.ts +0 -0
  172. /package/dist/{mongo → mongodb}/textLanguage.js +0 -0
  173. /package/dist/{mongo → mongodb}/vectorDistance.d.ts +0 -0
  174. /package/dist/{mongo → mongodb}/vectorDistance.js +0 -0
@@ -12,6 +12,10 @@ export class SqliteQuerier extends AbstractSqliteQuerier {
12
12
  this.db = db;
13
13
  this.extra = extra;
14
14
  }
15
+ /** Every querier of the pool is this one handle's session, so they share its transaction. */
16
+ get connection() {
17
+ return this.db;
18
+ }
15
19
  /** `reader` picks the call: `run()` would discard the rows of a statement that reads, RETURNING included. */
16
20
  async execute(query, values) {
17
21
  const stmt = await this.db.prepare(query);
@@ -3,15 +3,15 @@ import type { ExtraOptions } from '../type/index.js';
3
3
  import { AbstractLocalSqliteQuerierPool, type LocalSqliteDatabase, type LocalSqlitePoolOptions } from './localSqliteQuerierPool.js';
4
4
  import { SqliteDialect } from './sqliteDialect.js';
5
5
  /** Driver options, plus the loadable extensions to install on the connection. */
6
- export type Sqlite3PoolOptions = Options & LocalSqlitePoolOptions;
6
+ export type SqlitePoolOptions = Options & LocalSqlitePoolOptions;
7
7
  /**
8
8
  * Pool for `better-sqlite3`, or `bun:sqlite` when running under Bun - the same file, through whichever
9
9
  * driver the runtime provides.
10
10
  */
11
- export declare class Sqlite3QuerierPool extends AbstractLocalSqliteQuerierPool<LocalSqliteDatabase, SqliteDialect> {
11
+ export declare class SqliteQuerierPool extends AbstractLocalSqliteQuerierPool<LocalSqliteDatabase, SqliteDialect> {
12
12
  readonly filename: string | Buffer;
13
- readonly opts?: Sqlite3PoolOptions | undefined;
14
- constructor(filename?: string | Buffer, opts?: Sqlite3PoolOptions | undefined, extra?: ExtraOptions);
13
+ readonly opts?: SqlitePoolOptions | undefined;
14
+ constructor(filename?: string | Buffer, opts?: SqlitePoolOptions | undefined, extra?: ExtraOptions);
15
15
  /**
16
16
  * `bun:sqlite` rejects option keys it does not know, so `extensions` is stripped out, and opens only a
17
17
  * path, so a serialized database - which better-sqlite3 takes as its filename - is deserialized there instead.
@@ -5,7 +5,7 @@ import { SqliteDialect } from './sqliteDialect.js';
5
5
  * Pool for `better-sqlite3`, or `bun:sqlite` when running under Bun - the same file, through whichever
6
6
  * driver the runtime provides.
7
7
  */
8
- export class Sqlite3QuerierPool extends AbstractLocalSqliteQuerierPool {
8
+ export class SqliteQuerierPool extends AbstractLocalSqliteQuerierPool {
9
9
  filename;
10
10
  opts;
11
11
  constructor(filename = ':memory:', opts, extra) {
@@ -78,6 +78,8 @@ export interface DriverCapabilities {
78
78
  */
79
79
  readonly nativeArrays: boolean;
80
80
  }
81
+ /** What a nested transaction asks of its savepoint: to open it, release it as it succeeds, or roll back to it. */
82
+ export type SavepointCommand = 'open' | 'release' | 'rollback';
81
83
  /** How a dialect reports inserted ids: from the statement per row, or MySQL's first id, the rest inferred. */
82
84
  export type InsertIdSource = 'returning' | 'firstId';
83
85
  /**
@@ -115,9 +117,9 @@ export interface DialectFeatures {
115
117
  readonly supportsTimestamptz: boolean;
116
118
  /**
117
119
  * How a string column is sized: always unbounded (`text`, SQLite), bounded where a length is given
118
- * (`bounded-text`, the Postgres family), or always bounded, 255 by default (`varchar`).
120
+ * (`boundedText`, the Postgres family), or always bounded, 255 by default (`varchar`).
119
121
  */
120
- readonly stringSizing: 'text' | 'bounded-text' | 'varchar';
122
+ readonly stringSizing: 'text' | 'boundedText' | 'varchar';
121
123
  /** Whether the engine has unsigned integers, so `@Field({ unsigned: true })` reaches the column. */
122
124
  readonly supportsUnsigned: boolean;
123
125
  /**
@@ -169,6 +171,12 @@ export interface SqlDialectFeatures extends DialectFeatures {
169
171
  * MySQL's `MATCH` does, which reads only an index over exactly its columns.
170
172
  */
171
173
  readonly textScoreIndexes: boolean;
174
+ /**
175
+ * Whether a JSON column reaches the querier decoded, as the drivers of an engine with a JSON type hand
176
+ * it, inside a related row's JSON too. Elsewhere it is text, parsed on read; parsing a decoded string
177
+ * again would read `'123'` as `123`.
178
+ */
179
+ readonly jsonArrivesDecoded: boolean;
172
180
  /** Whether a multi-row upsert's `RETURNING` lists its rows in payload order; where not, the ids are read back. */
173
181
  readonly orderedUpsertReturning: boolean;
174
182
  /** Whether a JSON aggregate takes an `ORDER BY` of its own; where not, a relation's rows keep their derived table's order. */
@@ -181,6 +189,12 @@ export interface SqlDialectFeatures extends DialectFeatures {
181
189
  readonly serialDeclaresPrimaryKey: boolean;
182
190
  /** How the engine spells a trigger. One value rather than a flag each, as {@link rowLocks} is. */
183
191
  readonly triggers: TriggerFeatures;
192
+ /**
193
+ * What holds a named lock, the one a migration run takes so a second waits for it: a session (Postgres,
194
+ * MySQL), or a transaction kept open for the run (SQL Server, whose driver keeps a connection only for
195
+ * one). `false` where there is none: CockroachDB, SQLite, and PGlite, whose queriers share one session.
196
+ */
197
+ readonly namedLocks: 'session' | 'transaction' | false;
184
198
  }
185
199
  /**
186
200
  * What a trigger body calls the rows it reads. Row-based engines hand it a record on each side; SQL
@@ -3,7 +3,7 @@ import type { SqlDialectName } from './dialect.js';
3
3
  import type { FilterOptions, RelationQuery } from './query.js';
4
4
  import type { ColumnRef, QueryRaw, RawFor, RelationAggregate } from './queryRaw.js';
5
5
  import type { QueryWhere } from './queryWhere.js';
6
- import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsJson, IsMany, Json, Scalar, Type, Unpacked, Writable } from './utility.js';
6
+ import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsJson, JsonBrand, IsMany, Json, Scalar, Type, Unpacked, Writable } from './utility.js';
7
7
  import type { VectorDistance, VectorIndexOptions, VectorIndexType } from './vector.js';
8
8
  /** Brands the property an entity is identified by, where it is not `id`, `_id` or `uuid`. */
9
9
  export declare const idKey: unique symbol;
@@ -25,7 +25,7 @@ export type Key<E> = keyof E & string;
25
25
  * class is kept off the `Json` arm by the weak-type check.
26
26
  */
27
27
  export type FieldKey<E> = {
28
- readonly [K in keyof E]-?: [NonNullable<E[K]>] extends [Scalar | readonly Scalar[] | Json | readonly Json[]] ? K : never;
28
+ readonly [K in keyof E]-?: [NonNullable<E[K]>] extends [Scalar | readonly Scalar[] | JsonBrand | readonly JsonBrand[]] ? K : never;
29
29
  }[Key<E>];
30
30
  /**
31
31
  * The fields a caller writes: every one the class does not declare `readonly`. A field the database
@@ -78,8 +78,8 @@ export type ToOneRelationKey<E> = {
78
78
  }[RelationKey<E>];
79
79
  /** The relation names a parent holds many rows of: what a populated query fills, and what an aggregate reads. */
80
80
  export type ToManyRelationKey<E> = Exclude<RelationKey<E>, ToOneRelationKey<E>>;
81
- /** The payload `P` of a branded `Json<P>`, or `never` for any other type. */
82
- type UnwrapJson<T> = IsJson<T> extends true ? (T extends Json<infer P> ? P : never) : never;
81
+ /** The payload `P` of a branded `Json<P>`, `unknown` for a bare `Json`, which any path reads into, or `never` for any other type. */
82
+ type UnwrapJson<T> = IsJson<T> extends true ? (IsEqual<T, Json> extends true ? unknown : T extends Json<infer P> ? P : never) : never;
83
83
  /** What a JSON column declared as `V` holds, `Json<P>` or `Json<P>[]` alike; `never` on any other column. */
84
84
  type JsonPayload<V, T = NonNullable<V>> = IsJson<T> extends true ? UnwrapJson<T> : UnwrapJson<NonNullable<Unpacked<T>>>;
85
85
  /** Whether `V` is what a JSON column holds. */
@@ -219,6 +219,8 @@ export type StringColumnType = ColumnTypeOf<'string'>;
219
219
  export type DateColumnType = ColumnTypeOf<'date'>;
220
220
  /** A date column holding a time of day, which names no day: every driver reads it back as text, never a `Date`. */
221
221
  type TimeColumnType = 'time';
222
+ /** A numeric column holding an exact decimal, read as its text: a JS number would round it. */
223
+ type DecimalColumnType = 'decimal' | 'numeric';
222
224
  export type JsonColumnType = ColumnTypeOf<'json'>;
223
225
  export type BlobColumnType = ColumnTypeOf<'blob'>;
224
226
  export type BooleanColumnType = ColumnTypeOf<'boolean'>;
@@ -237,7 +239,7 @@ export type FieldType = StringConstructor | NumberConstructor | BooleanConstruct
237
239
  * compile. JSON is matched on its brand, which a `Json<string>` shares with `string`, and arrays before
238
240
  * scalars, so a vector is not read as a `number`.
239
241
  */
240
- export type TypeFor<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonColumnType : T extends readonly number[] ? VectorColumnType : T extends string ? StringConstructor | StringColumnType | TimeColumnType : T extends number ? NumberConstructor | NumericColumnType : T extends bigint ? BigIntConstructor | NumericColumnType : T extends boolean ? BooleanConstructor | BooleanColumnType : T extends Date ? DateConstructor | Exclude<DateColumnType, TimeColumnType> : T extends Uint8Array ? BlobColumnType : FieldType;
242
+ export type TypeFor<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonColumnType : T extends readonly number[] ? VectorColumnType : T extends string ? StringConstructor | StringColumnType | TimeColumnType | DecimalColumnType : T extends number ? NumberConstructor | Exclude<NumericColumnType, DecimalColumnType> : T extends bigint ? BigIntConstructor | NumericColumnType : T extends boolean ? BooleanConstructor | BooleanColumnType : T extends Date ? DateConstructor | Exclude<DateColumnType, TimeColumnType> : T extends Uint8Array ? BlobColumnType : FieldType;
241
243
  /** A field as the registry holds it: what was authored, plus what registration worked out, which no decorator can write. */
242
244
  export type FieldMeta<V = TsTypeOf<FieldType>> = Except<FieldOptions<V>, 'computed'> & {
243
245
  /** {@link FieldOptions.computed}, a callback resolved to the SQL it returns. */
@@ -336,7 +338,7 @@ type JsonDdlDefault = Scalar | Record<string, unknown> | readonly unknown[];
336
338
  * The TypeScript type a declared `type` implies, the inverse of {@link TypeFor}: a decorator checks the
337
339
  * property against it, `defineEntity` the other way round. `entityOptions.test-d.ts` keeps them agreeing.
338
340
  */
339
- 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 ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? Json<unknown> | readonly Json<unknown>[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
341
+ 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;
340
342
  /**
341
343
  * {@link FieldOptions} for a field declared as `V`, `type` checked by {@link TypeFor}. A foreign key may
342
344
  * omit it, taking the referenced key's column type instead.
@@ -359,19 +361,16 @@ type DeclaresNotNull<V> = null extends V ? unknown : {
359
361
  readonly nullable: false;
360
362
  };
361
363
  /**
362
- * A field a relation aggregate computes: the aggregate types it, so it declares no `type`, and only the
363
- * two a row change turns into a delta - `count` and `sum` - may be `stored`.
364
+ * A field a relation aggregate computes: the aggregate types it, so it declares no `type`, and it is
365
+ * read on each query, never `stored`.
364
366
  */
365
- type AggregateOptionsFor<V, E> = Except<FieldOptions<NonNullable<V>, E>, 'computed' | 'stored' | 'type'> & ({
366
- readonly computed: AggregateReading<E, V, boolean>;
367
+ type AggregateOptionsFor<V, E> = Except<FieldOptions<NonNullable<V>, E>, 'computed' | 'stored' | 'type'> & {
368
+ readonly computed: AggregateReading<E, V>;
367
369
  readonly stored?: false;
368
- } | {
369
- readonly computed: AggregateReading<E, V, true>;
370
- readonly stored: true;
371
- });
370
+ };
372
371
  /** An aggregate reading what the property holds, bivariant the way {@link EntitySql} is. */
373
- type AggregateReading<E, V, S extends boolean> = {
374
- agg(refs: ComputedRefs<E>): RelationAggregate<null extends V ? NonNullable<V> | null : NonNullable<V>, S>;
372
+ type AggregateReading<E, V> = {
373
+ agg(refs: ComputedRefs<E>): RelationAggregate<null extends V ? NonNullable<V> | null : NonNullable<V>>;
375
374
  }['agg'];
376
375
  /** The entity a relation points at: `Company` for `company?: Company` and `companies?: Company[]` alike. */
377
376
  export type RelationTarget<V> = Extract<Unpacked<V>, object>;
@@ -462,8 +461,13 @@ type RelationOwnerJoin<E, O> = (Required<Pick<RelationOptions<E, O>, 'through'>>
462
461
  readonly references: RelationReferencePairs<E, O>;
463
462
  readonly through?: never;
464
463
  };
465
- /** The side holding the foreign key, which `references` names and the actions attach to. */
466
- type RelationOptionsOwner<E, O> = Pick<RelationOptions<E, O>, 'entity' | 'cascade' | 'onDelete' | 'onUpdate'> & Required<Pick<RelationOptions<E, O>, 'references'>>;
464
+ /**
465
+ * The side holding the foreign key, which `references` names and the actions attach to. It cascades
466
+ * `'persist'` only: its target may be other rows' too, so a delete cascades from the side owning the rows.
467
+ */
468
+ type RelationOptionsOwner<E, O> = Pick<RelationOptions<E, O>, 'entity' | 'onDelete' | 'onUpdate'> & Required<Pick<RelationOptions<E, O>, 'references'>> & {
469
+ readonly cascade?: 'persist';
470
+ };
467
471
  type RelationOptionsInverseSide<E, O> = Pick<RelationOptions<E, O>, 'entity' | 'cascade'> & Required<Pick<RelationOptions<E, O>, 'mappedBy'>>;
468
472
  type RelationOptionsThroughOwner<E, O> = Pick<RelationOptions<E, O>, 'entity' | 'cascade'> & RelationOwnerJoin<E, O>;
469
473
  /** The key names of `E` as values, so a definition reads a member off it, `(post) => post.author`, and follows a rename. */
@@ -481,23 +485,19 @@ export type EntitySql<E> = QueryRaw | {
481
485
  /** One field of `C`, read off its refs: `(item) => item.amount`. */
482
486
  type PickRef<C, K extends keyof C> = (refs: RefMap<C>) => ColumnRef<K & string>;
483
487
  /**
484
- * A relation as a `computed` field reads it, its aggregates typed against the related entity. `count`
485
- * and `sum` are the two a row change turns into a delta, so they alone may be `stored`; the rest read
486
- * as a subquery and are `null` where the relation holds no row.
488
+ * A relation as a `computed` field reads it, its aggregates typed against the related entity. Each
489
+ * reads as a subquery; all but `count` and `sum` are `null` where the relation holds no row.
487
490
  */
488
491
  export type RelationRef<C> = {
489
- count(q?: AggregateFilter<C>): RelationAggregate<number, true>;
490
- count(q: AggregatePage<C>): RelationAggregate<number, false>;
491
- sum<K extends FieldKeyOf<C, number | bigint>>(pick: PickRef<C, K>, q?: AggregateFilter<C>): RelationAggregate<NonNullable<C[K]>, true>;
492
- sum<K extends FieldKeyOf<C, number | bigint>>(pick: PickRef<C, K>, q: AggregateTopRows<C>): RelationAggregate<NonNullable<C[K]>, false>;
493
- min<K extends FieldKey<C>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<NonNullable<C[K]> | null, false>;
494
- max<K extends FieldKey<C>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<NonNullable<C[K]> | null, false>;
495
- avg<K extends FieldKeyOf<C, number | bigint>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<number | null, false>;
492
+ count(q?: AggregatePage<C>): RelationAggregate<number>;
493
+ sum<K extends FieldKeyOf<C, number | bigint>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<NonNullable<C[K]>>;
494
+ min<K extends FieldKey<C>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<NonNullable<C[K]> | null>;
495
+ max<K extends FieldKey<C>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<NonNullable<C[K]> | null>;
496
+ avg<K extends FieldKeyOf<C, number | bigint>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<number | null>;
496
497
  };
497
498
  /**
498
- * What an aggregate reads of the related rows. The predicate is an {@link EntityPredicate} rather than a
499
- * full `$where` so that `stored: true` changes no call site: a trigger sees one row, and can evaluate
500
- * nothing that traverses a relation or opens a subquery.
499
+ * What an aggregate reads of the related rows: an {@link EntityPredicate} over each row's own fields,
500
+ * so a trigger could keep the aggregate one row at a time without any call site changing.
501
501
  */
502
502
  export type AggregateFilter<C> = {
503
503
  readonly $where?: EntityPredicate<C>;
@@ -513,7 +513,7 @@ export type AggregatePage<C> = AggregateFilter<C> & Pick<RelationQuery<C>, '$lim
513
513
  * the page an aggregate takes and the page a `$populate` takes cannot drift apart.
514
514
  */
515
515
  export type AggregateTopRows<C> = AggregateFilter<C> & Required<Pick<RelationQuery<C>, '$sort' | '$limit'>> & Pick<RelationQuery<C>, '$skip'>;
516
- /** Either of those, for the aggregates that are never `stored` and so need no second signature. */
516
+ /** Every related row, filtered or not, or the top ones an order picks. */
517
517
  export type AggregateRows<C> = AggregateFilter<C> | AggregateTopRows<C>;
518
518
  /** What a `computed` callback reads: the entity's fields as columns, its to-many relations as aggregates. */
519
519
  export type ComputedRefs<E, F extends keyof E = FieldKey<E>, R extends keyof E = ToManyRelationKey<E>> = RefMap<E, F> & {
@@ -27,23 +27,6 @@ export interface Migration<Q extends Querier = SqlQuerier> extends MigrationDefi
27
27
  */
28
28
  readonly name: string;
29
29
  }
30
- /**
31
- * Storage backend for tracking which migrations have been executed
32
- */
33
- export interface MigrationStorage {
34
- /**
35
- * Get list of already executed migration names
36
- */
37
- executed(): Promise<string[]>;
38
- /**
39
- * Mark a migration as executed, on the querier that ran it (inside its transaction, where there is one)
40
- */
41
- logWithQuerier(querier: Querier, migrationName: string): Promise<void>;
42
- /**
43
- * Remove a migration from the executed list, on the querier that reverted it
44
- */
45
- unlogWithQuerier(querier: Querier, migrationName: string): Promise<void>;
46
- }
47
30
  /**
48
31
  * Configuration options for the Migrator
49
32
  */
@@ -53,13 +36,14 @@ export interface MigratorOptions {
53
36
  */
54
37
  readonly migrationsPath?: string;
55
38
  /**
56
- * Custom storage implementation. Defaults to DatabaseMigrationStorage, or MongoMigrationStorage on MongoDB.
39
+ * Table, or MongoDB collection, name for storing migration state. Defaults to 'uql_migrations'. The lock a
40
+ * run holds is named after it.
57
41
  */
58
- readonly storage?: MigrationStorage;
42
+ readonly tableName?: string;
59
43
  /**
60
- * Table, or MongoDB collection, name for storing migration state. Defaults to 'uql_migrations'.
44
+ * Milliseconds `up` and `down` wait for the lock another run holds before failing. Defaults to 5 minutes.
61
45
  */
62
- readonly tableName?: string;
46
+ readonly lockTimeout?: number;
63
47
  /**
64
48
  * Logger function or options for migration output
65
49
  */
@@ -86,15 +70,12 @@ export interface MigratorOptions {
86
70
  */
87
71
  readonly schemaGenerator?: SchemaGenerator;
88
72
  }
89
- /**
90
- * Result of a migration run
91
- */
73
+ /** A migration `up` or `down` ran: a failing one throws instead. */
92
74
  export interface MigrationResult {
93
75
  readonly name: string;
94
76
  readonly direction: 'up' | 'down';
77
+ /** Milliseconds it took. */
95
78
  readonly duration: number;
96
- readonly success: boolean;
97
- readonly error?: Error;
98
79
  }
99
80
  /** A column as a statement renders one: a {@link ColumnNode} with the engine's type spelling and no graph links. */
100
81
  export interface ColumnSchema extends Except<ColumnNode, 'type' | 'table'> {
@@ -259,6 +240,8 @@ export interface CreateSchemaOptions {
259
240
  export interface DropSchemaOptions {
260
241
  readonly ifExists?: boolean;
261
242
  readonly cascade?: boolean;
243
+ /** The tables the database holds, by qualified name: one it lacks left no trigger function to drop. */
244
+ readonly present?: ReadonlySet<string>;
262
245
  /** The schema as it stands, whose foreign keys are dropped before any table, since a cycle of them has no drop order. */
263
246
  readonly existing?: SchemaAST;
264
247
  }
@@ -287,7 +270,7 @@ export interface SchemaGenerator {
287
270
  * `renamedColumns` are columns `currentTable` already holds under their new names.
288
271
  */
289
272
  diffSchema(entity: Type<object>, currentTable: TableNode | undefined, desiredAst?: SchemaAST, renamedColumns?: readonly Rename[]): SchemaDiff | undefined;
290
- /** The entities as one AST, built once per run for every {@link diffSchema}. Absent on MongoDB, which diffs only indexes. */
273
+ /** The entities as one AST, built once per run for every {@link diffSchema}. Absent on MongoDB, which diffs only indexes and a validator. */
291
274
  buildAST?(entities: readonly Type<object>[]): SchemaAST;
292
275
  /** How this engine's diff compares types and defaults. Absent where {@link buildAST} is. */
293
276
  diffOptions?(): DiffOptions;
@@ -10,8 +10,4 @@ export interface NamingStrategy {
10
10
  * Translates property name to column name.
11
11
  */
12
12
  columnName(propertyName: string): string;
13
- /**
14
- * Translates entity names to join table name (many-to-many).
15
- */
16
- joinTableName(sourceEntityName: string, targetEntityName: string, propertyName?: string): string;
17
13
  }
@@ -3,9 +3,10 @@ import type { SqlDialectName } from './dialect.js';
3
3
  import type { FieldKey, HookEvent, RelationKey } from './entity.js';
4
4
  import type { LoggingOptions } from './logger.js';
5
5
  import type { NamingStrategy } from './namingStrategy.js';
6
- import type { QueryFilter, QueryFindResult, QueryOptions, QueryPage, QuerySearch, QueryUpdateResult } from './query.js';
6
+ import type { QueryFilter, QueryFindResult, QueryOptions, QueryPage, QuerySearch, QueryUpdateResult, ReturningResult, WriteOptions } from './query.js';
7
+ import type { QueryRaw, RawValue } from './queryRaw.js';
7
8
  import type { ProjectedQuery, ProjectedRead, ProjectedResult, UniversalQuerier } from './universalQuerier.js';
8
- import type { Type } from './utility.js';
9
+ import type { BooleanLike, RawRow, Type } from './utility.js';
9
10
  import type { QuerierRaw } from './wire.js';
10
11
  /**
11
12
  * Isolation levels for transactions.
@@ -54,15 +55,21 @@ export interface Querier extends UniversalQuerier {
54
55
  deleteMany<E extends object>(q: QuerySearch<E> & {
55
56
  $entity: Type<E>;
56
57
  }, opts?: QueryOptions): Promise<number>;
57
- deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
58
+ deleteMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V>[]>>;
58
59
  /**
59
60
  * whether this querier is in a transaction or not.
60
61
  */
61
62
  readonly hasOpenTransaction: boolean;
62
63
  /**
63
- * run the given callback inside a transaction in this querier.
64
+ * Runs `callback` in a transaction. Inside one this flow already runs, it is a savepoint, whose failure
65
+ * undoes its own writes alone; a transaction another flow holds on this connection is waited for.
64
66
  */
65
67
  transaction<T>(callback: () => Promise<T>, opts?: TransactionOptions): Promise<T>;
68
+ /**
69
+ * Runs `callback` once the outermost transaction this flow is in commits, never if it rolls back; at
70
+ * once outside a transaction. For side effects a rollback cannot take back: a mail, a queued job.
71
+ */
72
+ onCommit(callback: () => unknown): Promise<void>;
66
73
  /**
67
74
  * starts a new transaction in this querier.
68
75
  */
@@ -95,13 +102,14 @@ export interface SqlQuerier extends Querier {
95
102
  */
96
103
  readonly dialect: AbstractSqlDialect;
97
104
  /**
98
- * Execute a raw SQL query and return results
99
- */
100
- all<T>(query: string, values?: readonly unknown[]): Promise<T[]>;
101
- /**
102
- * Execute a raw SQL command (INSERT, UPDATE, DELETE, DDL)
105
+ * The rows a statement answers, written as a tag, `all<Row>`SELECT ... WHERE id = ${id}``, each interpolated
106
+ * value bound, never spliced; or a `raw` built apart.
103
107
  */
104
- run(query: string, values?: readonly unknown[]): Promise<QueryUpdateResult>;
108
+ all<T extends object = RawRow>(strings: TemplateStringsArray, ...values: RawValue[]): Promise<T[]>;
109
+ all<T extends object = RawRow>(sql: QueryRaw): Promise<T[]>;
110
+ /** Runs a statement (INSERT, UPDATE, DELETE, DDL), written as a tag or a `raw`, each interpolated value bound. */
111
+ run(strings: TemplateStringsArray, ...values: RawValue[]): Promise<QueryUpdateResult>;
112
+ run(sql: QueryRaw): Promise<QueryUpdateResult>;
105
113
  }
106
114
  /**
107
115
  * Type guard to check if a querier supports raw SQL execution
@@ -1,4 +1,4 @@
1
- import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey, WrittenId } from './entity.js';
1
+ import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey } from './entity.js';
2
2
  import type { QueryLock } from './queryLock.js';
3
3
  import type { QueryRaw } from './queryRaw.js';
4
4
  import type { QueryWhere } from './queryWhere.js';
@@ -447,21 +447,15 @@ Pick<E, Exclude<ProjectedKeys<E, S, V, X, P>, PopulatedToMany<E, P>> & keyof E>
447
447
  } : E;
448
448
  /** The to-many relations a query populated, which come back as lists rather than as optional ones. */
449
449
  type PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;
450
- /** What upserting one row reports. `created` is only knowable for a single statement, so a batch has none. */
451
- export type QueryUpsertOneResult<E> = {
452
- readonly id?: WrittenId<E>;
453
- readonly changes?: number;
454
- /** Whether the record was created (`true`) or updated (`false`), where the dialect can tell. */
455
- readonly created?: boolean;
456
- };
457
450
  /**
458
- * What upserting many rows reports. `ids` is payload-aligned like an insert's, so it zips with the
459
- * rows that were passed, and carries a composite key as the map naming it.
451
+ * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,
452
+ * read in the same transaction after the write (before it, for a delete), so they hold what the database filled.
460
453
  */
461
- export type QueryUpsertManyResult<E> = {
462
- readonly ids: (WrittenId<E> | undefined)[];
463
- readonly changes?: number;
454
+ export type WriteOptions<E, S extends FieldKey<E>, V = true> = {
455
+ readonly returning?: QuerySelect<E, S, V>;
464
456
  };
457
+ /** What a write resolves to: `Plain`, its ids or its count, where it names no `returning` field; else `Read`. */
458
+ export type ReturningResult<S, Plain, Read> = [S] extends [never] ? Plain : Read;
465
459
  /**
466
460
  * result of an update operation, as the driver reports it - which is what `run` hands back, where
467
461
  * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.
@@ -478,14 +472,5 @@ export type QueryUpdateResult = {
478
472
  * altogether when the header reports nothing.
479
473
  */
480
474
  ids?: (PrimaryKey | undefined)[];
481
- /**
482
- * first inserted ID.
483
- */
484
- firstId?: PrimaryKey;
485
- /**
486
- * whether the record was created (`true`) or updated (`false`).
487
- * `undefined` when the dialect cannot determine this (e.g. SQLite).
488
- */
489
- created?: boolean;
490
475
  };
491
476
  export {};
@@ -1,5 +1,5 @@
1
1
  import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';
2
- import type { Type } from './utility.js';
2
+ import type { Scalar, Type } from './utility.js';
3
3
  /** What a `raw` callback receives. See {@link QueryRawFn}. */
4
4
  export type QueryRawRenderOptions = {
5
5
  /** The dialect rendering the SQL. */
@@ -35,6 +35,13 @@ export declare const RAW_ALIAS: unique symbol;
35
35
  export declare const RAW_TEXT: unique symbol;
36
36
  /** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */
37
37
  export declare const RAW_VALUE_TYPE: unique symbol;
38
+ /**
39
+ * What a `raw` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in
40
+ * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.
41
+ */
42
+ export type RawValue = Scalar | null | readonly (Scalar | null)[] | QueryRaw;
43
+ /** A statement as `all` and `run` take one: a tagged template's strings and values, or a `raw` built apart. */
44
+ export type SqlStatement = readonly [strings: TemplateStringsArray, ...values: RawValue[]] | readonly [sql: QueryRaw];
38
45
  export declare class QueryRaw {
39
46
  readonly [RAW_VALUE]: QueryRawFn;
40
47
  readonly [RAW_ALIAS]?: string;
@@ -72,15 +79,13 @@ export type RawFor<Raw, V> = Raw & {
72
79
  * It renders as the correlated subquery a `$count` reads, so a field holding one is read, filtered and
73
80
  * sorted like any other.
74
81
  *
75
- * `V` is the value it reads and `Storable` whether a trigger could keep it, both carried in phantom
76
- * fields so the aggregate a field declares decides the property's type and refuses `stored: true` on
77
- * one no delta can maintain.
82
+ * `V` is the value it reads, carried in a phantom field so the aggregate a field declares decides the
83
+ * property's type.
78
84
  */
79
- export declare class RelationAggregate<V = unknown, Storable extends boolean = boolean> extends QueryRaw {
85
+ export declare class RelationAggregate<V = unknown> extends QueryRaw {
80
86
  /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */
81
87
  readonly spec: RelationAggregateSpec;
82
88
  readonly [RAW_VALUE_TYPE]?: V;
83
- private readonly __storable;
84
89
  constructor(
85
90
  /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */
86
91
  spec: RelationAggregateSpec, value: QueryRawFn);
@@ -46,9 +46,8 @@ export class ColumnRef extends QueryRaw {
46
46
  * It renders as the correlated subquery a `$count` reads, so a field holding one is read, filtered and
47
47
  * sorted like any other.
48
48
  *
49
- * `V` is the value it reads and `Storable` whether a trigger could keep it, both carried in phantom
50
- * fields so the aggregate a field declares decides the property's type and refuses `stored: true` on
51
- * one no delta can maintain.
49
+ * `V` is the value it reads, carried in a phantom field so the aggregate a field declares decides the
50
+ * property's type.
52
51
  */
53
52
  export class RelationAggregate extends QueryRaw {
54
53
  spec;
@@ -1,7 +1,7 @@
1
1
  import type { EntityId, EntityWrite, FieldKey, RelationKey, UpdateWrite, WrittenId } from './entity.js';
2
- import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, QueryUpsertManyResult } from './query.js';
2
+ import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, ReturningResult, WriteOptions } from './query.js';
3
3
  import type { QueryAggMap, QueryAggregate, QueryAggregateResult, QueryGroupMap } from './queryAggregate.js';
4
- import type { Type } from './utility.js';
4
+ import type { BooleanLike, Type } from './utility.js';
5
5
  import type { QuerierCountedResult, QuerierRaw, QuerierResult, QuerierTransport } from './wire.js';
6
6
  /** The query type each projected read takes, keyed by the kind of read. */
7
7
  export type ProjectedQuery<E, S extends FieldKey<E>, V, X extends FieldKey<E>, P extends RelationKey<E>, C extends RelationKey<E>, Raw> = {
@@ -84,36 +84,34 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
84
84
  * reads, for bulk reads. `afterLoad` runs on each row as it arrives.
85
85
  */
86
86
  findManyStream: ProjectedRead<'many', 'stream', 'server', QueryOptions>;
87
- /** Insert a record and resolve to its id. See {@link UniversalQuerier.insertMany}. */
88
- insertOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>): Promise<WrittenId<E> | undefined>;
87
+ /** Insert a record and resolve to its id, or the row `returning` reads back. See {@link UniversalQuerier.insertMany}. */
88
+ insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, WrittenId<E> | undefined, QueryFindResult<E, S, V>>>;
89
89
  /**
90
- * Insert records in as few statements as the bind limit allows, resolving to their ids in payload order.
91
- * Ids are exact everywhere but MySQL, which infers them from its header and reports `undefined` rather
92
- * than a guess where it cannot: a batch naming some keys, or a key that is not `AUTO_INCREMENT`.
90
+ * Insert records in as few statements as the bind limit allows, resolving to their ids in payload order, or
91
+ * the rows `returning` reads back. Ids are exact everywhere but MySQL, which infers them from its header and
92
+ * reports `undefined` rather than a guess for a generated key that is not `AUTO_INCREMENT`.
93
93
  */
94
- insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
94
+ insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, (WrittenId<E> | undefined)[], QueryFindResult<E, S, V>[]>>;
95
+ /** Update the record with the given primary key; resolves to the number of affected rows, or the row `returning` reads back. */
96
+ updateOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V> | undefined>>;
97
+ /** Update the records matching the query; resolves to the number of affected rows, or the rows `returning` reads back. */
98
+ updateMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V>[]>>;
99
+ /** Delete, or soft-delete, the record with the given key; resolves to the number of affected rows, or the row as it was. */
100
+ deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V> | undefined>>;
101
+ /** Delete, or soft-delete, the records matching the query; resolves to the number of affected rows, or the rows as they were. */
102
+ deleteMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V>[]>>;
95
103
  /**
96
- * Insert or update a record by its conflict paths; resolves to its id and whether it was created. A conflicting
97
- * row takes the payload less those paths, or `update` as `updateMany` takes one: `{ uses: { $inc: 1 } }` counts,
98
- * and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
104
+ * Insert or update a record by its conflict paths; resolves to its id, or the row `returning` reads back. A
105
+ * conflicting row takes the payload less those paths, or `update` as `updateMany` takes one: `{ uses: { $inc: 1 } }`
106
+ * counts, and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
99
107
  */
100
- upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>): Promise<QueryUpsertOneResult<E>>;
101
- /** Insert or update records by their conflict paths, as `upsertOne` does; resolves to their ids in payload order. */
102
- upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>): Promise<QueryUpsertManyResult<E>>;
103
- /**
104
- * insert or update a record.
105
- * @param entity the entity to persist on
106
- * @param payload the data to be persisted
107
- * @return the ID
108
- */
109
- saveOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>): Promise<WrittenId<E> | undefined>;
110
- /**
111
- * Insert or update records.
112
- * @param entity the entity to persist on
113
- * @param payload the data to be persisted
114
- * @return the IDs
115
- */
116
- saveMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
108
+ upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, WrittenId<E> | undefined, QueryFindResult<E, S, V>>>;
109
+ /** Insert or update records by their conflict paths, as `upsertOne` does; resolves to their ids in payload order, or the rows. */
110
+ upsertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, (WrittenId<E> | undefined)[], QueryFindResult<E, S, V>[]>>;
111
+ /** Insert a record, or upsert one naming its key; resolves to its id, or the row `returning` reads back. */
112
+ saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, WrittenId<E> | undefined, QueryFindResult<E, S, V>>>;
113
+ /** Insert records, or upsert those naming their key; resolves to their ids in payload order, or the rows. */
114
+ saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, (WrittenId<E> | undefined)[], QueryFindResult<E, S, V>[]>>;
117
115
  /**
118
116
  * Restore soft-deleted records (sets the soft-delete field back to `null`). Throws if the
119
117
  * entity has no soft-delete field.
@@ -18,9 +18,14 @@ export type QueryComparableScalar = string | number | bigint | Date;
18
18
  export type PrimaryKey = string | number | bigint;
19
19
  /**
20
20
  * Brands a JSON field, `settings?: Json<{ isArchived?: boolean }>`, so it reads as a field rather than a
21
- * relation; `Json<T>[]` is a list of documents.
21
+ * relation; `Json<T>[]` is a list of documents, and a bare `Json` holds any JSON value, under any path. A
22
+ * `null` in `T` stays `null`, so a `JsonValue` type that includes it is a field that may be `null`.
22
23
  */
23
- export type Json<T = unknown> = T & JsonBrand;
24
+ export type Json<T extends object | string | number | boolean | null = JsonDocument> = T extends null ? null : T & JsonBrand;
25
+ /** Any value a JSON column holds, which a bare {@link Json} stands for. */
26
+ export type JsonDocument = string | number | boolean | readonly unknown[] | {
27
+ readonly [key: string]: unknown;
28
+ };
24
29
  declare const json: unique symbol;
25
30
  /** The marker {@link Json} adds: a symbol key, so no string key, path or autocomplete shows it. */
26
31
  export interface JsonBrand {
@@ -14,12 +14,12 @@ export declare function insertShapeOf<E>(meta: EntityMeta<E>, record: EntityData
14
14
  * whether or not it was filled yet. A record missing one writes its default.
15
15
  */
16
16
  export declare function getInsertFieldKeys<E>(meta: EntityMeta<E>, payloads: EntityData<E>[]): FieldKey<E>[];
17
- export declare function getFieldCallbackValue(val: OnFieldCallback): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QueryRaw | readonly import("../type/utility.js").JsonBrand[] | readonly number[] | Uint8Array<ArrayBufferLike>;
17
+ export declare function getFieldCallbackValue(val: OnFieldCallback): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QueryRaw | readonly number[] | readonly import("../type/utility.js").JsonBrand[] | Uint8Array<ArrayBufferLike>;
18
18
  /**
19
19
  * Resolves the value stamped on the soft-delete field when deleting a row.
20
20
  * `true` stamps the current timestamp (`new Date()`); any other marker is an {@link OnFieldCallback}.
21
21
  */
22
- export declare function getSoftDeleteValue(field: FieldOptions): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QueryRaw | readonly import("../type/utility.js").JsonBrand[] | readonly number[] | Uint8Array<ArrayBufferLike>;
22
+ export declare function getSoftDeleteValue(field: FieldOptions): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QueryRaw | readonly number[] | readonly import("../type/utility.js").JsonBrand[] | Uint8Array<ArrayBufferLike>;
23
23
  /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
24
24
  export declare function fillOnFields<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, payload: R | R[], callbackKey: CallbackKey): R[];
25
25
  /**
@@ -3,7 +3,7 @@ import { QueryRaw, resolveAggregateOp, SOFT_DELETE_FILTER, } from '../type/index
3
3
  import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
4
4
  import { defaultReadKeys, fieldKeys, isDatabaseWritten } from './field.util.js';
5
5
  import { entityName, getKeys, hasKeys, isOperatorObject, isRecord, someKey } from './object.util.js';
6
- import { whereAnd } from './query.util.js';
6
+ import { assertNoUndefined, whereAnd } from './query.util.js';
7
7
  import { UqlSecurityError, UqlUsageError } from './uqlError.js';
8
8
  /** The keys of `payload` a write persists as columns. */
9
9
  export function filterFieldKeys(meta, payload, callbackKey) {
@@ -369,6 +369,9 @@ export function parseGroupMap(group, select) {
369
369
  }
370
370
  for (const alias of getKeys(select)) {
371
371
  const { $where: where } = select[alias];
372
+ if (where) {
373
+ assertNoUndefined(where, `the $where of aggregate '${alias}'`);
374
+ }
372
375
  const call = select[alias];
373
376
  const key = getKeys(call).find((name) => name !== '$where');
374
377
  if (key === undefined) {