hysteria-orm 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts ADDED
@@ -0,0 +1,4374 @@
1
+ import * as mongodb from 'mongodb';
2
+ import * as sqlite3 from 'sqlite3';
3
+ import * as pg from 'pg';
4
+ import { PoolClient } from 'pg';
5
+ import * as mysql2_promise from 'mysql2/promise';
6
+ import { PoolConnection } from 'mysql2/promise';
7
+ import { PassThrough } from 'node:stream';
8
+ import { FormatOptionsWithLanguage } from 'sql-formatter';
9
+ import { Redis, RedisOptions } from 'ioredis';
10
+
11
+ type CaseConvention = "camel" | "snake" | "preserve" | RegExp | ((column: string) => string);
12
+
13
+ /**
14
+ * @description The most basic class for all models for both SQL and NoSQL databases
15
+ * @internal Not meant to be used outside of the library
16
+ */
17
+ declare abstract class Entity {
18
+ /**
19
+ * @description Defines the case convention for the model
20
+ * @description Useful in raw queries, better to leave it as none in Model definition so it will respect the exact column name from the model, else it will convert the column name to the case convention you choose (default is camel case)
21
+ * @type {CaseConvention}
22
+ */
23
+ static modelCaseConvention: CaseConvention;
24
+ /**
25
+ * @description Defines the case convention for the database, this should be the case convention you use in your database
26
+ * @type {CaseConvention}
27
+ */
28
+ static databaseCaseConvention: CaseConvention;
29
+ }
30
+
31
+ type Mysql2Import = typeof mysql2_promise;
32
+ type PgImport = typeof pg;
33
+ type Sqlite3Import = typeof sqlite3;
34
+ type MongoClientImport = typeof mongodb;
35
+ type ExcludeStringFromOptions<T> = T extends string ? never : T;
36
+ type MysqlCreateConnectionOptions = Parameters<Mysql2Import["createPool"]>[0];
37
+ type PgClientOptions = ExcludeStringFromOptions<ConstructorParameters<PgImport["Pool"]>[0]>;
38
+ type MongoConnectionOptions = NonNullable<ConstructorParameters<MongoClientImport["MongoClient"]>[1]>;
39
+ type DriverSpecificOptions = {
40
+ mysqlOptions?: MysqlCreateConnectionOptions;
41
+ pgOptions?: PgClientOptions;
42
+ mongoOptions?: MongoConnectionOptions;
43
+ };
44
+
45
+ type MongoCollectionKey<T> = T extends Collection ? T : never;
46
+ type BaseModelMethodOptions$1 = {
47
+ useConnection?: MongoDataSource;
48
+ session?: ReturnType<MongoDataSource["startSession"]>;
49
+ };
50
+ /**
51
+ * @descriptionAllows Allows a type safe way to make a Partial of T, while keeping the keys that are not in T for unstructured data
52
+ */
53
+ type ModelKeyOrAny<T> = {
54
+ [key in keyof T]?: T[key];
55
+ } & {
56
+ [key: string]: any;
57
+ };
58
+ /**
59
+ * @description Allows a type-safe way to make a Partial of T, while keeping the keys that are not in T for unstructured data, with values restricted to 1 or -1
60
+ */
61
+ type ModelKeyOrAnySort<T> = {
62
+ [key in keyof T]?: 1 | -1;
63
+ } & {
64
+ [key: string]: 1 | -1;
65
+ };
66
+
67
+ type FetchHooks$1 = "beforeFetch" | "afterFetch";
68
+ type BinaryOperatorType$2 = "$eq" | "$ne" | "$gt" | "$gte" | "$lt" | "$lte";
69
+ type BaseValues$2 = string | number | boolean | Date | Array<string | number | boolean | Date>;
70
+ type OneOptions$1 = {
71
+ throwErrorOnNull?: boolean;
72
+ ignoreHooks?: FetchHooks$1[];
73
+ };
74
+ type ManyOptions$1 = {
75
+ ignoreHooks?: FetchHooks$1[];
76
+ };
77
+ declare class MongoQueryBuilder<T extends Collection> {
78
+ protected idObject: MongoClientImport["Collection"]["prototype"]["find"]["prototype"]["filter"];
79
+ protected selectObject?: Record<string, 1>;
80
+ protected selectFields?: string[];
81
+ protected whereObject: MongoClientImport["Collection"]["prototype"]["find"]["prototype"]["filter"];
82
+ protected sortObject?: MongoClientImport["Collection"]["prototype"]["find"]["prototype"]["sort"];
83
+ protected limitNumber?: number;
84
+ protected offsetNumber?: number;
85
+ protected mongoDataSource: MongoDataSource;
86
+ protected collection: MongoClientImport["Collection"]["prototype"];
87
+ protected model: typeof Collection;
88
+ protected logs: boolean;
89
+ protected session?: ReturnType<MongoDataSource["startSession"]>;
90
+ constructor(model: typeof Collection, mongoDataSource: MongoDataSource, _session?: ReturnType<MongoDataSource["startSession"]>, logs?: boolean);
91
+ one(options?: OneOptions$1): Promise<T | null>;
92
+ oneOrFail(options?: OneOptions$1): Promise<T>;
93
+ many(options?: ManyOptions$1): Promise<T[]>;
94
+ /**
95
+ * @description Inserts a new document into the collection
96
+ * @param options.returning - If true, the inserted document will be returned, else only the inserted id from mongodb will be returned
97
+ */
98
+ insert<O extends ModelKeyOrAny<T>>(modelData: O, options?: {
99
+ ignoreHooks?: boolean;
100
+ returning?: boolean;
101
+ }): Promise<O & {
102
+ id: string;
103
+ }>;
104
+ /**
105
+ * @description Inserts multiple documents into the collection
106
+ * @param modelData
107
+ * @param options
108
+ * @returns
109
+ */
110
+ insertMany<O extends ModelKeyOrAny<T>>(modelData: O[], options?: {
111
+ ignoreHooks?: boolean;
112
+ returning?: boolean;
113
+ }): Promise<(O & {
114
+ id: string;
115
+ })[]>;
116
+ /**
117
+ * @Massive Updates all the documents that match the query
118
+ * @param modelData
119
+ * @returns
120
+ */
121
+ update(modelData: ModelKeyOrAny<T>, options?: {
122
+ ignoreHooks?: boolean;
123
+ }): Promise<T[]>;
124
+ /**
125
+ * @Massive Deletes all the documents that match the query
126
+ * @returns
127
+ */
128
+ delete(options?: {
129
+ ignoreHooks?: boolean;
130
+ }): Promise<void>;
131
+ /**
132
+ * @description Fetches the count of the query
133
+ * @returns - The count of the query
134
+ */
135
+ count(options?: {
136
+ ignoreHooks?: boolean;
137
+ }): Promise<number>;
138
+ /**
139
+ * @description Only fetches the provided fields
140
+ * @param fields - Fields to select
141
+ */
142
+ select(fields: MongoCollectionKey<T>[]): this;
143
+ select(fields: string[]): this;
144
+ /**
145
+ * @description Adds a where clause to the query
146
+ */
147
+ where(property: MongoCollectionKey<T>, operator: BinaryOperatorType$2, value: BaseValues$2): this;
148
+ where(property: string, operator: BinaryOperatorType$2, value: BaseValues$2): this;
149
+ where(property: MongoCollectionKey<T> | string, value: BaseValues$2): this;
150
+ /**
151
+ * @description Adds a where clause to the query - alias for where
152
+ */
153
+ andWhere(property: MongoCollectionKey<T>, operator: BinaryOperatorType$2, value: BaseValues$2): this;
154
+ andWhere(property: string, operator: BinaryOperatorType$2, value: BaseValues$2): this;
155
+ andWhere(property: MongoCollectionKey<T> | string, value: BaseValues$2): this;
156
+ /**
157
+ * @description Adds an or where clause to the query
158
+ */
159
+ orWhere(property: MongoCollectionKey<T>, operator: BinaryOperatorType$2, value: BaseValues$2): this;
160
+ orWhere(property: string, operator: BinaryOperatorType$2, value: BaseValues$2): this;
161
+ orWhere(property: MongoCollectionKey<T> | string, value: BaseValues$2): this;
162
+ /**
163
+ * @description Adds a where exists clause to the query
164
+ */
165
+ whereExists(property: MongoCollectionKey<T>): this;
166
+ whereExists(property: string): this;
167
+ /**
168
+ * @description Adds an and where exists clause to the query
169
+ */
170
+ andWhereExists(property: MongoCollectionKey<T>): this;
171
+ andWhereExists(property: string): this;
172
+ /**
173
+ * @description Adds an or where exists clause to the query
174
+ */
175
+ orWhereExists(property: MongoCollectionKey<T>): this;
176
+ orWhereExists(property: string): this;
177
+ /**
178
+ * @description Adds a where not exists clause to the query
179
+ */
180
+ whereNotExists(property: MongoCollectionKey<T>): this;
181
+ whereNotExists(property: string): this;
182
+ /**
183
+ * @description Adds an and where not exists clause to the query
184
+ */
185
+ andWhereNotExists(property: MongoCollectionKey<T>): this;
186
+ andWhereNotExists(property: string): this;
187
+ /**
188
+ * @description Adds an or where not exists clause to the query
189
+ */
190
+ orWhereNotExists(property: MongoCollectionKey<T>): this;
191
+ orWhereNotExists(property: string): this;
192
+ /**
193
+ * @description Adds a where not clause to the query
194
+ */
195
+ whereNot(property: MongoCollectionKey<T>, value: BaseValues$2): this;
196
+ whereNot(property: string, value: BaseValues$2): this;
197
+ /**
198
+ * @description Adds an and where not clause to the query
199
+ */
200
+ andWhereNot(property: MongoCollectionKey<T>, value: BaseValues$2): this;
201
+ andWhereNot(property: string, value: BaseValues$2): this;
202
+ /**
203
+ * @description Adds an or where not clause to the query
204
+ */
205
+ orWhereNot(property: MongoCollectionKey<T>, value: BaseValues$2): this;
206
+ orWhereNot(property: string, value: BaseValues$2): this;
207
+ /**
208
+ * @description Adds a where like clause to the query
209
+ */
210
+ whereLike(property: MongoCollectionKey<T>, value: string): this;
211
+ whereLike(property: string, value: string): this;
212
+ /**
213
+ * @description Adds an and where like clause to the query
214
+ */
215
+ andWhereLike(property: MongoCollectionKey<T>, value: string): this;
216
+ andWhereLike(property: string, value: string): this;
217
+ /**
218
+ * @description Adds an or where like clause to the query
219
+ */
220
+ orWhereLike(property: MongoCollectionKey<T>, value: string): this;
221
+ orWhereLike(property: string, value: string): this;
222
+ /**
223
+ * @description Adds a where not like clause to the query
224
+ */
225
+ whereNotLike(property: MongoCollectionKey<T>, value: string): this;
226
+ whereNotLike(property: string, value: string): this;
227
+ /**
228
+ * @description Adds an and where not like clause to the query
229
+ */
230
+ andWhereNotLike(property: MongoCollectionKey<T>, value: string): this;
231
+ andWhereNotLike(property: string, value: string): this;
232
+ /**
233
+ * @description Adds an or where not like clause to the query
234
+ */
235
+ orWhereNotLike(property: MongoCollectionKey<T>, value: string): this;
236
+ orWhereNotLike(property: string, value: string): this;
237
+ /**
238
+ * @description Adds a where in clause to the query
239
+ */
240
+ whereIn(property: MongoCollectionKey<T>, values: BaseValues$2[]): this;
241
+ whereIn(property: string, values: BaseValues$2[]): this;
242
+ /**
243
+ * @description Adds an and where in clause to the query
244
+ */
245
+ andWhereIn(property: MongoCollectionKey<T>, values: BaseValues$2[]): this;
246
+ andWhereIn(property: string, values: BaseValues$2[]): this;
247
+ /**
248
+ * @description Adds an or where in clause to the query
249
+ */
250
+ orWhereIn(property: MongoCollectionKey<T>, values: BaseValues$2[]): this;
251
+ orWhereIn(property: string, values: BaseValues$2[]): this;
252
+ /**
253
+ * @description Adds a where not in clause to the query
254
+ */
255
+ whereNotIn(property: MongoCollectionKey<T>, values: BaseValues$2[]): this;
256
+ whereNotIn(property: string, values: BaseValues$2[]): this;
257
+ /**
258
+ * @description Adds an and where not in clause to the query
259
+ */
260
+ andWhereNotIn(property: MongoCollectionKey<T>, values: BaseValues$2[]): this;
261
+ andWhereNotIn(property: string, values: BaseValues$2[]): this;
262
+ /**
263
+ * @description Adds an or where not in clause to the query
264
+ */
265
+ orWhereNotIn(property: MongoCollectionKey<T>, values: BaseValues$2[]): this;
266
+ orWhereNotIn(property: string, values: BaseValues$2[]): this;
267
+ /**
268
+ * @description Adds a where null clause to the query
269
+ */
270
+ whereNull(property: MongoCollectionKey<T>): this;
271
+ whereNull(property: string): this;
272
+ /**
273
+ * @description Adds an and where null clause to the query
274
+ */
275
+ andWhereNull(property: MongoCollectionKey<T>): this;
276
+ andWhereNull(property: string): this;
277
+ /**
278
+ * @description Adds an or where null clause to the query
279
+ */
280
+ orWhereNull(property: MongoCollectionKey<T>): this;
281
+ orWhereNull(property: string): this;
282
+ /**
283
+ * @description Adds a where not null clause to the query
284
+ */
285
+ whereNotNull(property: MongoCollectionKey<T>): this;
286
+ whereNotNull(property: string): this;
287
+ /**
288
+ * @description Adds an and where not null clause to the query
289
+ */
290
+ andWhereNotNull(property: MongoCollectionKey<T>): this;
291
+ andWhereNotNull(property: string): this;
292
+ /**
293
+ * @description Adds an or where not null clause to the query
294
+ */
295
+ orWhereNotNull(property: MongoCollectionKey<T>): this;
296
+ orWhereNotNull(property: string): this;
297
+ /**
298
+ * @description Adds a where between clause to the query
299
+ */
300
+ whereBetween(property: MongoCollectionKey<T>, values: [BaseValues$2, BaseValues$2]): this;
301
+ whereBetween(property: string, values: [BaseValues$2, BaseValues$2]): this;
302
+ /**
303
+ * @description Adds an and where between clause to the query
304
+ */
305
+ andWhereBetween(property: MongoCollectionKey<T>, values: [BaseValues$2, BaseValues$2]): this;
306
+ andWhereBetween(property: string, values: [BaseValues$2, BaseValues$2]): this;
307
+ /**
308
+ * @description Adds an or where between clause to the query
309
+ */
310
+ orWhereBetween(property: MongoCollectionKey<T>, values: [BaseValues$2, BaseValues$2]): this;
311
+ orWhereBetween(property: string, values: [BaseValues$2, BaseValues$2]): this;
312
+ /**
313
+ * @description Adds a where not between clause to the query
314
+ */
315
+ whereNotBetween(property: MongoCollectionKey<T>, values: [BaseValues$2, BaseValues$2]): this;
316
+ whereNotBetween(property: string, values: [BaseValues$2, BaseValues$2]): this;
317
+ /**
318
+ * @description Adds an and where not between clause to the query
319
+ */
320
+ andWhereNotBetween(property: MongoCollectionKey<T>, values: [BaseValues$2, BaseValues$2]): this;
321
+ andWhereNotBetween(property: string, values: [BaseValues$2, BaseValues$2]): this;
322
+ /**
323
+ * @description Adds an or where not between clause to the query
324
+ */
325
+ orWhereNotBetween(property: MongoCollectionKey<T>, values: [BaseValues$2, BaseValues$2]): this;
326
+ orWhereNotBetween(property: string, values: [BaseValues$2, BaseValues$2]): this;
327
+ /**
328
+ * @description Gives the possibility to add a raw where clause using the mongodb.Filter type
329
+ */
330
+ whereRaw(whereObject: MongoClientImport["Collection"]["prototype"]["find"]["prototype"]["filter"]): this;
331
+ /**
332
+ * @description Gives the possibility to add a raw where clause using the mongodb.Filter type
333
+ */
334
+ andRawWhere(whereObject: MongoClientImport["Collection"]["prototype"]["find"]["prototype"]["filter"]): this;
335
+ /**
336
+ * @description Gives the possibility to add a raw where clause using the mongodb.Filter type
337
+ */
338
+ orRawWhere(whereObject: MongoClientImport["Collection"]["prototype"]["find"]["prototype"]["filter"]): this;
339
+ /**
340
+ * @description Adds a sort to the query for the id
341
+ * @param sortBy - The sort criteria, which can be a number, string, object, or array of these types
342
+ * @returns
343
+ */
344
+ sortById(sortBy: 1 | -1): this;
345
+ /**
346
+ * @description Adds a sort to the query, do not use this method if you want to sort by id use the sortById method
347
+ * @param sortBy - The sort criteria, which can be a number, string, object, or array of these types
348
+ * @returns The current instance for chaining
349
+ */
350
+ sort(sortBy: 1 | -1): this;
351
+ sort(sortBy: MongoCollectionKey<T>): this;
352
+ sort(sortBy: MongoCollectionKey<T>[]): this;
353
+ sort(sortBy: string): this;
354
+ sort(sortBy: string[]): this;
355
+ sort(sortBy: ModelKeyOrAnySort<T>): this;
356
+ /**
357
+ * @description Adds a limit to the query
358
+ * @param limit - The limit to set
359
+ * @returns
360
+ */
361
+ limit(limit: number): this;
362
+ /**
363
+ * @description Adds an offset to the query
364
+ * @param offset - The offset to set
365
+ * @returns
366
+ */
367
+ offset(offset: number): this;
368
+ }
369
+
370
+ /**
371
+ * @description Creates a datasource for the selected database type with the provided credentials
372
+ */
373
+ type DataSourceType = "cockroachdb" | "mysql" | "postgres" | "mariadb" | "sqlite" | "mongo";
374
+ interface CommonDataSourceInput {
375
+ readonly type?: DataSourceType;
376
+ readonly logs?: boolean;
377
+ }
378
+ interface MongoDataSourceInput extends CommonDataSourceInput {
379
+ readonly type: "mongo";
380
+ readonly mongoOptions?: MongoConnectionOptions;
381
+ readonly url?: string;
382
+ }
383
+ interface PostgresSqlDataSourceInput extends CommonDataSourceInput {
384
+ readonly type?: "postgres" | "cockroachdb";
385
+ readonly host?: string;
386
+ readonly port?: number;
387
+ readonly username?: string;
388
+ readonly password?: string;
389
+ readonly database?: string;
390
+ readonly driverOptions?: PgClientOptions;
391
+ }
392
+ interface NotNullablePostgresSqlDataSourceInput extends PostgresSqlDataSourceInput {
393
+ readonly type?: "postgres" | "cockroachdb";
394
+ readonly host: string;
395
+ readonly username: string;
396
+ readonly password: string;
397
+ readonly database: string;
398
+ readonly port?: number;
399
+ readonly driverOptions?: PgClientOptions;
400
+ }
401
+ interface MysqlSqlDataSourceInput extends CommonDataSourceInput {
402
+ readonly type?: "mysql" | "mariadb";
403
+ readonly host?: string;
404
+ readonly port?: number;
405
+ readonly username?: string;
406
+ readonly password?: string;
407
+ readonly database?: string;
408
+ readonly driverOptions?: MysqlCreateConnectionOptions;
409
+ }
410
+ interface NotNullableMysqlSqlDataSourceInput extends MysqlSqlDataSourceInput {
411
+ readonly type?: "mysql" | "mariadb";
412
+ readonly host: string;
413
+ readonly username: string;
414
+ readonly password: string;
415
+ readonly database: string;
416
+ readonly port?: number;
417
+ readonly driverOptions?: MysqlCreateConnectionOptions;
418
+ }
419
+ interface SqliteDataSourceInput extends CommonDataSourceInput {
420
+ readonly type?: "sqlite";
421
+ readonly database?: string;
422
+ }
423
+ interface NotNullableSqliteDataSourceInput extends SqliteDataSourceInput {
424
+ readonly type?: "sqlite";
425
+ readonly database: string;
426
+ }
427
+ /**
428
+ * @description By default the connection details can be provided in the .env file, you can still override each prop with your actual connection details in the input
429
+ */
430
+ type DataSourceInput = MysqlSqlDataSourceInput | SqliteDataSourceInput | PostgresSqlDataSourceInput | MongoDataSourceInput;
431
+
432
+ declare abstract class DataSource {
433
+ type: DataSourceType;
434
+ host: string;
435
+ port: number;
436
+ username: string;
437
+ password: string;
438
+ database: string;
439
+ url: string;
440
+ logs: boolean;
441
+ protected constructor(input?: DataSourceInput);
442
+ protected handleCockroachdbSource(input?: PostgresSqlDataSourceInput): void;
443
+ protected handlePostgresSource(input?: PostgresSqlDataSourceInput): void;
444
+ protected handleMysqlSource(input?: MysqlSqlDataSourceInput): void;
445
+ protected handleSqliteSource(input?: SqliteDataSourceInput): void;
446
+ protected handleMongoSource(input?: MongoDataSourceInput): void;
447
+ }
448
+
449
+ type MongoFindOneOptions<T extends Collection> = {
450
+ ignoreHooks?: FetchHooks$1[];
451
+ select?: MongoCollectionKey<T>[];
452
+ where?: ModelKeyOrAny<T>;
453
+ };
454
+ type UnrestrictedMongoFindOneOptions<T extends Collection> = {
455
+ ignoreHooks?: FetchHooks$1[];
456
+ select?: string[];
457
+ where?: ModelKeyOrAny<T>;
458
+ };
459
+ type MongoFindManyOptions<T extends Collection> = MongoFindOneOptions<T> & {
460
+ sort?: ModelKeyOrAnySort<T>;
461
+ limit?: number;
462
+ offset?: number;
463
+ };
464
+ type MongoUnrestrictedFindManyOptions<T extends Collection> = UnrestrictedMongoFindOneOptions<T> & {
465
+ sort?: Record<string, 1 | -1>;
466
+ limit?: number;
467
+ offset?: number;
468
+ };
469
+ declare class CollectionManager<T extends Collection> {
470
+ protected logs: boolean;
471
+ protected collection: typeof Collection;
472
+ protected mongoClient: ReturnType<MongoDataSource["getCurrentConnection"]>;
473
+ protected mongoDataSource: MongoDataSource;
474
+ protected collectionInstance: MongoClientImport["Collection"]["prototype"];
475
+ protected session?: ReturnType<MongoDataSource["startSession"]>;
476
+ constructor(_collection: typeof Collection, mongoDataSource: MongoDataSource, session?: ReturnType<MongoDataSource["startSession"]>, logs?: boolean);
477
+ /**
478
+ * @description Finds all records that match the input
479
+ */
480
+ find(options?: MongoUnrestrictedFindManyOptions<T> | MongoFindManyOptions<T>): Promise<T[]>;
481
+ /**
482
+ * @description Finds the first record that matches the input
483
+ */
484
+ findOne(options: UnrestrictedMongoFindOneOptions<T> | MongoFindOneOptions<T>): Promise<T | null>;
485
+ /**
486
+ * @description Finds the first record that matches the input or throws an error
487
+ */
488
+ findOneOrFail(options: (UnrestrictedMongoFindOneOptions<T> | MongoFindOneOptions<T>) & {
489
+ customError?: Error;
490
+ }): Promise<T>;
491
+ /**
492
+ * @description Starts a query builder chain
493
+ */
494
+ query<T extends Collection>(): MongoQueryBuilder<T>;
495
+ /**
496
+ * @description Finds a record by its primary key
497
+ */
498
+ insert(modelData: ModelKeyOrAny<T>, options?: {
499
+ ignoreHooks?: boolean;
500
+ }): Promise<T>;
501
+ /**
502
+ * @description Creates multiple records
503
+ */
504
+ insertMany(modelData: ModelKeyOrAny<T>[], options?: {
505
+ ignoreHooks?: boolean;
506
+ }): Promise<T[]>;
507
+ /**
508
+ * @description Updates a record
509
+ */
510
+ updateRecord(modelData: T): Promise<T>;
511
+ /**
512
+ * @description Deletes a record
513
+ */
514
+ deleteRecord(model: T): Promise<T>;
515
+ }
516
+
517
+ type MongoClientInstance = InstanceType<MongoClientImport["MongoClient"]>;
518
+ declare class MongoDataSource extends DataSource {
519
+ url: string;
520
+ isConnected: boolean;
521
+ private mongoClient;
522
+ private static instance;
523
+ private constructor();
524
+ /**
525
+ * @description Returns the current connection to the mongo client to execute direct statements using the mongo client from `mongodb` package
526
+ */
527
+ getCurrentConnection(): MongoClientInstance;
528
+ /**
529
+ * @description Connects to the mongo database using the provided url and options
530
+ */
531
+ static connect(url?: string, options?: Partial<MongoConnectionOptions> & {
532
+ logs?: boolean;
533
+ }, cb?: (mongoDataSource: MongoDataSource) => Promise<void> | void): Promise<MongoDataSource>;
534
+ static getInstance(): MongoDataSource;
535
+ /**
536
+ * @description Starts a new session and transaction using the current connection
537
+ */
538
+ startSession(): InstanceType<MongoClientImport["ClientSession"]>;
539
+ /**
540
+ * @description Disconnects from the mongo database using the current connection established by the `connect` method
541
+ */
542
+ static disconnect(): Promise<void>;
543
+ /**
544
+ * @description Disconnects from the mongo database
545
+ */
546
+ disconnect(): Promise<void>;
547
+ /**
548
+ * @description Closes the current connection to the mongo database
549
+ * @alias disconnect
550
+ */
551
+ closeConnection(): Promise<void>;
552
+ /**
553
+ * @description Executes a callback function with the provided connection details
554
+ * @alias disconnect
555
+ */
556
+ static closeConnection(): Promise<void>;
557
+ /**
558
+ * @description Executes a callback function with the provided connection details
559
+ */
560
+ static useConnection(this: typeof MongoDataSource, connectionDetails: {
561
+ url: string;
562
+ options?: MongoConnectionOptions;
563
+ }, cb: (mongoDataSource: MongoDataSource) => Promise<void>): Promise<void>;
564
+ static query(collection: string): MongoQueryBuilder<Collection>;
565
+ query(collection: string): MongoQueryBuilder<Collection>;
566
+ getModelManager<T extends Collection>(model: typeof Collection, mongoDataSource: MongoDataSource, session?: InstanceType<MongoClientImport["ClientSession"]>): CollectionManager<T>;
567
+ }
568
+
569
+ declare class Collection extends Entity {
570
+ $annotations: Record<string, any>;
571
+ /**
572
+ * @description The sql sqlInstance generated by SqlDataSource.connect
573
+ */
574
+ static mongoInstance: MongoDataSource;
575
+ /**
576
+ * @description Used in order to override the table collection name
577
+ */
578
+ static _collection: string;
579
+ /**
580
+ * @description Table name for the collection, default will be the plural snake case of the collection name given that is in PascalCase (es. User -> users)
581
+ * @description If you want to override the table name, you can set the table property in the collection
582
+ * @warning This is a getter you cannot override it, if you want to override it use the table property
583
+ */
584
+ static get collection(): string;
585
+ /**
586
+ * @description The id of the record, this will be used to interact with the _id field in the database, every model has an id by default
587
+ */
588
+ id: string;
589
+ /**
590
+ * @description Gets the main query builder for the model
591
+ * @param options - The options to get the model manager
592
+ * @returns {MongoQueryBuilder<T>}
593
+ */
594
+ static query<T extends Collection>(this: new () => T | typeof Collection, options?: BaseModelMethodOptions$1): MongoQueryBuilder<T>;
595
+ /**
596
+ * @description Finds records in the collection, to use for simple queries
597
+ * @param this
598
+ * @param options
599
+ */
600
+ static find<T extends Collection>(this: new () => T | typeof Collection, options?: MongoFindManyOptions<T> & BaseModelMethodOptions$1): Promise<T[]>;
601
+ static find<T extends Collection>(this: new () => T | typeof Collection, options?: MongoUnrestrictedFindManyOptions<T> & BaseModelMethodOptions$1): Promise<T[]>;
602
+ /**
603
+ * @description Finds a record in the collection, to use for simple queries
604
+ * @param this
605
+ * @param options
606
+ */
607
+ static findOne<T extends Collection>(this: new () => T | typeof Collection, options: MongoFindOneOptions<T> & BaseModelMethodOptions$1): Promise<T | null>;
608
+ static findOne<T extends Collection>(this: new () => T | typeof Collection, options: UnrestrictedMongoFindOneOptions<T> & BaseModelMethodOptions$1): Promise<T | null>;
609
+ /**
610
+ * @description Finds a record in the collection, to use for simple queries
611
+ * @param this
612
+ * @param options
613
+ * @throws {Error} - If the record could not be found
614
+ * @returns {Promise<T>}
615
+ */
616
+ static findOneOrFail<T extends Collection>(this: new () => T | typeof Collection, options: MongoFindOneOptions<T> & BaseModelMethodOptions$1): Promise<T>;
617
+ static findOneOrFail<T extends Collection>(this: new () => T | typeof Collection, options: UnrestrictedMongoFindOneOptions<T> & BaseModelMethodOptions$1): Promise<T>;
618
+ /**
619
+ * @description Saves a new record to the collection
620
+ * @param model
621
+ * @param {Model} modelData - The data to be saved
622
+ * @param {BaseModelMethodOptions} options - The options to get the model manager
623
+ * @returns {Promise<T>}
624
+ */
625
+ static insert<T extends Collection>(this: new () => T | typeof Collection, modelData: ModelKeyOrAny<T>, options?: BaseModelMethodOptions$1): Promise<T>;
626
+ /**
627
+ * @description Saves multiple records to the collection
628
+ * @param {Model} modelData - The data to be fetched
629
+ * @param {BaseModelMethodOptions} options - The options to get the model manager
630
+ * @returns {Promise<T>}
631
+ */
632
+ static insertMany<T extends Collection>(this: new () => T | typeof Collection, modelData: ModelKeyOrAny<T>[], options?: BaseModelMethodOptions$1): Promise<T[]>;
633
+ /**
634
+ * @description Updates a record in the collection using it's id
635
+ * @param {Model} modelData - The data to be updated
636
+ * @param {BaseModelMethodOptions} options - The options to get the model manager
637
+ * @returns {Promise<T>} - The updated record refreshed from the database
638
+ */
639
+ static updateRecord<T extends Collection>(this: new () => T | typeof Collection, model: T, options?: BaseModelMethodOptions$1): Promise<T>;
640
+ /**
641
+ * @description Deletes a record in the collection using it's id
642
+ * @param {BaseModelMethodOptions} options - The options to get the model manager
643
+ * @returns {Promise<void>}
644
+ * @throws {Error} - If the record could not be deleted
645
+ */
646
+ static deleteRecord<T extends Collection>(this: new () => T | typeof Collection, model: T, options?: BaseModelMethodOptions$1): Promise<void>;
647
+ /**
648
+ * @description Gets the main connection from the mongoInstance
649
+ */
650
+ private static establishConnection;
651
+ /**
652
+ * @description Gives the correct model manager with the correct connection based on the options provided
653
+ * @param this
654
+ * @param options - The options to get the model manager
655
+ * @returns
656
+ */
657
+ private static dispatchModelManager;
658
+ /**
659
+ * @description Adds a beforeFetch clause to the model, adding the ability to modify the query before fetching the data
660
+ * @param queryBuilder
661
+ */
662
+ static beforeFetch(queryBuilder: MongoQueryBuilder<any>): void;
663
+ /**
664
+ * @description Adds a beforeInsert clause to the model, adding the ability to modify the data after fetching the data
665
+ * @param data
666
+ * @returns {T}
667
+ */
668
+ static beforeInsert(data: any): void;
669
+ /**
670
+ * @description Adds a beforeUpdate clause to the model, adding the ability to modify the query before updating the data
671
+ * @param data
672
+ */
673
+ static beforeUpdate(queryBuilder: MongoQueryBuilder<any>): void;
674
+ /**
675
+ * @description Adds a beforeDelete clause to the model, adding the ability to modify the query before deleting the data
676
+ * @param data
677
+ */
678
+ static beforeDelete(queryBuilder: MongoQueryBuilder<any>): void;
679
+ /**
680
+ * @description Adds a property to the model, adding the ability to modify the data after fetching the data
681
+ * @javascript
682
+ */
683
+ static property(propertyName: string): void;
684
+ /**
685
+ * @description Adds a afterFetch clause to the model, adding the ability to modify the data after fetching the data
686
+ * @param data
687
+ * @returns {T}
688
+ */
689
+ static afterFetch(data: any[]): Promise<Collection[]>;
690
+ }
691
+
692
+ /**
693
+ * @description Defines a property that will be used in the model
694
+ */
695
+ declare function property(): PropertyDecorator;
696
+ /**
697
+ * @description Returns the properties of the model, properties must be decorated with the property decorator
698
+ */
699
+ declare function getCollectionProperties(target: typeof Collection): string[];
700
+
701
+ type CommonConstraintOptions = {
702
+ constraintName?: string;
703
+ };
704
+ type OnUpdateOrDelete = "cascade" | "restrict" | "set null" | "no action";
705
+ type PrimaryKeyOptions = CommonConstraintOptions;
706
+ type ForeignKeyOptions = CommonConstraintOptions & {
707
+ onDelete?: OnUpdateOrDelete;
708
+ onUpdate?: OnUpdateOrDelete;
709
+ };
710
+ type CreateTableContext = "alter_table" | "create_table";
711
+
712
+ type OpenApiModelType = {
713
+ type: "object";
714
+ properties: Record<string, OpenApiModelPropertyType>;
715
+ required?: string[];
716
+ };
717
+ type OpenApiModelPropertyType = {
718
+ type: string;
719
+ items?: OpenApiModelType;
720
+ enum?: string[];
721
+ format?: string;
722
+ description?: string;
723
+ example?: any;
724
+ default?: any;
725
+ nullable?: boolean;
726
+ };
727
+
728
+ declare abstract class QueryNode {
729
+ /**
730
+ * Sql keyword to use for the query e.g. "select"
731
+ */
732
+ keyword: string;
733
+ /**
734
+ * The current parameter index to use for the query
735
+ */
736
+ currParamIndex: number;
737
+ /**
738
+ * Whether the query node is a raw value and should not be parsed by the interpreter
739
+ */
740
+ isRawValue: boolean;
741
+ /**
742
+ * Whether the keyword can be seen multiple times in the query, e.g. "join" can be seen multiple times in a query
743
+ */
744
+ abstract canKeywordBeSeenMultipleTimes: boolean;
745
+ /**
746
+ * The string to use to chain the keyword with the next keyword
747
+ */
748
+ abstract chainsWith: string;
749
+ /**
750
+ * The folder to use for the query node, e.g. "select" is in the "select" folder inside the interpreter map
751
+ */
752
+ abstract folder: string;
753
+ /**
754
+ * The file to use for the query node, e.g. "select" is in the "select" file inside the interpreter map
755
+ */
756
+ abstract file: string;
757
+ constructor(keyword: string, isRawValue?: boolean);
758
+ }
759
+
760
+ declare class RawNode extends QueryNode {
761
+ rawValue: string;
762
+ canKeywordBeSeenMultipleTimes: boolean;
763
+ chainsWith: string;
764
+ currParamIndex: number;
765
+ isRawValue: boolean;
766
+ folder: string;
767
+ file: string;
768
+ constructor(value: string);
769
+ }
770
+
771
+ type ConstraintType = "primary_key" | "foreign_key" | "unique" | "not_null" | "null" | "default";
772
+ declare class ConstraintNode extends QueryNode {
773
+ constraintType: ConstraintType;
774
+ columns?: (string | (() => string))[];
775
+ references?: {
776
+ table: string;
777
+ columns: (string | (() => string))[];
778
+ };
779
+ constraintName?: string;
780
+ onDelete?: "cascade" | "restrict" | "set null" | "no action";
781
+ onUpdate?: "cascade" | "restrict" | "set null" | "no action";
782
+ defaultValue?: string;
783
+ checkExpression?: string;
784
+ chainsWith: string;
785
+ canKeywordBeSeenMultipleTimes: boolean;
786
+ folder: string;
787
+ file: string;
788
+ constructor(constraintType: ConstraintType, args?: {
789
+ columns?: string[];
790
+ references?: {
791
+ table: string;
792
+ columns: string[];
793
+ };
794
+ constraintName?: string;
795
+ onDelete?: "cascade" | "restrict" | "set null" | "no action";
796
+ onUpdate?: "cascade" | "restrict" | "set null" | "no action";
797
+ defaultValue?: string;
798
+ checkExpression?: string;
799
+ }, isRawValue?: boolean);
800
+ }
801
+
802
+ declare class ColumnTypeNode extends QueryNode {
803
+ column: string | (() => string);
804
+ dataType: string;
805
+ length?: number;
806
+ precision?: number;
807
+ scale?: number;
808
+ enumValues?: readonly string[];
809
+ autoIncrement?: boolean;
810
+ withTimezone?: boolean;
811
+ chainsWith: string;
812
+ canKeywordBeSeenMultipleTimes: boolean;
813
+ folder: string;
814
+ file: string;
815
+ isRawValue: boolean;
816
+ constructor(column: string, dataType: string, opts?: {
817
+ length?: number;
818
+ precision?: number;
819
+ scale?: number;
820
+ enumValues?: readonly string[];
821
+ withTimezone?: boolean;
822
+ autoIncrement?: boolean;
823
+ isRawValue?: boolean;
824
+ });
825
+ }
826
+
827
+ type LockType = "for_update" | "for_share" | "for_no_key_update" | "for_key_share";
828
+ declare class LockNode extends QueryNode {
829
+ lockType: LockType;
830
+ skipLocked: boolean;
831
+ noWait: boolean;
832
+ chainsWith: string;
833
+ canKeywordBeSeenMultipleTimes: boolean;
834
+ folder: string;
835
+ file: string;
836
+ constructor(lockType: LockType, skipLocked?: boolean, noWait?: boolean);
837
+ }
838
+
839
+ declare class UnionNode extends QueryNode {
840
+ query: QueryNode | QueryNode[] | string;
841
+ isAll: boolean;
842
+ chainsWith: string;
843
+ canKeywordBeSeenMultipleTimes: boolean;
844
+ folder: string;
845
+ file: string;
846
+ constructor(query: QueryNode | QueryNode[] | string, isAll?: boolean);
847
+ }
848
+
849
+ declare class WithNode extends QueryNode {
850
+ alias: string;
851
+ body: QueryNode | QueryNode[];
852
+ clause: string;
853
+ chainsWith: string;
854
+ canKeywordBeSeenMultipleTimes: boolean;
855
+ folder: string;
856
+ file: string;
857
+ constructor(clause: string, alias: string, body: QueryNode | QueryNode[]);
858
+ }
859
+
860
+ declare abstract class BaseBuilder {
861
+ protected nodes: QueryNode[];
862
+ constructor(nodes: QueryNode[]);
863
+ getNodes(): QueryNode[];
864
+ }
865
+
866
+ declare class ConstraintBuilder extends BaseBuilder {
867
+ private readonly columnNode;
868
+ private readonly tableName?;
869
+ private namedConstraints;
870
+ private context;
871
+ private sqlType;
872
+ constructor(sqlType: SqlDataSourceType, nodes: QueryNode[], columnNode: ColumnTypeNode, tableName?: string, namedConstraints?: QueryNode[], context?: CreateTableContext);
873
+ /**
874
+ * @description Adds a primary key constraint to the column, if no constraint name is provided, it will be generated using the standard pattern: pk_${table}_${column}
875
+ * @param options is the options for the primary key constraint
876
+ */
877
+ primaryKey(options?: PrimaryKeyOptions): this;
878
+ /**
879
+ * @description Adds a foreign key constraint to the column, if no constraint name is provided, it will be generated using the standard pattern: fk_${table}_${leftColumn}_${rightColumn}
880
+ * @param references is the table and column name to reference, e.g. "users.id"
881
+ * @param options is the options for the foreign key constraint
882
+ */
883
+ foreignKey(references: `${string}.${string}`, options?: ForeignKeyOptions): this;
884
+ /**
885
+ * @description Sets the column to auto increment
886
+ */
887
+ increment(): this;
888
+ /**
889
+ * @description Sets the column to not nullable
890
+ */
891
+ notNullable(): this;
892
+ /**
893
+ * @description Sets the column to nullable, by default it already is nullable, this method is only used for alter table
894
+ */
895
+ nullable(): this;
896
+ /**
897
+ * @description Sets the default value for the column
898
+ * @param value is the default value for the column
899
+ */
900
+ default(value: string | number | boolean | null): this;
901
+ /**
902
+ * @description Sets the column to unique
903
+ * @param options is the options for the unique constraint
904
+ */
905
+ unique(options?: CommonConstraintOptions): this;
906
+ /**
907
+ * @description Sets the column to be after another column
908
+ * @param columnName is the name of the column to be after
909
+ * @mysql only
910
+ */
911
+ after(columnName: string): this;
912
+ private handleSqliteAutoIncrement;
913
+ }
914
+
915
+ declare class CreateTableBuilder extends BaseBuilder {
916
+ private tableName?;
917
+ private namedConstraints;
918
+ private context;
919
+ private sqlType;
920
+ constructor(sqlType: SqlDataSourceType, nodes: QueryNode[], tableName?: string, context?: "alter_table" | "create_table");
921
+ private build;
922
+ /**
923
+ * Fixed-length character string
924
+ * @mysql Supported as CHAR(length)
925
+ * @postgres Supported as CHAR(length)
926
+ * @sqlite Supported as TEXT (length ignored)
927
+ */
928
+ char(name: string, length?: number): ConstraintBuilder;
929
+ /**
930
+ * Variable-length character string
931
+ * @mysql Supported as VARCHAR(length)
932
+ * @postgres Supported as VARCHAR(length)
933
+ * @sqlite Supported as TEXT (length ignored)
934
+ */
935
+ varchar(name: string, length?: number): ConstraintBuilder;
936
+ /**
937
+ * @alias varchar
938
+ */
939
+ string(name: string, length?: number): ConstraintBuilder;
940
+ /**
941
+ * Text types with various sizes
942
+ * @mysql Supported as TEXT, MEDIUMTEXT, LONGTEXT, TINYTEXT
943
+ * @postgres All mapped to TEXT
944
+ * @sqlite All mapped to TEXT
945
+ */
946
+ text(name: string, type?: "longtext" | "mediumtext" | "tinytext"): ConstraintBuilder;
947
+ /**
948
+ * @mysql LONGTEXT
949
+ * @postgres TEXT
950
+ * @sqlite TEXT
951
+ */
952
+ longtext(name: string): ConstraintBuilder;
953
+ /**
954
+ * @mysql MEDIUMTEXT
955
+ * @postgres TEXT
956
+ * @sqlite TEXT
957
+ */
958
+ mediumtext(name: string): ConstraintBuilder;
959
+ /**
960
+ * @mysql TINYTEXT
961
+ * @postgres TEXT
962
+ * @sqlite TEXT
963
+ */
964
+ tinytext(name: string): ConstraintBuilder;
965
+ /**
966
+ * UUID identifier
967
+ * @mysql VARCHAR(36)
968
+ * @postgres UUID (native type)
969
+ * @sqlite VARCHAR(36)
970
+ */
971
+ uuid(name: string): ConstraintBuilder;
972
+ /**
973
+ * ULID (Universally Unique Lexicographically Sortable Identifier)
974
+ * @mysql VARCHAR(26)
975
+ * @postgres VARCHAR(26)
976
+ * @sqlite VARCHAR(26)
977
+ */
978
+ ulid(name: string): ConstraintBuilder;
979
+ /**
980
+ * Integer type
981
+ * @mysql INT (with optional auto_increment)
982
+ * @postgres INTEGER (with optional SERIAL for auto_increment)
983
+ * @sqlite INTEGER (with optional autoincrement)
984
+ */
985
+ integer(name: string, length?: number): ConstraintBuilder;
986
+ /**
987
+ * Small integer type
988
+ * @mysql TINYINT
989
+ * @postgres SMALLINT
990
+ * @sqlite INTEGER
991
+ */
992
+ tinyint(name: string, length?: number): ConstraintBuilder;
993
+ /**
994
+ * Small integer type
995
+ * @mysql SMALLINT
996
+ * @postgres SMALLINT
997
+ * @sqlite INTEGER
998
+ */
999
+ smallint(name: string, length?: number): ConstraintBuilder;
1000
+ /**
1001
+ * Medium integer type
1002
+ * @mysql MEDIUMINT
1003
+ * @postgres INTEGER
1004
+ * @sqlite INTEGER
1005
+ */
1006
+ mediumint(name: string, length?: number): ConstraintBuilder;
1007
+ /**
1008
+ * Large integer type
1009
+ * @mysql BIGINT (with optional auto_increment)
1010
+ * @postgres BIGINT (with optional BIGSERIAL for auto_increment)
1011
+ * @sqlite INTEGER
1012
+ */
1013
+ biginteger(name: string, length?: number): ConstraintBuilder;
1014
+ /**
1015
+ * @alias biginteger
1016
+ */
1017
+ bigint(name: string, length?: number): ConstraintBuilder;
1018
+ /**
1019
+ * Single precision floating point
1020
+ * @mysql FLOAT
1021
+ * @postgres REAL
1022
+ * @sqlite REAL
1023
+ */
1024
+ float(name: string, precision?: number): ConstraintBuilder;
1025
+ /**
1026
+ * Double precision floating point
1027
+ * @mysql DOUBLE
1028
+ * @postgres DOUBLE PRECISION
1029
+ * @sqlite REAL
1030
+ */
1031
+ double(name: string, precision?: number): ConstraintBuilder;
1032
+ /**
1033
+ * Real number type
1034
+ * @mysql DOUBLE (alias)
1035
+ * @postgres REAL
1036
+ * @sqlite REAL
1037
+ */
1038
+ real(name: string, precision?: number): ConstraintBuilder;
1039
+ /**
1040
+ * Exact decimal number
1041
+ * @mysql DECIMAL(precision, scale)
1042
+ * @postgres NUMERIC(precision, scale)
1043
+ * @sqlite NUMERIC(precision, scale)
1044
+ */
1045
+ decimal(name: string, precision?: number, scale?: number): ConstraintBuilder;
1046
+ /**
1047
+ * Exact numeric type (alias for decimal)
1048
+ * @mysql NUMERIC(precision, scale)
1049
+ * @postgres NUMERIC(precision, scale)
1050
+ * @sqlite NUMERIC(precision, scale)
1051
+ */
1052
+ numeric(name: string, precision?: number, scale?: number): ConstraintBuilder;
1053
+ /**
1054
+ * @description Short for integer.increment
1055
+ * @mysql INTEGER (with auto_increment)
1056
+ * @postgres INTEGER (with SERIAL for auto_increment)
1057
+ * @sqlite INTEGER (with autoincrement)
1058
+ */
1059
+ increment(name: string, length?: number): Omit<ConstraintBuilder, "increment">;
1060
+ /**
1061
+ * @description Short for biginteger.increment
1062
+ * @mysql BIGINT (with auto_increment)
1063
+ * @postgres BIGINT (with BIGSERIAL for auto_increment)
1064
+ * @sqlite INTEGER
1065
+ */
1066
+ bigIncrement(name: string, length?: number): Omit<ConstraintBuilder, "increment">;
1067
+ /**
1068
+ * Date type
1069
+ * @mysql DATE
1070
+ * @postgres DATE
1071
+ * @sqlite TEXT
1072
+ */
1073
+ date(name: string, precision?: number): ConstraintBuilder;
1074
+ /**
1075
+ * Time type
1076
+ * @mysql TIME(precision)
1077
+ * @postgres TIME(precision)
1078
+ * @sqlite TEXT
1079
+ */
1080
+ time(name: string, precision?: number): ConstraintBuilder;
1081
+ /**
1082
+ * Year type
1083
+ * @mysql YEAR
1084
+ * @postgres SMALLINT
1085
+ * @sqlite TEXT
1086
+ */
1087
+ year(name: string): ConstraintBuilder;
1088
+ /**
1089
+ * Date and time type
1090
+ * @mysql DATETIME(precision)
1091
+ * @postgres TIMESTAMP(precision) WITHOUT TIME ZONE
1092
+ * @sqlite TEXT
1093
+ */
1094
+ datetime(name: string, options?: {
1095
+ withTimezone?: boolean;
1096
+ precision?: number;
1097
+ }): ConstraintBuilder;
1098
+ /**
1099
+ * Timestamp type
1100
+ * @mysql TIMESTAMP(precision)
1101
+ * @postgres TIMESTAMP(precision) WITH/WITHOUT TIME ZONE
1102
+ * @sqlite TEXT
1103
+ */
1104
+ timestamp(name: string, options?: {
1105
+ withTimezone?: boolean;
1106
+ precision?: number;
1107
+ }): ConstraintBuilder;
1108
+ /**
1109
+ * Boolean type
1110
+ * @mysql BOOLEAN
1111
+ * @postgres BOOLEAN
1112
+ * @sqlite INTEGER
1113
+ */
1114
+ boolean(name: string): ConstraintBuilder;
1115
+ /**
1116
+ * Fixed-length binary data
1117
+ * @mysql BINARY(length)
1118
+ * @postgres BYTEA
1119
+ * @sqlite BLOB
1120
+ */
1121
+ binary(name: string): ConstraintBuilder;
1122
+ /**
1123
+ * Variable-length binary data
1124
+ * @mysql VARBINARY(length)
1125
+ * @postgres BYTEA
1126
+ * @sqlite BLOB
1127
+ */
1128
+ varbinary(name: string, length?: number): ConstraintBuilder;
1129
+ /**
1130
+ * Binary large object
1131
+ * @mysql BLOB
1132
+ * @postgres BYTEA
1133
+ * @sqlite BLOB
1134
+ */
1135
+ blob(name: string): ConstraintBuilder;
1136
+ /**
1137
+ * Small binary large object
1138
+ * @mysql TINYBLOB
1139
+ * @postgres BYTEA
1140
+ * @sqlite BLOB
1141
+ */
1142
+ tinyblob(name: string): ConstraintBuilder;
1143
+ /**
1144
+ * Medium binary large object
1145
+ * @mysql MEDIUMBLOB
1146
+ * @postgres BYTEA
1147
+ * @sqlite BLOB
1148
+ */
1149
+ mediumblob(name: string): ConstraintBuilder;
1150
+ /**
1151
+ * Large binary large object
1152
+ * @mysql LONGBLOB
1153
+ * @postgres BYTEA
1154
+ * @sqlite BLOB
1155
+ */
1156
+ longblob(name: string): ConstraintBuilder;
1157
+ /**
1158
+ * JSON data type
1159
+ * @mysql JSON (MySQL 5.7+)
1160
+ * @postgres JSON
1161
+ * @sqlite TEXT (not supported, stored as text)
1162
+ */
1163
+ json(name: string): ConstraintBuilder;
1164
+ /**
1165
+ * Binary JSON data type
1166
+ * @mysql Not supported (falls back to JSON)
1167
+ * @postgres JSONB
1168
+ * @sqlite TEXT (not supported, stored as text)
1169
+ */
1170
+ jsonb(name: string): ConstraintBuilder;
1171
+ /**
1172
+ * Enumeration type
1173
+ * @mysql ENUM(values)
1174
+ * @postgres TEXT with CHECK constraint
1175
+ * @sqlite TEXT
1176
+ */
1177
+ enum(name: string, values: readonly string[]): ConstraintBuilder;
1178
+ /**
1179
+ * Custom column type
1180
+ * @mysql Custom type as specified
1181
+ * @postgres Custom type as specified
1182
+ * @sqlite Custom type as specified
1183
+ */
1184
+ custom(name: string, type: string, length?: number): ConstraintBuilder;
1185
+ /**
1186
+ * Raw column type
1187
+ * @mysql Custom type as specified
1188
+ * @postgres Custom type as specified
1189
+ * @sqlite Custom type as specified
1190
+ * @example
1191
+ * ```ts
1192
+ * qb.rawColumn("name varchar(255)");
1193
+ * ```
1194
+ */
1195
+ rawColumn(raw: string): ConstraintBuilder;
1196
+ getNamedConstraints(): QueryNode[];
1197
+ }
1198
+
1199
+ declare class AlterTableBuilder extends BaseBuilder {
1200
+ private table;
1201
+ private sqlType;
1202
+ constructor(table: string, nodes: QueryNode[], sqlType: SqlDataSourceType);
1203
+ /**
1204
+ * @description Adds a column to the table
1205
+ * @param cb is the callback that will be used to build the column
1206
+ */
1207
+ addColumn(cb: (col: CreateTableBuilder) => ConstraintBuilder): void;
1208
+ /**
1209
+ * @description Alters a column, can generate multiple sql statements depending on the constraints
1210
+ * @throws HysteriaError if sqlite database
1211
+ */
1212
+ alterColumn(columnBuilder: (col: CreateTableBuilder) => ConstraintBuilder): void;
1213
+ /**
1214
+ * @description Drops a column
1215
+ */
1216
+ dropColumn(name: string): void;
1217
+ /**
1218
+ * @description Renames a column
1219
+ */
1220
+ renameColumn(oldName: string, newName: string): void;
1221
+ /**
1222
+ * @description Drops a default value from a column
1223
+ * @sqlite not supported and will throw error
1224
+ */
1225
+ dropDefault(columnName: string): void;
1226
+ /**
1227
+ * @description Adds a primary key to a column
1228
+ * @sqlite not supported and will throw error
1229
+ * @private Used internally by alterColumn
1230
+ */
1231
+ private addPrimaryKey;
1232
+ /**
1233
+ * @description Raw non type safe way builder to add a constraint
1234
+ * @sqlite not supported and will throw error
1235
+ */
1236
+ addConstraint(...options: ConstructorParameters<typeof ConstraintNode>): void;
1237
+ /**
1238
+ * @description Adds a foreign key constraint to a column
1239
+ * @sqlite not supported and will throw error
1240
+ * @private Used internally by alterColumn
1241
+ */
1242
+ private addForeignKey;
1243
+ /**
1244
+ * @description Adds a unique constraint to a column
1245
+ * @description By default generates a constraint name using standard pattern: uq_${table}_${column}
1246
+ * @sqlite not supported and will throw error
1247
+ * @private Used internally by alterColumn
1248
+ */
1249
+ private unique;
1250
+ /**
1251
+ * @description Sets a default value for a column
1252
+ * @sqlite not supported and will throw error
1253
+ * @private Used internally by alterColumn
1254
+ */
1255
+ private setDefault;
1256
+ /**
1257
+ * @description Drops a foreign key by column name and referenced column, generates constraint name using standard pattern: fk_${table}_${leftColumn}_${rightColumn}
1258
+ * @description If a custom constraint name was used to generate the foreign key, use `dropConstraint` instead
1259
+ * @param leftColumn is the current model column name (e.g. userId)
1260
+ * @param rightColumn is the referenced model column name (e.g. id)
1261
+ * @sqlite not supported and will throw error
1262
+ */
1263
+ dropForeignKey(leftColumn: string, rightColumn: string): void;
1264
+ /**
1265
+ * @description Drops a unique constraint by column name, generates constraint name using standard pattern: uq_${table}_${column}
1266
+ * @description If a custom constraint name was used to generate the unique constraint, use `dropConstraint` instead
1267
+ * @param columnName is the current model column name (e.g. userId)
1268
+ * @sqlite not supported and will throw error
1269
+ * @cockroachdb not supported
1270
+ */
1271
+ dropUnique(columnName: string, options?: CommonConstraintOptions): void;
1272
+ /**
1273
+ * @description Drops a constraint by constraint name
1274
+ * @sqlite not supported and will throw error
1275
+ */
1276
+ dropConstraint(constraintName: string): void;
1277
+ /**
1278
+ * @description Drops the primary key constraint
1279
+ * @postgres not supported, use `dropConstraint` instead with the pk constraint name
1280
+ * @sqlite not supported and will throw error
1281
+ * @throws HysteriaError if postgres and table is not provided
1282
+ */
1283
+ dropPrimaryKey(table?: string): void;
1284
+ }
1285
+
1286
+ declare class Schema {
1287
+ queryStatements: string[];
1288
+ sqlType: SqlDataSourceType;
1289
+ constructor(sqlType?: SqlDataSourceType);
1290
+ /**
1291
+ * @description Add raw query to the migration
1292
+ */
1293
+ rawQuery(query: string): void;
1294
+ /**
1295
+ * @description Runs the sql in the given file, throws error if file does not exist or is not .sql or .txt
1296
+ * @description File is splitted by semicolons and each statement is executed separately and in order
1297
+ */
1298
+ runFile(filePath: string): void;
1299
+ /**
1300
+ * @description Create table constructor
1301
+ */
1302
+ createTable(table: string, cb: (table: CreateTableBuilder) => void, options?: {
1303
+ ifNotExists?: boolean;
1304
+ }): void;
1305
+ /**
1306
+ * @description Alter table constructor
1307
+ */
1308
+ alterTable(table: string, cb: (t: AlterTableBuilder) => void): void;
1309
+ /**
1310
+ * @description Drop table in the database
1311
+ */
1312
+ dropTable(table: string, ifExists?: boolean): void;
1313
+ /**
1314
+ * @description Rename table in the database
1315
+ */
1316
+ renameTable(oldTable: string, newTable: string): void;
1317
+ /**
1318
+ * @description Truncate table
1319
+ */
1320
+ truncateTable(table: string): void;
1321
+ /**
1322
+ * @description Create index on table
1323
+ */
1324
+ createIndex(table: string, columns: string[] | string, options: CommonConstraintOptions): void;
1325
+ /**
1326
+ * @description Drop index on table
1327
+ * @mysql requires table name for index drop
1328
+ */
1329
+ dropIndex(indexName: string, table?: string): void;
1330
+ /**
1331
+ * @description Adds a primary key to a table
1332
+ */
1333
+ addPrimaryKey(table: string, columns: string[]): void;
1334
+ /**
1335
+ * @description Adds a UNIQUE constraint to a table
1336
+ */
1337
+ addUnique(table: string, columns: string[] | string, options?: CommonConstraintOptions): void;
1338
+ /**
1339
+ * @description Drops a foreign key from a table, uses a standard constraint name pattern: fk_${table}_${leftColumn}_${rightColumn}
1340
+ * @description If a custom constraint name was used to generate the foreign key, use `dropConstraint` instead
1341
+ */
1342
+ dropForeignKey(table: string, leftColumn: string, rightColumn: string): void;
1343
+ /**
1344
+ * @description Drops a UNIQUE constraint from a table
1345
+ * @description If no constraintName is provided, it computes the default name using columns
1346
+ */
1347
+ dropUnique(table: string, columnsOrConstraintName: string | string[], options?: CommonConstraintOptions): void;
1348
+ /**
1349
+ * @description Drops a primary key from a table
1350
+ */
1351
+ dropPrimaryKey(table: string): void;
1352
+ /**
1353
+ * @description Adds a foreign key to a table
1354
+ */
1355
+ addConstraint(table: string, ...options: ConstructorParameters<typeof ConstraintNode>): void;
1356
+ /**
1357
+ * @description Drops a constraint from a table
1358
+ */
1359
+ dropConstraint(table: string, constraintName: string): void;
1360
+ private generateAstInstance;
1361
+ }
1362
+
1363
+ declare class InterpreterUtils {
1364
+ private readonly model;
1365
+ private readonly modelColumnsMap;
1366
+ constructor(model: typeof Model);
1367
+ formatStringColumn(dbType: SqlDataSourceType, column: string): string;
1368
+ formatStringTable(dbType: SqlDataSourceType, table: string): string;
1369
+ prepareColumns(columns: string[], values: any[], mode?: "insert" | "update"): {
1370
+ columns: string[];
1371
+ values: any[];
1372
+ };
1373
+ }
1374
+
1375
+ type BaseValues$1 = string | number | boolean | undefined | null | RawNode;
1376
+ type BinaryOperatorType$1 = "=" | "!=" | "<>" | ">" | "<" | ">=" | "<=" | "is" | "is not" | "like" | "not like" | "is null" | "is not null" | "ilike" | "in" | "not in" | "between" | "not between" | "regexp" | "not regexp" | "not ilike";
1377
+ declare class WhereNode extends QueryNode {
1378
+ column: string;
1379
+ isNegated: boolean;
1380
+ operator: BinaryOperatorType$1;
1381
+ value: BaseValues$1 | BaseValues$1[];
1382
+ chainsWith: "and" | "or";
1383
+ canKeywordBeSeenMultipleTimes: boolean;
1384
+ folder: string;
1385
+ file: string;
1386
+ constructor(column: string, chainsWith: "and" | "or", isNegated: boolean | undefined, operator: BinaryOperatorType$1, value: BaseValues$1 | BaseValues$1[], isRawValue?: boolean);
1387
+ }
1388
+
1389
+ type SubqueryOperatorType = "in" | "not in" | "exists" | "not exists" | "between" | "not between" | ">" | "<" | ">=" | "<=";
1390
+ declare class WhereSubqueryNode extends QueryNode {
1391
+ column: string;
1392
+ operator: SubqueryOperatorType;
1393
+ subquery: string | QueryNode | QueryNode[];
1394
+ chainsWith: "and" | "or";
1395
+ canKeywordBeSeenMultipleTimes: boolean;
1396
+ folder: string;
1397
+ file: string;
1398
+ constructor(column: string, operator: SubqueryOperatorType, subquery: string | QueryNode | QueryNode[], chainsWith?: "and" | "or");
1399
+ }
1400
+
1401
+ declare class WhereGroupNode extends QueryNode {
1402
+ nodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[];
1403
+ chainsWith: "and" | "or";
1404
+ canKeywordBeSeenMultipleTimes: boolean;
1405
+ folder: string;
1406
+ file: string;
1407
+ constructor(nodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[], chainsWith?: "and" | "or");
1408
+ }
1409
+
1410
+ /**
1411
+ * @description Options for the relation
1412
+ * @property {string} softDeleteColumn - The column name for the soft delete column, if set, the relation will only return rows that have not been soft deleted
1413
+ * @property {string} softDeleteType - The type of the soft delete column
1414
+ */
1415
+ declare enum RelationEnum {
1416
+ hasOne = "hasOne",// One to One without foreign key
1417
+ belongsTo = "belongsTo",// One to One with foreign key
1418
+ hasMany = "hasMany",
1419
+ manyToMany = "manyToMany"
1420
+ }
1421
+ /**
1422
+ * Main Relation Class
1423
+ */
1424
+ declare abstract class Relation {
1425
+ abstract type: RelationEnum;
1426
+ model: typeof Model;
1427
+ columnName: string;
1428
+ foreignKey?: string;
1429
+ relatedModel: string;
1430
+ protected constructor(model: typeof Model, columnName: string);
1431
+ }
1432
+
1433
+ declare class SqlModelManagerUtils<T extends Model> {
1434
+ protected dbType: SqlDataSourceType;
1435
+ protected sqlDataSource: SqlDataSource;
1436
+ protected modelRelations: Relation[];
1437
+ protected modelRelationsMap: Map<string, Relation>;
1438
+ constructor(typeofModel: typeof Model, dbType: SqlDataSourceType, sqlDataSource: SqlDataSource);
1439
+ getRelationFromModel(relation: ModelRelation<T>): Relation;
1440
+ }
1441
+
1442
+ type PaginationMetadata = {
1443
+ perPage: number;
1444
+ currentPage: number;
1445
+ firstPage: number;
1446
+ isEmpty: boolean;
1447
+ total: number;
1448
+ lastPage: number;
1449
+ hasMorePages: boolean;
1450
+ hasPages: boolean;
1451
+ };
1452
+ type CursorPaginationMetadata = {
1453
+ perPage: number;
1454
+ firstPage: number;
1455
+ isEmpty: boolean;
1456
+ total: number;
1457
+ };
1458
+ type PaginatedData<T extends Model, A extends object = {}, R extends object = {}> = {
1459
+ paginationMetadata: PaginationMetadata;
1460
+ data: AnnotatedModel<T, A, R>[];
1461
+ };
1462
+ type CursorPaginatedData<T extends Model, A extends object = {}, R extends object = {}> = {
1463
+ paginationMetadata: CursorPaginationMetadata;
1464
+ data: AnnotatedModel<T, A, R>[];
1465
+ };
1466
+
1467
+ type DeleteOptions = {
1468
+ ignoreBeforeDeleteHook?: boolean;
1469
+ };
1470
+ type SoftDeleteOptions<T> = {
1471
+ column?: MongoCollectionKey<T>;
1472
+ value?: string | number | boolean;
1473
+ ignoreBeforeDeleteHook?: boolean;
1474
+ };
1475
+
1476
+ type BaseValues = string | number | boolean | null;
1477
+ type BinaryOperatorType = "=" | "!=" | "<>" | ">" | "<" | ">=" | "<=" | "like" | "ilike" | "in";
1478
+ declare class HavingNode extends QueryNode {
1479
+ column: string;
1480
+ isNegated: boolean;
1481
+ operator: BinaryOperatorType;
1482
+ value: BaseValues | BaseValues[];
1483
+ chainsWith: "and" | "or";
1484
+ canKeywordBeSeenMultipleTimes: boolean;
1485
+ folder: string;
1486
+ file: string;
1487
+ constructor(column: string, chainsWith: "and" | "or", isNegated: boolean | undefined, operator: BinaryOperatorType, value: BaseValues | BaseValues[], isRawValue?: boolean);
1488
+ }
1489
+
1490
+ declare class DistinctNode extends QueryNode {
1491
+ chainsWith: string;
1492
+ canKeywordBeSeenMultipleTimes: boolean;
1493
+ folder: string;
1494
+ file: string;
1495
+ constructor();
1496
+ }
1497
+
1498
+ declare class DistinctOnNode extends QueryNode {
1499
+ columns: string[];
1500
+ chainsWith: string;
1501
+ canKeywordBeSeenMultipleTimes: boolean;
1502
+ folder: string;
1503
+ file: string;
1504
+ constructor(columns: string[]);
1505
+ }
1506
+
1507
+ declare class FromNode extends QueryNode {
1508
+ table: string | QueryNode | QueryNode[];
1509
+ chainsWith: string;
1510
+ canKeywordBeSeenMultipleTimes: boolean;
1511
+ folder: string;
1512
+ file: string;
1513
+ alias?: string;
1514
+ constructor(table: string | QueryNode | QueryNode[], alias?: string);
1515
+ }
1516
+
1517
+ declare class SelectNode extends QueryNode {
1518
+ column: string | QueryNode | QueryNode[];
1519
+ alias?: string;
1520
+ sqlFunction?: string;
1521
+ chainsWith: string;
1522
+ canKeywordBeSeenMultipleTimes: boolean;
1523
+ folder: string;
1524
+ file: string;
1525
+ constructor(column: string | QueryNode | QueryNode[], alias?: string, sqlFunction?: string, isRaw?: boolean);
1526
+ }
1527
+
1528
+ declare class JoinNode extends QueryNode {
1529
+ table: string;
1530
+ left: string;
1531
+ right: string;
1532
+ on?: {
1533
+ left?: string;
1534
+ right?: string;
1535
+ operator: string;
1536
+ };
1537
+ chainsWith: string;
1538
+ canKeywordBeSeenMultipleTimes: boolean;
1539
+ folder: string;
1540
+ file: string;
1541
+ type: "inner" | "left" | "right" | "full" | "cross" | "natural";
1542
+ constructor(table: string, left: string, right: string, type: "inner" | "left" | "right" | "full" | "cross" | "natural" | undefined, on: {
1543
+ left?: string;
1544
+ right?: string;
1545
+ operator: string;
1546
+ }, isRawValue?: boolean);
1547
+ }
1548
+
1549
+ declare class GroupByNode extends QueryNode {
1550
+ column: string;
1551
+ chainsWith: string;
1552
+ canKeywordBeSeenMultipleTimes: boolean;
1553
+ folder: string;
1554
+ file: string;
1555
+ constructor(column: string, isRawValue?: boolean);
1556
+ }
1557
+
1558
+ declare class LimitNode extends QueryNode {
1559
+ limit: number;
1560
+ chainsWith: string;
1561
+ canKeywordBeSeenMultipleTimes: boolean;
1562
+ folder: string;
1563
+ file: string;
1564
+ constructor(limit: number);
1565
+ }
1566
+
1567
+ declare class OffsetNode extends QueryNode {
1568
+ offset: number;
1569
+ chainsWith: string;
1570
+ canKeywordBeSeenMultipleTimes: boolean;
1571
+ folder: string;
1572
+ file: string;
1573
+ constructor(offset: number);
1574
+ }
1575
+
1576
+ declare class OrderByNode extends QueryNode {
1577
+ column: string;
1578
+ direction: "asc" | "desc";
1579
+ chainsWith: string;
1580
+ canKeywordBeSeenMultipleTimes: boolean;
1581
+ folder: string;
1582
+ file: string;
1583
+ constructor(column: string, direction?: "asc" | "desc", isRawValue?: boolean);
1584
+ }
1585
+
1586
+ type DateFormat = "ISO" | "TIMESTAMP" | "DATE_ONLY" | "TIME_ONLY";
1587
+ type Timezone = "UTC" | "LOCAL";
1588
+
1589
+ type ColumnDataType = Exclude<keyof CreateTableBuilder, "enum" | "rawColumn" | "custom"> | readonly string[];
1590
+ type ColumnDataTypeOptionWithLength = {
1591
+ type?: "char" | "varchar" | "string" | "uuid" | "ulid" | "varbinary" | "integer" | "tinyint" | "smallint" | "mediumint" | "bigint";
1592
+ length?: number;
1593
+ };
1594
+ type ColumnDataTypeOptionWithEnum = {
1595
+ type?: readonly string[];
1596
+ };
1597
+ type ColumnDataTypeOptionWithPrecision = {
1598
+ type?: "float" | "double" | "real";
1599
+ precision?: number;
1600
+ };
1601
+ type ColumnDataTypeOptionWithScaleAndPrecision = {
1602
+ type?: "decimal" | "numeric";
1603
+ precision?: number;
1604
+ scale?: number;
1605
+ };
1606
+ type ColumnDataTypeOptionWithText = {
1607
+ type?: "text" | "longtext" | "mediumtext" | "tinytext";
1608
+ };
1609
+ type ColumnDataTypeOptionWithBinary = {
1610
+ type?: "binary" | "blob" | "tinyblob" | "mediumblob" | "longblob";
1611
+ };
1612
+ type ColumnDataTypeOptionWithDatePrecision = {
1613
+ type?: "date" | "time" | "datetime" | "timestamp";
1614
+ precision?: number;
1615
+ withTimezone?: boolean;
1616
+ };
1617
+ type ColumnDataTypeOptionSimple = {
1618
+ type?: "year" | "boolean" | "json" | "jsonb";
1619
+ };
1620
+ type ColumnDataTypeOption = ColumnDataTypeOptionWithLength | ColumnDataTypeOptionWithPrecision | ColumnDataTypeOptionWithScaleAndPrecision | ColumnDataTypeOptionWithText | ColumnDataTypeOptionWithBinary | ColumnDataTypeOptionWithDatePrecision | ColumnDataTypeOptionWithEnum | ColumnDataTypeOptionSimple;
1621
+ type LazyRelationType = {
1622
+ type?: RelationEnum;
1623
+ columnName: string;
1624
+ model: () => typeof Model;
1625
+ foreignKey: string | (() => string);
1626
+ constraintName: string | (() => string);
1627
+ onDelete?: OnUpdateOrDelete;
1628
+ onUpdate?: OnUpdateOrDelete;
1629
+ /**
1630
+ * @description Only for many to many relations
1631
+ */
1632
+ manyToManyOptions?: {
1633
+ primaryModel: string;
1634
+ throughModel: string | (() => string);
1635
+ leftForeignKey: string | (() => string);
1636
+ rightForeignKey: string | (() => string);
1637
+ wasModelProvided: boolean;
1638
+ };
1639
+ };
1640
+ type DateColumnOptions = {
1641
+ /**
1642
+ * @description The format to store dates in ('ISO' or 'TIMESTAMP')
1643
+ * @default "ISO"
1644
+ */
1645
+ format?: DateFormat;
1646
+ /**
1647
+ * @description The timezone to use ('UTC' or 'LOCAL')
1648
+ * @default "UTC"
1649
+ */
1650
+ timezone?: Timezone;
1651
+ /**
1652
+ * @description Whether to automatically update the timestamp on record updates, uses timezone and format from the dateColumn options
1653
+ * @default false
1654
+ */
1655
+ autoUpdate?: boolean;
1656
+ /**
1657
+ * @description Whether to automatically set the timestamp on record creation, uses timezone and format from the dateColumn options
1658
+ * @default false
1659
+ */
1660
+ autoCreate?: boolean;
1661
+ } & ColumnOptions;
1662
+ type SymmetricEncryptionOptions = {
1663
+ /**
1664
+ * @description The key to use for the symmetric encryption
1665
+ */
1666
+ key: string;
1667
+ } & ColumnOptions;
1668
+ type AsymmetricEncryptionOptions = {
1669
+ /**
1670
+ * @description The public key to use for the asymmetric encryption
1671
+ */
1672
+ publicKey: string;
1673
+ /**
1674
+ * @description The private key to use for the asymmetric encryption
1675
+ */
1676
+ privateKey: string;
1677
+ } & ColumnOptions;
1678
+ /**
1679
+ * columns
1680
+ * @description Options for the column decorator
1681
+ */
1682
+ type ColumnOptions = {
1683
+ /**
1684
+ * @description Whether the column is the primary key, composite primary keys are not supported
1685
+ * @warning Only one primary key is allowed per model
1686
+ * @throws {HysteriaError} if more than one primary key is defined
1687
+ * @default false
1688
+ */
1689
+ primaryKey?: boolean;
1690
+ /**
1691
+ * @description The name of the primary key constraint in the database for automatic migrations
1692
+ */
1693
+ primaryKeyConstraintName?: string;
1694
+ /**
1695
+ * @description Called on the value returned from the database before it is returned from the model
1696
+ */
1697
+ serialize?: (value: any) => any;
1698
+ /**
1699
+ * @description Called on the value before it is inserted or updated in the database
1700
+ * @warning This will not be called on massive update operations since it's not possible to know which values are being updated, so you must pass the value you want to update in the payload
1701
+ */
1702
+ prepare?: (value: any) => any;
1703
+ /**
1704
+ * @description Whether the column is returned in the serialization output, this column will always be undefined
1705
+ * @default false
1706
+ */
1707
+ hidden?: boolean;
1708
+ /**
1709
+ * @description If true, the prepare function will always be called on update regardless of whether the value has been provided in the update payload
1710
+ * @default false
1711
+ */
1712
+ autoUpdate?: boolean;
1713
+ /**
1714
+ * @description The name of the column in the database, can be used to specify the column name in the database
1715
+ * @default The name of the property following the model case convention
1716
+ */
1717
+ databaseName?: string;
1718
+ /**
1719
+ * @description Custom OpenAPI schema for the column, if omitted, the column type will be inferred from the other options in best effort
1720
+ */
1721
+ openApi?: OpenApiModelPropertyType & {
1722
+ required?: boolean;
1723
+ };
1724
+ /**
1725
+ * @description Whether the column can be null in the database
1726
+ * @migration Only affects auto-generated migrations
1727
+ */
1728
+ nullable?: boolean;
1729
+ /**
1730
+ * @description The default value for the column in the database
1731
+ * @migration Only affects auto-generated migrations
1732
+ */
1733
+ default?: string | number | null | boolean;
1734
+ } &
1735
+ /**
1736
+ * @description The data type of the column
1737
+ * @migration Only affects auto-generated migrations
1738
+ */
1739
+ ColumnDataTypeOption;
1740
+ type ColumnType = {
1741
+ columnName: string;
1742
+ databaseName: string;
1743
+ serialize?: (value: any) => any;
1744
+ prepare?: (value: any) => any;
1745
+ hidden?: boolean;
1746
+ autoUpdate?: boolean;
1747
+ isPrimary: boolean;
1748
+ openApi?: OpenApiModelPropertyType & {
1749
+ required?: boolean;
1750
+ };
1751
+ /** Database specific data for migrations, must be provided or it'll be ignored for auto-generated migrations */
1752
+ primaryKeyConstraintName?: string;
1753
+ type?: ColumnDataType;
1754
+ length?: number;
1755
+ precision?: number;
1756
+ scale?: number;
1757
+ withTimezone?: boolean;
1758
+ constraints?: {
1759
+ nullable?: boolean;
1760
+ default?: string | number | null | boolean;
1761
+ };
1762
+ };
1763
+ type ThroughModelCallback<T extends typeof Model> = () => T;
1764
+ type ThroughModelString = string;
1765
+ type ThroughModel<T extends typeof Model> = ThroughModelCallback<T> | ThroughModelString;
1766
+ type ExtractModelFromTM<TM extends ThroughModel<any>> = TM extends ThroughModelCallback<infer T> ? T : never;
1767
+ type ManyToManyOptions<T extends typeof Model, TM extends ThroughModel<T>> = {
1768
+ /**
1769
+ * @description The foreign key of current model on the Pivot table
1770
+ * @example If the current model is User and the through model is UserAddress, the leftForeignKey will be "userId"
1771
+ */
1772
+ leftForeignKey?: TM extends ThroughModelString ? string : ModelKey<InstanceType<ExtractModelFromTM<TM>>>;
1773
+ /**
1774
+ * @description The foreign key of the related model on the Pivot table
1775
+ * @example If the current model is User and the through model is UserAddress, the rightForeignKey will be "addressId"
1776
+ */
1777
+ rightForeignKey?: TM extends ThroughModelString ? string : ModelKey<InstanceType<ExtractModelFromTM<TM>>>;
1778
+ };
1779
+ type IndexType = {
1780
+ columns: string[];
1781
+ name: string;
1782
+ };
1783
+ type UniqueType = {
1784
+ columns: string[];
1785
+ name: string;
1786
+ };
1787
+
1788
+ declare abstract class FooterQueryBuilder<T extends Model> {
1789
+ protected sqlDataSource: SqlDataSource;
1790
+ protected model: typeof Model;
1791
+ protected groupByNodes: GroupByNode[];
1792
+ protected orderByNodes: OrderByNode[];
1793
+ protected limitNode: LimitNode | null;
1794
+ protected offsetNode: OffsetNode | null;
1795
+ protected modelColumns: ColumnType[];
1796
+ protected modelColumnsMap: Map<string, ColumnType>;
1797
+ protected logs: boolean;
1798
+ protected constructor(model: typeof Model, sqlDataSource: SqlDataSource);
1799
+ /**
1800
+ * @description Clears the group by query
1801
+ */
1802
+ clearGroupBy(): this;
1803
+ /**
1804
+ * @description Clears the order by query
1805
+ */
1806
+ clearOrderBy(): this;
1807
+ /**
1808
+ * @description Clears the limit query
1809
+ */
1810
+ clearLimit(): this;
1811
+ /**
1812
+ * @description Clears the offset query
1813
+ */
1814
+ clearOffset(): this;
1815
+ /**
1816
+ * @description Adds a group by query
1817
+ */
1818
+ groupBy(...columns: ModelKey<T>[]): this;
1819
+ groupBy<S extends string>(...columns: SelectableColumn<S>[]): this;
1820
+ /**
1821
+ * @description Adds a raw group by query, GROUP BY clause is not necessary and will be added automatically
1822
+ */
1823
+ groupByRaw(query: string): this;
1824
+ /**
1825
+ * @description Adds an order by query
1826
+ */
1827
+ orderBy(column: ModelKey<T>, order: OrderByChoices): this;
1828
+ orderBy<S extends string>(column: SelectableColumn<S>, order: OrderByChoices): this;
1829
+ /**
1830
+ * @description Adds a raw order by query, ORDER BY clause is not necessary and will be added automatically
1831
+ */
1832
+ orderByRaw(query: string): this;
1833
+ /**
1834
+ * @description Adds a limit query
1835
+ */
1836
+ limit(limit: number): this;
1837
+ /**
1838
+ * @description Adds an offset query
1839
+ */
1840
+ offset(offset: number): this;
1841
+ }
1842
+
1843
+ declare abstract class JoinQueryBuilder<T extends Model> extends FooterQueryBuilder<T> {
1844
+ protected joinNodes: JoinNode[];
1845
+ protected constructor(model: typeof Model, sqlDataSource: SqlDataSource);
1846
+ /**
1847
+ * @description Clear the join query
1848
+ */
1849
+ clearJoin(): this;
1850
+ /**
1851
+ * @description Join a table with the current model, join clause is not necessary and will be added automatically
1852
+ */
1853
+ joinRaw(query: string): this;
1854
+ /**
1855
+ * @description Join a table with the current model, join clause is not necessary and will be added automatically
1856
+ */
1857
+ leftJoinRaw(query: string): this;
1858
+ /**
1859
+ * @description Join a table with the current model, join clause is not necessary and will be added automatically
1860
+ */
1861
+ rightJoinRaw(query: string): this;
1862
+ /**
1863
+ * @description Join a table with the current model, join clause is not necessary and will be added automatically
1864
+ */
1865
+ fullJoinRaw(query: string): this;
1866
+ /**
1867
+ * @description Join a table with the current model, join clause is not necessary and will be added automatically
1868
+ */
1869
+ crossJoinRaw(query: string): this;
1870
+ /**
1871
+ * @description Join a table with the current model, join clause is not necessary and will be added automatically
1872
+ */
1873
+ naturalJoinRaw(query: string): this;
1874
+ /**
1875
+ * @alias join
1876
+ * @param relationTable - The table to join
1877
+ * @param referencingColumn - The column to reference from the relation table, must be in the format of `table.column`
1878
+ * @param primaryColumn - The primary column of the current model, default is caller model primary key if using a Model, if using a Raw Query Builder you must provide the key for the primary table, must be in the format of `table.column`
1879
+ * @param operator - The comparison operator to use in the ON clause (default: "=")
1880
+ */
1881
+ innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$1): this;
1882
+ innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$1): this;
1883
+ innerJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType$1): this;
1884
+ innerJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType$1): this;
1885
+ /**
1886
+ * @description Join a table with the current model
1887
+ * @param relationTable - The table to join
1888
+ * @param referencingColumn - The column to reference from the relation table, must be in the format of `table.column`
1889
+ * @param primaryColumn - The primary column of the current model, default is caller model primary key if using a Model, if using a Raw Query Builder you must provide the key for the primary table, must be in the format of `table.column`
1890
+ * @param operator - The comparison operator to use in the ON clause (default: "=")
1891
+ */
1892
+ join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$1): this;
1893
+ join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$1): this;
1894
+ join<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType$1): this;
1895
+ join<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType$1): this;
1896
+ /**
1897
+ * @description Join a table with the current model
1898
+ * @param relationTable - The table to join
1899
+ * @param referencingColumn - The column to reference from the relation table, must be in the format of `table.column`
1900
+ * @param primaryColumn - The primary column of the current model, default is caller model primary key if using a Model, if using a Raw Query Builder you must provide the key for the primary table, must be in the format of `table.column`
1901
+ * @param operator - The comparison operator to use in the ON clause (default: "=")
1902
+ */
1903
+ leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$1): this;
1904
+ leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$1): this;
1905
+ leftJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType$1): this;
1906
+ leftJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType$1): this;
1907
+ /**
1908
+ * @description Join a table with the current model
1909
+ * @param relationTable - The table to join
1910
+ * @param referencingColumn - The column to reference from the relation table
1911
+ * @param primaryColumn - The primary column of the current model, default is caller model primary key if using A Model, if using a Raw Query Builder you must provide the key for the primary table
1912
+ * @param operator - The comparison operator to use in the ON clause (default: "=")
1913
+ */
1914
+ rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$1): this;
1915
+ rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$1): this;
1916
+ /**
1917
+ * @description Perform a FULL OUTER JOIN with another table
1918
+ * @param relationTable - The table to join
1919
+ * @param referencingColumn - The column to reference from the relation table
1920
+ * @param primaryColumn - The primary column of the current model
1921
+ * @param operator - The comparison operator to use in the ON clause (default: "=")
1922
+ */
1923
+ fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$1): this;
1924
+ fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$1): this;
1925
+ }
1926
+
1927
+ declare class SelectQueryBuilder<T extends Model> extends JoinQueryBuilder<T> {
1928
+ protected dbType: SqlDataSourceType;
1929
+ protected modelSelectedColumns: string[];
1930
+ protected modelAnnotatedColumns: string[];
1931
+ protected withQuery?: string;
1932
+ protected fromNode: FromNode;
1933
+ protected distinctNode: DistinctNode | null;
1934
+ protected distinctOnNodes: DistinctOnNode[];
1935
+ protected selectNodes: SelectNode[];
1936
+ constructor(model: typeof Model, sqlDataSource: SqlDataSource);
1937
+ /**
1938
+ * @description Adds a SELECT condition to the query.
1939
+ * @description Can be stacked multiple times
1940
+ * @warning For annotations, use the `annotate` method instead, aliases and methods are not supported in the select method and will give error `column "${columnName} as ${alias}" does not exist`
1941
+ * @example
1942
+ * ```ts
1943
+ * const user = await User.query().select("name", "age").first(); // SELECT name, age FROM users
1944
+ * const user = await User.query().select("name", "users.age").first(); // SELECT name, users.age FROM users
1945
+ * ```
1946
+ */
1947
+ select<S extends string>(...columns: SelectableColumn<S>[]): this;
1948
+ select(...columns: (ModelKey<T> | "*")[]): this;
1949
+ /**
1950
+ * @description Adds a raw select statement to the query
1951
+ * @warning For models, only annotated columns are available and will be added to the `$annotations` property of the model. Everything else will be ignored, if you need a query like `selectRaw` you can use the `QueryBuilder` instead.
1952
+ */
1953
+ selectRaw(statement: string): this;
1954
+ /**
1955
+ * @description Clears the SELECT clause
1956
+ */
1957
+ clearSelect(): this;
1958
+ /**
1959
+ * @description Clears the FROM clause
1960
+ */
1961
+ clearFrom(): this;
1962
+ /**
1963
+ * @description Clears the DISTINCT clause
1964
+ */
1965
+ clearDistinct(): this;
1966
+ /**
1967
+ * @description Clears the DISTINCT ON clause
1968
+ */
1969
+ clearDistinctOn(): this;
1970
+ /**
1971
+ * @description Annotates a column with a SQL method or a simple alias
1972
+ * @description If using a model, the result will be available in the $annotations property of the model, else it will be available in the result of the query
1973
+ * @example
1974
+ * ```ts
1975
+ * const user = await User.query().annotate("max", "id", "maxId").first(); // max(id) as maxId
1976
+ * const user = await User.query().annotate("id", "superId").first(); // id as superId
1977
+ * const user = await User.query().annotate("id", "superId").first(); // id as superId
1978
+ * ```
1979
+ */
1980
+ annotate(column: string, alias: string): this;
1981
+ annotate(sqlMethod: SqlMethod, column: string, alias: string): this;
1982
+ annotate(sqlMethod: string, column: string, alias: string): this;
1983
+ /**
1984
+ * @description Sets the table to select from, by default is the table defined in the Model
1985
+ * @description Can be used on non select queries too, it will only specify the table name (es. INSERT INTO $table)
1986
+ */
1987
+ from(table: string): this;
1988
+ /**
1989
+ * @description Sets the table to select from, by default is the table defined in the Model
1990
+ * @description Better naming convention for non select queries
1991
+ * @alias from
1992
+ */
1993
+ table(table: string): this;
1994
+ /**
1995
+ * @description Adds a DISTINCT clause to the query
1996
+ */
1997
+ distinct(): this;
1998
+ /**
1999
+ * @description Adds a DISTINCT ON clause to the query
2000
+ * @postgresql Only usable with PostgreSQL
2001
+ */
2002
+ distinctOn(...columns: ModelKey<T>[]): this;
2003
+ distinctOn<S extends string>(...columns: SelectableColumn<S>[]): this;
2004
+ }
2005
+
2006
+ declare abstract class WhereQueryBuilder<T extends Model> extends SelectQueryBuilder<T> {
2007
+ protected whereNodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[];
2008
+ protected havingNodes: HavingNode[];
2009
+ protected isNestedCondition: boolean;
2010
+ constructor(model: typeof Model, sqlDataSource: SqlDataSource, isNestedCondition?: boolean);
2011
+ clearWhere(): this;
2012
+ clearHaving(): this;
2013
+ /**
2014
+ * @description Accepts a value and executes a callback only of the value is not null or undefined.
2015
+ * @warning The value is not checked for truthiness but existence, it is only checked for undefined or null. So false, 0, "", etc. will be considered truthy.
2016
+ */
2017
+ strictWhen(value: any, cb: (query: this) => void): this;
2018
+ /**
2019
+ * @description Accepts a value and executes a callback only of the value is not falsy.
2020
+ * @warning The value is checked for truthiness, so false, 0, "", etc. will be considered falsy. Use strictWhen for null or undefined only cases.
2021
+ */
2022
+ when(value: any, cb: (query: this) => void): this;
2023
+ /**
2024
+ * @description Adds a WHERE condition to the query.
2025
+ */
2026
+ where(column: ModelKey<T>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2027
+ where<S extends string>(column: SelectableColumn<S>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2028
+ where(cb: (queryBuilder: WhereOnlyQueryBuilder<T>) => void): this;
2029
+ where(column: ModelKey<T> | SelectableColumn<string>, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2030
+ where(column: ModelKey<T> | SelectableColumn<string>, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2031
+ where(column: ModelKey<T> | SelectableColumn<string>, value: BaseValues$1): this;
2032
+ /**
2033
+ * @description Adds an AND WHERE condition to the query.
2034
+ */
2035
+ andWhere(column: ModelKey<T>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2036
+ andWhere(column: SelectableColumn<string>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2037
+ andWhere(column: ModelKey<T> | SelectableColumn<string>, value: BaseValues$1): this;
2038
+ andWhere(cb: (queryBuilder: WhereOnlyQueryBuilder<T>) => void): this;
2039
+ andWhere(column: ModelKey<T> | SelectableColumn<string>, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2040
+ andWhere(column: ModelKey<T> | SelectableColumn<string>, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2041
+ /**
2042
+ * @description Adds an OR WHERE condition to the query.
2043
+ */
2044
+ orWhere(column: ModelKey<T>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2045
+ orWhere<S extends string>(column: SelectableColumn<S>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2046
+ orWhere<S extends string>(column: ModelKey<T> | SelectableColumn<S>, value: BaseValues$1): this;
2047
+ orWhere(cb: (queryBuilder: WhereOnlyQueryBuilder<T>) => void): this;
2048
+ orWhere(column: ModelKey<T> | SelectableColumn<string>, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2049
+ orWhere(column: ModelKey<T> | SelectableColumn<string>, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2050
+ /**
2051
+ * @description Adds a negated WHERE condition to the query.
2052
+ */
2053
+ whereNot(column: ModelKey<T>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2054
+ whereNot<S extends string>(column: SelectableColumn<S>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2055
+ whereNot(column: ModelKey<T> | SelectableColumn<string>, value: BaseValues$1): this;
2056
+ whereNot(column: ModelKey<T> | SelectableColumn<string>, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2057
+ whereNot(column: ModelKey<T> | SelectableColumn<string>, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2058
+ /**
2059
+ * @description Adds a negated AND WHERE condition to the query.
2060
+ */
2061
+ andWhereNot(column: ModelKey<T>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2062
+ andWhereNot<S extends string>(column: SelectableColumn<S>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2063
+ andWhereNot(column: ModelKey<T> | SelectableColumn<string>, value: BaseValues$1): this;
2064
+ andWhereNot(column: ModelKey<T> | SelectableColumn<string>, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2065
+ andWhereNot(column: ModelKey<T> | SelectableColumn<string>, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2066
+ /**
2067
+ * @description Adds a negated OR WHERE condition to the query.
2068
+ */
2069
+ orWhereNot(column: ModelKey<T>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2070
+ orWhereNot<S extends string>(column: SelectableColumn<S>, operator: BinaryOperatorType$1, value: BaseValues$1): this;
2071
+ orWhereNot(column: ModelKey<T> | SelectableColumn<string>, value: BaseValues$1): this;
2072
+ orWhereNot(column: ModelKey<T> | SelectableColumn<string>, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2073
+ orWhereNot(column: ModelKey<T> | SelectableColumn<string>, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void)): this;
2074
+ /**
2075
+ * @description Adds a WHERE BETWEEN condition to the query.
2076
+ */
2077
+ whereBetween(column: ModelKey<T>, min: BaseValues$1, max: BaseValues$1): this;
2078
+ whereBetween<S extends string>(column: SelectableColumn<S>, min: BaseValues$1, max: BaseValues$1): this;
2079
+ /**
2080
+ * @description Adds an AND WHERE BETWEEN condition to the query.
2081
+ */
2082
+ andWhereBetween(column: ModelKey<T>, min: BaseValues$1, max: BaseValues$1): this;
2083
+ andWhereBetween<S extends string>(column: SelectableColumn<S>, min: BaseValues$1, max: BaseValues$1): this;
2084
+ /**
2085
+ * @description Adds an OR WHERE BETWEEN condition to the query.
2086
+ */
2087
+ orWhereBetween(column: ModelKey<T>, min: BaseValues$1, max: BaseValues$1): this;
2088
+ orWhereBetween<S extends string>(column: SelectableColumn<S>, min: BaseValues$1, max: BaseValues$1): this;
2089
+ /**
2090
+ * @description Adds a WHERE NOT BETWEEN condition to the query.
2091
+ */
2092
+ whereNotBetween(column: ModelKey<T>, min: BaseValues$1, max: BaseValues$1): this;
2093
+ whereNotBetween<S extends string>(column: SelectableColumn<S>, min: BaseValues$1, max: BaseValues$1): this;
2094
+ /**
2095
+ * @description Adds an AND WHERE NOT BETWEEN condition to the query.
2096
+ */
2097
+ andWhereNotBetween(column: ModelKey<T>, min: BaseValues$1, max: BaseValues$1): this;
2098
+ andWhereNotBetween<S extends string>(column: SelectableColumn<S>, min: BaseValues$1, max: BaseValues$1): this;
2099
+ /**
2100
+ * @description Adds an OR WHERE NOT BETWEEN condition to the query.
2101
+ */
2102
+ orWhereNotBetween(column: ModelKey<T>, min: BaseValues$1, max: BaseValues$1): this;
2103
+ orWhereNotBetween<S extends string>(column: SelectableColumn<S>, min: BaseValues$1, max: BaseValues$1): this;
2104
+ /**
2105
+ * @description Adds a WHERE LIKE condition to the query.
2106
+ */
2107
+ whereLike(column: ModelKey<T>, value: string): this;
2108
+ whereLike<S extends string>(column: SelectableColumn<S>, value: string): this;
2109
+ /**
2110
+ * @description Adds an AND WHERE LIKE condition to the query.
2111
+ */
2112
+ andWhereLike(column: ModelKey<T>, value: string): this;
2113
+ andWhereLike<S extends string>(column: SelectableColumn<S>, value: string): this;
2114
+ /**
2115
+ * @description Adds an OR WHERE LIKE condition to the query.
2116
+ */
2117
+ orWhereLike(column: ModelKey<T>, value: string): this;
2118
+ orWhereLike<S extends string>(column: SelectableColumn<S>, value: string): this;
2119
+ /**
2120
+ * @description Adds a WHERE ILIKE condition to the query.
2121
+ */
2122
+ whereILike(column: ModelKey<T>, value: string): this;
2123
+ whereILike<S extends string>(column: SelectableColumn<S>, value: string): this;
2124
+ /**
2125
+ * @description Adds an AND WHERE ILIKE condition to the query.
2126
+ */
2127
+ andWhereILike(column: ModelKey<T>, value: string): this;
2128
+ andWhereILike<S extends string>(column: SelectableColumn<S>, value: string): this;
2129
+ /**
2130
+ * @description Adds an OR WHERE ILIKE condition to the query.
2131
+ */
2132
+ orWhereILike(column: ModelKey<T>, value: string): this;
2133
+ orWhereILike<S extends string>(column: SelectableColumn<S>, value: string): this;
2134
+ /**
2135
+ * @description Adds a WHERE NOT LIKE condition to the query.
2136
+ */
2137
+ whereNotLike(column: ModelKey<T>, value: string): this;
2138
+ whereNotLike<S extends string>(column: SelectableColumn<S>, value: string): this;
2139
+ /**
2140
+ * @description Adds an AND WHERE NOT LIKE condition to the query.
2141
+ */
2142
+ andWhereNotLike(column: ModelKey<T>, value: string): this;
2143
+ andWhereNotLike<S extends string>(column: SelectableColumn<S>, value: string): this;
2144
+ /**
2145
+ * @description Adds an OR WHERE NOT LIKE condition to the query.
2146
+ */
2147
+ orWhereNotLike(column: ModelKey<T>, value: string): this;
2148
+ orWhereNotLike<S extends string>(column: SelectableColumn<S>, value: string): this;
2149
+ /**
2150
+ * @description Adds a WHERE NOT ILIKE condition to the query.
2151
+ */
2152
+ whereNotILike(column: ModelKey<T>, value: string): this;
2153
+ whereNotILike<S extends string>(column: SelectableColumn<S>, value: string): this;
2154
+ /**
2155
+ * @description Adds an AND WHERE NOT ILIKE condition to the query.
2156
+ */
2157
+ andWhereNotILike(column: ModelKey<T>, value: string): this;
2158
+ andWhereNotILike<S extends string>(column: SelectableColumn<S>, value: string): this;
2159
+ /**
2160
+ * @description Adds an OR WHERE NOT ILIKE condition to the query.
2161
+ */
2162
+ orWhereNotILike(column: ModelKey<T>, value: string): this;
2163
+ orWhereNotILike<S extends string>(column: SelectableColumn<S>, value: string): this;
2164
+ /**
2165
+ * @description Adds a WHERE IN condition to the query.
2166
+ * @warning If the array is empty, it will add an impossible condition.
2167
+ */
2168
+ whereIn(column: ModelKey<T>, values: BaseValues$1[]): this;
2169
+ whereIn<S extends string>(column: SelectableColumn<S>, values: BaseValues$1[]): this;
2170
+ /**
2171
+ * @description Adds an AND WHERE IN condition to the query.
2172
+ * @warning If the array is empty, it will add an impossible condition.
2173
+ */
2174
+ andWhereIn(column: ModelKey<T>, values: BaseValues$1[]): this;
2175
+ andWhereIn<S extends string>(column: SelectableColumn<S>, values: BaseValues$1[]): this;
2176
+ /**
2177
+ * @description Adds an OR WHERE IN condition to the query.
2178
+ * @warning If the array is empty, it will add an impossible condition.
2179
+ */
2180
+ orWhereIn(column: ModelKey<T>, values: BaseValues$1[]): this;
2181
+ orWhereIn<S extends string>(column: SelectableColumn<S>, values: BaseValues$1[]): this;
2182
+ /**
2183
+ * @description Adds a WHERE NOT IN condition to the query.
2184
+ * @warning If the array is empty, it will add an obvious condition to make it true.
2185
+ */
2186
+ whereNotIn(column: ModelKey<T>, values: BaseValues$1[]): this;
2187
+ whereNotIn<S extends string>(column: SelectableColumn<S>, values: BaseValues$1[]): this;
2188
+ /**
2189
+ * @description Adds an OR WHERE NOT IN condition to the query.
2190
+ * @warning If the array is empty, it will add an obvious condition to make it true.
2191
+ */
2192
+ andWhereNotIn(column: ModelKey<T>, values: BaseValues$1[]): this;
2193
+ andWhereNotIn<S extends string>(column: SelectableColumn<S>, values: BaseValues$1[]): this;
2194
+ /**
2195
+ * @description Adds an OR WHERE NOT IN condition to the query.
2196
+ * @warning If the array is empty, it will add an obvious condition to make it true.
2197
+ */
2198
+ orWhereNotIn(column: ModelKey<T>, values: BaseValues$1[]): this;
2199
+ orWhereNotIn<S extends string>(column: SelectableColumn<S>, values: BaseValues$1[]): this;
2200
+ /**
2201
+ * @description Adds a WHERE NULL condition to the query.
2202
+ */
2203
+ whereNull(column: ModelKey<T>): this;
2204
+ whereNull<S extends string>(column: SelectableColumn<S>): this;
2205
+ /**
2206
+ * @description Adds an AND WHERE NULL condition to the query.
2207
+ */
2208
+ andWhereNull(column: ModelKey<T>): this;
2209
+ andWhereNull<S extends string>(column: SelectableColumn<S>): this;
2210
+ /**
2211
+ * @description Adds an OR WHERE NULL condition to the query.
2212
+ */
2213
+ orWhereNull(column: ModelKey<T>): this;
2214
+ orWhereNull<S extends string>(column: SelectableColumn<S>): this;
2215
+ /**
2216
+ * @description Adds a WHERE NOT NULL condition to the query.
2217
+ */
2218
+ whereNotNull(column: ModelKey<T>): this;
2219
+ whereNotNull<S extends string>(column: SelectableColumn<S>): this;
2220
+ /**
2221
+ * @description Adds an AND WHERE NOT NULL condition to the query.
2222
+ */
2223
+ andWhereNotNull(column: ModelKey<T>): this;
2224
+ andWhereNotNull<S extends string>(column: SelectableColumn<S>): this;
2225
+ /**
2226
+ * @description Adds an OR WHERE NOT NULL condition to the query.
2227
+ */
2228
+ orWhereNotNull(column: ModelKey<T>): this;
2229
+ orWhereNotNull<S extends string>(column: SelectableColumn<S>): this;
2230
+ /**
2231
+ * @description Adds a WHERE REGEXP condition to the query.
2232
+ */
2233
+ whereRegexp(column: ModelKey<T>, regexp: RegExp): this;
2234
+ whereRegexp<S extends string>(column: SelectableColumn<S>, regexp: RegExp): this;
2235
+ /**
2236
+ * @description Adds an AND WHERE REGEXP condition to the query.
2237
+ */
2238
+ andWhereRegexp(column: ModelKey<T>, regexp: RegExp): this;
2239
+ andWhereRegexp<S extends string>(column: SelectableColumn<S>, regexp: RegExp): this;
2240
+ /**
2241
+ * @description Adds an OR WHERE REGEXP condition to the query.
2242
+ */
2243
+ orWhereRegexp(column: ModelKey<T>, regexp: RegExp): this;
2244
+ orWhereRegexp<S extends string>(column: SelectableColumn<S>, regexp: RegExp): this;
2245
+ whereNotRegexp(column: ModelKey<T>, regexp: RegExp): this;
2246
+ whereNotRegexp<S extends string>(column: SelectableColumn<S>, regexp: RegExp): this;
2247
+ andWhereNotRegexp(column: ModelKey<T>, regexp: RegExp): this;
2248
+ andWhereNotRegexp<S extends string>(column: SelectableColumn<S>, regexp: RegExp): this;
2249
+ orWhereNotRegexp(column: ModelKey<T>, regexp: RegExp): this;
2250
+ orWhereNotRegexp<S extends string>(column: SelectableColumn<S>, regexp: RegExp): this;
2251
+ /**
2252
+ * @description Adds a AND WHERE EXISTS condition to the query. By default uses the same table, you can use the `from` method to change the table.
2253
+ */
2254
+ whereExists(cbOrQueryBuilder: (queryBuilder: QueryBuilder<T>) => void | QueryBuilder<T>): this;
2255
+ /**
2256
+ * @description Adds a AND WHERE EXISTS condition to the query. By default uses the same table, you can use the `from` method to change the table.
2257
+ */
2258
+ andWhereExists(cbOrQueryBuilder: (queryBuilder: QueryBuilder<T>) => void | QueryBuilder<T>): this;
2259
+ /**
2260
+ * @description Adds a OR WHERE EXISTS condition to the query. By default uses the same table, you can use the `from` method to change the table.
2261
+ */
2262
+ orWhereExists(cbOrQueryBuilder: (queryBuilder: QueryBuilder<T>) => void | QueryBuilder<T>): this;
2263
+ /**
2264
+ * @description Adds a WHERE NOT EXISTS condition to the query. By default uses the same table, you can use the `from` method to change the table.
2265
+ */
2266
+ whereNotExists(cbOrQueryBuilder: (queryBuilder: QueryBuilder<T>) => void | QueryBuilder<T>): this;
2267
+ /**
2268
+ * @description Adds a WHERE NOT EXISTS condition to the query. By default uses the same table, you can use the `from` method to change the table.
2269
+ */
2270
+ andWhereNotExists(cbOrQueryBuilder: (queryBuilder: QueryBuilder<T>) => void | QueryBuilder<T>): this;
2271
+ /**
2272
+ * @description Adds a WHERE NOT EXISTS condition to the query. By default uses the same table, you can use the `from` method to change the table.
2273
+ */
2274
+ orWhereNotExists(cbOrQueryBuilder: (queryBuilder: QueryBuilder<T>) => void | QueryBuilder<T>): this;
2275
+ /**
2276
+ * @description Adds a raw WHERE condition to the query.
2277
+ */
2278
+ whereRaw(query: string, queryParams?: any[]): this;
2279
+ /**
2280
+ * @description Adds a raw AND WHERE condition to the query.
2281
+ */
2282
+ andWhereRaw(query: string, queryParams?: any[]): this;
2283
+ /**
2284
+ * @description Adds a raw OR WHERE condition to the query.
2285
+ */
2286
+ orWhereRaw(query: string, queryParams?: any[]): this;
2287
+ /**
2288
+ * @description Adds a HAVING condition to the query.
2289
+ */
2290
+ having<S extends string>(column: SelectableColumn<S>, value: any): this;
2291
+ having(column: ModelKey<T>, operator: BinaryOperatorType$1, value: any): this;
2292
+ /**
2293
+ * @description Adds an AND HAVING condition to the query.
2294
+ */
2295
+ andHaving<S extends string>(column: SelectableColumn<S>, value: any): this;
2296
+ andHaving(column: ModelKey<T>, operator: BinaryOperatorType$1, value: any): this;
2297
+ /**
2298
+ * @description Adds an OR HAVING condition to the query.
2299
+ */
2300
+ orHaving<S extends string>(column: SelectableColumn<S>, value: any): this;
2301
+ orHaving(column: ModelKey<T>, operator: BinaryOperatorType$1, value: any): this;
2302
+ /**
2303
+ * @description Adds a raw HAVING condition to the query.
2304
+ */
2305
+ havingRaw(query: string): this;
2306
+ /**
2307
+ * @description Adds a raw OR HAVING condition to the query.
2308
+ */
2309
+ andHavingRaw(query: string): this;
2310
+ /**
2311
+ * @description Adds a raw OR HAVING condition to the query.
2312
+ */
2313
+ orHavingRaw(query: string): this;
2314
+ private buildSubQuery;
2315
+ private andWhereSubQuery;
2316
+ private orWhereSubQuery;
2317
+ private andWhereGroup;
2318
+ private orWhereGroup;
2319
+ }
2320
+
2321
+ type JsonParam = Record<string, unknown> | any[];
2322
+ declare class JsonQueryBuilder<T extends Model> extends WhereQueryBuilder<T> {
2323
+ /**
2324
+ * @description Filters records matching exact JSON value.
2325
+ */
2326
+ whereJson(column: ModelKey<T>, value: JsonParam): this;
2327
+ whereJson(column: string, value: JsonParam): this;
2328
+ /**
2329
+ * @description Filters records matching the given JSON value.
2330
+ */
2331
+ andWhereJson(column: ModelKey<T>, value: JsonParam): this;
2332
+ andWhereJson(column: string, value: JsonParam): this;
2333
+ /**
2334
+ * @description Filters records matching the given JSON value.
2335
+ */
2336
+ orWhereJson(column: ModelKey<T>, value: JsonParam): this;
2337
+ orWhereJson(column: string, value: JsonParam): this;
2338
+ /**
2339
+ * @description Filters records where JSON column does NOT contain the given value.
2340
+ * @sqlite might not work for all cases, suggest using the whereJsonRaw method instead
2341
+ */
2342
+ whereJsonNotContains(column: ModelKey<T>, value: JsonParam): this;
2343
+ whereJsonNotContains(column: string, value: JsonParam): this;
2344
+ /**
2345
+ * @description Filters records where JSON column does NOT contain the given value (AND).
2346
+ * @sqlite might not work for all cases, suggest using the whereJsonRaw method instead
2347
+ */
2348
+ andWhereJsonNotContains(column: ModelKey<T>, value: JsonParam): this;
2349
+ andWhereJsonNotContains(column: string, value: JsonParam): this;
2350
+ /**
2351
+ * @description Filters records where JSON column does NOT contain the given value (OR).
2352
+ * @sqlite might not work for all cases, suggest using the whereJsonRaw method instead
2353
+ */
2354
+ orWhereJsonNotContains(column: ModelKey<T>, value: JsonParam): this;
2355
+ orWhereJsonNotContains(column: string, value: JsonParam): this;
2356
+ /**
2357
+ * @description Filters records where JSON column contains the given value.
2358
+ * @sqlite might not work for all cases, suggest using the whereJsonRaw method instead
2359
+ */
2360
+ whereJsonContains(column: ModelKey<T>, value: JsonParam): this;
2361
+ whereJsonContains(column: string, value: JsonParam): this;
2362
+ /**
2363
+ * @description Filters records where JSON column contains the given value (AND).
2364
+ * @sqlite might not work for all cases, suggest using the whereJsonRaw method instead
2365
+ */
2366
+ andWhereJsonContains(column: ModelKey<T>, value: JsonParam): this;
2367
+ andWhereJsonContains(column: string, value: JsonParam): this;
2368
+ /**
2369
+ * @description Filters records where JSON column contains the given value (OR).
2370
+ * @sqlite might not work for all cases, suggest using the whereJsonRaw method instead
2371
+ */
2372
+ orWhereJsonContains(column: ModelKey<T>, value: JsonParam): this;
2373
+ orWhereJsonContains(column: string, value: JsonParam): this;
2374
+ /**
2375
+ * @description Filters records where JSON column does NOT match the given value.
2376
+ */
2377
+ whereNotJson(column: ModelKey<T>, value: JsonParam): this;
2378
+ whereNotJson(column: string, value: JsonParam): this;
2379
+ /**
2380
+ * @description Filters records where JSON column does NOT match the given value (AND).
2381
+ */
2382
+ andWhereNotJson(column: ModelKey<T>, value: JsonParam): this;
2383
+ andWhereNotJson(column: string, value: JsonParam): this;
2384
+ /**
2385
+ * @description Filters records where JSON column does NOT match the given value (OR).
2386
+ */
2387
+ orWhereNotJson(column: ModelKey<T>, value: JsonParam): this;
2388
+ orWhereNotJson(column: string, value: JsonParam): this;
2389
+ /**
2390
+ * @description Add a raw JSON filter expression.
2391
+ */
2392
+ whereJsonRaw(raw: string, params?: any[]): this;
2393
+ /**
2394
+ * @description Add a raw JSON filter expression (AND).
2395
+ */
2396
+ andWhereJsonRaw(raw: string, params?: any[]): this;
2397
+ /**
2398
+ * @description Add a raw JSON filter expression (OR).
2399
+ */
2400
+ orWhereJsonRaw(raw: string, params?: any[]): this;
2401
+ }
2402
+
2403
+ type PluckReturnType<T extends Model, K extends ModelKey<T>> = T[K] extends infer U ? U[] : never;
2404
+ type WhereOnlyQueryBuilder<T extends Model> = Pick<WhereQueryBuilder<T>, "where" | "andWhere" | "orWhere" | "whereNot" | "andWhereNot" | "orWhereNot" | "whereIn" | "andWhereIn" | "orWhereIn" | "whereNotIn" | "andWhereNotIn" | "orWhereNotIn" | "whereBetween" | "andWhereBetween" | "orWhereBetween" | "whereNotBetween" | "andWhereNotBetween" | "orWhereNotBetween" | "whereNull" | "andWhereNull" | "orWhereNull" | "whereNotNull" | "andWhereNotNull" | "orWhereNotNull" | "whereLike" | "andWhereLike" | "orWhereLike" | "whereILike" | "andWhereILike" | "orWhereILike" | "whereNotLike" | "andWhereNotLike" | "orWhereNotLike" | "whereNotILike" | "andWhereNotILike" | "orWhereNotILike" | "whereRegexp" | "andWhereRegexp" | "orWhereRegexp" | "whereNotRegexp" | "andWhereNotRegexp" | "orWhereNotRegexp" | "whereRaw" | "andWhereRaw" | "orWhereRaw" | "whereExists" | "orWhereExists" | "andWhereExists"> & Pick<JsonQueryBuilder<T>, "whereJson" | "andWhereJson" | "orWhereJson" | "whereJsonContains" | "andWhereJsonContains" | "orWhereJsonContains" | "whereJsonNotContains" | "andWhereJsonNotContains" | "orWhereJsonNotContains" | "whereJsonNotContains" | "andWhereJsonNotContains" | "orWhereJsonNotContains" | "whereJsonRaw" | "andWhereJsonRaw" | "orWhereJsonRaw" | "whereJsonNotContains" | "andWhereJsonNotContains" | "orWhereJsonNotContains">;
2405
+ type RelationRetrieveMethod<P extends any> = P extends any[] ? "many" : "one";
2406
+ type SelectableColumn<T extends string = string> = T extends `${infer Table}.${infer Column}.${string}` ? never : T extends `${string} ${string}` ? never : T extends `.${string}` | `${string}.` ? never : T extends `${string}-${string}` ? never : T extends `${string}.${string}` ? T : T;
2407
+ /**
2408
+ * @description A column that can be used in a join statement e.g. `users.id`
2409
+ */
2410
+ type JoinableColumn = `${string}.${string}`;
2411
+ /**
2412
+ * @description Options for streaming queries
2413
+ * @sqlite Ignores the options below
2414
+ */
2415
+ type StreamOptions = {
2416
+ highWaterMark?: number;
2417
+ /** Postgres only */
2418
+ rowMode?: "array";
2419
+ /** Postgres only */
2420
+ batchSize?: number;
2421
+ /** Postgres only */
2422
+ types?: any;
2423
+ /** Mysql only */
2424
+ objectMode?: boolean;
2425
+ };
2426
+ type Cursor<T extends Model, K extends ModelKey<T>> = {
2427
+ key: K;
2428
+ value: string | number;
2429
+ };
2430
+ type PaginateWithCursorOptions<T extends Model, K extends ModelKey<T>> = {
2431
+ discriminator: K;
2432
+ operator?: "<" | ">";
2433
+ orderBy?: "asc" | "desc";
2434
+ };
2435
+
2436
+ type UpdateOptions = {
2437
+ ignoreBeforeUpdateHook?: boolean;
2438
+ };
2439
+
2440
+ type TransactionIsolationLevel = "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
2441
+ type StartTransactionOptions = {
2442
+ isolationLevel?: TransactionIsolationLevel;
2443
+ };
2444
+ /**
2445
+ * @description Options for the transaction execution
2446
+ */
2447
+ type TransactionExecutionOptions = {
2448
+ /**
2449
+ * @description If true, the transaction will throw an error if it is inactive
2450
+ */
2451
+ throwErrorOnInactiveTransaction?: boolean;
2452
+ };
2453
+ type TransactionOptionsOrCallback = StartTransactionOptions | ((trx: Transaction) => Promise<void>);
2454
+ type StartTransactionReturnType<T extends TransactionOptionsOrCallback> = T extends StartTransactionOptions ? Transaction : T extends (trx: Transaction) => Promise<void> ? void : Transaction;
2455
+
2456
+ /**
2457
+ * @description Transaction class, not meant to be used directly, use sql.startTransaction() instead
2458
+ */
2459
+ declare class Transaction {
2460
+ /**
2461
+ * @description The sql data source instance that the transaction is running on here you can both query or execute raw queries
2462
+ * @example
2463
+ * ```ts
2464
+ * import { sql } from "hysteria-orm";
2465
+ * import { User } from "./models/user";
2466
+ *
2467
+ * // Raw queries
2468
+ * const trx = await sql.startTransaction();
2469
+ * await trx.rawQuery("SELECT * FROM users");
2470
+ *
2471
+ * // Model manager
2472
+ * const modelManager = trx.sql.getModelManager(User);
2473
+ * await modelManager.insert({ name: "John Doe" });
2474
+ *
2475
+ * // Query builder
2476
+ * await trx.query(User.table).insert({ name: "John Doe" });
2477
+ *
2478
+ * await trx.commit();
2479
+ * ```
2480
+ */
2481
+ sql: SqlDataSourceWithoutTransaction;
2482
+ /**
2483
+ * @description Whether the transaction is active
2484
+ */
2485
+ isActive: boolean;
2486
+ /**
2487
+ * @description The transaction unique identifier
2488
+ */
2489
+ transactionId: string;
2490
+ private connectionReleased;
2491
+ private isolationLevel?;
2492
+ private isNested;
2493
+ private nestingDepth;
2494
+ constructor(sql: SqlDataSource, isolationLevel?: TransactionIsolationLevel, isNested?: boolean, nestingDepth?: number);
2495
+ /**
2496
+ * @description Creates a new transaction with the same isolation level and same connection using save points
2497
+ * @description If a callback is provided, it will execute the callback and commit or rollback the nested transaction save points based on the callback's success or failure
2498
+ */
2499
+ nestedTransaction(): Promise<Transaction>;
2500
+ nestedTransaction(cb: (trx: Transaction) => Promise<void>): Promise<void>;
2501
+ /**
2502
+ * @description Starts a transaction, automatically handled from the sql data source instance in the `startTransaction` method
2503
+ */
2504
+ startTransaction(): Promise<void>;
2505
+ /**
2506
+ * @description Commit the transaction releasing the connection
2507
+ * @throws {HysteriaError} if the transaction is not active and options.throwErrorOnInactiveTransaction is true
2508
+ * @logs if the transaction is not active and options.throwErrorOnInactiveTransaction is false
2509
+ */
2510
+ commit(options?: TransactionExecutionOptions): Promise<void>;
2511
+ /**
2512
+ * @description Rollback the transaction releasing the connection
2513
+ * @throws {HysteriaError} if the transaction is not active and options.throwErrorOnInactiveTransaction is true
2514
+ * @logs if the transaction is not active and options.throwErrorOnInactiveTransaction is false
2515
+ */
2516
+ rollback(options?: TransactionExecutionOptions): Promise<void>;
2517
+ /**
2518
+ * @description Release the connection, does nothing if the connection is already released
2519
+ */
2520
+ private releaseConnection;
2521
+ private getIsolationLevelQuery;
2522
+ private getSavePointName;
2523
+ }
2524
+
2525
+ type ModelWithoutRelations<T extends Model> = Pick<T, ExcludeRelations<Omit<T, "*">>>;
2526
+ type NumberModelKey<T extends Model> = {
2527
+ [K in keyof T]: T[K] extends number | bigint ? K : never;
2528
+ }[keyof T];
2529
+ type BaseModelMethodOptions = {
2530
+ /**
2531
+ * @description The connection to use for the model, by default the main connection will be used
2532
+ * @description The main connection is the one created by the `sql.connect` method
2533
+ * @example
2534
+ * ```ts
2535
+ * import { sql } from "hysteria-orm";
2536
+ * const customConnection = await sql.connectToSecondarySource({
2537
+ * type: "postgres",
2538
+ * host: "localhost",
2539
+ * username: "root",
2540
+ * password: "root",
2541
+ * database: "test",
2542
+ * port: 5432,
2543
+ * });
2544
+ *
2545
+ * const user = await User.query({ connection: customConnection }).first();
2546
+ * ```
2547
+ */
2548
+ connection?: SqlDataSource | AugmentedSqlDataSource;
2549
+ /**
2550
+ * @description The transaction instance to use for the model
2551
+ */
2552
+ trx?: Transaction;
2553
+ /**
2554
+ * @description Whether to ignore the hooks for the model
2555
+ */
2556
+ ignoreHooks?: boolean;
2557
+ };
2558
+
2559
+ /**
2560
+ * @description Due to query limitations some query builder methods may not be available in a RelationQueryBuilder
2561
+ */
2562
+ type RelationQueryBuilderType<T extends Model, A extends Record<string, any> = {}, R extends Record<string, any> = {}> = Omit<ModelQueryBuilder<T, A, R>, "increment" | "decrement" | "first" | "firstOrFail" | "paginate" | "pluck" | "truncate" | "many" | "one" | "oneOrFail" | "insert" | "insertMany" | "update" | "delete" | "softDelete" | "getSum" | "getAvg" | "getMin" | "getMax" | "getCount" | "getMin" | "getMax" | "getCount">;
2563
+
2564
+ declare class ModelQueryBuilder<T extends Model, A extends Record<string, any> = {}, R extends Record<string, any> = {}> extends QueryBuilder<T> {
2565
+ relation: Relation;
2566
+ protected sqlModelManagerUtils: SqlModelManagerUtils<T>;
2567
+ protected relationQueryBuilders: ModelQueryBuilder<any>[];
2568
+ protected modelSelectedColumns: string[];
2569
+ private modelColumnsMap;
2570
+ private modelColumnsDatabaseNames;
2571
+ protected limitValue?: number;
2572
+ protected offsetValue?: number;
2573
+ performance: {
2574
+ many: (options?: ManyOptions, returnType?: "millis" | "seconds") => Promise<{
2575
+ data: AnnotatedModel<T, A, R>[];
2576
+ time: number;
2577
+ }>;
2578
+ one: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
2579
+ data: AnnotatedModel<T, A, R> | null;
2580
+ time: number;
2581
+ }>;
2582
+ oneOrFail: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
2583
+ data: AnnotatedModel<T, A, R>;
2584
+ time: number;
2585
+ }>;
2586
+ first: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
2587
+ data: AnnotatedModel<T, A, R> | null;
2588
+ time: number;
2589
+ }>;
2590
+ firstOrFail: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
2591
+ data: AnnotatedModel<T, A, R>;
2592
+ time: number;
2593
+ }>;
2594
+ paginate: (page: number, perPage: number, options?: {
2595
+ ignoreHooks?: boolean;
2596
+ }, returnType?: "millis" | "seconds") => Promise<{
2597
+ data: PaginatedData<T, A, R>;
2598
+ time: number;
2599
+ }>;
2600
+ exists: (returnType?: "millis" | "seconds") => Promise<{
2601
+ data: boolean;
2602
+ time: number;
2603
+ }>;
2604
+ paginateWithCursor: (page: number, options: PaginateWithCursorOptions<T, ModelKey<T>>, cursor?: Cursor<T, ModelKey<T>>, returnType?: "millis" | "seconds") => Promise<{
2605
+ data: [CursorPaginatedData<T, A, R>, Cursor<T, ModelKey<T>>];
2606
+ time: number;
2607
+ }>;
2608
+ };
2609
+ constructor(model: typeof Model, sqlDataSource: SqlDataSource);
2610
+ /**
2611
+ * @description Returns true if the query builder is a relation query builder, this changes the behavior of the query builder like limit, offset, etc.
2612
+ * @internal
2613
+ */
2614
+ protected get isRelationQueryBuilder(): boolean;
2615
+ /**
2616
+ * @description Creates a new ModelQueryBuilder instance from a model. Will use the main connection to the database by default.
2617
+ */
2618
+ static from(model: typeof Model, options?: BaseModelMethodOptions): ModelQueryBuilder<InstanceType<typeof model>>;
2619
+ one(options?: OneOptions): Promise<AnnotatedModel<T, A, R> | null>;
2620
+ first(options?: OneOptions): Promise<AnnotatedModel<T, A, R> | null>;
2621
+ oneOrFail(options?: {
2622
+ ignoreHooks?: OneOptions["ignoreHooks"] & {
2623
+ customError?: Error;
2624
+ };
2625
+ }): Promise<AnnotatedModel<T, A, R>>;
2626
+ firstOrFail(options?: {
2627
+ ignoreHooks?: OneOptions["ignoreHooks"] & {
2628
+ customError?: Error;
2629
+ };
2630
+ }): Promise<AnnotatedModel<T, A, R>>;
2631
+ many(options?: ManyOptions): Promise<AnnotatedModel<T, A, R>[]>;
2632
+ chunk(chunkSize: number, options?: ManyOptions): AsyncGenerator<AnnotatedModel<T, A, R>[]>;
2633
+ stream(options?: ManyOptions & StreamOptions, cb?: (stream: PassThrough & AsyncGenerator<AnnotatedModel<T, A, R>>) => void | Promise<void>): Promise<PassThrough & AsyncGenerator<AnnotatedModel<T, A, R>>>;
2634
+ paginateWithCursor<K extends ModelKey<T>>(page: number, options?: PaginateWithCursorOptions<T, K>, cursor?: Cursor<T, K>): Promise<[CursorPaginatedData<T, A, R>, Cursor<T, K>]>;
2635
+ private manyWithPerformance;
2636
+ private oneWithPerformance;
2637
+ private oneOrFailWithPerformance;
2638
+ private firstOrFailWithPerformance;
2639
+ private firstWithPerformance;
2640
+ private paginateWithPerformance;
2641
+ private paginateWithCursorWithPerformance;
2642
+ update(data: Partial<ModelWithoutRelations<T>>, options?: UpdateOptions): Promise<number>;
2643
+ softDelete(options?: SoftDeleteOptions<T>): Promise<number>;
2644
+ delete(options?: DeleteOptions): Promise<number>;
2645
+ getCount(column?: string, options?: {
2646
+ ignoreHooks: boolean;
2647
+ }): Promise<number>;
2648
+ getMax(column: string, options?: {
2649
+ ignoreHooks: boolean;
2650
+ }): Promise<number>;
2651
+ getMin(column: string, options?: {
2652
+ ignoreHooks: boolean;
2653
+ }): Promise<number>;
2654
+ getAvg(column: string, options?: {
2655
+ ignoreHooks: boolean;
2656
+ }): Promise<number>;
2657
+ getSum(column: string, options?: {
2658
+ ignoreHooks: boolean;
2659
+ }): Promise<number>;
2660
+ paginate(page: number, perPage: number, options?: {
2661
+ ignoreHooks: boolean;
2662
+ }): Promise<PaginatedData<T, A, R>>;
2663
+ select<S extends string>(...columns: SelectableColumn<S>[]): this;
2664
+ select(...columns: (ModelKey<T> | "*")[]): this;
2665
+ /**
2666
+ * @description Annotates a column with a SQL method or a simple alias
2667
+ * @description If using a model, the result will be available in the $annotations property of the model, else it will be available in the result of the query
2668
+ * @example
2669
+ * ```ts
2670
+ * const user = await User.query().annotate("max", "id", "maxId").first(); // max(id) as maxId
2671
+ * const user = await User.query().annotate("id", "superId").first(); // id as superId
2672
+ * ```
2673
+ */
2674
+ annotate<K extends string, V = any>(column: string, alias: K): ModelQueryBuilder<T, A & {
2675
+ [P in K]: V;
2676
+ }, R>;
2677
+ annotate<K extends string, S extends SqlMethod, V = CommonSqlMethodReturnType<S>>(sqlMethod: string, column: string, alias: K): ModelQueryBuilder<T, A & {
2678
+ [P in K]: V;
2679
+ }, R>;
2680
+ annotate<K extends string, S extends SqlMethod, V = CommonSqlMethodReturnType<S>>(sqlMethod: S, column: string, alias: K): ModelQueryBuilder<T, A & {
2681
+ [P in K]: V;
2682
+ }, R>;
2683
+ annotate<K extends string, S extends SqlMethod, V = CommonSqlMethodReturnType<S>>(sqlMethod: S, column: string, alias: K): ModelQueryBuilder<T, A & {
2684
+ [P in K]: V;
2685
+ }, R>;
2686
+ /**
2687
+ * @description Removes annotations from the serialized model, by default, annotations are maintained in the serialized model if `annotate` is used
2688
+ */
2689
+ removeAnnotations(): ModelQueryBuilder<T, {}>;
2690
+ /**
2691
+ * @description Fills the relations in the model in the serialized response. Relation must be defined in the model.
2692
+ * @warning Many to many relations have special behavior, since they require a join, a join clause will always be added to the query.
2693
+ * @warning Many to many relations uses the model foreign key for mapping in the `$annotations` property, this property will be removed from the model after the relation is filled.
2694
+ * @warning Foreign keys should always be selected in the relation query builder, otherwise the relation will not be filled.
2695
+ */
2696
+ load<RelationKey extends ModelRelation<T>, IA extends Record<string, any> = {}, IR extends Record<string, any> = {}>(relation: RelationKey, cb: (queryBuilder: RelationQueryBuilderType<RelatedInstance<T, RelationKey>>) => RelationQueryBuilderType<RelatedInstance<T, RelationKey>, IA, IR>): ModelQueryBuilder<T, A, R & {
2697
+ [K in RelationKey]: Awaited<ReturnType<ModelQueryBuilder<RelatedInstance<T, K>, IA, IR>[RelationRetrieveMethod<T[K]>]>>;
2698
+ }>;
2699
+ load<RelationKey extends ModelRelation<T>>(relation: RelationKey, cb?: (queryBuilder: RelationQueryBuilderType<RelatedInstance<T, RelationKey>>) => void): ModelQueryBuilder<T, A, R & {
2700
+ [K in RelationKey]: Awaited<ReturnType<ModelQueryBuilder<RelatedInstance<T, K>, {}, {}>[RelationRetrieveMethod<T[K]>]>>;
2701
+ }>;
2702
+ /**
2703
+ * @description Clears the relations from the query builder
2704
+ */
2705
+ clearRelations(): this;
2706
+ /**
2707
+ * @description Checks if the relation exists in the models and has the given filters, if no callback is provided, it only check if there is at least one record for the relation
2708
+ * @warning All select statements are ignored, since we're only checking if the relation exists, a "select 1" will be added to the Query
2709
+ */
2710
+ havingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, cb?: (queryBuilder: ModelQueryBuilder<RelatedInstance<T, RelationKey>>) => void): this;
2711
+ havingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, operatorOrValue?: BinaryOperatorType$1 | BaseValues$1, maybeValue?: BaseValues$1): this;
2712
+ /**
2713
+ * @description Checks if the relation exists in the models and has the given filters, if no callback is provided, it only check if there is at least one record for the relation
2714
+ * @warning All select statements are ignored, since we're only checking if the relation exists, a "select 1" will be added to the Query
2715
+ */
2716
+ andHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, cb?: (queryBuilder: ModelQueryBuilder<RelatedInstance<T, RelationKey>>) => void): this;
2717
+ andHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, operatorOrValue?: BinaryOperatorType$1 | BaseValues$1, maybeValue?: BaseValues$1): this;
2718
+ /**
2719
+ * @description Checks if the relation exists in the models and has the given filters, if no callback is provided, it only check if there is at least one record for the relation,
2720
+ * @warning All select statements are ignored, since we're only checking if the relation exists, a "select 1" will be added to the Query
2721
+ */
2722
+ orHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, cb?: (queryBuilder: ModelQueryBuilder<RelatedInstance<T, RelationKey>>) => void): this;
2723
+ orHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, operatorOrValue?: BinaryOperatorType$1 | BaseValues$1, maybeValue?: BaseValues$1): this;
2724
+ /**
2725
+ * @description Checks if the relation does not exist in the models and has the given filters, if no callback is provided, it only check if there is no record for the Relation
2726
+ * @warning All select statements are ignored, since we're only checking if the relation exists, a "select 1" will be added to the Query
2727
+ */
2728
+ notHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, cb?: (queryBuilder: ModelQueryBuilder<RelatedInstance<T, RelationKey>>) => void): this;
2729
+ notHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, operatorOrValue?: BinaryOperatorType$1 | BaseValues$1, maybeValue?: BaseValues$1): this;
2730
+ /**
2731
+ * @description Checks if the relation does not exist in the models and has the given filters, if no callback is provided, it only check if there is no record for the relation
2732
+ * @warning All select statements are ignored, since we're only checking if the relation exists, a "select 1" will be added to the Query
2733
+ */
2734
+ andNotHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, cb?: (queryBuilder: ModelQueryBuilder<RelatedInstance<T, RelationKey>>) => void): this;
2735
+ andNotHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, operatorOrValue?: BinaryOperatorType$1 | BaseValues$1, maybeValue?: BaseValues$1): this;
2736
+ /**
2737
+ * @description Checks if the relation does not exist in the models and has the given filters, if no callback is provided, it only check if there is no record for the Relation
2738
+ * @warning All select statements are ignored, since we're only checking if the relation exists, a "select 1" will be added to the Query
2739
+ */
2740
+ orNotHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, cb?: (queryBuilder: ModelQueryBuilder<RelatedInstance<T, RelationKey>>) => void): this;
2741
+ orNotHavingRelated<RelationKey extends ModelRelation<T>>(relation: RelationKey, operatorOrValue?: BinaryOperatorType$1 | BaseValues$1, maybeValue?: BaseValues$1): this;
2742
+ /**
2743
+ * @description Returns a copy of the query builder instance.
2744
+ */
2745
+ clone(): this;
2746
+ /**
2747
+ * @description Recursively processes all relations, including nested ones
2748
+ */
2749
+ protected processRelationsRecursively(models: T[]): Promise<void>;
2750
+ protected mapRelatedModelsToModels<R extends ModelWithoutRelations<T>>(relation: Relation, modelsToFillWithRelations: T[], relatedModels: R[]): void;
2751
+ protected getRelatedModelsForRelation(relationQueryBuilder: ModelQueryBuilder<any>, relation: Relation, models: T[]): Promise<ModelWithoutRelations<T>[]>;
2752
+ protected getRelatedModelsQueryForRelation(relationQueryBuilder: ModelQueryBuilder<any>, relation: Relation, models: T[]): ModelQueryBuilder<T>;
2753
+ protected getFilterValuesFromModelsForRelation(relation: Relation, models: T[]): any[];
2754
+ protected applyHavingRelatedFilter(relationQueryBuilder: ModelQueryBuilder<any>, relation: Relation, operator?: BinaryOperatorType$1, value?: BaseValues$1): void;
2755
+ protected addAdditionalColumnsToModel(row: any, typeofModel: typeof Model): Record<string, any>;
2756
+ }
2757
+
2758
+ declare class ModelManager<T extends Model> {
2759
+ protected sqlDataSource: SqlDataSource;
2760
+ protected sqlType: SqlDataSourceType;
2761
+ protected logs: boolean;
2762
+ protected model: typeof Model;
2763
+ protected modelInstance: T;
2764
+ protected astParser: AstParser;
2765
+ protected interpreterUtils: InterpreterUtils;
2766
+ /**
2767
+ * @description Constructor for ModelManager class.
2768
+ */
2769
+ constructor(model: typeof Model, sqlDataSource: SqlDataSource);
2770
+ /**
2771
+ * @description Finds all records that match the input
2772
+ */
2773
+ find<S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(input?: FindType<T, S, R>): Promise<AnnotatedModel<T, {}>[]>;
2774
+ find<S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(input?: UnrestrictedFindType<T, S, R>): Promise<AnnotatedModel<T, {}>[]>;
2775
+ /**
2776
+ * @description Finds the first record that matches the input
2777
+ */
2778
+ findOne<S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(input: UnrestrictedFindOneType<T, S, R>): Promise<AnnotatedModel<T, {}> | null>;
2779
+ findOne<S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(input: FindOneType<T, S, R>): Promise<AnnotatedModel<T, {}> | null>;
2780
+ /**
2781
+ * @description Finds the first record that matches the input or throws an error
2782
+ */
2783
+ findOneOrFail<S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(input: FindOneType<T, S, R>): Promise<AnnotatedModel<T, {}>>;
2784
+ findOneOrFail<S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(input: UnrestrictedFindOneType<T, S, R>): Promise<AnnotatedModel<T, {}>>;
2785
+ /**
2786
+ * @description Finds a record by its primary key
2787
+ * @description Ignores all model hooks
2788
+ * @throws {HysteriaError} if the model has no primary key
2789
+ */
2790
+ findOneByPrimaryKey(value: string | number, returning?: ModelKey<T>[]): Promise<AnnotatedModel<T, {}> | null>;
2791
+ /**
2792
+ * @description Creates a new record in the database
2793
+ */
2794
+ insert(model: Partial<T>, options?: InsertOptions<T>): Promise<AnnotatedModel<T, {}>>;
2795
+ /**
2796
+ * @description Creates multiple records in the database
2797
+ */
2798
+ insertMany(models: Partial<T>[], options?: InsertOptions<T>): Promise<AnnotatedModel<T, {}>[]>;
2799
+ upsertMany(conflictColumns: string[], columnsToUpdate: string[], data: ModelWithoutRelations<T>[], options?: UpsertOptions<T>): Promise<AnnotatedModel<T, {}>[]>;
2800
+ /**
2801
+ * @description Updates a record, returns the updated record
2802
+ * @description Model is retrieved from the database using the primary key regardless of any model hooks
2803
+ * @description Can only be used if the model has a primary key, use a massive update if the model has no primary key
2804
+ */
2805
+ updateRecord(model: Partial<T>, options?: {
2806
+ returning?: ModelKey<T>[];
2807
+ }): Promise<AnnotatedModel<T, {}>>;
2808
+ /**
2809
+ * @description Deletes a record
2810
+ * @description Can only be used if the model has a primary key, use a massive delete if the model has no primary key
2811
+ */
2812
+ deleteRecord(model: T): Promise<void>;
2813
+ /**
2814
+ * @description Returns a query builder instance
2815
+ */
2816
+ query(): Omit<ModelQueryBuilder<T>, "insert" | "insertMany">;
2817
+ /**
2818
+ * @description Mysql does not return the inserted model, so we need to get the inserted model from the database
2819
+ */
2820
+ private handleMysqlInsert;
2821
+ }
2822
+
2823
+ type TableColumnInfo = {
2824
+ name: string;
2825
+ dataType: string;
2826
+ isNullable: boolean;
2827
+ defaultValue: string | number | boolean | null;
2828
+ length?: number | null;
2829
+ precision?: number | null;
2830
+ scale?: number | null;
2831
+ withTimezone?: boolean | null;
2832
+ };
2833
+ type TableIndexInfo = {
2834
+ name: string;
2835
+ columns: string[];
2836
+ isUnique: boolean;
2837
+ };
2838
+ type TablePrimaryKeyInfo = {
2839
+ name?: string;
2840
+ columns: string[];
2841
+ };
2842
+ type TableSchemaInfo = {
2843
+ columns: TableColumnInfo[];
2844
+ indexes: TableIndexInfo[];
2845
+ foreignKeys: TableForeignKeyInfo[];
2846
+ primaryKey?: TablePrimaryKeyInfo;
2847
+ };
2848
+ type TableForeignKeyInfo = {
2849
+ name?: string;
2850
+ columns: string[];
2851
+ referencedTable: string;
2852
+ referencedColumns: string[];
2853
+ onDelete?: string | null;
2854
+ onUpdate?: string | null;
2855
+ };
2856
+
2857
+ /**
2858
+ * @description The SqlDataSource class is the main class for interacting with the database, it's used to create connections, execute queries, and manage transactions
2859
+ */
2860
+ declare class SqlDataSource extends DataSource {
2861
+ private static instance;
2862
+ private globalTransaction;
2863
+ private sqlType;
2864
+ private models;
2865
+ private ownsPool;
2866
+ /**
2867
+ * @description The pool of connections for the database
2868
+ */
2869
+ sqlPool: SqlPoolType | null;
2870
+ /**
2871
+ * @description Only used in transaction context to specify the connection, not meant to be used directly
2872
+ * @private
2873
+ */
2874
+ sqlConnection: GetConnectionReturnType<SqlDataSourceType> | null;
2875
+ /**
2876
+ * @description Options provided in the sql data source initialization
2877
+ */
2878
+ inputDetails: SqlDataSourceInput;
2879
+ /**
2880
+ * @description Establishes the default singleton connection used by default by all the Models, if not configuration is passed, env variables will be used instead
2881
+ * @description You can continue to use the global sql class exported by hysteria after the connection without having to rely on the return of this function
2882
+ * @throws {HysteriaError} If using models in input, and the model key is already used by the sql data source instance e.g. a model called `connect` is already used by the sql data source instance and will throw an error
2883
+ * @example
2884
+ * ```ts
2885
+ * import { sql } from "hysteria-orm";
2886
+ * const connection = await sql.connect();
2887
+ * // You can use both connection and sql from now own, since `sql` will use the default connection after being connected
2888
+ * connection.query();
2889
+ * sql.query();
2890
+ *
2891
+ * // Models will use the default connection after being connected
2892
+ * User.query(); // Will use the default connection
2893
+ * ```
2894
+ */
2895
+ static connect<T extends Record<string, SqlDataSourceModel> = {}>(input: SqlDataSourceInput<T>, cb?: (sqlDataSource: AugmentedSqlDataSource<T>) => Promise<void> | void): Promise<AugmentedSqlDataSource<T>>;
2896
+ static connect<T extends Record<string, SqlDataSourceModel> = {}>(cb?: (sqlDataSource: AugmentedSqlDataSource<T>) => Promise<void> | void): Promise<SqlDataSource>;
2897
+ /**
2898
+ * @description Get's another database connection and return it, this won't be marked as the default connection used by the Models, for that use the static method `connect`
2899
+ * @description By default not used by the Models, you have to pass it as a parameter to the Models to use it
2900
+ * @throws {HysteriaError} If using models in input, and the model key is already used by the sql data source instance e.g. a model called `connect` is already used by the sql data source instance and will throw an error
2901
+ * @example
2902
+ * ```ts
2903
+ * const anotherSql = await Sql.connectToSecondarySource({
2904
+ * ...connectionData
2905
+ * });
2906
+ *
2907
+ * const user = await User.query({ connection: anotherSql }).many();
2908
+ * ```
2909
+ */
2910
+ static connectToSecondarySource<T extends Record<string, SqlDataSourceModel> = {}>(input: SqlDataSourceInput<T>, cb?: (sqlDataSource: AugmentedSqlDataSource<T>) => Promise<void> | void): Promise<AugmentedSqlDataSource<T>>;
2911
+ static connectToSecondarySource<T extends Record<string, SqlDataSourceModel> = {}>(cb?: (sqlDataSource: AugmentedSqlDataSource<T>) => Promise<void> | void): Promise<SqlDataSource>;
2912
+ /**
2913
+ * @description Creates a new connection and executes a callback with the new instance, the connection is automatically closed after the callback is executed, so it's lifespan is only inside the callback
2914
+ * @description By default not used by the Models, you have to pass it as a parameter to the Models to use it
2915
+ * @throws {HysteriaError} If using models in input, and the model key is already used by the sql data source instance e.g. a model called `connect` is already used by the sql data source instance and will throw an error
2916
+ * @example
2917
+ * ```ts
2918
+ * await Sql.useConnection({
2919
+ * ...connectionData
2920
+ * }, (sql) => {
2921
+ * const user = await User.query({ connection: sql }).many();
2922
+ * });
2923
+ * ```
2924
+ */
2925
+ static useConnection<T extends Record<string, SqlDataSourceModel> = {}>(connectionDetails: UseConnectionInput<T>, cb: (sqlDataSource: AugmentedSqlDataSource<T>) => Promise<void>): Promise<void>;
2926
+ /**
2927
+ * @description Returns the instance of the SqlDataSource
2928
+ * @throws {HysteriaError} If the connection is not established
2929
+ */
2930
+ static getInstance(): SqlDataSource;
2931
+ /**
2932
+ * @description Returns a QueryBuilder instance
2933
+ * @description Query builder from the SqlDataSource instance returns raw data from the database, the data is not parsed or serialized in any way
2934
+ * @description Optimal for performance-critical operations
2935
+ * @description Use Models to have type safety and serialization
2936
+ */
2937
+ static query(table: string): QueryBuilder;
2938
+ /**
2939
+ * @description Creates a table on the database, return the query to be executed to create the table
2940
+ */
2941
+ static createTable(...args: Parameters<Schema["createTable"]>): string;
2942
+ /**
2943
+ * @description Alters a table on the database, return the queries to be executed in order to alter the table
2944
+ */
2945
+ static alterTable(...args: Parameters<Schema["alterTable"]>): string[];
2946
+ /**
2947
+ * @description Starts a global transaction on the database
2948
+ */
2949
+ static startGlobalTransaction(options?: StartTransactionOptions): Promise<Transaction>;
2950
+ /**
2951
+ * @description Commits a global transaction on the database
2952
+ * @throws {HysteriaError} If the global transaction is not started
2953
+ */
2954
+ static commitGlobalTransaction(): Promise<void>;
2955
+ /**
2956
+ * @description Rolls back a global transaction on the database
2957
+ * @throws {HysteriaError} If the global transaction is not started
2958
+ */
2959
+ static rollbackGlobalTransaction(): Promise<void>;
2960
+ /**
2961
+ * @description Starts a transaction on a dedicated connection from the pool and returns a Transaction instance
2962
+ * @param cb if a callback is provided, it will execute the callback and commit or rollback the transaction based on the callback's success or failure
2963
+ * @param options.isolationLevel The isolation level to use for the transaction
2964
+ * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
2965
+ * @param options.endConnection Whether to end the connection after the transaction is committed or rolled back (Default is true, better to leave it this way)
2966
+ * @sqlite ignores the isolation level
2967
+ */
2968
+ static startTransaction(options?: StartTransactionOptions): Promise<Transaction>;
2969
+ static startTransaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
2970
+ /**
2971
+ * @alias startTransaction
2972
+ * @param cb if a callback is provided, it will execute the callback and commit or rollback the transaction based on the callback's success or failure
2973
+ * @param options.isolationLevel The isolation level to use for the transaction
2974
+ * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
2975
+ * @param options.endConnection Whether to end the connection after the transaction is committed or rolled back (Default is true, better to leave it this way)
2976
+ * @sqlite ignores the isolation level
2977
+ */
2978
+ static transaction(options?: StartTransactionOptions): Promise<Transaction>;
2979
+ static transaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
2980
+ static transaction(optionsOrCb?: StartTransactionOptions | ((trx: Transaction) => Promise<void>), maybeOptions?: StartTransactionOptions): Promise<StartTransactionReturnType<TransactionOptionsOrCallback>>;
2981
+ /**
2982
+ * @description Retrieves informations from the database for the given table
2983
+ */
2984
+ static getTableSchema(table: string): Promise<TableSchemaInfo>;
2985
+ /**
2986
+ * @description Closes the current connection
2987
+ */
2988
+ static closeConnection(): Promise<void>;
2989
+ /**
2990
+ * @alias closeConnection
2991
+ */
2992
+ static disconnect(): Promise<void>;
2993
+ /**
2994
+ * @description Executes a raw query on the database
2995
+ */
2996
+ static rawQuery<T = any>(query: string, params?: any[]): Promise<T>;
2997
+ /**
2998
+ * @description Adds a raw statement to an operation like where or update, those raw values won't be used as bindings and will be used as the are
2999
+ * @example
3000
+ * ```ts
3001
+ * import { sql } from "hysteria-orm";
3002
+ *
3003
+ * await User.query().where("name", sql.rawStatement("LOWER(name)"));
3004
+ * ```
3005
+ */
3006
+ static rawStatement(value: string): RawNode;
3007
+ private constructor();
3008
+ /**
3009
+ * @description Returns true if the connection is established
3010
+ */
3011
+ get isConnected(): boolean;
3012
+ /**
3013
+ * @description Clones the SqlDataSource instance
3014
+ * @param options.shouldRecreatePool Whether to recreate the pool of connections for the given driver, by default it's false
3015
+ * @sqlite ignores the shouldRecreatePool option
3016
+ * @returns A new SqlDataSource instance with the same input details
3017
+ */
3018
+ clone(options?: SqlCloneOptions): Promise<this>;
3019
+ /**
3020
+ * @description Returns the type of the database
3021
+ */
3022
+ getDbType(): SqlDataSourceType;
3023
+ /**
3024
+ * @description Returns a QueryBuilder instance
3025
+ * @description Query builder from the SqlDataSource instance uses raw data from the database so the data is not parsed or serialized in any way
3026
+ * @description Optimal for performance-critical operations
3027
+ * @description Use Models to have type safety and serialization
3028
+ */
3029
+ query(table: string): QueryBuilder;
3030
+ /**
3031
+ * @description Return the query to alter the given table schema
3032
+ */
3033
+ alterTable(...args: Parameters<Schema["alterTable"]>): string[];
3034
+ /**
3035
+ * @description Return the query to create the given table schema
3036
+ */
3037
+ createTable(...args: Parameters<Schema["createTable"]>): string;
3038
+ /**
3039
+ * @description Starts a global transaction on the database on the main connection pool, intended to for testing purposes only, don't use it in production
3040
+ */
3041
+ startGlobalTransaction(options?: StartTransactionOptions): Promise<Transaction>;
3042
+ /**
3043
+ * @description Commits a global transaction on the database on the main connection pool, intended to for testing purposes only, don't use it in production
3044
+ * @throws {HysteriaError} If the global transaction is not started
3045
+ */
3046
+ commitGlobalTransaction(options?: TransactionExecutionOptions): Promise<void>;
3047
+ /**
3048
+ * @description Rolls back a global transaction on the database on the main connection pool, intended to for testing purposes only, don't use it in production
3049
+ * @throws {HysteriaError} If the global transaction is not started and options.throwErrorOnInactiveTransaction is true
3050
+ */
3051
+ rollbackGlobalTransaction(options?: TransactionExecutionOptions): Promise<void>;
3052
+ /**
3053
+ * @description Get's a connection from the pool and starts a transaction on the database and returns an already started transaction instance
3054
+ * @param cb if a callback is provided, it will execute the callback and commit or rollback the transaction based on the callback's success or failure
3055
+ * @param options.isolationLevel The isolation level to use for the transaction
3056
+ * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
3057
+ * @param options.endConnection Whether to end the connection after the transaction is committed or rolled back (Default is true, better to leave it this way)
3058
+ * @sqlite ignores the isolation level
3059
+ */
3060
+ startTransaction(options?: StartTransactionOptions): Promise<Transaction>;
3061
+ startTransaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
3062
+ /**
3063
+ * @alias startTransaction
3064
+ * @description Get's a connection from the pool and starts a transaction on the database and returns an already started transaction instance
3065
+ * @param cb if a callback is provided, it will execute the callback and commit or rollback the transaction based on the callback's success or failure
3066
+ * @param options.isolationLevel The isolation level to use for the transaction
3067
+ * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
3068
+ * @param options.endConnection Whether to end the connection after the transaction is committed or rolled back (Default is true, better to leave it this way)
3069
+ * @sqlite ignores the isolation level
3070
+ */
3071
+ transaction(options?: StartTransactionOptions): Promise<Transaction>;
3072
+ transaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
3073
+ /**
3074
+ * @description Returns a ModelManager instance for the given model, it's advised to use Model static methods instead.
3075
+ * @description This is intended to use only if you do not want to use active record pattern
3076
+ */
3077
+ getModelManager<T extends Model>(model: {
3078
+ new (): T;
3079
+ } | typeof Model): ModelManager<T>;
3080
+ /**
3081
+ * @description Returns the current raw driver Pool, you can specify the type of connection you want to get to have better type safety
3082
+ * @throws {HysteriaError} If the connection pool is not established
3083
+ * @example
3084
+ * const mysqlConnection = sql.getPool("mysql"); // mysql2 Pool
3085
+ * const pgConnection = sql.getPool("postgres"); // pg Pool
3086
+ * const sqliteConnection = sql.getPool("sqlite"); // sqlite3 Database
3087
+ */
3088
+ getPool<T extends SqlDataSourceType = typeof this.sqlType>(_specificType?: T): getPoolReturnType<T>;
3089
+ /**
3090
+ * @description Returns a connection from the pool, you can specify the type of connection you want to get to have better type safety
3091
+ * @throws {HysteriaError} If the connection is not established
3092
+ * @example
3093
+ * const mysqlConnection = sql.getConnection("mysql"); // mysql2 PoolConnection
3094
+ * const pgConnection = sql.getConnection("postgres"); // pg PoolClient
3095
+ * const sqliteConnection = sql.getConnection("sqlite"); // sqlite3 Database
3096
+ */
3097
+ getConnection<T extends SqlDataSourceType = typeof this.sqlType>(_specificType?: T): Promise<GetConnectionReturnType<T>>;
3098
+ /**
3099
+ * @description Closes the current connection
3100
+ * @description If there is an active global transaction, it will be rolled back
3101
+ */
3102
+ closeConnection(): Promise<void>;
3103
+ getConnectionDetails(): SqlDataSourceInput;
3104
+ /**
3105
+ * @alias closeConnection
3106
+ */
3107
+ disconnect(): Promise<void>;
3108
+ /**
3109
+ * @description Syncs the schema of the database with the models metadata
3110
+ * @warning This will drop and recreate all the indexes and constraints, use with caution and not in production environments
3111
+ * @param options.transactional Whether to use a transaction to sync the schema, if true it will use a transaction for the entire sync operation, defaults to false
3112
+ * @sqlite Not supported but won't throw an error
3113
+ */
3114
+ syncSchema(options?: {
3115
+ transactional: boolean;
3116
+ }): Promise<void>;
3117
+ /**
3118
+ * @description Executes a raw query on the database
3119
+ */
3120
+ rawQuery<T = any>(query: string, params?: any[]): Promise<T>;
3121
+ /**
3122
+ * @description Adds a raw statement to an operation like where or update, those raw values won't be used as bindings and will be used as the are
3123
+ * @example
3124
+ * ```ts
3125
+ * import { sql } from "hysteria-orm";
3126
+ *
3127
+ * await User.query().where("name", sql.rawStatement("LOWER(name)"));
3128
+ * ```
3129
+ */
3130
+ rawStatement(value: string): RawNode;
3131
+ /**
3132
+ * @description Retrieves information from the database for the given table
3133
+ */
3134
+ getTableSchema(table: string): Promise<TableSchemaInfo>;
3135
+ /**
3136
+ * @description Models provided inside the connection method will always be used for openapi schema generation
3137
+ * @experimental
3138
+ */
3139
+ getModelOpenApiSchema(): (OpenApiModelType & {
3140
+ modelName: string;
3141
+ })[];
3142
+ /**
3143
+ * @description Introspects table columns metadata
3144
+ */
3145
+ getTableInfo(table: string): Promise<TableColumnInfo[]>;
3146
+ /**
3147
+ * @description Introspects table indexes metadata using AST-driven queries
3148
+ */
3149
+ getIndexInfo(table: string): Promise<TableIndexInfo[]>;
3150
+ getForeignKeyInfo(table: string): Promise<TableForeignKeyInfo[]>;
3151
+ /**
3152
+ * @description Introspects table primary key from the database
3153
+ */
3154
+ getPrimaryKeyInfo(table: string): Promise<TablePrimaryKeyInfo | undefined>;
3155
+ private testConnectionQuery;
3156
+ private sanitizeModelKeys;
3157
+ static get isInGlobalTransaction(): boolean;
3158
+ get isInGlobalTransaction(): boolean;
3159
+ /**
3160
+ * @description Returns the models registered on this SqlDataSource instance (as provided in connect input)
3161
+ */
3162
+ get registeredModels(): Record<string, typeof Model>;
3163
+ }
3164
+
3165
+ type SqlDriverSpecificOptions = Omit<DriverSpecificOptions, "mongoOptions" | "redisOptions">;
3166
+ type MysqlConnectionInstance = Awaited<ReturnType<Mysql2Import["createPool"]>>;
3167
+ type PgPoolClientInstance = InstanceType<PgImport["Pool"]>;
3168
+ type SqliteConnectionInstance = InstanceType<Sqlite3Import["Database"]>;
3169
+ type SqlPoolType = MysqlConnectionInstance | PgPoolClientInstance | SqliteConnectionInstance;
3170
+ /**
3171
+ * @description The connection policies for the sql data source
3172
+ * @default By default, the connection policies are not set, so no query will be retried
3173
+ */
3174
+ type ConnectionPolicies = {
3175
+ retry?: {
3176
+ maxRetries?: number;
3177
+ delay?: number;
3178
+ };
3179
+ };
3180
+ type SqlDataSourceModel = typeof Model;
3181
+ /**
3182
+ * @description The input type for the SqlDataSource constructor
3183
+ * @description The connectionPolicies object is used to configure the connection policies for the sql data source
3184
+ */
3185
+ type SqlDataSourceInput<T extends Record<string, SqlDataSourceModel> = {}> = {
3186
+ readonly type?: Exclude<DataSourceType, "mongo">;
3187
+ /**
3188
+ * @description Whether to log the sql queries and other debug information
3189
+ */
3190
+ readonly logs?: boolean;
3191
+ /**
3192
+ * @description The connection policies to use for the sql data source that are not configured in the driverOptions
3193
+ */
3194
+ connectionPolicies?: ConnectionPolicies;
3195
+ /**
3196
+ * @description The query format options to use for the sql data source, it tells how the sql queries should be formatted before being executed and logged
3197
+ */
3198
+ queryFormatOptions?: FormatOptionsWithLanguage;
3199
+ /**
3200
+ * @description The models to use for the sql data source, if used models will be registered in the sql data source instance and will be available for the models to use
3201
+ * @description Models can still be used as standalone entities, but they won't be available for the sql data source instance
3202
+ */
3203
+ models?: T;
3204
+ /**
3205
+ * @description The driver specific options to use for the sql data source, it's used to configure the driver specific options for the sql data source
3206
+ */
3207
+ driverOptions?: SqlDriverSpecificOptions;
3208
+ } & (MysqlSqlDataSourceInput | PostgresSqlDataSourceInput | SqliteDataSourceInput);
3209
+ type UseConnectionInput<T extends Record<string, SqlDataSourceModel> = {}> = {
3210
+ readonly type: Exclude<DataSourceType, "mongo">;
3211
+ readonly logs?: boolean;
3212
+ readonly models?: T;
3213
+ readonly driverOptions?: SqlDriverSpecificOptions;
3214
+ connectionPolicies?: ConnectionPolicies;
3215
+ queryFormatOptions?: FormatOptionsWithLanguage;
3216
+ } & (NotNullableMysqlSqlDataSourceInput | NotNullablePostgresSqlDataSourceInput | NotNullableSqliteDataSourceInput);
3217
+ type SqlDataSourceType = Exclude<DataSourceType, "mongo">;
3218
+ type SqlCloneOptions = {
3219
+ /**
3220
+ * @description Whether to recreate the pool of connections for the given driver, by default it's false
3221
+ * @warning If false, the pool of connections will be reused from the caller instance
3222
+ */
3223
+ shouldRecreatePool?: boolean;
3224
+ };
3225
+ type getPoolReturnType<T = SqlDataSourceType> = T extends "mysql" ? MysqlConnectionInstance : T extends "mariadb" ? MysqlConnectionInstance : T extends "postgres" ? PgPoolClientInstance : T extends "cockroachdb" ? PgPoolClientInstance : T extends "sqlite" ? SqliteConnectionInstance : never;
3226
+ type GetConnectionReturnType<T = SqlDataSourceType> = T extends "mysql" ? PoolConnection : T extends "mariadb" ? PoolConnection : T extends "postgres" ? PoolClient : T extends "cockroachdb" ? PoolClient : T extends "sqlite" ? InstanceType<Sqlite3Import["Database"]> : never;
3227
+ type AugmentedSqlDataSource<T extends Record<string, SqlDataSourceModel> = {}> = SqlDataSource & {
3228
+ [key in keyof T]: T[key];
3229
+ };
3230
+ type SqlDataSourceWithoutTransaction<T extends Record<string, SqlDataSourceModel> = {}> = Pick<SqlDataSource, "sqlPool" | "sqlConnection" | "inputDetails" | "isConnected" | "getDbType" | "clone" | "getModelManager" | "getPool" | "getConnection" | "closeConnection" | "getConnectionDetails" | "disconnect" | "syncSchema" | "rawQuery" | "rawStatement" | "getTableSchema" | "getModelOpenApiSchema" | "getTableInfo" | "getIndexInfo" | "getForeignKeyInfo" | "getPrimaryKeyInfo" | "registeredModels" | "type" | "host" | "port" | "username" | "password" | "database" | "logs" | "query"> & {
3231
+ [key in keyof T]: T[key];
3232
+ };
3233
+
3234
+ type AstParserType = {
3235
+ sql: string;
3236
+ bindings: any[];
3237
+ };
3238
+
3239
+ declare class AstParser {
3240
+ private readonly dbType;
3241
+ private readonly model;
3242
+ constructor(model: typeof Model, dbType: SqlDataSourceType);
3243
+ parse(nodes: (QueryNode | null)[], startBindingIndex?: number, isNestedCondition?: boolean): AstParserType;
3244
+ /**
3245
+ * Map the database type to a common type if shares the same driver (e.g. mysql and mariadb)
3246
+ */
3247
+ private mapCommonDbType;
3248
+ }
3249
+
3250
+ declare class QueryBuilder<T extends Model = any> extends JsonQueryBuilder<T> {
3251
+ model: typeof Model;
3252
+ protected astParser: AstParser;
3253
+ protected unionNodes: UnionNode[];
3254
+ protected withNodes: WithNode[];
3255
+ protected lockQueryNodes: LockNode[];
3256
+ protected isNestedCondition: boolean;
3257
+ protected mustRemoveAnnotations: boolean;
3258
+ protected interpreterUtils: InterpreterUtils;
3259
+ /**
3260
+ * @description Performance methods that return the time that took to execute the query with the result
3261
+ */
3262
+ performance: {
3263
+ many: (returnType?: "millis" | "seconds") => Promise<{
3264
+ data: AnnotatedModel<T, any, any>[];
3265
+ time: number;
3266
+ }>;
3267
+ one: (returnType?: "millis" | "seconds") => Promise<{
3268
+ data: AnnotatedModel<T, any, any> | null;
3269
+ time: number;
3270
+ }>;
3271
+ oneOrFail: (returnType?: "millis" | "seconds") => Promise<{
3272
+ data: any;
3273
+ time: number;
3274
+ }>;
3275
+ first: (returnType?: "millis" | "seconds") => Promise<{
3276
+ data: AnnotatedModel<T, any, any> | null;
3277
+ time: number;
3278
+ }>;
3279
+ firstOrFail: (returnType?: "millis" | "seconds") => Promise<{
3280
+ data: any;
3281
+ time: number;
3282
+ }>;
3283
+ paginate: (page: number, perPage: number, returnType?: "millis" | "seconds") => Promise<{
3284
+ data: PaginatedData<T>;
3285
+ time: number;
3286
+ }>;
3287
+ paginateWithCursor: (page: number, options: PaginateWithCursorOptions<T, ModelKey<T>>, cursor?: Cursor<T, ModelKey<T>>, returnType?: "millis" | "seconds") => Promise<{
3288
+ data: [CursorPaginatedData<T>, Cursor<T, ModelKey<T>>];
3289
+ time: number;
3290
+ }>;
3291
+ exists: (returnType?: "millis" | "seconds") => Promise<{
3292
+ data: boolean;
3293
+ time: number;
3294
+ }>;
3295
+ };
3296
+ constructor(model: typeof Model, sqlDataSource?: SqlDataSource);
3297
+ protected get fromTable(): string;
3298
+ /**
3299
+ * @description Executes the query and returns true if the query returns at least one result, false otherwise.
3300
+ */
3301
+ exists(): Promise<boolean>;
3302
+ /**
3303
+ * @description Executes the query and returns true if the query returns at least one result, false otherwise.
3304
+ * @description Returns the time that took to execute the query
3305
+ */
3306
+ existsWithPerformance(returnType?: "millis" | "seconds"): Promise<{
3307
+ data: boolean;
3308
+ time: number;
3309
+ }>;
3310
+ /**
3311
+ * @description Executes the query and retrieves multiple results.
3312
+ */
3313
+ many(): Promise<AnnotatedModel<T, any, any>[]>;
3314
+ /**
3315
+ * @description Executes the query and retrieves a single column from the results.
3316
+ * @param key - The column to retrieve from the results, must be a Model Column
3317
+ */
3318
+ pluck<K extends ModelKey<T>>(key: K): Promise<PluckReturnType<T, K>>;
3319
+ /**
3320
+ * @description Executes the query and retrieves a single result.
3321
+ */
3322
+ one(): Promise<AnnotatedModel<T, any, any> | null>;
3323
+ /**
3324
+ * @alias one
3325
+ */
3326
+ first(): Promise<AnnotatedModel<T, any, any> | null>;
3327
+ /**
3328
+ * @description Executes the query and retrieves the first result. Fail if no result is found.
3329
+ */
3330
+ oneOrFail(): Promise<AnnotatedModel<T, any, any>>;
3331
+ /**
3332
+ * @alias oneOrFail
3333
+ */
3334
+ firstOrFail(): Promise<AnnotatedModel<T, any, any>>;
3335
+ /**
3336
+ * @description Executes the query and returns a node readable stream.
3337
+ * @description If used by a model query builder, it will serialize the models and apply the hooks and relations.
3338
+ * @postgres needs the pg-query-stream package in order to work
3339
+ * @throws If using postgres and the `pg-query-stream` package is not installed
3340
+ */
3341
+ stream<M extends Model = T>(options?: StreamOptions, cb?: (stream: PassThrough & AsyncGenerator<AnnotatedModel<M, any, any>>) => void | Promise<void>): Promise<PassThrough & AsyncGenerator<AnnotatedModel<M, {}, {}>>>;
3342
+ /**
3343
+ * @description Chunks the query into smaller queries, it returns a generator of the chunks
3344
+ * @description It will continue to yield chunks until the query returns no results
3345
+ * @description Useful for large queries that need to be processed in chunks
3346
+ * @warning overrides limit and offset set before in the query builder
3347
+ * @param chunkSize - The size of the chunk
3348
+ * @returns a generator of the chunks
3349
+ * @example
3350
+ * const chunks = await queryBuilder.chunk(100);
3351
+ * // first chunk
3352
+ * const firstChunk = await chunks.next();
3353
+ * console.log(firstChunk.value);
3354
+ * // second chunk
3355
+ * const secondChunk = await chunks.next();
3356
+ * console.log(secondChunk.value);
3357
+ * // third chunk
3358
+ * const thirdChunk = await chunks.next();
3359
+ * console.log(thirdChunk.value);
3360
+ *
3361
+ * @example
3362
+ * const chunkSize = 3;
3363
+ * const chunks = [];
3364
+ * const query = sql.query("users").orderBy("name", "asc");
3365
+ * for await (const chunk of sql.chunk(chunkSize)) {
3366
+ * chunks.push(chunk);
3367
+ * }
3368
+ *
3369
+ * console.log(chunks);
3370
+ */
3371
+ chunk(chunkSize: number): AsyncGenerator<any[], void, unknown>;
3372
+ /**
3373
+ * @description Executes the query and retrieves multiple paginated results.
3374
+ * @description Overrides the limit and offset clauses in order to paginate the results.
3375
+ * @description Allows to avoid offset clause that can be inefficient for large datasets
3376
+ * @description If using a model query builder, primary key is used as discriminator by default
3377
+ * @param options - The options for the paginate with cursor
3378
+ * @param options.discriminator - The discriminator to use for the paginate with Cursor pagination
3379
+ * @param options.operator - The operator to use for the paginate with Cursor pagination
3380
+ * @param options.orderBy - The order by to use for the paginate with Cursor pagination
3381
+ * @param cursor - The cursor to use for the paginate with Cursor pagination
3382
+ * @warning If no order by clause is present in the query, the query will add an order by clause to the query `orderBy(discriminator, "asc")`
3383
+ * @returns the pagination metadata and the cursor for the next page
3384
+ */
3385
+ paginateWithCursor<K extends ModelKey<T>>(limit: number, options: PaginateWithCursorOptions<T, K>, cursor?: Cursor<T, K>): Promise<[CursorPaginatedData<T>, Cursor<T, K>]>;
3386
+ /**
3387
+ * @description Selects a subquery, subquery must return a single column
3388
+ */
3389
+ selectSubQuery(cbOrQueryBuilder: ((subQuery: QueryBuilder<T>) => void) | QueryBuilder<any>, alias: string): this;
3390
+ /**
3391
+ * @description Locks the table for update
3392
+ * @param skipLocked - If true, the query will skip locked rows
3393
+ * @sqlite does not support skipping locked rows, it will be ignored
3394
+ */
3395
+ lockForUpdate(options?: {
3396
+ skipLocked?: boolean;
3397
+ noWait?: boolean;
3398
+ }): this;
3399
+ /**
3400
+ * @description Locks the table for share
3401
+ * @param skipLocked - If true, the query will skip locked rows
3402
+ * @sqlite does not support skipping locked rows, it will be ignored
3403
+ */
3404
+ forShare(options?: {
3405
+ skipLocked?: boolean;
3406
+ noWait?: boolean;
3407
+ }): this;
3408
+ /**
3409
+ * @description Adds a UNION to the query.
3410
+ */
3411
+ union(query: string, bindings?: any[]): this;
3412
+ union(cb: UnionCallBack<T>): this;
3413
+ /**
3414
+ * @description Adds a UNION ALL to the query.
3415
+ */
3416
+ unionAll(query: string, bindings?: any[]): this;
3417
+ unionAll(cb: UnionCallBack<T>): this;
3418
+ unionAll(queryBuilder: QueryBuilder<any>): this;
3419
+ /**
3420
+ * @description Increments the value of a column by a given amount, column must be of a numeric type in order to be incremented
3421
+ * @typeSafe - In typescript, only numeric columns of the model will be accepted if using a Model
3422
+ * @default value + 1
3423
+ * @returns the number of affected rows
3424
+ */
3425
+ increment(column: NumberModelKey<T>, value?: number): Promise<number>;
3426
+ /**
3427
+ * @description Decrements the value of a column by a given amount, column must be of a numeric type in order to be decremented
3428
+ * @typeSafe - In typescript, only numeric columns of the model will be accepted if using a Model
3429
+ * @default value - 1
3430
+ * @returns the number of affected rows
3431
+ */
3432
+ decrement(column: NumberModelKey<T>, value?: number): Promise<number>;
3433
+ /**
3434
+ * @description Executes the query and retrieves the count of results, it ignores all select, group by, order by, limit and offset clauses if they are present.
3435
+ */
3436
+ getCount(column?: string): Promise<number>;
3437
+ /**
3438
+ * @description Executes the query and retrieves the maximum value of a column, it ignores all select, group by, order by, limit and offset clauses if they are present.
3439
+ */
3440
+ getMax(column: string): Promise<number>;
3441
+ /**
3442
+ * @description Executes the query and retrieves the minimum value of a column, it ignores all select, group by, order by, limit and offset clauses if they are present.
3443
+ */
3444
+ getMin(column: string): Promise<number>;
3445
+ /**
3446
+ * @description Executes the query and retrieves the average value of a column, it ignores all select, group by, order by, limit and offset clauses if they are present.
3447
+ */
3448
+ getAvg(column: string): Promise<number>;
3449
+ /**
3450
+ * @description Executes the query and retrieves the sum of a column, it ignores all select, group by, order by, limit and offset clauses if they are present.
3451
+ */
3452
+ getSum(column: string): Promise<number>;
3453
+ /**
3454
+ * @description Executes the query and retrieves multiple paginated results.
3455
+ * @description Overrides the limit and offset clauses in order to paginate the results.
3456
+ */
3457
+ paginate(page: number, perPage: number): Promise<PaginatedData<T>>;
3458
+ /**
3459
+ * @description Overrides the from clause in the query.
3460
+ */
3461
+ from(table: string, alias?: string): this;
3462
+ from(cb: (qb: QueryBuilder<T>) => void, alias: string): this;
3463
+ /**
3464
+ * @description Adds a CTE to the query using a callback to build the subquery.
3465
+ */
3466
+ with(alias: string, cb: (qb: QueryBuilder<T>) => void): this;
3467
+ /**
3468
+ * @description Adds a recursive CTE to the query using a callback to build the subquery.
3469
+ */
3470
+ withRecursive(alias: string, cb: (qb: QueryBuilder<T>) => void): this;
3471
+ /**
3472
+ * @description Adds a materialized CTE to the query using a callback to build the subquery.
3473
+ * @postgres only
3474
+ * @throws HysteriaError if the database type is not postgres
3475
+ */
3476
+ withMaterialized(alias: string, cb: (qb: QueryBuilder<T>) => void): this;
3477
+ /**
3478
+ * @description Insert record into a table
3479
+ * @param returning - The columns to return from the query, only supported by postgres and cockroachdb - default is "*"
3480
+ * @returns raw driver response
3481
+ */
3482
+ insert(data: Record<string, any>, returning?: string[]): Promise<T>;
3483
+ /**
3484
+ * @description Insert multiple records into a table
3485
+ * @param returning - The columns to return from the query, only supported by postgres and cockroachdb - default is "*"
3486
+ * @returns raw driver response
3487
+ */
3488
+ insertMany(data: Record<string, any>[], returning?: string[]): Promise<T[]>;
3489
+ /**
3490
+ * @description Updates records from a table
3491
+ * @returns the number of affected rows
3492
+ */
3493
+ update(data: Record<string, any>): Promise<number>;
3494
+ /**
3495
+ * @description Deletes all records from a table
3496
+ */
3497
+ truncate(): Promise<void>;
3498
+ /**
3499
+ * @description Deletes records from a table
3500
+ * @returns the number of affected rows
3501
+ */
3502
+ delete(): Promise<number>;
3503
+ /**
3504
+ * @description Soft deletes records from a table
3505
+ * @default column - 'deletedAt'
3506
+ * @default value - The current date and time in UTC timezone in the format "YYYY-MM-DD HH:mm:ss"
3507
+ * @returns the number of affected rows
3508
+ */
3509
+ softDelete(options?: SoftDeleteOptions<T>): Promise<number>;
3510
+ /**
3511
+ * @description Returns the query with the parameters bound to the query
3512
+ */
3513
+ toQuery(dbType?: SqlDataSourceType): string;
3514
+ /**
3515
+ * @description Returns the query with database driver placeholders and the params
3516
+ */
3517
+ unWrap(dbType?: SqlDataSourceType): ReturnType<typeof AstParser.prototype.parse>;
3518
+ /**
3519
+ * @description Returns a deep clone of the query builder instance.
3520
+ */
3521
+ clone(): this;
3522
+ protected clearLockQuery(): this;
3523
+ protected clearUnionQuery(): this;
3524
+ protected clearWithQuery(): this;
3525
+ extractQueryNodes(): QueryNode[];
3526
+ protected clearForFunctions(): this;
3527
+ /**
3528
+ * @description Makes a many query and returns the time that took to execute that query
3529
+ */
3530
+ private manyWithPerformance;
3531
+ /**
3532
+ * @description Makes a one query and returns the time that took to execute that query
3533
+ */
3534
+ private oneWithPerformance;
3535
+ /**
3536
+ * @alias oneWithPerformance
3537
+ */
3538
+ private firstWithPerformance;
3539
+ /**
3540
+ * @alias oneOrFailWithPerformance
3541
+ */
3542
+ private firstOrFailWithPerformance;
3543
+ private paginateWithPerformance;
3544
+ private paginateWithCursorWithPerformance;
3545
+ /**
3546
+ * @description Makes a one or fail query and returns the time that took to execute that query
3547
+ */
3548
+ private oneOrFailWithPerformance;
3549
+ }
3550
+
3551
+ type UnionCallBack<T extends Model> = (queryBuilder: QueryBuilder<T>) => QueryBuilder<T>;
3552
+ type SqlMethod = "sum" | "avg" | "max" | "min" | "count" | "upper" | "lower" | "trim" | "length" | "cast" | "convert" | "abs" | "round" | "floor" | "ceil";
3553
+
3554
+ type ModelInstanceType<O> = O extends typeof Model ? InstanceType<O> : never;
3555
+ type FetchHooks = "beforeFetch" | "afterFetch";
3556
+ type OneOptions = {
3557
+ ignoreHooks?: FetchHooks[];
3558
+ };
3559
+ type ManyOptions = {
3560
+ ignoreHooks?: FetchHooks[];
3561
+ };
3562
+ type AnnotatedModel<T extends Model, A extends object = {}, R extends object = {}> = [keyof A] extends [never] ? ModelWithoutRelations<T> & R : ModelWithoutRelations<T> & {
3563
+ $annotations: A;
3564
+ } & R;
3565
+ type CommonSqlMethodReturnType<T extends SqlMethod> = T extends "count" | "sum" | "avg" | "min" | "max" ? number : T extends "upper" | "lower" | "trim" ? string : T extends "length" ? number : T extends "cast" | "convert" ? any : T extends "abs" | "round" | "floor" | "ceil" ? number : any;
3566
+ type RelatedInstance<M extends Model, K extends ModelRelation<M>> = M[K] extends (infer R)[] ? R extends Model ? R : never : M[K] extends Model ? M[K] : never;
3567
+
3568
+ declare class BelongsTo extends Relation {
3569
+ type: RelationEnum;
3570
+ foreignKey: string;
3571
+ constructor(relatedModel: typeof Model, columnName: string, foreignKey: string);
3572
+ }
3573
+
3574
+ declare class HasMany extends Relation {
3575
+ type: RelationEnum;
3576
+ foreignKey: string;
3577
+ constructor(relatedModel: typeof Model, columnName: string, foreignKey: string);
3578
+ }
3579
+
3580
+ declare class HasOne extends Relation {
3581
+ type: RelationEnum;
3582
+ foreignKey: string;
3583
+ constructor(relatedModel: typeof Model, columnName: string, foreignKey: string);
3584
+ }
3585
+
3586
+ declare class ManyToMany extends Relation {
3587
+ type: RelationEnum;
3588
+ /**
3589
+ * @description The model that establishes the relation
3590
+ */
3591
+ primaryModel: string;
3592
+ /**
3593
+ * @description The model that is being related to
3594
+ */
3595
+ relatedModel: string;
3596
+ /**
3597
+ * @description The foreign key of the related model in the through table
3598
+ */
3599
+ rightForeignKey: string;
3600
+ /**
3601
+ * @description The table that joins the two models
3602
+ */
3603
+ throughModel: string;
3604
+ /**
3605
+ * @description The foreign key of the primary model in the through table
3606
+ */
3607
+ leftForeignKey: string;
3608
+ constructor(model: typeof Model, columnName: string, data: {
3609
+ primaryModel: string;
3610
+ throughModel: string;
3611
+ leftForeignKey: string;
3612
+ rightForeignKey: string;
3613
+ });
3614
+ }
3615
+
3616
+ type UpsertOptions<T extends Model> = {
3617
+ ignoreHooks?: boolean;
3618
+ updateOnConflict?: boolean;
3619
+ returning?: ModelKey<T>[];
3620
+ };
3621
+ type InsertOptions<T extends Model> = {
3622
+ ignoreHooks?: boolean;
3623
+ returning?: ModelKey<T>[];
3624
+ };
3625
+ type ExcludeRelations<T> = {
3626
+ [K in keyof T]: T[K] extends (Model[] | HasMany) | (Model | HasMany) | (Model | BelongsTo) | (Model[] | BelongsTo) | (Model | HasOne) | (Model[] | HasOne) | (Model | ManyToMany) | (Model[] | ManyToMany) | ((...args: any[]) => any) ? never : K;
3627
+ }[keyof T];
3628
+ type OnlyRelations<T> = {
3629
+ [K in keyof T]: T[K] extends Model[] | Model ? K : never;
3630
+ }[keyof T];
3631
+ type OnlyM2MRelations<T> = {
3632
+ [K in keyof T]: K extends string ? (T[K] extends Model[] ? K : never) : never;
3633
+ }[keyof T];
3634
+ type WhereType<T> = {
3635
+ [K in keyof T]?: T[K];
3636
+ };
3637
+ type ModelKey<T extends Model> = {
3638
+ [K in keyof T]: T[K] extends (Model[] | HasMany) | (Model | HasMany) | (Model | BelongsTo) | (Model[] | BelongsTo) | (Model | HasOne) | (Model[] | HasOne) ? never : K extends "*" ? never : K;
3639
+ }[keyof T];
3640
+ type ModelRelation<T extends Model> = OnlyRelations<T>;
3641
+ type OrderByChoices = "asc" | "desc";
3642
+ type OrderByType<T extends Model> = {
3643
+ [K in keyof T]?: OrderByChoices;
3644
+ } & {
3645
+ [K in string]?: OrderByChoices;
3646
+ };
3647
+ type UnrestrictedFindOneType<T extends Model, S extends ModelKey<T>[] = any[], R extends ModelRelation<T>[] = never[]> = {
3648
+ select?: S;
3649
+ relations?: R;
3650
+ ignoreHooks?: FetchHooks[];
3651
+ where?: Record<string, any>;
3652
+ orderBy?: OrderByType<T>;
3653
+ groupBy?: string[];
3654
+ offset?: number;
3655
+ };
3656
+ type UnrestrictedFindType<T extends Model, S extends ModelKey<T>[] = any[], R extends ModelRelation<T>[] = never[]> = Omit<UnrestrictedFindOneType<T, S, R>, "throwErrorOnNull"> & {
3657
+ limit?: number;
3658
+ };
3659
+ type FindOneType<T extends Model, S extends ModelKey<T>[] = any[], R extends ModelRelation<T>[] = never[]> = {
3660
+ select?: S;
3661
+ offset?: number;
3662
+ relations?: R;
3663
+ orderBy?: OrderByType<T>;
3664
+ groupBy?: ModelKey<T>[];
3665
+ where?: WhereType<T>;
3666
+ ignoreHooks?: FetchHooks[];
3667
+ };
3668
+ type FindType<T extends Model, S extends ModelKey<T>[] = any[], R extends ModelRelation<T>[] = never[]> = Omit<FindOneType<T, S, R>, "throwErrorOnNull"> & {
3669
+ limit?: number;
3670
+ };
3671
+ type FindReturnType<T extends Model, S extends ModelKey<T>[] = any[], R extends ModelRelation<T>[] = never[]> = S extends readonly any[] ? S[number] extends never ? ModelWithoutRelations<T> & {
3672
+ [K in R[number] & keyof T]: T[K];
3673
+ } : {
3674
+ [K in S[number] & keyof T]: T[K];
3675
+ } & {
3676
+ [K in R[number] & keyof T]: T[K];
3677
+ } : ModelWithoutRelations<T> & {
3678
+ [K in R[number] & keyof T]: T[K];
3679
+ };
3680
+
3681
+ /**
3682
+ * @description Represents a Table in the Database
3683
+ */
3684
+ declare abstract class Model extends Entity {
3685
+ private "*";
3686
+ /**
3687
+ * @description The column used to soft delete a record, default is deletedAt
3688
+ */
3689
+ static softDeleteColumn: string;
3690
+ /**
3691
+ * @description The value used to soft delete a record, default is the current date and time
3692
+ * @default format: "YYYY-MM-DD HH:mm:ss" in UTC timezone
3693
+ */
3694
+ static softDeleteValue: string;
3695
+ /**
3696
+ * @description The sql sqlInstance generated by SqlDataSource.connect
3697
+ */
3698
+ static sqlInstance: SqlDataSource;
3699
+ /**
3700
+ * @description Getter for the table name of the model
3701
+ */
3702
+ static get table(): string;
3703
+ /**
3704
+ * @description Setter for the table name of the model
3705
+ */
3706
+ static set table(value: string);
3707
+ /**
3708
+ * @description Getter for the primary key of the model
3709
+ */
3710
+ static get primaryKey(): string | undefined;
3711
+ /**
3712
+ * @description Constructor for the model, it's not meant to be used directly, it just initializes the $annotations, it's advised to only use the static methods to interact with the database to save the model
3713
+ * @description Using the constructor could lead to unexpected behavior, if you want to create a new record use the insert method
3714
+ * @deprecated
3715
+ */
3716
+ constructor();
3717
+ /**
3718
+ * @description Returns all the records for the given model
3719
+ */
3720
+ static all<T extends Model>(this: new () => T | typeof Model, options?: BaseModelMethodOptions): Promise<AnnotatedModel<T, {}>[]>;
3721
+ /**
3722
+ * @description Gives a query sqlInstance for the given model
3723
+ */
3724
+ static query<T extends Model>(this: new () => T | typeof Model, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): ModelQueryBuilder<T>;
3725
+ /**
3726
+ * @description Finds the first record in the database
3727
+ * @deprecated Used only for debugging purposes, use findOne or query instead
3728
+ */
3729
+ static first<T extends Model>(this: new () => T | typeof Model, options?: BaseModelMethodOptions): Promise<AnnotatedModel<T, {}> | null>;
3730
+ /**
3731
+ * @description Finds records for the given model
3732
+ */
3733
+ static find<T extends Model, S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(this: new () => T | typeof Model, findOptions?: FindType<T, S, R> | UnrestrictedFindType<T, S, R>, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<FindReturnType<T, S, R>[]>;
3734
+ /**
3735
+ * @description Finds a record for the given model or throws an error if it doesn't exist
3736
+ */
3737
+ static findOneOrFail<T extends Model, S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(this: new () => T | typeof Model, findOneOptions: (FindOneType<T, S, R> | UnrestrictedFindOneType<T, S, R>) & {
3738
+ customError?: Error;
3739
+ }, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<FindReturnType<T, S, R>>;
3740
+ /**
3741
+ * @description Finds a record for the given model
3742
+ */
3743
+ static findOne<T extends Model, S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(this: new () => T | typeof Model, findOneOptions: (FindOneType<T, S, R> | UnrestrictedFindOneType<T, S, R>) & BaseModelMethodOptions, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<FindReturnType<T, S, R> | null>;
3744
+ /**
3745
+ * @description Finds records for the given column and value
3746
+ */
3747
+ static findBy<T extends Model, S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(this: new () => T | typeof Model, column: S, value: string | number | boolean | Date | null, options?: BaseModelMethodOptions): Promise<FindReturnType<T, S, R>[]>;
3748
+ /**
3749
+ * @description Finds the first record for the given column and value
3750
+ */
3751
+ static findOneBy<T extends Model, S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(this: new () => T | typeof Model, column: ModelKey<T>, value: string | number | boolean | Date | null, options?: BaseModelMethodOptions): Promise<FindReturnType<T, S, R> | null>;
3752
+ /**
3753
+ * @description Finds a record for the given model for the given value, the model must have a primary key defined else it will throw an error
3754
+ */
3755
+ static findOneByPrimaryKey<T extends Model, S extends ModelKey<T>[] = never[], R extends ModelRelation<T>[] = never[]>(this: new () => T | typeof Model, value: string | number, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<FindReturnType<T, S, R> | null>;
3756
+ /**
3757
+ * @description Refreshes a model from the database, the model must have a primary key defined
3758
+ */
3759
+ static refresh<T extends Model>(this: new () => T | typeof Model, model: T, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<AnnotatedModel<T, {}> | null>;
3760
+ /**
3761
+ * @description Saves a new record to the database
3762
+ * @description $annotations will be ignored if set in the modelData and won't be returned in the response
3763
+ * @warning If not using postgres and the model has no primary key, the model will be saved, but it won't be possible to retrieve it so at that point it will be returned as null, this is not typed as Model | null for type safety reasons
3764
+ * @mysql If no Primary Key is present in the model definition, the exact input model will be returned
3765
+ * @sqlite If no Primary Key is present in the model definition, the exact input will be returned
3766
+ * @sqlite Returning Not supported and won't have effect
3767
+ */
3768
+ static insert<T extends Model>(this: new () => T | typeof Model, modelData: Partial<ModelWithoutRelations<T>>, options?: BaseModelMethodOptions & InsertOptions<T>): Promise<AnnotatedModel<T, {}>>;
3769
+ /**
3770
+ * @description Saves multiple records to the database
3771
+ * @description $annotations will be ignored if set in the modelData and won't be returned in the response
3772
+ * @warning If not using postgres and the model has no primary key, the models will be saved, but it won't be possible to retrieve them so at that point they will be returned as an empty array
3773
+ * @mysql If no Primary Key is present in the model definition, the exact input model will be returned
3774
+ * @sqlite If no Primary Key is present in the model definition, the exact input will be returned
3775
+ * @sqlite Returning Not supported and won't have effect
3776
+ */
3777
+ static insertMany<T extends Model>(this: new () => T | typeof Model, modelsData: Partial<ModelWithoutRelations<T>>[], options?: BaseModelMethodOptions & InsertOptions<T>): Promise<AnnotatedModel<T, {}>[]>;
3778
+ /**
3779
+ * @description Syncs in the through table the given models for the given relation
3780
+ * @param relation The many to many relation to sync, this is not type safe since many to many relations defined at a decorator level
3781
+ * @param leftModel The source (left) model instance to synchronize in the many-to-many relation.
3782
+ * @param rightModels The target (right) model instances to associate with the left model in the join table.
3783
+ * @param joinTableCustomData Optional function that returns custom data for each join table row (receives rightModel and index)
3784
+ * @param options.caseConvention Optional. Controls naming convention for left/right foreign keys in the join table. Defaults to the left model's convention; set to `none` to disable.
3785
+ * @warning Use only when the join table contains no business logic beyond foreign keys. For business logic, define and use a dedicated join model.
3786
+ * @warning This method does not trigger hooks on the join table, even if a Model exists. Use the join model's `insertMany` for hook support.
3787
+ * @throws {HysteriaError} If the specified relation does not exist on the model.
3788
+ * @throws {HysteriaError} If the specified relation is not a many-to-many relation.
3789
+ */
3790
+ static sync<T extends Model, R extends OnlyM2MRelations<T>>(this: new () => T | typeof Model, relation: R, leftModel: T, rightModels: T[R] extends any[] ? T[R] : T[R][], joinTableCustomData?: (rightModel: T[R] extends any[] ? T[R][number] : T[R], index: number) => Record<string, any>, options?: BaseModelMethodOptions & {
3791
+ caseConvention?: CaseConvention;
3792
+ }): Promise<void>;
3793
+ /**
3794
+ * @description Updates a record, returns the updated record
3795
+ * @description Model is retrieved from the database using the primary key regardless of any model hooks
3796
+ * @description Can only be used if the model has a primary key, use a massive update if the model has no primary key
3797
+ * @throws {HysteriaError} If the model has no primary key
3798
+ */
3799
+ static updateRecord<T extends Model>(this: new () => T | typeof Model, modelSqlInstance: Partial<T>, updatePayload?: ModelWithoutRelations<T>, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<AnnotatedModel<T, {}>>;
3800
+ /**
3801
+ * @description Finds the first record or creates a new one if it doesn't exist
3802
+ */
3803
+ static firstOrInsert<T extends Model, O extends boolean = false>(this: new () => T | typeof Model, searchCriteria: Partial<ModelWithoutRelations<T>>, createData: Partial<ModelWithoutRelations<T>>, options?: Omit<BaseModelMethodOptions, "ignoreHooks"> & {
3804
+ fullResponse?: O;
3805
+ }): Promise<O extends true ? {
3806
+ isNew: boolean;
3807
+ model: T;
3808
+ } : T>;
3809
+ /**
3810
+ * @description Updates or creates a new record
3811
+ */
3812
+ static upsert<T extends Model>(this: new () => T | typeof Model, searchCriteria: Partial<ModelWithoutRelations<T>>, data: Partial<ModelWithoutRelations<T>>, options?: UpsertOptions<T> & BaseModelMethodOptions): Promise<AnnotatedModel<T, {}>>;
3813
+ /**
3814
+ * @description Updates or creates multiple records
3815
+ * @param {updateOnConflict} If true, the record will be updated if it exists, otherwise it will be ignored
3816
+ */
3817
+ static upsertMany<T extends Model>(this: new () => T | typeof Model, conflictColumns: ModelKey<T>[], data: Partial<ModelWithoutRelations<T>>[], options?: UpsertOptions<T> & BaseModelMethodOptions): Promise<AnnotatedModel<T, {}>[]>;
3818
+ /**
3819
+ * @description Deletes a record to the database
3820
+ */
3821
+ static deleteRecord<T extends Model>(this: new () => T | typeof Model, modelSqlInstance: T, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<void>;
3822
+ /**
3823
+ * @description Soft Deletes a record to the database
3824
+ * @description default column: deletedAt
3825
+ * @description default value: The current date and time in UTC timezone in the format "YYYY-MM-DD HH:mm:ss"
3826
+ * @description You can override the column and value by providing the column and value on the static properties of the model `softDeleteColumn` and `softDeleteValue`
3827
+ */
3828
+ static softDelete<T extends Model>(this: new () => T | typeof Model, modelSqlInstance: T, softDeleteOptions?: {
3829
+ column?: ModelKey<T>;
3830
+ value?: string | number | boolean | Date;
3831
+ }, options?: Omit<BaseModelMethodOptions, "ignoreHooks">): Promise<AnnotatedModel<T, {}>>;
3832
+ /**
3833
+ * @description Truncates the table for the given model
3834
+ */
3835
+ static truncate<T extends Model>(this: new () => T | typeof Model, options?: BaseModelMethodOptions): Promise<void>;
3836
+ /**
3837
+ * @description Returns the table info for the model form the database
3838
+ */
3839
+ static getTableInfo(): Promise<TableColumnInfo[]>;
3840
+ /**
3841
+ * @description Returns the index info for the model form the database
3842
+ */
3843
+ static getIndexInfo(): Promise<TableIndexInfo[]>;
3844
+ /**
3845
+ * @description Returns the table schema for the model form the database
3846
+ */
3847
+ static getTableSchema(): Promise<TableSchemaInfo>;
3848
+ /**
3849
+ * @description Merges the provided data with the model instance
3850
+ */
3851
+ static combineProps<T extends Model>(sqlInstance: Partial<T>, data: Partial<T>): void;
3852
+ /**
3853
+ * @description Adds a beforeFetch clause to the model, adding the ability to modify the query before fetching the data
3854
+ */
3855
+ static beforeFetch?(queryBuilder: ModelQueryBuilder<any>): void;
3856
+ /**
3857
+ * @description Adds a beforeInsert clause to the model, adding the ability to modify the data before inserting the data
3858
+ * @param {Model} data The single model to be inserted, in insertMany the hook will be called for each model
3859
+ * @example
3860
+ * ```typescript
3861
+ * static async beforeInsert?(data: User): Promise<void> {
3862
+ * data.name = data.name.toUpperCase();
3863
+ * }
3864
+ * ```
3865
+ */
3866
+ static beforeInsert?(data: any): Promise<void> | void;
3867
+ /**
3868
+ * @description Adds a beforeUpdate clause to the model, adding the ability to modify the query before updating the data
3869
+ */
3870
+ static beforeUpdate?(queryBuilder: ModelQueryBuilder<any>): void;
3871
+ /**
3872
+ * @description Adds a beforeDelete clause to the model, adding the ability to modify the query before deleting the data
3873
+ */
3874
+ static beforeDelete?(queryBuilder: ModelQueryBuilder<any>): void;
3875
+ /**
3876
+ * @description Adds a afterFetch clause to the model, adding the ability to modify the data after fetching the data
3877
+ * @param {Model} data The single model to be fetched, in queries that return multiple models the hook will be called for each model
3878
+ * @example
3879
+ * ```typescript
3880
+ * static async afterFetch?(data: User): Promise<User> {
3881
+ * return data;
3882
+ * }
3883
+ * ```
3884
+ */
3885
+ static afterFetch?(data: any): Promise<any> | any;
3886
+ /**
3887
+ * @description Returns the columns of the model
3888
+ */
3889
+ static getColumns(): ColumnType[];
3890
+ /**
3891
+ * @description Returns the relations of the model
3892
+ */
3893
+ static getRelations(): LazyRelationType[];
3894
+ /**
3895
+ * @description Returns the indexes metadata of the model
3896
+ */
3897
+ static getIndexes(): IndexType[];
3898
+ static getUniques(): UniqueType[];
3899
+ /**
3900
+ * @description Defines a column in the model, useful in javascript in order to not have to rely on decorators since are not supported without a transpiler like babel
3901
+ * @javascript
3902
+ */
3903
+ static column(columnName: string, ...args: Parameters<typeof column>): void;
3904
+ /**
3905
+ * @description Defines an hasOne relation
3906
+ * @javascript
3907
+ */
3908
+ static hasOne(columnName: string, ...args: Parameters<typeof hasOne>): void;
3909
+ /**
3910
+ * @description Defines an hasMany
3911
+ * @javascript
3912
+ */
3913
+ static hasMany(columnName: string, ...args: Parameters<typeof hasMany>): void;
3914
+ /**
3915
+ * @description Defines a belongsTo
3916
+ * @javascript
3917
+ */
3918
+ static belongsTo(columnName: string, ...args: Parameters<typeof belongsTo>): void;
3919
+ /**
3920
+ * @description Defines a many to many
3921
+ * @javascript
3922
+ */
3923
+ static manyToMany(columnName: string, ...args: Parameters<typeof manyToMany>): void;
3924
+ /**
3925
+ * @description Establishes a connection to the database instantiated from the SqlDataSource.connect method, this is done automatically when using the static methods
3926
+ * @description This method is meant to be used only if you want to establish sql sqlInstance of the model directly
3927
+ * @internal
3928
+ */
3929
+ private static establishConnection;
3930
+ /**
3931
+ * @description Gives the correct model manager with the correct connection based on the options provided
3932
+ */
3933
+ private static dispatchModelManager;
3934
+ }
3935
+
3936
+ type BaseModelRelationType = {
3937
+ onDelete?: OnUpdateOrDelete;
3938
+ onUpdate?: OnUpdateOrDelete;
3939
+ constraintName?: string;
3940
+ };
3941
+ /**
3942
+ * @description Class decorator to define indexes on the model
3943
+ * @description If no indexName is provided, the index name will be the model name plus the columns joined by underscores
3944
+ * @example User will have an index named "user_name_index" on the "name" column
3945
+ * @example User will have an index named "user_name_email_index" on the "name" and "email" columns
3946
+ * ```ts
3947
+ * @index(["name", "email"], "user_name_email_index")
3948
+ * class User extends Model {
3949
+ * @column()
3950
+ * name!: string;
3951
+ * }
3952
+ *
3953
+ * @index(["name", "email"])
3954
+ * class User extends Model {
3955
+ * @column()
3956
+ * name!: string;
3957
+ * }
3958
+ * ```
3959
+ */
3960
+ declare function index(indexes: string | string[], indexName?: string): ClassDecorator;
3961
+ declare function unique(columns: string | string[], constraintName?: string): ClassDecorator;
3962
+ /**
3963
+ * @description Decorator to define a view on the model
3964
+ * @description This will automatically create a view on the database with the given statement
3965
+ * @description Since a view is intended to get data from other tables, a migration is not necessary
3966
+ * @example
3967
+ * ```ts
3968
+ * @view((query) => {
3969
+ * query.select("*").from("users");
3970
+ * })
3971
+ * class User extends Model {
3972
+ * @column()
3973
+ * name!: string;
3974
+ * }
3975
+ * ```
3976
+ */
3977
+ declare function view(statement: (query: ModelQueryBuilder<any>) => void): ClassDecorator;
3978
+ /**
3979
+ * @description Decorator to define a column in the model
3980
+ */
3981
+ declare function column(options?: ColumnOptions): PropertyDecorator;
3982
+ declare namespace column {
3983
+ var primary: typeof primaryKeyColumn;
3984
+ var date: typeof dateColumn;
3985
+ var boolean: typeof booleanColumn;
3986
+ var json: typeof jsonColumn;
3987
+ var uuid: typeof uuidColumn;
3988
+ var ulid: typeof ulidColumn;
3989
+ var integer: typeof integerColumn;
3990
+ var float: typeof floatColumn;
3991
+ var encryption: {
3992
+ symmetric: typeof symmetric;
3993
+ asymmetric: typeof asymmetric;
3994
+ };
3995
+ }
3996
+ declare function primaryKeyColumn(options?: Omit<ColumnOptions, "primaryKey">): PropertyDecorator;
3997
+ declare function floatColumn(options?: Omit<ColumnOptions, "serialize">): PropertyDecorator;
3998
+ /**
3999
+ * @description Decorator to define a integer column in the model, this will automatically convert the integer to the correct format for the database
4000
+ * @description Useful in databases like postgres where the integer is returned as a string by the driver
4001
+ * @description Defaults type to integer for migration generation
4002
+ */
4003
+ declare function integerColumn(options?: Omit<ColumnOptions, "serialize">): PropertyDecorator;
4004
+ /**
4005
+ * @description Decorator to define a uuid column in the model
4006
+ * @description This will automatically generate a uuid if no value is provided
4007
+ * @description Defaults type to uuid for migration generation
4008
+ */
4009
+ declare function uuidColumn(options?: Omit<ColumnOptions, "prepare">): PropertyDecorator;
4010
+ /**
4011
+ * @description Decorator to define a ulid column in the model
4012
+ * @description This will automatically generate a ulid if no value is provided
4013
+ * @description Defaults type to ulid for migration generation
4014
+ */
4015
+ declare function ulidColumn(options?: Omit<ColumnOptions, "prepare">): PropertyDecorator;
4016
+ /**
4017
+ * @description Decorator to define a symmetric encrypted column in the model with a key
4018
+ * @description This will automatically encrypt the value before it is inserted or updated in the database and decrypt it when it is retrieved from the database
4019
+ * @description If no value is provided, the value will be returned as is
4020
+ */
4021
+ declare function symmetric(options: Omit<SymmetricEncryptionOptions, "prepare" | "serialize">): PropertyDecorator;
4022
+ /**
4023
+ * @description Decorator to define a asymmetric encrypted column in the model with public and private keys
4024
+ * @description This will automatically encrypt the value before it is inserted or updated in the database and decrypt it when it is retrieved from the database
4025
+ * @description If no value is provided, the value will be returned as is
4026
+ */
4027
+ declare function asymmetric(options: Omit<AsymmetricEncryptionOptions, "prepare" | "serialize">): PropertyDecorator;
4028
+ /**
4029
+ * @description Decorator to define a boolean column in the model
4030
+ * @description This will automatically convert the boolean to the correct format for the database, useful for mysql since it stores booleans as tinyint(1)
4031
+ * @description Defaults type to boolean for migration generation
4032
+ */
4033
+ declare function booleanColumn(options?: Omit<ColumnOptions, "prepare" | "serialize">): PropertyDecorator;
4034
+ /**
4035
+ * @description Decorator to define a date column in the model
4036
+ * @description This will automatically convert the date to the correct format for the database
4037
+ * @description Supports both ISO format (YYYY-MM-DD HH:mm:ss) and Unix timestamp
4038
+ * @description Handles timezone conversion between UTC and local time
4039
+ * @description Can automatically update/create timestamps
4040
+ * @param options Configuration options for the date column
4041
+ * @param options.format The format to store dates in ('ISO' or 'TIMESTAMP')
4042
+ * @param options.timezone The timezone to use ('UTC' or 'LOCAL')
4043
+ * @param options.autoUpdate Whether to automatically update the timestamp on record updates
4044
+ * @param options.autoCreate Whether to automatically set the timestamp on record creation
4045
+ */
4046
+ declare function dateColumn(options?: Omit<DateColumnOptions, "prepare" | "serialize">): PropertyDecorator;
4047
+ /**
4048
+ * @description Decorator to define a json column in the model
4049
+ * @description This will automatically convert the json to the correct format for the database
4050
+ * @throws json parse error if the value from the database is not valid json
4051
+ * @description Defaults type to jsonb for migration generation
4052
+ */
4053
+ declare function jsonColumn(options?: Omit<ColumnOptions, "prepare" | "serialize">): PropertyDecorator;
4054
+ declare function getModelColumns(target: typeof Model): ColumnType[];
4055
+ /**
4056
+ * relations
4057
+ */
4058
+ /**
4059
+ * @description Establishes a belongs to relation with the given model
4060
+ * @default foreignKey by default will be the singular of the model that establishes the relation name plus "_id"
4061
+ * @example Post that has a user will have foreignKey "user_id" on the model
4062
+ * ```typescript
4063
+ * belongsTo<typeof Post>(() => User, 'userId')
4064
+ * ```
4065
+ */
4066
+ declare function belongsTo<M extends typeof Model = any, R extends typeof Model = any>(model: () => R, foreignKey?: ModelKey<InstanceType<M>>, options?: BaseModelRelationType): PropertyDecorator;
4067
+ /**
4068
+ * @description Establishes a has one relation with the given model
4069
+ * @default foreignKey by default will be the singular of the model name plus "_id"
4070
+ * @example User will have foreignKey "user_id" on the Post model
4071
+ */
4072
+ declare function hasOne<T extends typeof Model>(model: () => T, foreignKey?: ModelKey<InstanceType<T>>): PropertyDecorator;
4073
+ /**
4074
+ * @description Establishes a has many relation with the given model
4075
+ * @default foreignKey by default will be the singular of the model name plus "_id"
4076
+ * @example User will have foreignKey "user_id" on the Post model
4077
+ */
4078
+ declare function hasMany<T extends typeof Model>(model: () => T, foreignKey?: ModelKey<InstanceType<T>>): PropertyDecorator;
4079
+ /**
4080
+ * @description Establishes a many to many relation with the given model
4081
+ * @default foreignKey by default will be the singular of the model that establishes the relation name plus "_id"
4082
+ * @param model The model that establishes the relation
4083
+ * @param throughModel The model that is used to join the two models
4084
+ * @param throughModelKeys The keys of the through model
4085
+ * @param throughModelKeys.leftForeignKey The foreign key of the through model from the primary model (where you are defining the many to many relation)
4086
+ * @param throughModelKeys.rightForeignKey The foreign key of the through model from the related model (the model you are joining to)
4087
+ * @example User will have foreignKey "user_id" on the Join table by default
4088
+ */
4089
+ declare function manyToMany<R extends typeof Model, T extends typeof Model, TM extends ThroughModel<T>>(model: () => R, throughModel: TM, throughModelKeys?: ManyToManyOptions<T, TM>, options?: BaseModelRelationType): PropertyDecorator;
4090
+ declare function getRelationsMetadata(target: typeof Model): LazyRelationType[];
4091
+ /**
4092
+ * @description Returns the relations of the model
4093
+ */
4094
+ declare function getRelations(target: typeof Model): Relation[];
4095
+ /**
4096
+ * @description Returns the primary key of the model
4097
+ */
4098
+ declare function getPrimaryKey(target: typeof Model): string;
4099
+ declare function getIndexes(target: typeof Model): IndexType[];
4100
+ declare function getUniques(target: typeof Model): UniqueType[];
4101
+
4102
+ type FactoryReturnType<T extends number, O extends Model> = T extends 1 ? O : O[];
4103
+
4104
+ declare class ModelFactory<M extends Model> {
4105
+ typeofModel: typeof Model;
4106
+ modelData: Partial<M>;
4107
+ /**
4108
+ * @description Constructor for the model factory
4109
+ */
4110
+ constructor(typeofModel: typeof Model, modelData: Partial<M>);
4111
+ /**
4112
+ * @description Merges the provided data with the model data
4113
+ */
4114
+ merge(modelData: Partial<ModelWithoutRelations<M>>): void;
4115
+ /**
4116
+ * @description Create a model
4117
+ * @param howMany - The number of models to create
4118
+ * @returns The created model(s) where howMany = 1 returns a single model and howMany !== 1 returns an array of models
4119
+ */
4120
+ create<T extends number>(howMany: T): Promise<FactoryReturnType<T, M>>;
4121
+ }
4122
+ declare const createModelFactory: <M extends Model>(typeofModel: typeof Model, modelData: Partial<ModelWithoutRelations<M>>) => ModelFactory<M>;
4123
+
4124
+ /**
4125
+ * @description Mixin to add createdAt, updatedAt and deletedAt columns to a model
4126
+ */
4127
+ declare class TimestampedModel extends Model {
4128
+ createdAt: Date;
4129
+ updatedAt: Date;
4130
+ deletedAt: Date | null;
4131
+ }
4132
+
4133
+ /**
4134
+ * @description Mixin to add a uuid column to a model
4135
+ */
4136
+ declare class UuidModel extends Model {
4137
+ id: string;
4138
+ }
4139
+
4140
+ /**
4141
+ * @description Mixin to add an autogenerated id column to a model
4142
+ */
4143
+ declare class AutogeneratedModel extends Model {
4144
+ id: BigInt;
4145
+ }
4146
+
4147
+ /**
4148
+ * @description Mixin to add a user model with id, email, createdAt, updatedAt and deletedAt columns
4149
+ */
4150
+ declare class User extends Model {
4151
+ id: BigInt;
4152
+ email: string;
4153
+ createdAt: Date;
4154
+ updatedAt: Date;
4155
+ deletedAt: Date | null;
4156
+ }
4157
+
4158
+ /**
4159
+ * @description The RedisStorable type is a type that can be stored in redis
4160
+ */
4161
+ type RedisStorable = string | number | boolean | Buffer | Array<any> | Record<string, any>;
4162
+ /**
4163
+ * @description The RedisFetchable type is a type that can be fetched from redis
4164
+ */
4165
+ type RedisFetchable = string | number | boolean | Record<string, any> | Array<any> | null;
4166
+ /**
4167
+ * @description The RedisDataSource class is a wrapper around the ioredis library that provides a simple interface to interact with a redis database
4168
+ */
4169
+ declare class RedisDataSource {
4170
+ static isConnected: boolean;
4171
+ protected static redisDataSourceInstance: RedisDataSource;
4172
+ isConnected: boolean;
4173
+ protected ioRedisConnection: Redis;
4174
+ constructor(ioRedisConnection: Redis);
4175
+ /**
4176
+ * @description Returns the raw ioredis connection
4177
+ * @returns {Redis}
4178
+ */
4179
+ static get ioredis(): Redis;
4180
+ /**
4181
+ * @description Returns the raw ioredis connection
4182
+ * @returns {Redis}
4183
+ */
4184
+ get ioredis(): Redis;
4185
+ /**
4186
+ * @description Connects to the redis database establishing a connection. If no connection details are provided, the default values from the env will be taken instead
4187
+ * @description The User input connection details will always come first
4188
+ * @description This is intended as a singleton connection to the redis database, if you need multiple connections, use the getConnection method
4189
+ */
4190
+ static connect(input?: RedisOptions): Promise<void>;
4191
+ /**
4192
+ * @description Establishes a connection to the redis database and returns the connection
4193
+ * @param input
4194
+ * @returns
4195
+ */
4196
+ static getConnection(input?: RedisOptions): Promise<RedisDataSource>;
4197
+ /**
4198
+ * @description Sets a key-value pair in the redis database
4199
+ * @param {string} key - The key
4200
+ * @param {string} value - The value
4201
+ * @param {number} expirationTime - The expiration time in milliseconds
4202
+ */
4203
+ static set(key: string, value: RedisStorable, expirationTime?: number): Promise<void>;
4204
+ /**
4205
+ * @description Gets the value of a key in the redis database
4206
+ * @param {string} key - The key
4207
+ * @returns {Promise<string>}
4208
+ */
4209
+ static get<T = RedisFetchable>(key: string): Promise<T | null>;
4210
+ /**
4211
+ * @description Gets the value of a key in the redis database as a buffer
4212
+ */
4213
+ static getBuffer(key: string): Promise<Buffer | null>;
4214
+ /**
4215
+ * @description Gets the value of a key in the redis database and deletes the key
4216
+ * @param {string} key - The key
4217
+ * @returns {Promise
4218
+ * <T | null>}
4219
+ */
4220
+ static consume<T = RedisFetchable>(key: string): Promise<T | null>;
4221
+ /**
4222
+ * @description Deletes a key from the redis database
4223
+ * @param {string} key - The key
4224
+ * @returns {Promise<void>}
4225
+ */
4226
+ static delete(key: string): Promise<void>;
4227
+ /**
4228
+ * @description Flushes all the data in the redis database
4229
+ * @returns {Promise<void>}
4230
+ */
4231
+ static flushAll(): Promise<void>;
4232
+ /**
4233
+ * @description Disconnects from the redis database
4234
+ * @returns {Promise<void>}
4235
+ */
4236
+ static disconnect(): Promise<void>;
4237
+ /**
4238
+ * @description Sets a key-value pair in the redis database
4239
+ * @param {string} key - The key
4240
+ * @param {string} value - The value
4241
+ * @param {number} expirationTime - The expiration time in milliseconds
4242
+ * @returns {Promise<void>}
4243
+ */
4244
+ set(key: string, value: RedisStorable, expirationTime?: number): Promise<void>;
4245
+ /**
4246
+ * @description Gets the value of a key in the redis database
4247
+ * @param {string} key - The key
4248
+ * @returns {Promise<string>}
4249
+ */
4250
+ get<T = RedisFetchable>(key: string): Promise<T | null>;
4251
+ /**
4252
+ * @description Gets the value of a key in the redis database as a buffer
4253
+ */
4254
+ getBuffer(key: string): Promise<Buffer | null>;
4255
+ /**
4256
+ * @description Gets the value of a key in the redis database and deletes the key
4257
+ * @param {string} key - The key
4258
+ * @returns {Promise
4259
+ * <T | null>}
4260
+ */
4261
+ consume<T = RedisFetchable>(key: string): Promise<T | null>;
4262
+ /**
4263
+ * @description Deletes a key from the redis database
4264
+ * @param {string} key - The key
4265
+ * @returns {Promise<void>}
4266
+ */
4267
+ delete(key: string): Promise<void>;
4268
+ /**
4269
+ * @description Flushes all the data in the redis database
4270
+ * @returns {Promise<void>}
4271
+ */
4272
+ flushAll(): Promise<void>;
4273
+ /**
4274
+ * @description Disconnects from the redis database
4275
+ * @returns {Promise<void>}
4276
+ */
4277
+ disconnect(forceError?: boolean): Promise<void>;
4278
+ protected static getValue<T = RedisFetchable>(value: string | null): T | null;
4279
+ }
4280
+
4281
+ declare abstract class Migration {
4282
+ dbType: SqlDataSourceType;
4283
+ migrationName: string;
4284
+ schema: Schema;
4285
+ constructor(dbType: SqlDataSourceType);
4286
+ /**
4287
+ * @description This method is called when the migration is to be run
4288
+ */
4289
+ abstract up(): Promise<void>;
4290
+ /**
4291
+ * @description This method is called when the migration is to be rolled back
4292
+ */
4293
+ abstract down(): Promise<void>;
4294
+ /**
4295
+ * @description This method is called after the migration has been run
4296
+ */
4297
+ afterMigration?(sqlDataSource: SqlDataSource): Promise<void>;
4298
+ }
4299
+
4300
+ /**
4301
+ * @description Can be used to run migrations programmatically
4302
+ */
4303
+ declare class ClientMigrator {
4304
+ protected migrationPath: string;
4305
+ protected sqlDataSourceInput?: SqlDataSource["inputDetails"] | SqlDataSource;
4306
+ constructor(migrationPath?: string, sqlDataSourceInput?: SqlDataSource["inputDetails"] | SqlDataSource);
4307
+ /**
4308
+ * @description Runs programmatic migrations up
4309
+ */
4310
+ up(): Promise<void>;
4311
+ /**
4312
+ * @description Runs programmatic migrations down
4313
+ */
4314
+ down(): Promise<void>;
4315
+ /**
4316
+ * @description Runs programmatic migrations up or down
4317
+ * @param direction - The direction to migrate, either "up" or "down"
4318
+ */
4319
+ private migrate;
4320
+ }
4321
+ /**
4322
+ * @description Defines a programmatic migrator, can be used to run migrations programmatically
4323
+ * @param migrationPath - The path to the migrations
4324
+ * @param sqlDataSourceInput - The sql data source input, if not provided, env variables will be used
4325
+ */
4326
+ declare const defineMigrator: (migrationPath: string, sqlDataSourceInput?: SqlDataSource["inputDetails"] | SqlDataSource) => ClientMigrator;
4327
+
4328
+ type CustomLogger = {
4329
+ info(message: string): void;
4330
+ error(message: string): void;
4331
+ warn(message: string): void;
4332
+ };
4333
+ declare class HysteriaLogger {
4334
+ static loggerInstance: CustomLogger;
4335
+ static setCustomLogger(customLogger: CustomLogger): void;
4336
+ static info(message: string): void;
4337
+ static error(message: string | Error): void;
4338
+ static warn(message: string): void;
4339
+ }
4340
+
4341
+ type WithPerformanceResult<R = any> = [string, R];
4342
+ /**
4343
+ * @description executes the async function with a timer to check how long it took
4344
+ * @param `returnType` of the performance in milliseconds or seconds
4345
+ * @param `fix` Number of digits in the decimal part of the performance result
4346
+ * @returns An array with the millis or seconds that the function took as first element, and the result of the async function as second element
4347
+ */
4348
+ declare const withPerformance: <R = any>(fn: (...params: any) => Promise<R>, returnType?: "millis" | "seconds", fix?: number) => Promise<WithPerformanceResult<R>>;
4349
+
4350
+ type HysteriaErrorCode = "ROW_NOT_FOUND" | `UNSUPPORTED_DATABASE_TYPE_${string}` | `RELATION_TYPE_NOT_SUPPORTED_${string}` | `NOT_SUPPORTED_IN_${string}` | `RELATION_NOT_FOUND_IN_MODEL_${string}` | `UNKNOWN_RELATION_TYPE_${string}` | `DISTINCT_ON_NOT_SUPPORTED_IN_${string}` | `CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA` | `CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA_${string}` | `FOREIGN_KEY_VALUES_MISSING_FOR_HAS_ONE_RELATION_${string}` | `FOREIGN_KEY_VALUES_MISSING_FOR_BELONGS_TO_RELATION_${string}` | `PRIMARY_KEY_VALUES_MISSING_FOR_HAS_MANY_RELATION_${string}` | `MANY_TO_MANY_RELATION_NOT_FOUND_FOR_RELATED_MODEL_${string}` | `PRIMARY_KEY_VALUES_MISSING_FOR_MANY_TO_MANY_RELATION_${string}` | `RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${string}` | `FOR_SHARE_NOT_SUPPORTED_IN_${string}` | `SKIP_LOCKED_NOT_SUPPORTED_IN_${string}` | `LOCK_FOR_UPDATE_NOT_SUPPORTED_${string}` | `SQLITE_NOT_SUPPORTED` | `COCKROACHDB_NOT_SUPPORTED` | `RELATION_NOT_FOUND` | `POSTGRES_TABLE_REQUIRED` | `RELATION_NOT_MANY_TO_MANY` | "MATERIALIZED_CTE_NOT_SUPPORTED" | "DUPLICATE_MODEL_KEYS_WHILE_INSTANTIATING_MODELS" | "INVALID_ONE_PARAMETER_WHERE_CONDITION" | "INVALID_PAGINATION_PARAMETERS" | "MISSING_ALIAS_FOR_SUBQUERY" | "MODEL_HAS_NO_PRIMARY_KEY" | "PRIMARY_KEY_NOT_FOUND" | "SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL" | "MUST_CALL_BUILD_CTE_AT_LEAST_ONCE" | "REGEXP_NOT_SUPPORTED_IN_SQLITE" | "MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL" | "INSERT_FAILED" | "MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED" | "FILE_NOT_A_SQL_OR_TXT_FILE" | "CONNECTION_NOT_ESTABLISHED" | "TRANSACTION_NOT_ACTIVE" | "DEVELOPMENT_ERROR" | "MIGRATION_MODULE_NOT_FOUND" | "DRIVER_NOT_FOUND" | "FILE_NOT_FOUND_OR_NOT_ACCESSIBLE" | "ENV_NOT_SET" | "REQUIRED_VALUE_NOT_SET" | "SET_FAILED" | "GET_FAILED" | "REFERENCES_OPTION_REQUIRED" | "DELETE_FAILED" | "INVALID_DEFAULT_VALUE" | "DISCONNECT_FAILED" | "FLUSH_FAILED" | "LEFT_COLUMN_NOT_PROVIDED_FOR_JOIN" | "RIGHT_COLUMN_NOT_PROVIDED_FOR_JOIN" | "MODEL_HAS_NO_PRIMARY_KEY" | "GLOBAL_TRANSACTION_ALREADY_STARTED" | "GLOBAL_TRANSACTION_NOT_STARTED" | "MYSQL_REQUIRES_TABLE_NAME_FOR_INDEX_DROP" | "INVALID_DATE_OBJECT" | "INVALID_DATE_STRING" | "FAILED_TO_PARSE_DATE" | "MIGRATION_MODULE_REQUIRES_TS_NODE" | "FAILED_TO_ENCRYPT_SYMMETRICALLY" | "FAILED_TO_DECRYPT_SYMMETRICALLY" | "FAILED_TO_ENCRYPT_ASYMMETRICALLY" | "FAILED_TO_DECRYPT_ASYMMETRICALLY" | "UNSUPPORTED_RELATION_TYPE";
4351
+
4352
+ declare class HysteriaError extends Error {
4353
+ code: HysteriaErrorCode;
4354
+ caller: string;
4355
+ error?: Error;
4356
+ constructor(caller: string, code: HysteriaErrorCode, error?: Error);
4357
+ }
4358
+
4359
+ /**
4360
+ * Generates OpenAPI schemas for multiple models
4361
+ */
4362
+ declare const generateOpenApiModel: <T extends new () => Model>(models: T[]) => OpenApiModelType[];
4363
+ /**
4364
+ * Generates OpenAPI schema for a single model
4365
+ */
4366
+ declare const generateOpenApiModelSchema: <T extends new () => Model>(model: T) => OpenApiModelType;
4367
+ /**
4368
+ * Generates OpenAPI schemas with additional metadata
4369
+ */
4370
+ declare const generateOpenApiModelWithMetadata: <T extends new () => Model>(models: T[]) => Array<OpenApiModelType & {
4371
+ modelName: string;
4372
+ }>;
4373
+
4374
+ export { type AnnotatedModel, type AsymmetricEncryptionOptions, type AugmentedSqlDataSource, AutogeneratedModel, type BaseModelMethodOptions, type BaseModelRelationType, ClientMigrator, Collection, type ColumnDataTypeOption, type ColumnDataTypeOptionSimple, type ColumnDataTypeOptionWithBinary, type ColumnDataTypeOptionWithDatePrecision, type ColumnDataTypeOptionWithEnum, type ColumnDataTypeOptionWithLength, type ColumnDataTypeOptionWithPrecision, type ColumnDataTypeOptionWithScaleAndPrecision, type ColumnDataTypeOptionWithText, type ColumnOptions, type ColumnType, type CommonDataSourceInput, type CommonSqlMethodReturnType, type ConnectionPolicies, type DataSourceInput, type DataSourceType, type DateColumnOptions, type FetchHooks, type GetConnectionReturnType, HysteriaError, type IndexType, type LazyRelationType, type ManyOptions, type ManyToManyOptions, Migration, Model, type ModelInstanceType, ModelQueryBuilder, type ModelWithoutRelations, MongoDataSource, type MongoDataSourceInput, type MysqlConnectionInstance, type MysqlSqlDataSourceInput, type NotNullableMysqlSqlDataSourceInput, type NotNullablePostgresSqlDataSourceInput, type NotNullableSqliteDataSourceInput, type NumberModelKey, type OneOptions, type PgPoolClientInstance, type PostgresSqlDataSourceInput, QueryBuilder, type RedisFetchable, type RedisStorable, type RelatedInstance, type RelationQueryBuilderType, type SqlCloneOptions, type SqlDataSourceInput, type SqlDataSourceModel, type SqlDataSourceType, type SqlDataSourceWithoutTransaction, type SqlDriverSpecificOptions, type SqlPoolType, type SqliteConnectionInstance, type SqliteDataSourceInput, type StartTransactionOptions, type SymmetricEncryptionOptions, type ThroughModel, TimestampedModel, Transaction, type TransactionExecutionOptions, type UniqueType, type UseConnectionInput, User, UuidModel, belongsTo, column, createModelFactory, defineMigrator, generateOpenApiModel, generateOpenApiModelSchema, generateOpenApiModelWithMetadata, getCollectionProperties, getIndexes, getModelColumns, type getPoolReturnType, getPrimaryKey, getRelations, getRelationsMetadata, getUniques, hasMany, hasOne, index, HysteriaLogger as logger, manyToMany, MongoDataSource as mongo, property, RedisDataSource as redis, SqlDataSource as sql, unique, view, withPerformance };