metal-orm 1.0.33 → 1.0.34

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/dist/index.d.ts CHANGED
@@ -1,5 +1,714 @@
1
- import { L as LiteralNode, O as OperandNode, C as ColumnRef, a as ColumnNode, B as BinaryExpressionNode, E as ExpressionNode, b as LogicalExpressionNode, N as NullExpressionNode, I as InExpressionNode, c as BetweenExpressionNode, J as JsonPathNode, d as CaseExpressionNode, S as SelectQueryNode, e as ExistsExpressionNode, W as WindowFunctionNode, f as OrderDirection, F as FunctionNode, g as ScalarSubqueryNode, h as ColumnDef, T as TableRef, i as TableDef, j as InsertQueryNode, k as InsertCompiler, l as CompiledQuery, D as Dialect, m as DialectKey, U as UpdateQueryNode, n as UpdateCompiler, o as DeleteQueryNode, p as DeleteCompiler, q as CompilerContext, r as FunctionTableNode, s as DerivedTableNode, t as TableSourceNode, u as ForeignKeyReference, v as IndexColumn, w as IndexDef, x as DbExecutor, H as HydrationPlan, y as NamingStrategy, R as RelationMap, z as EntityContext, A as Entity, G as HasManyRelation, K as HasOneRelation, M as BelongsToRelation, P as BelongsToManyRelation, Q as HasManyCollection, V as BelongsToReference, X as ManyToManyCollection, Y as OrmSession, Z as SelectQueryBuilder, _ as ExecutionContext, $ as HydrationContext } from './select-BuMpVcVt.js';
2
- export { aL as AnyDomainEvent, ab as CascadeMode, a0 as CheckConstraint, ai as ColumnToTs, a4 as ColumnType, ay as DbExecutorFactory, a7 as DefaultValue, aK as DomainEvent, aD as DomainEventBus, aB as DomainEventHandler, aF as EntityStatus, az as ExternalTransaction, aN as HasDomainEvents, ak as HasOneReference, au as HydrationMetadata, as as HydrationPivotPlan, at as HydrationRelationPlan, aj as InferRow, aC as InitialHandlers, aA as Orm, aM as OrmDomainEvent, av as OrmInterceptor, ax as OrmOptions, aw as OrmSessionOptions, aO as QueryLogEntry, aP as QueryLogger, aR as QueryResult, a6 as RawDefaultValue, a5 as ReferentialAction, aI as RelationChange, aJ as RelationChangeEntry, ac as RelationDef, aH as RelationKey, a9 as RelationKinds, ah as RelationTargetTable, aa as RelationType, aT as SimpleQueryRunner, a2 as TableHooks, a1 as TableOptions, aG as TrackedEntity, aE as addDomainEvent, af as belongsTo, ag as belongsToMany, a8 as col, al as createColumn, aU as createExecutorFromQueryRunner, am as createLiteral, aQ as createQueryLoggingExecutor, a3 as defineTable, ad as hasMany, ae as hasOne, ap as isCaseExpressionNode, ar as isExpressionSelectionNode, ao as isFunctionNode, an as isOperandNode, aq as isWindowFunctionNode, aS as rowsToQueryResult } from './select-BuMpVcVt.js';
1
+ /**
2
+ * Supported column data types for database schema definitions
3
+ */
4
+ type ColumnType = 'INT' | 'INTEGER' | 'BIGINT' | 'VARCHAR' | 'TEXT' | 'JSON' | 'ENUM' | 'DECIMAL' | 'FLOAT' | 'DOUBLE' | 'UUID' | 'BINARY' | 'VARBINARY' | 'BLOB' | 'BYTEA' | 'DATE' | 'DATETIME' | 'TIMESTAMP' | 'TIMESTAMPTZ' | 'BOOLEAN' | 'int' | 'integer' | 'bigint' | 'varchar' | 'text' | 'json' | 'enum' | 'decimal' | 'float' | 'double' | 'uuid' | 'binary' | 'varbinary' | 'blob' | 'bytea' | 'date' | 'datetime' | 'timestamp' | 'timestamptz' | 'boolean';
5
+ type ReferentialAction = 'NO ACTION' | 'RESTRICT' | 'CASCADE' | 'SET NULL' | 'SET DEFAULT';
6
+ interface RawDefaultValue {
7
+ raw: string;
8
+ }
9
+ type DefaultValue = unknown | RawDefaultValue;
10
+ interface ForeignKeyReference {
11
+ /** Target table name */
12
+ table: string;
13
+ /** Target column name */
14
+ column: string;
15
+ /** Optional constraint name */
16
+ name?: string;
17
+ /** ON DELETE action */
18
+ onDelete?: ReferentialAction;
19
+ /** ON UPDATE action */
20
+ onUpdate?: ReferentialAction;
21
+ /** Whether the constraint is deferrable (Postgres) */
22
+ deferrable?: boolean;
23
+ }
24
+ /**
25
+ * Definition of a database column
26
+ */
27
+ interface ColumnDef<T extends ColumnType = ColumnType> {
28
+ /** Column name (filled at runtime by defineTable) */
29
+ name: string;
30
+ /** Data type of the column */
31
+ type: T;
32
+ /** Whether this column is a primary key */
33
+ primary?: boolean;
34
+ /** Whether this column cannot be null */
35
+ notNull?: boolean;
36
+ /** Whether this column must be unique (or name of the unique constraint) */
37
+ unique?: boolean | string;
38
+ /** Default value for the column */
39
+ default?: DefaultValue;
40
+ /** Whether the column auto-increments / identity */
41
+ autoIncrement?: boolean;
42
+ /** Identity strategy where supported */
43
+ generated?: 'always' | 'byDefault';
44
+ /** Inline check constraint expression */
45
+ check?: string;
46
+ /** Foreign key reference */
47
+ references?: ForeignKeyReference;
48
+ /** Column comment/description */
49
+ comment?: string;
50
+ /** Additional arguments for the column type (e.g., VARCHAR length) */
51
+ args?: any[];
52
+ /** Table name this column belongs to (filled at runtime by defineTable) */
53
+ table?: string;
54
+ }
55
+ /**
56
+ * Factory for creating column definitions with common data types
57
+ */
58
+ declare const col: {
59
+ /**
60
+ * Creates an integer column definition
61
+ * @returns ColumnDef with INT type
62
+ */
63
+ int: () => ColumnDef<"INT">;
64
+ /**
65
+ * Creates a big integer column definition
66
+ */
67
+ bigint: () => ColumnDef<"BIGINT">;
68
+ /**
69
+ * Creates a variable character column definition
70
+ * @param length - Maximum length of the string
71
+ * @returns ColumnDef with VARCHAR type
72
+ */
73
+ varchar: (length: number) => ColumnDef<"VARCHAR">;
74
+ /**
75
+ * Creates a fixed precision decimal column definition
76
+ */
77
+ decimal: (precision: number, scale?: number) => ColumnDef<"DECIMAL">;
78
+ /**
79
+ * Creates a floating point column definition
80
+ */
81
+ float: (precision?: number) => ColumnDef<"FLOAT">;
82
+ /**
83
+ * Creates a UUID column definition
84
+ */
85
+ uuid: () => ColumnDef<"UUID">;
86
+ /**
87
+ * Creates a binary large object column definition
88
+ */
89
+ blob: () => ColumnDef<"BLOB">;
90
+ /**
91
+ * Creates a fixed-length binary column definition
92
+ */
93
+ binary: (length?: number) => ColumnDef<"BINARY">;
94
+ /**
95
+ * Creates a variable-length binary column definition
96
+ */
97
+ varbinary: (length?: number) => ColumnDef<"VARBINARY">;
98
+ /**
99
+ * Creates a Postgres bytea column definition
100
+ */
101
+ bytea: () => ColumnDef<"BYTEA">;
102
+ /**
103
+ * Creates a timestamp column definition
104
+ */
105
+ timestamp: () => ColumnDef<"TIMESTAMP">;
106
+ /**
107
+ * Creates a timestamptz column definition
108
+ */
109
+ timestamptz: () => ColumnDef<"TIMESTAMPTZ">;
110
+ /**
111
+ * Creates a date column definition
112
+ */
113
+ date: () => ColumnDef<"DATE">;
114
+ /**
115
+ * Creates a datetime column definition
116
+ */
117
+ datetime: () => ColumnDef<"DATETIME">;
118
+ /**
119
+ * Creates a JSON column definition
120
+ * @returns ColumnDef with JSON type
121
+ */
122
+ json: () => ColumnDef<"JSON">;
123
+ /**
124
+ * Creates a boolean column definition
125
+ * @returns ColumnDef with BOOLEAN type
126
+ */
127
+ boolean: () => ColumnDef<"BOOLEAN">;
128
+ /**
129
+ * Creates an enum column definition
130
+ * @param values - Enum values
131
+ */
132
+ enum: (values: string[]) => ColumnDef<"ENUM">;
133
+ /**
134
+ * Marks a column definition as a primary key
135
+ * @param def - Column definition to modify
136
+ * @returns Modified ColumnDef with primary: true
137
+ */
138
+ primaryKey: <T extends ColumnType>(def: ColumnDef<T>) => ColumnDef<T>;
139
+ /**
140
+ * Marks a column as NOT NULL
141
+ */
142
+ notNull: <T extends ColumnType>(def: ColumnDef<T>) => ColumnDef<T>;
143
+ /**
144
+ * Marks a column as UNIQUE
145
+ */
146
+ unique: <T extends ColumnType>(def: ColumnDef<T>, name?: string) => ColumnDef<T>;
147
+ /**
148
+ * Sets a default value for the column
149
+ */
150
+ default: <T extends ColumnType>(def: ColumnDef<T>, value: unknown) => ColumnDef<T>;
151
+ /**
152
+ * Sets a raw SQL default value for the column
153
+ */
154
+ defaultRaw: <T extends ColumnType>(def: ColumnDef<T>, expression: string) => ColumnDef<T>;
155
+ /**
156
+ * Marks a column as auto-increment / identity
157
+ */
158
+ autoIncrement: <T extends ColumnType>(def: ColumnDef<T>, strategy?: ColumnDef["generated"]) => ColumnDef<T>;
159
+ /**
160
+ * Adds a foreign key reference
161
+ */
162
+ references: <T extends ColumnType>(def: ColumnDef<T>, ref: ForeignKeyReference) => ColumnDef<T>;
163
+ /**
164
+ * Adds a check constraint to the column
165
+ */
166
+ check: <T extends ColumnType>(def: ColumnDef<T>, expression: string) => ColumnDef<T>;
167
+ };
168
+
169
+ /**
170
+ * Types of relationships supported between tables
171
+ */
172
+ declare const RelationKinds: {
173
+ /** One-to-one relationship */
174
+ readonly HasOne: "HAS_ONE";
175
+ /** One-to-many relationship */
176
+ readonly HasMany: "HAS_MANY";
177
+ /** Many-to-one relationship */
178
+ readonly BelongsTo: "BELONGS_TO";
179
+ /** Many-to-many relationship with pivot metadata */
180
+ readonly BelongsToMany: "BELONGS_TO_MANY";
181
+ };
182
+ /**
183
+ * Type representing the supported relationship kinds
184
+ */
185
+ type RelationType = (typeof RelationKinds)[keyof typeof RelationKinds];
186
+ type CascadeMode = 'none' | 'all' | 'persist' | 'remove' | 'link';
187
+ /**
188
+ * One-to-many relationship definition
189
+ */
190
+ interface HasManyRelation<TTarget extends TableDef = TableDef> {
191
+ type: typeof RelationKinds.HasMany;
192
+ target: TTarget;
193
+ foreignKey: string;
194
+ localKey?: string;
195
+ cascade?: CascadeMode;
196
+ }
197
+ /**
198
+ * One-to-one relationship definition
199
+ */
200
+ interface HasOneRelation<TTarget extends TableDef = TableDef> {
201
+ type: typeof RelationKinds.HasOne;
202
+ target: TTarget;
203
+ foreignKey: string;
204
+ localKey?: string;
205
+ cascade?: CascadeMode;
206
+ }
207
+ /**
208
+ * Many-to-one relationship definition
209
+ */
210
+ interface BelongsToRelation<TTarget extends TableDef = TableDef> {
211
+ type: typeof RelationKinds.BelongsTo;
212
+ target: TTarget;
213
+ foreignKey: string;
214
+ localKey?: string;
215
+ cascade?: CascadeMode;
216
+ }
217
+ /**
218
+ * Many-to-many relationship definition with rich pivot metadata
219
+ */
220
+ interface BelongsToManyRelation<TTarget extends TableDef = TableDef> {
221
+ type: typeof RelationKinds.BelongsToMany;
222
+ target: TTarget;
223
+ pivotTable: TableDef;
224
+ pivotForeignKeyToRoot: string;
225
+ pivotForeignKeyToTarget: string;
226
+ localKey?: string;
227
+ targetKey?: string;
228
+ pivotPrimaryKey?: string;
229
+ defaultPivotColumns?: string[];
230
+ cascade?: CascadeMode;
231
+ }
232
+ /**
233
+ * Union type representing any supported relationship definition
234
+ */
235
+ type RelationDef = HasManyRelation | HasOneRelation | BelongsToRelation | BelongsToManyRelation;
236
+ /**
237
+ * Creates a one-to-many relationship definition
238
+ * @param target - Target table of the relationship
239
+ * @param foreignKey - Foreign key column name on the child table
240
+ * @param localKey - Local key column name (optional)
241
+ * @returns HasManyRelation definition
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * hasMany(usersTable, 'user_id')
246
+ * ```
247
+ */
248
+ declare const hasMany: <TTarget extends TableDef>(target: TTarget, foreignKey: string, localKey?: string, cascade?: CascadeMode) => HasManyRelation<TTarget>;
249
+ /**
250
+ * Creates a one-to-one relationship definition
251
+ * @param target - Target table of the relationship
252
+ * @param foreignKey - Foreign key column name on the child table
253
+ * @param localKey - Local key column name (optional)
254
+ * @returns HasOneRelation definition
255
+ */
256
+ declare const hasOne: <TTarget extends TableDef>(target: TTarget, foreignKey: string, localKey?: string, cascade?: CascadeMode) => HasOneRelation<TTarget>;
257
+ /**
258
+ * Creates a many-to-one relationship definition
259
+ * @param target - Target table of the relationship
260
+ * @param foreignKey - Foreign key column name on the child table
261
+ * @param localKey - Local key column name (optional)
262
+ * @returns BelongsToRelation definition
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * belongsTo(usersTable, 'user_id')
267
+ * ```
268
+ */
269
+ declare const belongsTo: <TTarget extends TableDef>(target: TTarget, foreignKey: string, localKey?: string, cascade?: CascadeMode) => BelongsToRelation<TTarget>;
270
+ /**
271
+ * Creates a many-to-many relationship definition with pivot metadata
272
+ * @param target - Target table
273
+ * @param pivotTable - Intermediate pivot table definition
274
+ * @param options - Pivot metadata configuration
275
+ * @returns BelongsToManyRelation definition
276
+ */
277
+ declare const belongsToMany: <TTarget extends TableDef>(target: TTarget, pivotTable: TableDef, options: {
278
+ pivotForeignKeyToRoot: string;
279
+ pivotForeignKeyToTarget: string;
280
+ localKey?: string;
281
+ targetKey?: string;
282
+ pivotPrimaryKey?: string;
283
+ defaultPivotColumns?: string[];
284
+ cascade?: CascadeMode;
285
+ }) => BelongsToManyRelation<TTarget>;
286
+
287
+ interface IndexColumn {
288
+ column: string;
289
+ order?: 'ASC' | 'DESC';
290
+ nulls?: 'FIRST' | 'LAST';
291
+ }
292
+ interface IndexDef {
293
+ name?: string;
294
+ columns: (string | IndexColumn)[];
295
+ unique?: boolean;
296
+ where?: string;
297
+ }
298
+ interface CheckConstraint {
299
+ name?: string;
300
+ expression: string;
301
+ }
302
+ interface TableOptions {
303
+ schema?: string;
304
+ primaryKey?: string[];
305
+ indexes?: IndexDef[];
306
+ checks?: CheckConstraint[];
307
+ comment?: string;
308
+ engine?: string;
309
+ charset?: string;
310
+ collation?: string;
311
+ }
312
+ interface TableHooks {
313
+ beforeInsert?(ctx: unknown, entity: any): Promise<void> | void;
314
+ afterInsert?(ctx: unknown, entity: any): Promise<void> | void;
315
+ beforeUpdate?(ctx: unknown, entity: any): Promise<void> | void;
316
+ afterUpdate?(ctx: unknown, entity: any): Promise<void> | void;
317
+ beforeDelete?(ctx: unknown, entity: any): Promise<void> | void;
318
+ afterDelete?(ctx: unknown, entity: any): Promise<void> | void;
319
+ }
320
+ /**
321
+ * Definition of a database table with its columns and relationships
322
+ * @typeParam T - Type of the columns record
323
+ */
324
+ interface TableDef<T extends Record<string, ColumnDef> = Record<string, ColumnDef>> {
325
+ /** Name of the table */
326
+ name: string;
327
+ /** Optional schema/catalog name */
328
+ schema?: string;
329
+ /** Record of column definitions keyed by column name */
330
+ columns: T;
331
+ /** Record of relationship definitions keyed by relation name */
332
+ relations: Record<string, RelationDef>;
333
+ /** Optional lifecycle hooks */
334
+ hooks?: TableHooks;
335
+ /** Composite primary key definition (falls back to column.primary flags) */
336
+ primaryKey?: string[];
337
+ /** Secondary indexes */
338
+ indexes?: IndexDef[];
339
+ /** Table-level check constraints */
340
+ checks?: CheckConstraint[];
341
+ /** Table comment/description */
342
+ comment?: string;
343
+ /** Dialect-specific options */
344
+ engine?: string;
345
+ charset?: string;
346
+ collation?: string;
347
+ }
348
+ /**
349
+ * Creates a table definition with columns and relationships
350
+ * @typeParam T - Type of the columns record
351
+ * @param name - Name of the table
352
+ * @param columns - Record of column definitions
353
+ * @param relations - Record of relationship definitions (optional)
354
+ * @returns Complete table definition with runtime-filled column metadata
355
+ *
356
+ * @example
357
+ * ```typescript
358
+ * const usersTable = defineTable('users', {
359
+ * id: col.primaryKey(col.int()),
360
+ * name: col.varchar(255),
361
+ * email: col.varchar(255)
362
+ * });
363
+ * ```
364
+ */
365
+ declare const defineTable: <T extends Record<string, ColumnDef>>(name: string, columns: T, relations?: Record<string, RelationDef>, hooks?: TableHooks, options?: TableOptions) => TableDef<T>;
366
+
367
+ /**
368
+ * Resolves a relation definition to its target table type.
369
+ */
370
+ type RelationTargetTable<TRel extends RelationDef> = TRel extends HasManyRelation<infer TTarget> ? TTarget : TRel extends HasOneRelation<infer TTarget> ? TTarget : TRel extends BelongsToRelation<infer TTarget> ? TTarget : TRel extends BelongsToManyRelation<infer TTarget> ? TTarget : never;
371
+ /**
372
+ * Maps a ColumnDef to its TypeScript type representation
373
+ */
374
+ type ColumnToTs<T extends ColumnDef> = T['type'] extends 'INT' | 'INTEGER' | 'int' | 'integer' ? number : T['type'] extends 'BIGINT' | 'bigint' ? number | bigint : T['type'] extends 'DECIMAL' | 'decimal' | 'FLOAT' | 'float' | 'DOUBLE' | 'double' ? number : T['type'] extends 'BOOLEAN' | 'boolean' ? boolean : T['type'] extends 'JSON' | 'json' ? unknown : T['type'] extends 'BLOB' | 'blob' | 'BINARY' | 'binary' | 'VARBINARY' | 'varbinary' | 'BYTEA' | 'bytea' ? Buffer : T['type'] extends 'DATE' | 'date' | 'DATETIME' | 'datetime' | 'TIMESTAMP' | 'timestamp' | 'TIMESTAMPTZ' | 'timestamptz' ? string : string;
375
+ /**
376
+ * Infers a row shape from a table definition
377
+ */
378
+ type InferRow<TTable extends TableDef> = {
379
+ [K in keyof TTable['columns']]: ColumnToTs<TTable['columns'][K]>;
380
+ };
381
+ type RelationResult$1<T extends RelationDef> = T extends HasManyRelation<infer TTarget> ? InferRow<TTarget>[] : T extends HasOneRelation<infer TTarget> ? InferRow<TTarget> | null : T extends BelongsToRelation<infer TTarget> ? InferRow<TTarget> | null : T extends BelongsToManyRelation<infer TTarget> ? (InferRow<TTarget> & {
382
+ _pivot?: any;
383
+ })[] : never;
384
+ /**
385
+ * Maps relation names to the expected row results
386
+ */
387
+ type RelationMap<TTable extends TableDef> = {
388
+ [K in keyof TTable['relations']]: RelationResult$1<TTable['relations'][K]>;
389
+ };
390
+ interface HasManyCollection<TChild> {
391
+ load(): Promise<TChild[]>;
392
+ getItems(): TChild[];
393
+ add(data: Partial<TChild>): TChild;
394
+ attach(entity: TChild): void;
395
+ remove(entity: TChild): void;
396
+ clear(): void;
397
+ }
398
+ interface BelongsToReference<TParent> {
399
+ load(): Promise<TParent | null>;
400
+ get(): TParent | null;
401
+ set(data: Partial<TParent> | TParent | null): TParent | null;
402
+ }
403
+ interface HasOneReference<TChild> {
404
+ load(): Promise<TChild | null>;
405
+ get(): TChild | null;
406
+ set(data: Partial<TChild> | TChild | null): TChild | null;
407
+ }
408
+ interface ManyToManyCollection<TTarget> {
409
+ load(): Promise<TTarget[]>;
410
+ getItems(): TTarget[];
411
+ attach(target: TTarget | number | string): void;
412
+ detach(target: TTarget | number | string): void;
413
+ syncByIds(ids: (number | string)[]): Promise<void>;
414
+ }
415
+ type EntityInstance<TTable extends TableDef, TRow = InferRow<TTable>> = TRow & {
416
+ [K in keyof RelationMap<TTable>]: TTable['relations'][K] extends HasManyRelation<infer TTarget> ? HasManyCollection<EntityInstance<TTarget>> : TTable['relations'][K] extends HasOneRelation<infer TTarget> ? HasOneReference<EntityInstance<TTarget>> : TTable['relations'][K] extends BelongsToManyRelation<infer TTarget> ? ManyToManyCollection<EntityInstance<TTarget>> : TTable['relations'][K] extends BelongsToRelation<infer TTarget> ? BelongsToReference<EntityInstance<TTarget>> : never;
417
+ } & {
418
+ $load<K extends keyof RelationMap<TTable>>(relation: K): Promise<RelationMap<TTable>[K]>;
419
+ };
420
+
421
+ /**
422
+ * SQL operators used in query conditions
423
+ */
424
+ declare const SQL_OPERATORS: {
425
+ /** Equality operator */
426
+ readonly EQUALS: "=";
427
+ /** Not equals operator */
428
+ readonly NOT_EQUALS: "!=";
429
+ /** Greater than operator */
430
+ readonly GREATER_THAN: ">";
431
+ /** Greater than or equal operator */
432
+ readonly GREATER_OR_EQUAL: ">=";
433
+ /** Less than operator */
434
+ readonly LESS_THAN: "<";
435
+ /** Less than or equal operator */
436
+ readonly LESS_OR_EQUAL: "<=";
437
+ /** LIKE pattern matching operator */
438
+ readonly LIKE: "LIKE";
439
+ /** NOT LIKE pattern matching operator */
440
+ readonly NOT_LIKE: "NOT LIKE";
441
+ /** IN membership operator */
442
+ readonly IN: "IN";
443
+ /** NOT IN membership operator */
444
+ readonly NOT_IN: "NOT IN";
445
+ /** BETWEEN range operator */
446
+ readonly BETWEEN: "BETWEEN";
447
+ /** NOT BETWEEN range operator */
448
+ readonly NOT_BETWEEN: "NOT BETWEEN";
449
+ /** IS NULL null check operator */
450
+ readonly IS_NULL: "IS NULL";
451
+ /** IS NOT NULL null check operator */
452
+ readonly IS_NOT_NULL: "IS NOT NULL";
453
+ /** Logical AND operator */
454
+ readonly AND: "AND";
455
+ /** Logical OR operator */
456
+ readonly OR: "OR";
457
+ /** EXISTS operator */
458
+ readonly EXISTS: "EXISTS";
459
+ /** NOT EXISTS operator */
460
+ readonly NOT_EXISTS: "NOT EXISTS";
461
+ };
462
+ /**
463
+ * Type representing any supported SQL operator
464
+ */
465
+ type SqlOperator = (typeof SQL_OPERATORS)[keyof typeof SQL_OPERATORS];
466
+ /**
467
+ * Types of SQL joins supported
468
+ */
469
+ declare const JOIN_KINDS: {
470
+ /** INNER JOIN type */
471
+ readonly INNER: "INNER";
472
+ /** LEFT JOIN type */
473
+ readonly LEFT: "LEFT";
474
+ /** RIGHT JOIN type */
475
+ readonly RIGHT: "RIGHT";
476
+ /** CROSS JOIN type */
477
+ readonly CROSS: "CROSS";
478
+ };
479
+ /**
480
+ * Type representing any supported join kind
481
+ */
482
+ type JoinKind = (typeof JOIN_KINDS)[keyof typeof JOIN_KINDS];
483
+ /**
484
+ * Ordering directions for result sorting
485
+ */
486
+ declare const ORDER_DIRECTIONS: {
487
+ /** Ascending order */
488
+ readonly ASC: "ASC";
489
+ /** Descending order */
490
+ readonly DESC: "DESC";
491
+ };
492
+ /**
493
+ * Type representing any supported order direction
494
+ */
495
+ type OrderDirection = (typeof ORDER_DIRECTIONS)[keyof typeof ORDER_DIRECTIONS];
496
+ /**
497
+ * Supported database dialects
498
+ */
499
+ declare const SUPPORTED_DIALECTS: {
500
+ /** MySQL database dialect */
501
+ readonly MYSQL: "mysql";
502
+ /** SQLite database dialect */
503
+ readonly SQLITE: "sqlite";
504
+ /** Microsoft SQL Server dialect */
505
+ readonly MSSQL: "mssql";
506
+ /** PostgreSQL database dialect */
507
+ readonly POSTGRES: "postgres";
508
+ };
509
+ /**
510
+ * Type representing any supported database dialect
511
+ */
512
+ type DialectName$1 = (typeof SUPPORTED_DIALECTS)[keyof typeof SUPPORTED_DIALECTS];
513
+
514
+ /**
515
+ * Minimal column reference used by AST builders.
516
+ * Accepts any object with a name and optional table/alias fields
517
+ * (schema ColumnDef/TableDef remain structurally compatible).
518
+ */
519
+ interface ColumnRef {
520
+ name: string;
521
+ table?: string;
522
+ alias?: string;
523
+ }
524
+ /**
525
+ * Minimal table reference used by AST builders.
526
+ * Keeps AST decoupled from full schema TableDef shape.
527
+ */
528
+ interface TableRef {
529
+ name: string;
530
+ schema?: string;
531
+ alias?: string;
532
+ }
533
+
534
+ /**
535
+ * AST node representing a literal value
536
+ */
537
+ interface LiteralNode {
538
+ type: 'Literal';
539
+ /** The literal value (string, number, boolean, or null) */
540
+ value: string | number | boolean | null;
541
+ }
542
+ /**
543
+ * AST node representing a column reference
544
+ */
545
+ interface ColumnNode {
546
+ type: 'Column';
547
+ /** Table name the column belongs to */
548
+ table: string;
549
+ /** Column name */
550
+ name: string;
551
+ /** Optional alias for the column */
552
+ alias?: string;
553
+ /** Optional scope marker (e.g., 'outer' for correlated references) */
554
+ scope?: 'outer' | 'default';
555
+ }
556
+ /**
557
+ * AST node representing a function call
558
+ */
559
+ interface FunctionNode {
560
+ type: 'Function';
561
+ /** Function name (e.g., COUNT, SUM) */
562
+ name: string;
563
+ /** Optional canonical function key for dialect-aware rendering */
564
+ fn?: string;
565
+ /** Function arguments */
566
+ args: OperandNode[];
567
+ /** Optional alias for the function result */
568
+ alias?: string;
569
+ /** Optional ORDER BY clause used by aggregations like GROUP_CONCAT */
570
+ orderBy?: OrderByNode[];
571
+ /** Optional separator argument used by GROUP_CONCAT-like functions */
572
+ separator?: OperandNode;
573
+ /** Optional DISTINCT modifier */
574
+ distinct?: boolean;
575
+ }
576
+ /**
577
+ * AST node representing a JSON path expression
578
+ */
579
+ interface JsonPathNode {
580
+ type: 'JsonPath';
581
+ /** Source column */
582
+ column: ColumnNode;
583
+ /** JSON path expression */
584
+ path: string;
585
+ /** Optional alias for the result */
586
+ alias?: string;
587
+ }
588
+ /**
589
+ * AST node representing a scalar subquery
590
+ */
591
+ interface ScalarSubqueryNode {
592
+ type: 'ScalarSubquery';
593
+ /** Subquery to execute */
594
+ query: SelectQueryNode;
595
+ /** Optional alias for the subquery result */
596
+ alias?: string;
597
+ }
598
+ /**
599
+ * AST node representing a CASE expression
600
+ */
601
+ interface CaseExpressionNode {
602
+ type: 'CaseExpression';
603
+ /** WHEN-THEN conditions */
604
+ conditions: {
605
+ when: ExpressionNode;
606
+ then: OperandNode;
607
+ }[];
608
+ /** Optional ELSE clause */
609
+ else?: OperandNode;
610
+ /** Optional alias for the result */
611
+ alias?: string;
612
+ }
613
+ /**
614
+ * AST node representing a window function
615
+ */
616
+ interface WindowFunctionNode {
617
+ type: 'WindowFunction';
618
+ /** Window function name (e.g., ROW_NUMBER, RANK) */
619
+ name: string;
620
+ /** Function arguments */
621
+ args: (ColumnNode | LiteralNode | JsonPathNode)[];
622
+ /** Optional PARTITION BY clause */
623
+ partitionBy?: ColumnNode[];
624
+ /** Optional ORDER BY clause */
625
+ orderBy?: OrderByNode[];
626
+ /** Optional alias for the result */
627
+ alias?: string;
628
+ }
629
+ /**
630
+ * Union type representing any operand that can be used in expressions
631
+ */
632
+ type OperandNode = ColumnNode | LiteralNode | FunctionNode | JsonPathNode | ScalarSubqueryNode | CaseExpressionNode | WindowFunctionNode;
633
+ declare const isOperandNode: (node: any) => node is OperandNode;
634
+ declare const isFunctionNode: (node: any) => node is FunctionNode;
635
+ declare const isCaseExpressionNode: (node: any) => node is CaseExpressionNode;
636
+ declare const isWindowFunctionNode: (node: any) => node is WindowFunctionNode;
637
+ declare const isExpressionSelectionNode: (node: ColumnRef | FunctionNode | CaseExpressionNode | WindowFunctionNode) => node is FunctionNode | CaseExpressionNode | WindowFunctionNode;
638
+ /**
639
+ * AST node representing a binary expression (e.g., column = value)
640
+ */
641
+ interface BinaryExpressionNode {
642
+ type: 'BinaryExpression';
643
+ /** Left operand */
644
+ left: OperandNode;
645
+ /** Comparison operator */
646
+ operator: SqlOperator;
647
+ /** Right operand */
648
+ right: OperandNode;
649
+ /** Optional escape character for LIKE expressions */
650
+ escape?: LiteralNode;
651
+ }
652
+ /**
653
+ * AST node representing a logical expression (AND/OR)
654
+ */
655
+ interface LogicalExpressionNode {
656
+ type: 'LogicalExpression';
657
+ /** Logical operator (AND or OR) */
658
+ operator: 'AND' | 'OR';
659
+ /** Operands to combine */
660
+ operands: ExpressionNode[];
661
+ }
662
+ /**
663
+ * AST node representing a null check expression
664
+ */
665
+ interface NullExpressionNode {
666
+ type: 'NullExpression';
667
+ /** Operand to check for null */
668
+ left: OperandNode;
669
+ /** Null check operator */
670
+ operator: 'IS NULL' | 'IS NOT NULL';
671
+ }
672
+ /**
673
+ * AST node representing an IN/NOT IN expression
674
+ */
675
+ interface InExpressionNode {
676
+ type: 'InExpression';
677
+ /** Left operand to check */
678
+ left: OperandNode;
679
+ /** IN/NOT IN operator */
680
+ operator: 'IN' | 'NOT IN';
681
+ /** Values to check against */
682
+ right: OperandNode[];
683
+ }
684
+ /**
685
+ * AST node representing an EXISTS/NOT EXISTS expression
686
+ */
687
+ interface ExistsExpressionNode {
688
+ type: 'ExistsExpression';
689
+ /** EXISTS/NOT EXISTS operator */
690
+ operator: SqlOperator;
691
+ /** Subquery to check */
692
+ subquery: SelectQueryNode;
693
+ }
694
+ /**
695
+ * AST node representing a BETWEEN/NOT BETWEEN expression
696
+ */
697
+ interface BetweenExpressionNode {
698
+ type: 'BetweenExpression';
699
+ /** Operand to check */
700
+ left: OperandNode;
701
+ /** BETWEEN/NOT BETWEEN operator */
702
+ operator: 'BETWEEN' | 'NOT BETWEEN';
703
+ /** Lower bound */
704
+ lower: OperandNode;
705
+ /** Upper bound */
706
+ upper: OperandNode;
707
+ }
708
+ /**
709
+ * Union type representing any supported expression node
710
+ */
711
+ type ExpressionNode = BinaryExpressionNode | LogicalExpressionNode | NullExpressionNode | InExpressionNode | ExistsExpressionNode | BetweenExpressionNode;
3
712
 
