uql-orm 0.111.2 → 0.112.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.
package/README.md CHANGED
@@ -60,7 +60,7 @@ export class User {
60
60
  @Field(f.string().unique())
61
61
  email!: string;
62
62
 
63
- @OneToMany({ entity: () => Post, mappedBy: (post) => post.author })
63
+ @OneToMany(() => Post, { mappedBy: (post) => post.author })
64
64
  posts?: Post[];
65
65
  }
66
66
 
@@ -78,7 +78,7 @@ export class Post {
78
78
  @Field(f.references(() => User).nullable())
79
79
  authorId?: number | null;
80
80
 
81
- @ManyToOne({ entity: () => User, references: (post) => post.authorId })
81
+ @ManyToOne(() => User, { references: (post) => post.authorId })
82
82
  author?: User;
83
83
  }
84
84
  ```
@@ -100,8 +100,8 @@ export const Post = defineEntity({
100
100
  author: () => rel.manyToOne(User, { references: (post) => post.authorId }),
101
101
  }));
102
102
 
103
- // One name for the entity and its rows, as a class has: a function takes `post: Post`.
104
- export type Post = InstanceType<typeof Post>;
103
+ // One name for the entity and its rows, as a class has: a function takes `post: Post`, and hovers and errors print `Post`.
104
+ export interface Post extends InstanceType<typeof Post> {}
105
105
  ```
106
106
 
107
107
  ### 2. A pool, and the migrations it drives
@@ -94,19 +94,10 @@ type KeyIsRequired<O, N> = N extends keyof O ? {} extends Pick<O, N> ? {
94
94
  type VersionIsBranded<This> = [VersionKey<This>] extends [never] ? {
95
95
  readonly __versionNeedsVersionKeyBrand: true;
96
96
  } : unknown;
97
- /**
98
- * `E` comes from the mandatory `entity` getter, so the context can insist the property really holds that
99
- * entity: `@ManyToOne({ entity: () => Other })` on a `Company` field stops compiling, and a to-many
100
- * cardinality on a non-array property does too. `entity` is required because nothing reflects it now.
101
- * `O` is inferred from the class the decorator sits on, which types `references`' own side.
102
- */
103
- type WithEntity<E, O> = O & {
104
- readonly entity: EntityGetter<E>;
105
- };
106
- export declare function OneToOne<E extends object, O>(opts: WithEntity<E, RelationOneToOneOptions<E, O>>): MemberDecorator<E | undefined, O>;
107
- export declare function ManyToOne<E extends object, O>(opts: WithEntity<E, RelationManyToOneOptions<E, O>>): MemberDecorator<E | undefined, O>;
108
- export declare function OneToMany<E extends object, O>(opts: WithEntity<E, RelationOneToManyOptions<E, O>>): MemberDecorator<readonly E[] | undefined, O>;
109
- export declare function ManyToMany<E extends object, O>(opts: WithEntity<E, RelationManyToManyOptions<E, O>>): MemberDecorator<readonly E[] | undefined, O>;
97
+ export declare function OneToOne<E extends object, O>(entity: EntityGetter<E>, opts: RelationOneToOneOptions<E, O>): MemberDecorator<E | undefined, O>;
98
+ export declare function ManyToOne<E extends object, O>(entity: EntityGetter<E>, opts?: RelationManyToOneOptions<E, O>): MemberDecorator<E | undefined, O>;
99
+ export declare function OneToMany<E extends object, O>(entity: EntityGetter<E>, opts?: RelationOneToManyOptions<E, O>): MemberDecorator<readonly E[] | undefined, O>;
100
+ export declare function ManyToMany<E extends object, O>(entity: EntityGetter<E>, opts: RelationManyToManyOptions<E, O>): MemberDecorator<readonly E[] | undefined, O>;
110
101
  /** What a hook method is called with: the row as `this`, and the querier's context. */
111
102
  type HookMethod<This> = (this: This, ctx: HookContext) => unknown;
112
103
  export declare const BeforeInsert: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
@@ -20,22 +20,31 @@ export function Computed(expression) {
20
20
  computed instanceof RelationAggregate ? aggregateField(computed) : computed[COLUMN_OPTIONS];
21
21
  };
22
22
  }
