uql-orm 0.110.0 → 0.111.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 (54) hide show
  1. package/README.md +3 -3
  2. package/dist/bunSql/bunSqlQuerier.d.ts +2 -5
  3. package/dist/d1/d1Querier.d.ts +1 -2
  4. package/dist/d1/d1Querier.js +0 -2
  5. package/dist/dialect/abstractSqlDialect.js +2 -2
  6. package/dist/dialect/aliases.d.ts +2 -0
  7. package/dist/dialect/aliases.js +2 -0
  8. package/dist/entity/columnOptionsBuilder.d.ts +1 -1
  9. package/dist/entity/columnOptionsBuilder.js +2 -2
  10. package/dist/entity/decorator/members.d.ts +15 -6
  11. package/dist/entity/metadata/definedFixture/animal.d.ts +4 -0
  12. package/dist/entity/metadata/definedFixture/animal.js +1 -1
  13. package/dist/entity/metadata/definedFixture/author.d.ts +4 -0
  14. package/dist/entity/metadata/definedFixture/author.js +1 -1
  15. package/dist/entity/metadata/definedFixture/book.d.ts +5 -0
  16. package/dist/entity/metadata/definedFixture/book.js +1 -1
  17. package/dist/entity/metadata/definition.d.ts +0 -2
  18. package/dist/entity/metadata/definition.js +3 -8
  19. package/dist/mariadb/mariadbQuerier.d.ts +2 -4
  20. package/dist/migrate/builder/columnBuilder.js +2 -2
  21. package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
  22. package/dist/migrate/codegen/fieldOptionsSource.js +2 -13
  23. package/dist/migrate/schemaGenerator.d.ts +2 -2
  24. package/dist/migrate/schemaGenerator.js +9 -5
  25. package/dist/mongodb/mongodbQuerier.d.ts +1 -2
  26. package/dist/mongodb/mongodbQuerier.js +0 -2
  27. package/dist/mssql/mssqlQuerier.d.ts +2 -4
  28. package/dist/mysql/mysql2Querier.d.ts +2 -10
  29. package/dist/pglite/pgliteQuerier.d.ts +4 -7
  30. package/dist/pglite/pgliteQuerier.js +0 -2
  31. package/dist/postgres/pgQuerier.d.ts +2 -1
  32. package/dist/querier/abstractPoolQuerier.d.ts +1 -2
  33. package/dist/querier/abstractPoolQuerier.js +0 -2
  34. package/dist/querier/abstractSqlQuerier.d.ts +8 -2
  35. package/dist/querier/abstractSqlQuerier.js +29 -4
  36. package/dist/schema/canonicalType.d.ts +3 -3
  37. package/dist/schema/canonicalType.js +9 -4
  38. package/dist/schema/declaredColumn.d.ts +2 -4
  39. package/dist/schema/declaredColumn.js +4 -5
  40. package/dist/schema/schemaASTBuilder.js +1 -2
  41. package/dist/sqlite/hranaQuerier.d.ts +1 -2
  42. package/dist/sqlite/hranaQuerier.js +0 -2
  43. package/dist/sqlite/sqliteQuerier.d.ts +3 -9
  44. package/dist/sqlite/sqliteQuerier.js +0 -2
  45. package/dist/turso/tursoSessionQuerier.d.ts +1 -2
  46. package/dist/turso/tursoSessionQuerier.js +0 -2
  47. package/dist/type/column.d.ts +4 -6
  48. package/dist/type/definedEntity.d.ts +1 -1
  49. package/dist/type/entity.d.ts +4 -5
  50. package/dist/type/querierPool.d.ts +1 -1
  51. package/dist/util/field.util.d.ts +1 -7
  52. package/dist/util/field.util.js +2 -12
  53. package/package.json +1 -1
  54. package/skills/uql-orm/SKILL.md +5 -5
package/README.md CHANGED
@@ -54,7 +54,7 @@ import { Entity, f, Field, ManyToOne, OneToMany } from 'uql-orm';
54
54
 
55
55
  @Entity()
