uql-orm 0.109.2 → 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 (56) 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 -2
  9. package/dist/entity/columnOptionsBuilder.js +2 -5
  10. package/dist/entity/decorator/members.d.ts +37 -11
  11. package/dist/entity/decorator/members.js +0 -5
  12. package/dist/entity/metadata/definedFixture/animal.d.ts +4 -0
  13. package/dist/entity/metadata/definedFixture/animal.js +1 -1
  14. package/dist/entity/metadata/definedFixture/author.d.ts +4 -0
  15. package/dist/entity/metadata/definedFixture/author.js +1 -1
  16. package/dist/entity/metadata/definedFixture/book.d.ts +5 -0
  17. package/dist/entity/metadata/definedFixture/book.js +1 -1
  18. package/dist/entity/metadata/definition.d.ts +0 -2
  19. package/dist/entity/metadata/definition.js +4 -9
  20. package/dist/mariadb/mariadbQuerier.d.ts +2 -4
  21. package/dist/migrate/builder/columnBuilder.js +2 -2
  22. package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
  23. package/dist/migrate/codegen/fieldOptionsSource.js +2 -13
  24. package/dist/migrate/schemaGenerator.d.ts +2 -2
  25. package/dist/migrate/schemaGenerator.js +9 -5
  26. package/dist/mongodb/mongodbQuerier.d.ts +1 -2
  27. package/dist/mongodb/mongodbQuerier.js +0 -2
  28. package/dist/mssql/mssqlQuerier.d.ts +2 -4
  29. package/dist/mysql/mysql2Querier.d.ts +2 -10
  30. package/dist/pglite/pgliteQuerier.d.ts +4 -7
  31. package/dist/pglite/pgliteQuerier.js +0 -2
  32. package/dist/postgres/pgQuerier.d.ts +2 -1
  33. package/dist/querier/abstractPoolQuerier.d.ts +1 -2
  34. package/dist/querier/abstractPoolQuerier.js +0 -2
  35. package/dist/querier/abstractSqlQuerier.d.ts +8 -2
  36. package/dist/querier/abstractSqlQuerier.js +29 -4
  37. package/dist/schema/canonicalType.d.ts +3 -3
  38. package/dist/schema/canonicalType.js +9 -4
  39. package/dist/schema/declaredColumn.d.ts +2 -4
  40. package/dist/schema/declaredColumn.js +4 -5
  41. package/dist/schema/schemaASTBuilder.js +1 -2
  42. package/dist/sqlite/hranaQuerier.d.ts +1 -2
  43. package/dist/sqlite/hranaQuerier.js +0 -2
  44. package/dist/sqlite/sqliteQuerier.d.ts +3 -9
  45. package/dist/sqlite/sqliteQuerier.js +0 -2
  46. package/dist/turso/tursoSessionQuerier.d.ts +1 -2
  47. package/dist/turso/tursoSessionQuerier.js +0 -2
  48. package/dist/type/column.d.ts +41 -73
  49. package/dist/type/definedEntity.d.ts +1 -1
  50. package/dist/type/entity.d.ts +19 -14
  51. package/dist/type/querierPool.d.ts +1 -1
  52. package/dist/type/utility.d.ts +4 -2
  53. package/dist/util/field.util.d.ts +1 -7
  54. package/dist/util/field.util.js +2 -12
  55. package/package.json +5 -5
  56. package/skills/uql-orm/SKILL.md +7 -7
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. */
@@ -24,12 +24,11 @@ export declare class ColumnOptionsBuilder {
24
24
  columnType(columnType: QuerySql): ColumnOptionsBuilder;
25
25
  references(references: () => Type<object>): ColumnOptionsBuilder;
26
26
  onDelete(onDelete: ForeignKeyAction): ColumnOptionsBuilder;
27
- narrow(): ColumnOptionsBuilder;
28
27
  as(computed: QuerySql): ColumnOptionsBuilder;
29
28
  stored(events?: readonly StampEvent[]): ColumnOptionsBuilder;
30
29
  precision(precision: number): ColumnOptionsBuilder;
31
30
  scale(scale: number): ColumnOptionsBuilder;
32
- autoIncrement(autoIncrement?: boolean): ColumnOptionsBuilder;
31
+ autoIncrement(): ColumnOptionsBuilder;
33
32
  length(length: number): ColumnOptionsBuilder;
34
33
  dimensions(dimensions: number): ColumnOptionsBuilder;
35
34
  distance(distance: VectorDistance): ColumnOptionsBuilder;
@@ -56,9 +56,6 @@ export class ColumnOptionsBuilder {
56
56
  onDelete(onDelete) {
57
57
  return this.with({ onDelete });
58
58
  }
59
- narrow() {
60
- return this;
61
- }
62
59
  as(computed) {
63
60
  return this.with({ computed });
64
61
  }
@@ -71,8 +68,8 @@ export class ColumnOptionsBuilder {
71
68
  scale(scale) {
72
69
  return this.with({ scale });
73
70
  }
74
- autoIncrement(autoIncrement = true) {
75
- return this.with({ autoIncrement });
71
+ autoIncrement() {
72
+ return this.with({ isId: true, autoIncrement: true });
76
73
  }
77
74
  length(length) {
78
75
  return this.with({ length });
@@ -1,4 +1,4 @@
1
- import { type Column, type ComputedRefs, type EntityGetter, type FilledOptions, type filledKey, type HookContext, type IsEqual, type Json, type JsonBrand, type NamedIdKey, type NullOf, type QuerySql, RelationAggregate, type RelationManyToManyOptions, type RelationManyToOneOptions, type RelationOneToManyOptions, type RelationOneToOneOptions, type VersionKey } from '../../type/index.js';
1
+ import { type Column, type ComputedRefs, type EntityGetter, type FilledOptions, type filledKey, type HookContext, type HoldsKind, type IsEqual, type Json, type JsonBrand, type NamedIdKey, type NullOf, type QuerySql, type ReferencedKey, RelationAggregate, type RelationManyToManyOptions, type RelationManyToOneOptions, type RelationOneToManyOptions, type RelationOneToOneOptions, type VersionKey } from '../../type/index.js';
2
2
  /** A member decorator that also constrains the property it may be applied to, on a class `O`. */
3
3
  type MemberDecorator<V, O = unknown> = (value: undefined, context: ClassFieldDecoratorContext<O, V>) => void;
4
4
  /**
@@ -10,23 +10,40 @@ type MemberDecorator<V, O = unknown> = (value: undefined, context: ClassFieldDec
10
10
  * family - `jsonb`, whose document the property shapes, or `numeric`, either number kind - is meant to
11
11
  * be narrowed. A column insists on its `null`; an aggregate, whose value is exact, insists on all of it.
12
12
  */
13
- type AdmittingDecorator<V, M, O, Filled = true, Key = false, Lock = false> = <P extends V | undefined, N extends PropertyKey>(value: undefined, context: ClassFieldDecoratorContext<O, P> & {
13
+ type AdmittingDecorator<V, M, O> = <P extends V | undefined, N extends PropertyKey>(value: undefined, context: MemberContext<O, P, N, M, true, false, false>) => void;
14
+ /** What {@link AdmittingDecorator} asks of a property, a column's own value aside. */
15
+ type MemberContext<O, P, N, M, Filled, Key, Lock> = ClassFieldDecoratorContext<O, P> & {
14
16
  readonly name: N;
15
- } & ([M] extends [P] ? unknown : {
17
+ } & ([
18
+ M
19
+ ] extends [P] ? unknown : {
16
20
  readonly __propertyMustAdmit: M;
17
- }) & FilledIfBranded<O, N, Filled> & ([Key] extends [true] ? KeyIsNamed<O> : unknown) & ([Lock] extends [true] ? VersionIsBranded<O> : unknown)) => void;
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
+ /** An {@link AdmittingDecorator} for a column: its class is the decorator's own, and `K` is the key it references, `never` if none. */
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
+ /** Refuses a property that does not hold the key a column references: a builder cannot say, a property brands what it does not. */
25
+ type PropertyHoldsKey<P, K> = [K] extends [never] ? unknown : HoldsKind<P, K> extends true ? unknown : {
26
+ readonly __propertyMustHoldReferencedKey: K;
27
+ };
28
+ /** The key a typed column references, `never` otherwise: `f.references` has no type of its own, its value being the key. */
29
+ type ReferencedKeyOf<O> = O extends {
30
+ readonly type: unknown;
31
+ readonly references: () => infer C;
32
+ } ? NonNullable<ReferencedKey<C>> : never;
18
33
  /** A field the `filledKey` brand lets an insert leave out, which only a default can then fill. */
19
34
  type FilledIfBranded<O, N, Filled> = [Filled] extends [true] ? unknown : typeof filledKey extends keyof O ? N extends O[typeof filledKey] ? {
20
35
  readonly __filledKeyNeedsADefault: true;
21
36
  } : unknown : unknown;
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, V>, O extends {
39
+ readonly version: true;
40
+ } ? true : false, ReferencedKeyOf<O>>;
22
41
  /**
23
42
  * Declares a persisted field, the property checked against the column: `@Field(f.string()) name!: string;`, and
24
- * `@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()`.
25
44
  * @example `@Field(f.references(() => User).nullable()) userId?: number | null;`
26
45
  */
27
- export declare function Field<This, O, V>(column: Column<O, V>): AdmittingDecorator<Narrowable<V> | NullOf<O>, NullOf<O>, This, O extends FilledOptions ? true : false, IsKey<O>, O extends {
28
- readonly version: true;
29
- } ? true : false>;
46
+ export declare function Field<O, V>(column: Column<O, V>): FieldDecorator<O, V>;
30
47
  /**
31
48
  * Declares a field the database computes, read off the entity's refs: SQL as a column,
32
49
  * `@Computed((user) => f.string().as(sql`upper(${user.name})`)) readonly shout?: string;`, or a relation
@@ -43,10 +60,15 @@ type ComputedValue<C> = C extends RelationAggregate<infer V> ? V : C extends Col
43
60
  type ComputedAdmits<C> = C extends RelationAggregate<infer V> ? V : C extends Column<infer O> ? NullOf<O> : never;
44
61
  /** A JSON column with no schema holds any document, which the property narrows: `Json<Settings>`. */
45
62
  type Narrowable<V> = IsEqual<V, Json> extends true ? JsonBrand | readonly JsonBrand[] : V;
46
- /** Whether the column is a key, which the class has to name. */
47
- 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 {
48
68
  readonly isId: true;
49
- } ? true : false;
69
+ } ? O extends FilledOptions ? true : O extends {
70
+ readonly references: unknown;
71
+ } ? 'supplied' : [V] extends [number | bigint] ? 'supplied' : true : false;
50
72
  /**
51
73
  * A key the type level cannot name, reported on each key column that leaves it unnamed. Where no `idKey`
52
74
  * brand and no conventional name applies, `IdKey` falls back to every field, and `IdValue`,
@@ -55,6 +77,10 @@ type IsKey<O> = O extends {
55
77
  type KeyIsNamed<This> = [NamedIdKey<This>] extends [never] ? {
56
78
  readonly __keyNeedsIdKeyBrand: true;
57
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;
58
84
  /**
59
85
  * An optimistic lock the type level cannot see. `version: true` is what makes the column a lock at run
60
86
  * time; the `versionKey` brand is what makes an update payload require it, and a lock only half
@@ -3,11 +3,6 @@ import { aggregateField } from '../../util/field.util.js';
3
3
  import { memberRefs } from '../../util/sql.js';
4
4
  import { relationRegistration } from '../metadata/definition.js';
5
5
  import { memberRegistrations } from './bag.js';
6
- /**
7
- * Declares a persisted field, the property checked against the column: `@Field(f.string()) name!: string;`, and
8
- * `@Field(f.string().nullable()) bio?: string | null;` for a column holding `null`. A key is `f.number().id()`.
9
- * @example `@Field(f.references(() => User).nullable()) userId?: number | null;`
10
- */
11
6
  export function Field(column) {
12
7
  return (_value, context) => {
13
8
  memberRegistrations(context.metadata).fields[String(context.name)] = column[COLUMN_OPTIONS];
@@ -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,16 +714,11 @@ 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
- /** The kinds a column of `type` holds as a join compares them, as `JoinKind` does: a bigint is a number, which BIGINT widens. */
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) {
728
723
  const types = valueTypesOf(type);
729
724
  return types && [...new Set(types.map((kind) => (kind === 'bigint' ? 'number' : kind)))];
@@ -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
  }