23
- function relation(opts) {
23
+ /**
24
+ * `E` comes from the target getter, so the context can insist the property really holds that entity:
25
+ * `@ManyToOne(() => Other)` on a `Company` field stops compiling, and a to-many cardinality on a non-array
26
+ * property does too. `O` is inferred from the class the decorator sits on, which types `references`' own side.
27
+ */
28
+ function relation(cardinality, entity, opts) {
24
29
  return (_value, context) => {
25
- memberRegistrations(context.metadata).relations[String(context.name)] = relationRegistration(opts);
30
+ memberRegistrations(context.metadata).relations[String(context.name)] = relationRegistration({
31
+ cardinality,
32
+ entity,
33
+ ...opts,
34
+ });
26
35
  };
27
36
  }
28
- export function OneToOne(opts) {
29
- return relation({ cardinality: '11', ...opts });
37
+ export function OneToOne(entity, opts) {
38
+ return relation('11', entity, opts);
30
39
  }
31
- export function ManyToOne(opts) {
32
- return relation({ cardinality: 'm1', ...opts });
40
+ export function ManyToOne(entity, opts) {
41
+ return relation('m1', entity, opts);
33
42
  }
34
- export function OneToMany(opts) {
35
- return relation({ cardinality: '1m', ...opts });
43
+ export function OneToMany(entity, opts) {
44
+ return relation('1m', entity, opts);
36
45
  }
37
- export function ManyToMany(opts) {
38
- return relation({ cardinality: 'mm', ...opts });
46
+ export function ManyToMany(entity, opts) {
47
+ return relation('mm', entity, opts);
39
48
  }
40
49
  function hook(event) {
41
50
  return () =>
@@ -140,5 +140,6 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
140
140
  } & {
141
141
  bio?: string | null | undefined;
142
142
  }, false>;
143
- export type Author = InstanceType<typeof Author>;
143
+ export interface Author extends InstanceType<typeof Author> {
144
+ }
144
145
  export declare const label: (author: Author) => string;
@@ -0,0 +1,126 @@
1
+ export declare const Folder: import("../../../index.js").RelatedEntity<object & {
2
+ id: number;
3
+ name: string;
4
+ size: number;
5
+ } & {
6
+ parentId?: number | null | undefined;
7
+ } & import("../../../index.js").Brands<{
8
+ readonly id: import("../../../index.js").NumericColumn<{
9
+ readonly type: NumberConstructor;
10
+ } & {
11
+ readonly isId: true;
12
+ readonly autoIncrement: true;
13
+ }, number>;
14
+ readonly name: import("../../../index.js").StringColumn<{
15
+ readonly type: StringConstructor;
16
+ }, string>;
17
+ readonly size: import("../../../index.js").NumericColumn<{
18
+ readonly type: NumberConstructor;
19
+ }, number>;
20
+ readonly parentId: import("../../../index.js").NumericColumn<{
21
+ readonly type: NumberConstructor;
22
+ } & {
23
+ readonly nullable: true;
24
+ }, number>;
25
+ }, object> & import("../../../index.js").RelationRow<{
26
+ readonly parent: () => import("../../../index.js").DefinedRelation<object & {
27
+ id: number;
28
+ name: string;
29
+ size: number;
30
+ } & {
31
+ parentId?: number | null | undefined;
32
+ } & import("../../../index.js").Brands<{
33
+ readonly id: import("../../../index.js").NumericColumn<{
34
+ readonly type: NumberConstructor;
35
+ } & {
36
+ readonly isId: true;
37
+ readonly autoIncrement: true;
38
+ }, number>;
39
+ readonly name: import("../../../index.js").StringColumn<{
40
+ readonly type: StringConstructor;
41
+ }, string>;
42
+ readonly size: import("../../../index.js").NumericColumn<{
43
+ readonly type: NumberConstructor;
44
+ }, number>;
45
+ readonly parentId: import("../../../index.js").NumericColumn<{
46
+ readonly type: NumberConstructor;
47
+ } & {
48
+ readonly nullable: true;
49
+ }, number>;
50
+ }, object> & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").AggregateRow<{
51
+ readonly childCount: () => import("../../../index.js").RelationAggregate<number>;
52
+ readonly childSize: () => import("../../../index.js").RelationAggregate<number>;
53
+ }>, "m1", object & {
54
+ id: number;
55
+ name: string;
56
+ size: number;
57
+ } & {
58
+ parentId?: number | null | undefined;
59
+ } & import("../../../index.js").Brands<{
60
+ readonly id: import("../../../index.js").NumericColumn<{
61
+ readonly type: NumberConstructor;
62
+ } & {
63
+ readonly isId: true;
64
+ readonly autoIncrement: true;
65
+ }, number>;
66
+ readonly name: import("../../../index.js").StringColumn<{
67
+ readonly type: StringConstructor;
68
+ }, string>;
69
+ readonly size: import("../../../index.js").NumericColumn<{
70
+ readonly type: NumberConstructor;
71
+ }, number>;
72
+ readonly parentId: import("../../../index.js").NumericColumn<{
73
+ readonly type: NumberConstructor;
74
+ } & {
75
+ readonly nullable: true;
76
+ }, number>;
77
+ }, object> & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").AggregateRow<{
78
+ readonly childCount: () => import("../../../index.js").RelationAggregate<number>;
79
+ readonly childSize: () => import("../../../index.js").RelationAggregate<number>;
80
+ }>>;
81
+ readonly children: () => import("../../../index.js").DefinedRelation<object & {
82
+ id: number;
83
+ name: string;
84
+ size: number;
85
+ } & {
86
+ parentId?: number | null | undefined;
87
+ } & import("../../../index.js").Brands<{
88
+ readonly id: import("../../../index.js").NumericColumn<{
89
+ readonly type: NumberConstructor;
90
+ } & {
91
+ readonly isId: true;
92
+ readonly autoIncrement: true;
93
+ }, number>;
94
+ readonly name: import("../../../index.js").StringColumn<{
95
+ readonly type: StringConstructor;
96
+ }, string>;
97
+ readonly size: import("../../../index.js").NumericColumn<{
98
+ readonly type: NumberConstructor;
99
+ }, number>;
100
+ readonly parentId: import("../../../index.js").NumericColumn<{
101
+ readonly type: NumberConstructor;
102
+ } & {
103
+ readonly nullable: true;
104
+ }, number>;
105
+ }, object> & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").AggregateRow<{
106
+ readonly childCount: () => import("../../../index.js").RelationAggregate<number>;
107
+ readonly childSize: () => import("../../../index.js").RelationAggregate<number>;
108
+ }>, "1m", {
109
+ id: number;
110
+ name: string;
111
+ size: number;
112
+ } & {
113
+ parentId?: number | null | undefined;
114
+ }>;
115
+ }> & import("../../../index.js").AggregateRow<{
116
+ readonly childCount: () => import("../../../index.js").RelationAggregate<number>;
117
+ readonly childSize: () => import("../../../index.js").RelationAggregate<number>;
118
+ }>, number, {
119
+ id: number;
120
+ name: string;
121
+ size: number;
122
+ } & {
123
+ parentId?: number | null | undefined;
124
+ }, false>;
125
+ export interface Folder extends InstanceType<typeof Folder> {
126
+ }
@@ -0,0 +1,12 @@
1
+ import { f } from '../../column.js';
2
+ import { defineEntity } from '../definition.js';
3
+ export const Folder = defineEntity({
4
+ name: 'Folder',
5
+ fields: { id: f.number().autoIncrement(), name: f.string(), size: f.number(), parentId: f.number().nullable() },
6
+ }).relations((rel) => ({
7
+ parent: () => rel.manyToOne(Folder, { references: (folder) => folder.parentId }),
8
+ children: () => rel.oneToMany(Folder, { mappedBy: (folder) => folder.parent }),
9
+ }), (folder) => ({
10
+ childCount: () => folder.children.count(),
11
+ childSize: () => folder.children.sum((child) => child.size),
12
+ }));
@@ -69,8 +69,8 @@ export function keyOf(pick) {
69
69
  const KEY_MAP = new Proxy({}, { get: (_, key) => key });
70
70
  function addRelation(meta, key, registration) {
71
71
  const { entity } = meta;
72
- if (!registration.entity) {
73
- throw new UqlUsageError(`'${entity.name}.${key}' needs an 'entity' getter, e.g. '@ManyToOne({ entity: () => Company })'.`);
72
+ if (typeof registration.entity !== 'function') {
73
+ throw new UqlUsageError(`'${entity.name}.${key}' needs its target first, e.g. '@ManyToOne(() => Company)'.`);
74
74
  }
75
75
  if (registration.through && registration.references) {
76
76
  throw new UqlUsageError(`'${entity.name}.${key}' joins through a junction, whose column referencing each side is the join; ` +
@@ -246,7 +246,7 @@ function fieldsOf(name, values) {
246
246
  if (field instanceof RelationAggregate) {
247
247
  return [key, aggregateField(field)];
248
248
  }
249
- // The types refuse anything else; an untyped caller still reaches here.
249
+ // The types refuse anything else, but for an aggregate thunk, whose constraint cannot read what it returns.
250
250
  if (!isColumn(field)) {
251
251
  throw new UqlUsageError(`'${name}.${key}' is neither a column nor an aggregate: declare it as one`);
252
252
  }
@@ -1,8 +1,14 @@
1
- import { createPool, type Pool } from 'mariadb';
1
+ import { createPool, type Pool, type SqlError } from 'mariadb';
2
2
  import { AbstractSqlQuerierPool } from '../querier/index.js';
3
3
  import type { ExtraOptions } from '../type/index.js';
4
4
  import { MariaDialect } from './mariaDialect.js';
5
5
  import { MariadbQuerier } from './mariadbQuerier.js';
6
+ declare module 'mariadb' {
7
+ /** The pool is an `EventEmitter` firing 'error' on a connection it cannot open or clean up, which its types leave out. */
8
+ interface Pool {
9
+ on(ev: 'error', callback: (err: SqlError) => void): Pool;
10
+ }
11
+ }
6
12
  type PoolConfig = Exclude<Parameters<typeof createPool>[0], string>;
7
13
  export declare class MariadbQuerierPool extends AbstractSqlQuerierPool<MariadbQuerier, MariaDialect> {
8
14
  readonly pool: Pool;
@@ -13,7 +13,6 @@ export class MariadbQuerierPool extends AbstractSqlQuerierPool {
13
13
  // reads as its UTC text, which hydration decodes, since the connector would take it for local time
14
14
  // whatever `timezone` says; that only sets the session's zone, UTC, so `NOW()` agrees.
15
15
  this.pool = createPool({ timezone: 'Z', dateStrings: true, ...opts });
16
- // `mariadb` fires 'error' at runtime without declaring it, hence the cast; this makes it visible.
17
16
  attachPoolErrorHandler(this.pool, 'MariaDB pool connection encountered an error', extra?.logger);
18
17
  }
19
18
  async getQuerier() {
@@ -169,14 +169,13 @@ export class EntityCodeGenerator {
169
169
  const relatedClassName = this.options.classNameTransformer(rel.to.table.name);
170
170
  const references = this.referencesSource(rel, relatedClassName);
171
171
  const options = [
172
- `entity: () => ${relatedClassName}`,
173
172
  ...(references ? [`references: ${references}`] : []),
174
173
  ...(rel.onDelete && rel.onDelete !== DEFAULT_FOREIGN_KEY_ACTION ? [`onDelete: '${rel.onDelete}'`] : []),
175
174
  ...(rel.onUpdate && rel.onUpdate !== DEFAULT_FOREIGN_KEY_ACTION ? [`onUpdate: '${rel.onUpdate}'`] : []),
176
175
  ];
177
176
  return [
178
177
  ...this.syncDoc(`Relation to ${rel.to.table.name} via ${rel.from.columns.map((c) => c.name).join(', ')}`),
179
- ` @${rel.type}({ ${options.join(', ')} })`,
178
+ ` @${rel.type}(() => ${relatedClassName}${options.length ? `, { ${options.join(', ')} }` : ''})`,
180
179
  ` ${this.owningPropertyName(rel)}?: ${relatedClassName};`,
181
180
  ].join('\n');
182
181
  }
@@ -225,7 +224,7 @@ export class EntityCodeGenerator {
225
224
  const many = inverseType === 'OneToMany' || inverseType === 'ManyToMany';
226
225
  return [
227
226
  ...this.syncDoc(`Inverse relation from ${rel.from.table.name}`),
228
- ` @${inverseType}({ entity: () => ${relatedClassName}, mappedBy: (${param}) => ${inverse} })`,
227
+ ` @${inverseType}(() => ${relatedClassName}, { mappedBy: (${param}) => ${inverse} })`,
229
228
  ` ${this.inversePropertyName(rel)}?: ${relatedClassName}${many ? '[]' : ''};`,
230
229
  ].join('\n');
231
230
  }
@@ -1,11 +1,11 @@
1
1
  import { AbstractSqlQuerier, type BoundStatement } from '../querier/index.js';
2
- import type { ExtraOptions, TransactionOptions } from '../type/index.js';
2
+ import type { ExtraOptions, RawRow, TransactionOptions } from '../type/index.js';
3
3
  import type { SqlExecution } from '../util/sql.util.js';
4
4
  import { type SqliteBindValue } from './bindValues.js';
5
5
  import type { SqliteDialect } from './sqliteDialect.js';
6
6
  export type HranaInValue = SqliteBindValue | ArrayBuffer | Date;
7
7
  export type HranaResultSet = {
8
- rows: unknown[];
8
+ rows: RawRow[];
9
9
  rowsAffected: number;
10
10
  };
11
11
  export type HranaStatement = {
@@ -18,7 +18,7 @@ export type LocalSqlitePoolOptions = {
18
18
  export type LocalSqliteDatabase = {
19
19
  prepare(sql: string): SqlitePreparedStatement;
20
20
  loadExtension(path: string): void;
21
- /** Defines a SQL function, which `bun:sqlite` cannot. */
21
+ /** Defines a SQL function, which `bun:sqlite` has only in its newer releases. */
22
22
  function?(name: string, options: {
23
23
  deterministic: boolean;
24
24
  }, fn: (...args: SqlValue[]) => SqlValue): unknown;
@@ -13,8 +13,8 @@ export declare class SqliteQuerierPool extends AbstractLocalSqliteQuerierPool<Lo
13
13
  readonly opts?: SqlitePoolOptions | undefined;
14
14
  constructor(filename?: string | Buffer, opts?: SqlitePoolOptions | undefined, extra?: ExtraOptions);
15
15
  /**
16
- * `bun:sqlite` rejects option keys it does not know, so `extensions` is stripped out, and opens only a
17
- * path, so a serialized database - which better-sqlite3 takes as its filename - is deserialized there instead.
16
+ * `extensions` is uql's, so it never reaches the driver. `bun:sqlite` opens only a path, so a serialized
17
+ * database, which better-sqlite3 takes as its filename, is deserialized there instead.
18
18
  */
19
19
  protected createDb(): Promise<LocalSqliteDatabase>;
20
20
  }
@@ -14,8 +14,8 @@ export class SqliteQuerierPool extends AbstractLocalSqliteQuerierPool {
14
14
  this.opts = opts;
15
15
  }
16
16
  /**
17
- * `bun:sqlite` rejects option keys it does not know, so `extensions` is stripped out, and opens only a
18
- * path, so a serialized database - which better-sqlite3 takes as its filename - is deserialized there instead.
17
+ * `extensions` is uql's, so it never reaches the driver. `bun:sqlite` opens only a path, so a serialized
18
+ * database, which better-sqlite3 takes as its filename, is deserialized there instead.
19
19
  */
20
20
  async createDb() {
21
21
  const { extensions, ...driverOpts } = this.opts ?? {};
@@ -76,6 +76,13 @@ export type AggregateFields = {
76
76
  readonly computed: QuerySql;
77
77
  }>;
78
78
  };
79
+ /**
80
+ * What `relations` constrains its aggregates to: a thunk returning `void`, which TypeScript checks without reading what it
81
+ * returns. Reading it would read a tree's own to-many while its type is inferred (TS7022); first read refuses a wrong value.
82
+ */
83
+ type AggregateThunks = {
84
+ readonly [key: string]: () => void;
85
+ };
79
86
  /** The aggregate fields a `relations` callback declares, as a row reads them, never written. */
80
87
  export type AggregateRow<A> = {
81
88
  readonly [K in keyof A]-?: A[K] extends () => infer F ? FieldValue<F> : never;
@@ -160,7 +167,7 @@ type DefinedSections<Row, Key, Columns, B, Abstract> = {
160
167
  * The relations, each read lazily so entities pointing at each other declare in either order, and the values
161
168
  * read over the to-many ones, its base's too: `(author) => ({ postCount: () => author.posts.count() })`.
162
169
  */
163
- relations<const R, const A extends AggregateFields = {}>(relations: (rel: RelationBuilder<Columns>) => R, aggregates?: (refs: RefMap<Columns> & AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): RelatedEntity<Row & RelationRow<R> & AggregateRow<A>, Key, Columns, Abstract>;
170
+ relations<const R, const A extends AggregateThunks = {}>(relations: (rel: RelationBuilder<Columns>) => R, aggregates?: (refs: RefMap<Columns> & AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): RelatedEntity<Row & RelationRow<R> & AggregateRow<A>, Key, Columns, Abstract>;
164
171
  };
165
172
  /** A defined entity's class once its relations are in: its filters may follow, and read through them. */
166
173
  export type RelatedEntity<Row, Key, Columns, Abstract = false> = DefinedClass<Row, Key, Columns, Abstract> & {
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.111.2",
6
+ "version": "0.112.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -67,7 +67,7 @@ export class User {
67
67
  @Field(f.string().unique())
68
68
  email!: string;
69
69
 
70
- @OneToMany({ entity: () => Post, mappedBy: (post) => post.author })
70
+ @OneToMany(() => Post, { mappedBy: (post) => post.author })
71
71
  posts?: Post[];
72
72
  }
73
73
 
@@ -82,7 +82,7 @@ export class Post {
82
82
  @Field(f.references(() => User).nullable())
83
83
  authorId?: string | null;
84
84
 
85
- @ManyToOne({ entity: () => User, references: (post) => post.authorId })
85
+ @ManyToOne(() => User, { references: (post) => post.authorId })
86
86
  author?: User;
87
87
  }
88
88
  ```
@@ -92,7 +92,7 @@ export class Post {
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.
95
- - `mappedBy` and `references` may be left out where only one member fits. `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity. `cascade: true` writes related rows with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
95
+ - A relation decorator takes its target first, then its options, as `rel.*` does. `mappedBy` and `references` may be left out where only one member fits, and then the options too: `@OneToMany(() => Post)`. `@ManyToMany(() => Tag, { through: () => PostTag })` names the junction entity. `cascade: true` writes related rows with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
96
96
  - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring entity options but no table is `@Entity({ abstract: true, ... }) abstract class`, which cannot be queried.
97
97
  - Optimistic lock: `@Field(f.version())` with `[versionKey]?: 'version'` on the class. An update, and an upsert or save of a row that exists, must carry the version it read; a stale one throws `UqlOptimisticLockError`.
98
98
  - Computed fields are `readonly`: ``@Computed((u) => f.string().as(sql`${u.first} || ' ' || ${u.last}`))``, `.stored()` for a generated column, or a relation aggregate, `@Computed((user) => user.posts.count())`.
@@ -120,7 +120,7 @@ export const Author = defineEntity({
120
120
  (rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }),
121
121
  (author) => ({ bookCount: () => author.books.count() }),
122
122
  );
123
- export type Author = InstanceType<typeof Author>;
123
+ export interface Author extends InstanceType<typeof Author> {}
124
124
 
125
125
  export const Book = defineEntity({
126
126
  name: 'Book',
@@ -138,7 +138,7 @@ export const Book = defineEntity({
138
138
  }));
139
139
  ```
140
140
 
141
- - Columns are the same builders. No `!` or `?` to write: a `.nullable()` column reads `| null`, a default makes it optional on insert, `f.enum()` gives the literal union. A constructor's type argument narrows the column, a brand or a JSON payload with no runtime schema: `f.uuid<UserId>().id()`, `f.json<Settings>()`. It checks the type against the column and exists only in types; a default is written as that type. A filter then takes the branded type, and a foreign key to a branded key must carry the same brand, whether a relation or a decorated property declares it.
141
+ - Columns are the same builders. No `!` or `?` to write: a `.nullable()` column reads `| null`, a default makes it optional on insert, `f.enum()` gives the literal union. A constructor's type argument narrows the column, a brand or a JSON payload with no runtime schema: `f.uuid<UserId>().id()`, `f.json<Settings>()`. It checks the type against the column and exists only in types; a default is written as that type. A filter then takes the branded type, and a foreign key to a branded key must carry the same brand, whether a relation or a decorated property declares it. Name its rows with an interface, `export interface Author extends InstanceType<typeof Author> {}`: hovers and errors then print `Author`, which a type alias expands.
142
142
  - `defineEntity` takes `name` (the table derives from it), `table`, `schema`, `extends`, `abstract` and `fields`. Every other option is a section chained after it, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters`, `hooks`, then `relations` last; only a `filters` reading through relations follows it.
143
143
  - A relation is a thunk, so entities pointing at each other can sit in any order and file. A foreign key is a plain field that a `manyToOne` names as `references`, checked against the target's key type. `relations`' second callback declares aggregate fields: aggregates over a to-many, or expressions mixing them with columns.
144
144
  - A JSON column's payload is any Standard Schema (Zod, Valibot, ArkType), typed by its output. uql never runs it, so a write is not validated.