56
56
  export class User {
57
- @Field(f.number().id())
57
+ @Field(f.number().autoIncrement())
58
58
  id?: number;
59
59
 
60
60
  @Field(f.string().unique())
@@ -66,7 +66,7 @@ export class User {
66
66
 
67
67
  @Entity()
68
68
  export class Post {
69
- @Field(f.number().id())
69
+ @Field(f.number().autoIncrement())
70
70
  id?: number;
71
71
 
72
72
  @Field(f.string())
@@ -91,7 +91,7 @@ import { defineEntity, f } from 'uql-orm';
91
91
  export const Post = defineEntity({
92
92
  name: 'Post',
93
93
  fields: {
94
- id: f.number().id(),
94
+ id: f.number().autoIncrement(),
95
95
  title: f.string(),
96
96
  likes: f.number().nullable(),
97
97
  authorId: f.number().nullable(),
@@ -1,4 +1,5 @@
1
1
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
2
+ import type { SqlExecution } from '../util/sql.util.js';
2
3
  import { type BunSqlConn } from './bunSql.util.js';
3
4
  /**
4
5
  * A querier for `bun:sql` over a reserved connection, so raw SQL goes through `pool.sql` rather than
@@ -9,10 +10,6 @@ export declare class BunSqlQuerier extends AbstractPoolQuerier<BunSqlConn> {
9
10
  * Through `.unsafe()`, which takes the compiled text where Bun's tagged template would parse its own: safe, as
10
11
  * every value is bound.
11
12
  */
12
- protected execute(sql: string, values?: unknown[]): Promise<{
13
- rows: import("../index.js").RawRow[];
14
- changes: number | undefined;
15
- id: import("../index.js").PrimaryKey | undefined;
16
- }>;
13
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
17
14
  protected releaseConn(conn: BunSqlConn): Promise<void>;
18
15
  }
@@ -26,8 +26,7 @@ export interface D1Queryable {
26
26
  }
27
27
  export declare class D1Querier extends AbstractSqlQuerier {
28
28
  readonly db: D1Queryable;
29
- readonly extra?: ExtraOptions | undefined;
30
- constructor(db: D1Queryable, dialect: D1SqliteDialect, extra?: ExtraOptions | undefined);
29
+ constructor(db: D1Queryable, dialect: D1SqliteDialect, extra?: ExtraOptions);
31
30
  protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
32
31
  /** A list as one `batch()`, which D1 runs in order as one transaction: the one it has. */
33
32
  protected executeBatch(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
@@ -3,11 +3,9 @@ import { toBindValues } from '../sqlite/bindValues.js';
3
3
  import { UqlUsageError } from '../util/uqlError.js';
4
4
  export class D1Querier extends AbstractSqlQuerier {
5
5
  db;
6
- extra;
7
6
  constructor(db, dialect, extra) {
8
7
  super(dialect, extra);
9
8
  this.db = db;
10
- this.extra = extra;
11
9
  }
12
10
  async execute(sql, values) {
13
11
  return executionOf(await this.prepared(sql, values).all());
@@ -1,5 +1,5 @@
1
1
  import { fieldOf, getMeta, relationOf } from '../entity/index.js';
2
- import { generatesKey, ownsSoleKey, valueFieldOf } from '../entity/metadata/definition.js';
2
+ import { generatesKey, valueFieldOf } from '../entity/metadata/definition.js';
3
3
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, REF_ENTITY, REF_KEY, ColumnRef, renderSql, RAW_ALIAS, } from '../type/index.js';
4
4
  import { utcTimestamp } from '../util/date.js';
5
5
  import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys, lacksValueOnInsert, } from '../util/field.util.js';
@@ -1472,7 +1472,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1472
1472
  if (write.kind === 'insert' || write.kind === 'upsert') {
1473
1473
  const [row] = fillOnFields(meta, { ...write.row }, 'onInsert', 'trigger');
1474
1474
  const unfilled = definedEntries(meta.fields)
1475
- .filter(([key, field]) => row[key] === undefined && lacksValueOnInsert(field, ownsSoleKey(meta, key)))
1475
+ .filter(([key, field]) => row[key] === undefined && lacksValueOnInsert(field))
1476
1476
  .map(([key]) => key);
1477
1477
  if (unfilled.length) {
1478
1478
  throw new UqlUsageError(`a trigger's insert into '${meta.name}' leaves out ${unfilled.map((key) => `'${key}'`).join(', ')}, ` +
@@ -33,6 +33,8 @@ export declare const JSON_SKIP_KEY = "_uql_skip";
33
33
  export declare const SAVEPOINT_PREFIX = "_uql_sp";
34
34
  /** The cursor a stream declares. Suffixed per call, so two streams on one connection cannot collide. */
35
35
  export declare const CURSOR_ALIAS = "_uql_cursor";
36
+ /** The column reading a key's SQL default ahead of the insert writing it, where an engine reports only a generated key. */
37
+ export declare const KEY_DEFAULT_ALIAS = "_uql_key_default";
36
38
  /** The SQL Server table variable an `OUTPUT` fills. */
37
39
  export declare const OUTPUT_TABLE = "@_uql_output";
38
40
  /** What SQL Server's report of a write's rows reads {@link OUTPUT_TABLE} as, the table its fields are projected off. */
@@ -34,6 +34,8 @@ export const JSON_SKIP_KEY = `${OWNED_PREFIX}_skip`;
34
34
  export const SAVEPOINT_PREFIX = `${OWNED_PREFIX}_sp`;
35
35
  /** The cursor a stream declares. Suffixed per call, so two streams on one connection cannot collide. */
36
36
  export const CURSOR_ALIAS = `${OWNED_PREFIX}_cursor`;
37
+ /** The column reading a key's SQL default ahead of the insert writing it, where an engine reports only a generated key. */
38
+ export const KEY_DEFAULT_ALIAS = `${OWNED_PREFIX}_key_default`;
37
39
  /** The SQL Server table variable an `OUTPUT` fills. */
38
40
  export const OUTPUT_TABLE = `@${OWNED_PREFIX}_output`;
39
41
  /** What SQL Server's report of a write's rows reads {@link OUTPUT_TABLE} as, the table its fields are projected off. */
@@ -28,7 +28,7 @@ export declare class ColumnOptionsBuilder {
28
28
  stored(events?: readonly StampEvent[]): ColumnOptionsBuilder;
29
29
  precision(precision: number): ColumnOptionsBuilder;
30
30
  scale(scale: number): ColumnOptionsBuilder;
31
- autoIncrement(autoIncrement?: boolean): ColumnOptionsBuilder;
31
+ autoIncrement(): ColumnOptionsBuilder;
32
32
  length(length: number): ColumnOptionsBuilder;
33
33
  dimensions(dimensions: number): ColumnOptionsBuilder;
34
34
  distance(distance: VectorDistance): ColumnOptionsBuilder;
@@ -68,8 +68,8 @@ export class ColumnOptionsBuilder {
68
68
  scale(scale) {
69
69
  return this.with({ scale });
70
70
  }
71
- autoIncrement(autoIncrement = true) {
72
- return this.with({ autoIncrement });
71
+ autoIncrement() {
72
+ return this.with({ isId: true, autoIncrement: true });
73
73
  }
74
74
  length(length) {
75
75
  return this.with({ length });
@@ -18,7 +18,7 @@ type MemberContext<O, P, N, M, Filled, Key, Lock> = ClassFieldDecoratorContext<O
18
18
  M
19
19
  ] extends [P] ? unknown : {
20
20
  readonly __propertyMustAdmit: M;
21
- }) & FilledIfBranded<O, N, Filled> & ([Key] extends [true] ? KeyIsNamed<O> : unknown) & ([Lock] extends [true] ? VersionIsBranded<O> : unknown);
21
+ }) & FilledIfBranded<O, N, Filled> & ([Key] extends [false] ? unknown : [Key] extends ['supplied'] ? KeyIsNamed<O> & KeyIsRequired<P> : KeyIsNamed<O>) & ([Lock] extends [true] ? VersionIsBranded<O> : unknown);
22
22
  /** An {@link AdmittingDecorator} for a column: its class is the decorator's own, and `K` is the key it references, `never` if none. */
23
23
  type ColumnDecorator<V, M, Filled, Key, Lock, K = never> = <This, P extends V | undefined, N extends PropertyKey>(value: undefined, context: MemberContext<This, P, N, M, Filled, Key, Lock> & PropertyHoldsKey<P, K>) => void;
24
24
  /** Refuses a property that does not hold the key a column references: a builder cannot say, a property brands what it does not. */
@@ -35,12 +35,12 @@ type FilledIfBranded<O, N, Filled> = [Filled] extends [true] ? unknown : typeof
35
35
  readonly __filledKeyNeedsADefault: true;
36
36
  } : unknown : unknown;
37
37
  /** What `Field` answers: a column's own checks, and that a property holds the key its column references. */
38
- type FieldDecorator<O, V> = ColumnDecorator<Narrowable<V> | NullOf<O>, NullOf<O>, O extends FilledOptions ? true : false, IsKey<O>, O extends {
38
+ type FieldDecorator<O, V> = ColumnDecorator<Narrowable<V> | NullOf<O>, NullOf<O>, O extends FilledOptions ? true : false, IsKey<O, V>, O extends {
39
39
  readonly version: true;
40
40
  } ? true : false, ReferencedKeyOf<O>>;
41
41
  /**
42
42
  * Declares a persisted field, the property checked against the column: `@Field(f.string()) name!: string;`, and
43
- * `@Field(f.string().nullable()) bio?: string | null;` for a column holding `null`. A key is `f.number().id()`.
43
+ * `@Field(f.string().nullable()) bio?: string | null;` for a column holding `null`. A key is `f.number().autoIncrement()`.
44
44
  * @example `@Field(f.references(() => User).nullable()) userId?: number | null;`
45
45
  */
46
46
  export declare function Field<O, V>(column: Column<O, V>): FieldDecorator<O, V>;
@@ -60,10 +60,15 @@ type ComputedValue<C> = C extends RelationAggregate<infer V> ? V : C extends Col
60
60
  type ComputedAdmits<C> = C extends RelationAggregate<infer V> ? V : C extends Column<infer O> ? NullOf<O> : never;
61
61
  /** A JSON column with no schema holds any document, which the property narrows: `Json<Settings>`. */
62
62
  type Narrowable<V> = IsEqual<V, Json> extends true ? JsonBrand | readonly JsonBrand[] : V;
63
- /** Whether the column is a key, which the class has to name. */
64
- type IsKey<O> = O extends {
63
+ /**
64
+ * Whether the column is a key, which the class has to name, and `'supplied'` where no engine fills it: a text key is
65
+ * one MongoDB fills, which an entity cannot rule out.
66
+ */
67
+ type IsKey<O, V> = O extends {
65
68
  readonly isId: true;
66
- } ? true : false;
69
+ } ? O extends FilledOptions ? true : O extends {
70
+ readonly references: unknown;
71
+ } ? 'supplied' : [V] extends [number | bigint] ? 'supplied' : true : false;
67
72
  /**
68
73
  * A key the type level cannot name, reported on each key column that leaves it unnamed. Where no `idKey`
69
74
  * brand and no conventional name applies, `IdKey` falls back to every field, and `IdValue`,
@@ -72,6 +77,10 @@ type IsKey<O> = O extends {
72
77
  type KeyIsNamed<This> = [NamedIdKey<This>] extends [never] ? {
73
78
  readonly __keyNeedsIdKeyBrand: true;
74
79
  } : unknown;
80
+ /** A key nothing fills cannot be `?`, which would let an insert leave it out. */
81
+ type KeyIsRequired<P> = undefined extends P ? {
82
+ readonly __keyNothingFillsMustBeRequired: true;
83
+ } : unknown;
75
84
  /**
76
85
  * An optimistic lock the type level cannot see. `version: true` is what makes the column a lock at run
77
86
  * time; the `versionKey` brand is what makes an update payload require it, and a lock only half
@@ -6,6 +6,7 @@ export declare const Animal: import("../../../index.js").DefinedEntity<object &
6
6
  readonly type: NumberConstructor;
7
7
  } & {
8
8
  readonly isId: true;
9
+ readonly autoIncrement: true;
9
10
  }, number>;
10
11
  readonly name: import("../../../index.js").StringColumn<{
11
12
  readonly type: StringConstructor;
@@ -22,6 +23,7 @@ export declare const Dog: import("../../../index.js").DefinedEntity<import("../.
22
23
  readonly type: NumberConstructor;
23
24
  } & {
24
25
  readonly isId: true;
26
+ readonly autoIncrement: true;
25
27
  }, number>;
26
28
  readonly name: import("../../../index.js").StringColumn<{
27
29
  readonly type: StringConstructor;
@@ -42,6 +44,7 @@ export declare const Dog: import("../../../index.js").DefinedEntity<import("../.
42
44
  readonly type: NumberConstructor;
43
45
  } & {
44
46
  readonly isId: true;
47
+ readonly autoIncrement: true;
45
48
  }, number>;
46
49
  readonly name: import("../../../index.js").StringColumn<{
47
50
  readonly type: StringConstructor;
@@ -59,6 +62,7 @@ export declare const Dog: import("../../../index.js").DefinedEntity<import("../.
59
62
  readonly type: NumberConstructor;
60
63
  } & {
61
64
  readonly isId: true;
65
+ readonly autoIncrement: true;
62
66
  }, number>;
63
67
  readonly name: import("../../../index.js").StringColumn<{
64
68
  readonly type: StringConstructor;
@@ -2,6 +2,6 @@ import { f } from '../../column.js';
2
2
  import { defineEntity } from '../definition.js';
3
3
  export const Animal = defineEntity({
4
4
  name: 'Animal',
5
- fields: { id: f.number().id(), name: f.string() },
5
+ fields: { id: f.number().autoIncrement(), name: f.string() },
6
6
  });
7
7
  export const Dog = defineEntity({ name: 'Dog', extends: Animal, fields: { tricks: f.number().nullable() } });
@@ -9,6 +9,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
9
9
  readonly type: NumberConstructor;
10
10
  } & {
11
11
  readonly isId: true;
12
+ readonly autoIncrement: true;
12
13
  }, number>;
13
14
  readonly name: import("../../../index.js").StringColumn<{
14
15
  readonly type: StringConstructor;
@@ -36,6 +37,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
36
37
  readonly type: NumberConstructor;
37
38
  } & {
38
39
  readonly isId: true;
40
+ readonly autoIncrement: true;
39
41
  }, number>;
40
42
  readonly title: import("../../../index.js").StringColumn<{
41
43
  readonly type: StringConstructor;
@@ -70,6 +72,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
70
72
  readonly type: NumberConstructor;
71
73
  } & {
72
74
  readonly isId: true;
75
+ readonly autoIncrement: true;
73
76
  }, number>;
74
77
  readonly name: import("../../../index.js").StringColumn<{
75
78
  readonly type: StringConstructor;
@@ -98,6 +101,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
98
101
  readonly type: NumberConstructor;
99
102
  } & {
100
103
  readonly isId: true;
104
+ readonly autoIncrement: true;
101
105
  }, number>;
102
106
  readonly name: import("../../../index.js").StringColumn<{
103
107
  readonly type: StringConstructor;
@@ -5,7 +5,7 @@ import { Book } from './book.js';
5
5
  export const Author = defineEntity({
6
6
  name: 'Author',
7
7
  fields: {
8
- id: f.number().id(),
8
+ id: f.number().autoIncrement(),
9
9
  name: f.string(),
10
10
  bio: f.string().nullable(),
11
11
  createdAt: f.date().default(currentTimestamp),
@@ -10,6 +10,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
10
10
  readonly type: NumberConstructor;
11
11
  } & {
12
12
  readonly isId: true;
13
+ readonly autoIncrement: true;
13
14
  }, number>;
14
15
  readonly title: import("../../../index.js").StringColumn<{
15
16
  readonly type: StringConstructor;
@@ -44,6 +45,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
44
45
  readonly type: NumberConstructor;
45
46
  } & {
46
47
  readonly isId: true;
48
+ readonly autoIncrement: true;
47
49
  }, number>;
48
50
  readonly name: import("../../../index.js").StringColumn<{
49
51
  readonly type: StringConstructor;
@@ -71,6 +73,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
71
73
  readonly type: NumberConstructor;
72
74
  } & {
73
75
  readonly isId: true;
76
+ readonly autoIncrement: true;
74
77
  }, number>;
75
78
  readonly title: import("../../../index.js").StringColumn<{
76
79
  readonly type: StringConstructor;
@@ -117,6 +120,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
117
120
  readonly type: NumberConstructor;
118
121
  } & {
119
122
  readonly isId: true;
123
+ readonly autoIncrement: true;
120
124
  }, number>;
121
125
  readonly name: import("../../../index.js").StringColumn<{
122
126
  readonly type: StringConstructor;
@@ -144,6 +148,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
144
148
  readonly type: NumberConstructor;
145
149
  } & {
146
150
  readonly isId: true;
151
+ readonly autoIncrement: true;
147
152
  }, number>;
148
153
  readonly title: import("../../../index.js").StringColumn<{
149
154
  readonly type: StringConstructor;
@@ -5,7 +5,7 @@ import { Author } from './author.js';
5
5
  export const Book = defineEntity({
6
6
  name: 'Book',
7
7
  fields: {
8
- id: f.number().id(),
8
+ id: f.number().autoIncrement(),
9
9
  title: f.string(),
10
10
  stock: f.number().default(0),
11
11
  status: f.enum(['draft', 'published']),
@@ -80,8 +80,6 @@ export declare function foreignKeysOf<E>(meta: EntityMeta<E>): RelationMeta[];
80
80
  * extending another may join by other columns. Kept once resolved.
81
81
  */
82
82
  export declare function referenceKeys<E>(meta: EntityMeta<E>): ReadonlySet<string>;
83
- /** Whether `key` is `meta`'s whole primary key and its own, not the key of the row it references. */
84
- export declare function ownsSoleKey<E>(meta: EntityMeta<E>, key: string): boolean;
85
83
  /** Whether the database generates `meta`'s key on insert: the one answer every insert path reads. */
86
84
  export declare function generatesKey<E>(meta: EntityMeta<E>): boolean;
87
85
  export {};
@@ -1,5 +1,5 @@
1
1
  import { COLUMN_OPTIONS, REF_KEY, RelationAggregate, SECTION_ENTRY, SOFT_DELETE_FILTER, } from '../../type/index.js';
2
- import { aggregateField, defaultReadKeys, fieldKeys, isAutoIncrement, isInlinedExpression, } from '../../util/field.util.js';
2
+ import { aggregateField, defaultReadKeys, fieldKeys, isInlinedExpression } from '../../util/field.util.js';
3
3
  import { fieldOptionConflict, findVectorIndex, valueTypesOf, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, indexRefs, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, isRecord, whereWith, } from '../../util/index.js';
4
4
  import { UqlUsageError } from '../../util/uqlError.js';
5
5
  import { ownRegistrations } from '../decorator/bag.js';
@@ -362,7 +362,7 @@ export function registerEntity(entity, opts = {}, members) {
362
362
  }
363
363
  const ids = getIdKeys(meta);
364
364
  if (!ids.length && !meta.abstract) {
365
- throw new UqlUsageError(`'${entity.name}' must have at least one id field (declare one with 'id()', as in 'f.number().id()')`);
365
+ throw new UqlUsageError(`'${entity.name}' must have at least one id field (declare one with '.autoIncrement()', which the database generates, or '.id()', which the caller supplies)`);
366
366
  }
367
367
  meta.ids = ids;
368
368
  metas.set(entity, meta);
@@ -714,14 +714,9 @@ export function referenceKeys(meta) {
714
714
  return references.filter(({ foreign }) => ids.some((id) => id === foreign)).map(({ local }) => local);
715
715
  })));
716
716
  }
717
- /** Whether `key` is `meta`'s whole primary key and its own, not the key of the row it references. */
718
- export function ownsSoleKey(meta, key) {
719
- return soleId(meta)?.key === key && !referenceKeys(meta).has(key);
720
- }
721
717
  /** Whether the database generates `meta`'s key on insert: the one answer every insert path reads. */
722
718
  export function generatesKey(meta) {
723
- const sole = soleId(meta);
724
- return !!sole && isAutoIncrement(sole.field, ownsSoleKey(meta, sole.key));
719
+ return soleId(meta)?.field.autoIncrement === true;
725
720
  }
726
721
  /** The kinds a column of `type` holds as a join compares them, as `HoldsKind` does: a bigint is a number, which BIGINT widens. */
727
722
  function joinedKinds(type) {
@@ -1,12 +1,10 @@
1
1
  import type { PoolConnection } from 'mariadb';
2
2
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
3
  import type { RawRow } from '../type/index.js';
4
+ import type { SqlExecution } from '../util/sql.util.js';
4
5
  export declare class MariadbQuerier extends AbstractPoolQuerier<PoolConnection> {
5
6
  /** A read, or a `RETURNING` write, answers rows, counted by them; any other write an OK packet reporting `affectedRows`. */
6
- protected execute(sql: string, values?: unknown[]): Promise<{
7
- rows: RawRow[];
8
- changes: any;
9
- }>;
7
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
10
8
  /**
11
9
  * Closed through the driver's own `close`, which `Readable` does not type: a loop leaving early only destroys
12
10
  * the stream, which leaves the socket paused mid-result and the connection hung for its next statement.
@@ -90,7 +90,7 @@ export class TableColumn {
90
90
  if (conflict) {
91
91
  throw new UqlUsageError(`'${this.#name}' ${conflict}`);
92
92
  }
93
- const column = declaredColumn(field, { name: this.#name, soleKey: false, compile: migrationSql });
93
+ const column = declaredColumn(field, { name: this.#name, compile: migrationSql });
94
94
  return {
95
95
  ...column,
96
96
  type: this.#unsigned ? { ...column.type, unsigned: true } : column.type,
@@ -104,7 +104,7 @@ export class TableColumn {
104
104
  export function tableColumns(add) {
105
105
  const named = (name, column) => add(new TableColumn(name, column));
106
106
  return {
107
- id: (name = 'id') => named(name, columns.bigint().id().autoIncrement()),
107
+ id: (name = 'id') => named(name, columns.bigint().autoIncrement()),
108
108
  integer: (name) => named(name, columns.column('int')),
109
109
  smallint: (name) => named(name, columns.column('smallint')),
110
110
  bigint: (name) => named(name, columns.bigint()),
@@ -248,6 +248,6 @@ function propertySource(col, propertyName) {
248
248
  if (col.nullable && !col.isPrimaryKey) {
249
249
  return `${written}${propertyName}?: ${type} | null`;
250
250
  }
251
- const filled = !col.isPrimaryKey && col.defaultValue !== undefined;
251
+ const filled = col.defaultValue !== undefined || col.isAutoIncrement;
252
252
  return `${written}${propertyName}${filled ? '?' : '!'}: ${type}`;
253
253
  }
@@ -1,7 +1,6 @@
1
1
  import { canonicalToColumnType, isVectorCategory } from '../../schema/canonicalType.js';
2
2
  import { SqlExpression } from '../../schema/sqlExpression.js';
3
3
  import { DATE_PRECISION } from '../../util/date.js';
4
- import { isAutoIncrement } from '../../util/field.util.js';
5
4
  import { jsonDocument } from '../../util/object.util.js';
6
5
  import { escapeSingleQuotes } from '../../util/sqlLiteral.js';
7
6
  import { quoted, sqlTag } from './sourceLiteral.js';
@@ -19,11 +18,8 @@ const METHOD_SOURCE = {
19
18
  ],
20
19
  // A column is NOT NULL unless it says otherwise; a key is a key, which holds no null.
21
20
  nullable: (col) => (col.nullable && !col.isPrimaryKey ? ['.nullable()'] : []),
22
- isPrimaryKey: (col) => (col.isPrimaryKey ? ['.id()'] : []),
23
- // Generates where `isAutoIncrement` says, which only a column the database treats otherwise contradicts.
24
- isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, ownsSoleKey(col)) === col.isAutoIncrement
25
- ? []
26
- : [col.isAutoIncrement ? '.autoIncrement()' : '.autoIncrement(false)'],
21
+ isPrimaryKey: (col) => (col.isPrimaryKey && !col.isAutoIncrement ? ['.id()'] : []),
22
+ isAutoIncrement: (col) => (col.isPrimaryKey && col.isAutoIncrement ? ['.autoIncrement()'] : []),
27
23
  isUnique: (col) => (col.isUnique ? ['.unique()'] : []),
28
24
  defaultValue: (col) => {
29
25
  const value = defaultSource(col);
@@ -38,13 +34,6 @@ const METHOD_SOURCE = {
38
34
  // The graph link: a foreign key becomes a relation decorator, emitted beside the field rather than in it.
39
35
  table: null,
40
36
  };
41
- /** The AST's reading of the entity's `ownsSoleKey`: the table's whole key, and not the key of a row it references. */
42
- function ownsSoleKey(col) {
43
- const { primaryKey, outgoingRelations } = col.table;
44
- return (col.isPrimaryKey &&
45
- primaryKey?.columns.length === 1 &&
46
- !outgoingRelations.some(({ from }) => from.columns.includes(col)));
47
- }
48
37
  /** Whether to write `type`'s precision: not for a timestamp at a `Date`'s milliseconds, its default. */
49
38
  function writesPrecision(type) {
50
39
  return type.precision !== undefined && !(type.category === 'timestamp' && type.precision === DATE_PRECISION);
@@ -18,8 +18,8 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
18
18
  /** Escape an identifier (table name, column name, etc.) */
19
19
  private escapeId;
20
20
  /**
21
- * The SQL type a column is spelled with: its canonical type, plus the engine's generated suffix on an
22
- * auto-increment key, so a foreign key taking its type from the key gets the same one.
21
+ * The SQL type a column is spelled with: its canonical type, the key's where it is one, plus the engine's generated
22
+ * suffix on an auto-increment key, so a foreign key taking its type from the key gets the same one.
23
23
  */
24
24
  private columnSqlType;
25
25
  /**
@@ -1,5 +1,5 @@
1
1
  import { getMeta } from '../entity/index.js';
2
- import { canonicalToSql, engineType, isVectorCategory } from '../schema/canonicalType.js';
2
+ import { canonicalToSql, engineType, isVectorCategory, suppliedKeySql } from '../schema/canonicalType.js';
3
3
  import { indexChanges } from '../schema/indexDifferences.js';
4
4
  import { matchByKey } from '../schema/matchByKey.js';
5
5
  import { buildSchemaAST } from '../schema/schemaASTBuilder.js';
@@ -40,12 +40,16 @@ export class SqlSchemaGenerator {
40
40
  return this.dialect.escapeId(identifier);
41
41
  }
42
42
  /**
43
- * The SQL type a column is spelled with: its canonical type, plus the engine's generated suffix on an
44
- * auto-increment key, so a foreign key taking its type from the key gets the same one.
43
+ * The SQL type a column is spelled with: its canonical type, the key's where it is one, plus the engine's generated
44
+ * suffix on an auto-increment key, so a foreign key taking its type from the key gets the same one.
45
45
  */
46
46
  columnSqlType(col) {
47
- const type = canonicalToSql(col.type, this.dialect);
48
- return col.isPrimaryKey && col.isAutoIncrement ? `${type} ${this.dialect.autoIncrementSuffix}` : type;
47
+ if (!col.isPrimaryKey) {
48
+ return canonicalToSql(col.type, this.dialect);
49
+ }
50
+ return col.isAutoIncrement
51
+ ? `${canonicalToSql(col.type, this.dialect)} ${this.dialect.autoIncrementSuffix}`
52
+ : suppliedKeySql(col.type, this.dialect);
49
53
  }
50
54
  /**
51
55
  * The entity side as an AST, carrying this generator's default referential action. Named by the dialect's
@@ -8,10 +8,9 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
8
8
  #private;
9
9
  readonly dialect: MongoDialect;
10
10
  readonly conn: MongoClient;
11
- readonly extra?: ExtraOptions | undefined;
12
11
  /** The open transaction's session, for a raw call through `db` to run inside it: `{ session: querier.session }`. */
13
12
  get session(): ClientSession | undefined;
14
- constructor(dialect: MongoDialect, conn: MongoClient, extra?: ExtraOptions | undefined);
13
+ constructor(dialect: MongoDialect, conn: MongoClient, extra?: ExtraOptions);
15
14
  /** Runs `task` on the open transaction's session, if any, after everything queued before it, timed as `label`. */
16
15
  private execute;
17
16
  protected internalFindMany<E extends Document>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
@@ -26,7 +26,6 @@ function refuseTriggers(entity) {
26
26
  export class MongodbQuerier extends AbstractQuerier {
27
27
  dialect;
28
28
  conn;
29
- extra;
30
29
  #session;
31
30
  /** The open transaction's session, for a raw call through `db` to run inside it: `{ session: querier.session }`. */
32
31
  get session() {
@@ -36,7 +35,6 @@ export class MongodbQuerier extends AbstractQuerier {
36
35
  super(extra);
37
36
  this.dialect = dialect;
38
37
  this.conn = conn;
39
- this.extra = extra;
40
38
  }
41
39
  /** Runs `task` on the open transaction's session, if any, after everything queued before it, timed as `label`. */
42
40
  execute(label, task) {
@@ -1,6 +1,7 @@
1
1
  import mssql from 'mssql';
2
2
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
3
  import type { RawRow, TransactionOptions } from '../type/index.js';
4
+ import type { SqlExecution } from '../util/sql.util.js';
4
5
  /** What `tedious` hands back for one statement, whichever shape it took. */
5
6
  type MsSqlResult = {
6
7
  recordset?: RawRow[] & {
@@ -46,10 +47,7 @@ export declare class MsSqlQuerier extends AbstractPoolQuerier<MsSqlConnection> {
46
47
  * `rowsAffected` carries one entry per statement, and a write runs in a batch of several - the table variable
47
48
  * its ids go through, the read handing them back uncounted - so the counts are summed.
48
49
  */
49
- protected execute(sql: string, values?: unknown[]): Promise<{
50
- rows: RawRow[];
51
- changes: number;
52
- }>;
50
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
53
51
  /**
54
52
  * The driver's own stream over the request, which pauses the request while the loop is behind, so
55
53
  * rows arrive only as fast as they are read. A failure the driver reports through the promise alone
@@ -1,21 +1,13 @@
1
1
  import type { PoolConnection } from 'mysql2';
2
- import type { RowDataPacket } from 'mysql2/promise';
3
2
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
+ import type { SqlExecution } from '../util/sql.util.js';
4
4
  /**
5
5
  * Holds the driver's own connection rather than its promise wrapper, whose types name the connection
6
6
  * inside it a promise one too: streaming is the own connection's alone.
7
7
  */
8
8
  export declare class MySql2Querier extends AbstractPoolQuerier<PoolConnection> {
9
9
  /** A read answers its rows; a write, the header naming how many rows it changed and the first id it generated. */
10
- protected execute(sql: string, values?: unknown[]): Promise<{
11
- rows: RowDataPacket[];
12
- changes?: undefined;
13
- id?: undefined;
14
- } | {
15
- rows: never[];
16
- changes: number;
17
- id: number;
18
- }>;
10
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
19
11
  internalStream(query: string, values?: unknown[]): AsyncGenerator<any, void, any>;
20
12
  protected releaseConn(conn: PoolConnection, discard: boolean): Promise<void>;
21
13
  }
@@ -1,5 +1,6 @@
1
1
  import { AbstractSqlQuerier } from '../querier/index.js';
2
- import type { ExtraOptions, RawRow } from '../type/index.js';
2
+ import type { ExtraOptions } from '../type/index.js';
3
+ import type { SqlExecution } from '../util/sql.util.js';
3
4
  import type { PgliteDialect } from './pgliteDialect.js';
4
5
  /** The two methods uql uses of `@electric-sql/pglite`, stated so its published types do not depend on a pre-1.0 package. */
5
6
  export type PgliteDatabase = {
@@ -17,16 +18,12 @@ export type PgliteDatabase = {
17
18
  */
18
19
  export declare class PgliteQuerier extends AbstractSqlQuerier {
19
20
  readonly db: PgliteDatabase;
20
- readonly extra?: ExtraOptions | undefined;
21
- constructor(db: PgliteDatabase, dialect: PgliteDialect, extra?: ExtraOptions | undefined);
21
+ constructor(db: PgliteDatabase, dialect: PgliteDialect, extra?: ExtraOptions);
22
22
  /** Every querier of the pool is this one handle's session, so they share its transaction. */
23
23
  protected get connection(): object;
24
24
  /**
25
25
  * `affectedRows`, not `rowCount`: PGlite derives the former from the command tag of a write only, where the
26
26
  * latter also counts a `SELECT`'s rows and is absent altogether from a DDL tag.
27
27
  */
28
- protected execute(sql: string, values?: unknown[]): Promise<{
29
- rows: RawRow[];
30
- changes: number | undefined;
31
- }>;
28
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
32
29
  }
@@ -7,11 +7,9 @@ import { AbstractSqlQuerier } from '../querier/index.js';
7
7
  */
8
8
  export class PgliteQuerier extends AbstractSqlQuerier {
9
9
  db;
10
- extra;
11
10
  constructor(db, dialect, extra) {
12
11
  super(dialect, extra);
13
12
  this.db = db;
14
- this.extra = extra;
15
13
  }
16
14
  /** Every querier of the pool is this one handle's session, so they share its transaction. */
17
15
  get connection() {
@@ -1,5 +1,6 @@
1
1
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
2
2
  import type { RawRow } from '../type/index.js';
3
+ import type { SqlExecution } from '../util/sql.util.js';
3
4
  import { type PgResult } from './pgExecution.js';
4
5
  export interface PgAnyClient {
5
6
  query(text: string, values?: unknown[]): Promise<PgResult>;
@@ -19,7 +20,7 @@ export declare class PgQuerier extends AbstractPoolQuerier<PgAnyClient> {
19
20
  * the process: the querier hears it while it holds the client, and what it hands the client back to after it.
20
21
  */
21
22
  protected acquired(conn: PgAnyClient): PgAnyClient;
22
- protected execute(sql: string, values?: unknown[]): Promise<import("../util/sql.util.js").SqlExecution>;
23
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
23
24
  internalStream(query: string, values?: unknown[]): AsyncGenerator<RawRow, void, any>;
24
25
  protected releaseConn(conn: PgAnyClient, discard: boolean): Promise<void>;
25
26
  }
@@ -3,10 +3,9 @@ import type { ExtraOptions } from '../type/index.js';
3
3
  import { AbstractSqlQuerier } from './abstractSqlQuerier.js';
4
4
  export declare abstract class AbstractPoolQuerier<C> extends AbstractSqlQuerier {
5
5
  protected readonly connect: () => Promise<C>;
6
- readonly extra?: ExtraOptions | undefined;
7
6
  protected conn: C | undefined;
8
7
  protected getConn(): C;
9
- constructor(connect: () => Promise<C>, dialect: AbstractSqlDialect, extra?: ExtraOptions | undefined);
8
+ constructor(connect: () => Promise<C>, dialect: AbstractSqlDialect, extra?: ExtraOptions);
10
9
  protected lazyConnect(): Promise<void>;
11
10
  /** A connection as this querier takes it from its pool, before its first statement: see {@link releaseConn}. */
12
11
  protected acquired(conn: C): C;
@@ -1,7 +1,6 @@
1
1
  import { AbstractSqlQuerier } from './abstractSqlQuerier.js';
2
2
  export class AbstractPoolQuerier extends AbstractSqlQuerier {
3
3
  connect;
4
- extra;
5
4
  conn;
6
5
  getConn() {
7
6
  if (!this.conn)
@@ -11,7 +10,6 @@ export class AbstractPoolQuerier extends AbstractSqlQuerier {
11
10
  constructor(connect, dialect, extra) {
12
11
  super(dialect, extra);
13
12
  this.connect = connect;
14
- this.extra = extra;
15
13
  }
16
14
  async lazyConnect() {
17
15
  await super.lazyConnect();
@@ -10,9 +10,8 @@ export type BoundStatement = {
10
10
  export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
11
11
  #private;
12
12
  readonly dialect: AbstractSqlDialect;
13
- readonly extra?: ExtraOptions | undefined;
14
13
  hasOpenTransaction: boolean;
15
- constructor(dialect: AbstractSqlDialect, extra?: ExtraOptions | undefined);
14
+ constructor(dialect: AbstractSqlDialect, extra?: ExtraOptions);
16
15
  /** Runs one statement on the driver: what it read, how many rows it changed, and any id its header reports. */
17
16
  protected abstract execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
18
17
  /** What a write reports: the rows it changed, and their ids, inferred from a header's first id where the dialect reads them so. */
@@ -104,6 +103,13 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
104
103
  estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
105
104
  protected internalAggregate<E extends object>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): Promise<RawRow[]>;
106
105
  internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
106
+ /**
107
+ * Writes a defaulted key onto each row naming none, where the engine reports only a key it generates: the row then
108
+ * names its key, the value the column would have taken, SQL evaluated first.
109
+ */
110
+ private fillDefaultedKeys;
111
+ /** What SQL evaluates to on its own, `count` times, each as a column's default would: one statement, a value a row. */
112
+ private evaluated;
107
113
  /**
108
114
  * The statements an insert of `rows` takes, as the indexes of the rows each writes. Grouped by whether a row names
109
115
  * its key, as the two carry different columns: a budget taken over their union would under-fill the statement
@@ -1,8 +1,9 @@
1
- import { AGGREGATE_VALUE_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
1
+ import { AGGREGATE_VALUE_ALIAS, KEY_DEFAULT_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
2
2
  import { getMeta } from '../entity/index.js';
3
3
  import { generatesKey, idOf, namesEvery, namesKey, soleId } from '../entity/metadata/definition.js';
4
+ import { QuerySql } from '../type/querySql.js';
4
5
  import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf, upsertKeepsOwnKey, getKeys, rowKey, } from '../util/index.js';
5
- import { statementOf } from '../util/sql.js';
6
+ import { sql, statementOf } from '../util/sql.js';
6
7
  import { UqlUsageError } from '../util/uqlError.js';
7
8
  import { AbstractQuerier } from './abstractQuerier.js';
8
9
  import { streamViaCursor } from './cursorStream.js';
@@ -64,14 +65,12 @@ function inPayloadOrder(meta, rows, reported) {
64
65
  }
65
66
  export class AbstractSqlQuerier extends AbstractQuerier {
66
67
  dialect;
67
- extra;
68
68
  hasOpenTransaction = false;
69
69
  /** Cached `auto_increment_increment` stride; see {@link loadInsertIdIncrement}. */
70
70
  #insertIdIncrement;
71
71
  constructor(dialect, extra) {
72
72
  super(extra);
73
73
  this.dialect = dialect;
74
- this.extra = extra;
75
74
  }
76
75
  /** What a write reports: the rows it changed, and their ids, inferred from a header's first id where the dialect reads them so. */
77
76
  updateResultOf(result) {
@@ -286,6 +285,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
286
285
  const [idKey] = meta.ids;
287
286
  const sole = soleId(meta);
288
287
  const generatedKey = generatesKey(meta);
288
+ await this.fillDefaultedKeys(meta, rows);
289
289
  // Only a statement whose every row left its key to the database needs its ids, which a supplied one would void
290
290
  // in a header: a `RETURNING` reports them all, a header only a generated key's.
291
291
  const statements = this.insertChunks(meta, rows).map((indexes) => ({
@@ -318,6 +318,31 @@ export class AbstractSqlQuerier extends AbstractQuerier {
318
318
  }
319
319
  });
320
320
  }
321
+ /**
322
+ * Writes a defaulted key onto each row naming none, where the engine reports only a key it generates: the row then
323
+ * names its key, the value the column would have taken, SQL evaluated first.
324
+ */
325
+ async fillDefaultedKeys(meta, rows) {
326
+ const sole = soleId(meta);
327
+ if (sole?.field.defaultValue === undefined || this.dialect.insertIdSource === 'returning') {
328
+ return;
329
+ }
330
+ const unnamed = rows.filter((row) => !namesKey(meta, row));
331
+ if (!unnamed.length) {
332
+ return;
333
+ }
334
+ const value = sole.field.defaultValue;
335
+ const keys = value instanceof QuerySql ? await this.evaluated(value, unnamed.length) : unnamed.map(() => value);
336
+ unnamed.forEach((row, at) => {
337
+ row[sole.key] = keys[at];
338
+ });
339
+ }
340
+ /** What SQL evaluates to on its own, `count` times, each as a column's default would: one statement, a value a row. */
341
+ async evaluated(value, count) {
342
+ const select = sql `SELECT ${value} AS ${sql.id(KEY_DEFAULT_ALIAS)}`;
343
+ const rows = await this.rowsOf(sql.join(new Array(count).fill(select), ' UNION ALL '));
344
+ return rows.map((row) => row[KEY_DEFAULT_ALIAS]);
345
+ }
321
346
  /**
322
347
  * The statements an insert of `rows` takes, as the indexes of the rows each writes. Grouped by whether a row names
323
348
  * its key, as the two carry different columns: a budget taken over their union would under-fill the statement
@@ -19,9 +19,9 @@ type TypeBounds = {
19
19
  * `TINYINT(1)` means boolean on MySQL.
20
20
  */
21
21
  export declare function sqlToCanonical(sqlType: string, reported?: TypeBounds): CanonicalType;
22
- /**
23
- * Convert a canonical type to a SQL type string for a specific dialect instance.
24
- */
22
+ /** {@link canonicalToSql} for a key the database does not generate, which an engine may spell apart from one it does. */
23
+ export declare function suppliedKeySql(type: CanonicalType, dialect: AbstractDialect): string;
24
+ /** Convert a canonical type to a SQL type string for a specific dialect instance. */
25
25
  export declare function canonicalToSql(type: CanonicalType, dialect: AbstractDialect): string;
26
26
  /**
27
27
  * Convert a canonical type to a TypeScript type string.
@@ -203,7 +203,7 @@ const ENGINE_TYPES = {
203
203
  timestampPrecision: 0,
204
204
  },
205
205
  // SQLite uses affinity, so no size variants. `F32_BLOB` is libSQL's vector type; elsewhere just a name of BLOB affinity.
206
- sqlite: { scalars: withVectorType(SQLITE_SCALAR_MAP, 'F32_BLOB') },
206
+ sqlite: { scalars: withVectorType(SQLITE_SCALAR_MAP, 'F32_BLOB'), suppliedIntegerKey: 'INT' },
207
207
  // 2025 and up; below that the server refuses the type rather than storing it as text.
208
208
  mssql: { scalars: withVectorType(MSSQL_SCALAR_MAP, 'VECTOR'), sizes: MSSQL_SIZES, timestampPrecision: 7 },
209
209
  mongodb: { scalars: withVectorType(MONGO_SCALAR_MAP, 'array') },
@@ -277,9 +277,14 @@ function declaredSqlType(options) {
277
277
  }
278
278
  return columnType ?? (typeof type === 'string' ? type : undefined);
279
279
  }
280
- /**
281
- * Convert a canonical type to a SQL type string for a specific dialect instance.
282
- */
280
+ /** {@link canonicalToSql} for a key the database does not generate, which an engine may spell apart from one it does. */
281
+ export function suppliedKeySql(type, dialect) {
282
+ const { suppliedIntegerKey } = ENGINE_TYPES[dialect.dialectName];
283
+ return suppliedIntegerKey && type.category === 'integer' && !type.raw
284
+ ? suppliedIntegerKey
285
+ : canonicalToSql(type, dialect);
286
+ }
287
+ /** Convert a canonical type to a SQL type string for a specific dialect instance. */
283
288
  export function canonicalToSql(type, dialect) {
284
289
  if (type.raw)
285
290
  return type.raw;
@@ -1,11 +1,9 @@
1
1
  import type { Except, FieldMeta, QuerySql } from '../type/index.js';
2
2
  import type { ColumnNode } from './types.js';
3
3
  /**
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 whole and own key, which a numeric one auto-increments as, and `compile` renders its SQL.
4
+ * The column a field's options declare, whether an entity's table or a migration holds it: `compile` renders its SQL.
6
5
  */
7
- export declare function declaredColumn(field: FieldMeta, { name, soleKey, compile, }: {
6
+ export declare function declaredColumn(field: FieldMeta, { name, compile }: {
8
7
  readonly name: string;
9
- readonly soleKey: boolean;
10
8
  readonly compile: (sql: QuerySql) => string;
11
9
  }): Except<ColumnNode, 'table'>;
@@ -1,18 +1,17 @@
1
- import { declaresNotNull, fieldFamily, isAutoIncrement } from '../util/field.util.js';
1
+ import { declaresNotNull, fieldFamily } from '../util/field.util.js';
2
2
  import { resolveColumnCanonicalType } from './canonicalType.js';
3
3
  import { schemaDefault } from './sqlExpression.js';
4
4
  /**
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 whole and own key, which a numeric one auto-increments as, and `compile` renders its SQL.
5
+ * The column a field's options declare, whether an entity's table or a migration holds it: `compile` renders its SQL.
7
6
  */
8
- export function declaredColumn(field, { name, soleKey, compile, }) {
7
+ export function declaredColumn(field, { name, compile }) {
9
8
  return {
10
9
  name,
11
10
  type: resolveColumnCanonicalType(field),
12
11
  nullable: !declaresNotNull(field),
13
12
  defaultValue: schemaDefault(field.defaultValue, compile, fieldFamily(field) === 'json'),
14
13
  isPrimaryKey: field.isId === true,
15
- isAutoIncrement: isAutoIncrement(field, soleKey),
14
+ isAutoIncrement: field.autoIncrement === true,
16
15
  isUnique: field.unique ?? false,
17
16
  // A stamp is filled by a trigger, so it is a column like any other; only `stored: true` generates.
18
17
  generatedAs: field.stored === true && field.computed ? compile(field.computed) : undefined,
@@ -1,4 +1,4 @@
1
- import { fieldOf, foreignKeysOf, getMeta, ownsSoleKey } from '../entity/metadata/definition.js';
1
+ import { fieldOf, foreignKeysOf, getMeta } 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
4
  import { isInlinedExpression } from '../util/field.util.js';
@@ -50,7 +50,6 @@ function addTableFromEntity(ctx, meta) {
50
50
  const column = {
51
51
  ...declaredColumn(field, {
52
52
  name: columnName,
53
- soleKey: ownsSoleKey(meta, key),
54
53
  compile: (sql) => ctx.compileDdl(sql, meta.entity),
55
54
  }),
56
55
  ...(notNull.has(key) && { nullable: false }),
@@ -45,10 +45,9 @@ export type HranaQuerierConnectionOptions = {
45
45
  */
46
46
  export declare class HranaQuerier extends AbstractSqlQuerier {
47
47
  readonly client: HranaClient;
48
- readonly extra?: ExtraOptions | undefined;
49
48
  private tx?;
50
49
  private readonly closeClientOnRelease;
51
- constructor(client: HranaClient, dialect: SqliteDialect, extra?: ExtraOptions | undefined, connection?: HranaQuerierConnectionOptions);
50
+ constructor(client: HranaClient, dialect: SqliteDialect, extra?: ExtraOptions, connection?: HranaQuerierConnectionOptions);
52
51
  /** Runs on the open transaction's handle when there is one. */
53
52
  protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
54
53
  /** A list as one request: the client's `batch`, all or none; inside an open transaction, its own, which joins it. */
@@ -9,13 +9,11 @@ import { sqliteStatements, toBindValues } from './bindValues.js';
9
9
  */
10
10
  export class HranaQuerier extends AbstractSqlQuerier {
11
11
  client;
12
- extra;
13
12
  tx;
14
13
  closeClientOnRelease;
15
14
  constructor(client, dialect, extra, connection) {
16
15
  super(dialect, extra);
17
16
  this.client = client;
18
- this.extra = extra;
19
17
  this.closeClientOnRelease = connection?.closeClientOnRelease ?? false;
20
18
  }
21
19
  /** Runs on the open transaction's handle when there is one. */
@@ -1,5 +1,6 @@
1
1
  import { AbstractSqlQuerier } from '../querier/index.js';
2
2
  import type { ExtraOptions, RawRow } from '../type/index.js';
3
+ import type { SqlExecution } from '../util/sql.util.js';
3
4
  import { type SqliteBindValue } from './bindValues.js';
4
5
  import type { SqliteDialect } from './sqliteDialect.js';
5
6
  /**
@@ -32,18 +33,11 @@ export type SqliteDatabase = {
32
33
  */
33
34
  export declare class SqliteQuerier extends AbstractSqlQuerier {
34
35
  readonly db: SqliteDatabase;
35
- readonly extra?: ExtraOptions | undefined;
36
- constructor(db: SqliteDatabase, dialect: SqliteDialect, extra?: ExtraOptions | undefined);
36
+ constructor(db: SqliteDatabase, dialect: SqliteDialect, extra?: ExtraOptions);
37
37
  /** Every querier of the pool is this one handle's session, so they share its transaction. */
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
- protected execute(sql: string, values?: unknown[]): Promise<{
41
- rows: RawRow[];
42
- changes?: undefined;
43
- } | {
44
- rows: never[];
45
- changes: number;
46
- }>;
40
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
47
41
  /** Row by row, as the driver steps the statement. */
48
42
  internalStream(sql: string, values?: unknown[]): AsyncGenerator<RawRow, void, unknown>;
49
43
  }
@@ -8,11 +8,9 @@ import { toBindValues } from './bindValues.js';
8
8
  */
9
9
  export class SqliteQuerier extends AbstractSqlQuerier {
10
10
  db;
11
- extra;
12
11
  constructor(db, dialect, extra) {
13
12
  super(dialect, extra);
14
13
  this.db = db;
15
- this.extra = extra;
16
14
  }
17
15
  /** Every querier of the pool is this one handle's session, so they share its transaction. */
18
16
  get connection() {
@@ -49,8 +49,7 @@ export type TursoSession = {
49
49
  /** A Turso Cloud querier on a stream of its own, which holds its transaction and which `release` closes. */
50
50
  export declare class TursoSessionQuerier extends AbstractSqlQuerier {
51
51
  readonly session: TursoSession;
52
- readonly extra?: ExtraOptions | undefined;
53
- constructor(session: TursoSession, dialect: SqliteDialect, extra?: ExtraOptions | undefined);
52
+ constructor(session: TursoSession, dialect: SqliteDialect, extra?: ExtraOptions);
54
53
  protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
55
54
  /**
56
55
  * A list as one request, all or none: its own `BEGIN IMMEDIATE` and `COMMIT` in it, or, inside an open
@@ -4,11 +4,9 @@ import { decodeBigInts } from '../util/wideNumber.js';
4
4
  /** A Turso Cloud querier on a stream of its own, which holds its transaction and which `release` closes. */
5
5
  export class TursoSessionQuerier extends AbstractSqlQuerier {
6
6
  session;
7
- extra;
8
7
  constructor(session, dialect, extra) {
9
8
  super(dialect, extra);
10
9
  this.session = session;
11
- this.extra = extra;
12
10
  }
13
11
  async execute(sql, values) {
14
12
  return executionOf(await this.session.execute(sql, toBindValues(values), true));
@@ -74,7 +74,7 @@ export interface ColumnBuilder<in out O, in out V, F extends Family> extends Col
74
74
  readonly nullable: true;
75
75
  }, F>;
76
76
  /** Makes it the primary key, or a column of a composite one. */
77
- id(this: Lacking<'nullable'>): With<O, V, {
77
+ id(this: Lacking<'nullable' | 'autoIncrement'>): With<O, V, {
78
78
  readonly isId: true;
79
79
  }, F>;
80
80
  /** The column's DDL default: a value, or SQL the database evaluates per row (`currentTimestamp`, `sql`). */
@@ -150,13 +150,11 @@ export interface NumericColumn<in out O, in out V> extends ColumnBuilder<O, V, '
150
150
  scale(this: TypeNotSql, digits: number): NumericColumn<O & {
151
151
  readonly scale: number;
152
152
  }, V>;
153
- /** Has the database generate the value, which a numeric sole key does unless `autoIncrement(false)` says otherwise. */
154
- autoIncrement(): NumericColumn<O & {
153
+ /** Makes it the primary key, which the database generates. A key the caller supplies is `.id()`. */
154
+ autoIncrement(this: Lacking<'nullable' | 'isId'>): NumericColumn<O & {
155
+ readonly isId: true;
155
156
  readonly autoIncrement: true;
156
157
  }, V>;
157
- autoIncrement(generated: false): NumericColumn<O & {
158
- readonly autoIncrement: false;
159
- }, V>;
160
158
  }
161
159
  export interface StringColumn<in out O, in out V> extends ColumnBuilder<O, V, 'string'> {
162
160
  length(this: TypeNotSql, length: number): StringColumn<O & {
@@ -100,7 +100,7 @@ type IdKeyOf<F> = FlagKeys<F, Column<{
100
100
  type VersionKeyOf<F> = FlagKeys<F, Column<{
101
101
  readonly version: true;
102
102
  }>>;
103
- type FilledKeyOf<F> = Exclude<FlagKeys<F, Column<FilledOptions>>, IdKeyOf<F>>;
103
+ type FilledKeyOf<F> = FlagKeys<F, Column<FilledOptions>>;
104
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
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'>;
@@ -49,11 +49,10 @@ export type WritableKey<E> = {
49
49
  readonly [K in FieldKey<E>]-?: IsEqual<Pick<E, K>, Writable<Pick<E, K>>> extends true ? K : never;
50
50
  }[FieldKey<E>];
51
51
  /**
52
- * What an insert may leave out however the entity declares it: a single-column key, which something
53
- * usually generates, the version, which uql starts at 0, and what {@link filledKey} lists. A composite
54
- * key is the references a row is made of, so an insert names it.
52
+ * What an insert may leave out, the class saying so: `_id`, which MongoDB fills, the version, which uql starts at 0,
53
+ * and what {@link filledKey} lists. A `?` property a write keeps as it is.
55
54
  */
56
- type FilledKey<E> = SoleIdKey<E> | VersionKey<E> | (BrandNames<E, typeof filledKey> & FieldKey<E>);
55
+ type FilledKey<E> = VersionKey<E> | (('_id' | BrandNames<E, typeof filledKey>) & FieldKey<E>);
57
56
  /**
58
57
  * A whole-record write as a caller supplies one: {@link EntityData} without the fields it cannot write,
59
58
  * a {@link FilledKey} optional. That part is a conditional, which TypeScript leaves shut while it types a
@@ -343,7 +342,7 @@ export type FieldOptions<V = unknown> = {
343
342
  readonly unique?: boolean;
344
343
  /** The column's DDL default: a literal, or SQL the database evaluates per inserted row (`currentTimestamp`, `sql`). */
345
344
  readonly defaultValue?: DdlDefault<V> | QuerySql;
346
- /** Whether the database generates the value; a numeric sole key does unless something else fills it. */
345
+ /** Whether the database generates the value. */
347
346
  readonly autoIncrement?: boolean;
348
347
  /**
349
348
  * `true` for an index over the column, a string to name it. A foreign key column is indexed unless
@@ -25,7 +25,7 @@ export interface QuerierPool<Q extends Querier = Querier, D extends AbstractDial
25
25
  /**
26
26
  * extra options
27
27
  */
28
- readonly extra?: ExtraOptions;
28
+ readonly extra?: ExtraOptions | undefined;
29
29
  /**
30
30
  * Default connection for application queries, transactions, and anything that should use the pool's primary URL.
31
31
  */
@@ -38,12 +38,6 @@ 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
- /**
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.
45
- */
46
- export declare function isAutoIncrement(field: FieldOptions, soleKey: boolean): boolean;
47
41
  /** The column family of a field, from its `columnType` if set, else from its `type`. */
48
42
  export declare function fieldFamily(field: FieldOptions): ColumnFamily | undefined;
49
43
  /** Whether the column is NOT NULL: every column is, a key included, unless it declares `nullable()`. */
@@ -59,7 +53,7 @@ export declare function lacksValue(column: {
59
53
  * {@link lacksValue} for an insert leaving the field out, where a computed column, a stamp its trigger fills included,
60
54
  * holds a value too, unlike on the rows a migration finds.
61
55
  */
62
- export declare function lacksValueOnInsert(field: FieldOptions, soleKey: boolean): boolean;
56
+ export declare function lacksValueOnInsert(field: FieldOptions): boolean;
63
57
  /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
64
58
  export declare function isFieldKey<E>(meta: EntityMeta<E>, key: string): key is FieldKey<E>;
65
59
  /** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
@@ -83,16 +83,6 @@ export function aggregateField(aggregate) {
83
83
  export function isDatabaseWritten(field) {
84
84
  return field.computed !== undefined;
85
85
  }
86
- /**
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.
90
- */
91
- export function isAutoIncrement(field, soleKey) {
92
- if (field.autoIncrement !== undefined)
93
- return field.autoIncrement;
94
- return soleKey && columnFamily(field.type) === 'numeric' && !field.onInsert;
95
- }
96
86
  /** The column family of a field, from its `columnType` if set, else from its `type`. */
97
87
  export function fieldFamily(field) {
98
88
  return columnFamily(field.columnType ?? field.type);
@@ -109,12 +99,12 @@ export function lacksValue(column) {
109
99
  * {@link lacksValue} for an insert leaving the field out, where a computed column, a stamp its trigger fills included,
110
100
  * holds a value too, unlike on the rows a migration finds.
111
101
  */
112
- export function lacksValueOnInsert(field, soleKey) {
102
+ export function lacksValueOnInsert(field) {
113
103
  return (!isDatabaseWritten(field) &&
114
104
  lacksValue({
115
105
  nullable: !declaresNotNull(field),
116
106
  defaultValue: field.defaultValue,
117
- isAutoIncrement: isAutoIncrement(field, soleKey),
107
+ isAutoIncrement: field.autoIncrement === true,
118
108
  }));
119
109
  }
120
110
  /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
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.110.0",
6
+ "version": "0.111.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -73,7 +73,7 @@ export class User {
73
73
 
74
74
  @Entity()
75
75
  export class Post {
76
- @Field(f.number().id())
76
+ @Field(f.number().autoIncrement())
77
77
  id?: number;
78
78
 
79
79
  @Field(f.string().nullable())
@@ -88,7 +88,7 @@ export class Post {
88
88
  ```
89
89
 
90
90
  - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal(precision?, scale?)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other SQL type uql names (`f.column('smallint')`, `f.column('date')` for a day with no time, `f.column('timestamptz')`), typed by its family, and `f.references(() => Target)` for a foreign key typed as the target's key. A type uql does not name is ``.columnType(sql`citext`)``. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A builder is immutable, so `const money = f.decimal(12, 2)` is shared across fields, each chaining its own `.nullable()`.
91
- - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the single-column key and version uql fills. A NOT NULL field a default fills (`.default()`, `.onInsert()`) stays `!` and is listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
91
+ - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the version uql fills. A key the database generates is `@Field(f.number().autoIncrement()) id?: number` (`f.bigint().autoIncrement()` past 2^53); `.id()` alone generates nothing, so `f.number().id()` is a key the caller supplies and `@Field` refuses `?` on it, as on a `.references()` key. A NOT NULL field something fills (`.default()`, `.onInsert()`, a generated key) stays `!` when listed in the class's `[filledKey]?: 'id' | 'createdAt'`: inserts may omit it, reads always have it. MongoDB fills a text key declared `?` and `_id`. `defineEntity` works all of this out.
92
92
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
93
93
  - `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
94
94
  - A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
@@ -112,7 +112,7 @@ const Settings = z.object({ theme: z.string(), bio: z.string().optional() });
112
112
  export const Author = defineEntity({
113
113
  name: 'Author',
114
114
  fields: {
115
- id: f.number().id(),
115
+ id: f.number().autoIncrement(),
116
116
  name: f.string(),
117
117
  settings: f.json(Settings).nullable(),
118
118
  },
@@ -125,7 +125,7 @@ export type Author = InstanceType<typeof Author>;
125
125
  export const Book = defineEntity({
126
126
  name: 'Book',
127
127
  fields: {
128
- id: f.number().id(),
128
+ id: f.number().autoIncrement(),
129
129
  title: f.string(),
130
130
  stock: f.number().default(0),
131
131
  authorId: f.number(),
@@ -164,7 +164,7 @@ declare module 'uql-orm' {
164
164
  },
165
165
  })
166
166
  export class Invoice {
167
- @Field(f.number().id()) id?: number;
167
+ @Field(f.number().autoIncrement()) id?: number;
168
168
  @Field(f.number()) companyId!: number;
169
169
  @Field(f.string().nullable()) status?: string | null;
170
170
  @Field(f.date().nullable().softDelete()) deletedAt?: Date | null;