hysteria-orm 10.2.3 → 10.3.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.cts CHANGED
@@ -1,15 +1,18 @@
1
+ import { PoolAttributes, Pool, Connection, Result } from 'oracledb';
1
2
  import * as mssql from 'mssql';
2
- import { config, Transaction as Transaction$1 } from 'mssql';
3
+ import { config, Transaction as Transaction$1, IResult } from 'mssql';
3
4
  import * as mongodb from 'mongodb';
4
5
  import { Collection as Collection$1 } from 'mongodb';
5
6
  import * as sqlite3 from 'sqlite3';
7
+ import { RunResult } from 'sqlite3';
6
8
  import * as pg from 'pg';
7
- import { ClientConfig, PoolClient } from 'pg';
9
+ import { ClientConfig, PoolClient, QueryResult as QueryResult$1 } from 'pg';
8
10
  import * as mysql2_promise from 'mysql2/promise';
9
- import { PoolOptions, PoolConnection } from 'mysql2/promise';
11
+ import { PoolOptions, PoolConnection, QueryResult } from 'mysql2/promise';
10
12
  import { RedisOptions, Redis } from 'ioredis';
11
13
  import { PassThrough } from 'node:stream';
12
14
  import { FormatOptionsWithLanguage } from 'sql-formatter';
15
+ import express from 'express';
13
16
 
14
17
  type CaseConvention = "camel" | "snake" | "preserve" | RegExp | ((column: string) => string);
15
18
 