4
713
  type LiteralValue = LiteralNode['value'];
5
714
  type ValueOperandInput = OperandNode | LiteralValue;
@@ -195,132 +904,1843 @@ declare const lead: (col: ColumnRef | ColumnNode, offset?: number, defaultValue?
195
904
  * @param col - Column to get first value from
196
905
  * @returns Window function node for FIRST_VALUE
197
906
  */
198
- declare const firstValue: (col: ColumnRef | ColumnNode) => WindowFunctionNode;
907
+ declare const firstValue: (col: ColumnRef | ColumnNode) => WindowFunctionNode;
908
+ /**
909
+ * Creates a LAST_VALUE window function
910
+ * @param col - Column to get last value from
911
+ * @returns Window function node for LAST_VALUE
912
+ */
913
+ declare const lastValue: (col: ColumnRef | ColumnNode) => WindowFunctionNode;
914
+ /**
915
+ * Creates a custom window function
916
+ * @param name - Window function name
917
+ * @param args - Function arguments
918
+ * @param partitionBy - Optional PARTITION BY columns
919
+ * @param orderBy - Optional ORDER BY clauses
920
+ * @returns Window function node
921
+ */
922
+ declare const windowFunction: (name: string, args?: (ColumnRef | ColumnNode | LiteralNode | JsonPathNode)[], partitionBy?: (ColumnRef | ColumnNode)[], orderBy?: {
923
+ column: ColumnRef | ColumnNode;
924
+ direction: OrderDirection;
925
+ }[]) => WindowFunctionNode;
926
+
927
+ /**
928
+ * Creates a COUNT function expression
929
+ * @param col - Column to count
930
+ * @returns Function node with COUNT
931
+ */
932
+ declare const count: (col: ColumnRef | ColumnNode) => FunctionNode;
933
+ /**
934
+ * Creates a SUM function expression
935
+ * @param col - Column to sum
936
+ * @returns Function node with SUM
937
+ */
938
+ declare const sum: (col: ColumnRef | ColumnNode) => FunctionNode;
939
+ /**
940
+ * Creates an AVG function expression
941
+ * @param col - Column to average
942
+ * @returns Function node with AVG
943
+ */
944
+ declare const avg: (col: ColumnRef | ColumnNode) => FunctionNode;
945
+ /**
946
+ * Creates a MIN function expression
947
+ * @param col - Column to take the minimum of
948
+ * @returns Function node with MIN
949
+ */
950
+ declare const min: (col: ColumnRef | ColumnNode) => FunctionNode;
951
+ /**
952
+ * Creates a MAX function expression
953
+ * @param col - Column to take the maximum of
954
+ * @returns Function node with MAX
955
+ */
956
+ declare const max: (col: ColumnRef | ColumnNode) => FunctionNode;
957
+ type GroupConcatOrderByInput = {
958
+ column: ColumnRef | ColumnNode;
959
+ direction?: OrderDirection;
960
+ };
961
+ type GroupConcatOptions = {
962
+ separator?: ValueOperandInput;
963
+ orderBy?: GroupConcatOrderByInput[];
964
+ };
965
+ /**
966
+ * Aggregates grouped strings into a single value.
967
+ */
968
+ declare const groupConcat: (col: ColumnRef | ColumnNode, options?: GroupConcatOptions) => FunctionNode;
969
+
970
+ /**
971
+ * Visitor for expression nodes
972
+ */
973
+ interface ExpressionVisitor<R> {
974
+ visitBinaryExpression?(node: BinaryExpressionNode): R;
975
+ visitLogicalExpression?(node: LogicalExpressionNode): R;
976
+ visitNullExpression?(node: NullExpressionNode): R;
977
+ visitInExpression?(node: InExpressionNode): R;
978
+ visitExistsExpression?(node: ExistsExpressionNode): R;
979
+ visitBetweenExpression?(node: BetweenExpressionNode): R;
980
+ otherwise?(node: ExpressionNode): R;
981
+ }
982
+ /**
983
+ * Visitor for operand nodes
984
+ */
985
+ interface OperandVisitor<R> {
986
+ visitColumn?(node: ColumnNode): R;
987
+ visitLiteral?(node: LiteralNode): R;
988
+ visitFunction?(node: FunctionNode): R;
989
+ visitJsonPath?(node: JsonPathNode): R;
990
+ visitScalarSubquery?(node: ScalarSubqueryNode): R;
991
+ visitCaseExpression?(node: CaseExpressionNode): R;
992
+ visitWindowFunction?(node: WindowFunctionNode): R;
993
+ otherwise?(node: OperandNode): R;
994
+ }
995
+ type ExpressionDispatch = <R>(node: any, visitor: ExpressionVisitor<R>) => R;
996
+ type OperandDispatch = <R>(node: any, visitor: OperandVisitor<R>) => R;
997
+ /**
998
+ * Registers a dispatcher for a custom expression node type.
999
+ * Allows new node kinds without modifying the core switch.
1000
+ */
1001
+ declare const registerExpressionDispatcher: (type: string, dispatcher: ExpressionDispatch) => void;
1002
+ /**
1003
+ * Registers a dispatcher for a custom operand node type.
1004
+ * Allows new node kinds without modifying the core switch.
1005
+ */
1006
+ declare const registerOperandDispatcher: (type: string, dispatcher: OperandDispatch) => void;
1007
+ /**
1008
+ * Clears all registered dispatchers. Primarily for tests.
1009
+ */
1010
+ declare const clearExpressionDispatchers: () => void;
1011
+ declare const clearOperandDispatchers: () => void;
1012
+ /**
1013
+ * Dispatches an expression node to the visitor
1014
+ * @param node - Expression node to visit
1015
+ * @param visitor - Visitor implementation
1016
+ */
1017
+ declare const visitExpression: <R>(node: ExpressionNode, visitor: ExpressionVisitor<R>) => R;
1018
+ /**
1019
+ * Dispatches an operand node to the visitor
1020
+ * @param node - Operand node to visit
1021
+ * @param visitor - Visitor implementation
1022
+ */
1023
+ declare const visitOperand: <R>(node: OperandNode, visitor: OperandVisitor<R>) => R;
1024
+
1025
+ /**
1026
+ * Adapts a schema ColumnDef to an AST-friendly ColumnRef.
1027
+ */
1028
+ declare const toColumnRef: (col: ColumnRef | ColumnDef) => ColumnRef;
1029
+ /**
1030
+ * Adapts a schema TableDef to an AST-friendly TableRef.
1031
+ */
1032
+ declare const toTableRef: (table: TableRef | TableDef) => TableRef;
1033
+
1034
+ /**
1035
+ * AST node representing a JOIN clause
1036
+ */
1037
+ interface JoinNode {
1038
+ type: 'Join';
1039
+ /** Type of join (INNER, LEFT, RIGHT, etc.) */
1040
+ kind: JoinKind;
1041
+ /** Table to join */
1042
+ table: TableSourceNode;
1043
+ /** Join condition expression */
1044
+ condition: ExpressionNode;
1045
+ /** Optional metadata for non-SQL concerns (e.g., relation name) */
1046
+ meta?: Record<string, unknown>;
1047
+ }
1048
+
1049
+ /**
1050
+ * AST node representing a table reference in a query
1051
+ */
1052
+ interface TableNode {
1053
+ type: 'Table';
1054
+ /** Table name */
1055
+ name: string;
1056
+ /** Optional schema name */
1057
+ schema?: string;
1058
+ /** Optional table alias */
1059
+ alias?: string;
1060
+ }
1061
+ /**
1062
+ * AST node representing a function used as a table source (table-valued function)
1063
+ */
1064
+ interface FunctionTableNode {
1065
+ type: 'FunctionTable';
1066
+ /** Function name */
1067
+ name: string;
1068
+ /** Optional schema for the function (some dialects) */
1069
+ schema?: string;
1070
+ /** Function arguments as operand nodes */
1071
+ args?: any[];
1072
+ /** Optional alias for the function table */
1073
+ alias?: string;
1074
+ /** LATERAL flag */
1075
+ lateral?: boolean;
1076
+ /** WITH ORDINALITY flag */
1077
+ withOrdinality?: boolean;
1078
+ /** Optional column aliases */
1079
+ columnAliases?: string[];
1080
+ }
1081
+ /**
1082
+ * AST node representing a derived table (subquery with an alias)
1083
+ */
1084
+ interface DerivedTableNode {
1085
+ type: 'DerivedTable';
1086
+ /** Subquery providing the rows */
1087
+ query: SelectQueryNode;
1088
+ /** Required alias for the derived table */
1089
+ alias: string;
1090
+ /** Optional column aliases */
1091
+ columnAliases?: string[];
1092
+ }
1093
+ type TableSourceNode = TableNode | FunctionTableNode | DerivedTableNode;
1094
+ /**
1095
+ * AST node representing an ORDER BY clause
1096
+ */
1097
+ interface OrderByNode {
1098
+ type: 'OrderBy';
1099
+ /** Column to order by */
1100
+ column: ColumnNode;
1101
+ /** Order direction (ASC or DESC) */
1102
+ direction: OrderDirection;
1103
+ }
1104
+ /**
1105
+ * AST node representing a Common Table Expression (CTE)
1106
+ */
1107
+ interface CommonTableExpressionNode {
1108
+ type: 'CommonTableExpression';
1109
+ /** CTE name */
1110
+ name: string;
1111
+ /** Optional column names */
1112
+ columns?: string[];
1113
+ /** CTE query */
1114
+ query: SelectQueryNode;
1115
+ /** Whether the CTE is recursive */
1116
+ recursive: boolean;
1117
+ }
1118
+ /**
1119
+ * Supported set operation kinds for compound SELECT queries
1120
+ */
1121
+ type SetOperationKind = 'UNION' | 'UNION ALL' | 'INTERSECT' | 'EXCEPT';
1122
+ /**
1123
+ * AST node representing a set operation (UNION, INTERSECT, etc.)
1124
+ */
1125
+ interface SetOperationNode {
1126
+ type: 'SetOperation';
1127
+ /** Operator to combine queries */
1128
+ operator: SetOperationKind;
1129
+ /** Right-hand query in the compound expression */
1130
+ query: SelectQueryNode;
1131
+ }
1132
+ /**
1133
+ * AST node representing a complete SELECT query
1134
+ */
1135
+ interface SelectQueryNode {
1136
+ type: 'SelectQuery';
1137
+ /** Optional CTEs (WITH clauses) */
1138
+ ctes?: CommonTableExpressionNode[];
1139
+ /** FROM clause table (either a Table or a FunctionTable) */
1140
+ from: TableSourceNode;
1141
+ /** SELECT clause columns */
1142
+ columns: (ColumnNode | FunctionNode | ScalarSubqueryNode | CaseExpressionNode | WindowFunctionNode)[];
1143
+ /** JOIN clauses */
1144
+ joins: JoinNode[];
1145
+ /** Optional WHERE clause */
1146
+ where?: ExpressionNode;
1147
+ /** Optional GROUP BY clause */
1148
+ groupBy?: ColumnNode[];
1149
+ /** Optional HAVING clause */
1150
+ having?: ExpressionNode;
1151
+ /** Optional ORDER BY clause */
1152
+ orderBy?: OrderByNode[];
1153
+ /** Optional LIMIT clause */
1154
+ limit?: number;
1155
+ /** Optional OFFSET clause */
1156
+ offset?: number;
1157
+ /** Optional query metadata */
1158
+ meta?: Record<string, unknown>;
1159
+ /** Optional DISTINCT clause */
1160
+ distinct?: ColumnNode[];
1161
+ /** Optional set operations chaining this query with others */
1162
+ setOps?: SetOperationNode[];
1163
+ }
1164
+ interface InsertQueryNode {
1165
+ type: 'InsertQuery';
1166
+ /** Target table */
1167
+ into: TableNode;
1168
+ /** Column order for inserted values */
1169
+ columns: ColumnNode[];
1170
+ /** Rows of values to insert */
1171
+ values: OperandNode[][];
1172
+ /** Optional RETURNING clause */
1173
+ returning?: ColumnNode[];
1174
+ }
1175
+ interface UpdateAssignmentNode {
1176
+ /** Column to update */
1177
+ column: ColumnNode;
1178
+ /** Value to set */
1179
+ value: OperandNode;
1180
+ }
1181
+ interface UpdateQueryNode {
1182
+ type: 'UpdateQuery';
1183
+ /** Table being updated */
1184
+ table: TableNode;
1185
+ /** Assignments for SET clause */
1186
+ set: UpdateAssignmentNode[];
1187
+ /** Optional WHERE clause */
1188
+ where?: ExpressionNode;
1189
+ /** Optional RETURNING clause */
1190
+ returning?: ColumnNode[];
1191
+ }
1192
+ interface DeleteQueryNode {
1193
+ type: 'DeleteQuery';
1194
+ /** Table to delete from */
1195
+ from: TableNode;
1196
+ /** Optional WHERE clause */
1197
+ where?: ExpressionNode;
1198
+ /** Optional RETURNING clause */
1199
+ returning?: ColumnNode[];
1200
+ }
1201
+
1202
+ /**
1203
+ * Plan describing pivot columns needed for hydration
1204
+ */
1205
+ interface HydrationPivotPlan {
1206
+ table: string;
1207
+ primaryKey: string;
1208
+ aliasPrefix: string;
1209
+ columns: string[];
1210
+ }
1211
+ /**
1212
+ * Plan for hydrating relationship data
1213
+ */
1214
+ interface HydrationRelationPlan {
1215
+ /** Name of the relationship */
1216
+ name: string;
1217
+ /** Alias prefix for the relationship */
1218
+ aliasPrefix: string;
1219
+ /** Type of relationship */
1220
+ type: RelationType;
1221
+ /** Target table name */
1222
+ targetTable: string;
1223
+ /** Target table primary key */
1224
+ targetPrimaryKey: string;
1225
+ /** Foreign key column */
1226
+ foreignKey: string;
1227
+ /** Local key column */
1228
+ localKey: string;
1229
+ /** Columns to include */
1230
+ columns: string[];
1231
+ /** Optional pivot plan for many-to-many relationships */
1232
+ pivot?: HydrationPivotPlan;
1233
+ }
1234
+ /**
1235
+ * Complete hydration plan for a query
1236
+ */
1237
+ interface HydrationPlan {
1238
+ /** Root table name */
1239
+ rootTable: string;
1240
+ /** Root table primary key */
1241
+ rootPrimaryKey: string;
1242
+ /** Root table columns */
1243
+ rootColumns: string[];
1244
+ /** Relationship hydration plans */
1245
+ relations: HydrationRelationPlan[];
1246
+ }
1247
+ /**
1248
+ * Metadata bag for attaching hydration to query ASTs without coupling AST types.
1249
+ */
1250
+ interface HydrationMetadata {
1251
+ hydration?: HydrationPlan;
1252
+ [key: string]: unknown;
1253
+ }
1254
+
1255
+ interface FunctionRenderContext {
1256
+ node: FunctionNode;
1257
+ compiledArgs: string[];
1258
+ /** Helper to compile additional operands (e.g., separators or ORDER BY columns) */
1259
+ compileOperand: (operand: OperandNode) => string;
1260
+ }
1261
+ type FunctionRenderer = (ctx: FunctionRenderContext) => string;
1262
+ interface FunctionStrategy {
1263
+ /**
1264
+ * Returns a renderer for a specific function name (e.g. "DATE_ADD").
1265
+ * Returns undefined if this dialect doesn't support the function.
1266
+ */
1267
+ getRenderer(functionName: string): FunctionRenderer | undefined;
1268
+ }
1269
+
1270
+ /**
1271
+ * Context for SQL compilation with parameter management
1272
+ */
1273
+ interface CompilerContext {
1274
+ /** Array of parameters */
1275
+ params: unknown[];
1276
+ /** Function to add a parameter and get its placeholder */
1277
+ addParameter(value: unknown): string;
1278
+ }
1279
+ /**
1280
+ * Result of SQL compilation
1281
+ */
1282
+ interface CompiledQuery {
1283
+ /** Generated SQL string */
1284
+ sql: string;
1285
+ /** Parameters for the query */
1286
+ params: unknown[];
1287
+ }
1288
+ interface SelectCompiler {
1289
+ compileSelect(ast: SelectQueryNode): CompiledQuery;
1290
+ }
1291
+ interface InsertCompiler {
1292
+ compileInsert(ast: InsertQueryNode): CompiledQuery;
1293
+ }
1294
+ interface UpdateCompiler {
1295
+ compileUpdate(ast: UpdateQueryNode): CompiledQuery;
1296
+ }
1297
+ interface DeleteCompiler {
1298
+ compileDelete(ast: DeleteQueryNode): CompiledQuery;
1299
+ }
1300
+ /**
1301
+ * Abstract base class for SQL dialect implementations
1302
+ */
1303
+ declare abstract class Dialect implements SelectCompiler, InsertCompiler, UpdateCompiler, DeleteCompiler {
1304
+ /** Dialect identifier used for function rendering and formatting */
1305
+ protected abstract readonly dialect: DialectName$1;
1306
+ /**
1307
+ * Compiles a SELECT query AST to SQL
1308
+ * @param ast - Query AST to compile
1309
+ * @returns Compiled query with SQL and parameters
1310
+ */
1311
+ compileSelect(ast: SelectQueryNode): CompiledQuery;
1312
+ compileInsert(ast: InsertQueryNode): CompiledQuery;
1313
+ compileUpdate(ast: UpdateQueryNode): CompiledQuery;
1314
+ compileDelete(ast: DeleteQueryNode): CompiledQuery;
1315
+ supportsReturning(): boolean;
1316
+ /**
1317
+ * Compiles SELECT query AST to SQL (to be implemented by concrete dialects)
1318
+ * @param ast - Query AST
1319
+ * @param ctx - Compiler context
1320
+ * @returns SQL string
1321
+ */
1322
+ protected abstract compileSelectAst(ast: SelectQueryNode, ctx: CompilerContext): string;
1323
+ protected abstract compileInsertAst(ast: InsertQueryNode, ctx: CompilerContext): string;
1324
+ protected abstract compileUpdateAst(ast: UpdateQueryNode, ctx: CompilerContext): string;
1325
+ protected abstract compileDeleteAst(ast: DeleteQueryNode, ctx: CompilerContext): string;
1326
+ /**
1327
+ * Quotes an SQL identifier (to be implemented by concrete dialects)
1328
+ * @param id - Identifier to quote
1329
+ * @returns Quoted identifier
1330
+ */
1331
+ abstract quoteIdentifier(id: string): string;
1332
+ /**
1333
+ * Compiles a WHERE clause
1334
+ * @param where - WHERE expression
1335
+ * @param ctx - Compiler context
1336
+ * @returns SQL WHERE clause or empty string
1337
+ */
1338
+ protected compileWhere(where: ExpressionNode | undefined, ctx: CompilerContext): string;
1339
+ protected compileReturning(returning: ColumnNode[] | undefined, ctx: CompilerContext): string;
1340
+ /**
1341
+ * Generates subquery for EXISTS expressions
1342
+ * Rule: Always forces SELECT 1, ignoring column list
1343
+ * Maintains FROM, JOINs, WHERE, GROUP BY, ORDER BY, LIMIT/OFFSET
1344
+ * Does not add ';' at the end
1345
+ * @param ast - Query AST
1346
+ * @param ctx - Compiler context
1347
+ * @returns SQL for EXISTS subquery
1348
+ */
1349
+ protected compileSelectForExists(ast: SelectQueryNode, ctx: CompilerContext): string;
1350
+ /**
1351
+ * Creates a new compiler context
1352
+ * @returns Compiler context with parameter management
1353
+ */
1354
+ protected createCompilerContext(): CompilerContext;
1355
+ /**
1356
+ * Formats a parameter placeholder
1357
+ * @param index - Parameter index
1358
+ * @returns Formatted placeholder string
1359
+ */
1360
+ protected formatPlaceholder(index: number): string;
1361
+ /**
1362
+ * Whether the current dialect supports a given set operation.
1363
+ * Override in concrete dialects to restrict support.
1364
+ */
1365
+ protected supportsSetOperation(kind: SetOperationKind): boolean;
1366
+ /**
1367
+ * Validates set-operation semantics:
1368
+ * - Ensures the dialect supports requested operators.
1369
+ * - Enforces that only the outermost compound query may have ORDER/LIMIT/OFFSET.
1370
+ * @param ast - Query to validate
1371
+ * @param isOutermost - Whether this node is the outermost compound query
1372
+ */
1373
+ protected validateSetOperations(ast: SelectQueryNode, isOutermost?: boolean): void;
1374
+ /**
1375
+ * Hoists CTEs from set-operation operands to the outermost query so WITH appears once.
1376
+ * @param ast - Query AST
1377
+ * @returns Normalized AST without inner CTEs and a list of hoisted CTEs
1378
+ */
1379
+ private hoistCtes;
1380
+ /**
1381
+ * Normalizes a SELECT AST before compilation (validation + CTE hoisting).
1382
+ * @param ast - Query AST
1383
+ * @returns Normalized query AST
1384
+ */
1385
+ protected normalizeSelectAst(ast: SelectQueryNode): SelectQueryNode;
1386
+ private readonly expressionCompilers;
1387
+ private readonly operandCompilers;
1388
+ protected readonly functionStrategy: FunctionStrategy;
1389
+ protected constructor(functionStrategy?: FunctionStrategy);
1390
+ /**
1391
+ * Creates a new Dialect instance (for testing purposes)
1392
+ * @param functionStrategy - Optional function strategy
1393
+ * @returns New Dialect instance
1394
+ */
1395
+ static create(functionStrategy?: FunctionStrategy): Dialect;
1396
+ /**
1397
+ * Registers an expression compiler for a specific node type
1398
+ * @param type - Expression node type
1399
+ * @param compiler - Compiler function
1400
+ */
1401
+ protected registerExpressionCompiler<T extends ExpressionNode>(type: T['type'], compiler: (node: T, ctx: CompilerContext) => string): void;
1402
+ /**
1403
+ * Registers an operand compiler for a specific node type
1404
+ * @param type - Operand node type
1405
+ * @param compiler - Compiler function
1406
+ */
1407
+ protected registerOperandCompiler<T extends OperandNode>(type: T['type'], compiler: (node: T, ctx: CompilerContext) => string): void;
1408
+ /**
1409
+ * Compiles an expression node
1410
+ * @param node - Expression node to compile
1411
+ * @param ctx - Compiler context
1412
+ * @returns Compiled SQL expression
1413
+ */
1414
+ protected compileExpression(node: ExpressionNode, ctx: CompilerContext): string;
1415
+ /**
1416
+ * Compiles an operand node
1417
+ * @param node - Operand node to compile
1418
+ * @param ctx - Compiler context
1419
+ * @returns Compiled SQL operand
1420
+ */
1421
+ protected compileOperand(node: OperandNode, ctx: CompilerContext): string;
1422
+ private registerDefaultExpressionCompilers;
1423
+ private registerDefaultOperandCompilers;
1424
+ protected compileJsonPath(node: JsonPathNode): string;
1425
+ /**
1426
+ * Compiles a function operand, using the dialect's function strategy.
1427
+ */
1428
+ protected compileFunctionOperand(fnNode: FunctionNode, ctx: CompilerContext): string;
1429
+ }
1430
+
1431
+ type DialectKey = 'postgres' | 'mysql' | 'sqlite' | 'mssql' | (string & {});
1432
+
1433
+ /**
1434
+ * Node types that can be used in query projections
1435
+ */
1436
+ type ProjectionNode = ColumnNode | FunctionNode | ScalarSubqueryNode | CaseExpressionNode | WindowFunctionNode;
1437
+ /**
1438
+ * Manages the state of a SELECT query being built
1439
+ */
1440
+ declare class SelectQueryState {
1441
+ /**
1442
+ * Table definition for the query
1443
+ */
1444
+ readonly table: TableDef;
1445
+ /**
1446
+ * Abstract Syntax Tree (AST) representation of the query
1447
+ */
1448
+ readonly ast: SelectQueryNode;
1449
+ /**
1450
+ * Creates a new SelectQueryState instance
1451
+ * @param table - Table definition
1452
+ * @param ast - Optional existing AST
1453
+ */
1454
+ constructor(table: TableDef, ast?: SelectQueryNode);
1455
+ /**
1456
+ * Creates a new SelectQueryState with updated AST
1457
+ * @param nextAst - Updated AST
1458
+ * @returns New SelectQueryState instance
1459
+ */
1460
+ private clone;
1461
+ /**
1462
+ * Adds columns to the query
1463
+ * @param newCols - Columns to add
1464
+ * @returns New SelectQueryState with added columns
1465
+ */
1466
+ withColumns(newCols: ProjectionNode[]): SelectQueryState;
1467
+ /**
1468
+ * Adds a join to the query
1469
+ * @param join - Join node to add
1470
+ * @returns New SelectQueryState with added join
1471
+ */
1472
+ withJoin(join: JoinNode): SelectQueryState;
1473
+ /**
1474
+ * Replaces the FROM clause.
1475
+ * @param from - Table source for the FROM clause
1476
+ * @returns New SelectQueryState with updated FROM
1477
+ */
1478
+ withFrom(from: TableSourceNode): SelectQueryState;
1479
+ /**
1480
+ * Adds a WHERE clause to the query
1481
+ * @param predicate - WHERE predicate expression
1482
+ * @returns New SelectQueryState with WHERE clause
1483
+ */
1484
+ withWhere(predicate: ExpressionNode): SelectQueryState;
1485
+ /**
1486
+ * Adds a HAVING clause to the query
1487
+ * @param predicate - HAVING predicate expression
1488
+ * @returns New SelectQueryState with HAVING clause
1489
+ */
1490
+ withHaving(predicate: ExpressionNode): SelectQueryState;
1491
+ /**
1492
+ * Adds GROUP BY columns to the query
1493
+ * @param columns - Columns to group by
1494
+ * @returns New SelectQueryState with GROUP BY clause
1495
+ */
1496
+ withGroupBy(columns: ColumnNode[]): SelectQueryState;
1497
+ /**
1498
+ * Adds ORDER BY clauses to the query
1499
+ * @param orderBy - ORDER BY nodes
1500
+ * @returns New SelectQueryState with ORDER BY clause
1501
+ */
1502
+ withOrderBy(orderBy: OrderByNode[]): SelectQueryState;
1503
+ /**
1504
+ * Adds DISTINCT columns to the query
1505
+ * @param columns - Columns to make distinct
1506
+ * @returns New SelectQueryState with DISTINCT clause
1507
+ */
1508
+ withDistinct(columns: ColumnNode[]): SelectQueryState;
1509
+ /**
1510
+ * Adds a LIMIT clause to the query
1511
+ * @param limit - Maximum number of rows to return
1512
+ * @returns New SelectQueryState with LIMIT clause
1513
+ */
1514
+ withLimit(limit: number): SelectQueryState;
1515
+ /**
1516
+ * Adds an OFFSET clause to the query
1517
+ * @param offset - Number of rows to skip
1518
+ * @returns New SelectQueryState with OFFSET clause
1519
+ */
1520
+ withOffset(offset: number): SelectQueryState;
1521
+ /**
1522
+ * Adds a Common Table Expression (CTE) to the query
1523
+ * @param cte - CTE node to add
1524
+ * @returns New SelectQueryState with CTE
1525
+ */
1526
+ withCte(cte: CommonTableExpressionNode): SelectQueryState;
1527
+ /**
1528
+ * Adds a set operation (UNION/INTERSECT/EXCEPT) to the query
1529
+ * @param op - Set operation node to add
1530
+ * @returns New SelectQueryState with set operation
1531
+ */
1532
+ withSetOperation(op: SetOperationNode): SelectQueryState;
1533
+ }
1534
+
1535
+ /**
1536
+ * Manages hydration planning for query results
1537
+ */
1538
+ declare class HydrationPlanner {
1539
+ private readonly table;
1540
+ private readonly plan?;
1541
+ /**
1542
+ * Creates a new HydrationPlanner instance
1543
+ * @param table - Table definition
1544
+ * @param plan - Optional existing hydration plan
1545
+ */
1546
+ constructor(table: TableDef, plan?: HydrationPlan);
1547
+ /**
1548
+ * Captures root table columns for hydration planning
1549
+ * @param columns - Columns to capture
1550
+ * @returns Updated HydrationPlanner with captured columns
1551
+ */
1552
+ captureRootColumns(columns: ProjectionNode[]): HydrationPlanner;
1553
+ /**
1554
+ * Includes a relation in the hydration plan
1555
+ * @param rel - Relation definition
1556
+ * @param relationName - Name of the relation
1557
+ * @param aliasPrefix - Alias prefix for relation columns
1558
+ * @param columns - Columns to include from the relation
1559
+ * @returns Updated HydrationPlanner with included relation
1560
+ */
1561
+ includeRelation(rel: RelationDef, relationName: string, aliasPrefix: string, columns: string[], pivot?: {
1562
+ aliasPrefix: string;
1563
+ columns: string[];
1564
+ }): HydrationPlanner;
1565
+ /**
1566
+ * Gets the current hydration plan
1567
+ * @returns Current hydration plan or undefined
1568
+ */
1569
+ getPlan(): HydrationPlan | undefined;
1570
+ /**
1571
+ * Gets the current hydration plan or creates a default one
1572
+ * @returns Current hydration plan or default plan
1573
+ */
1574
+ private getPlanOrDefault;
1575
+ /**
1576
+ * Builds a relation plan for hydration
1577
+ * @param rel - Relation definition
1578
+ * @param relationName - Name of the relation
1579
+ * @param aliasPrefix - Alias prefix for relation columns
1580
+ * @param columns - Columns to include from the relation
1581
+ * @returns Hydration relation plan
1582
+ */
1583
+ private buildRelationPlan;
1584
+ }
1585
+
1586
+ /**
1587
+ * Manages hydration planning for query results
1588
+ */
1589
+ declare class HydrationManager {
1590
+ private readonly table;
1591
+ private readonly planner;
1592
+ /**
1593
+ * Creates a new HydrationManager instance
1594
+ * @param table - Table definition
1595
+ * @param planner - Hydration planner
1596
+ */
1597
+ constructor(table: TableDef, planner: HydrationPlanner);
1598
+ /**
1599
+ * Creates a new HydrationManager with updated planner
1600
+ * @param nextPlanner - Updated hydration planner
1601
+ * @returns New HydrationManager instance
1602
+ */
1603
+ private clone;
1604
+ /**
1605
+ * Handles column selection for hydration planning
1606
+ * @param state - Current query state
1607
+ * @param newColumns - Newly selected columns
1608
+ * @returns Updated HydrationManager with captured columns
1609
+ */
1610
+ onColumnsSelected(state: SelectQueryState, newColumns: ProjectionNode[]): HydrationManager;
1611
+ /**
1612
+ * Handles relation inclusion for hydration planning
1613
+ * @param state - Current query state
1614
+ * @param relation - Relation definition
1615
+ * @param relationName - Name of the relation
1616
+ * @param aliasPrefix - Alias prefix for the relation
1617
+ * @param targetColumns - Target columns to include
1618
+ * @returns Updated HydrationManager with included relation
1619
+ */
1620
+ onRelationIncluded(state: SelectQueryState, relation: RelationDef, relationName: string, aliasPrefix: string, targetColumns: string[], pivot?: {
1621
+ aliasPrefix: string;
1622
+ columns: string[];
1623
+ }): HydrationManager;
1624
+ /**
1625
+ * Applies hydration plan to the AST
1626
+ * @param ast - Query AST to modify
1627
+ * @returns AST with hydration metadata
1628
+ */
1629
+ applyToAst(ast: SelectQueryNode): SelectQueryNode;
1630
+ /**
1631
+ * Gets the current hydration plan
1632
+ * @returns Hydration plan or undefined if none exists
1633
+ */
1634
+ getPlan(): HydrationPlan | undefined;
1635
+ /**
1636
+ * Attaches hydration metadata to a query AST node.
1637
+ */
1638
+ private attachHydrationMeta;
1639
+ /**
1640
+ * Determines whether the query needs pagination rewriting to keep LIMIT/OFFSET
1641
+ * applied to parent rows when eager-loading multiplicative relations.
1642
+ */
1643
+ private requiresParentPagination;
1644
+ private hasMultiplyingRelations;
1645
+ /**
1646
+ * Rewrites the query using CTEs so LIMIT/OFFSET target distinct parent rows
1647
+ * instead of the joined result set.
1648
+ *
1649
+ * The strategy:
1650
+ * - Hoist the original query (minus limit/offset) into a base CTE.
1651
+ * - Select distinct parent ids from that base CTE with the original ordering and pagination.
1652
+ * - Join the base CTE against the paged ids to retrieve the joined rows for just that page.
1653
+ */
1654
+ private wrapForParentPagination;
1655
+ private nextCteName;
1656
+ private getProjectionNames;
1657
+ private buildProjectionAliasMap;
1658
+ private mapOrderBy;
1659
+ private buildPagingColumns;
1660
+ }
1661
+
1662
+ /**
1663
+ * Result of column selection operation
1664
+ */
1665
+ interface ColumnSelectionResult {
1666
+ /**
1667
+ * Updated query state
1668
+ */
1669
+ state: SelectQueryState;
1670
+ /**
1671
+ * Columns that were added
1672
+ */
1673
+ addedColumns: ProjectionNode[];
1674
+ }
1675
+ /**
1676
+ * Service for manipulating query AST (Abstract Syntax Tree)
1677
+ */
1678
+ declare class QueryAstService {
1679
+ private readonly table;
1680
+ private readonly state;
1681
+ /**
1682
+ * Creates a new QueryAstService instance
1683
+ * @param table - Table definition
1684
+ * @param state - Current query state
1685
+ */
1686
+ constructor(table: TableDef, state: SelectQueryState);
1687
+ /**
1688
+ * Selects columns for the query
1689
+ * @param columns - Columns to select (key: alias, value: column definition or expression)
1690
+ * @returns Column selection result with updated state and added columns
1691
+ */
1692
+ select(columns: Record<string, ColumnDef | FunctionNode | CaseExpressionNode | WindowFunctionNode>): ColumnSelectionResult;
1693
+ /**
1694
+ * Selects raw column expressions (best-effort parser for simple references/functions)
1695
+ * @param cols - Raw column expressions
1696
+ * @returns Column selection result with updated state and added columns
1697
+ */
1698
+ selectRaw(cols: string[]): ColumnSelectionResult;
1699
+ /**
1700
+ * Adds a Common Table Expression (CTE) to the query
1701
+ * @param name - Name of the CTE
1702
+ * @param query - Query for the CTE
1703
+ * @param columns - Optional column names for the CTE
1704
+ * @param recursive - Whether the CTE is recursive
1705
+ * @returns Updated query state with CTE
1706
+ */
1707
+ withCte(name: string, query: SelectQueryNode, columns?: string[], recursive?: boolean): SelectQueryState;
1708
+ /**
1709
+ * Adds a set operation (UNION/UNION ALL/INTERSECT/EXCEPT) to the query
1710
+ * @param operator - Set operator
1711
+ * @param query - Right-hand side query
1712
+ * @returns Updated query state with set operation
1713
+ */
1714
+ withSetOperation(operator: SetOperationKind, query: SelectQueryNode): SelectQueryState;
1715
+ /**
1716
+ * Replaces the FROM clause for the current query.
1717
+ * @param from - Table source to use in the FROM clause
1718
+ * @returns Updated query state with new FROM
1719
+ */
1720
+ withFrom(from: TableSourceNode): SelectQueryState;
1721
+ /**
1722
+ * Selects a subquery as a column
1723
+ * @param alias - Alias for the subquery
1724
+ * @param query - Subquery to select
1725
+ * @returns Updated query state with subquery selection
1726
+ */
1727
+ selectSubquery(alias: string, query: SelectQueryNode): SelectQueryState;
1728
+ /**
1729
+ * Adds a JOIN clause to the query
1730
+ * @param join - Join node to add
1731
+ * @returns Updated query state with JOIN
1732
+ */
1733
+ withJoin(join: JoinNode): SelectQueryState;
1734
+ /**
1735
+ * Adds a WHERE clause to the query
1736
+ * @param expr - Expression for the WHERE clause
1737
+ * @returns Updated query state with WHERE clause
1738
+ */
1739
+ withWhere(expr: ExpressionNode): SelectQueryState;
1740
+ /**
1741
+ * Adds a GROUP BY clause to the query
1742
+ * @param col - Column to group by
1743
+ * @returns Updated query state with GROUP BY clause
1744
+ */
1745
+ withGroupBy(col: ColumnDef | ColumnNode): SelectQueryState;
1746
+ /**
1747
+ * Adds a HAVING clause to the query
1748
+ * @param expr - Expression for the HAVING clause
1749
+ * @returns Updated query state with HAVING clause
1750
+ */
1751
+ withHaving(expr: ExpressionNode): SelectQueryState;
1752
+ /**
1753
+ * Adds an ORDER BY clause to the query
1754
+ * @param col - Column to order by
1755
+ * @param direction - Order direction (ASC/DESC)
1756
+ * @returns Updated query state with ORDER BY clause
1757
+ */
1758
+ withOrderBy(col: ColumnDef | ColumnNode, direction: OrderDirection): SelectQueryState;
1759
+ /**
1760
+ * Adds a DISTINCT clause to the query
1761
+ * @param cols - Columns to make distinct
1762
+ * @returns Updated query state with DISTINCT clause
1763
+ */
1764
+ withDistinct(cols: ColumnNode[]): SelectQueryState;
1765
+ /**
1766
+ * Adds a LIMIT clause to the query
1767
+ * @param limit - Maximum number of rows to return
1768
+ * @returns Updated query state with LIMIT clause
1769
+ */
1770
+ withLimit(limit: number): SelectQueryState;
1771
+ /**
1772
+ * Adds an OFFSET clause to the query
1773
+ * @param offset - Number of rows to skip
1774
+ * @returns Updated query state with OFFSET clause
1775
+ */
1776
+ withOffset(offset: number): SelectQueryState;
1777
+ /**
1778
+ * Combines expressions with AND operator
1779
+ * @param existing - Existing expression
1780
+ * @param next - New expression to combine
1781
+ * @returns Combined expression
1782
+ */
1783
+ private combineExpressions;
1784
+ }
1785
+
1786
+ /**
1787
+ * Result of a relation operation
1788
+ */
1789
+ interface RelationResult {
1790
+ /**
1791
+ * Updated query state
1792
+ */
1793
+ state: SelectQueryState;
1794
+ /**
1795
+ * Updated hydration manager
1796
+ */
1797
+ hydration: HydrationManager;
1798
+ }
1799
+
1800
+ /**
1801
+ * Join kinds allowed when including a relation using `.include(...)`.
1802
+ */
1803
+ type RelationIncludeJoinKind = typeof JOIN_KINDS.LEFT | typeof JOIN_KINDS.INNER;
1804
+ /**
1805
+ * Options for including a relation in a query
1806
+ */
1807
+ interface RelationIncludeOptions {
1808
+ columns?: string[];
1809
+ aliasPrefix?: string;
1810
+ filter?: ExpressionNode;
1811
+ joinKind?: RelationIncludeJoinKind;
1812
+ pivot?: {
1813
+ columns?: string[];
1814
+ aliasPrefix?: string;
1815
+ };
1816
+ }
1817
+
1818
+ /**
1819
+ * Service for handling relation operations (joins, includes, etc.)
1820
+ */
1821
+ declare class RelationService {
1822
+ private readonly table;
1823
+ private readonly state;
1824
+ private readonly hydration;
1825
+ private readonly createQueryAstService;
1826
+ private readonly projectionHelper;
1827
+ /**
1828
+ * Creates a new RelationService instance
1829
+ * @param table - Table definition
1830
+ * @param state - Current query state
1831
+ * @param hydration - Hydration manager
1832
+ */
1833
+ constructor(table: TableDef, state: SelectQueryState, hydration: HydrationManager, createQueryAstService: (table: TableDef, state: SelectQueryState) => QueryAstService);
1834
+ /**
1835
+ * Joins a relation to the query
1836
+ * @param relationName - Name of the relation to join
1837
+ * @param joinKind - Type of join to use
1838
+ * @param extraCondition - Additional join condition
1839
+ * @returns Relation result with updated state and hydration
1840
+ */
1841
+ joinRelation(relationName: string, joinKind: JoinKind, extraCondition?: ExpressionNode): RelationResult;
1842
+ /**
1843
+ * Matches records based on a relation with an optional predicate
1844
+ * @param relationName - Name of the relation to match
1845
+ * @param predicate - Optional predicate expression
1846
+ * @returns Relation result with updated state and hydration
1847
+ */
1848
+ match(relationName: string, predicate?: ExpressionNode): RelationResult;
1849
+ /**
1850
+ * Includes a relation in the query result
1851
+ * @param relationName - Name of the relation to include
1852
+ * @param options - Options for relation inclusion
1853
+ * @returns Relation result with updated state and hydration
1854
+ */
1855
+ include(relationName: string, options?: RelationIncludeOptions): RelationResult;
1856
+ /**
1857
+ * Applies relation correlation to a query AST
1858
+ * @param relationName - Name of the relation
1859
+ * @param ast - Query AST to modify
1860
+ * @returns Modified query AST with relation correlation
1861
+ */
1862
+ applyRelationCorrelation(relationName: string, ast: SelectQueryNode, additionalCorrelation?: ExpressionNode): SelectQueryNode;
1863
+ /**
1864
+ * Creates a join node for a relation
1865
+ * @param state - Current query state
1866
+ * @param relationName - Name of the relation
1867
+ * @param joinKind - Type of join to use
1868
+ * @param extraCondition - Additional join condition
1869
+ * @returns Updated query state with join
1870
+ */
1871
+ private withJoin;
1872
+ /**
1873
+ * Selects columns for a relation
1874
+ * @param state - Current query state
1875
+ * @param hydration - Hydration manager
1876
+ * @param columns - Columns to select
1877
+ * @returns Relation result with updated state and hydration
1878
+ */
1879
+ private selectColumns;
1880
+ /**
1881
+ * Gets a relation definition by name
1882
+ * @param relationName - Name of the relation
1883
+ * @returns Relation definition
1884
+ * @throws Error if relation is not found
1885
+ */
1886
+ private getRelation;
1887
+ /**
1888
+ * Creates a QueryAstService instance
1889
+ * @param state - Current query state
1890
+ * @returns QueryAstService instance
1891
+ */
1892
+ private astService;
1893
+ private rootTableName;
1894
+ }
1895
+
1896
+ /**
1897
+ * Dependencies for query builder operations
1898
+ */
1899
+ interface SelectQueryBuilderDependencies {
1900
+ /**
1901
+ * Creates a new query state
1902
+ * @param table - Table definition
1903
+ * @returns New query state
1904
+ */
1905
+ createState: (table: TableDef) => SelectQueryState;
1906
+ /**
1907
+ * Creates a new hydration manager
1908
+ * @param table - Table definition
1909
+ * @returns New hydration manager
1910
+ */
1911
+ createHydration: (table: TableDef) => HydrationManager;
1912
+ /**
1913
+ * Creates a new hydration planner
1914
+ * @param table - Table definition
1915
+ * @returns Hydration planner
1916
+ */
1917
+ createHydrationPlanner: (table: TableDef) => HydrationPlanner;
1918
+ /**
1919
+ * Creates a new query AST service
1920
+ * @param table - Table definition
1921
+ * @param state - Query state
1922
+ * @returns New query AST service
1923
+ */
1924
+ createQueryAstService: (table: TableDef, state: SelectQueryState) => QueryAstService;
1925
+ /**
1926
+ * Creates a new relation service
1927
+ * @param table - Table definition
1928
+ * @param state - Query state
1929
+ * @param hydration - Hydration manager
1930
+ * @returns New relation service
1931
+ */
1932
+ createRelationService: (table: TableDef, state: SelectQueryState, hydration: HydrationManager) => RelationService;
1933
+ }
1934
+
1935
+ type QueryResult = {
1936
+ columns: string[];
1937
+ values: unknown[][];
1938
+ };
1939
+ interface DbExecutor {
1940
+ executeSql(sql: string, params?: unknown[]): Promise<QueryResult[]>;
1941
+ beginTransaction?(): Promise<void>;
1942
+ commitTransaction?(): Promise<void>;
1943
+ rollbackTransaction?(): Promise<void>;
1944
+ }
1945
+ /**
1946
+ * Convert an array of row objects into a QueryResult.
1947
+ */
1948
+ declare function rowsToQueryResult(rows: Array<Record<string, unknown>>): QueryResult;
199
1949
  /**
200
- * Creates a LAST_VALUE window function
201
- * @param col - Column to get last value from
202
- * @returns Window function node for LAST_VALUE
1950
+ * Minimal contract that most SQL clients can implement.
203
1951
  */
204
- declare const lastValue: (col: ColumnRef | ColumnNode) => WindowFunctionNode;
1952
+ interface SimpleQueryRunner {
1953
+ query(sql: string, params?: unknown[]): Promise<Array<Record<string, unknown>>>;
1954
+ beginTransaction?(): Promise<void>;
1955
+ commitTransaction?(): Promise<void>;
1956
+ rollbackTransaction?(): Promise<void>;
1957
+ }
205
1958
  /**
206
- * Creates a custom window function
207
- * @param name - Window function name
208
- * @param args - Function arguments
209
- * @param partitionBy - Optional PARTITION BY columns
210
- * @param orderBy - Optional ORDER BY clauses
211
- * @returns Window function node
1959
+ * Generic factory: turn any SimpleQueryRunner into a DbExecutor.
212
1960
  */
213
- declare const windowFunction: (name: string, args?: (ColumnRef | ColumnNode | LiteralNode | JsonPathNode)[], partitionBy?: (ColumnRef | ColumnNode)[], orderBy?: {
214
- column: ColumnRef | ColumnNode;
215
- direction: OrderDirection;
216
- }[]) => WindowFunctionNode;
1961
+ declare function createExecutorFromQueryRunner(runner: SimpleQueryRunner): DbExecutor;
1962
+
1963
+ type EntityConstructor = new (...args: any[]) => any;
1964
+ type EntityOrTableTarget = EntityConstructor | TableDef;
1965
+ type EntityOrTableTargetResolver = EntityOrTableTarget | (() => EntityOrTableTarget);
217
1966
 
218
1967
  /**
219
- * Creates a COUNT function expression
220
- * @param col - Column to count
221
- * @returns Function node with COUNT
222
- */
223
- declare const count: (col: ColumnRef | ColumnNode) => FunctionNode;
1968
+ * Entity status enum representing the lifecycle state of an entity
1969
+ */
1970
+ declare enum EntityStatus {
1971
+ /** Entity is newly created and not yet persisted */
1972
+ New = "new",
1973
+ /** Entity is managed by the ORM and synchronized with the database */
1974
+ Managed = "managed",
1975
+ /** Entity has been modified but not yet persisted */
1976
+ Dirty = "dirty",
1977
+ /** Entity has been marked for removal */
1978
+ Removed = "removed",
1979
+ /** Entity is detached from the ORM context */
1980
+ Detached = "detached"
1981
+ }
224
1982
  /**
225
- * Creates a SUM function expression
226
- * @param col - Column to sum
227
- * @returns Function node with SUM
228
- */
229
- declare const sum: (col: ColumnRef | ColumnNode) => FunctionNode;
1983
+ * Represents an entity being tracked by the ORM
1984
+ */
1985
+ interface TrackedEntity {
1986
+ /** The table definition this entity belongs to */
1987
+ table: TableDef;
1988
+ /** The actual entity instance */
1989
+ entity: any;
1990
+ /** Primary key value of the entity */
1991
+ pk: string | number | null;
1992
+ /** Current status of the entity */
1993
+ status: EntityStatus;
1994
+ /** Original values of the entity when it was loaded */
1995
+ original: Record<string, any> | null;
1996
+ }
230
1997
  /**
231
- * Creates an AVG function expression
232
- * @param col - Column to average
233
- * @returns Function node with AVG
1998
+ * Type representing a key for relation navigation
1999
+ */
2000
+ type RelationKey = string;
2001
+ /**
2002
+ * Represents a change operation on a relation
2003
+ * @typeParam T - Type of the related entity
2004
+ */
2005
+ type RelationChange<T> = {
2006
+ kind: 'add';
2007
+ entity: T;
2008
+ } | {
2009
+ kind: 'attach';
2010
+ entity: T;
2011
+ } | {
2012
+ kind: 'remove';
2013
+ entity: T;
2014
+ } | {
2015
+ kind: 'detach';
2016
+ entity: T;
2017
+ };
2018
+ /**
2019
+ * Represents a relation change entry in the unit of work
2020
+ */
2021
+ interface RelationChangeEntry {
2022
+ /** Root entity that owns the relation */
2023
+ root: any;
2024
+ /** Key of the relation being changed */
2025
+ relationKey: RelationKey;
2026
+ /** Table definition of the root entity */
2027
+ rootTable: TableDef;
2028
+ /** Name of the relation */
2029
+ relationName: string;
2030
+ /** Relation definition */
2031
+ relation: RelationDef;
2032
+ /** The change being applied */
2033
+ change: RelationChange<any>;
2034
+ }
2035
+ /**
2036
+ * Represents a domain event that can be emitted by entities
2037
+ * @typeParam TType - Type of the event (string literal)
234
2038
  */
235
- declare const avg: (col: ColumnRef | ColumnNode) => FunctionNode;
2039
+ interface DomainEvent<TType extends string = string> {
2040
+ /** Type identifier for the event */
2041
+ readonly type: TType;
2042
+ /** Timestamp when the event occurred */
2043
+ readonly occurredAt?: Date;
2044
+ }
236
2045
  /**
237
- * Creates a MIN function expression
238
- * @param col - Column to take the minimum of
239
- * @returns Function node with MIN
2046
+ * Type representing any domain event
240
2047
  */
241
- declare const min: (col: ColumnRef | ColumnNode) => FunctionNode;
2048
+ type AnyDomainEvent = DomainEvent<string>;
242
2049
  /**
243
- * Creates a MAX function expression
244
- * @param col - Column to take the maximum of
245
- * @returns Function node with MAX
2050
+ * Type representing ORM-specific domain events
246
2051
  */
247
- declare const max: (col: ColumnRef | ColumnNode) => FunctionNode;
248
- type GroupConcatOrderByInput = {
249
- column: ColumnRef | ColumnNode;
250
- direction?: OrderDirection;
251
- };
252
- type GroupConcatOptions = {
253
- separator?: ValueOperandInput;
254
- orderBy?: GroupConcatOrderByInput[];
255
- };
2052
+ type OrmDomainEvent = AnyDomainEvent;
256
2053
  /**
257
- * Aggregates grouped strings into a single value.
2054
+ * Interface for entities that can emit domain events
2055
+ * @typeParam E - Type of domain events this entity can emit
258
2056
  */
259
- declare const groupConcat: (col: ColumnRef | ColumnNode, options?: GroupConcatOptions) => FunctionNode;
2057
+ interface HasDomainEvents<E extends DomainEvent = AnyDomainEvent> {
2058
+ /** Array of domain events emitted by this entity */
2059
+ domainEvents?: E[];
2060
+ }
260
2061
 
261
2062
  /**
262
- * Visitor for expression nodes
2063
+ * Strategy interface for converting database names to TypeScript identifiers
263
2064
  */
264
- interface ExpressionVisitor<R> {
265
- visitBinaryExpression?(node: BinaryExpressionNode): R;
266
- visitLogicalExpression?(node: LogicalExpressionNode): R;
267
- visitNullExpression?(node: NullExpressionNode): R;
268
- visitInExpression?(node: InExpressionNode): R;
269
- visitExistsExpression?(node: ExistsExpressionNode): R;
270
- visitBetweenExpression?(node: BetweenExpressionNode): R;
271
- otherwise?(node: ExpressionNode): R;
2065
+ interface NamingStrategy {
2066
+ /**
2067
+ * Converts a table name to a TypeScript symbol name
2068
+ * @param table - Table node, function table node, or name
2069
+ * @returns Valid TypeScript identifier
2070
+ */
2071
+ tableToSymbol(table: TableSourceNode | string): string;
2072
+ /**
2073
+ * Converts a column reference to a property name
2074
+ * @param column - Column node
2075
+ * @returns Valid TypeScript property name
2076
+ */
2077
+ columnToProperty(column: ColumnNode): string;
2078
+ }
2079
+
2080
+ interface QueryContext {
2081
+ sql: string;
2082
+ params: unknown[];
2083
+ }
2084
+ type QueryInterceptor = (ctx: QueryContext, next: () => Promise<QueryResult[]>) => Promise<QueryResult[]>;
2085
+ declare class InterceptorPipeline {
2086
+ private interceptors;
2087
+ use(interceptor: QueryInterceptor): void;
2088
+ run(ctx: QueryContext, executor: DbExecutor): Promise<QueryResult[]>;
2089
+ }
2090
+
2091
+ interface OrmOptions<E extends DomainEvent = OrmDomainEvent> {
2092
+ dialect: Dialect;
2093
+ executorFactory: DbExecutorFactory;
2094
+ interceptors?: InterceptorPipeline;
2095
+ namingStrategy?: NamingStrategy;
2096
+ }
2097
+ interface DbExecutorFactory {
2098
+ createExecutor(options?: {
2099
+ tx?: ExternalTransaction;
2100
+ }): DbExecutor;
2101
+ createTransactionalExecutor(): DbExecutor;
2102
+ }
2103
+ interface ExternalTransaction {
2104
+ }
2105
+ declare class Orm<E extends DomainEvent = OrmDomainEvent> {
2106
+ readonly dialect: Dialect;
2107
+ readonly interceptors: InterceptorPipeline;
2108
+ readonly namingStrategy: NamingStrategy;
2109
+ private readonly executorFactory;
2110
+ constructor(opts: OrmOptions<E>);
2111
+ createSession(options?: {
2112
+ tx?: ExternalTransaction;
2113
+ }): OrmSession<E>;
2114
+ transaction<T>(fn: (session: OrmSession<E>) => Promise<T>): Promise<T>;
2115
+ }
2116
+
2117
+ declare class IdentityMap {
2118
+ private readonly buckets;
2119
+ get bucketsMap(): Map<string, Map<string, TrackedEntity>>;
2120
+ getEntity(table: TableDef, pk: string | number): any | undefined;
2121
+ register(tracked: TrackedEntity): void;
2122
+ remove(tracked: TrackedEntity): void;
2123
+ getEntitiesForTable(table: TableDef): TrackedEntity[];
2124
+ clear(): void;
2125
+ private toIdentityKey;
2126
+ }
2127
+
2128
+ declare class UnitOfWork {
2129
+ private readonly dialect;
2130
+ private readonly executor;
2131
+ private readonly identityMap;
2132
+ private readonly hookContext;
2133
+ private readonly trackedEntities;
2134
+ constructor(dialect: Dialect, executor: DbExecutor, identityMap: IdentityMap, hookContext: () => unknown);
2135
+ get identityBuckets(): Map<string, Map<string, TrackedEntity>>;
2136
+ getTracked(): TrackedEntity[];
2137
+ getEntity(table: TableDef, pk: string | number): any | undefined;
2138
+ getEntitiesForTable(table: TableDef): TrackedEntity[];
2139
+ findTracked(entity: any): TrackedEntity | undefined;
2140
+ setEntity(table: TableDef, pk: string | number, entity: any): void;
2141
+ trackNew(table: TableDef, entity: any, pk?: string | number): void;
2142
+ trackManaged(table: TableDef, pk: string | number, entity: any): void;
2143
+ markDirty(entity: any): void;
2144
+ markRemoved(entity: any): void;
2145
+ flush(): Promise<void>;
2146
+ reset(): void;
2147
+ private flushInsert;
2148
+ private flushUpdate;
2149
+ private flushDelete;
2150
+ private runHook;
2151
+ private computeChanges;
2152
+ private extractColumns;
2153
+ private executeCompiled;
2154
+ private getReturningColumns;
2155
+ private applyReturningResults;
2156
+ private normalizeColumnName;
2157
+ private registerIdentity;
2158
+ private createSnapshot;
2159
+ private getPrimaryKeyValue;
2160
+ }
2161
+
2162
+ type EventOfType<E extends DomainEvent, TType extends E['type']> = Extract<E, {
2163
+ type: TType;
2164
+ }>;
2165
+ type DomainEventHandler<E extends DomainEvent, Context> = (event: E, ctx: Context) => Promise<void> | void;
2166
+ type InitialHandlers<E extends DomainEvent, Context> = {
2167
+ [K in E['type']]?: DomainEventHandler<EventOfType<E, K>, Context>[];
2168
+ };
2169
+ declare class DomainEventBus<E extends DomainEvent, Context> {
2170
+ private readonly handlers;
2171
+ constructor(initialHandlers?: InitialHandlers<E, Context>);
2172
+ on<TType extends E['type']>(type: TType, handler: DomainEventHandler<EventOfType<E, TType>, Context>): void;
2173
+ register<TType extends E['type']>(type: TType, handler: DomainEventHandler<EventOfType<E, TType>, Context>): void;
2174
+ dispatch(trackedEntities: Iterable<TrackedEntity>, ctx: Context): Promise<void>;
272
2175
  }
2176
+ declare const addDomainEvent: <E extends DomainEvent>(entity: HasDomainEvents<E>, event: E) => void;
2177
+
2178
+ declare class RelationChangeProcessor {
2179
+ private readonly unitOfWork;
2180
+ private readonly dialect;
2181
+ private readonly executor;
2182
+ private readonly relationChanges;
2183
+ constructor(unitOfWork: UnitOfWork, dialect: Dialect, executor: DbExecutor);
2184
+ registerChange(entry: RelationChangeEntry): void;
2185
+ reset(): void;
2186
+ process(): Promise<void>;
2187
+ private handleHasManyChange;
2188
+ private handleHasOneChange;
2189
+ private handleBelongsToChange;
2190
+ private handleBelongsToManyChange;
2191
+ private assignHasManyForeignKey;
2192
+ private detachHasManyChild;
2193
+ private assignHasOneForeignKey;
2194
+ private detachHasOneChild;
2195
+ private insertPivotRow;
2196
+ private deletePivotRow;
2197
+ private resolvePrimaryKeyValue;
2198
+ }
2199
+
273
2200
  /**
274
- * Visitor for operand nodes
2201
+ * Represents a single SQL query log entry
275
2202
  */
276
- interface OperandVisitor<R> {
277
- visitColumn?(node: ColumnNode): R;
278
- visitLiteral?(node: LiteralNode): R;
279
- visitFunction?(node: FunctionNode): R;
280
- visitJsonPath?(node: JsonPathNode): R;
281
- visitScalarSubquery?(node: ScalarSubqueryNode): R;
282
- visitCaseExpression?(node: CaseExpressionNode): R;
283
- visitWindowFunction?(node: WindowFunctionNode): R;
284
- otherwise?(node: OperandNode): R;
2203
+ interface QueryLogEntry {
2204
+ /** The SQL query that was executed */
2205
+ sql: string;
2206
+ /** Parameters used in the query */
2207
+ params?: unknown[];
285
2208
  }
286
- type ExpressionDispatch = <R>(node: any, visitor: ExpressionVisitor<R>) => R;
287
- type OperandDispatch = <R>(node: any, visitor: OperandVisitor<R>) => R;
288
2209
  /**
289
- * Registers a dispatcher for a custom expression node type.
290
- * Allows new node kinds without modifying the core switch.
2210
+ * Function type for query logging callbacks
2211
+ * @param entry - The query log entry to process
291
2212
  */
292
- declare const registerExpressionDispatcher: (type: string, dispatcher: ExpressionDispatch) => void;
2213
+ type QueryLogger = (entry: QueryLogEntry) => void;
293
2214
  /**
294
- * Registers a dispatcher for a custom operand node type.
295
- * Allows new node kinds without modifying the core switch.
2215
+ * Creates a wrapped database executor that logs all SQL queries
2216
+ * @param executor - Original database executor to wrap
2217
+ * @param logger - Optional logger function to receive query log entries
2218
+ * @returns Wrapped executor that logs queries before execution
296
2219
  */
297
- declare const registerOperandDispatcher: (type: string, dispatcher: OperandDispatch) => void;
2220
+ declare const createQueryLoggingExecutor: (executor: DbExecutor, logger?: QueryLogger) => DbExecutor;
2221
+
298
2222
  /**
299
- * Clears all registered dispatchers. Primarily for tests.
2223
+ * Context for SQL query execution
300
2224
  */
301
- declare const clearExpressionDispatchers: () => void;
302
- declare const clearOperandDispatchers: () => void;
2225
+ interface ExecutionContext {
2226
+ /** Database dialect to use for SQL generation */
2227
+ dialect: Dialect;
2228
+ /** Database executor for running SQL queries */
2229
+ executor: DbExecutor;
2230
+ /** Interceptor pipeline for query processing */
2231
+ interceptors: InterceptorPipeline;
2232
+ }
2233
+
2234
+ interface EntityContext {
2235
+ dialect: Dialect;
2236
+ executor: DbExecutor;
2237
+ getEntity(table: TableDef, pk: any): any;
2238
+ setEntity(table: TableDef, pk: any, entity: any): void;
2239
+ trackNew(table: TableDef, entity: any, pk?: any): void;
2240
+ trackManaged(table: TableDef, pk: any, entity: any): void;
2241
+ markDirty(entity: any): void;
2242
+ markRemoved(entity: any): void;
2243
+ getEntitiesForTable(table: TableDef): TrackedEntity[];
2244
+ registerRelationChange(root: any, relationKey: RelationKey, rootTable: TableDef, relationName: string, relation: RelationDef, change: RelationChange<any>): void;
2245
+ }
2246
+
2247
+ interface HydrationContext<E extends DomainEvent = AnyDomainEvent> {
2248
+ identityMap: IdentityMap;
2249
+ unitOfWork: UnitOfWork;
2250
+ domainEvents: DomainEventBus<E, OrmSession<E>>;
2251
+ relationChanges: RelationChangeProcessor;
2252
+ entityContext: EntityContext;
2253
+ }
2254
+
2255
+ interface OrmInterceptor {
2256
+ beforeFlush?(ctx: EntityContext): Promise<void> | void;
2257
+ afterFlush?(ctx: EntityContext): Promise<void> | void;
2258
+ }
2259
+ interface OrmSessionOptions<E extends DomainEvent = OrmDomainEvent> {
2260
+ orm: Orm<E>;
2261
+ executor: DbExecutor;
2262
+ queryLogger?: QueryLogger;
2263
+ interceptors?: OrmInterceptor[];
2264
+ domainEventHandlers?: InitialHandlers<E, OrmSession<E>>;
2265
+ }
2266
+ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements EntityContext {
2267
+ readonly orm: Orm<E>;
2268
+ readonly executor: DbExecutor;
2269
+ readonly identityMap: IdentityMap;
2270
+ readonly unitOfWork: UnitOfWork;
2271
+ readonly domainEvents: DomainEventBus<E, OrmSession<E>>;
2272
+ readonly relationChanges: RelationChangeProcessor;
2273
+ private readonly interceptors;
2274
+ constructor(opts: OrmSessionOptions<E>);
2275
+ get dialect(): Dialect;
2276
+ get identityBuckets(): Map<string, Map<string, TrackedEntity>>;
2277
+ get tracked(): TrackedEntity[];
2278
+ getEntity(table: TableDef, pk: any): any | undefined;
2279
+ setEntity(table: TableDef, pk: any, entity: any): void;
2280
+ trackNew(table: TableDef, entity: any, pk?: any): void;
2281
+ trackManaged(table: TableDef, pk: any, entity: any): void;
2282
+ markDirty(entity: any): void;
2283
+ markRemoved(entity: any): void;
2284
+ registerRelationChange: (root: any, relationKey: RelationKey, rootTable: TableDef, relationName: string, relation: RelationDef, change: RelationChange<any>) => void;
2285
+ getEntitiesForTable(table: TableDef): TrackedEntity[];
2286
+ registerInterceptor(interceptor: OrmInterceptor): void;
2287
+ registerDomainEventHandler<TType extends E['type']>(type: TType, handler: DomainEventHandler<Extract<E, {
2288
+ type: TType;
2289
+ }>, OrmSession<E>>): void;
2290
+ find<TTable extends TableDef>(entityClass: EntityConstructor, id: any): Promise<EntityInstance<TTable> | null>;
2291
+ findOne<TTable extends TableDef>(qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable> | null>;
2292
+ findMany<TTable extends TableDef>(qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable>[]>;
2293
+ persist(entity: object): Promise<void>;
2294
+ remove(entity: object): Promise<void>;
2295
+ flush(): Promise<void>;
2296
+ commit(): Promise<void>;
2297
+ rollback(): Promise<void>;
2298
+ getExecutionContext(): ExecutionContext;
2299
+ getHydrationContext(): HydrationContext<E>;
2300
+ }
2301
+
2302
+ type SelectDialectInput = Dialect | DialectKey;
2303
+
2304
+ type ColumnSelectionValue = ColumnDef | FunctionNode | CaseExpressionNode | WindowFunctionNode;
2305
+ type DeepSelectConfig<TTable extends TableDef> = {
2306
+ root?: (keyof TTable['columns'] & string)[];
2307
+ } & {
2308
+ [K in keyof TTable['relations'] & string]?: (keyof RelationTargetTable<TTable['relations'][K]>['columns'] & string)[];
2309
+ };
2310
+ type WhereHasOptions = {
2311
+ correlate?: ExpressionNode;
2312
+ };
2313
+ type RelationCallback = <TChildTable extends TableDef>(qb: SelectQueryBuilder<any, TChildTable>) => SelectQueryBuilder<any, TChildTable>;
303
2314
  /**
304
- * Dispatches an expression node to the visitor
305
- * @param node - Expression node to visit
306
- * @param visitor - Visitor implementation
2315
+
2316
+ * Main query builder class for constructing SQL SELECT queries
2317
+
2318
+ * @typeParam T - Result type for projections (unused)
2319
+
2320
+ * @typeParam TTable - Table definition being queried
2321
+
307
2322
  */
308
- declare const visitExpression: <R>(node: ExpressionNode, visitor: ExpressionVisitor<R>) => R;
2323
+ declare class SelectQueryBuilder<T = any, TTable extends TableDef = TableDef> {
2324
+ private readonly env;
2325
+ private readonly context;
2326
+ private readonly columnSelector;
2327
+ private readonly relationManager;
2328
+ private readonly lazyRelations;
2329
+ /**
2330
+
2331
+ * Creates a new SelectQueryBuilder instance
2332
+
2333
+ * @param table - Table definition to query
2334
+
2335
+ * @param state - Optional initial query state
2336
+
2337
+ * @param hydration - Optional hydration manager
2338
+
2339
+ * @param dependencies - Optional query builder dependencies
2340
+
2341
+ */
2342
+ constructor(table: TTable, state?: SelectQueryState, hydration?: HydrationManager, dependencies?: Partial<SelectQueryBuilderDependencies>, lazyRelations?: Set<string>);
2343
+ private clone;
2344
+ /**
2345
+ * Applies an alias to the root FROM table.
2346
+ * @param alias - Alias to apply
2347
+ */
2348
+ as(alias: string): SelectQueryBuilder<T, TTable>;
2349
+ private resolveQueryNode;
2350
+ private applyCorrelation;
2351
+ private createChildBuilder;
2352
+ private applyAst;
2353
+ private applyJoin;
2354
+ private applySetOperation;
2355
+ /**
2356
+
2357
+ * Selects specific columns for the query
2358
+
2359
+ * @param columns - Record of column definitions, function nodes, case expressions, or window functions
2360
+
2361
+ * @returns New query builder instance with selected columns
2362
+
2363
+ */
2364
+ select(columns: Record<string, ColumnSelectionValue>): SelectQueryBuilder<T, TTable>;
2365
+ /**
2366
+ * Selects columns from the root table by name (typed).
2367
+ * @param cols - Column names on the root table
2368
+ */
2369
+ selectColumns<K extends keyof TTable['columns'] & string>(...cols: K[]): SelectQueryBuilder<T, TTable>;
2370
+ /**
2371
+
2372
+ * Selects raw column expressions
2373
+
2374
+ * @param cols - Column expressions as strings
2375
+
2376
+ * @returns New query builder instance with raw column selections
2377
+
2378
+ */
2379
+ selectRaw(...cols: string[]): SelectQueryBuilder<T, TTable>;
2380
+ /**
2381
+
2382
+ * Adds a Common Table Expression (CTE) to the query
2383
+
2384
+ * @param name - Name of the CTE
2385
+
2386
+ * @param query - Query builder or query node for the CTE
2387
+
2388
+ * @param columns - Optional column names for the CTE
2389
+
2390
+ * @returns New query builder instance with the CTE
2391
+
2392
+ */
2393
+ with(name: string, query: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode, columns?: string[]): SelectQueryBuilder<T, TTable>;
2394
+ /**
2395
+
2396
+ * Adds a recursive Common Table Expression (CTE) to the query
2397
+
2398
+ * @param name - Name of the CTE
2399
+
2400
+ * @param query - Query builder or query node for the CTE
2401
+
2402
+ * @param columns - Optional column names for the CTE
2403
+
2404
+ * @returns New query builder instance with the recursive CTE
2405
+
2406
+ */
2407
+ withRecursive(name: string, query: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode, columns?: string[]): SelectQueryBuilder<T, TTable>;
2408
+ /**
2409
+ * Replaces the FROM clause with a derived table (subquery with alias)
2410
+ * @param subquery - Subquery to use as the FROM source
2411
+ * @param alias - Alias for the derived table
2412
+ * @param columnAliases - Optional column alias list
2413
+ * @returns New query builder instance with updated FROM
2414
+ */
2415
+ fromSubquery(subquery: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode, alias: string, columnAliases?: string[]): SelectQueryBuilder<T, TTable>;
2416
+ /**
2417
+
2418
+ * Selects a subquery as a column
2419
+
2420
+ * @param alias - Alias for the subquery column
2421
+
2422
+ * @param sub - Query builder or query node for the subquery
2423
+
2424
+ * @returns New query builder instance with the subquery selection
2425
+
2426
+ */
2427
+ selectSubquery(alias: string, sub: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode): SelectQueryBuilder<T, TTable>;
2428
+ /**
2429
+ * Adds a JOIN against a derived table (subquery with alias)
2430
+ * @param subquery - Subquery to join
2431
+ * @param alias - Alias for the derived table
2432
+ * @param condition - Join condition expression
2433
+ * @param joinKind - Join kind (defaults to INNER)
2434
+ * @param columnAliases - Optional column alias list for the derived table
2435
+ * @returns New query builder instance with the derived-table join
2436
+ */
2437
+ joinSubquery(subquery: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode, alias: string, condition: BinaryExpressionNode, joinKind?: JoinKind, columnAliases?: string[]): SelectQueryBuilder<T, TTable>;
2438
+ /**
2439
+
2440
+ * Adds an INNER JOIN to the query
2441
+
2442
+ * @param table - Table to join
2443
+
2444
+ * @param condition - Join condition expression
2445
+
2446
+ * @returns New query builder instance with the INNER JOIN
2447
+
2448
+ */
2449
+ innerJoin(table: TableDef, condition: BinaryExpressionNode): SelectQueryBuilder<T, TTable>;
2450
+ /**
2451
+
2452
+ * Adds a LEFT JOIN to the query
2453
+
2454
+ * @param table - Table to join
2455
+
2456
+ * @param condition - Join condition expression
2457
+
2458
+ * @returns New query builder instance with the LEFT JOIN
2459
+
2460
+ */
2461
+ leftJoin(table: TableDef, condition: BinaryExpressionNode): SelectQueryBuilder<T, TTable>;
2462
+ /**
2463
+
2464
+ * Adds a RIGHT JOIN to the query
2465
+
2466
+ * @param table - Table to join
2467
+
2468
+ * @param condition - Join condition expression
2469
+
2470
+ * @returns New query builder instance with the RIGHT JOIN
2471
+
2472
+ */
2473
+ rightJoin(table: TableDef, condition: BinaryExpressionNode): SelectQueryBuilder<T, TTable>;
2474
+ /**
2475
+
2476
+ * Matches records based on a relationship
2477
+
2478
+ * @param relationName - Name of the relationship to match
2479
+
2480
+ * @param predicate - Optional predicate expression
2481
+
2482
+ * @returns New query builder instance with the relationship match
2483
+
2484
+ */
2485
+ match(relationName: string, predicate?: ExpressionNode): SelectQueryBuilder<T, TTable>;
2486
+ /**
2487
+
2488
+ * Joins a related table
2489
+
2490
+ * @param relationName - Name of the relationship to join
2491
+
2492
+ * @param joinKind - Type of join (defaults to INNER)
2493
+
2494
+ * @param extraCondition - Optional additional join condition
2495
+
2496
+ * @returns New query builder instance with the relationship join
2497
+
2498
+ */
2499
+ joinRelation(relationName: string, joinKind?: JoinKind, extraCondition?: ExpressionNode): SelectQueryBuilder<T, TTable>;
2500
+ /**
2501
+
2502
+ * Includes related data in the query results
2503
+
2504
+ * @param relationName - Name of the relationship to include
2505
+
2506
+ * @param options - Optional include options
2507
+
2508
+ * @returns New query builder instance with the relationship inclusion
2509
+
2510
+ */
2511
+ include(relationName: string, options?: RelationIncludeOptions): SelectQueryBuilder<T, TTable>;
2512
+ includeLazy<K extends keyof RelationMap<TTable>>(relationName: K): SelectQueryBuilder<T, TTable>;
2513
+ /**
2514
+ * Selects columns for a related table in a single hop.
2515
+ */
2516
+ selectRelationColumns<K extends keyof TTable['relations'] & string, TRel extends RelationDef = TTable['relations'][K], TTarget extends TableDef = RelationTargetTable<TRel>, C extends keyof TTarget['columns'] & string = keyof TTarget['columns'] & string>(relationName: K, ...cols: C[]): SelectQueryBuilder<T, TTable>;
2517
+ /**
2518
+ * Convenience alias for selecting specific columns from a relation.
2519
+ */
2520
+ includePick<K extends keyof TTable['relations'] & string, TRel extends RelationDef = TTable['relations'][K], TTarget extends TableDef = RelationTargetTable<TRel>, C extends keyof TTarget['columns'] & string = keyof TTarget['columns'] & string>(relationName: K, cols: C[]): SelectQueryBuilder<T, TTable>;
2521
+ /**
2522
+ * Selects columns for the root table and relations from a single config object.
2523
+ */
2524
+ selectColumnsDeep(config: DeepSelectConfig<TTable>): SelectQueryBuilder<T, TTable>;
2525
+ getLazyRelations(): (keyof RelationMap<TTable>)[];
2526
+ getTable(): TTable;
2527
+ execute(ctx: OrmSession): Promise<EntityInstance<TTable>[]>;
2528
+ executeWithContexts(execCtx: ExecutionContext, hydCtx: HydrationContext): Promise<EntityInstance<TTable>[]>;
2529
+ /**
2530
+
2531
+ * Adds a WHERE condition to the query
2532
+
2533
+ * @param expr - Expression for the WHERE clause
2534
+
2535
+ * @returns New query builder instance with the WHERE condition
2536
+
2537
+ */
2538
+ where(expr: ExpressionNode): SelectQueryBuilder<T, TTable>;
2539
+ /**
2540
+
2541
+ * Adds a GROUP BY clause to the query
2542
+
2543
+ * @param col - Column definition or column node to group by
2544
+
2545
+ * @returns New query builder instance with the GROUP BY clause
2546
+
2547
+ */
2548
+ groupBy(col: ColumnDef | ColumnNode): SelectQueryBuilder<T, TTable>;
2549
+ /**
2550
+
2551
+ * Adds a HAVING condition to the query
2552
+
2553
+ * @param expr - Expression for the HAVING clause
2554
+
2555
+ * @returns New query builder instance with the HAVING condition
2556
+
2557
+ */
2558
+ having(expr: ExpressionNode): SelectQueryBuilder<T, TTable>;
2559
+ /**
2560
+
2561
+ * Adds an ORDER BY clause to the query
2562
+
2563
+ * @param col - Column definition or column node to order by
2564
+
2565
+ * @param direction - Order direction (defaults to ASC)
2566
+
2567
+ * @returns New query builder instance with the ORDER BY clause
2568
+
2569
+ */
2570
+ orderBy(col: ColumnDef | ColumnNode, direction?: OrderDirection): SelectQueryBuilder<T, TTable>;
2571
+ /**
2572
+
2573
+ * Adds a DISTINCT clause to the query
2574
+
2575
+ * @param cols - Columns to make distinct
2576
+
2577
+ * @returns New query builder instance with the DISTINCT clause
2578
+
2579
+ */
2580
+ distinct(...cols: (ColumnDef | ColumnNode)[]): SelectQueryBuilder<T, TTable>;
2581
+ /**
2582
+
2583
+ * Adds a LIMIT clause to the query
2584
+
2585
+ * @param n - Maximum number of rows to return
2586
+
2587
+ * @returns New query builder instance with the LIMIT clause
2588
+
2589
+ */
2590
+ limit(n: number): SelectQueryBuilder<T, TTable>;
2591
+ /**
2592
+
2593
+ * Adds an OFFSET clause to the query
2594
+
2595
+ * @param n - Number of rows to skip
2596
+
2597
+ * @returns New query builder instance with the OFFSET clause
2598
+
2599
+ */
2600
+ offset(n: number): SelectQueryBuilder<T, TTable>;
2601
+ /**
2602
+
2603
+ * Combines this query with another using UNION
2604
+
2605
+ * @param query - Query to union with
2606
+
2607
+ * @returns New query builder instance with the set operation
2608
+
2609
+ */
2610
+ union(query: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode): SelectQueryBuilder<T, TTable>;
2611
+ /**
2612
+
2613
+ * Combines this query with another using UNION ALL
2614
+
2615
+ * @param query - Query to union with
2616
+
2617
+ * @returns New query builder instance with the set operation
2618
+
2619
+ */
2620
+ unionAll(query: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode): SelectQueryBuilder<T, TTable>;
2621
+ /**
2622
+
2623
+ * Combines this query with another using INTERSECT
2624
+
2625
+ * @param query - Query to intersect with
2626
+
2627
+ * @returns New query builder instance with the set operation
2628
+
2629
+ */
2630
+ intersect(query: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode): SelectQueryBuilder<T, TTable>;
2631
+ /**
2632
+
2633
+ * Combines this query with another using EXCEPT
2634
+
2635
+ * @param query - Query to subtract
2636
+
2637
+ * @returns New query builder instance with the set operation
2638
+
2639
+ */
2640
+ except(query: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode): SelectQueryBuilder<T, TTable>;
2641
+ /**
2642
+
2643
+ * Adds a WHERE EXISTS condition to the query
2644
+
2645
+ * @param subquery - Subquery to check for existence
2646
+
2647
+ * @returns New query builder instance with the WHERE EXISTS condition
2648
+
2649
+ */
2650
+ whereExists(subquery: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode, correlate?: ExpressionNode): SelectQueryBuilder<T, TTable>;
2651
+ /**
2652
+
2653
+ * Adds a WHERE NOT EXISTS condition to the query
2654
+
2655
+ * @param subquery - Subquery to check for non-existence
2656
+
2657
+ * @returns New query builder instance with the WHERE NOT EXISTS condition
2658
+
2659
+ */
2660
+ whereNotExists(subquery: SelectQueryBuilder<any, TableDef<any>> | SelectQueryNode, correlate?: ExpressionNode): SelectQueryBuilder<T, TTable>;
2661
+ /**
2662
+
2663
+ * Adds a WHERE EXISTS condition based on a relationship
2664
+
2665
+ * @param relationName - Name of the relationship to check
2666
+
2667
+ * @param callback - Optional callback to modify the relationship query
2668
+
2669
+ * @returns New query builder instance with the relationship existence check
2670
+
2671
+ */
2672
+ whereHas(relationName: string, callbackOrOptions?: RelationCallback | WhereHasOptions, maybeOptions?: WhereHasOptions): SelectQueryBuilder<T, TTable>;
2673
+ /**
2674
+
2675
+ * Adds a WHERE NOT EXISTS condition based on a relationship
2676
+
2677
+ * @param relationName - Name of the relationship to check
2678
+
2679
+ * @param callback - Optional callback to modify the relationship query
2680
+
2681
+ * @returns New query builder instance with the relationship non-existence check
2682
+
2683
+ */
2684
+ whereHasNot(relationName: string, callbackOrOptions?: RelationCallback | WhereHasOptions, maybeOptions?: WhereHasOptions): SelectQueryBuilder<T, TTable>;
2685
+ /**
2686
+
2687
+ * Compiles the query to SQL for a specific dialect
2688
+
2689
+ * @param dialect - Database dialect to compile for
2690
+
2691
+ * @returns Compiled query with SQL and parameters
2692
+
2693
+ */
2694
+ compile(dialect: SelectDialectInput): CompiledQuery;
2695
+ /**
2696
+
2697
+ * Converts the query to SQL string for a specific dialect
2698
+
2699
+ * @param dialect - Database dialect to generate SQL for
2700
+
2701
+ * @returns SQL string representation of the query
2702
+
2703
+ */
2704
+ toSql(dialect: SelectDialectInput): string;
2705
+ /**
2706
+
2707
+ * Gets the hydration plan for the query
2708
+
2709
+ * @returns Hydration plan or undefined if none exists
2710
+
2711
+ */
2712
+ getHydrationPlan(): HydrationPlan | undefined;
2713
+ /**
2714
+
2715
+ * Gets the Abstract Syntax Tree (AST) representation of the query
2716
+
2717
+ * @returns Query AST with hydration applied
2718
+
2719
+ */
2720
+ getAST(): SelectQueryNode;
2721
+ }
309
2722
  /**
310
- * Dispatches an operand node to the visitor
311
- * @param node - Operand node to visit
312
- * @param visitor - Visitor implementation
313
- */
314
- declare const visitOperand: <R>(node: OperandNode, visitor: OperandVisitor<R>) => R;
315
2723
 
316
- /**
317
- * Adapts a schema ColumnDef to an AST-friendly ColumnRef.
2724
+ * Creates a column node for use in expressions
2725
+
2726
+ * @param table - Table name
2727
+
2728
+ * @param name - Column name
2729
+
2730
+ * @returns ColumnNode with the specified table and name
2731
+
318
2732
  */
319
- declare const toColumnRef: (col: ColumnRef | ColumnDef) => ColumnRef;
2733
+ declare const createColumn: (table: string, name: string) => ColumnNode;
320
2734
  /**
321
- * Adapts a schema TableDef to an AST-friendly TableRef.
2735
+
2736
+ * Creates a literal value node for use in expressions
2737
+
2738
+ * @param val - Literal value (string or number)
2739
+
2740
+ * @returns LiteralNode with the specified value
2741
+
322
2742
  */
323
- declare const toTableRef: (table: TableRef | TableDef) => TableRef;
2743
+ declare const createLiteral: (val: string | number) => LiteralNode;
324
2744
 
325
2745
  /**
326
2746
  * Build a typed selection map from a TableDef.
@@ -1198,8 +3618,8 @@ declare class TypeScriptGenerator implements ExpressionVisitor<string>, OperandV
1198
3618
  private mapOp;
1199
3619
  }
1200
3620
 
1201
- declare const createEntityProxy: <TTable extends TableDef, TLazy extends keyof RelationMap<TTable> = keyof RelationMap<TTable>>(ctx: EntityContext, table: TTable, row: Record<string, any>, lazyRelations?: TLazy[]) => Entity<TTable>;
1202
- declare const createEntityFromRow: <TTable extends TableDef>(ctx: EntityContext, table: TTable, row: Record<string, any>, lazyRelations?: (keyof RelationMap<TTable>)[]) => Entity<TTable>;
3621
+ declare const createEntityProxy: <TTable extends TableDef, TLazy extends keyof RelationMap<TTable> = keyof RelationMap<TTable>>(ctx: EntityContext, table: TTable, row: Record<string, any>, lazyRelations?: TLazy[]) => EntityInstance<TTable>;
3622
+ declare const createEntityFromRow: <TTable extends TableDef>(ctx: EntityContext, table: TTable, row: Record<string, any>, lazyRelations?: (keyof RelationMap<TTable>)[]) => EntityInstance<TTable>;
1203
3623
 
1204
3624
  type Rows$3 = Record<string, any>[];
1205
3625
  declare const loadHasManyRelation: (ctx: EntityContext, rootTable: TableDef, _relationName: string, relation: HasManyRelation) => Promise<Map<string, Rows$3>>;
@@ -1302,8 +3722,75 @@ declare class DefaultManyToManyCollection<TTarget> implements ManyToManyCollecti
1302
3722
  toJSON(): TTarget[];
1303
3723
  }
1304
3724
 
1305
- declare function executeHydrated<TTable extends TableDef>(session: OrmSession, qb: SelectQueryBuilder<any, TTable>): Promise<Entity<TTable>[]>;
1306
- declare function executeHydratedWithContexts<TTable extends TableDef>(_execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<any, TTable>): Promise<Entity<TTable>[]>;
3725
+ declare function executeHydrated<TTable extends TableDef>(session: OrmSession, qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable>[]>;
3726
+ declare function executeHydratedWithContexts<TTable extends TableDef>(_execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable>[]>;
3727
+
3728
+ interface StandardDecoratorContext {
3729
+ kind: string;
3730
+ name?: string | symbol;
3731
+ metadata?: Record<PropertyKey, unknown>;
3732
+ addInitializer?(initializer: (this: unknown) => void): void;
3733
+ static?: boolean;
3734
+ private?: boolean;
3735
+ }
3736
+ interface DualModePropertyDecorator {
3737
+ (target: object, propertyKey: string | symbol): void;
3738
+ (value: unknown, context: StandardDecoratorContext): void;
3739
+ }
3740
+ interface DualModeClassDecorator {
3741
+ <TFunction extends Function>(value: TFunction): void | TFunction;
3742
+ <TFunction extends Function>(value: TFunction, context: StandardDecoratorContext): void | TFunction;
3743
+ }
3744
+
3745
+ interface EntityOptions {
3746
+ tableName?: string;
3747
+ hooks?: TableHooks;
3748
+ }
3749
+ declare function Entity(options?: EntityOptions): DualModeClassDecorator;
3750
+
3751
+ interface ColumnOptions {
3752
+ type: ColumnType;
3753
+ args?: ColumnDef['args'];
3754
+ notNull?: boolean;
3755
+ primary?: boolean;
3756
+ }
3757
+ type ColumnInput = ColumnOptions | ColumnDef;
3758
+ declare function Column(definition: ColumnInput): DualModePropertyDecorator;
3759
+ declare function PrimaryKey(definition: ColumnInput): DualModePropertyDecorator;
3760
+
3761
+ interface BaseRelationOptions {
3762
+ target: EntityOrTableTargetResolver;
3763
+ cascade?: CascadeMode;
3764
+ localKey?: string;
3765
+ }
3766
+ interface HasManyOptions extends BaseRelationOptions {
3767
+ foreignKey: string;
3768
+ }
3769
+ interface HasOneOptions extends BaseRelationOptions {
3770
+ foreignKey: string;
3771
+ }
3772
+ interface BelongsToOptions extends BaseRelationOptions {
3773
+ foreignKey: string;
3774
+ }
3775
+ interface BelongsToManyOptions {
3776
+ target: EntityOrTableTargetResolver;
3777
+ pivotTable: EntityOrTableTargetResolver;
3778
+ pivotForeignKeyToRoot: string;
3779
+ pivotForeignKeyToTarget: string;
3780
+ localKey?: string;
3781
+ targetKey?: string;
3782
+ pivotPrimaryKey?: string;
3783
+ defaultPivotColumns?: string[];
3784
+ cascade?: CascadeMode;
3785
+ }
3786
+ declare function HasMany(options: HasManyOptions): DualModePropertyDecorator;
3787
+ declare function HasOne(options: HasOneOptions): DualModePropertyDecorator;
3788
+ declare function BelongsTo(options: BelongsToOptions): DualModePropertyDecorator;
3789
+ declare function BelongsToMany(options: BelongsToManyOptions): DualModePropertyDecorator;
3790
+
3791
+ declare const bootstrapEntities: () => TableDef[];
3792
+ declare const getTableDefFromEntity: (ctor: EntityConstructor) => TableDef | undefined;
3793
+ declare const selectFromEntity: <TTable extends TableDef>(ctor: EntityConstructor) => SelectQueryBuilder<any, TTable>;
1307
3794
 
1308
3795
  interface PostgresClientLike {
1309
3796
  query(text: string, params?: unknown[]): Promise<{
@@ -1376,4 +3863,4 @@ interface CreateTediousClientOptions {
1376
3863
  declare function createTediousMssqlClient(connection: TediousConnectionLike, { Request, TYPES }: TediousModule, options?: CreateTediousClientOptions): MssqlClientLike;
1377
3864
  declare function createTediousExecutor(connection: TediousConnectionLike, module: TediousModule, options?: CreateTediousClientOptions): DbExecutor;
1378
3865
 
1379
- export { AsyncLocalStorage, BelongsToManyRelation, BelongsToReference, BelongsToRelation, BetweenExpressionNode, BinaryExpressionNode, CaseExpressionNode, ColumnDef, type ColumnDiff, ColumnNode, ColumnRef, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, DbExecutor, DefaultBelongsToReference, DefaultHasManyCollection, DefaultManyToManyCollection, DeleteQueryBuilder, type DialectName, Entity, EntityContext, ExecutionContext, ExistsExpressionNode, ExpressionNode, type ExpressionVisitor, ForeignKeyReference, FunctionNode, type GroupConcatOptions, HasManyCollection, HasManyRelation, HasOneRelation, HydrationContext, HydrationPlan, InExpressionNode, IndexColumn, IndexDef, InsertQueryBuilder, type IntrospectOptions, JsonPathNode, LiteralNode, type LiteralValue, LogicalExpressionNode, ManyToManyCollection, type MssqlClientLike, MySqlDialect, type MysqlClientLike, NullExpressionNode, OperandNode, type OperandVisitor, OrmSession, type PostgresClientLike, PostgresDialect, RelationMap, type RenderColumnOptions, ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, SqlServerDialect, type SqliteClientLike, SqliteDialect, type SynchronizeOptions, TableDef, TableRef, type TediousColumn, type TediousConnectionLike, type TediousModule, type TediousRequest, type TediousRequestCtor, type TediousTypes, TypeScriptGenerator, UpdateQueryBuilder, type ValueOperandInput, WindowFunctionNode, abs, acos, and, ascii, asin, atan, atan2, avg, between, caseWhen, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, columnOperand, concat, concatWs, correlateBy, cos, cot, count, createEntityFromRow, createEntityProxy, createMssqlExecutor, createMysqlExecutor, createPostgresExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, degrees, denseRank, diffSchema, endOfMonth, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getSchemaIntrospector, groupConcat, gt, gte, hydrateRows, inList, instr, introspectSchema, isNotNull, isNull, isValueOperandInput, jsonPath, lag, lastValue, lead, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, locate, log, log10, logBase, lower, lpad, lt, lte, ltrim, max, min, mod, month, neq, notBetween, notExists, notInList, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, repeat, replace, right, round, rowNumber, rpad, rtrim, sel, sign, sin, space, sqrt, substr, sum, synchronizeSchema, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };
3866
+ export { type AnyDomainEvent, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type CascadeMode, type CaseExpressionNode, type CheckConstraint, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, DefaultBelongsToReference, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, type EntityOptions, EntityStatus, type ExecutionContext, type ExistsExpressionNode, type ExpressionNode, type ExpressionVisitor, type ExternalTransaction, type ForeignKeyReference, type FunctionNode, type GroupConcatOptions, type HasDomainEvents, HasMany, type HasManyCollection, type HasManyOptions, type HasManyRelation, HasOne, type HasOneOptions, type HasOneReference, type HasOneRelation, type HydrationContext, type HydrationMetadata, type HydrationPivotPlan, type HydrationPlan, type HydrationRelationPlan, type InExpressionNode, type IndexColumn, type IndexDef, type InferRow, type InitialHandlers, InsertQueryBuilder, type IntrospectOptions, type JsonPathNode, type LiteralNode, type LiteralValue, type LogicalExpressionNode, type ManyToManyCollection, type MssqlClientLike, MySqlDialect, type MysqlClientLike, type NullExpressionNode, type OperandNode, type OperandVisitor, Orm, type OrmDomainEvent, type OrmInterceptor, type OrmOptions, OrmSession, type OrmSessionOptions, type PostgresClientLike, PostgresDialect, PrimaryKey, type QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type RelationKey, RelationKinds, type RelationMap, type RelationTargetTable, type RelationType, type RenderColumnOptions, type ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, type SimpleQueryRunner, SqlServerDialect, type SqliteClientLike, SqliteDialect, type SynchronizeOptions, type TableDef, type TableHooks, type TableOptions, type TableRef, type TediousColumn, type TediousConnectionLike, type TediousModule, type TediousRequest, type TediousRequestCtor, type TediousTypes, type TrackedEntity, TypeScriptGenerator, UpdateQueryBuilder, type ValueOperandInput, type WindowFunctionNode, abs, acos, addDomainEvent, and, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bootstrapEntities, caseWhen, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, col, columnOperand, concat, concatWs, correlateBy, cos, cot, count, createColumn, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createLiteral, createMssqlExecutor, createMysqlExecutor, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, denseRank, diffSchema, endOfMonth, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getSchemaIntrospector, getTableDefFromEntity, groupConcat, gt, gte, hasMany, hasOne, hydrateRows, inList, instr, introspectSchema, isCaseExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonPath, lag, lastValue, lead, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, locate, log, log10, logBase, lower, lpad, lt, lte, ltrim, max, min, mod, month, neq, notBetween, notExists, notInList, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, repeat, replace, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, sel, selectFromEntity, sign, sin, space, sqrt, substr, sum, synchronizeSchema, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };