alepha 0.11.4 → 0.11.5

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/postgres.d.ts CHANGED
@@ -1 +1,1861 @@
1
- export * from '@alepha/postgres';
1
+ import * as _alepha_core10 from "alepha";
2
+ import { Alepha, AlephaError, Descriptor, DescriptorArgs, KIND, Page, Static, StaticEncode, TBigInt, TInteger, TNull, TNumber, TNumberOptions, TObject, TObjectOptions, TOptional, TPage, TSchema, TString, TStringOptions, TUnion, TUnsafe, pageSchema } from "alepha";
3
+ import { DateTime, DateTimeProvider } from "alepha/datetime";
4
+ import * as drizzle_orm0 from "drizzle-orm";
5
+ import { BuildExtraConfigColumns, SQL, SQLWrapper, sql } from "drizzle-orm";
6
+ import * as drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
7
+ import { LockConfig, LockStrength, PgColumn, PgColumnBuilderBase, PgDatabase, PgInsertValue, PgSchema, PgSelectBase, PgSequenceOptions, PgTableExtraConfigValue, PgTableWithColumns, PgTransaction, PgTransactionConfig, UpdateDeleteAction } from "drizzle-orm/pg-core";
8
+ import * as _alepha_logger0 from "alepha/logger";
9
+ import * as _alepha_lock0 from "alepha/lock";
10
+ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
11
+ import postgres from "postgres";
12
+ import * as _alepha_retry0 from "alepha/retry";
13
+ import * as typebox11 from "typebox";
14
+ import { PgTransactionConfig as PgTransactionConfig$1 } from "drizzle-orm/pg-core/session";
15
+ import * as DrizzleKit from "drizzle-kit/api";
16
+ import { MigrationConfig } from "drizzle-orm/migrator";
17
+ import * as dayjs0 from "dayjs";
18
+ import { UpdateDeleteAction as UpdateDeleteAction$1 } from "drizzle-orm/pg-core/foreign-keys";
19
+ export * from "drizzle-orm/pg-core";
20
+
21
+ //#region src/schemas/insertSchema.d.ts
22
+ /**
23
+ * Transforms a TObject schema for insert operations.
24
+ * All default properties at the root level are made optional.
25
+ *
26
+ * @example
27
+ * Before: { name: string; age: number(default=0); }
28
+ * After: { name: string; age?: number; }
29
+ */
30
+ type TObjectInsert<T extends TObject> = TObject<{ [K in keyof T["properties"]]: T["properties"][K] extends {
31
+ [PG_DEFAULT]: any;
32
+ } | {
33
+ "~optional": true;
34
+ } ? TOptional<T["properties"][K]> : T["properties"][K] }>;
35
+ declare const insertSchema: <T extends TObject>(obj: T) => TObjectInsert<T>;
36
+ //#endregion
37
+ //#region src/schemas/updateSchema.d.ts
38
+ /**
39
+ * Transforms a TObject schema for update operations.
40
+ * All optional properties at the root level are made nullable (i.e., `T | null`).
41
+ * This allows an API endpoint to explicitly accept `null` to clear an optional field in the database.
42
+ *
43
+ * @example
44
+ * Before: { name?: string; age: number; }
45
+ * After: { name?: string | null; age: number; }
46
+ */
47
+ type TObjectUpdate<T extends TObject> = TObject<{ [K in keyof T["properties"]]: T["properties"][K] extends TOptional<infer U> ? TOptional<TUnion<[U, TNull]>> : T["properties"][K] }>;
48
+ declare const updateSchema: <T extends TObject>(schema: T) => TObjectUpdate<T>;
49
+ //#endregion
50
+ //#region src/descriptors/$entity.d.ts
51
+ /**
52
+ * Creates a database entity descriptor that defines table structure using TypeBox schemas.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { t } from "alepha";
57
+ * import { $entity } from "alepha/postgres";
58
+ *
59
+ * const userEntity = $entity({
60
+ * name: "users",
61
+ * schema: t.object({
62
+ * id: pg.primaryKey(),
63
+ * name: t.text(),
64
+ * email: t.email(),
65
+ * }),
66
+ * });
67
+ * ```
68
+ */
69
+ declare const $entity: {
70
+ <TSchema$1 extends TObject>(options: EntityDescriptorOptions<TSchema$1>): EntityDescriptor<TSchema$1>;
71
+ [KIND]: typeof EntityDescriptor;
72
+ };
73
+ interface EntityDescriptorOptions<T extends TObject, Keys = keyof Static<T>> {
74
+ /**
75
+ * The database table name that will be created for this entity.
76
+ * If not provided, name will be inferred from the $repository variable name.
77
+ */
78
+ name: string;
79
+ /**
80
+ * TypeBox schema defining the table structure and column types.
81
+ */
82
+ schema: T;
83
+ /**
84
+ * Database indexes to create for query optimization.
85
+ */
86
+ indexes?: (Keys | {
87
+ /**
88
+ * Single column to index.
89
+ */
90
+ column: Keys;
91
+ /**
92
+ * Whether this should be a unique index (enforces uniqueness constraint).
93
+ */
94
+ unique?: boolean;
95
+ /**
96
+ * Custom name for the index. If not provided, generates name automatically.
97
+ */
98
+ name?: string;
99
+ } | {
100
+ /**
101
+ * Multiple columns for composite index (order matters for query optimization).
102
+ */
103
+ columns: Keys[];
104
+ /**
105
+ * Whether this should be a unique index (enforces uniqueness constraint).
106
+ */
107
+ unique?: boolean;
108
+ /**
109
+ * Custom name for the index. If not provided, generates name automatically.
110
+ */
111
+ name?: string;
112
+ })[];
113
+ /**
114
+ * Foreign key constraints to maintain referential integrity.
115
+ */
116
+ foreignKeys?: Array<{
117
+ /**
118
+ * Optional name for the foreign key constraint.
119
+ */
120
+ name?: string;
121
+ /**
122
+ * Local columns that reference the foreign table.
123
+ */
124
+ columns: Array<keyof Static<T>>;
125
+ /**
126
+ * Referenced columns in the foreign table.
127
+ * Must be EntityColumn references from other entities.
128
+ */
129
+ foreignColumns: Array<() => EntityColumn<any>>;
130
+ }>;
131
+ /**
132
+ * Additional table constraints for data validation.
133
+ *
134
+ * Constraints enforce business rules at the database level, providing
135
+ * an additional layer of data integrity beyond application validation.
136
+ *
137
+ * **Constraint Types**:
138
+ * - **Unique constraints**: Prevent duplicate values across columns
139
+ * - **Check constraints**: Enforce custom validation rules with SQL expressions
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * constraints: [
144
+ * {
145
+ * name: "unique_user_email",
146
+ * columns: ["email"],
147
+ * unique: true
148
+ * },
149
+ * {
150
+ * name: "valid_age_range",
151
+ * columns: ["age"],
152
+ * check: sql`age >= 0 AND age <= 150`
153
+ * },
154
+ * {
155
+ * name: "unique_user_username_per_tenant",
156
+ * columns: ["tenantId", "username"],
157
+ * unique: true
158
+ * }
159
+ * ]
160
+ * ```
161
+ */
162
+ constraints?: Array<{
163
+ /**
164
+ * Columns involved in this constraint.
165
+ */
166
+ columns: Array<keyof Static<T>>;
167
+ /**
168
+ * Optional name for the constraint.
169
+ */
170
+ name?: string;
171
+ /**
172
+ * Whether this is a unique constraint.
173
+ */
174
+ unique?: boolean | {};
175
+ /**
176
+ * SQL expression for check constraint validation.
177
+ */
178
+ check?: SQL;
179
+ }>;
180
+ /**
181
+ * Advanced Drizzle ORM configuration for complex table setups.
182
+ */
183
+ config?: (self: BuildExtraConfigColumns<string, FromSchema<T>, "pg">) => PgTableExtraConfigValue[];
184
+ }
185
+ declare class EntityDescriptor<T extends TObject = TObject> {
186
+ readonly options: EntityDescriptorOptions<T>;
187
+ constructor(options: EntityDescriptorOptions<T>);
188
+ alias(alias: string): this;
189
+ get cols(): EntityColumns<T>;
190
+ get name(): string;
191
+ get schema(): T;
192
+ get insertSchema(): TObjectInsert<T>;
193
+ get updateSchema(): TObjectUpdate<T>;
194
+ }
195
+ /**
196
+ * Convert a schema to columns.
197
+ */
198
+ type FromSchema<T extends TObject> = { [key in keyof T["properties"]]: PgColumnBuilderBase };
199
+ type SchemaToTableConfig<T extends TObject> = {
200
+ name: string;
201
+ schema: string | undefined;
202
+ columns: { [key in keyof T["properties"]]: PgColumn };
203
+ dialect: string;
204
+ };
205
+ type EntityColumn<T extends TObject> = {
206
+ name: string;
207
+ entity: EntityDescriptor<T>;
208
+ };
209
+ type EntityColumns<T extends TObject> = { [key in keyof T["properties"]]: EntityColumn<T> };
210
+ //#endregion
211
+ //#region src/constants/PG_SYMBOLS.d.ts
212
+ declare const PG_DEFAULT: unique symbol;
213
+ declare const PG_PRIMARY_KEY: unique symbol;
214
+ declare const PG_CREATED_AT: unique symbol;
215
+ declare const PG_UPDATED_AT: unique symbol;
216
+ declare const PG_DELETED_AT: unique symbol;
217
+ declare const PG_VERSION: unique symbol;
218
+ declare const PG_IDENTITY: unique symbol;
219
+ declare const PG_ENUM: unique symbol;
220
+ declare const PG_REF: unique symbol;
221
+ /**
222
+ * @deprecated Use `PG_IDENTITY` instead.
223
+ */
224
+ declare const PG_SERIAL: unique symbol;
225
+ type PgDefault = typeof PG_DEFAULT;
226
+ type PgRef = typeof PG_REF;
227
+ type PgPrimaryKey = typeof PG_PRIMARY_KEY;
228
+ type PgSymbols = {
229
+ [PG_DEFAULT]: {};
230
+ [PG_PRIMARY_KEY]: {};
231
+ [PG_CREATED_AT]: {};
232
+ [PG_UPDATED_AT]: {};
233
+ [PG_DELETED_AT]: {};
234
+ [PG_VERSION]: {};
235
+ [PG_IDENTITY]: PgIdentityOptions;
236
+ [PG_REF]: PgRefOptions;
237
+ [PG_ENUM]: PgEnumOptions;
238
+ /**
239
+ * @deprecated Use `PG_IDENTITY` instead.
240
+ */
241
+ [PG_SERIAL]: {};
242
+ };
243
+ type PgSymbolKeys = keyof PgSymbols;
244
+ type PgIdentityOptions = {
245
+ mode: "always" | "byDefault";
246
+ } & PgSequenceOptions & {
247
+ name?: string;
248
+ };
249
+ interface PgEnumOptions {
250
+ name?: string;
251
+ }
252
+ interface PgRefOptions {
253
+ ref: () => {
254
+ name: string;
255
+ entity: EntityDescriptor;
256
+ };
257
+ actions?: {
258
+ onUpdate?: UpdateDeleteAction;
259
+ onDelete?: UpdateDeleteAction;
260
+ };
261
+ }
262
+ //#endregion
263
+ //#region src/errors/PgError.d.ts
264
+ declare class PgError extends AlephaError {
265
+ name: string;
266
+ constructor(message: string, cause?: unknown);
267
+ }
268
+ //#endregion
269
+ //#region src/helpers/pgAttr.d.ts
270
+ /**
271
+ * Decorates a typebox schema with a Postgres attribute.
272
+ *
273
+ * > It's just a fancy way to add Symbols to a field.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * import { t } from "alepha";
278
+ * import { PG_UPDATED_AT } from "../constants/PG_SYMBOLS";
279
+ *
280
+ * export const updatedAtSchema = pgAttr(
281
+ * t.datetime(), PG_UPDATED_AT,
282
+ * );
283
+ * ```
284
+ */
285
+ declare const pgAttr: <T extends TSchema, Attr extends PgSymbolKeys>(type: T, attr: Attr, value?: PgSymbols[Attr]) => PgAttr<T, Attr>;
286
+ /**
287
+ * Retrieves the fields of a schema that have a specific attribute.
288
+ */
289
+ declare const getAttrFields: (schema: TObject, name: PgSymbolKeys) => PgAttrField[];
290
+ /**
291
+ * Type representation.
292
+ */
293
+ type PgAttr<T extends TSchema, TAttr extends PgSymbolKeys> = T & { [K in TAttr]: PgSymbols[K] };
294
+ interface PgAttrField {
295
+ key: string;
296
+ type: TSchema;
297
+ data: any;
298
+ nested?: any[];
299
+ one?: boolean;
300
+ }
301
+ //#endregion
302
+ //#region src/interfaces/FilterOperators.d.ts
303
+ interface FilterOperators<TValue> {
304
+ /**
305
+ * Test that two values are equal.
306
+ *
307
+ * Remember that the SQL standard dictates that
308
+ * two NULL values are not equal, so if you want to test
309
+ * whether a value is null, you may want to use
310
+ * `isNull` instead.
311
+ *
312
+ * ## Examples
313
+ *
314
+ * ```ts
315
+ * // Select cars made by Ford
316
+ * db.select().from(cars)
317
+ * .where(eq(cars.make, 'Ford'))
318
+ * ```
319
+ *
320
+ * @see isNull for a way to test equality to NULL.
321
+ */
322
+ eq?: TValue;
323
+ /**
324
+ * Test that two values are not equal.
325
+ *
326
+ * Remember that the SQL standard dictates that
327
+ * two NULL values are not equal, so if you want to test
328
+ * whether a value is not null, you may want to use
329
+ * `isNotNull` instead.
330
+ *
331
+ * ## Examples
332
+ *
333
+ * ```ts
334
+ * // Select cars not made by Ford
335
+ * db.select().from(cars)
336
+ * .where(ne(cars.make, 'Ford'))
337
+ * ```
338
+ *
339
+ * @see isNotNull for a way to test whether a value is not null.
340
+ */
341
+ ne?: TValue;
342
+ /**
343
+ * Test that the first expression passed is greater than
344
+ * the second expression.
345
+ *
346
+ * ## Examples
347
+ *
348
+ * ```ts
349
+ * // Select cars made after 2000.
350
+ * db.select().from(cars)
351
+ * .where(gt(cars.year, 2000))
352
+ * ```
353
+ *
354
+ * @see gte for greater-than-or-equal
355
+ */
356
+ gt?: TValue;
357
+ /**
358
+ * Test that the first expression passed is greater than
359
+ * or equal to the second expression. Use `gt` to
360
+ * test whether an expression is strictly greater
361
+ * than another.
362
+ *
363
+ * ## Examples
364
+ *
365
+ * ```ts
366
+ * // Select cars made on or after 2000.
367
+ * db.select().from(cars)
368
+ * .where(gte(cars.year, 2000))
369
+ * ```
370
+ *
371
+ * @see gt for a strictly greater-than condition
372
+ */
373
+ gte?: TValue;
374
+ /**
375
+ * Test that the first expression passed is less than
376
+ * the second expression.
377
+ *
378
+ * ## Examples
379
+ *
380
+ * ```ts
381
+ * // Select cars made before 2000.
382
+ * db.select().from(cars)
383
+ * .where(lt(cars.year, 2000))
384
+ * ```
385
+ *
386
+ * @see lte for greater-than-or-equal
387
+ */
388
+ lt?: TValue;
389
+ /**
390
+ * Test that the first expression passed is less than
391
+ * or equal to the second expression.
392
+ *
393
+ * ## Examples
394
+ *
395
+ * ```ts
396
+ * // Select cars made before 2000.
397
+ * db.select().from(cars)
398
+ * .where(lte(cars.year, 2000))
399
+ * ```
400
+ *
401
+ * @see lt for a strictly less-than condition
402
+ */
403
+ lte?: TValue;
404
+ /**
405
+ * Test whether the first parameter, a column or expression,
406
+ * has a value from a list passed as the second argument.
407
+ *
408
+ * ## Throws
409
+ *
410
+ * The argument passed in the second array can't be empty:
411
+ * if an empty is provided, this method will throw.
412
+ *
413
+ * ## Examples
414
+ *
415
+ * ```ts
416
+ * // Select cars made by Ford or GM.
417
+ * db.select().from(cars)
418
+ * .where(inArray(cars.make, ['Ford', 'GM']))
419
+ * ```
420
+ *
421
+ * @see notInArray for the inverse of this test
422
+ */
423
+ inArray?: TValue[];
424
+ /**
425
+ * Test whether the first parameter, a column or expression,
426
+ * has a value that is not present in a list passed as the
427
+ * second argument.
428
+ *
429
+ * ## Throws
430
+ *
431
+ * The argument passed in the second array can't be empty:
432
+ * if an empty is provided, this method will throw.
433
+ *
434
+ * ## Examples
435
+ *
436
+ * ```ts
437
+ * // Select cars made by any company except Ford or GM.
438
+ * db.select().from(cars)
439
+ * .where(notInArray(cars.make, ['Ford', 'GM']))
440
+ * ```
441
+ *
442
+ * @see inArray for the inverse of this test
443
+ */
444
+ notInArray?: TValue[];
445
+ /**
446
+ * Test whether an expression is not NULL. By the SQL standard,
447
+ * NULL is neither equal nor not equal to itself, so
448
+ * it's recommended to use `isNull` and `notIsNull` for
449
+ * comparisons to NULL.
450
+ *
451
+ * ## Examples
452
+ *
453
+ * ```ts
454
+ * // Select cars that have been discontinued.
455
+ * db.select().from(cars)
456
+ * .where(isNotNull(cars.discontinuedAt))
457
+ * ```
458
+ *
459
+ * @see isNull for the inverse of this test
460
+ */
461
+ isNotNull?: true;
462
+ /**
463
+ * Test whether an expression is NULL. By the SQL standard,
464
+ * NULL is neither equal nor not equal to itself, so
465
+ * it's recommended to use `isNull` and `notIsNull` for
466
+ * comparisons to NULL.
467
+ *
468
+ * ## Examples
469
+ *
470
+ * ```ts
471
+ * // Select cars that have no discontinuedAt date.
472
+ * db.select().from(cars)
473
+ * .where(isNull(cars.discontinuedAt))
474
+ * ```
475
+ *
476
+ * @see isNotNull for the inverse of this test
477
+ */
478
+ isNull?: true;
479
+ /**
480
+ * Test whether an expression is between two values. This
481
+ * is an easier way to express range tests, which would be
482
+ * expressed mathematically as `x <= a <= y` but in SQL
483
+ * would have to be like `a >= x AND a <= y`.
484
+ *
485
+ * Between is inclusive of the endpoints: if `column`
486
+ * is equal to `min` or `max`, it will be TRUE.
487
+ *
488
+ * ## Examples
489
+ *
490
+ * ```ts
491
+ * // Select cars made between 1990 and 2000
492
+ * db.select().from(cars)
493
+ * .where(between(cars.year, 1990, 2000))
494
+ * ```
495
+ *
496
+ * @see notBetween for the inverse of this test
497
+ */
498
+ between?: [number, number];
499
+ /**
500
+ * Test whether an expression is not between two values.
501
+ *
502
+ * This, like `between`, includes its endpoints, so if
503
+ * the `column` is equal to `min` or `max`, in this case
504
+ * it will evaluate to FALSE.
505
+ *
506
+ * ## Examples
507
+ *
508
+ * ```ts
509
+ * // Exclude cars made in the 1970s
510
+ * db.select().from(cars)
511
+ * .where(notBetween(cars.year, 1970, 1979))
512
+ * ```
513
+ *
514
+ * @see between for the inverse of this test
515
+ */
516
+ notBetween?: [number, number];
517
+ /**
518
+ * Compare a column to a pattern, which can include `%` and `_`
519
+ * characters to match multiple variations. Including `%`
520
+ * in the pattern matches zero or more characters, and including
521
+ * `_` will match a single character.
522
+ *
523
+ * ## Examples
524
+ *
525
+ * ```ts
526
+ * // Select all cars with 'Turbo' in their names.
527
+ * db.select().from(cars)
528
+ * .where(like(cars.name, '%Turbo%'))
529
+ * ```
530
+ *
531
+ * @see ilike for a case-insensitive version of this condition
532
+ */
533
+ like?: string;
534
+ /**
535
+ * The inverse of like - this tests that a given column
536
+ * does not match a pattern, which can include `%` and `_`
537
+ * characters to match multiple variations. Including `%`
538
+ * in the pattern matches zero or more characters, and including
539
+ * `_` will match a single character.
540
+ *
541
+ * ## Examples
542
+ *
543
+ * ```ts
544
+ * // Select all cars that don't have "ROver" in their name.
545
+ * db.select().from(cars)
546
+ * .where(notLike(cars.name, '%Rover%'))
547
+ * ```
548
+ *
549
+ * @see like for the inverse condition
550
+ * @see notIlike for a case-insensitive version of this condition
551
+ */
552
+ notLike?: string;
553
+ /**
554
+ * Case-insensitively compare a column to a pattern,
555
+ * which can include `%` and `_`
556
+ * characters to match multiple variations. Including `%`
557
+ * in the pattern matches zero or more characters, and including
558
+ * `_` will match a single character.
559
+ *
560
+ * Unlike like, this performs a case-insensitive comparison.
561
+ *
562
+ * ## Examples
563
+ *
564
+ * ```ts
565
+ * // Select all cars with 'Turbo' in their names.
566
+ * db.select().from(cars)
567
+ * .where(ilike(cars.name, '%Turbo%'))
568
+ * ```
569
+ *
570
+ * @see like for a case-sensitive version of this condition
571
+ */
572
+ ilike?: string;
573
+ /**
574
+ * The inverse of ilike - this case-insensitively tests that a given column
575
+ * does not match a pattern, which can include `%` and `_`
576
+ * characters to match multiple variations. Including `%`
577
+ * in the pattern matches zero or more characters, and including
578
+ * `_` will match a single character.
579
+ *
580
+ * ## Examples
581
+ *
582
+ * ```ts
583
+ * // Select all cars that don't have "Rover" in their name.
584
+ * db.select().from(cars)
585
+ * .where(notLike(cars.name, '%Rover%'))
586
+ * ```
587
+ *
588
+ * @see ilike for the inverse condition
589
+ * @see notLike for a case-sensitive version of this condition
590
+ */
591
+ notIlike?: string;
592
+ /**
593
+ * Test that a column or expression contains all elements of
594
+ * the list passed as the second argument.
595
+ *
596
+ * ## Throws
597
+ *
598
+ * The argument passed in the second array can't be empty:
599
+ * if an empty is provided, this method will throw.
600
+ *
601
+ * ## Examples
602
+ *
603
+ * ```ts
604
+ * // Select posts where its tags contain "Typescript" and "ORM".
605
+ * db.select().from(posts)
606
+ * .where(arrayContains(posts.tags, ['Typescript', 'ORM']))
607
+ * ```
608
+ *
609
+ * @see arrayContained to find if an array contains all elements of a column or expression
610
+ * @see arrayOverlaps to find if a column or expression contains any elements of an array
611
+ */
612
+ arrayContains?: TValue;
613
+ /**
614
+ * Test that the list passed as the second argument contains
615
+ * all elements of a column or expression.
616
+ *
617
+ * ## Throws
618
+ *
619
+ * The argument passed in the second array can't be empty:
620
+ * if an empty is provided, this method will throw.
621
+ *
622
+ * ## Examples
623
+ *
624
+ * ```ts
625
+ * // Select posts where its tags contain "Typescript", "ORM" or both,
626
+ * // but filtering posts that have additional tags.
627
+ * db.select().from(posts)
628
+ * .where(arrayContained(posts.tags, ['Typescript', 'ORM']))
629
+ * ```
630
+ *
631
+ * @see arrayContains to find if a column or expression contains all elements of an array
632
+ * @see arrayOverlaps to find if a column or expression contains any elements of an array
633
+ */
634
+ arrayContained?: TValue;
635
+ /**
636
+ * Test that a column or expression contains any elements of
637
+ * the list passed as the second argument.
638
+ *
639
+ * ## Throws
640
+ *
641
+ * The argument passed in the second array can't be empty:
642
+ * if an empty is provided, this method will throw.
643
+ *
644
+ * ## Examples
645
+ *
646
+ * ```ts
647
+ * // Select posts where its tags contain "Typescript", "ORM" or both.
648
+ * db.select().from(posts)
649
+ * .where(arrayOverlaps(posts.tags, ['Typescript', 'ORM']))
650
+ * ```
651
+ *
652
+ * @see arrayContains to find if a column or expression contains all elements of an array
653
+ * @see arrayContained to find if an array contains all elements of a column or expression
654
+ */
655
+ arrayOverlaps?: TValue;
656
+ }
657
+ //#endregion
658
+ //#region src/interfaces/PgQueryWhere.d.ts
659
+ type PgQueryWhere<T extends TObject, Relations extends PgRelationMap<TObject> | undefined = undefined> = (PgQueryWhereOperators<T> & PgQueryWhereConditions<T>) | (PgQueryWhereRelations<Relations> & PgQueryWhereOperators<T> & PgQueryWhereConditions<T, Relations>);
660
+ type PgQueryWhereOrSQL<T extends TObject, Relations extends PgRelationMap<TObject> | undefined = undefined> = SQLWrapper | PgQueryWhere<T, Relations>;
661
+ type PgQueryWhereOperators<T extends TObject> = { [Key in keyof Static<T>]?: FilterOperators<Static<T>[Key]> | Static<T>[Key] | (Static<T>[Key] extends object ? NestedJsonbQuery<Static<T>[Key]> : never) };
662
+ type PgQueryWhereConditions<T extends TObject, Relations extends PgRelationMap<TObject> | undefined = undefined> = {
663
+ /**
664
+ * Combine a list of conditions with the `and` operator. Conditions
665
+ * that are equal `undefined` are automatically ignored.
666
+ *
667
+ * ## Examples
668
+ *
669
+ * ```ts
670
+ * db.select().from(cars)
671
+ * .where(
672
+ * and(
673
+ * eq(cars.make, 'Volvo'),
674
+ * eq(cars.year, 1950),
675
+ * )
676
+ * )
677
+ * ```
678
+ */
679
+ and?: Array<PgQueryWhereOrSQL<T, Relations>>;
680
+ /**
681
+ * Combine a list of conditions with the `or` operator. Conditions
682
+ * that are equal `undefined` are automatically ignored.
683
+ *
684
+ * ## Examples
685
+ *
686
+ * ```ts
687
+ * db.select().from(cars)
688
+ * .where(
689
+ * or(
690
+ * eq(cars.make, 'GM'),
691
+ * eq(cars.make, 'Ford'),
692
+ * )
693
+ * )
694
+ * ```
695
+ */
696
+ or?: Array<PgQueryWhereOrSQL<T, Relations>>;
697
+ /**
698
+ * Negate the meaning of an expression using the `not` keyword.
699
+ *
700
+ * ## Examples
701
+ *
702
+ * ```ts
703
+ * // Select cars _not_ made by GM or Ford.
704
+ * db.select().from(cars)
705
+ * .where(not(inArray(cars.make, ['GM', 'Ford'])))
706
+ * ```
707
+ */
708
+ not?: PgQueryWhereOrSQL<T, Relations>;
709
+ /**
710
+ * Test whether a subquery evaluates to have any rows.
711
+ *
712
+ * ## Examples
713
+ *
714
+ * ```ts
715
+ * // Users whose `homeCity` column has a match in a cities
716
+ * // table.
717
+ * db
718
+ * .select()
719
+ * .from(users)
720
+ * .where(
721
+ * exists(db.select()
722
+ * .from(cities)
723
+ * .where(eq(users.homeCity, cities.id))),
724
+ * );
725
+ * ```
726
+ *
727
+ * @see notExists for the inverse of this test
728
+ */
729
+ exists?: SQLWrapper;
730
+ };
731
+ type PgQueryWhereRelations<Relations extends PgRelationMap<TObject> | undefined = undefined> = Relations extends PgRelationMap<TObject> ? { [K in keyof Relations]?: PgQueryWhere<Relations[K]["join"]["schema"], Relations[K]["with"]> } : {};
732
+ /**
733
+ * Recursively allow nested queries for JSONB object/array types
734
+ */
735
+ type NestedJsonbQuery<T> = T extends object ? T extends Array<infer U> ? U extends object ? { [K in keyof U]?: FilterOperators<U[K]> | U[K] } : FilterOperators<U> | U : { [K in keyof T]?: FilterOperators<T[K]> | T[K] | (T[K] extends object ? NestedJsonbQuery<T[K]> : never) } : FilterOperators<T> | T;
736
+ //#endregion
737
+ //#region src/interfaces/PgQuery.d.ts
738
+ /**
739
+ * Order direction for sorting
740
+ */
741
+ type OrderDirection = "asc" | "desc";
742
+ /**
743
+ * Single order by clause with column and direction
744
+ */
745
+ interface OrderByClause<T> {
746
+ column: keyof T;
747
+ direction?: OrderDirection;
748
+ }
749
+ /**
750
+ * Order by parameter - supports 3 modes:
751
+ * 1. String: orderBy: "name" (defaults to ASC)
752
+ * 2. Single object: orderBy: { column: "name", direction: "desc" }
753
+ * 3. Array: orderBy: [{ column: "name", direction: "asc" }, { column: "age", direction: "desc" }]
754
+ */
755
+ type OrderBy<T> = keyof T | OrderByClause<T> | Array<OrderByClause<T>>;
756
+ /**
757
+ * Generic query interface for PostgreSQL entities
758
+ */
759
+ interface PgQuery<T extends TObject = TObject> {
760
+ distinct?: (keyof Static<T>)[];
761
+ columns?: (keyof Static<T>)[];
762
+ where?: PgQueryWhereOrSQL<T>;
763
+ limit?: number;
764
+ offset?: number;
765
+ orderBy?: OrderBy<Static<T>>;
766
+ groupBy?: (keyof Static<T>)[];
767
+ }
768
+ type PgStatic<T extends TObject, Relations extends PgRelationMap<T>> = Static<T> & { [K in keyof Relations]: Static<Relations[K]["join"]["schema"]> & (Relations[K]["with"] extends PgRelationMap<TObject> ? PgStatic<Relations[K]["join"]["schema"], Relations[K]["with"]> : {}) };
769
+ interface PgQueryRelations<T extends TObject = TObject, Relations extends PgRelationMap<T> | undefined = undefined> extends PgQuery<T> {
770
+ with?: Relations;
771
+ where?: PgQueryWhereOrSQL<T, Relations>;
772
+ }
773
+ type PgRelationMap<Base extends TObject> = Record<string, PgRelation<Base>>;
774
+ type PgRelation<Base extends TObject> = {
775
+ type?: "left" | "inner" | "right";
776
+ join: {
777
+ schema: TObject;
778
+ name: string;
779
+ };
780
+ on: SQLWrapper | [keyof Static<Base>, {
781
+ name: string;
782
+ }];
783
+ with?: PgRelationMap<TObject>;
784
+ };
785
+ //#endregion
786
+ //#region src/descriptors/$sequence.d.ts
787
+ /**
788
+ * Creates a PostgreSQL sequence descriptor for generating unique numeric values.
789
+ */
790
+ declare const $sequence: {
791
+ (options?: SequenceDescriptorOptions): SequenceDescriptor;
792
+ [KIND]: typeof SequenceDescriptor;
793
+ };
794
+ interface SequenceDescriptorOptions extends PgSequenceOptions {
795
+ /**
796
+ * The name of the sequence. If not provided, the property key will be used.
797
+ */
798
+ name?: string;
799
+ provider?: DatabaseProvider;
800
+ }
801
+ declare class SequenceDescriptor extends Descriptor<SequenceDescriptorOptions> {
802
+ readonly provider: DatabaseProvider;
803
+ onInit(): void;
804
+ get name(): string;
805
+ next(): Promise<number>;
806
+ current(): Promise<number>;
807
+ protected $provider(): DatabaseProvider;
808
+ }
809
+ //#endregion
810
+ //#region src/services/ModelBuilder.d.ts
811
+ /**
812
+ * Database-specific table configuration functions
813
+ */
814
+ interface TableConfigBuilders<TConfig> {
815
+ index: (name: string) => {
816
+ on: (...columns: any[]) => TConfig;
817
+ };
818
+ uniqueIndex: (name: string) => {
819
+ on: (...columns: any[]) => TConfig;
820
+ };
821
+ unique: (name: string) => {
822
+ on: (...columns: any[]) => TConfig;
823
+ };
824
+ check: (name: string, sql: SQL) => TConfig;
825
+ foreignKey: (config: {
826
+ name: string;
827
+ columns: any[];
828
+ foreignColumns: any[];
829
+ }) => TConfig;
830
+ }
831
+ /**
832
+ * Abstract base class for transforming Alepha Descriptors (Entity, Sequence, etc...)
833
+ * into drizzle models (tables, enums, sequences, etc...).
834
+ */
835
+ declare abstract class ModelBuilder {
836
+ /**
837
+ * Build a table from an entity descriptor.
838
+ */
839
+ abstract buildTable(entity: EntityDescriptor, options: {
840
+ tables: Map<string, unknown>;
841
+ enums: Map<string, unknown>;
842
+ schema: string;
843
+ }): void;
844
+ /**
845
+ * Build a sequence from a sequence descriptor.
846
+ */
847
+ abstract buildSequence(sequence: SequenceDescriptor, options: {
848
+ sequences: Map<string, unknown>;
849
+ schema: string;
850
+ }): void;
851
+ /**
852
+ * Convert camelCase to snake_case for column names.
853
+ */
854
+ protected toColumnName(str: string): string;
855
+ /**
856
+ * Build the table configuration function for any database.
857
+ * This includes indexes, foreign keys, constraints, and custom config.
858
+ *
859
+ * @param entity - The entity descriptor
860
+ * @param builders - Database-specific builder functions
861
+ * @param tableResolver - Function to resolve entity references to table columns
862
+ * @param customConfigHandler - Optional handler for custom config
863
+ */
864
+ protected buildTableConfig<TConfig, TSelf>(entity: EntityDescriptor, builders: TableConfigBuilders<TConfig>, tableResolver?: (entityName: string) => any, customConfigHandler?: (config: any, self: TSelf) => TConfig[]): ((self: TSelf) => TConfig[]) | undefined;
865
+ }
866
+ //#endregion
867
+ //#region src/providers/drivers/DatabaseProvider.d.ts
868
+ type SQLLike = SQLWrapper | string;
869
+ declare abstract class DatabaseProvider {
870
+ protected readonly alepha: Alepha;
871
+ protected abstract readonly builder: ModelBuilder;
872
+ abstract readonly db: PgDatabase<any>;
873
+ abstract readonly dialect: "postgres" | "sqlite";
874
+ readonly enums: Map<string, unknown>;
875
+ readonly tables: Map<string, unknown>;
876
+ readonly sequences: Map<string, unknown>;
877
+ table<T extends TObject>(entity: EntityDescriptor<T>): PgTableWithColumns<SchemaToTableConfig<T>>;
878
+ get schema(): string;
879
+ registerEntity(entity: EntityDescriptor): void;
880
+ registerSequence(sequence: SequenceDescriptor): void;
881
+ abstract execute(statement: SQLLike): Promise<Record<string, unknown>[]>;
882
+ run<T extends TObject>(statement: SQLLike, schema: T): Promise<Array<Static<T>>>;
883
+ }
884
+ //#endregion
885
+ //#region src/schemas/pageQuerySchema.d.ts
886
+ declare const pageQuerySchema: typebox11.TObject<{
887
+ page: typebox11.TOptional<typebox11.TInteger>;
888
+ size: typebox11.TOptional<typebox11.TInteger>;
889
+ sort: typebox11.TOptional<typebox11.TString>;
890
+ }>;
891
+ type PageQuery = Static<typeof pageQuerySchema>;
892
+ //#endregion
893
+ //#region src/services/PgJsonQueryManager.d.ts
894
+ /**
895
+ * Manages JSONB query generation for nested object and array queries in PostgreSQL.
896
+ * This class handles complex nested queries using PostgreSQL's JSONB operators.
897
+ */
898
+ declare class PgJsonQueryManager {
899
+ /**
900
+ * Check if a query contains nested JSONB queries.
901
+ * A nested query is when the value is an object with operator keys.
902
+ */
903
+ hasNestedQuery(where: PgQueryWhere<TObject>): boolean;
904
+ /**
905
+ * Build a JSONB query condition for nested object queries.
906
+ * Supports deep nesting like: { profile: { contact: { email: { eq: "test@example.com" } } } }
907
+ *
908
+ * @param column The JSONB column
909
+ * @param path The path to the nested property (e.g., ['profile', 'contact', 'email'])
910
+ * @param operator The filter operator (e.g., { eq: "test@example.com" })
911
+ * @returns SQL condition
912
+ */
913
+ buildJsonbCondition(column: PgColumn, path: string[], operator: FilterOperators<any>): SQL | undefined;
914
+ /**
915
+ * Build JSONB array query conditions.
916
+ * Supports queries like: { addresses: { city: { eq: "Wonderland" } } }
917
+ * which translates to: EXISTS (SELECT 1 FROM jsonb_array_elements(addresses) elem WHERE elem->>'city' = 'Wonderland')
918
+ */
919
+ buildJsonbArrayCondition(column: PgColumn, path: string[], arrayPath: string, operator: FilterOperators<any>): SQL | undefined;
920
+ /**
921
+ * Apply a filter operator to a JSONB value.
922
+ */
923
+ private applyOperatorToJsonValue;
924
+ /**
925
+ * Parse a nested query object and extract the path and operator.
926
+ * For example: { profile: { contact: { email: { eq: "test@example.com" } } } }
927
+ * Returns: { path: ['profile', 'contact', 'email'], operator: { eq: "test@example.com" } }
928
+ */
929
+ parseNestedQuery(nestedQuery: any, currentPath?: string[]): Array<{
930
+ path: string[];
931
+ operator: FilterOperators<any>;
932
+ }>;
933
+ /**
934
+ * Determine if a property is a JSONB column based on the schema.
935
+ * A column is JSONB if it's defined as an object or array in the TypeBox schema.
936
+ */
937
+ isJsonbColumn(schema: TObject, columnName: string): boolean;
938
+ /**
939
+ * Check if an array property contains primitive types (string, number, boolean, etc.)
940
+ * rather than objects. Primitive arrays should use native Drizzle operators.
941
+ * @returns true if the array contains primitives, false if it contains objects
942
+ */
943
+ isPrimitiveArray(schema: TObject, columnName: string): boolean;
944
+ /**
945
+ * Check if a nested path points to an array property.
946
+ */
947
+ isArrayProperty(schema: TObject, path: string[]): boolean;
948
+ }
949
+ //#endregion
950
+ //#region src/services/PgQueryManager.d.ts
951
+ declare class PgQueryManager {
952
+ protected readonly jsonQueryManager: PgJsonQueryManager;
953
+ protected readonly alepha: Alepha;
954
+ /**
955
+ * Convert a query object to a SQL query.
956
+ */
957
+ toSQL(query: PgQueryWhereOrSQL<TObject>, options: {
958
+ schema: TObject;
959
+ col: (key: string) => PgColumn;
960
+ joins?: PgJoin[];
961
+ }): SQL | undefined;
962
+ /**
963
+ * Build a JSONB query for nested object/array queries.
964
+ */
965
+ protected buildJsonbQuery(column: PgColumn, nestedQuery: any, schema: TObject, columnName: string): SQL | undefined;
966
+ /**
967
+ * Check if an object has any filter operator properties.
968
+ */
969
+ protected hasFilterOperatorProperties(obj: any): boolean;
970
+ /**
971
+ * Map a filter operator to a SQL query.
972
+ */
973
+ mapOperatorToSql(operator: FilterOperators<any> | any, column: PgColumn, columnSchema?: TObject, columnName?: string): SQL | undefined;
974
+ /**
975
+ * Parse pagination sort string to orderBy format.
976
+ * Format: "firstName,-lastName" -> [{ column: "firstName", direction: "asc" }, { column: "lastName", direction: "desc" }]
977
+ * - Columns separated by comma
978
+ * - Prefix with '-' for DESC direction
979
+ *
980
+ * @param sort Pagination sort string
981
+ * @returns OrderBy array or single object
982
+ */
983
+ parsePaginationSort(sort: string): Array<{
984
+ column: string;
985
+ direction: "asc" | "desc";
986
+ }> | {
987
+ column: string;
988
+ direction: "asc" | "desc";
989
+ };
990
+ /**
991
+ * Normalize orderBy parameter to array format.
992
+ * Supports 3 modes:
993
+ * 1. String: "name" -> [{ column: "name", direction: "asc" }]
994
+ * 2. Object: { column: "name", direction: "desc" } -> [{ column: "name", direction: "desc" }]
995
+ * 3. Array: [{ column: "name" }, { column: "age", direction: "desc" }] -> normalized array
996
+ *
997
+ * @param orderBy The orderBy parameter
998
+ * @returns Normalized array of order by clauses
999
+ */
1000
+ normalizeOrderBy(orderBy: any): Array<{
1001
+ column: string;
1002
+ direction: "asc" | "desc";
1003
+ }>;
1004
+ /**
1005
+ * Create a pagination object.
1006
+ *
1007
+ * @deprecated Use `createPagination` from @alepha/core instead.
1008
+ * This method now delegates to the framework-level helper.
1009
+ *
1010
+ * @param entities The entities to paginate.
1011
+ * @param limit The limit of the pagination.
1012
+ * @param offset The offset of the pagination.
1013
+ * @param sort Optional sort metadata to include in response.
1014
+ */
1015
+ createPagination<T>(entities: T[], limit?: number, offset?: number, sort?: Array<{
1016
+ column: string;
1017
+ direction: "asc" | "desc";
1018
+ }>): _alepha_core10.Page<T>;
1019
+ }
1020
+ interface PgJoin {
1021
+ table: string;
1022
+ schema: TObject;
1023
+ key: string;
1024
+ col: (key: string) => PgColumn;
1025
+ parent?: string;
1026
+ }
1027
+ //#endregion
1028
+ //#region src/services/PgRelationManager.d.ts
1029
+ declare class PgRelationManager {
1030
+ /**
1031
+ * Recursively build joins for the query builder based on the relations map
1032
+ */
1033
+ buildJoins(provider: DatabaseProvider, builder: PgSelectBase<any, any, any>, joins: Array<PgJoin>, withRelations: PgRelationMap<TObject>, table: PgTableWithColumns<any>, parentKey?: string): void;
1034
+ /**
1035
+ * Map a row with its joined relations based on the joins definition
1036
+ */
1037
+ mapRowWithJoins(record: Record<string, unknown>, row: Record<string, unknown>, schema: TObject, joins: PgJoin[], parentKey?: string): Record<string, unknown>;
1038
+ /**
1039
+ * Check if all values in an object are null (indicates a left join with no match)
1040
+ */
1041
+ private isAllNull;
1042
+ /**
1043
+ * Build a schema that includes all join properties recursively
1044
+ */
1045
+ buildSchemaWithJoins(baseSchema: TObject, joins: PgJoin[], parentPath?: string): TObject;
1046
+ }
1047
+ //#endregion
1048
+ //#region src/descriptors/$repository.d.ts
1049
+ /**
1050
+ * Creates a repository for database operations on a defined entity.
1051
+ *
1052
+ * This descriptor provides a comprehensive, type-safe interface for performing all
1053
+ * database operations on entities defined with $entity. It offers a rich set of
1054
+ * CRUD operations, advanced querying capabilities, pagination, transactions, and
1055
+ * built-in support for audit trails and soft deletes.
1056
+ */
1057
+ declare const $repository: {
1058
+ <T extends TObject>(optionsOrEntity: EntityDescriptor<T> | EntityDescriptorOptions<T> | RepositoryDescriptorOptions<T>): RepositoryDescriptor<T>;
1059
+ [KIND]: typeof RepositoryDescriptor;
1060
+ };
1061
+ interface RepositoryDescriptorOptions<T extends TObject> {
1062
+ /**
1063
+ * The entity table definition created with $entity.
1064
+ *
1065
+ * This table:
1066
+ * - Must be created using the $entity descriptor
1067
+ * - Defines the schema, indexes, and constraints for the repository
1068
+ * - Provides type information for all repository operations
1069
+ * - Must include exactly one primary key field
1070
+ *
1071
+ * The repository will automatically:
1072
+ * - Generate typed CRUD operations based on the entity schema
1073
+ * - Handle audit fields like createdAt, updatedAt, deletedAt
1074
+ * - Support optimistic locking if version field is present
1075
+ * - Provide soft delete functionality if deletedAt field exists
1076
+ *
1077
+ * **Entity Requirements**:
1078
+ * - Must have been created with $entity descriptor
1079
+ * - Schema must include a primary key field marked with `pg.primaryKey()`
1080
+ * - Corresponding database table must exist (created via migrations)
1081
+ *
1082
+ * @example
1083
+ * ```ts
1084
+ * const User = $entity({
1085
+ * name: "users",
1086
+ * schema: t.object({
1087
+ * id: pg.primaryKey(t.uuid()),
1088
+ * email: t.text({ format: "email" }),
1089
+ * name: t.text()
1090
+ * })
1091
+ * });
1092
+ *
1093
+ * const userRepository = $repository({ table: User });
1094
+ * ```
1095
+ */
1096
+ entity: EntityDescriptor<T>;
1097
+ /**
1098
+ * Override the default PostgreSQL database provider.
1099
+ *
1100
+ * By default, the repository will use the injected PostgresProvider from the
1101
+ * dependency injection container. Use this option to:
1102
+ * - Connect to a different database
1103
+ * - Use a specific connection pool
1104
+ * - Implement custom database behavior
1105
+ * - Support multi-tenant architectures with database per tenant
1106
+ *
1107
+ * **Common Use Cases**:
1108
+ * - Multi-database applications
1109
+ * - Read replicas for query optimization
1110
+ * - Different databases for different entity types
1111
+ * - Testing with separate test databases
1112
+ *
1113
+ * @default Uses injected PostgresProvider
1114
+ *
1115
+ * @example ReadOnlyPostgresProvider
1116
+ * @example TenantSpecificPostgresProvider
1117
+ * @example TestDatabaseProvider
1118
+ */
1119
+ provider?: DatabaseProvider;
1120
+ name?: string;
1121
+ }
1122
+ declare class RepositoryDescriptor<T extends TObject = TObject> extends Descriptor<RepositoryDescriptorOptions<T>> {
1123
+ protected readonly relationManager: PgRelationManager;
1124
+ protected readonly queryManager: PgQueryManager;
1125
+ protected readonly dateTimeProvider: DateTimeProvider;
1126
+ protected readonly alepha: Alepha;
1127
+ readonly provider: DatabaseProvider;
1128
+ constructor(args: DescriptorArgs<RepositoryDescriptorOptions<T>>);
1129
+ /**
1130
+ * Get the entity descriptor associated with this repository.
1131
+ */
1132
+ get entity(): EntityDescriptor<T>;
1133
+ /**
1134
+ * Represents the primary key of the table.
1135
+ * - Key is the name of the primary key column.
1136
+ * - Type is the type (TypeBox) of the primary key column.
1137
+ *
1138
+ * ID is mandatory. If the table does not have a primary key, it will throw an error.
1139
+ */
1140
+ get id(): {
1141
+ type: TSchema;
1142
+ key: keyof T["properties"];
1143
+ col: PgColumn;
1144
+ };
1145
+ /**
1146
+ * Get Drizzle table object.
1147
+ */
1148
+ get table(): PgTableWithColumns<SchemaToTableConfig<T>>;
1149
+ /**
1150
+ * Get SQL table name. (from Drizzle table object)
1151
+ */
1152
+ get tableName(): string;
1153
+ /**
1154
+ * Getter for the database connection from the database provider.
1155
+ */
1156
+ protected get db(): PgDatabase<any>;
1157
+ /**
1158
+ * Execute a SQL query.
1159
+ *
1160
+ * This method allows executing raw SQL queries against the database.
1161
+ * This is by far the easiest way to run custom queries that are not covered by the repository's built-in methods!
1162
+ *
1163
+ * You must use the `sql` tagged template function from Drizzle ORM to create the query. https://orm.drizzle.team/docs/sql
1164
+ *
1165
+ * @example
1166
+ * ```ts
1167
+ * class App {
1168
+ * repository = $repository({ ... });
1169
+ * async getAdults() {
1170
+ * const users = repository.table; // Drizzle table object
1171
+ * await repository.query(sql`SELECT * FROM ${users} WHERE ${users.age} > ${18}`);
1172
+ * // or better
1173
+ * await repository.query((users) => sql`SELECT * FROM ${users} WHERE ${users.age} > ${18}`);
1174
+ * }
1175
+ * }
1176
+ * ```
1177
+ */
1178
+ query<R extends TObject = T>(query: SQLLike | ((table: PgTableWithColumns<SchemaToTableConfig<T>>, db: PgDatabase<any>) => SQLLike), schema?: R): Promise<Static<R>[]>;
1179
+ /**
1180
+ * Map raw database fields to entity fields. (handles column name differences)
1181
+ */
1182
+ protected mapRawFieldsToEntity(row: Record<string, unknown>): any;
1183
+ /**
1184
+ * Get a Drizzle column from the table by his name.
1185
+ */
1186
+ protected col(name: keyof StaticEncode<T>): PgColumn;
1187
+ /**
1188
+ * Run a transaction.
1189
+ */
1190
+ transaction<T>(transaction: (tx: PgTransaction<any, Record<string, any>, any>) => Promise<T>, config?: PgTransactionConfig): Promise<T>;
1191
+ /**
1192
+ * Start a SELECT query on the table.
1193
+ */
1194
+ protected select(opts?: StatementOptions): drizzle_orm_pg_core0.PgSelectBase<string, Record<string, PgColumn<drizzle_orm0.ColumnBaseConfig<drizzle_orm0.ColumnDataType, string>, {}, {}>>, "single", Record<string, "not-null">, false, never, {
1195
+ [x: string]: unknown;
1196
+ }[], {
1197
+ [x: string]: PgColumn<drizzle_orm0.ColumnBaseConfig<drizzle_orm0.ColumnDataType, string>, {}, {}>;
1198
+ }>;
1199
+ /**
1200
+ * Start a SELECT DISTINCT query on the table.
1201
+ */
1202
+ protected selectDistinct(opts?: StatementOptions, columns?: (keyof Static<T>)[]): drizzle_orm_pg_core0.PgSelectBase<string, Record<string, any>, "partial", Record<string, "not-null">, false, never, {
1203
+ [x: string]: any;
1204
+ }[], {
1205
+ [x: string]: any;
1206
+ }>;
1207
+ /**
1208
+ * Start an INSERT query on the table.
1209
+ */
1210
+ protected insert(opts?: StatementOptions): drizzle_orm_pg_core0.PgInsertBuilder<PgTableWithColumns<SchemaToTableConfig<T>>, any, false>;
1211
+ /**
1212
+ * Start an UPDATE query on the table.
1213
+ */
1214
+ protected update(opts?: StatementOptions): drizzle_orm_pg_core0.PgUpdateBuilder<PgTableWithColumns<SchemaToTableConfig<T>>, any>;
1215
+ /**
1216
+ * Start a DELETE query on the table.
1217
+ */
1218
+ protected delete(opts?: StatementOptions): drizzle_orm_pg_core0.PgDeleteBase<PgTableWithColumns<SchemaToTableConfig<T>>, any, undefined, undefined, false, never>;
1219
+ /**
1220
+ * Create a Drizzle `select` query based on a JSON query object.
1221
+ *
1222
+ * > This method is the base for `find`, `findOne`, `findById`, and `paginate`.
1223
+ */
1224
+ find<R extends PgRelationMap<T>>(query?: PgQueryRelations<T, R>, opts?: StatementOptions): Promise<PgStatic<T, R>[]>;
1225
+ /**
1226
+ * Find a single entity.
1227
+ */
1228
+ findOne<R extends PgRelationMap<T>>(query: Pick<PgQueryRelations<T, R>, "with" | "where">, opts?: StatementOptions): Promise<PgStatic<T, R>>;
1229
+ /**
1230
+ * Find entities with pagination.
1231
+ *
1232
+ * It uses the same parameters as `find()`, but adds pagination metadata to the response.
1233
+ *
1234
+ * > Pagination CAN also do a count query to get the total number of elements.
1235
+ */
1236
+ paginate<R extends PgRelationMap<T>>(pagination?: PageQuery, query?: PgQueryRelations<T, R>, opts?: StatementOptions & {
1237
+ count?: boolean;
1238
+ }): Promise<Page<PgStatic<T, R>>>;
1239
+ /**
1240
+ * Find an entity by ID.
1241
+ *
1242
+ * This is a convenience method for `findOne` with a where clause on the primary key.
1243
+ * If you need more complex queries, use `findOne` instead.
1244
+ */
1245
+ findById(id: string | number, opts?: StatementOptions): Promise<Static<T>>;
1246
+ /**
1247
+ * Helper to create a type-safe query object.
1248
+ */
1249
+ createQuery(): PgQuery<T>;
1250
+ /**
1251
+ * Helper to create a type-safe where clause.
1252
+ */
1253
+ createQueryWhere(): PgQueryWhere<T>;
1254
+ /**
1255
+ * Create an entity.
1256
+ *
1257
+ * @param data The entity to create.
1258
+ * @param opts The options for creating the entity.
1259
+ * @returns The ID of the created entity.
1260
+ */
1261
+ create(data: Static<TObjectInsert<T>>, opts?: StatementOptions): Promise<Static<T>>;
1262
+ /**
1263
+ * Create many entities.
1264
+ *
1265
+ * @param values The entities to create.
1266
+ * @param opts The statement options.
1267
+ * @returns The created entities.
1268
+ */
1269
+ createMany(values: Array<Static<TObjectInsert<T>>>, opts?: StatementOptions): Promise<Static<T>[]>;
1270
+ /**
1271
+ * Find an entity and update it.
1272
+ */
1273
+ updateOne(where: PgQueryWhereOrSQL<T>, data: Partial<Static<TObjectUpdate<T>>>, opts?: StatementOptions): Promise<Static<T>>;
1274
+ /**
1275
+ * Save a given entity.
1276
+ *
1277
+ * @example
1278
+ * ```ts
1279
+ * const entity = await repository.findById(1);
1280
+ * entity.name = "New Name"; // update a field
1281
+ * delete entity.description; // delete a field
1282
+ * await repository.save(entity);
1283
+ * ```
1284
+ *
1285
+ * Difference with `updateById/updateOne`:
1286
+ *
1287
+ * - requires the entity to be fetched first (whole object is expected)
1288
+ * - check pg.version() if present -> optimistic locking
1289
+ * - validate entity against schema
1290
+ * - undefined values will be set to null, not ignored!
1291
+ *
1292
+ * @see {@link PostgresTypeProvider#version}
1293
+ * @see {@link PgVersionMismatchError}
1294
+ */
1295
+ save(entity: Static<T>, opts?: StatementOptions): Promise<void>;
1296
+ /**
1297
+ * Find an entity by ID and update it.
1298
+ */
1299
+ updateById(id: string | number, data: Partial<Static<TObjectUpdate<T>>>, opts?: StatementOptions): Promise<Static<T>>;
1300
+ /**
1301
+ * Find many entities and update all of them.
1302
+ */
1303
+ updateMany(where: PgQueryWhereOrSQL<T>, data: Partial<Static<TObjectUpdate<T>>>, opts?: StatementOptions): Promise<Array<number | string>>;
1304
+ /**
1305
+ * Find many and delete all of them.
1306
+ * @returns Array of deleted entity IDs
1307
+ */
1308
+ deleteMany(where?: PgQueryWhereOrSQL<T>, opts?: StatementOptions): Promise<Array<number | string>>;
1309
+ /**
1310
+ * Delete all entities.
1311
+ * @returns Array of deleted entity IDs
1312
+ */
1313
+ clear(opts?: StatementOptions): Promise<Array<number | string>>;
1314
+ /**
1315
+ * Delete the given entity.
1316
+ *
1317
+ * You must fetch the entity first in order to delete it.
1318
+ * @returns Array containing the deleted entity ID
1319
+ */
1320
+ destroy(entity: Static<T>, opts?: StatementOptions): Promise<Array<number | string>>;
1321
+ /**
1322
+ * Find an entity and delete it.
1323
+ * @returns Array of deleted entity IDs (should contain at most one ID)
1324
+ */
1325
+ deleteOne(where?: PgQueryWhereOrSQL<T>, opts?: StatementOptions): Promise<Array<number | string>>;
1326
+ /**
1327
+ * Find an entity by ID and delete it.
1328
+ * @returns Array containing the deleted entity ID
1329
+ * @throws PgEntityNotFoundError if the entity is not found
1330
+ */
1331
+ deleteById(id: string | number, opts?: StatementOptions): Promise<Array<number | string>>;
1332
+ /**
1333
+ * Count entities.
1334
+ */
1335
+ count(where?: PgQueryWhereOrSQL<T>, opts?: StatementOptions): Promise<number>;
1336
+ protected conflictMessagePattern: string;
1337
+ protected handleError(error: unknown, message: string): PgError;
1338
+ protected withDeletedAt(where: PgQueryWhereOrSQL<T>, opts?: {
1339
+ force?: boolean;
1340
+ }): PgQueryWhereOrSQL<T>;
1341
+ protected deletedAt(): PgAttrField | undefined;
1342
+ /**
1343
+ * Convert something to valid Pg Insert Value.
1344
+ */
1345
+ protected cast(data: any, insert: boolean): PgInsertValue<PgTableWithColumns<SchemaToTableConfig<T>>>;
1346
+ /**
1347
+ * Transform a row from the database into a clean entity.
1348
+ *
1349
+ * - Validate against schema
1350
+ * - Replace all null values by undefined
1351
+ * - Fix date-time and date fields to ISO strings
1352
+ * - Cast BigInt to string
1353
+ */
1354
+ protected clean<T extends TObject>(row: Record<string, unknown>, schema: T): Static<T>;
1355
+ /**
1356
+ * Clean a row with joins recursively
1357
+ */
1358
+ protected cleanWithJoins<T extends TObject>(row: Record<string, unknown>, schema: T, joins: PgJoin[], parentPath?: string): Static<T>;
1359
+ /**
1360
+ * Convert a where clause to SQL.
1361
+ */
1362
+ protected toSQL(where: PgQueryWhereOrSQL<T>, joins?: PgJoin[]): SQL | undefined;
1363
+ /**
1364
+ * Get the where clause for an ID.
1365
+ *
1366
+ * @param id The ID to get the where clause for.
1367
+ * @returns The where clause for the ID.
1368
+ */
1369
+ protected getWhereId(id: string | number): PgQueryWhere<T>;
1370
+ /**
1371
+ * Find a primary key in the schema.
1372
+ */
1373
+ protected getPrimaryKey(schema: TObject): {
1374
+ key: string;
1375
+ col: PgColumn<drizzle_orm0.ColumnBaseConfig<drizzle_orm0.ColumnDataType, string>, {}, {}>;
1376
+ type: TSchema;
1377
+ };
1378
+ protected $provider(): DatabaseProvider;
1379
+ }
1380
+ /**
1381
+ * The options for a statement.
1382
+ */
1383
+ interface StatementOptions {
1384
+ /**
1385
+ * Transaction to use.
1386
+ */
1387
+ tx?: PgTransaction<any, Record<string, any>>;
1388
+ /**
1389
+ * Lock strength.
1390
+ */
1391
+ for?: LockStrength | {
1392
+ config: LockConfig;
1393
+ strength: LockStrength;
1394
+ };
1395
+ /**
1396
+ * If true, ignore soft delete.
1397
+ */
1398
+ force?: boolean;
1399
+ /**
1400
+ * Force the current time.
1401
+ */
1402
+ now?: DateTime;
1403
+ }
1404
+ //#endregion
1405
+ //#region src/descriptors/$transaction.d.ts
1406
+ /**
1407
+ * Creates a transaction descriptor for database operations requiring atomicity and consistency.
1408
+ *
1409
+ * This descriptor provides a convenient way to wrap database operations in PostgreSQL
1410
+ * transactions, ensuring ACID properties and automatic retry logic for version conflicts.
1411
+ * It integrates seamlessly with the repository pattern and provides built-in handling
1412
+ * for optimistic locking scenarios with automatic retry on version mismatches.
1413
+ *
1414
+ * **Important Notes**:
1415
+ * - All operations within the transaction handler are atomic
1416
+ * - Automatic retry on `PgVersionMismatchError` for optimistic locking
1417
+ * - Pass `{ tx }` option to all repository operations within the transaction
1418
+ * - Transactions are automatically rolled back on any unhandled error
1419
+ * - Use appropriate isolation levels based on your consistency requirements
1420
+ */
1421
+ declare const $transaction: <T extends any[], R>(opts: TransactionDescriptorOptions<T, R>) => _alepha_retry0.RetryDescriptorFn<(...args: T) => Promise<R>>;
1422
+ interface TransactionDescriptorOptions<T extends any[], R> {
1423
+ /**
1424
+ * Transaction handler function that contains all database operations to be executed atomically.
1425
+ *
1426
+ * This function:
1427
+ * - Receives a transaction object as the first parameter
1428
+ * - Should pass the transaction to all repository operations via `{ tx }` option
1429
+ * - All operations within are automatically rolled back if any error occurs
1430
+ * - Has access to the full Alepha dependency injection container
1431
+ * - Will be automatically retried if a `PgVersionMismatchError` occurs
1432
+ *
1433
+ * **Transaction Guidelines**:
1434
+ * - Keep transactions as short as possible to minimize lock contention
1435
+ * - Always pass the `tx` parameter to repository operations
1436
+ * - Handle expected business errors gracefully
1437
+ * - Log important operations for debugging and audit trails
1438
+ * - Consider the impact of long-running transactions on performance
1439
+ *
1440
+ * **Error Handling**:
1441
+ * - Throwing any error will automatically roll back the transaction
1442
+ * - `PgVersionMismatchError` triggers automatic retry logic
1443
+ * - Other database errors will be propagated after rollback
1444
+ * - Use try-catch within the handler for business-specific error handling
1445
+ *
1446
+ * @param tx - The PostgreSQL transaction object to use for all database operations
1447
+ * @param ...args - Additional arguments passed to the transaction function
1448
+ * @returns Promise resolving to the transaction result
1449
+ *
1450
+ * @example
1451
+ * ```ts
1452
+ * handler: async (tx, orderId: string, newStatus: string) => {
1453
+ * // Get the current order (with transaction)
1454
+ * const order = await this.orders.findById(orderId, { tx });
1455
+ *
1456
+ * // Validate business rules
1457
+ * if (!this.isValidStatusTransition(order.status, newStatus)) {
1458
+ * throw new Error(`Invalid status transition: ${order.status} -> ${newStatus}`);
1459
+ * }
1460
+ *
1461
+ * // Update order status (with transaction)
1462
+ * const updatedOrder = await this.orders.updateById(
1463
+ * orderId,
1464
+ * { status: newStatus },
1465
+ * { tx }
1466
+ * );
1467
+ *
1468
+ * // Create audit log (with transaction)
1469
+ * await this.auditLogs.create({
1470
+ * id: generateUUID(),
1471
+ * entityId: orderId,
1472
+ * action: 'status_change',
1473
+ * oldValue: order.status,
1474
+ * newValue: newStatus,
1475
+ * timestamp: new Date().toISOString()
1476
+ * }, { tx });
1477
+ *
1478
+ * return updatedOrder;
1479
+ * }
1480
+ * ```
1481
+ */
1482
+ handler: (tx: PgTransaction<any, any, any>, ...args: T) => Promise<R>;
1483
+ /**
1484
+ * PostgreSQL transaction configuration options.
1485
+ *
1486
+ * This allows you to customize transaction behavior including:
1487
+ * - **Isolation Level**: Controls visibility of concurrent transaction changes
1488
+ * - **Access Mode**: Whether the transaction is read-only or read-write
1489
+ * - **Deferrable**: For serializable transactions, allows deferring to avoid conflicts
1490
+ *
1491
+ * **Isolation Levels**:
1492
+ * - **read_uncommitted**: Lowest isolation, allows dirty reads (rarely used)
1493
+ * - **read_committed**: Default level, prevents dirty reads
1494
+ * - **repeatable_read**: Prevents dirty and non-repeatable reads
1495
+ * - **serializable**: Highest isolation, full ACID compliance
1496
+ *
1497
+ * **Access Modes**:
1498
+ * - **read_write**: Default, allows both read and write operations
1499
+ * - **read_only**: Only allows read operations, can provide performance benefits
1500
+ *
1501
+ * **When to Use Different Isolation Levels**:
1502
+ * - **read_committed**: Most common operations, good balance of consistency and performance
1503
+ * - **repeatable_read**: When you need consistent reads throughout the transaction
1504
+ * - **serializable**: Critical financial operations, when absolute consistency is required
1505
+ *
1506
+ * @example
1507
+ * ```ts
1508
+ * config: {
1509
+ * isolationLevel: 'serializable', // Highest consistency for financial operations
1510
+ * accessMode: 'read_write'
1511
+ * }
1512
+ * ```
1513
+ *
1514
+ * @example
1515
+ * ```ts
1516
+ * config: {
1517
+ * isolationLevel: 'read_committed', // Default level for most operations
1518
+ * accessMode: 'read_only' // Performance optimization for read-only operations
1519
+ * }
1520
+ * ```
1521
+ */
1522
+ config?: PgTransactionConfig$1;
1523
+ }
1524
+ type TransactionContext = PgTransaction<any, any, any>;
1525
+ //#endregion
1526
+ //#region src/errors/PgConflictError.d.ts
1527
+ declare class PgConflictError extends PgError {
1528
+ readonly name = "PgConflictError";
1529
+ readonly status = 409;
1530
+ }
1531
+ //#endregion
1532
+ //#region src/errors/PgEntityNotFoundError.d.ts
1533
+ declare class PgEntityNotFoundError extends PgError {
1534
+ readonly name = "EntityNotFoundError";
1535
+ readonly status = 404;
1536
+ constructor(entityName: string);
1537
+ }
1538
+ //#endregion
1539
+ //#region src/errors/PgMigrationError.d.ts
1540
+ declare class PgMigrationError extends PgError {
1541
+ readonly name = "PgMigrationError";
1542
+ constructor(cause?: unknown);
1543
+ }
1544
+ //#endregion
1545
+ //#region src/errors/PgVersionMismatchError.d.ts
1546
+ /**
1547
+ * Error thrown when there is a version mismatch.
1548
+ * It's thrown by {@link RepositoryDescriptor#save} when the updated entity version does not match the one in the database.
1549
+ * This is used for optimistic concurrency control.
1550
+ */
1551
+ declare class PgVersionMismatchError extends PgError {
1552
+ readonly name = "PgVersionMismatchError";
1553
+ constructor(table: string, id: any);
1554
+ }
1555
+ //#endregion
1556
+ //#region src/providers/DrizzleKitProvider.d.ts
1557
+ declare class DrizzleKitProvider {
1558
+ protected readonly log: _alepha_logger0.Logger;
1559
+ protected readonly alepha: Alepha;
1560
+ /**
1561
+ * Synchronize database with current schema definitions.
1562
+ *
1563
+ * In development mode, it will generate and execute migrations based on the current state.
1564
+ * In testing mode, it will generate migrations from scratch without applying them.
1565
+ *
1566
+ * Does nothing in production mode, you must handle migrations manually.
1567
+ */
1568
+ synchronize(provider: DatabaseProvider): Promise<void>;
1569
+ /**
1570
+ * Mostly used for testing purposes. You can generate SQL migration statements without executing them.
1571
+ */
1572
+ generateMigration(provider: DatabaseProvider, prevSnapshot?: any): Promise<{
1573
+ statements: string[];
1574
+ models: Record<string, unknown>;
1575
+ snapshot?: any;
1576
+ }>;
1577
+ /**
1578
+ * Load all tables, enums, sequences, etc. from the provider's repositories.
1579
+ */
1580
+ getModels(provider: DatabaseProvider): Record<string, unknown>;
1581
+ /**
1582
+ * Load the migration snapshot from the database.
1583
+ */
1584
+ protected loadDevMigrations(provider: DatabaseProvider): Promise<DevMigrations | undefined>;
1585
+ protected saveDevMigrations(provider: DatabaseProvider, curr: Record<string, any>, devMigrations?: DevMigrations): Promise<void>;
1586
+ protected executeStatements(statements: string[], provider: DatabaseProvider, catchErrors?: boolean): Promise<void>;
1587
+ protected createSchemaIfNotExists(provider: DatabaseProvider, schemaName: string): Promise<void>;
1588
+ /**
1589
+ * Try to load the official Drizzle Kit API.
1590
+ * If not available, fallback to the local kit import.
1591
+ */
1592
+ protected importDrizzleKit(): typeof DrizzleKit;
1593
+ }
1594
+ declare const devMigrationsSchema: typebox11.TObject<{
1595
+ id: typebox11.TNumber;
1596
+ name: typebox11.TString;
1597
+ snapshot: typebox11.TString;
1598
+ created_at: typebox11.TString;
1599
+ }>;
1600
+ type DevMigrations = Static<typeof devMigrationsSchema>;
1601
+ //#endregion
1602
+ //#region src/services/PostgresModelBuilder.d.ts
1603
+ declare class PostgresModelBuilder extends ModelBuilder {
1604
+ protected schemas: Map<string, drizzle_orm_pg_core0.PgSchema<string>>;
1605
+ protected getPgSchema(name: string): any;
1606
+ buildTable(entity: EntityDescriptor<any>, options: {
1607
+ tables: Map<string, unknown>;
1608
+ enums: Map<string, unknown>;
1609
+ schema: string;
1610
+ }): void;
1611
+ buildSequence(sequence: SequenceDescriptor, options: {
1612
+ sequences: Map<string, unknown>;
1613
+ schema: string;
1614
+ }): void;
1615
+ /**
1616
+ * Get PostgreSQL-specific config builder for the table.
1617
+ */
1618
+ protected getTableConfig(entity: EntityDescriptor, tables: Map<string, unknown>): ((self: BuildExtraConfigColumns<string, any, "pg">) => PgTableExtraConfigValue[]) | undefined;
1619
+ schemaToPgColumns: <T extends TObject>(tableName: string, schema: T, nsp: PgSchema, enums: Map<string, unknown>, tables: Map<string, unknown>) => FromSchema<T>;
1620
+ mapFieldToColumn: (tableName: string, fieldName: string, value: TSchema, nsp: PgSchema, enums: Map<string, any>) => any;
1621
+ /**
1622
+ * Map a string to a PG column.
1623
+ *
1624
+ * @param key The key of the field.
1625
+ * @param value The value of the field.
1626
+ */
1627
+ mapStringToColumn: (key: string, value: TSchema) => drizzle_orm_pg_core0.PgUUIDBuilderInitial<string> | drizzle_orm_pg_core0.PgCustomColumnBuilder<{
1628
+ name: string;
1629
+ dataType: "custom";
1630
+ columnType: "PgCustomColumn";
1631
+ data: Buffer<ArrayBufferLike>;
1632
+ driverParam: unknown;
1633
+ enumValues: undefined;
1634
+ }> | drizzle_orm_pg_core0.PgTimestampStringBuilderInitial<string> | drizzle_orm_pg_core0.PgDateStringBuilderInitial<string> | drizzle_orm_pg_core0.PgTextBuilderInitial<string, [string, ...string[]]>;
1635
+ }
1636
+ //#endregion
1637
+ //#region src/providers/drivers/NodePostgresProvider.d.ts
1638
+ declare module "alepha" {
1639
+ interface Env extends Partial<Static<typeof envSchema>> {}
1640
+ }
1641
+ declare const envSchema: _alepha_core10.TObject<{
1642
+ /**
1643
+ * Main configuration for database connection.
1644
+ * Accept a string in the format of a Postgres connection URL.
1645
+ * Example: postgres://user:password@localhost:5432/database
1646
+ * or
1647
+ * Example: postgres://user:password@localhost:5432/database?sslmode=require
1648
+ */
1649
+ DATABASE_URL: _alepha_core10.TOptional<_alepha_core10.TString>;
1650
+ /**
1651
+ * In addition to the DATABASE_URL, you can specify the postgres schema name.
1652
+ *
1653
+ * It will monkey patch drizzle tables.
1654
+ */
1655
+ POSTGRES_SCHEMA: _alepha_core10.TOptional<_alepha_core10.TString>;
1656
+ /**
1657
+ * Synchronize the database schema with the models.
1658
+ * It uses a custom implementation, it's not related to `drizzle-kit push` command.
1659
+ * It will generate the migration script and save it to the DB.
1660
+ *
1661
+ * This is recommended for development and testing purposes only.
1662
+ */
1663
+ POSTGRES_SYNCHRONIZE: _alepha_core10.TOptional<_alepha_core10.TBoolean>;
1664
+ }>;
1665
+ interface NodePostgresProviderOptions {
1666
+ migrations: MigrationConfig;
1667
+ connection: postgres.Options<any>;
1668
+ }
1669
+ declare class NodePostgresProvider extends DatabaseProvider {
1670
+ static readonly SSL_MODES: readonly ["require", "allow", "prefer", "verify-full"];
1671
+ readonly dialect = "postgres";
1672
+ protected readonly log: _alepha_logger0.Logger;
1673
+ protected readonly env: {
1674
+ DATABASE_URL?: string | undefined;
1675
+ POSTGRES_SCHEMA?: string | undefined;
1676
+ POSTGRES_SYNCHRONIZE?: boolean | undefined;
1677
+ };
1678
+ protected readonly alepha: Alepha;
1679
+ protected readonly kit: DrizzleKitProvider;
1680
+ protected readonly builder: PostgresModelBuilder;
1681
+ protected client?: postgres.Sql;
1682
+ protected pg?: PostgresJsDatabase;
1683
+ readonly options: NodePostgresProviderOptions;
1684
+ /**
1685
+ * In testing mode, the schema name will be generated and deleted after the test.
1686
+ */
1687
+ protected schemaForTesting: string | undefined;
1688
+ execute(statement: SQLLike): Promise<Array<Record<string, unknown>>>;
1689
+ /**
1690
+ * Get Postgres schema.
1691
+ */
1692
+ get schema(): string;
1693
+ get db(): PostgresJsDatabase;
1694
+ protected readonly onStart: _alepha_core10.HookDescriptor<"start">;
1695
+ protected readonly onStop: _alepha_core10.HookDescriptor<"stop">;
1696
+ connect(): Promise<void>;
1697
+ close(): Promise<void>;
1698
+ protected migrate: _alepha_lock0.LockDescriptor<() => Promise<void>>;
1699
+ /**
1700
+ * Generate a minimal migration configuration.
1701
+ */
1702
+ protected getMigrationOptions(): MigrationConfig;
1703
+ /**
1704
+ * Map the DATABASE_URL to postgres client options.
1705
+ */
1706
+ protected getClientOptions(): postgres.Options<any>;
1707
+ protected ssl(url: URL): "require" | "allow" | "prefer" | "verify-full" | undefined;
1708
+ /**
1709
+ * For testing purposes, generate a unique schema name.
1710
+ * The schema name will be generated based on the current date and time.
1711
+ * It will be in the format of `test_YYYYMMDD_HHMMSS_randomSuffix`.
1712
+ */
1713
+ protected generateTestSchemaName(): string;
1714
+ }
1715
+ //#endregion
1716
+ //#region src/providers/PostgresTypeProvider.d.ts
1717
+ declare class PostgresTypeProvider {
1718
+ readonly attr: <T extends TSchema, Attr extends PgSymbolKeys>(type: T, attr: Attr, value?: PgSymbols[Attr]) => PgAttr<T, Attr>;
1719
+ /**
1720
+ * Creates a primary key with an identity column.
1721
+ */
1722
+ readonly identityPrimaryKey: (identity?: PgIdentityOptions, options?: TNumberOptions) => PgAttr<PgAttr<PgAttr<TInteger, typeof PG_PRIMARY_KEY>, typeof PG_IDENTITY>, typeof PG_DEFAULT>;
1723
+ /**
1724
+ * Creates a primary key with a big identity column. (default)
1725
+ */
1726
+ readonly bigIdentityPrimaryKey: (identity?: PgIdentityOptions, options?: TNumberOptions) => PgAttr<PgAttr<PgAttr<TNumber, typeof PG_PRIMARY_KEY>, typeof PG_IDENTITY>, typeof PG_DEFAULT>;
1727
+ /**
1728
+ * Creates a primary key with a UUID column.
1729
+ */
1730
+ readonly uuidPrimaryKey: () => PgAttr<PgAttr<TString, typeof PG_PRIMARY_KEY>, typeof PG_DEFAULT>;
1731
+ /**
1732
+ * Creates a primary key for a given type. Supports:
1733
+ * - `t.int()` -> PG INT (default)
1734
+ * - `t.bigint()` -> PG BIGINT
1735
+ * - `t.uuid()` -> PG UUID
1736
+ */
1737
+ primaryKey(): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;
1738
+ primaryKey(type: TString, options?: TStringOptions): PgAttr<PgAttr<TString, PgPrimaryKey>, PgDefault>;
1739
+ primaryKey(type: TInteger, options?: TNumberOptions, identity?: PgIdentityOptions): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;
1740
+ primaryKey(type: TNumber, options?: TNumberOptions, identity?: PgIdentityOptions): PgAttr<PgAttr<TNumber, PgPrimaryKey>, PgDefault>;
1741
+ primaryKey(type: TBigInt, options?: TNumberOptions, identity?: PgIdentityOptions): PgAttr<PgAttr<TBigInt, PgPrimaryKey>, PgDefault>;
1742
+ /**
1743
+ * Wrap a schema with "default" attribute.
1744
+ * This is used to set a default value for a column in the database.
1745
+ */
1746
+ readonly default: <T extends TSchema>(type: T, value?: Static<T>) => PgAttr<T, PgDefault>;
1747
+ /**
1748
+ * Creates a column 'version'.
1749
+ *
1750
+ * This is used to track the version of a row in the database.
1751
+ *
1752
+ * You can use it for optimistic concurrency control (OCC) with {@link RepositoryDescriptor#save}.
1753
+ *
1754
+ * @see {@link RepositoryDescriptor#save}
1755
+ * @see {@link PgVersionMismatchError}
1756
+ */
1757
+ readonly version: (options?: TNumberOptions) => PgAttr<PgAttr<TInteger, typeof PG_VERSION>, typeof PG_DEFAULT>;
1758
+ /**
1759
+ * Creates a column Created At. So just a datetime column with a default value of the current timestamp.
1760
+ */
1761
+ readonly createdAt: (options?: TStringOptions) => PgAttr<PgAttr<typebox11.TCodec<TString, dayjs0.Dayjs>, typeof PG_CREATED_AT>, typeof PG_DEFAULT>;
1762
+ /**
1763
+ * Creates a column Updated At. Like createdAt, but it is updated on every update of the row.
1764
+ */
1765
+ readonly updatedAt: (options?: TStringOptions) => PgAttr<PgAttr<typebox11.TCodec<TString, dayjs0.Dayjs>, typeof PG_UPDATED_AT>, typeof PG_DEFAULT>;
1766
+ /**
1767
+ * Creates a column Deleted At for soft delete functionality.
1768
+ * This is used to mark rows as deleted without actually removing them from the database.
1769
+ * The column is nullable - NULL means not deleted, timestamp means deleted.
1770
+ */
1771
+ readonly deletedAt: (options?: TStringOptions) => PgAttr<typebox11.TOptional<typebox11.TCodec<TString, dayjs0.Dayjs>>, typeof PG_DELETED_AT>;
1772
+ /**
1773
+ * Creates a Postgres ENUM type.
1774
+ *
1775
+ * > By default, `t.enum()` is mapped to a TEXT column in Postgres.
1776
+ * > Using this method, you can create a real ENUM type in the database.
1777
+ *
1778
+ * @example
1779
+ * ```ts
1780
+ * const statusEnum = pg.enum(["pending", "active", "archived"], { name: "status_enum" });
1781
+ * ```
1782
+ */
1783
+ readonly enum: <T extends string[]>(values: [...T], pgEnumOptions?: PgEnumOptions, typeOptions?: TStringOptions) => PgAttr<TUnsafe<T[number]>, typeof PG_ENUM>;
1784
+ /**
1785
+ * Creates a reference to another table or schema. Basically a foreign key.
1786
+ */
1787
+ readonly ref: <T extends TSchema>(type: T, ref: () => any, actions?: {
1788
+ onUpdate?: UpdateDeleteAction$1;
1789
+ onDelete?: UpdateDeleteAction$1;
1790
+ }) => PgAttr<T, PgRef>;
1791
+ /**
1792
+ * Creates a page schema for a given object schema.
1793
+ * It's used by {@link RepositoryDescriptor#paginate} method.
1794
+ */
1795
+ readonly page: <T extends TObject>(resource: T, options?: TObjectOptions) => TPage<T>;
1796
+ }
1797
+ declare const pg: PostgresTypeProvider;
1798
+ //#endregion
1799
+ //#region src/schemas/legacyIdSchema.d.ts
1800
+ /**
1801
+ * @deprecated Use `pg.primaryKey()` instead.
1802
+ */
1803
+ declare const legacyIdSchema: PgAttr<PgAttr<PgAttr<typebox11.TInteger, typeof PG_PRIMARY_KEY>, typeof PG_SERIAL>, typeof PG_DEFAULT>;
1804
+ //#endregion
1805
+ //#region src/types/schema.d.ts
1806
+ /**
1807
+ * Postgres schema type.
1808
+ */
1809
+ declare const schema: <TDocument extends TSchema>(name: string, document: TDocument) => drizzle_orm0.$Type<drizzle_orm_pg_core0.PgCustomColumnBuilder<{
1810
+ name: string;
1811
+ dataType: "custom";
1812
+ columnType: "PgCustomColumn";
1813
+ data: typebox11.StaticType<[], "Decode", {}, {}, TDocument>;
1814
+ driverParam: string;
1815
+ enumValues: undefined;
1816
+ }>, typebox11.StaticType<[], "Decode", {}, {}, TDocument>>;
1817
+ //#endregion
1818
+ //#region src/index.d.ts
1819
+ /**
1820
+ * Postgres client based on Drizzle ORM, Alepha type-safe friendly.
1821
+ *
1822
+ * ```ts
1823
+ * const users = $entity({
1824
+ * name: "users",
1825
+ * schema: t.object({
1826
+ * id: pg.primaryKey(),
1827
+ * name: t.text(),
1828
+ * email: t.text(),
1829
+ * }),
1830
+ * });
1831
+ *
1832
+ * class Db {
1833
+ * users = $repository(users);
1834
+ * }
1835
+ *
1836
+ * const db = alepha.inject(Db);
1837
+ * const user = await db.users.one({ name: { eq: "John Doe" } });
1838
+ * ```
1839
+ *
1840
+ * This is not a full ORM, but rather a set of tools to work with Postgres databases in a type-safe way.
1841
+ *
1842
+ * It provides:
1843
+ * - A type-safe way to define entities and repositories. (via `$entity` and `$repository`)
1844
+ * - Custom query builders and filters.
1845
+ * - Built-in special columns like `createdAt`, `updatedAt`, `deletedAt`, `version`.
1846
+ * - Automatic JSONB support.
1847
+ * - Automatic synchronization of entities with the database schema (for testing and development).
1848
+ * - Fallback to raw SQL via Drizzle ORM `sql` function.
1849
+ *
1850
+ * Migrations are supported via Drizzle ORM, you need to use the `drizzle-kit` CLI tool to generate and run migrations.
1851
+ *
1852
+ * @see {@link $entity}
1853
+ * @see {@link $sequence}
1854
+ * @see {@link $repository}
1855
+ * @see {@link $transaction}
1856
+ * @module alepha.postgres
1857
+ */
1858
+ declare const AlephaPostgres: _alepha_core10.Service<_alepha_core10.Module<{}>>;
1859
+ //#endregion
1860
+ export { $entity, $repository, $sequence, $transaction, AlephaPostgres, DatabaseProvider, DrizzleKitProvider, EntityColumn, EntityColumns, EntityDescriptor, EntityDescriptorOptions, FilterOperators, FromSchema, NodePostgresProvider, NodePostgresProviderOptions, OrderBy, OrderByClause, OrderDirection, PG_CREATED_AT, PG_DEFAULT, PG_DELETED_AT, PG_ENUM, PG_IDENTITY, PG_PRIMARY_KEY, PG_REF, PG_SERIAL, PG_UPDATED_AT, PG_VERSION, type Page, PageQuery, PgAttr, PgAttrField, PgConflictError, PgDefault, PgEntityNotFoundError, PgEnumOptions, PgError, PgIdentityOptions, PgMigrationError, PgPrimaryKey, PgQuery, PgQueryRelations, PgQueryWhere, PgQueryWhereOrSQL, PgRef, PgRefOptions, PgRelation, PgRelationMap, PgStatic, PgSymbolKeys, PgSymbols, PgVersionMismatchError, PostgresTypeProvider, RepositoryDescriptor, RepositoryDescriptorOptions, SQLLike, SchemaToTableConfig, SequenceDescriptor, SequenceDescriptorOptions, StatementOptions, TObjectInsert, TObjectUpdate, type TPage, TransactionContext, TransactionDescriptorOptions, drizzle_orm0 as drizzle, getAttrFields, insertSchema, legacyIdSchema, pageQuerySchema, pageSchema, pg, pgAttr, schema, sql, updateSchema };
1861
+ //# sourceMappingURL=index.d.ts.map