@@ -34,7 +37,7 @@ declare abstract class Entity {
34
37
  /**
35
38
  * @description Creates a datasource for the selected database type with the provided credentials
36
39
  */
37
- type DataSourceType = "cockroachdb" | "mysql" | "postgres" | "mariadb" | "sqlite" | "mssql" | "mongo";
40
+ type DataSourceType = "oracledb" | "cockroachdb" | "mysql" | "postgres" | "mariadb" | "sqlite" | "mssql" | "mongo";
38
41
  interface MssqlDataSourceInput extends CommonDataSourceInput {
39
42
  readonly type: "mssql";
40
43
  readonly host?: string;
@@ -43,11 +46,19 @@ interface MssqlDataSourceInput extends CommonDataSourceInput {
43
46
  readonly password?: string;
44
47
  readonly database?: string;
45
48
  }
49
+ interface OracleDBDataSourceInput extends CommonDataSourceInput {
50
+ readonly type: "oracledb";
51
+ readonly host?: string;
52
+ readonly port?: number;
53
+ readonly username?: string;
54
+ readonly password?: string;
55
+ readonly database?: string;
56
+ }
46
57
  interface CommonDataSourceInput {
47
58
  readonly type?: DataSourceType;
48
59
  readonly logs?: boolean;
49
60
  }
50
- interface MongoDataSourceInput extends CommonDataSourceInput {
61
+ interface MongoDataSourceInput$1 extends CommonDataSourceInput {
51
62
  readonly type: "mongo";
52
63
  readonly mongoOptions?: MongoConnectionOptions;
53
64
  readonly url?: string;
@@ -68,6 +79,22 @@ interface NotNullablePostgresSqlDataSourceInput extends PostgresSqlDataSourceInp
68
79
  readonly database: string;
69
80
  readonly port?: number;
70
81
  }
82
+ interface NotNullableOracleMssqlDataSourceInput extends MssqlDataSourceInput {
83
+ readonly type: "mssql";
84
+ readonly host: string;
85
+ readonly username: string;
86
+ readonly password: string;
87
+ readonly database: string;
88
+ readonly port?: number;
89
+ }
90
+ interface NotNullableOracleDBDataSourceInput extends OracleDBDataSourceInput {
91
+ readonly type: "oracledb";
92
+ readonly host: string;
93
+ readonly username: string;
94
+ readonly password: string;
95
+ readonly database: string;
96
+ readonly port?: number;
97
+ }
71
98
  interface MysqlSqlDataSourceInput extends CommonDataSourceInput {
72
99
  readonly type?: "mysql" | "mariadb";
73
100
  readonly host?: string;
@@ -95,20 +122,21 @@ interface NotNullableSqliteDataSourceInput extends SqliteDataSourceInput {
95
122
  /**
96
123
  * @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
97
124
  */
98
- type DataSourceInput = MssqlDataSourceInput | MysqlSqlDataSourceInput | SqliteDataSourceInput | PostgresSqlDataSourceInput | MongoDataSourceInput;
125
+ type DataSourceInput = OracleDBDataSourceInput | MssqlDataSourceInput | MysqlSqlDataSourceInput | SqliteDataSourceInput | PostgresSqlDataSourceInput | MongoDataSourceInput$1;
99
126
 
100
127
  type Mysql2Import = typeof mysql2_promise;
101
128
  type PgImport = typeof pg;
102
129
  type Sqlite3Import = typeof sqlite3;
103
130
  type MongoClientImport = typeof mongodb;
104
131
  type MssqlImport = typeof mssql;
132
+ type OracleDBCreateConnectionOptions = PoolAttributes;
105
133
  type MysqlCreateConnectionOptions = PoolOptions;
106
134
  type PgClientOptions = ClientConfig;
107
135
  type MssqlConnectionOptions = Omit<config, "options"> & {
108
136
  options?: Omit<NonNullable<config["options"]>, "abortTransactionOnError" | "enableImplicitTransactions">;
109
137
  };
110
138
  type MongoConnectionOptions = NonNullable<ConstructorParameters<MongoClientImport["MongoClient"]>[1]>;
111
- type DriverSpecificOptions<T extends DataSourceType> = T extends "mongo" ? MongoConnectionOptions : T extends "cockroachdb" | "postgres" ? PgClientOptions : T extends "redis" ? RedisOptions : T extends "mysql" | "mariadb" ? MysqlCreateConnectionOptions : T extends "mssql" ? MssqlConnectionOptions : never;
139
+ type DriverSpecificOptions<T extends DataSourceType> = T extends "mongo" ? MongoConnectionOptions : T extends "cockroachdb" | "postgres" ? PgClientOptions : T extends "redis" ? RedisOptions : T extends "mysql" | "mariadb" ? MysqlCreateConnectionOptions : T extends "mssql" ? MssqlConnectionOptions : T extends "oracledb" ? OracleDBCreateConnectionOptions : never;
112
140
 
113
141
  type MongoCollectionKey<T> = T extends Collection ? T : never;
114
142
  type BaseModelMethodOptions$1 = {
@@ -449,8 +477,9 @@ declare abstract class DataSource {
449
477
  protected handlePostgresSource(input?: PostgresSqlDataSourceInput): void;
450
478
  protected handleMysqlSource(input?: MysqlSqlDataSourceInput): void;
451
479
  protected handleSqliteSource(input?: SqliteDataSourceInput): void;
452
- protected handleMongoSource(input?: MongoDataSourceInput): void;
480
+ protected handleMongoSource(input?: MongoDataSourceInput$1): void;
453
481
  protected handleMssqlSource(input?: MssqlDataSourceInput): void;
482
+ protected handleOracleDBSource(input?: MssqlDataSourceInput): void;
454
483
  }
455
484
 
456
485
  type MongoFindOneOptions<T extends Collection> = {
@@ -522,22 +551,34 @@ declare class CollectionManager<T extends Collection> {
522
551
  }
523
552
 
524
553
  type MongoClientInstance = InstanceType<MongoClientImport["MongoClient"]>;
554
+ interface MongoDataSourceInput {
555
+ url?: string;
556
+ options?: MongoConnectionOptions;
557
+ logs?: boolean;
558
+ }
525
559
  declare class MongoDataSource extends DataSource {
526
560
  url: string;
527
561
  isConnected: boolean;
528
562
  private mongoClient;
563
+ private mongoOptions?;
529
564
  private static instance;
530
- private constructor();
565
+ constructor(input?: MongoDataSourceInput);
566
+ /**
567
+ * @description Establishes the connection to MongoDB and sets this as the primary instance
568
+ */
569
+ connect(): Promise<void>;
570
+ /**
571
+ * @description Establishes the connection without setting this as the primary instance
572
+ */
573
+ private connectWithoutSettingPrimary;
531
574
  /**
532
575
  * @description Returns the current connection to the mongo client to execute direct statements using the mongo client from `mongodb` package
533
576
  */
534
577
  getCurrentConnection(): MongoClientInstance;
535
578
  /**
536
- * @description Connects to the mongo database using the provided url and options
579
+ * @description Creates a secondary connection to MongoDB (does not become the primary instance)
537
580
  */
538
- static connect(url?: string, options?: Partial<MongoConnectionOptions> & {
539
- logs?: boolean;
540
- }, cb?: (mongoDataSource: MongoDataSource) => Promise<void> | void): Promise<MongoDataSource>;
581
+ static connectToSecondarySource(input: MongoDataSourceInput): Promise<MongoDataSource>;
541
582
  static getInstance(): MongoDataSource;
542
583
  /**
543
584
  * @description Starts a new session and transaction using the current connection
@@ -562,12 +603,9 @@ declare class MongoDataSource extends DataSource {
562
603
  */
563
604
  static closeConnection(): Promise<void>;
564
605
  /**
565
- * @description Executes a callback function with the provided connection details
606
+ * @description Executes a callback function with the provided connection details, automatically closing the connection when done
566
607
  */
567
- static useConnection(this: typeof MongoDataSource, connectionDetails: {
568
- url: string;
569
- options?: MongoConnectionOptions;
570
- }, cb: (mongoDataSource: MongoDataSource) => Promise<void>): Promise<void>;
608
+ static useConnection(this: typeof MongoDataSource, input: MongoDataSourceInput, cb: (mongoDataSource: MongoDataSource) => Promise<void>): Promise<void>;
571
609
  static query(collection: string): MongoQueryBuilder<Collection>;
572
610
  query(collection: string): MongoQueryBuilder<Collection>;
573
611
  getModelManager<T extends Collection>(model: typeof Collection, mongoDataSource: MongoDataSource, session?: InstanceType<MongoClientImport["ClientSession"]>): CollectionManager<T>;
@@ -1031,7 +1069,7 @@ type AdminJsInstance = {
1031
1069
  /**
1032
1070
  * @description Express router for AdminJS (if using express adapter)
1033
1071
  */
1034
- router?: unknown;
1072
+ router?: ReturnType<typeof express.Router>;
1035
1073
  };
1036
1074
 
1037
1075
  interface CacheAdapter {
@@ -1041,23 +1079,133 @@ interface CacheAdapter {
1041
1079
  disconnect?(): Promise<void>;
1042
1080
  }
1043
1081
 
1044
- type CacheKeys = Record<string, (...args: any[]) => Promise<any>>;
1082
+ type CacheKeys = Record<string, (...args: any[]) => Promise<any> | any>;
1045
1083
  type UseCacheReturnType<C extends CacheKeys, K extends keyof C> = K extends never ? never : Awaited<ReturnType<C[K]>>;
1046
1084
 
1047
- type OpenApiModelType = {
1048
- type: "object";
1049
- properties: Record<string, OpenApiModelPropertyType>;
1050
- required?: string[];
1085
+ type Sqlite3ConnectionOptions = {
1086
+ mode: number;
1051
1087
  };
1052
- type OpenApiModelPropertyType = {
1053
- type: string;
1054
- items?: OpenApiModelType;
1055
- enum?: string[];
1056
- format?: string;
1057
- description?: string;
1058
- example?: any;
1059
- default?: any;
1060
- nullable?: boolean;
1088
+ type SqlDriverSpecificOptions<T extends DataSourceType> = Omit<DriverSpecificOptions<T>, "mongoOptions" | "redisOptions">;
1089
+ type MysqlConnectionInstance = Awaited<ReturnType<Mysql2Import["createPool"]>>;
1090
+ type PgPoolClientInstance = InstanceType<PgImport["Pool"]>;
1091
+ type SqliteConnectionInstance = InstanceType<Sqlite3Import["Database"]>;
1092
+ type OracleDBPoolInstance = Pool;
1093
+ type MssqlPoolInstance = InstanceType<MssqlImport["ConnectionPool"]>;
1094
+ type MssqlConnectionInstance = Awaited<ReturnType<MssqlPoolInstance["connect"]>>;
1095
+ type SqlPoolType = OracleDBPoolInstance | MysqlConnectionInstance | PgPoolClientInstance | SqliteConnectionInstance | MssqlPoolInstance;
1096
+ /**
1097
+ * @description The connection policies for the sql data source
1098
+ * @default the connection policies are not set, so no query will be retried
1099
+ */
1100
+ type ConnectionPolicies = {
1101
+ /**
1102
+ * @description The retry policy for the sql data source, it allows to retry a query if it fails
1103
+ */
1104
+ retry?: {
1105
+ maxRetries?: number;
1106
+ delay?: number;
1107
+ };
1108
+ };
1109
+ type SqlDataSourceModel = typeof Model;
1110
+ /**
1111
+ * @description Common input properties shared across all SqlDataSource types
1112
+ */
1113
+ type SqlDataSourceInputBase<T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = {
1114
+ /**
1115
+ * @description Whether to log the sql queries and other debug information
1116
+ */
1117
+ readonly logs?: boolean;
1118
+ /**
1119
+ * @description The connection policies to use for the sql data source that are not configured in the driverOptions
1120
+ */
1121
+ connectionPolicies?: ConnectionPolicies;
1122
+ /**
1123
+ * @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
1124
+ */
1125
+ queryFormatOptions?: FormatOptionsWithLanguage;
1126
+ /**
1127
+ * @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
1128
+ * @description Models can still be used as standalone entities, but they won't be available for the sql data source instance
1129
+ */
1130
+ models?: T;
1131
+ /**
1132
+ * @description The path to the migrations folder for the sql data source, it's used to configure the migrations path for the sql data source
1133
+ * @default "database/migrations"
1134
+ */
1135
+ migrationsPath?: string;
1136
+ /**
1137
+ * @description The cache strategy to use for the sql data source, it's used to configure the cache strategy for the sql data source
1138
+ */
1139
+ cacheStrategy?: {
1140
+ cacheAdapter?: CacheAdapter;
1141
+ keys: C;
1142
+ };
1143
+ /**
1144
+ * @description AdminJS configuration for the admin panel
1145
+ * @description To use AdminJS, install: `npm install adminjs`
1146
+ */
1147
+ adminJs?: AdminJsOptions;
1148
+ };
1149
+ /**
1150
+ * @description Maps a SqlDataSourceType to its corresponding input interface
1151
+ */
1152
+ type MapSqlDataSourceTypeToInput<D extends SqlDataSourceType> = D extends "mysql" | "mariadb" ? MysqlSqlDataSourceInput : D extends "postgres" | "cockroachdb" ? PostgresSqlDataSourceInput : D extends "sqlite" ? SqliteDataSourceInput : D extends "mssql" ? MssqlDataSourceInput : D extends "oracledb" ? OracleDBDataSourceInput : never;
1153
+ /**
1154
+ * @description The input type for the SqlDataSource constructor
1155
+ * @description The connectionPolicies object is used to configure the connection policies for the sql data source
1156
+ */
1157
+ type SqlDataSourceInput<D extends SqlDataSourceType = SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = SqlDataSourceInputBase<T, C> & {
1158
+ /**
1159
+ * @description The type of the database to connect to
1160
+ */
1161
+ readonly type: D;
1162
+ /**
1163
+ * @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
1164
+ * @warning For usage with types, you must have driver types installed if the driver handles types in a type package like e.g. `@types/pg`
1165
+ */
1166
+ driverOptions?: SqlDriverSpecificOptions<D>;
1167
+ } & Omit<MapSqlDataSourceTypeToInput<D>, "type">;
1168
+ /**
1169
+ * @description Maps a SqlDataSourceType to its corresponding non-nullable input interface
1170
+ */
1171
+ type MapSqlDataSourceTypeToNotNullableInput<D extends SqlDataSourceType> = D extends "mysql" | "mariadb" ? NotNullableMysqlSqlDataSourceInput : D extends "postgres" | "cockroachdb" ? NotNullablePostgresSqlDataSourceInput : D extends "sqlite" ? NotNullableSqliteDataSourceInput : D extends "mssql" ? NotNullableOracleMssqlDataSourceInput : D extends "oracledb" ? NotNullableOracleDBDataSourceInput : never;
1172
+ type UseConnectionInput<D extends SqlDataSourceType = SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = {
1173
+ /**
1174
+ * @description The type of the database to connect to
1175
+ */
1176
+ readonly type: D;
1177
+ readonly logs?: boolean;
1178
+ readonly models?: T;
1179
+ readonly driverOptions?: SqlDriverSpecificOptions<D>;
1180
+ connectionPolicies?: ConnectionPolicies;
1181
+ queryFormatOptions?: FormatOptionsWithLanguage;
1182
+ cacheStrategy?: {
1183
+ cacheAdapter: CacheAdapter;
1184
+ keys: C;
1185
+ };
1186
+ /**
1187
+ * @description AdminJS configuration for the admin panel
1188
+ * @description AdminJS is completely optional - dependencies are loaded at runtime via dynamic import()
1189
+ */
1190
+ adminJs?: AdminJsOptions;
1191
+ } & Omit<MapSqlDataSourceTypeToNotNullableInput<D>, "type">;
1192
+ type SqlDataSourceType = Exclude<DataSourceType, "mongo">;
1193
+ type SqlCloneOptions = {
1194
+ /**
1195
+ * @description Whether to recreate the pool of connections for the given driver, by default it's false
1196
+ * @warning If false, the pool of connections will be reused from the caller instance
1197
+ */
1198
+ shouldRecreatePool?: boolean;
1199
+ };
1200
+ type getPoolReturnType<T = SqlDataSourceType> = T extends "mysql" ? MysqlConnectionInstance : T extends "mariadb" ? MysqlConnectionInstance : T extends "postgres" ? PgPoolClientInstance : T extends "cockroachdb" ? PgPoolClientInstance : T extends "sqlite" ? SqliteConnectionInstance : T extends "mssql" ? MssqlPoolInstance : T extends "oracledb" ? OracleDBPoolInstance : never;
1201
+ 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"]> : T extends "mssql" ? Transaction$1 : T extends "oracledb" ? Connection : never;
1202
+ /** Only accepts formats `string` e `string as string` */
1203
+ type NoSpace<S extends string> = S extends `${infer _} ${infer _}` ? never : S;
1204
+ type TableFormat<S extends string> = NoSpace<S> | (S extends `${infer L} as ${infer R}` ? `${NoSpace<L>} as ${NoSpace<R>}` : never);
1205
+
1206
+ type AstParserType = {
1207
+ sql: string;
1208
+ bindings: any[];
1061
1209
  };
1062
1210
 
1063
1211
  declare abstract class QueryNode {
@@ -1092,6 +1240,48 @@ declare abstract class QueryNode {
1092
1240
  constructor(keyword: string, isRawValue?: boolean);
1093
1241
  }
1094
1242
 
1243
+ declare class AstParser {
1244
+ private readonly dbType;
1245
+ private readonly model;
1246
+ constructor(model: typeof Model, dbType: SqlDataSourceType);
1247
+ parse(nodes: (QueryNode | null)[], startBindingIndex?: number, isNestedCondition?: boolean): AstParserType;
1248
+ /**
1249
+ * Map the database type to a common type if shares the same driver (e.g. mysql and mariadb)
1250
+ */
1251
+ private mapCommonDbType;
1252
+ /**
1253
+ * @description Generates MSSQL table hints from lock node
1254
+ * MSSQL uses WITH (UPDLOCK), WITH (HOLDLOCK), etc. as table hints
1255
+ * READPAST is the MSSQL equivalent of SKIP LOCKED
1256
+ */
1257
+ private getMssqlTableHints;
1258
+ }
1259
+
1260
+ declare class ColumnTypeNode extends QueryNode {
1261
+ column: string | (() => string);
1262
+ dataType: string;
1263
+ length?: number;
1264
+ precision?: number;
1265
+ scale?: number;
1266
+ enumValues?: readonly string[];
1267
+ autoIncrement?: boolean;
1268
+ withTimezone?: boolean;
1269
+ chainsWith: string;
1270
+ canKeywordBeSeenMultipleTimes: boolean;
1271
+ folder: string;
1272
+ file: string;
1273
+ isRawValue: boolean;
1274
+ constructor(column: string, dataType: string, opts?: {
1275
+ length?: number;
1276
+ precision?: number;
1277
+ scale?: number;
1278
+ enumValues?: readonly string[];
1279
+ withTimezone?: boolean;
1280
+ autoIncrement?: boolean;
1281
+ isRawValue?: boolean;
1282
+ });
1283
+ }
1284
+
1095
1285
  declare class RawNode extends QueryNode {
1096
1286
  rawValue: string;
1097
1287
  canKeywordBeSeenMultipleTimes: boolean;
@@ -1134,31 +1324,6 @@ declare class ConstraintNode extends QueryNode {
1134
1324
  }, isRawValue?: boolean);
1135
1325
  }
1136
1326
 
1137
- declare class ColumnTypeNode extends QueryNode {
1138
- column: string | (() => string);
1139
- dataType: string;
1140
- length?: number;
1141
- precision?: number;
1142
- scale?: number;
1143
- enumValues?: readonly string[];
1144
- autoIncrement?: boolean;
1145
- withTimezone?: boolean;
1146
- chainsWith: string;
1147
- canKeywordBeSeenMultipleTimes: boolean;
1148
- folder: string;
1149
- file: string;
1150
- isRawValue: boolean;
1151
- constructor(column: string, dataType: string, opts?: {
1152
- length?: number;
1153
- precision?: number;
1154
- scale?: number;
1155
- enumValues?: readonly string[];
1156
- withTimezone?: boolean;
1157
- autoIncrement?: boolean;
1158
- isRawValue?: boolean;
1159
- });
1160
- }
1161
-
1162
1327
  type LockType = "for_update" | "for_share" | "for_no_key_update" | "for_key_share";
1163
1328
  declare class LockNode extends QueryNode {
1164
1329
  lockType: LockType;
@@ -1192,47 +1357,147 @@ declare class WithNode extends QueryNode {
1192
1357
  constructor(clause: string, alias: string, body: QueryNode | QueryNode[]);
1193
1358
  }
1194
1359
 
1195
- declare abstract class BaseBuilder {
1196
- protected nodes: QueryNode[];
1197
- constructor(nodes: QueryNode[]);
1198
- getNodes(): QueryNode[];
1360
+ declare class FromNode extends QueryNode {
1361
+ table: string | QueryNode | QueryNode[];
1362
+ chainsWith: string;
1363
+ canKeywordBeSeenMultipleTimes: boolean;
1364
+ folder: string;
1365
+ file: string;
1366
+ alias?: string;
1367
+ constructor(table: string | QueryNode | QueryNode[], alias?: string);
1199
1368
  }
1200
1369
 
1201
- declare class ConstraintBuilder extends BaseBuilder {
1202
- private readonly columnNode;
1203
- private readonly tableName?;
1204
- private namedConstraints;
1205
- private context;
1206
- private sqlType;
1207
- constructor(sqlType: SqlDataSourceType, nodes: QueryNode[], columnNode: ColumnTypeNode, tableName?: string, namedConstraints?: QueryNode[], context?: CreateTableContext);
1208
- /**
1209
- * @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}
1210
- * @param options is the options for the primary key constraint
1211
- */
1212
- primaryKey(options?: PrimaryKeyOptions): this;
1213
- /**
1214
- * @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}
1215
- * @param references is the table and column name to reference, e.g. "users.id"
1216
- * @param options is the options for the foreign key constraint
1217
- */
1218
- foreignKey(references: `${string}.${string}`, options?: ForeignKeyOptions): this;
1219
- /**
1220
- * @description Sets the column to auto increment
1221
- */
1222
- increment(): this;
1223
- /**
1224
- * @description Sets the column to not nullable
1225
- */
1226
- notNullable(): this;
1227
- /**
1228
- * @description Sets the column to nullable, by default it already is nullable, this method is only used for alter table
1229
- */
1230
- nullable(): this;
1231
- /**
1232
- * @description Sets the default value for the column
1233
- * @param value is the default value for the column
1234
- */
1235
- default(value: string | number | boolean | null | RawNode): this;
1370
+ declare class DeleteNode extends QueryNode {
1371
+ fromNode: FromNode;
1372
+ chainsWith: string;
1373
+ canKeywordBeSeenMultipleTimes: boolean;
1374
+ folder: string;
1375
+ file: string;
1376
+ constructor(fromNode: FromNode, isRawValue?: boolean);
1377
+ }
1378
+
1379
+ declare class InsertNode extends QueryNode {
1380
+ fromNode: FromNode;
1381
+ records: Record<string, any>[];
1382
+ returning?: string[];
1383
+ disableReturning: boolean;
1384
+ chainsWith: string;
1385
+ canKeywordBeSeenMultipleTimes: boolean;
1386
+ folder: string;
1387
+ file: string;
1388
+ constructor(fromNode: FromNode, records?: Record<string, any>[], returning?: string[], disableReturning?: boolean, isRawValue?: boolean);
1389
+ }
1390
+
1391
+ declare class OnDuplicateNode extends QueryNode {
1392
+ table: string;
1393
+ conflictColumns: string[];
1394
+ columnsToUpdate: string[];
1395
+ returning?: string[];
1396
+ mode: "update" | "ignore";
1397
+ chainsWith: string;
1398
+ canKeywordBeSeenMultipleTimes: boolean;
1399
+ folder: string;
1400
+ file: string;
1401
+ constructor(table: string, conflictColumns: string[], columnsToUpdate: string[], mode?: "update" | "ignore", returning?: string[], isRawValue?: boolean);
1402
+ }
1403
+
1404
+ declare class TruncateNode extends QueryNode {
1405
+ fromNode: FromNode | string;
1406
+ chainsWith: string;
1407
+ canKeywordBeSeenMultipleTimes: boolean;
1408
+ folder: string;
1409
+ file: string;
1410
+ constructor(fromNode: FromNode | string, isRawValue?: boolean);
1411
+ }
1412
+
1413
+ declare class UpdateNode extends QueryNode {
1414
+ fromNode: FromNode;
1415
+ columns: string[];
1416
+ values: (any | RawNode)[];
1417
+ chainsWith: string;
1418
+ canKeywordBeSeenMultipleTimes: boolean;
1419
+ folder: string;
1420
+ file: string;
1421
+ constructor(fromNode: FromNode, columns?: string[], values?: (any | RawNode)[], isRawValue?: boolean);
1422
+ }
1423
+
1424
+ declare class InterpreterUtils {
1425
+ private readonly model;
1426
+ private readonly modelColumnsMap;
1427
+ constructor(model: typeof Model);
1428
+ formatStringColumn(dbType: SqlDataSourceType, column: string): string;
1429
+ /**
1430
+ * @description Formats the table name for the database type, idempotent for quoting
1431
+ */
1432
+ formatStringTable(dbType: SqlDataSourceType, table: string): string;
1433
+ prepareColumns(columns: string[], values: any[], mode?: "insert" | "update"): Promise<{
1434
+ columns: string[];
1435
+ values: any[];
1436
+ }>;
1437
+ /**
1438
+ * @description Formats the from node for write operations removing the "from" keyword
1439
+ */
1440
+ getFromForWriteOperations(dbType: SqlDataSourceType, fromNode: FromNode): string;
1441
+ }
1442
+
1443
+ type OpenApiModelType = {
1444
+ type: "object";
1445
+ properties: Record<string, OpenApiModelPropertyType>;
1446
+ required?: string[];
1447
+ };
1448
+ type OpenApiModelPropertyType = {
1449
+ type: string;
1450
+ items?: OpenApiModelType;
1451
+ enum?: string[];
1452
+ format?: string;
1453
+ description?: string;
1454
+ example?: any;
1455
+ default?: any;
1456
+ nullable?: boolean;
1457
+ };
1458
+
1459
+ declare abstract class BaseBuilder {
1460
+ protected nodes: QueryNode[];
1461
+ constructor(nodes: QueryNode[]);
1462
+ getNodes(): QueryNode[];
1463
+ }
1464
+
1465
+ declare class ConstraintBuilder extends BaseBuilder {
1466
+ private readonly columnNode;
1467
+ private readonly tableName?;
1468
+ private namedConstraints;
1469
+ private context;
1470
+ private sqlType;
1471
+ constructor(sqlType: SqlDataSourceType, nodes: QueryNode[], columnNode: ColumnTypeNode, tableName?: string, namedConstraints?: QueryNode[], context?: CreateTableContext);
1472
+ /**
1473
+ * @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}
1474
+ * @param options is the options for the primary key constraint
1475
+ */
1476
+ primaryKey(options?: PrimaryKeyOptions): this;
1477
+ /**
1478
+ * @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}
1479
+ * @param references is the table and column name to reference, e.g. "users.id"
1480
+ * @param options is the options for the foreign key constraint
1481
+ */
1482
+ foreignKey(references: `${string}.${string}`, options?: ForeignKeyOptions): this;
1483
+ /**
1484
+ * @description Sets the column to auto increment
1485
+ */
1486
+ increment(): this;
1487
+ /**
1488
+ * @description Sets the column to not nullable
1489
+ */
1490
+ notNullable(): this;
1491
+ /**
1492
+ * @description Sets the column to nullable, by default it already is nullable, this method is only used for alter table
1493
+ */
1494
+ nullable(): this;
1495
+ /**
1496
+ * @description Sets the default value for the column
1497
+ * @param value is the default value for the column
1498
+ * @oracle not supported must be defined manually in a separate statement
1499
+ */
1500
+ default(value: string | number | boolean | null | RawNode): this;
1236
1501
  /**
1237
1502
  * @description Sets the column to unique
1238
1503
  * @param options is the options for the unique constraint
@@ -1704,35 +1969,6 @@ declare class Schema {
1704
1969
  private generateAstInstance;
1705
1970
  }
1706
1971
 
1707
- declare class FromNode extends QueryNode {
1708
- table: string | QueryNode | QueryNode[];
1709
- chainsWith: string;
1710
- canKeywordBeSeenMultipleTimes: boolean;
1711
- folder: string;
1712
- file: string;
1713
- alias?: string;
1714
- constructor(table: string | QueryNode | QueryNode[], alias?: string);
1715
- }
1716
-
1717
- declare class InterpreterUtils {
1718
- private readonly model;
1719
- private readonly modelColumnsMap;
1720
- constructor(model: typeof Model);
1721
- formatStringColumn(dbType: SqlDataSourceType, column: string): string;
1722
- /**
1723
- * @description Formats the table name for the database type, idempotent for quoting
1724
- */
1725
- formatStringTable(dbType: SqlDataSourceType, table: string): string;
1726
- prepareColumns(columns: string[], values: any[], mode?: "insert" | "update"): Promise<{
1727
- columns: string[];
1728
- values: any[];
1729
- }>;
1730
- /**
1731
- * @description Formats the from node for write operations removing the "from" keyword
1732
- */
1733
- getFromForWriteOperations(dbType: SqlDataSourceType, fromNode: FromNode): string;
1734
- }
1735
-
1736
1972
  type DeleteOptions = {
1737
1973
  ignoreBeforeDeleteHook?: boolean;
1738
1974
  };
@@ -2885,223 +3121,82 @@ type UpdateOptions = {
2885
3121
  ignoreBeforeUpdateHook?: boolean;
2886
3122
  };
2887
3123
 
2888
- type TransactionIsolationLevel = "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
2889
- type StartTransactionOptions = {
2890
- isolationLevel?: TransactionIsolationLevel;
2891
- };
2892
3124
  /**
2893
- * @description Options for the transaction execution
3125
+ * @description Due to query limitations some query builder methods may not be available in a RelationQueryBuilder
2894
3126
  */
2895
- type TransactionExecutionOptions = {
3127
+ 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">;
3128
+
3129
+ declare class ModelQueryBuilder<T extends Model, A extends Record<string, any> = {}, R extends Record<string, any> = {}> extends QueryBuilder<T> {
3130
+ relation: Relation;
3131
+ protected sqlModelManagerUtils: SqlModelManagerUtils<T>;
3132
+ protected relationQueryBuilders: ModelQueryBuilder<any>[];
3133
+ protected modelSelectedColumns: string[];
3134
+ private modelColumnsMap;
3135
+ private modelColumnsDatabaseNames;
3136
+ protected limitValue?: number;
3137
+ protected offsetValue?: number;
3138
+ performance: {
3139
+ many: (options?: ManyOptions, returnType?: "millis" | "seconds") => Promise<{
3140
+ data: AnnotatedModel<T, A, R>[];
3141
+ time: number;
3142
+ }>;
3143
+ one: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3144
+ data: AnnotatedModel<T, A, R> | null;
3145
+ time: number;
3146
+ }>;
3147
+ oneOrFail: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3148
+ data: AnnotatedModel<T, A, R>;
3149
+ time: number;
3150
+ }>;
3151
+ first: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3152
+ data: AnnotatedModel<T, A, R> | null;
3153
+ time: number;
3154
+ }>;
3155
+ firstOrFail: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3156
+ data: AnnotatedModel<T, A, R>;
3157
+ time: number;
3158
+ }>;
3159
+ paginate: (page: number, perPage: number, options?: {
3160
+ ignoreHooks?: boolean;
3161
+ }, returnType?: "millis" | "seconds") => Promise<{
3162
+ data: PaginatedData<T, A, R>;
3163
+ time: number;
3164
+ }>;
3165
+ exists: (returnType?: "millis" | "seconds") => Promise<{
3166
+ data: boolean;
3167
+ time: number;
3168
+ }>;
3169
+ paginateWithCursor: (page: number, options: PaginateWithCursorOptions<T, ModelKey<T>>, cursor?: Cursor<T, ModelKey<T>>, returnType?: "millis" | "seconds") => Promise<{
3170
+ data: [CursorPaginatedData<T, A, R>, Cursor<T, ModelKey<T>>];
3171
+ time: number;
3172
+ }>;
3173
+ truncate: (returnType?: "millis" | "seconds") => Promise<{
3174
+ data: void;
3175
+ time: number;
3176
+ }>;
3177
+ delete: (returnType?: "millis" | "seconds") => Promise<{
3178
+ data: number;
3179
+ time: number;
3180
+ }>;
3181
+ update: (data: Partial<ModelWithoutRelations<T>>, options?: UpdateOptions, returnType?: "millis" | "seconds") => Promise<{
3182
+ data: number;
3183
+ time: number;
3184
+ }>;
3185
+ softDelete: (options?: Omit<SoftDeleteOptions<T>, "ignoreBeforeDeleteHook">, returnType?: "millis" | "seconds") => Promise<{
3186
+ data: number;
3187
+ time: number;
3188
+ }>;
3189
+ pluck: (key: ModelKey<T>, returnType?: "millis" | "seconds") => Promise<{
3190
+ data: PluckReturnType<T, ModelKey<T>>;
3191
+ time: number;
3192
+ }>;
3193
+ };
3194
+ constructor(model: typeof Model, sqlDataSource: SqlDataSource);
2896
3195
  /**
2897
- * @description If true, the transaction will throw an error if it is inactive
3196
+ * @description Returns true if the query builder is a relation query builder, this changes the behavior of the query builder like limit, offset, etc.
3197
+ * @internal
2898
3198
  */
2899
- throwErrorOnInactiveTransaction?: boolean;
2900
- };
2901
- type TransactionOptionsOrCallback = StartTransactionOptions | ((trx: Transaction) => Promise<void>);
2902
- type StartTransactionReturnType<T extends TransactionOptionsOrCallback> = T extends StartTransactionOptions ? Transaction : T extends (trx: Transaction) => Promise<void> ? void : Transaction;
2903
-
2904
- /**
2905
- * @description Transaction class, not meant to be used directly, use sql.startTransaction() instead
2906
- */
2907
- declare class Transaction {
2908
- /**
2909
- * @description The sql data source instance that the transaction is running on here you can both query or execute raw queries
2910
- * @example
2911
- * ```ts
2912
- * import { sql } from "hysteria-orm";
2913
- * import { User } from "./models/user";
2914
- *
2915
- * // Raw queries
2916
- * const trx = await sql.startTransaction();
2917
- * await trx.rawQuery("SELECT * FROM users");
2918
- *
2919
- * // Model manager
2920
- * const modelManager = trx.sql.getModelManager(User);
2921
- * await modelManager.insert({ name: "John Doe" });
2922
- *
2923
- * // Query builder
2924
- * await trx.query(User.table).insert({ name: "John Doe" });
2925
- *
2926
- * await trx.commit();
2927
- * ```
2928
- */
2929
- sql: SqlDataSourceWithoutTransaction;
2930
- /**
2931
- * @description Whether the transaction is active
2932
- */
2933
- isActive: boolean;
2934
- /**
2935
- * @description The transaction unique identifier
2936
- */
2937
- transactionId: string;
2938
- private connectionReleased;
2939
- private isolationLevel?;
2940
- private isNested;
2941
- private nestingDepth;
2942
- constructor(sql: SqlDataSource, isolationLevel?: TransactionIsolationLevel, isNested?: boolean, nestingDepth?: number);
2943
- /**
2944
- * @description Creates a new transaction with the same isolation level and same connection using save points
2945
- * @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
2946
- */
2947
- nestedTransaction(): Promise<Transaction>;
2948
- nestedTransaction(cb: (trx: Transaction) => Promise<void>): Promise<void>;
2949
- /**
2950
- * @description Starts a transaction, automatically handled from the sql data source instance in the `startTransaction` method
2951
- */
2952
- startTransaction(): Promise<void>;
2953
- /**
2954
- * @description Commit the transaction releasing the connection
2955
- * @throws {HysteriaError} if the transaction is not active and options.throwErrorOnInactiveTransaction is true
2956
- * @logs if the transaction is not active and options.throwErrorOnInactiveTransaction is false
2957
- */
2958
- commit(options?: TransactionExecutionOptions): Promise<void>;
2959
- /**
2960
- * @description Rollback the transaction releasing the connection
2961
- * @throws {HysteriaError} if the transaction is not active and options.throwErrorOnInactiveTransaction is true
2962
- * @logs if the transaction is not active and options.throwErrorOnInactiveTransaction is false
2963
- */
2964
- rollback(options?: TransactionExecutionOptions): Promise<void>;
2965
- /**
2966
- * @description Release the connection, does nothing if the connection is already released
2967
- */
2968
- private releaseConnection;
2969
- private getIsolationLevelQuery;
2970
- private getSavePointName;
2971
- private getMssqlTransactionLevel;
2972
- }
2973
-
2974
- type ModelWithoutRelations<T extends Model> = Pick<T, ExcludeRelations<Omit<T, "*">>>;
2975
- type NumberModelKey<T extends Model> = {
2976
- [K in keyof T]: T[K] extends number | bigint ? K : never;
2977
- }[keyof T];
2978
- type BaseModelMethodOptions = {
2979
- /**
2980
- * @description The connection to use for the model, by default the main connection will be used
2981
- * @description The main connection is the one created by the `sql.connect` method
2982
- * @example
2983
- * ```ts
2984
- * import { sql } from "hysteria-orm";
2985
- * const customConnection = await sql.connectToSecondarySource({
2986
- * type: "postgres",
2987
- * host: "localhost",
2988
- * username: "root",
2989
- * password: "root",
2990
- * database: "test",
2991
- * port: 5432,
2992
- * });
2993
- *
2994
- * const user = await User.query({ connection: customConnection }).first();
2995
- * ```
2996
- */
2997
- connection?: SqlDataSource | AugmentedSqlDataSource;
2998
- /**
2999
- * @description The transaction instance to use for the model
3000
- */
3001
- trx?: Transaction;
3002
- /**
3003
- * @description Whether to ignore the hooks for the model
3004
- */
3005
- ignoreHooks?: boolean;
3006
- };
3007
- /**
3008
- * @description Options that can be provided to a raw sql operation (like the raw QueryBuilder)
3009
- */
3010
- type RawModelOptions = {
3011
- /**
3012
- * Alias for the table
3013
- */
3014
- alias?: string;
3015
- /**
3016
- * @description Convert the column casing before making a Database query, by default preserves what is provided
3017
- */
3018
- databaseCaseConvention?: CaseConvention;
3019
- /**
3020
- * Column to use for soft deleted, by default is `deleted_at`
3021
- */
3022
- softDeleteColumn?: string;
3023
- /**
3024
- * Column to use for soft deleted, by default is date in format: "YYYY-MM-DD HH:mm:ss" in UTC timezone
3025
- */
3026
- softDeleteValue?: string | boolean;
3027
- };
3028
-
3029
- /**
3030
- * @description Due to query limitations some query builder methods may not be available in a RelationQueryBuilder
3031
- */
3032
- 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">;
3033
-
3034
- declare class ModelQueryBuilder<T extends Model, A extends Record<string, any> = {}, R extends Record<string, any> = {}> extends QueryBuilder<T> {
3035
- relation: Relation;
3036
- protected sqlModelManagerUtils: SqlModelManagerUtils<T>;
3037
- protected relationQueryBuilders: ModelQueryBuilder<any>[];
3038
- protected modelSelectedColumns: string[];
3039
- private modelColumnsMap;
3040
- private modelColumnsDatabaseNames;
3041
- protected limitValue?: number;
3042
- protected offsetValue?: number;
3043
- performance: {
3044
- many: (options?: ManyOptions, returnType?: "millis" | "seconds") => Promise<{
3045
- data: AnnotatedModel<T, A, R>[];
3046
- time: number;
3047
- }>;
3048
- one: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3049
- data: AnnotatedModel<T, A, R> | null;
3050
- time: number;
3051
- }>;
3052
- oneOrFail: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3053
- data: AnnotatedModel<T, A, R>;
3054
- time: number;
3055
- }>;
3056
- first: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3057
- data: AnnotatedModel<T, A, R> | null;
3058
- time: number;
3059
- }>;
3060
- firstOrFail: (options?: OneOptions, returnType?: "millis" | "seconds") => Promise<{
3061
- data: AnnotatedModel<T, A, R>;
3062
- time: number;
3063
- }>;
3064
- paginate: (page: number, perPage: number, options?: {
3065
- ignoreHooks?: boolean;
3066
- }, returnType?: "millis" | "seconds") => Promise<{
3067
- data: PaginatedData<T, A, R>;
3068
- time: number;
3069
- }>;
3070
- exists: (returnType?: "millis" | "seconds") => Promise<{
3071
- data: boolean;
3072
- time: number;
3073
- }>;
3074
- paginateWithCursor: (page: number, options: PaginateWithCursorOptions<T, ModelKey<T>>, cursor?: Cursor<T, ModelKey<T>>, returnType?: "millis" | "seconds") => Promise<{
3075
- data: [CursorPaginatedData<T, A, R>, Cursor<T, ModelKey<T>>];
3076
- time: number;
3077
- }>;
3078
- truncate: (returnType?: "millis" | "seconds") => Promise<{
3079
- data: void;
3080
- time: number;
3081
- }>;
3082
- delete: (returnType?: "millis" | "seconds") => Promise<{
3083
- data: number;
3084
- time: number;
3085
- }>;
3086
- update: (data: Partial<ModelWithoutRelations<T>>, options?: UpdateOptions, returnType?: "millis" | "seconds") => Promise<{
3087
- data: number;
3088
- time: number;
3089
- }>;
3090
- softDelete: (options?: Omit<SoftDeleteOptions<T>, "ignoreBeforeDeleteHook">, returnType?: "millis" | "seconds") => Promise<{
3091
- data: number;
3092
- time: number;
3093
- }>;
3094
- pluck: (key: ModelKey<T>, returnType?: "millis" | "seconds") => Promise<{
3095
- data: PluckReturnType<T, ModelKey<T>>;
3096
- time: number;
3097
- }>;
3098
- };
3099
- constructor(model: typeof Model, sqlDataSource: SqlDataSource);
3100
- /**
3101
- * @description Returns true if the query builder is a relation query builder, this changes the behavior of the query builder like limit, offset, etc.
3102
- * @internal
3103
- */
3104
- protected get isRelationQueryBuilder(): boolean;
3199
+ protected get isRelationQueryBuilder(): boolean;
3105
3200
  /**
3106
3201
  * @description Creates a new ModelQueryBuilder instance from a model. Will use the main connection to the database by default.
3107
3202
  */
@@ -3380,6 +3475,12 @@ declare class ModelManager<T extends Model> {
3380
3475
  * @description Mysql does not return the inserted model, so we need to get the inserted model from the database
3381
3476
  */
3382
3477
  private handleMysqlInsert;
3478
+ /**
3479
+ * @description Oracle with identity columns doesn't support INSERT ALL properly.
3480
+ * This method inserts records one at a time to avoid duplicate ID issues.
3481
+ * After each insert, it queries the row back using unique columns to get the generated ID.
3482
+ */
3483
+ private handleOracleIdentityInsert;
3383
3484
  }
3384
3485
 
3385
3486
  type TableColumnInfo = {
@@ -3417,233 +3518,277 @@ type TableForeignKeyInfo = {
3417
3518
  };
3418
3519
 
3419
3520
  /**
3420
- * @description The SqlDataSource class is the main class for interacting with the database, it's used to create connections, execute queries, and manage transactions
3521
+ * @description Maps a SqlDataSourceType to the raw driver response type
3421
3522
  */
3422
- declare class SqlDataSource extends DataSource {
3423
- private static instance;
3424
- private globalTransaction;
3425
- private sqlType;
3426
- private models;
3427
- private ownsPool;
3523
+ type RawQueryResponseType<D extends SqlDataSourceType> = D extends "mysql" | "mariadb" ? QueryResult : D extends "postgres" | "cockroachdb" ? QueryResult$1 : D extends "sqlite" ? RunResult : D extends "mssql" ? IResult<any> : D extends "oracledb" ? Result<any> : any;
3524
+
3525
+ type TransactionIsolationLevel = "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
3526
+ type StartTransactionOptions = {
3527
+ isolationLevel?: TransactionIsolationLevel;
3528
+ };
3529
+ /**
3530
+ * @description Options for the transaction execution
3531
+ */
3532
+ type TransactionExecutionOptions = {
3428
3533
  /**
3429
- * @description The pool of connections for the database
3534
+ * @description If true, the transaction will throw an error if it is inactive
3430
3535
  */
3431
- sqlPool: SqlPoolType | null;
3536
+ throwErrorOnInactiveTransaction?: boolean;
3537
+ };
3538
+
3539
+ /**
3540
+ * @description Transaction class, not meant to be used directly, use sql.startTransaction() instead
3541
+ */
3542
+ declare class Transaction {
3432
3543
  /**
3433
- * @description Only used in transaction context to specify the connection, not meant to be used directly
3434
- * @private
3544
+ * @description The sql data source instance that the transaction is running on here you can both query or execute raw queries
3545
+ * @example
3546
+ * ```ts
3547
+ * import { sql } from "hysteria-orm";
3548
+ * import { User } from "./models/user";
3549
+ *
3550
+ * // Raw queries
3551
+ * const trx = await sql.startTransaction();
3552
+ * await trx.rawQuery("SELECT * FROM users");
3553
+ *
3554
+ * // Model manager
3555
+ * const modelManager = trx.sql.getModelManager(User);
3556
+ * await modelManager.insert({ name: "John Doe" });
3557
+ *
3558
+ * // Query builder
3559
+ * await trx.query(User.table).insert({ name: "John Doe" });
3560
+ *
3561
+ * await trx.commit();
3562
+ * ```
3435
3563
  */
3436
- sqlConnection: GetConnectionReturnType<SqlDataSourceType> | null;
3564
+ sql: Omit<SqlDataSource, "transaction" | "startGlobalTransaction" | "startTransaction">;
3437
3565
  /**
3438
- * @description Options provided in the sql data source initialization
3566
+ * @description Whether the transaction is active
3439
3567
  */
3440
- inputDetails: SqlDataSourceInput<SqlDataSourceType>;
3568
+ isActive: boolean;
3441
3569
  /**
3442
- * @description Adapter for `useCache`, uses an in memory strategy by default
3570
+ * @description The transaction unique identifier
3443
3571
  */
3444
- cacheAdapter: CacheAdapter;
3572
+ transactionId: string;
3573
+ private connectionReleased;
3574
+ private isolationLevel?;
3575
+ private isNested;
3576
+ private nestingDepth;
3577
+ constructor(sql: SqlDataSource, isolationLevel?: TransactionIsolationLevel, isNested?: boolean, nestingDepth?: number);
3445
3578
  /**
3446
- * @description Maps global keys to specific handlers for cache handling
3579
+ * @description Creates a new transaction with the same isolation level and same connection using save points
3580
+ * @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
3447
3581
  */
3448
- cacheKeys: CacheKeys;
3582
+ nestedTransaction(): Promise<Transaction>;
3583
+ nestedTransaction(cb: (trx: Transaction) => Promise<void>): Promise<void>;
3449
3584
  /**
3450
- * @description The path to the migrations folder for the sql data source, it's used to configure the migrations path for the sql data source
3585
+ * @description Starts a transaction, automatically handled from the sql data source instance in the `startTransaction` method
3451
3586
  */
3452
- migrationsPath: string;
3587
+ startTransaction(): Promise<void>;
3453
3588
  /**
3454
- * @description AdminJS configuration options
3589
+ * @description Commit the transaction releasing the connection
3590
+ * @throws {HysteriaError} if the transaction is not active and options.throwErrorOnInactiveTransaction is true
3591
+ * @logs if the transaction is not active and options.throwErrorOnInactiveTransaction is false
3455
3592
  */
3456
- private adminJsOptions?;
3593
+ commit(options?: TransactionExecutionOptions): Promise<void>;
3594
+ /**
3595
+ * @description Rollback the transaction releasing the connection
3596
+ * @throws {HysteriaError} if the transaction is not active and options.throwErrorOnInactiveTransaction is true
3597
+ * @logs if the transaction is not active and options.throwErrorOnInactiveTransaction is false
3598
+ */
3599
+ rollback(options?: TransactionExecutionOptions): Promise<void>;
3600
+ /**
3601
+ * @description Release the connection, does nothing if the connection is already released
3602
+ */
3603
+ private releaseConnection;
3604
+ private getIsolationLevelQuery;
3605
+ private getSavePointName;
3606
+ private getMssqlTransactionLevel;
3607
+ }
3608
+
3609
+ /**
3610
+ * @description The SqlDataSource class is the main class for interacting with the database, it's used to create connections, execute queries, and manage transactions
3611
+ * @example
3612
+ * ```ts
3613
+ * // Create and connect to a database
3614
+ * const sql = new SqlDataSource({
3615
+ * type: "mysql",
3616
+ * host: "localhost",
3617
+ * username: "root",
3618
+ * password: "password",
3619
+ * database: "mydb",
3620
+ * models: { User, Post }
3621
+ * });
3622
+ * await sql.connect();
3623
+ *
3624
+ * // Now you can use the connection
3625
+ * const users = await sql.query("users").many();
3626
+ * ```
3627
+ */
3628
+ declare class SqlDataSource<D extends SqlDataSourceType = SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> extends DataSource {
3629
+ #private;
3630
+ private globalTransaction;
3631
+ private sqlType;
3632
+ private _models;
3633
+ private ownsPool;
3634
+ /**
3635
+ * @description The pool of connections for the database
3636
+ */
3637
+ sqlPool: SqlPoolType | null;
3638
+ /**
3639
+ * @description Only used in transaction context to specify the connection, not meant to be used directly
3640
+ * @private
3641
+ */
3642
+ sqlConnection: GetConnectionReturnType<D> | null;
3643
+ /**
3644
+ * @description Options provided in the sql data source initialization
3645
+ */
3646
+ inputDetails: SqlDataSourceInput<D, T, C>;
3647
+ /**
3648
+ * @description Adapter for `useCache`, uses an in memory strategy by default
3649
+ */
3650
+ cacheAdapter: CacheAdapter;
3651
+ /**
3652
+ * @description Maps global keys to specific handlers for cache handling
3653
+ */
3654
+ cacheKeys: C;
3655
+ /**
3656
+ * @description The path to the migrations folder for the sql data source, it's used to configure the migrations path for the sql data source
3657
+ */
3658
+ migrationsPath: string;
3659
+ /**
3660
+ * @description AdminJS configuration options
3661
+ */
3662
+ private adminJsOptions?;
3457
3663
  /**
3458
3664
  * @description Cached AdminJS instance
3459
3665
  */
3460
3666
  private adminJsInstance?;
3461
3667
  /**
3462
- * @description Establishes the default singleton connection used by default by all the Models, if not configuration is passed, env variables will be used instead
3463
- * @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
3464
- * @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
3465
- * @example
3466
- * ```ts
3467
- * import { sql } from "hysteria-orm";
3468
- * const connection = await sql.connect();
3469
- * // You can use both connection and sql from now own, since `sql` will use the default connection after being connected
3470
- * connection.query();
3471
- * sql.query();
3472
- *
3473
- * // Models will use the default connection after being connected
3474
- * User.query(); // Will use the default connection
3475
- * ```
3668
+ * @description Returns the primary instance of the SqlDataSource (set via connect with setPrimary: true)
3669
+ * All models by default will use this instance to execute queries unless you pass a different connection/transaction in the query options
3476
3670
  */
3477
- static connect<U extends SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}>(input: SqlDataSourceInput<U, T, C>, cb?: (sqlDataSource: AugmentedSqlDataSource<T, C>) => Promise<void> | void): Promise<AugmentedSqlDataSource<T, C>>;
3478
- static connect<T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}>(cb?: (sqlDataSource: AugmentedSqlDataSource<T, C>) => Promise<void> | void): Promise<AugmentedSqlDataSource<T, C>>;
3671
+ static get instance(): SqlDataSource;
3479
3672
  /**
3480
- * @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`
3673
+ * @description Creates a secondary database connection that won't be set as the primary instance
3481
3674
  * @description By default not used by the Models, you have to pass it as a parameter to the Models to use it
3482
- * @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
3483
3675
  * @example
3484
3676
  * ```ts
3485
- * const anotherSql = await Sql.connectToSecondarySource({
3486
- * ...connectionData
3677
+ * const secondaryDb = await SqlDataSource.connectToSecondarySource({
3678
+ * type: "postgres",
3679
+ * host: "replica.db.com",
3680
+ * ...
3487
3681
  * });
3488
3682
  *
3489
- * const user = await User.query({ connection: anotherSql }).many();
3683
+ * const user = await User.query({ connection: secondaryDb }).many();
3490
3684
  * ```
3491
3685
  */
3492
- static connectToSecondarySource<U extends SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}>(input: SqlDataSourceInput<U, T, C>, cb?: (sqlDataSource: AugmentedSqlDataSource<T, C>) => Promise<void> | void): Promise<AugmentedSqlDataSource<T, C>>;
3493
- static connectToSecondarySource<T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}>(cb?: (sqlDataSource: AugmentedSqlDataSource<T, C>) => Promise<void> | void): Promise<AugmentedSqlDataSource<T, C>>;
3686
+ static connectToSecondarySource<U extends SqlDataSourceType, M extends Record<string, SqlDataSourceModel> = {}, K extends CacheKeys = {}>(input: SqlDataSourceInput<U, M, K>, cb?: (sqlDataSource: SqlDataSource<U, M, K>) => Promise<void> | void): Promise<SqlDataSource<U, M, K>>;
3494
3687
  /**
3495
- * @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
3496
- * @description By default not used by the Models, you have to pass it as a parameter to the Models to use it
3497
- * @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
3688
+ * @description Creates a temporary connection that is automatically closed after the callback is executed
3498
3689
  * @example
3499
3690
  * ```ts
3500
- * await Sql.useConnection({
3501
- * ...connectionData
3502
- * }, (sql) => {
3503
- * const user = await User.query({ connection: sql }).many();
3691
+ * await SqlDataSource.useConnection({
3692
+ * type: "mysql",
3693
+ * ...connectionData
3694
+ * }, async (sql) => {
3695
+ * const user = await User.query({ connection: sql }).many();
3504
3696
  * });
3697
+ * // Connection is automatically closed here
3505
3698
  * ```
3506
3699
  */
3507
- static useConnection<U extends SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}>(connectionDetails: UseConnectionInput<U, T, C>, cb: (sqlDataSource: AugmentedSqlDataSource<T, C>) => Promise<void>): Promise<void>;
3508
- /**
3509
- * @description Returns the instance of the SqlDataSource
3510
- * @throws {HysteriaError} If the connection is not established
3511
- */
3512
- static getInstance(): SqlDataSource;
3700
+ static useConnection<U extends SqlDataSourceType, M extends Record<string, SqlDataSourceModel> = {}, K extends CacheKeys = {}>(connectionDetails: UseConnectionInput<U, M, K>, cb: (sqlDataSource: SqlDataSource<U, M, K>) => Promise<void>): Promise<void>;
3513
3701
  /**
3514
- * @description Returns a QueryBuilder instance
3515
- * @description Query builder from the SqlDataSource instance returns raw data from the database, the data is not parsed or serialized in any way
3516
- * @description Optimal for performance-critical operations
3517
- * @description Use Models to have type safety and serialization
3518
- * @description Default soft delete column is "deleted_at" with stringed date value
3519
- * @param table The table name to query from, must be in valid sql format `table` or `table as alias`
3520
- */
3521
- static query<S extends string>(table: TableFormat<S>, options?: RawModelOptions): QueryBuilder;
3522
- /**
3523
- * @description Returns a dry query builder instance
3524
- * @description The dry query builder instance will not execute the query, it will return the query statement
3525
- * @returns The dry query builder instance
3702
+ * @description Closes the primary connection (singleton instance)
3526
3703
  */
3527
- static dryQuery<S extends string>(table: TableFormat<S>, options?: RawModelOptions): DryQueryBuilderWithoutReadOperations;
3528
- /**
3529
- * @description Creates a table on the database, return the query to be executed to create the table
3530
- */
3531
- static createTable(...args: Parameters<Schema["createTable"]>): string;
3704
+ static closeConnection(): Promise<void>;
3532
3705
  /**
3533
- * @description Alters a table on the database, return the queries to be executed in order to alter the table
3706
+ * @alias closeConnection
3534
3707
  */
3535
- static alterTable(...args: Parameters<Schema["alterTable"]>): string[];
3708
+ static disconnect(): Promise<void>;
3536
3709
  /**
3537
- * @description Starts a global transaction on the database
3710
+ * @description Starts a global transaction on the primary database connection
3711
+ * @description Intended for testing purposes - wraps all operations in a transaction that can be rolled back
3538
3712
  */
3539
3713
  static startGlobalTransaction(options?: StartTransactionOptions): Promise<Transaction>;
3540
3714
  /**
3541
- * @description Commits a global transaction on the database
3715
+ * @description Commits a global transaction on the primary database connection
3542
3716
  * @throws {HysteriaError} If the global transaction is not started
3543
3717
  */
3544
3718
  static commitGlobalTransaction(): Promise<void>;
3545
3719
  /**
3546
- * @description Rolls back a global transaction on the database
3720
+ * @description Rolls back a global transaction on the primary database connection
3547
3721
  * @throws {HysteriaError} If the global transaction is not started
3548
3722
  */
3549
3723
  static rollbackGlobalTransaction(): Promise<void>;
3550
3724
  /**
3551
- * @description Starts a transaction on a dedicated connection from the pool and returns a Transaction instance
3552
- * @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
3553
- * @param options.isolationLevel The isolation level to use for the transaction
3554
- * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
3555
- * @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)
3556
- * @sqlite ignores the isolation level
3557
- */
3558
- static startTransaction(options?: StartTransactionOptions): Promise<Transaction>;
3559
- static startTransaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
3560
- /**
3561
- * @alias startTransaction
3562
- * @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
3563
- * @param options.isolationLevel The isolation level to use for the transaction
3564
- * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
3565
- * @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)
3566
- * @sqlite ignores the isolation level
3567
- */
3568
- static transaction(options?: StartTransactionOptions): Promise<Transaction>;
3569
- static transaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
3570
- static transaction(optionsOrCb?: StartTransactionOptions | ((trx: Transaction) => Promise<void>), maybeOptions?: StartTransactionOptions): Promise<StartTransactionReturnType<TransactionOptionsOrCallback>>;
3571
- /**
3572
- * @description Retrieves informations from the database for the given table
3573
- */
3574
- static getTableSchema(table: string): Promise<TableSchemaInfo>;
3575
- /**
3576
- * @description Closes the current connection
3577
- */
3578
- static closeConnection(): Promise<void>;
3579
- /**
3580
- * @alias closeConnection
3725
+ * @description Returns true if the primary instance is in a global transaction
3581
3726
  */
3582
- static disconnect(): Promise<void>;
3583
- /**
3584
- * @description Executes a raw query on the database
3585
- */
3586
- static rawQuery<T = any>(query: string, params?: any[]): Promise<T>;
3727
+ static get isInGlobalTransaction(): boolean;
3587
3728
  /**
3588
- * @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
3729
+ * @description Creates a new SqlDataSource instance. Call `.connect()` to establish the connection.
3730
+ * @param input Configuration options for the database connection. If not provided, uses env variables.
3589
3731
  * @example
3590
3732
  * ```ts
3591
- * import { sql } from "hysteria-orm";
3733
+ * // With explicit config
3734
+ * const sql = new SqlDataSource({
3735
+ * type: "mysql",
3736
+ * host: "localhost",
3737
+ * username: "root",
3738
+ * password: "password",
3739
+ * database: "mydb",
3740
+ * models: { User, Post }
3741
+ * });
3742
+ * await sql.connect();
3592
3743
  *
3593
- * await User.query().where("name", sql.rawStatement("LOWER(name)"));
3744
+ * // Using env variables
3745
+ * const sql = new SqlDataSource();
3746
+ * await sql.connect();
3594
3747
  * ```
3595
3748
  */
3596
- static rawStatement(value: string): RawNode;
3749
+ constructor(input?: SqlDataSourceInput<D, T, C>);
3597
3750
  /**
3598
- * @description Initializes AdminJS with the configured options
3599
- * @description All AdminJS dependencies are loaded at runtime via dynamic import() to keep the plugin optional
3600
- * @description To use AdminJS, install: npm install adminjs
3601
- * @throws {HysteriaError} If AdminJS is not enabled or connection not established
3602
- * @returns The AdminJS instance
3751
+ * @description Establishes the database connection and sets this instance as the primary connection
3752
+ * @throws {HysteriaError} If the connection is already established, use `SqlDataSource.useConnection` or `SqlDataSource.connectToSecondarySource` for auxiliary connections
3753
+ * @example
3754
+ * ```ts
3755
+ * const sql = new SqlDataSource({ type: "mysql", ... });
3756
+ * await sql.connect();
3757
+ * ```
3603
3758
  */
3604
- static initializeAdminJs(): Promise<AdminJsAdminInstance>;
3759
+ connect(): Promise<void>;
3605
3760
  /**
3606
- * @description Initializes AdminJS with Express router
3607
- * @description All AdminJS dependencies are loaded at runtime via dynamic import() to keep the plugin optional
3608
- * @description To use AdminJS with Express, install: npm install adminjs @adminjs/express express express-formidable --save-dev
3609
- * @throws {HysteriaError} If AdminJS is not enabled or connection not established
3610
- * @returns The AdminJS instance with Express router
3761
+ * @description Returns true if the connection is established
3611
3762
  */
3612
- static initializeAdminJsExpress(): Promise<AdminJsInstance>;
3763
+ get isConnected(): boolean;
3613
3764
  /**
3614
- * @description Returns the AdminJS instance if initialized
3615
- * @returns The AdminJS instance or undefined if not initialized
3765
+ * @description Returns true if this instance is in a global transaction
3616
3766
  */
3617
- static getAdminJs(): AdminJsInstance | undefined;
3767
+ get isInGlobalTransaction(): boolean;
3618
3768
  /**
3619
- * @description Checks if AdminJS is enabled
3620
- * @returns True if AdminJS is enabled
3769
+ * @description Returns the models configured on this SqlDataSource instance
3621
3770
  */
3622
- static isAdminJsEnabled(): boolean;
3623
- private constructor();
3771
+ get models(): T;
3624
3772
  /**
3625
3773
  * @description Uses the cache adapter to get a value from the cache
3626
3774
  * @param key The key to get the value from
3627
3775
  * @param args The arguments to pass to the key handler
3628
3776
  */
3629
- useCache<M extends Record<string, typeof Model>, C extends CacheKeys, K extends keyof C>(this: AugmentedSqlDataSource<M, C>, key: K, ...args: Parameters<C[K]>): Promise<UseCacheReturnType<C, K>>;
3777
+ useCache<K extends keyof C>(key: K, ...args: Parameters<C[K]>): Promise<UseCacheReturnType<C, K>>;
3630
3778
  /**
3631
3779
  * @description Uses the cache adapter to get a value from the cache
3632
3780
  * @param key The key to get the value from
3633
3781
  * @param ttl The time to live for the value in milliseconds
3634
3782
  * @param args The arguments to pass to the key handler
3635
3783
  */
3636
- useCache<M extends Record<string, typeof Model>, C extends CacheKeys, K extends keyof C>(this: AugmentedSqlDataSource<M, C>, key: K, ttl: number, ...args: Parameters<C[K]>): Promise<UseCacheReturnType<C, K>>;
3784
+ useCache<K extends keyof C>(key: K, ttl: number, ...args: Parameters<C[K]>): Promise<UseCacheReturnType<C, K>>;
3637
3785
  /**
3638
3786
  * @description Invalidates a value from the cache
3639
3787
  * @param key The key to invalidate the value from
3640
- * @param args The arguments to pass to the key handler
3788
+ * @param args The arguments to pass to the key handler (required if the handler expects arguments)
3641
3789
  */
3642
- invalidCache<M extends Record<string, typeof Model>, C extends CacheKeys, K extends keyof C>(this: AugmentedSqlDataSource<M, C>, key: K, ...args: Parameters<C[K]>): Promise<void>;
3643
- /**
3644
- * @description Returns true if the connection is established
3645
- */
3646
- get isConnected(): boolean;
3790
+ invalidCache<K extends keyof C>(key: K, ...args: Parameters<C[K]>): Promise<void>;
3791
+ invalidCache<K extends keyof C>(key: K): Promise<void>;
3647
3792
  /**
3648
3793
  * @description Clones the SqlDataSource instance
3649
3794
  * @param options.shouldRecreatePool Whether to recreate the pool of connections for the given driver, by default it's false
@@ -3654,20 +3799,15 @@ declare class SqlDataSource extends DataSource {
3654
3799
  /**
3655
3800
  * @description Returns the type of the database
3656
3801
  */
3657
- getDbType(): SqlDataSourceType;
3802
+ getDbType(): D;
3658
3803
  /**
3659
- * @description Returns a QueryBuilder instance
3660
- * @description Query builder from the SqlDataSource instance uses raw data from the database so the data is not parsed or serialized in any way
3661
- * @description Optimal for performance-critical operations
3662
- * @description Use Models to have type safety and serialization
3663
- * @description Default soft delete column is "deleted_at" with stringed date value
3664
- * @param table The table name to query from, must be in valid sql format `table` or `table as alias`
3804
+ * @description Returns a QueryBuilder instance for raw queries
3805
+ * @description Query builder from the SqlDataSource instance returns raw data from the database
3806
+ * @param table The table name to query from
3665
3807
  */
3666
3808
  query<S extends string>(table: TableFormat<S>, options?: RawModelOptions): QueryBuilder;
3667
3809
  /**
3668
- * @description Returns a DryQueryBuilder instance
3669
- * @description The dry query builder instance will not execute the query, it will return the query statement
3670
- * @returns The dry query builder instance
3810
+ * @description Returns a DryQueryBuilder instance that returns the query statement without executing
3671
3811
  */
3672
3812
  dryQuery<S extends string>(table: TableFormat<S>, options?: RawModelOptions): DryQueryBuilderWithoutReadOperations;
3673
3813
  /**
@@ -3679,94 +3819,77 @@ declare class SqlDataSource extends DataSource {
3679
3819
  */
3680
3820
  createTable(...args: Parameters<Schema["createTable"]>): string;
3681
3821
  /**
3682
- * @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
3822
+ * @description Starts a global transaction on the database
3823
+ * @description Intended for testing purposes - wraps all operations in a transaction that can be rolled back
3683
3824
  */
3684
3825
  startGlobalTransaction(options?: StartTransactionOptions): Promise<Transaction>;
3685
3826
  /**
3686
- * @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
3827
+ * @description Commits a global transaction on the database
3687
3828
  * @throws {HysteriaError} If the global transaction is not started
3688
3829
  */
3689
3830
  commitGlobalTransaction(options?: TransactionExecutionOptions): Promise<void>;
3690
3831
  /**
3691
- * @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
3692
- * @throws {HysteriaError} If the global transaction is not started and options.throwErrorOnInactiveTransaction is true
3832
+ * @description Rolls back a global transaction on the database
3693
3833
  */
3694
3834
  rollbackGlobalTransaction(options?: TransactionExecutionOptions): Promise<void>;
3695
3835
  /**
3696
- * @description Get's a connection from the pool and starts a transaction on the database and returns an already started transaction instance
3836
+ * @description Starts a transaction on a dedicated connection from the pool
3697
3837
  * @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
3698
3838
  * @param options.isolationLevel The isolation level to use for the transaction
3699
- * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
3700
- * @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)
3701
3839
  * @sqlite ignores the isolation level
3702
3840
  */
3703
3841
  startTransaction(options?: StartTransactionOptions): Promise<Transaction>;
3704
3842
  startTransaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
3705
3843
  /**
3706
3844
  * @alias startTransaction
3707
- * @description Get's a connection from the pool and starts a transaction on the database and returns an already started transaction instance
3708
- * @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
3709
- * @param options.isolationLevel The isolation level to use for the transaction
3710
- * @param options.throwErrorOnInactiveTransaction Whether to throw an error if the transaction is not active
3711
- * @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)
3712
- * @sqlite ignores the isolation level
3713
3845
  */
3714
3846
  transaction(options?: StartTransactionOptions): Promise<Transaction>;
3715
3847
  transaction(cb: (trx: Transaction) => Promise<void>, options?: StartTransactionOptions): Promise<void>;
3716
3848
  /**
3717
- * @description Returns a ModelManager instance for the given model, it's advised to use Model static methods instead.
3718
- * @description This is intended to use only if you do not want to use active record pattern
3849
+ * @description Returns a ModelManager instance for the given model
3719
3850
  */
3720
- getModelManager<T extends Model>(model: {
3721
- new (): T;
3722
- } | typeof Model): ModelManager<T>;
3851
+ getModelManager<M extends Model>(model: {
3852
+ new (): M;
3853
+ } | typeof Model): ModelManager<M>;
3723
3854
  /**
3724
- * @description Returns the current raw driver Pool, you can specify the type of connection you want to get to have better type safety
3855
+ * @description Returns the current raw driver Pool
3725
3856
  * @throws {HysteriaError} If the connection pool is not established
3726
- * @example
3727
- * const mysqlConnection = sql.getPool("mysql"); // mysql2 Pool
3728
- * const pgConnection = sql.getPool("postgres"); // pg Pool
3729
- * const sqliteConnection = sql.getPool("sqlite"); // sqlite3 Database
3730
3857
  */
3731
- getPool<T extends SqlDataSourceType = typeof this.sqlType>(_specificType?: T): getPoolReturnType<T>;
3858
+ getPool(): getPoolReturnType<D>;
3732
3859
  /**
3733
- * @description Returns a connection from the pool, you can specify the type of connection you want to get to have better type safety
3860
+ * @description Returns a connection from the pool
3734
3861
  * @throws {HysteriaError} If the connection is not established
3735
- * @example
3736
- * const mysqlConnection = sql.getConnection("mysql"); // mysql2 PoolConnection
3737
- * const pgConnection = sql.getConnection("postgres"); // pg PoolClient
3738
- * const sqliteConnection = sql.getConnection("sqlite"); // sqlite3 Database
3739
3862
  */
3740
- getConnection<T extends SqlDataSourceType = typeof this.sqlType>(_specificType?: T): Promise<GetConnectionReturnType<T>>;
3863
+ getConnection(): Promise<GetConnectionReturnType<D>>;
3741
3864
  /**
3742
3865
  * @description Closes the current connection
3743
3866
  * @description If there is an active global transaction, it will be rolled back
3744
3867
  */
3745
3868
  closeConnection(): Promise<void>;
3746
- getConnectionDetails(): SqlDataSourceInput<SqlDataSourceType>;
3869
+ /**
3870
+ * @description Returns the connection details
3871
+ */
3872
+ getConnectionDetails(): SqlDataSourceInput<D, T, C>;
3747
3873
  /**
3748
3874
  * @alias closeConnection
3749
3875
  */
3750
3876
  disconnect(): Promise<void>;
3751
3877
  /**
3752
3878
  * @description Syncs the schema of the database with the models metadata
3753
- * @warning This will drop and recreate all the indexes and constraints, use with caution and not in production environments
3754
- * @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
3879
+ * @warning This will drop and recreate all the indexes and constraints, use with caution
3755
3880
  * @sqlite Not supported but won't throw an error
3756
3881
  */
3757
3882
  syncSchema(options?: {
3758
3883
  transactional: boolean;
3759
3884
  }): Promise<void>;
3760
3885
  /**
3761
- * @description Executes a raw query on the database
3886
+ * @description Executes a raw query on the database and returns the raw driver result
3762
3887
  */
3763
- rawQuery<T = any>(query: string, params?: any[]): Promise<T>;
3888
+ rawQuery<R = RawQueryResponseType<D>>(query: string, params?: any[]): Promise<R>;
3764
3889
  /**
3765
- * @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
3890
+ * @description Adds a raw statement to an operation like where or update
3766
3891
  * @example
3767
3892
  * ```ts
3768
- * import { sql } from "hysteria-orm";
3769
- *
3770
3893
  * await User.query().where("name", sql.rawStatement("LOWER(name)"));
3771
3894
  * ```
3772
3895
  */
@@ -3785,33 +3908,24 @@ declare class SqlDataSource extends DataSource {
3785
3908
  })[];
3786
3909
  /**
3787
3910
  * @description Initializes AdminJS with the configured options
3788
- * @description All AdminJS dependencies are loaded at runtime via dynamic import() to keep the plugin optional
3789
- * @description To use AdminJS, install: npm install adminjs
3790
3911
  * @throws {HysteriaError} If AdminJS is not enabled in the configuration
3791
- * @returns The AdminJS instance
3792
3912
  */
3793
3913
  initializeAdminJs(): Promise<AdminJsAdminInstance>;
3794
3914
  /**
3795
3915
  * @description Initializes AdminJS with Express router
3796
- * @description All AdminJS dependencies are loaded at runtime via dynamic import() to keep the plugin optional
3797
- * @description To use AdminJS with Express, install: npm install adminjs @adminjs/express express express-formidable --save-dev
3798
3916
  * @throws {HysteriaError} If AdminJS is not enabled in the configuration
3799
- * @returns The AdminJS instance with Express router
3800
3917
  */
3801
- initializeAdminJsExpress(): Promise<AdminJsInstance>;
3918
+ initializeAdminJsExpress(): Promise<Required<AdminJsInstance>>;
3802
3919
  /**
3803
3920
  * @description Returns the AdminJS instance if initialized
3804
- * @returns The AdminJS instance or undefined if not initialized
3805
3921
  */
3806
3922
  getAdminJs(): AdminJsInstance | undefined;
3807
3923
  /**
3808
3924
  * @description Returns the AdminJS configuration options
3809
- * @returns The AdminJS configuration options or undefined if not configured
3810
3925
  */
3811
3926
  getAdminJsOptions(): AdminJsOptions | undefined;
3812
3927
  /**
3813
3928
  * @description Checks if AdminJS is enabled
3814
- * @returns True if AdminJS is enabled
3815
3929
  */
3816
3930
  isAdminJsEnabled(): boolean;
3817
3931
  /**
@@ -3819,217 +3933,79 @@ declare class SqlDataSource extends DataSource {
3819
3933
  */
3820
3934
  getTableInfo(table: string): Promise<TableColumnInfo[]>;
3821
3935
  /**
3822
- * @description Introspects table indexes metadata using AST-driven queries
3936
+ * @description Introspects table indexes metadata
3823
3937
  */
3824
3938
  getIndexInfo(table: string): Promise<TableIndexInfo[]>;
3939
+ /**
3940
+ * @description Introspects table foreign keys metadata
3941
+ */
3825
3942
  getForeignKeyInfo(table: string): Promise<TableForeignKeyInfo[]>;
3826
3943
  /**
3827
3944
  * @description Introspects table primary key from the database
3828
3945
  */
3829
3946
  getPrimaryKeyInfo(table: string): Promise<TablePrimaryKeyInfo | undefined>;
3830
- private testConnectionQuery;
3831
- private sanitizeModelKeys;
3832
- static get isInGlobalTransaction(): boolean;
3833
- get isInGlobalTransaction(): boolean;
3834
3947
  /**
3835
- * @description Returns the models registered on this SqlDataSource instance (as provided in connect input)
3948
+ * @description Internal method to establish connection without setting as primary instance
3949
+ * @description Used by connectToSecondarySource and useConnection
3836
3950
  */
3837
- get registeredModels(): Record<string, typeof Model>;
3951
+ private connectWithoutSettingPrimary;
3838
3952
  }
3839
3953
 
3840
- type Sqlite3ConnectionOptions = {
3841
- mode: number;
3842
- };
3843
- type SqlDriverSpecificOptions<T extends DataSourceType> = Omit<DriverSpecificOptions<T>, "mongoOptions" | "redisOptions">;
3844
- type MysqlConnectionInstance = Awaited<ReturnType<Mysql2Import["createPool"]>>;
3845
- type PgPoolClientInstance = InstanceType<PgImport["Pool"]>;
3846
- type SqliteConnectionInstance = InstanceType<Sqlite3Import["Database"]>;
3847
- type MssqlPoolInstance = InstanceType<MssqlImport["ConnectionPool"]>;
3848
- type MssqlConnectionInstance = Awaited<ReturnType<MssqlPoolInstance["connect"]>>;
3849
- type SqlPoolType = MysqlConnectionInstance | PgPoolClientInstance | SqliteConnectionInstance | MssqlPoolInstance;
3850
- /**
3851
- * @description The connection policies for the sql data source
3852
- * @default By default, the connection policies are not set, so no query will be retried
3853
- */
3854
- type ConnectionPolicies = {
3855
- /**
3856
- * @description The retry policy for the sql data source, it allows to retry a query if it fails
3857
- */
3858
- retry?: {
3859
- maxRetries?: number;
3860
- delay?: number;
3861
- };
3862
- };
3863
- type SqlDataSourceModel = typeof Model;
3864
- /**
3865
- * @description The input type for the SqlDataSource constructor
3866
- * @description The connectionPolicies object is used to configure the connection policies for the sql data source
3867
- */
3868
- type SqlDataSourceInput<D extends SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = {
3869
- readonly type?: D;
3870
- /**
3871
- * @description Whether to log the sql queries and other debug information
3872
- */
3873
- readonly logs?: boolean;
3874
- /**
3875
- * @description The connection policies to use for the sql data source that are not configured in the driverOptions
3876
- */
3877
- connectionPolicies?: ConnectionPolicies;
3878
- /**
3879
- * @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
3880
- */
3881
- queryFormatOptions?: FormatOptionsWithLanguage;
3954
+ type ModelWithoutRelations<T extends Model> = Pick<T, ExcludeRelations<Omit<T, "*">>>;
3955
+ type NumberModelKey<T extends Model> = {
3956
+ [K in keyof T]: T[K] extends number | bigint ? K : never;
3957
+ }[keyof T];
3958
+ type BaseModelMethodOptions = {
3882
3959
  /**
3883
- * @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
3884
- * @description Models can still be used as standalone entities, but they won't be available for the sql data source instance
3960
+ * @description The connection to use for the model, by default the main connection will be used
3961
+ * @description The main connection is the one created via `new SqlDataSource().connect()`
3962
+ * @example
3963
+ * ```ts
3964
+ * import { SqlDataSource } from "hysteria-orm";
3965
+ * const customConnection = await SqlDataSource.connectToSecondarySource({
3966
+ * type: "postgres",
3967
+ * host: "localhost",
3968
+ * username: "root",
3969
+ * password: "root",
3970
+ * database: "test",
3971
+ * port: 5432,
3972
+ * });
3973
+ *
3974
+ * const user = await User.query({ connection: customConnection }).first();
3975
+ * ```
3885
3976
  */
3886
- models?: T;
3977
+ connection?: SqlDataSource;
3887
3978
  /**
3888
- * @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
3889
- * @warning For usage with types, you must have driver types installed if the driver handles types in a type package like e.g. `@types/pg`
3979
+ * @description The transaction instance to use for the model
3890
3980
  */
3891
- driverOptions?: SqlDriverSpecificOptions<D>;
3981
+ trx?: Transaction;
3892
3982
  /**
3893
- * @description The path to the migrations folder for the sql data source, it's used to configure the migrations path for the sql data source
3894
- * @default "database/migrations"
3983
+ * @description Whether to ignore the hooks for the model
3895
3984
  */
3896
- migrationsPath?: string;
3985
+ ignoreHooks?: boolean;
3986
+ };
3987
+ /**
3988
+ * @description Options that can be provided to a raw sql operation (like the raw QueryBuilder)
3989
+ */
3990
+ type RawModelOptions = {
3897
3991
  /**
3898
- * @description The cache strategy to use for the sql data source, it's used to configure the cache strategy for the sql data source
3992
+ * Alias for the table
3899
3993
  */
3900
- cacheStrategy?: {
3901
- cacheAdapter?: CacheAdapter;
3902
- keys: C;
3903
- };
3994
+ alias?: string;
3904
3995
  /**
3905
- * @description AdminJS configuration for the admin panel
3906
- * @description To use AdminJS, install: `npm install adminjs`
3996
+ * @description Convert the column casing before making a Database query, by default preserves what is provided
3907
3997
  */
3908
- adminJs?: AdminJsOptions;
3909
- } & (MysqlSqlDataSourceInput | MssqlDataSourceInput | PostgresSqlDataSourceInput | SqliteDataSourceInput);
3910
- type UseConnectionInput<D extends SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = {
3911
- readonly type: Exclude<DataSourceType, "mongo">;
3912
- readonly logs?: boolean;
3913
- readonly models?: T;
3914
- readonly driverOptions?: SqlDriverSpecificOptions<D>;
3915
- connectionPolicies?: ConnectionPolicies;
3916
- queryFormatOptions?: FormatOptionsWithLanguage;
3917
- cacheStrategy?: {
3918
- cacheAdapter: CacheAdapter;
3919
- keys: C;
3920
- };
3998
+ databaseCaseConvention?: CaseConvention;
3921
3999
  /**
3922
- * @description AdminJS configuration for the admin panel
3923
- * @description AdminJS is completely optional - dependencies are loaded at runtime via dynamic import()
4000
+ * Column to use for soft deleted, by default is `deleted_at`
3924
4001
  */
3925
- adminJs?: AdminJsOptions;
3926
- } & (NotNullableMysqlSqlDataSourceInput | NotNullablePostgresSqlDataSourceInput | NotNullableSqliteDataSourceInput);
3927
- type SqlDataSourceType = Exclude<DataSourceType, "mongo">;
3928
- type SqlCloneOptions = {
4002
+ softDeleteColumn?: string;
3929
4003
  /**
3930
- * @description Whether to recreate the pool of connections for the given driver, by default it's false
3931
- * @warning If false, the pool of connections will be reused from the caller instance
4004
+ * Column to use for soft deleted, by default is date in format: "YYYY-MM-DD HH:mm:ss" in UTC timezone
3932
4005
  */
3933
- shouldRecreatePool?: boolean;
3934
- };
3935
- type getPoolReturnType<T = SqlDataSourceType> = T extends "mysql" ? MysqlConnectionInstance : T extends "mariadb" ? MysqlConnectionInstance : T extends "postgres" ? PgPoolClientInstance : T extends "cockroachdb" ? PgPoolClientInstance : T extends "sqlite" ? SqliteConnectionInstance : T extends "mssql" ? MssqlPoolInstance : never;
3936
- 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"]> : T extends "mssql" ? Transaction$1 : never;
3937
- type UseCacheOverloads<C extends CacheKeys> = {
3938
- <K extends keyof C>(key: K, ...args: Parameters<C[K]>): Promise<UseCacheReturnType<C, K>>;
3939
- <K extends keyof C>(key: K, ttl: number, ...args: Parameters<C[K]>): Promise<UseCacheReturnType<C, K>>;
3940
- };
3941
- type UseCacheType<C extends CacheKeys> = keyof C extends never ? SqlDataSource["useCache"] : UseCacheOverloads<C>;
3942
- type InvalidCacheType<C extends CacheKeys> = keyof C extends never ? SqlDataSource["invalidCache"] : <K extends keyof C>(key: K) => Promise<void>;
3943
- type AugmentedSqlDataSource<T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = Omit<SqlDataSource, "useCache" | "invalidCache" | "clone"> & {
3944
- useCache: UseCacheType<C>;
3945
- invalidCache: InvalidCacheType<C>;
3946
- clone(options?: SqlCloneOptions): Promise<AugmentedSqlDataSource<T, C>>;
3947
- } & {
3948
- [key in keyof T]: T[key];
3949
- };
3950
- 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"> & {
3951
- [key in keyof T]: T[key];
3952
- };
3953
- /** Only accepts formats `string` e `string as string` */
3954
- type NoSpace<S extends string> = S extends `${infer _} ${infer _}` ? never : S;
3955
- type TableFormat<S extends string> = NoSpace<S> | (S extends `${infer L} as ${infer R}` ? `${NoSpace<L>} as ${NoSpace<R>}` : never);
3956
-
3957
- type AstParserType = {
3958
- sql: string;
3959
- bindings: any[];
4006
+ softDeleteValue?: string | boolean;
3960
4007
  };
3961
4008
 
3962
- declare class AstParser {
3963
- private readonly dbType;
3964
- private readonly model;
3965
- constructor(model: typeof Model, dbType: SqlDataSourceType);
3966
- parse(nodes: (QueryNode | null)[], startBindingIndex?: number, isNestedCondition?: boolean): AstParserType;
3967
- /**
3968
- * Map the database type to a common type if shares the same driver (e.g. mysql and mariadb)
3969
- */
3970
- private mapCommonDbType;
3971
- /**
3972
- * @description Generates MSSQL table hints from lock node
3973
- * MSSQL uses WITH (UPDLOCK), WITH (HOLDLOCK), etc. as table hints
3974
- * READPAST is the MSSQL equivalent of SKIP LOCKED
3975
- */
3976
- private getMssqlTableHints;
3977
- }
3978
-
3979
- declare class DeleteNode extends QueryNode {
3980
- fromNode: FromNode;
3981
- chainsWith: string;
3982
- canKeywordBeSeenMultipleTimes: boolean;
3983
- folder: string;
3984
- file: string;
3985
- constructor(fromNode: FromNode, isRawValue?: boolean);
3986
- }
3987
-
3988
- declare class InsertNode extends QueryNode {
3989
- fromNode: FromNode;
3990
- records: Record<string, any>[];
3991
- returning?: string[];
3992
- disableReturning: boolean;
3993
- chainsWith: string;
3994
- canKeywordBeSeenMultipleTimes: boolean;
3995
- folder: string;
3996
- file: string;
3997
- constructor(fromNode: FromNode, records?: Record<string, any>[], returning?: string[], disableReturning?: boolean, isRawValue?: boolean);
3998
- }
3999
-
4000
- declare class OnDuplicateNode extends QueryNode {
4001
- table: string;
4002
- conflictColumns: string[];
4003
- columnsToUpdate: string[];
4004
- returning?: string[];
4005
- mode: "update" | "ignore";
4006
- chainsWith: string;
4007
- canKeywordBeSeenMultipleTimes: boolean;
4008
- folder: string;
4009
- file: string;
4010
- constructor(table: string, conflictColumns: string[], columnsToUpdate: string[], mode?: "update" | "ignore", returning?: string[], isRawValue?: boolean);
4011
- }
4012
-
4013
- declare class TruncateNode extends QueryNode {
4014
- fromNode: FromNode | string;
4015
- chainsWith: string;
4016
- canKeywordBeSeenMultipleTimes: boolean;
4017
- folder: string;
4018
- file: string;
4019
- constructor(fromNode: FromNode | string, isRawValue?: boolean);
4020
- }
4021
-
4022
- declare class UpdateNode extends QueryNode {
4023
- fromNode: FromNode;
4024
- columns: string[];
4025
- values: (any | RawNode)[];
4026
- chainsWith: string;
4027
- canKeywordBeSeenMultipleTimes: boolean;
4028
- folder: string;
4029
- file: string;
4030
- constructor(fromNode: FromNode, columns?: string[], values?: (any | RawNode)[], isRawValue?: boolean);
4031
- }
4032
-
4033
4009
  declare class QueryBuilder<T extends Model = any> extends JsonQueryBuilder<T> {
4034
4010
  model: typeof Model;
4035
4011
  protected astParser: AstParser;
@@ -4294,6 +4270,7 @@ declare class QueryBuilder<T extends Model = any> extends JsonQueryBuilder<T> {
4294
4270
  * @description Insert multiple records into a table
4295
4271
  * @param returning - The columns to return from the query, only supported by postgres and cockroachdb - default is "*"
4296
4272
  * @returns raw driver response
4273
+ * @oracledb may do multiple inserts with auto-generated identity columns
4297
4274
  */
4298
4275
  insertMany(data: Record<string, any>[], returning?: string[]): Promise<T[]>;
4299
4276
  /**
@@ -4591,6 +4568,7 @@ declare abstract class Model extends Entity {
4591
4568
  * @mysql If no Primary Key is present in the model definition, the model will be returned
4592
4569
  * @sqlite If no Primary Key is present in the model definition, the model will be returned
4593
4570
  * @sqlite Returning Not supported and won't have effect
4571
+ * @oracledb may do multiple inserts with auto-generated identity columns
4594
4572
  */
4595
4573
  static insertMany<T extends Model>(this: new () => T | typeof Model, modelsData: Partial<ModelWithoutRelations<T>>[], options?: BaseModelMethodOptions & InsertOptions<T>): Promise<AnnotatedModel<T, {}>[]>;
4596
4574
  /**
@@ -5810,7 +5788,7 @@ declare abstract class Migration {
5810
5788
  /**
5811
5789
  * @description This method is called after the migration has been run
5812
5790
  */
5813
- afterMigration?(sqlDataSource: SqlDataSource | AugmentedSqlDataSource): Promise<void>;
5791
+ afterMigration?(sqlDataSource: SqlDataSource): Promise<void>;
5814
5792
  }
5815
5793
 
5816
5794
  /**
@@ -5863,7 +5841,7 @@ type WithPerformanceResult<R = any> = [string, R];
5863
5841
  */
5864
5842
  declare const withPerformance: <A extends any[], R>(fn: (...args: A) => Promise<R>, returnType?: "millis" | "seconds", fix?: number) => (...args: A) => Promise<WithPerformanceResult<R>>;
5865
5843
 
5866
- type HysteriaErrorCode = `UNSUPPORTED_ISOLATION_LEVEL_${string}` | "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}` | `KEY_${string}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG` | `CACHE_ADAPTER_NOT_CONFIGURED` | `SQLITE_NOT_SUPPORTED` | `COCKROACHDB_NOT_SUPPORTED` | `RELATION_NOT_FOUND` | `POSTGRES_TABLE_REQUIRED` | `MODEL_HAS_NO_PRIMARY_KEY_VALUE` | `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" | "LPUSH_FAILED" | "RPUSH_FAILED" | "LPOP_FAILED" | "RPOP_FAILED" | "LRANGE_FAILED" | "LLEN_FAILED" | "HSET_FAILED" | "HMSET_FAILED" | "HGET_FAILED" | "HGETALL_FAILED" | "HMGET_FAILED" | "HDEL_FAILED" | "HEXISTS_FAILED" | "HKEYS_FAILED" | "HLEN_FAILED" | "SADD_FAILED" | "SMEMBERS_FAILED" | "SREM_FAILED" | "SISMEMBER_FAILED" | "SCARD_FAILED" | "SINTER_FAILED" | "SUNION_FAILED" | "SDIFF_FAILED" | "ZADD_FAILED" | "ZRANGE_FAILED" | "ZREVRANGE_FAILED" | "ZREM_FAILED" | "ZSCORE_FAILED" | "ZCARD_FAILED" | "SUBSCRIBE_FAILED" | "UNSUBSCRIBE_FAILED" | "PUBLISH_FAILED" | "PSUBSCRIBE_FAILED" | "PUNSUBSCRIBE_FAILED" | "EXISTS_FAILED" | "EXPIRE_FAILED" | "EXPIREAT_FAILED" | "PEXPIRE_FAILED" | "TTL_FAILED" | "PTTL_FAILED" | "PERSIST_FAILED" | "KEYS_FAILED" | "RENAME_FAILED" | "TYPE_FAILED" | "SCAN_FAILED" | "ADMINJS_NOT_ENABLED" | "ADMINJS_INITIALIZATION_FAILED" | "ADMINJS_NO_MODELS_PROVIDED";
5844
+ type HysteriaErrorCode = "CONNECTION_ALREADY_ESTABLISHED" | `UNSUPPORTED_ISOLATION_LEVEL_${string}` | "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}` | `KEY_${string}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG` | `CACHE_ADAPTER_NOT_CONFIGURED` | `SQLITE_NOT_SUPPORTED` | `COCKROACHDB_NOT_SUPPORTED` | `RELATION_NOT_FOUND` | `POSTGRES_TABLE_REQUIRED` | `MODEL_HAS_NO_PRIMARY_KEY_VALUE` | `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" | "LPUSH_FAILED" | "RPUSH_FAILED" | "LPOP_FAILED" | "RPOP_FAILED" | "LRANGE_FAILED" | "LLEN_FAILED" | "HSET_FAILED" | "HMSET_FAILED" | "HGET_FAILED" | "HGETALL_FAILED" | "HMGET_FAILED" | "HDEL_FAILED" | "HEXISTS_FAILED" | "HKEYS_FAILED" | "HLEN_FAILED" | "SADD_FAILED" | "SMEMBERS_FAILED" | "SREM_FAILED" | "SISMEMBER_FAILED" | "SCARD_FAILED" | "SINTER_FAILED" | "SUNION_FAILED" | "SDIFF_FAILED" | "ZADD_FAILED" | "ZRANGE_FAILED" | "ZREVRANGE_FAILED" | "ZREM_FAILED" | "ZSCORE_FAILED" | "ZCARD_FAILED" | "SUBSCRIBE_FAILED" | "UNSUBSCRIBE_FAILED" | "PUBLISH_FAILED" | "PSUBSCRIBE_FAILED" | "PUNSUBSCRIBE_FAILED" | "EXISTS_FAILED" | "EXPIRE_FAILED" | "EXPIREAT_FAILED" | "PEXPIRE_FAILED" | "TTL_FAILED" | "PTTL_FAILED" | "PERSIST_FAILED" | "KEYS_FAILED" | "RENAME_FAILED" | "TYPE_FAILED" | "SCAN_FAILED" | "ADMINJS_NOT_ENABLED" | "ADMINJS_INITIALIZATION_FAILED" | "ADMINJS_NO_MODELS_PROVIDED";
5867
5845
 
5868
5846
  declare class HysteriaError extends Error {
5869
5847
  code: HysteriaErrorCode;
@@ -5888,4 +5866,4 @@ declare const generateOpenApiModelWithMetadata: <T extends new () => Model>(mode
5888
5866
  $id?: string;
5889
5867
  }>;
5890
5868
 
5891
- export { type AdminJsActionOptions, type AdminJsAssets, type AdminJsBranding, type AdminJsInstance, type AdminJsLocale, type AdminJsOptions, type AdminJsPage, type AdminJsPropertyOptions, type AdminJsResourceOptions, type AdminJsSettings, type AnnotatedModel, type AsymmetricEncryptionOptions, type AugmentedSqlDataSource, AutogeneratedModel, type BaseModelMethodOptions, type BaseModelRelationType, type CacheAdapter, type CacheKeys, 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, DryModelQueryBuilder, DryQueryBuilder, type FetchHooks, type GetConnectionReturnType, HysteriaError, InMemoryAdapter, type IndexType, type LazyRelationType, type ManyOptions, type ManyToManyOptions, type ManyToManyStringOptions, Migration, Model, type ModelInstanceType, ModelQueryBuilder, type ModelWithoutRelations, MongoDataSource, type MongoDataSourceInput, type MssqlConnectionInstance, type MssqlDataSourceInput, type MssqlPoolInstance, type MysqlConnectionInstance, type MysqlSqlDataSourceInput, type NotNullableMysqlSqlDataSourceInput, type NotNullablePostgresSqlDataSourceInput, type NotNullableSqliteDataSourceInput, type NumberModelKey, type OneOptions, type PgPoolClientInstance, type PostgresSqlDataSourceInput, QueryBuilder, type RawModelOptions, RawNode, RedisCacheAdapter, type RedisFetchable, type RedisStorable, type RelatedInstance, type RelationQueryBuilderType, type SqlCloneOptions, type SqlDataSourceInput, type SqlDataSourceModel, type SqlDataSourceType, type SqlDataSourceWithoutTransaction, type SqlDriverSpecificOptions, type SqlPoolType, type Sqlite3ConnectionOptions, type SqliteConnectionInstance, type SqliteDataSourceInput, type StartTransactionOptions, type SymmetricEncryptionOptions, type TableFormat, type ThroughModel, TimestampedModel, Transaction, type TransactionExecutionOptions, type UniqueType, type UseCacheReturnType, type UseConnectionInput, UserMixin, 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 };
5869
+ export { type AdminJsActionOptions, type AdminJsAssets, type AdminJsBranding, type AdminJsInstance, type AdminJsLocale, type AdminJsOptions, type AdminJsPage, type AdminJsPropertyOptions, type AdminJsResourceOptions, type AdminJsSettings, type AnnotatedModel, type AsymmetricEncryptionOptions, AutogeneratedModel, type BaseModelMethodOptions, type BaseModelRelationType, type CacheAdapter, type CacheKeys, 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, DryModelQueryBuilder, DryQueryBuilder, type FetchHooks, type GetConnectionReturnType, HysteriaError, InMemoryAdapter, type IndexType, type LazyRelationType, type ManyOptions, type ManyToManyOptions, type ManyToManyStringOptions, Migration, Model, type ModelInstanceType, ModelQueryBuilder, type ModelWithoutRelations, MongoDataSource, type MongoDataSourceInput$1 as MongoDataSourceInput, type MssqlConnectionInstance, type MssqlDataSourceInput, type MssqlPoolInstance, type MysqlConnectionInstance, type MysqlSqlDataSourceInput, type NotNullableMysqlSqlDataSourceInput, type NotNullableOracleDBDataSourceInput, type NotNullableOracleMssqlDataSourceInput, type NotNullablePostgresSqlDataSourceInput, type NotNullableSqliteDataSourceInput, type NumberModelKey, type OneOptions, type OracleDBDataSourceInput, type OracleDBPoolInstance, type PgPoolClientInstance, type PostgresSqlDataSourceInput, QueryBuilder, type RawModelOptions, RawNode, RedisCacheAdapter, type RedisFetchable, type RedisStorable, type RelatedInstance, type RelationQueryBuilderType, type SqlCloneOptions, SqlDataSource, type SqlDataSourceInput, type SqlDataSourceModel, type SqlDataSourceType, type SqlDriverSpecificOptions, type SqlPoolType, type Sqlite3ConnectionOptions, type SqliteConnectionInstance, type SqliteDataSourceInput, type StartTransactionOptions, type SymmetricEncryptionOptions, type TableFormat, type ThroughModel, TimestampedModel, Transaction, type TransactionExecutionOptions, type UniqueType, type UseCacheReturnType, type UseConnectionInput, UserMixin, UuidModel, belongsTo, column, createModelFactory, defineMigrator, generateOpenApiModel, generateOpenApiModelSchema, generateOpenApiModelWithMetadata, getCollectionProperties, getIndexes, getModelColumns, type getPoolReturnType, getPrimaryKey, getRelations, getRelationsMetadata, getUniques, hasMany, hasOne, index, HysteriaLogger as logger, manyToMany, property, RedisDataSource as redis, unique, view, withPerformance };