hysteria-orm 10.7.4 → 10.7.6

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
@@ -10,8 +10,8 @@ import { PoolConfig, PoolClient, QueryResult as QueryResult$1 } from 'pg';
10
10
  import * as mysql2_promise from 'mysql2/promise';
11
11
  import { PoolOptions, PoolConnection, QueryResult } from 'mysql2/promise';
12
12
  import { RedisOptions, Redis } from 'ioredis';
13
- import express from 'express';
14
13
  import { FormatOptionsWithLanguage } from 'sql-formatter';
14
+ import express from 'express';
15
15
  import { PassThrough } from 'node:stream';
16
16
 
17
17
  type CaseConvention = "camel" | "snake" | "preserve" | RegExp | ((column: string) => string);
@@ -949,6 +949,262 @@ type OpenApiModelPropertyType = {
949
949
  nullable?: boolean;
950
950
  };
951
951
 
952
+ interface CacheAdapter {
953
+ /**
954
+ * @description Gets a value from the cache
955
+ * @param key The key to get the value from
956
+ * @returns The value from the cache
957
+ */
958
+ get<T = void>(key: string): Promise<T>;
959
+ /**
960
+ * @description Sets a value in the cache
961
+ * @param key The key to set the value to
962
+ * @param data The value to set in the cache
963
+ * @param ttl The time to live for the value in milliseconds
964
+ */
965
+ set<T = any>(key: string, data: T, ttl?: number): Promise<void>;
966
+ /**
967
+ * @description Invalidates a value from the cache
968
+ * @param key The key to invalidate the value from
969
+ */
970
+ invalidate(key: string): Promise<void>;
971
+ /**
972
+ * @description Invalidates all values from the cache starting with the given key
973
+ * @param key The key to invalidate the values from
974
+ */
975
+ invalidateAll(key: string): Promise<void>;
976
+ /**
977
+ * @description Disconnects from the cache adapter if needed when the data source disconnects
978
+ */
979
+ disconnect?(): Promise<void>;
980
+ }
981
+
982
+ type CacheKeys = Record<string, (...args: any[]) => Promise<any> | any>;
983
+ type UseCacheReturnType<C extends CacheKeys, K extends keyof C> = K extends never ? never : Awaited<ReturnType<C[K]>>;
984
+
985
+ type Sqlite3ConnectionOptions = {
986
+ mode: number;
987
+ };
988
+ type SqlDriverSpecificOptions<T extends DataSourceType> = Omit<DriverSpecificOptions<T>, "mongoOptions" | "redisOptions">;
989
+ type MysqlConnectionInstance = Awaited<ReturnType<Mysql2Import["createPool"]>>;
990
+ type PgPoolClientInstance = InstanceType<PgImport["Pool"]>;
991
+ type SqliteConnectionInstance = InstanceType<Sqlite3Import["Database"]>;
992
+ type OracleDBPoolInstance = Pool;
993
+ type MssqlPoolInstance = InstanceType<MssqlImport["ConnectionPool"]>;
994
+ type MssqlConnectionInstance = Awaited<ReturnType<MssqlPoolInstance["connect"]>>;
995
+ type SqlPoolType = OracleDBPoolInstance | MysqlConnectionInstance | PgPoolClientInstance | SqliteConnectionInstance | MssqlPoolInstance;
996
+ /**
997
+ * @description The connection policies for the sql data source
998
+ * @default the connection policies are not set, so no query will be retried
999
+ */
1000
+ type ConnectionPolicies = {
1001
+ /**
1002
+ * @description The retry policy for the sql data source, it allows to retry a query if it fails
1003
+ */
1004
+ retry?: {
1005
+ maxRetries?: number;
1006
+ delay?: number;
1007
+ };
1008
+ };
1009
+ /**
1010
+ * Accepts both decorator-based model classes (`typeof Model` subclasses)
1011
+ * and programmatic models created via `defineModel`.
1012
+ */
1013
+ type SqlDataSourceModel = AnyModelConstructor;
1014
+ /**
1015
+ * @description Base migration configuration options available for all databases
1016
+ */
1017
+ type MigrationConfigBase = {
1018
+ /**
1019
+ * @description The path to the migrations folder, can be overridden in the cli command
1020
+ * @default "database/migrations"
1021
+ */
1022
+ path?: string;
1023
+ /**
1024
+ * @description Path to the tsconfig.json file for TypeScript migration files, can be overridden in the cli command
1025
+ * @default "./tsconfig.json"
1026
+ */
1027
+ tsconfig?: string;
1028
+ /**
1029
+ * @description Acquire advisory lock before running migrations to prevent concurrent execution, can be overridden in the cli command
1030
+ * @default true
1031
+ */
1032
+ lock?: boolean;
1033
+ /**
1034
+ * @description Lock timeout in milliseconds for migration advisory lock acquisition, can be overridden in the cli command
1035
+ * @default 30000
1036
+ */
1037
+ lockTimeout?: number;
1038
+ };
1039
+ /**
1040
+ * @description Migration configuration with transactional support for PostgreSQL and CockroachDB
1041
+ */
1042
+ type MigrationConfigWithTransactional = MigrationConfigBase & {
1043
+ /**
1044
+ * @description Runs all pending migrations in a single transaction, can be overridden in the cli command
1045
+ * @default true
1046
+ * @note Only available for PostgreSQL and CockroachDB
1047
+ */
1048
+ transactional?: boolean;
1049
+ };
1050
+ /**
1051
+ * @description Migration configuration type based on database type
1052
+ * @description Adds transactional option only for PostgreSQL and CockroachDB
1053
+ */
1054
+ type MigrationConfig<D extends SqlDataSourceType = SqlDataSourceType> = D extends "postgres" | "cockroachdb" ? MigrationConfigWithTransactional : MigrationConfigBase;
1055
+ /**
1056
+ * @description Seeder configuration options
1057
+ */
1058
+ type SeederConfig = {
1059
+ /**
1060
+ * @description The path to the seeders folder
1061
+ * @default "database/seeders"
1062
+ */
1063
+ path?: string;
1064
+ /**
1065
+ * @description Path to the tsconfig.json file for TypeScript seeder files
1066
+ * @default "./tsconfig.json"
1067
+ */
1068
+ tsconfig?: string;
1069
+ };
1070
+ /**
1071
+ * @description Common input properties shared across all SqlDataSource types
1072
+ */
1073
+ type SqlDataSourceInputBase<T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}, D extends SqlDataSourceType = SqlDataSourceType> = {
1074
+ /**
1075
+ * @description Whether to log the sql queries and other debug information. Can be a boolean or a LoggerConfig object for granular control.
1076
+ * @warning Logs are synchronous by default and add overhead — do not use in production unless you override with an async custom logger.
1077
+ * @default false
1078
+ */
1079
+ readonly logs?: boolean | LoggerConfig;
1080
+ /**
1081
+ * @description The connection policies to use for the sql data source that are not configured in the driverOptions
1082
+ */
1083
+ connectionPolicies?: ConnectionPolicies;
1084
+ /**
1085
+ * @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
1086
+ */
1087
+ queryFormatOptions?: FormatOptionsWithLanguage;
1088
+ /**
1089
+ * @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
1090
+ * @description Models can still be used as standalone entities, but they won't be available for the sql data source instance
1091
+ */
1092
+ models?: T;
1093
+ /**
1094
+ * @description Migration configuration for the sql data source
1095
+ */
1096
+ migrations?: MigrationConfig<D>;
1097
+ /**
1098
+ * @description Seeder configuration for the sql data source
1099
+ */
1100
+ seeders?: SeederConfig;
1101
+ /**
1102
+ * @description The cache strategy to use for the sql data source, it's used to configure the cache strategy for the sql data source
1103
+ */
1104
+ cacheStrategy?: {
1105
+ cacheAdapter?: CacheAdapter;
1106
+ keys: C;
1107
+ };
1108
+ /**
1109
+ * @description AdminJS configuration for the admin panel
1110
+ * @description To use AdminJS, install: `npm install adminjs`
1111
+ */
1112
+ adminJs?: AdminJsOptions;
1113
+ };
1114
+ /**
1115
+ * @description Maps a SqlDataSourceType to its corresponding input interface
1116
+ */
1117
+ 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;
1118
+ type SlaveContext = {
1119
+ type: SqlDataSourceType;
1120
+ host: string;
1121
+ port: number;
1122
+ username: string;
1123
+ password: string;
1124
+ database: string;
1125
+ };
1126
+ /**
1127
+ * @description The input type for the SqlDataSource constructor
1128
+ * @description The connectionPolicies object is used to configure the connection policies for the sql data source
1129
+ */
1130
+ type SqlDataSourceInput<D extends SqlDataSourceType = SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = SqlDataSourceInputBase<T, C, D> & {
1131
+ /**
1132
+ * @description The type of the database to connect to
1133
+ */
1134
+ readonly type: D;
1135
+ /**
1136
+ * @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
1137
+ * @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`
1138
+ */
1139
+ driverOptions?: SqlDriverSpecificOptions<D>;
1140
+ /**
1141
+ * @description The replication configuration for the sql data source, it's used to configure the replication for the sql data source
1142
+ */
1143
+ replication?: {
1144
+ /**
1145
+ * @description The function to call when a slave server fails, if not provided an error will be thrown
1146
+ */
1147
+ onSlaveServerFailure?: (error: Error, context: SlaveContext) => void | Promise<void>;
1148
+ /**
1149
+ * @description The slaves data sources to use for the sql data source, slaves are automatically used for read operations unless specified otherwise
1150
+ */
1151
+ slaves?: Omit<UseConnectionInput<D, T, C>, "slaves" | "models" | "cacheStrategy" | "adminJs" | "logs" | "queryFormatOptions" | "migrations">[];
1152
+ /**
1153
+ * @description The algorithm to use for selecting the slave for read operations
1154
+ * @default "roundRobin" - Distributes requests evenly across all slaves in sequence
1155
+ * @option "random" - Randomly selects a slave for each request
1156
+ */
1157
+ slaveAlgorithm?: SlaveAlgorithm;
1158
+ };
1159
+ } & Omit<MapSqlDataSourceTypeToInput<D>, "type">;
1160
+ /**
1161
+ * @description Maps a SqlDataSourceType to its corresponding non-nullable input interface
1162
+ */
1163
+ 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;
1164
+ type UseConnectionInput<D extends SqlDataSourceType = SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = {
1165
+ /**
1166
+ * @description The type of the database to connect to
1167
+ */
1168
+ readonly type: D;
1169
+ readonly logs?: boolean | LoggerConfig;
1170
+ readonly models?: T;
1171
+ readonly driverOptions?: SqlDriverSpecificOptions<D>;
1172
+ connectionPolicies?: ConnectionPolicies;
1173
+ queryFormatOptions?: FormatOptionsWithLanguage;
1174
+ cacheStrategy?: {
1175
+ cacheAdapter: CacheAdapter;
1176
+ keys: C;
1177
+ };
1178
+ /**
1179
+ * @description AdminJS configuration for the admin panel
1180
+ * @description AdminJS is completely optional - dependencies are loaded at runtime via dynamic import()
1181
+ */
1182
+ adminJs?: AdminJsOptions;
1183
+ } & Omit<MapSqlDataSourceTypeToNotNullableInput<D>, "type">;
1184
+ type SqlDataSourceType = Exclude<DataSourceType, "mongo">;
1185
+ type SqlCloneOptions = {
1186
+ /**
1187
+ * @description Whether to recreate the pool of connections for the given driver, by default it's false
1188
+ * @warning If false, the pool of connections will be reused from the caller instance
1189
+ */
1190
+ shouldRecreatePool?: boolean;
1191
+ };
1192
+ 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;
1193
+ 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;
1194
+ /** Only accepts formats `string` e `string as string` */
1195
+ type NoSpace<S extends string> = S extends `${infer _} ${infer _}` ? never : S;
1196
+ type TableFormat<S extends string> = NoSpace<S> | (S extends `${infer L} as ${infer R}` ? `${NoSpace<L>} as ${NoSpace<R>}` : never);
1197
+ type ReplicationType = "master" | "slave";
1198
+ /**
1199
+ * @description Algorithm for selecting a slave database for read operations
1200
+ * @option "roundRobin" - Distributes requests evenly across all slaves in sequence
1201
+ * @option "random" - Randomly selects a slave for each request
1202
+ */
1203
+ type SlaveAlgorithm = "roundRobin" | "random";
1204
+ type RawQueryOptions = {
1205
+ replicationMode?: ReplicationType;
1206
+ };
1207
+
952
1208
  /**
953
1209
  * @description AdminJS plugin types - All AdminJS imports are done at runtime via dynamic import()
954
1210
  * @description This ensures the plugin is completely optional
@@ -976,7 +1232,7 @@ type AdminJsOptions = {
976
1232
  * @description Models to expose in the AdminJS panel
977
1233
  * @description If not provided, all models registered in the SqlDataSource will be used
978
1234
  */
979
- resources?: (typeof Model)[];
1235
+ resources?: SqlDataSourceModel[];
980
1236
  /**
981
1237
  * @description Custom resource options for specific models
982
1238
  */
@@ -1261,300 +1517,48 @@ type AdminJsInstance = {
1261
1517
  router?: ReturnType<typeof express.Router>;
1262
1518
  };
1263
1519
 
1264
- interface CacheAdapter {
1265
- /**
1266
- * @description Gets a value from the cache
1267
- * @param key The key to get the value from
1268
- * @returns The value from the cache
1269
- */
1270
- get<T = void>(key: string): Promise<T>;
1271
- /**
1272
- * @description Sets a value in the cache
1273
- * @param key The key to set the value to
1274
- * @param data The value to set in the cache
1275
- * @param ttl The time to live for the value in milliseconds
1276
- */
1277
- set<T = any>(key: string, data: T, ttl?: number): Promise<void>;
1278
- /**
1279
- * @description Invalidates a value from the cache
1280
- * @param key The key to invalidate the value from
1281
- */
1282
- invalidate(key: string): Promise<void>;
1283
- /**
1284
- * @description Invalidates all values from the cache starting with the given key
1285
- * @param key The key to invalidate the values from
1286
- */
1287
- invalidateAll(key: string): Promise<void>;
1288
- /**
1289
- * @description Disconnects from the cache adapter if needed when the data source disconnects
1290
- */
1291
- disconnect?(): Promise<void>;
1292
- }
1293
-
1294
- type CacheKeys = Record<string, (...args: any[]) => Promise<any> | any>;
1295
- type UseCacheReturnType<C extends CacheKeys, K extends keyof C> = K extends never ? never : Awaited<ReturnType<C[K]>>;
1296
-
1297
1520
  declare abstract class QueryNode {
1298
1521
  /**
1299
- * Sql keyword to use for the query e.g. "select"
1300
- */
1301
- keyword: string;
1302
- /**
1303
- * The current parameter index to use for the query
1304
- */
1305
- currParamIndex: number;
1306
- /**
1307
- * Whether the query node is a raw value and should not be parsed by the interpreter
1308
- */
1309
- isRawValue: boolean;
1310
- /**
1311
- * Whether the keyword can be seen multiple times in the query, e.g. "join" can be seen multiple times in a query
1312
- */
1313
- abstract canKeywordBeSeenMultipleTimes: boolean;
1314
- /**
1315
- * The string to use to chain the keyword with the next keyword
1316
- */
1317
- abstract chainsWith: string;
1318
- /**
1319
- * The folder to use for the query node, e.g. "select" is in the "select" folder inside the interpreter map
1320
- */
1321
- abstract folder: string;
1322
- /**
1323
- * The file to use for the query node, e.g. "select" is in the "select" file inside the interpreter map
1324
- */
1325
- abstract file: string;
1326
- constructor(keyword: string, isRawValue?: boolean);
1327
- }
1328
-
1329
- declare class RawNode extends QueryNode {
1330
- rawValue: string;
1331
- canKeywordBeSeenMultipleTimes: boolean;
1332
- chainsWith: string;
1333
- currParamIndex: number;
1334
- isRawValue: boolean;
1335
- folder: string;
1336
- file: string;
1337
- constructor(value: string);
1338
- }
1339
-
1340
- type Sqlite3ConnectionOptions = {
1341
- mode: number;
1342
- };
1343
- type SqlDriverSpecificOptions<T extends DataSourceType> = Omit<DriverSpecificOptions<T>, "mongoOptions" | "redisOptions">;
1344
- type MysqlConnectionInstance = Awaited<ReturnType<Mysql2Import["createPool"]>>;
1345
- type PgPoolClientInstance = InstanceType<PgImport["Pool"]>;
1346
- type SqliteConnectionInstance = InstanceType<Sqlite3Import["Database"]>;
1347
- type OracleDBPoolInstance = Pool;
1348
- type MssqlPoolInstance = InstanceType<MssqlImport["ConnectionPool"]>;
1349
- type MssqlConnectionInstance = Awaited<ReturnType<MssqlPoolInstance["connect"]>>;
1350
- type SqlPoolType = OracleDBPoolInstance | MysqlConnectionInstance | PgPoolClientInstance | SqliteConnectionInstance | MssqlPoolInstance;
1351
- /**
1352
- * @description The connection policies for the sql data source
1353
- * @default the connection policies are not set, so no query will be retried
1354
- */
1355
- type ConnectionPolicies = {
1356
- /**
1357
- * @description The retry policy for the sql data source, it allows to retry a query if it fails
1358
- */
1359
- retry?: {
1360
- maxRetries?: number;
1361
- delay?: number;
1362
- };
1363
- };
1364
- type SqlDataSourceModel = typeof Model;
1365
- /**
1366
- * @description Base migration configuration options available for all databases
1367
- */
1368
- type MigrationConfigBase = {
1369
- /**
1370
- * @description The path to the migrations folder, can be overridden in the cli command
1371
- * @default "database/migrations"
1372
- */
1373
- path?: string;
1374
- /**
1375
- * @description Path to the tsconfig.json file for TypeScript migration files, can be overridden in the cli command
1376
- * @default "./tsconfig.json"
1377
- */
1378
- tsconfig?: string;
1379
- /**
1380
- * @description Acquire advisory lock before running migrations to prevent concurrent execution, can be overridden in the cli command
1381
- * @default true
1382
- */
1383
- lock?: boolean;
1384
- /**
1385
- * @description Lock timeout in milliseconds for migration advisory lock acquisition, can be overridden in the cli command
1386
- * @default 30000
1387
- */
1388
- lockTimeout?: number;
1389
- };
1390
- /**
1391
- * @description Migration configuration with transactional support for PostgreSQL and CockroachDB
1392
- */
1393
- type MigrationConfigWithTransactional = MigrationConfigBase & {
1394
- /**
1395
- * @description Runs all pending migrations in a single transaction, can be overridden in the cli command
1396
- * @default true
1397
- * @note Only available for PostgreSQL and CockroachDB
1398
- */
1399
- transactional?: boolean;
1400
- };
1401
- /**
1402
- * @description Migration configuration type based on database type
1403
- * @description Adds transactional option only for PostgreSQL and CockroachDB
1404
- */
1405
- type MigrationConfig<D extends SqlDataSourceType = SqlDataSourceType> = D extends "postgres" | "cockroachdb" ? MigrationConfigWithTransactional : MigrationConfigBase;
1406
- /**
1407
- * @description Seeder configuration options
1408
- */
1409
- type SeederConfig = {
1410
- /**
1411
- * @description The path to the seeders folder
1412
- * @default "database/seeders"
1413
- */
1414
- path?: string;
1415
- /**
1416
- * @description Path to the tsconfig.json file for TypeScript seeder files
1417
- * @default "./tsconfig.json"
1418
- */
1419
- tsconfig?: string;
1420
- };
1421
- /**
1422
- * @description Common input properties shared across all SqlDataSource types
1423
- */
1424
- type SqlDataSourceInputBase<T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}, D extends SqlDataSourceType = SqlDataSourceType> = {
1425
- /**
1426
- * @description Whether to log the sql queries and other debug information. Can be a boolean or a LoggerConfig object for granular control.
1427
- * @warning Logs are synchronous by default and add overhead — do not use in production unless you override with an async custom logger.
1428
- * @default false
1429
- */
1430
- readonly logs?: boolean | LoggerConfig;
1431
- /**
1432
- * @description The connection policies to use for the sql data source that are not configured in the driverOptions
1433
- */
1434
- connectionPolicies?: ConnectionPolicies;
1435
- /**
1436
- * @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
1437
- */
1438
- queryFormatOptions?: FormatOptionsWithLanguage;
1439
- /**
1440
- * @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
1441
- * @description Models can still be used as standalone entities, but they won't be available for the sql data source instance
1442
- */
1443
- models?: T;
1444
- /**
1445
- * @description Migration configuration for the sql data source
1446
- */
1447
- migrations?: MigrationConfig<D>;
1448
- /**
1449
- * @description Seeder configuration for the sql data source
1450
- */
1451
- seeders?: SeederConfig;
1452
- /**
1453
- * @description The cache strategy to use for the sql data source, it's used to configure the cache strategy for the sql data source
1454
- */
1455
- cacheStrategy?: {
1456
- cacheAdapter?: CacheAdapter;
1457
- keys: C;
1458
- };
1459
- /**
1460
- * @description AdminJS configuration for the admin panel
1461
- * @description To use AdminJS, install: `npm install adminjs`
1462
- */
1463
- adminJs?: AdminJsOptions;
1464
- };
1465
- /**
1466
- * @description Maps a SqlDataSourceType to its corresponding input interface
1467
- */
1468
- 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;
1469
- type SlaveContext = {
1470
- type: SqlDataSourceType;
1471
- host: string;
1472
- port: number;
1473
- username: string;
1474
- password: string;
1475
- database: string;
1476
- };
1477
- /**
1478
- * @description The input type for the SqlDataSource constructor
1479
- * @description The connectionPolicies object is used to configure the connection policies for the sql data source
1480
- */
1481
- type SqlDataSourceInput<D extends SqlDataSourceType = SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = SqlDataSourceInputBase<T, C, D> & {
1482
- /**
1483
- * @description The type of the database to connect to
1484
- */
1485
- readonly type: D;
1486
- /**
1487
- * @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
1488
- * @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`
1489
- */
1490
- driverOptions?: SqlDriverSpecificOptions<D>;
1491
- /**
1492
- * @description The replication configuration for the sql data source, it's used to configure the replication for the sql data source
1493
- */
1494
- replication?: {
1495
- /**
1496
- * @description The function to call when a slave server fails, if not provided an error will be thrown
1497
- */
1498
- onSlaveServerFailure?: (error: Error, context: SlaveContext) => void | Promise<void>;
1499
- /**
1500
- * @description The slaves data sources to use for the sql data source, slaves are automatically used for read operations unless specified otherwise
1501
- */
1502
- slaves?: Omit<UseConnectionInput<D, T, C>, "slaves" | "models" | "cacheStrategy" | "adminJs" | "logs" | "queryFormatOptions" | "migrations">[];
1503
- /**
1504
- * @description The algorithm to use for selecting the slave for read operations
1505
- * @default "roundRobin" - Distributes requests evenly across all slaves in sequence
1506
- * @option "random" - Randomly selects a slave for each request
1507
- */
1508
- slaveAlgorithm?: SlaveAlgorithm;
1509
- };
1510
- } & Omit<MapSqlDataSourceTypeToInput<D>, "type">;
1511
- /**
1512
- * @description Maps a SqlDataSourceType to its corresponding non-nullable input interface
1513
- */
1514
- 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;
1515
- type UseConnectionInput<D extends SqlDataSourceType = SqlDataSourceType, T extends Record<string, SqlDataSourceModel> = {}, C extends CacheKeys = {}> = {
1522
+ * Sql keyword to use for the query e.g. "select"
1523
+ */
1524
+ keyword: string;
1516
1525
  /**
1517
- * @description The type of the database to connect to
1526
+ * The current parameter index to use for the query
1518
1527
  */
1519
- readonly type: D;
1520
- readonly logs?: boolean | LoggerConfig;
1521
- readonly models?: T;
1522
- readonly driverOptions?: SqlDriverSpecificOptions<D>;
1523
- connectionPolicies?: ConnectionPolicies;
1524
- queryFormatOptions?: FormatOptionsWithLanguage;
1525
- cacheStrategy?: {
1526
- cacheAdapter: CacheAdapter;
1527
- keys: C;
1528
- };
1528
+ currParamIndex: number;
1529
1529
  /**
1530
- * @description AdminJS configuration for the admin panel
1531
- * @description AdminJS is completely optional - dependencies are loaded at runtime via dynamic import()
1530
+ * Whether the query node is a raw value and should not be parsed by the interpreter
1532
1531
  */
1533
- adminJs?: AdminJsOptions;
1534
- } & Omit<MapSqlDataSourceTypeToNotNullableInput<D>, "type">;
1535
- type SqlDataSourceType = Exclude<DataSourceType, "mongo">;
1536
- type SqlCloneOptions = {
1532
+ isRawValue: boolean;
1537
1533
  /**
1538
- * @description Whether to recreate the pool of connections for the given driver, by default it's false
1539
- * @warning If false, the pool of connections will be reused from the caller instance
1534
+ * Whether the keyword can be seen multiple times in the query, e.g. "join" can be seen multiple times in a query
1540
1535
  */
1541
- shouldRecreatePool?: boolean;
1542
- };
1543
- 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;
1544
- 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;
1545
- /** Only accepts formats `string` e `string as string` */
1546
- type NoSpace<S extends string> = S extends `${infer _} ${infer _}` ? never : S;
1547
- type TableFormat<S extends string> = NoSpace<S> | (S extends `${infer L} as ${infer R}` ? `${NoSpace<L>} as ${NoSpace<R>}` : never);
1548
- type ReplicationType = "master" | "slave";
1549
- /**
1550
- * @description Algorithm for selecting a slave database for read operations
1551
- * @option "roundRobin" - Distributes requests evenly across all slaves in sequence
1552
- * @option "random" - Randomly selects a slave for each request
1553
- */
1554
- type SlaveAlgorithm = "roundRobin" | "random";
1555
- type RawQueryOptions = {
1556
- replicationMode?: ReplicationType;
1557
- };
1536
+ abstract canKeywordBeSeenMultipleTimes: boolean;
1537
+ /**
1538
+ * The string to use to chain the keyword with the next keyword
1539
+ */
1540
+ abstract chainsWith: string;
1541
+ /**
1542
+ * The folder to use for the query node, e.g. "select" is in the "select" folder inside the interpreter map
1543
+ */
1544
+ abstract folder: string;
1545
+ /**
1546
+ * The file to use for the query node, e.g. "select" is in the "select" file inside the interpreter map
1547
+ */
1548
+ abstract file: string;
1549
+ constructor(keyword: string, isRawValue?: boolean);
1550
+ }
1551
+
1552
+ declare class RawNode extends QueryNode {
1553
+ rawValue: string;
1554
+ canKeywordBeSeenMultipleTimes: boolean;
1555
+ chainsWith: string;
1556
+ currParamIndex: number;
1557
+ isRawValue: boolean;
1558
+ folder: string;
1559
+ file: string;
1560
+ constructor(value: string);
1561
+ }
1558
1562
 
1559
1563
  declare abstract class BaseBuilder {
1560
1564
  protected nodes: QueryNode[];
@@ -3163,7 +3167,7 @@ type ColumnDataTypeOption = ColumnDataTypeOptionWithLength | ColumnDataTypeOptio
3163
3167
  type LazyRelationType = {
3164
3168
  type?: RelationEnum;
3165
3169
  columnName: string;
3166
- model: () => typeof Model;
3170
+ model: () => AnyModelConstructor;
3167
3171
  foreignKey: string | (() => string);
3168
3172
  constraintName: string | (() => string);
3169
3173
  onDelete?: OnUpdateOrDelete;
@@ -3192,11 +3196,13 @@ type DateColumnOptions = {
3192
3196
  timezone?: Timezone;
3193
3197
  /**
3194
3198
  * @description Whether to automatically update the timestamp on record updates, uses timezone and format from the dateColumn options
3199
+ * @warning This is a code wise implementation it does not generate a trigger in the database, works with bulk updates too
3195
3200
  * @default false
3196
3201
  */
3197
3202
  autoUpdate?: boolean;
3198
3203
  /**
3199
3204
  * @description Whether to automatically set the timestamp on record creation, uses timezone and format from the dateColumn options
3205
+ * @warning This is a code wise implementation it does not generate a trigger in the database, works with bulk creations too
3200
3206
  * @default false
3201
3207
  */
3202
3208
  autoCreate?: boolean;
@@ -3309,11 +3315,11 @@ type ColumnType = {
3309
3315
  default?: string | number | null | boolean;
3310
3316
  };
3311
3317
  };
3312
- type ThroughModelCallback<T extends typeof Model> = () => T;
3318
+ type ThroughModelCallback<T extends AnyModelConstructor> = () => T;
3313
3319
  type ThroughModelString = string;
3314
- type ThroughModel<T extends typeof Model> = ThroughModelCallback<T> | ThroughModelString;
3320
+ type ThroughModel<T extends AnyModelConstructor> = ThroughModelCallback<T> | ThroughModelString;
3315
3321
  type ExtractModelFromTM<TM extends ThroughModel<any>> = TM extends ThroughModelCallback<infer T> ? T : never;
3316
- type ManyToManyOptions<T extends typeof Model, TM extends ThroughModel<T>> = {
3322
+ type ManyToManyOptions<T extends AnyModelConstructor, TM extends ThroughModel<T>> = {
3317
3323
  /**
3318
3324
  * @description The foreign key of current model on the Pivot table
3319
3325
  * @example If the current model is User and the through model is UserAddress, the leftForeignKey will be "userId"
@@ -3659,12 +3665,12 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
3659
3665
  */
3660
3666
  innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType): this;
3661
3667
  innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType): this;
3662
- innerJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType): this;
3663
- innerJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType): this;
3668
+ innerJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType): this;
3669
+ innerJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType): this;
3664
3670
  innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3665
3671
  innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, callback: JoinOnCallback): this;
3666
- innerJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3667
- innerJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, callback: JoinOnCallback): this;
3672
+ innerJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3673
+ innerJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, callback: JoinOnCallback): this;
3668
3674
  /**
3669
3675
  * @description Join a table with the current model
3670
3676
  * @param relationTable - The table to join
@@ -3674,12 +3680,12 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
3674
3680
  */
3675
3681
  join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType): this;
3676
3682
  join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType): this;
3677
- join<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType): this;
3678
- join<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType): this;
3683
+ join<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType): this;
3684
+ join<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType): this;
3679
3685
  join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3680
3686
  join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, callback: JoinOnCallback): this;
3681
- join<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3682
- join<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, callback: JoinOnCallback): this;
3687
+ join<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3688
+ join<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, callback: JoinOnCallback): this;
3683
3689
  /**
3684
3690
  * @description Join a table with the current model
3685
3691
  * @param relationTable - The table to join
@@ -3689,12 +3695,12 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
3689
3695
  */
3690
3696
  leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType): this;
3691
3697
  leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType): this;
3692
- leftJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType): this;
3693
- leftJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType): this;
3698
+ leftJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator?: BinaryOperatorType): this;
3699
+ leftJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn?: ModelKey<T>, operator?: BinaryOperatorType): this;
3694
3700
  leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3695
3701
  leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, callback: JoinOnCallback): this;
3696
- leftJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3697
- leftJoin<R extends typeof Model>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, callback: JoinOnCallback): this;
3702
+ leftJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3703
+ leftJoin<R extends AnyModelConstructor>(relationModel: R, referencingColumn: ModelKey<InstanceType<R>>, primaryColumn: ModelKey<T>, callback: JoinOnCallback): this;
3698
3704
  /**
3699
3705
  * @description Join a table with the current model
3700
3706
  * @param relationTable - The table to join
@@ -3704,7 +3710,7 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
3704
3710
  */
3705
3711
  rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType): this;
3706
3712
  rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType): this;
3707
- rightJoin<R extends typeof Model>(relationTable: string | R, referencingColumnOrPrimaryColumn: ModelKey<InstanceType<R>> | JoinableColumn | ModelKey<T>, primaryColumn?: JoinableColumn | ModelKey<T>, operator?: BinaryOperatorType): this;
3713
+ rightJoin<R extends AnyModelConstructor>(relationTable: string | R, referencingColumnOrPrimaryColumn: ModelKey<InstanceType<R>> | JoinableColumn | ModelKey<T>, primaryColumn?: JoinableColumn | ModelKey<T>, operator?: BinaryOperatorType): this;
3708
3714
  rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3709
3715
  rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, callback: JoinOnCallback): this;
3710
3716
  /**
@@ -3716,7 +3722,7 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
3716
3722
  */
3717
3723
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType): this;
3718
3724
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType): this;
3719
- fullJoin<R extends typeof Model>(relationTable: string | R, referencingColumnOrPrimaryColumn: ModelKey<InstanceType<R>> | JoinableColumn | ModelKey<T>, primaryColumn?: JoinableColumn | ModelKey<T>, operator?: BinaryOperatorType): this;
3725
+ fullJoin<R extends AnyModelConstructor>(relationTable: string | R, referencingColumnOrPrimaryColumn: ModelKey<InstanceType<R>> | JoinableColumn | ModelKey<T>, primaryColumn?: JoinableColumn | ModelKey<T>, operator?: BinaryOperatorType): this;
3720
3726
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator: BinaryOperatorType, callback: JoinOnCallback): this;
3721
3727
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, callback: JoinOnCallback): this;
3722
3728
  }
@@ -4623,7 +4629,7 @@ declare class ModelQueryBuilder<T extends Model, S extends Record<string, any> =
4623
4629
  finally(onfinally?: (() => void) | null | undefined): Promise<SelectedModel<T, S, R>[]>;
4624
4630
  chunk(chunkSize: number, options?: ManyOptions): AsyncGenerator<SelectedModel<T, S, R>[] | T[]>;
4625
4631
  stream(options?: ManyOptions & StreamOptions): Promise<PassThrough & AsyncGenerator<SelectedModel<T, S, R> | T>>;
4626
- paginateWithCursor<K extends ModelKey<T>>(page: number, options?: PaginateWithCursorOptions<T, K>, cursor?: Cursor<T, K>): Promise<[CursorPaginatedData<T, S, R>, Cursor<T, K>]>;
4632
+ paginateWithCursor<K extends ModelKey<T>>(limit: number, options?: PaginateWithCursorOptions<T, K>, cursor?: Cursor<T, K>): Promise<[CursorPaginatedData<T, S, R>, Cursor<T, K>]>;
4627
4633
  /**
4628
4634
  * @description Inserts a new record into the database, it is not advised to use this method directly from the query builder if using a ModelQueryBuilder (`Model.query()`), use the `Model.insert` method instead.
4629
4635
  */
@@ -5466,7 +5472,7 @@ declare class SqlDataSource<D extends SqlDataSourceType = SqlDataSourceType, T e
5466
5472
  * @description Returns a ModelQueryBuilder instance for the given model
5467
5473
  * @param Model The model to create the query builder from
5468
5474
  */
5469
- from<T extends typeof Model>(Model: T): ModelQueryBuilder<InstanceType<T>>;
5475
+ from<T extends AnyModelConstructor>(model: T): ModelQueryBuilder<InstanceType<T>>;
5470
5476
  /**
5471
5477
  * @description Returns a SchemaBuilder instance for DDL operations
5472
5478
  * @description The builder will execute queries when awaited or when .execute() is called
@@ -5768,7 +5774,7 @@ type RawModelOptions = {
5768
5774
  * @example
5769
5775
  * type UserInstance = ModelInstanceType<typeof User>; // User
5770
5776
  */
5771
- type ModelInstanceType<O> = O extends typeof Model ? InstanceType<O> : never;
5777
+ type ModelInstanceType<O> = O extends AnyModelConstructor ? InstanceType<O> : never;
5772
5778
  /**
5773
5779
  * Available fetch hook combinations for query execution.
5774
5780
  * Hooks can be selectively ignored when fetching data.
@@ -6522,6 +6528,480 @@ declare abstract class Model<T extends Model<T> = any> extends Entity {
6522
6528
  private static dispatchModelManager;
6523
6529
  }
6524
6530
 
6531
+ declare const __selfBrand: unique symbol;
6532
+
6533
+ /**
6534
+ * Phantom-typed descriptor for a model column.
6535
+ * `T` carries the TypeScript type the column resolves to at the instance level.
6536
+ */
6537
+ interface ColumnDef<T = unknown> {
6538
+ readonly _phantom: T;
6539
+ readonly _apply: (target: Object, propertyKey: string) => void;
6540
+ }
6541
+ /**
6542
+ * Phantom-typed descriptor for a model relation.
6543
+ * `T` carries the TypeScript type the relation resolves to at the instance level.
6544
+ */
6545
+ interface RelationDef<T = any> {
6546
+ readonly _phantom: T;
6547
+ readonly _apply: (target: Object, propertyKey: string) => void;
6548
+ }
6549
+ type ColOptions = Omit<ColumnOptions, "primaryKey" | "serialize" | "prepare">;
6550
+ type ColPrimaryOptions = Omit<ColumnOptions, "primaryKey" | "serialize" | "prepare">;
6551
+ type ColStringOptions = Omit<ColumnOptions, "type" | "serialize" | "prepare"> & {
6552
+ length?: number;
6553
+ };
6554
+ type ColTextOptions = Omit<ColumnOptions, "type" | "serialize" | "prepare">;
6555
+ type ColIntegerOptions = Omit<ColumnOptions, "serialize" | "prepare">;
6556
+ type ColBigIntegerOptions = Omit<ColumnOptions, "serialize" | "prepare">;
6557
+ type ColFloatOptions = Omit<ColumnOptions, "serialize" | "prepare">;
6558
+ type ColDecimalOptions = Omit<ColumnOptions, "serialize" | "prepare"> & {
6559
+ precision?: number;
6560
+ scale?: number;
6561
+ };
6562
+ type ColIncrementOptions = Omit<ColumnOptions, "serialize" | "prepare" | "primaryKey" | "nullable">;
6563
+ type ColBigIncrementOptions = Omit<ColumnOptions, "serialize" | "prepare" | "primaryKey" | "nullable">;
6564
+ type ColBooleanOptions = Omit<ColumnOptions, "prepare" | "serialize">;
6565
+ type ColDateOptions = Omit<DateColumnOptions, "format" | "serialize" | "prepare">;
6566
+ type ColDatetimeOptions = Omit<DatetimeColumnOptions, "serialize" | "prepare">;
6567
+ type ColTimestampOptions = Omit<DatetimeColumnOptions, "serialize" | "prepare">;
6568
+ type ColTimeOptions = Omit<DateColumnOptions, "format" | "serialize" | "prepare">;
6569
+ type ColJsonOptions = Omit<ColumnOptions, "prepare" | "serialize">;
6570
+ type ColUuidOptions = Omit<ColumnOptions, "prepare" | "serialize">;
6571
+ type ColUlidOptions = Omit<ColumnOptions, "prepare" | "serialize">;
6572
+ type ColBinaryOptions = Omit<ColumnOptions, "type" | "serialize" | "prepare">;
6573
+ type ColEnumOptions = Omit<ColumnOptions, "type" | "serialize" | "prepare">;
6574
+ type ColSymmetricOptions = Omit<SymmetricEncryptionOptions, "prepare" | "serialize">;
6575
+ type ColAsymmetricOptions = Omit<AsymmetricEncryptionOptions, "prepare" | "serialize">;
6576
+ type RelationConstraintOptions = {
6577
+ /**
6578
+ * Useful for auto generated migrations to specify the on delete action, it does not affect the code wise implementation
6579
+ */
6580
+ onDelete?: OnUpdateOrDelete;
6581
+ /**
6582
+ * Useful for auto generated migrations to specify the on update action, it does not affect the code wise implementation
6583
+ */
6584
+ onUpdate?: OnUpdateOrDelete;
6585
+ /**
6586
+ * Useful for auto generated migrations to specify the constraint name, it does not affect the code wise implementation
6587
+ */
6588
+ constraintName?: string;
6589
+ };
6590
+ type RelationNullableOption = {
6591
+ nullable?: boolean;
6592
+ };
6593
+ /**
6594
+ * Resolves to `Base` when `Opts` has `{ nullable: false }`, otherwise
6595
+ * `Base | null | undefined`. This powers nullable-aware type inference
6596
+ * for `col.*()` methods.
6597
+ */
6598
+ type NullableColumn<Base, Opts> = Opts extends {
6599
+ nullable: false;
6600
+ } ? Base : Base | null | undefined;
6601
+ type TypedSerialize<T> = {
6602
+ serialize?: (value: any) => T;
6603
+ };
6604
+ type TypedPrepare<T> = {
6605
+ prepare?: (value: T) => any;
6606
+ };
6607
+ interface ColNamespace {
6608
+ /**
6609
+ * Generic column — you control the TypeScript type via `col<T>()`.
6610
+ * Use for columns whose type doesn't match any built-in helper.
6611
+ *
6612
+ * Supports typed `serialize` and `prepare` callbacks.
6613
+ *
6614
+ * ```ts
6615
+ * col<string>({ nullable: false })
6616
+ * col<MyCustomType>({ serialize: (raw) => parse(raw), prepare: (v) => stringify(v) })
6617
+ * ```
6618
+ */
6619
+ <T = unknown>(options?: ColOptions & TypedSerialize<T> & TypedPrepare<T>): ColumnDef<T>;
6620
+ /**
6621
+ * Generic primary key column. Defaults to `string | number`.
6622
+ * Override the generic when you know the exact type.
6623
+ *
6624
+ * ```ts
6625
+ * col.primary<number>({ nullable: false })
6626
+ * ```
6627
+ */
6628
+ primary<T = string | number>(options?: ColPrimaryOptions & TypedSerialize<T> & TypedPrepare<T>): ColumnDef<T>;
6629
+ /**
6630
+ * VARCHAR column. Accepts an optional `length` option.
6631
+ * Type: `string` (nullable-aware).
6632
+ *
6633
+ * ```ts
6634
+ * col.string({ length: 255, nullable: false }) // string
6635
+ * col.string() // string | null | undefined
6636
+ * ```
6637
+ */
6638
+ string<O extends ColStringOptions = ColStringOptions>(options?: O & TypedSerialize<NullableColumn<string, O>> & TypedPrepare<NullableColumn<string, O>>): ColumnDef<NullableColumn<string, O>>;
6639
+ /**
6640
+ * LONGTEXT column for large text content.
6641
+ * Type: `string` (nullable-aware).
6642
+ */
6643
+ text<O extends ColTextOptions = ColTextOptions>(options?: O & TypedSerialize<NullableColumn<string, O>> & TypedPrepare<NullableColumn<string, O>>): ColumnDef<NullableColumn<string, O>>;
6644
+ /**
6645
+ * Integer column.
6646
+ * Type: `number` (nullable-aware). Only `prepare` is exposed (no `serialize`).
6647
+ */
6648
+ integer<O extends ColIntegerOptions = ColIntegerOptions>(options?: O & TypedPrepare<NullableColumn<number, O>>): ColumnDef<NullableColumn<number, O>>;
6649
+ /**
6650
+ * Big integer column for values exceeding 32-bit range.
6651
+ * Type: `number | bigint` (nullable-aware). Only `prepare` is exposed.
6652
+ */
6653
+ bigInteger<O extends ColBigIntegerOptions = ColBigIntegerOptions>(options?: O & TypedPrepare<NullableColumn<number | bigint, O>>): ColumnDef<NullableColumn<number | bigint, O>>;
6654
+ /**
6655
+ * Floating-point column.
6656
+ * Type: `number` (nullable-aware). Only `prepare` is exposed.
6657
+ */
6658
+ float<O extends ColFloatOptions = ColFloatOptions>(options?: O & TypedPrepare<NullableColumn<number, O>>): ColumnDef<NullableColumn<number, O>>;
6659
+ /**
6660
+ * Decimal column with optional `precision` and `scale`.
6661
+ * Type: `number` (nullable-aware). Only `prepare` is exposed.
6662
+ *
6663
+ * ```ts
6664
+ * col.decimal({ precision: 10, scale: 2, nullable: false }) // number
6665
+ * ```
6666
+ */
6667
+ decimal<O extends ColDecimalOptions = ColDecimalOptions>(options?: O & TypedPrepare<NullableColumn<number, O>>): ColumnDef<NullableColumn<number, O>>;
6668
+ /**
6669
+ * Auto-incrementing integer primary key. Always non-nullable.
6670
+ * Type: `number`. Only `prepare` is exposed.
6671
+ */
6672
+ increment(options?: ColIncrementOptions & TypedPrepare<number>): ColumnDef<number>;
6673
+ /**
6674
+ * Auto-incrementing bigint primary key. Always non-nullable.
6675
+ * Type: `number`. Only `prepare` is exposed.
6676
+ */
6677
+ bigIncrement(options?: ColBigIncrementOptions & TypedPrepare<number>): ColumnDef<number>;
6678
+ /**
6679
+ * Boolean column.
6680
+ * Type: `boolean` (nullable-aware). No `serialize` or `prepare` exposed.
6681
+ */
6682
+ boolean<O extends ColBooleanOptions = ColBooleanOptions>(options?: O): ColumnDef<NullableColumn<boolean, O>>;
6683
+ /**
6684
+ * DATE column (YYYY-MM-DD). Defaults to `Date` because database drivers
6685
+ * return `Date` objects.
6686
+ *
6687
+ * To type as `string`, use `col.date<string>()` and provide a `serialize`
6688
+ * function that converts the driver `Date` into a string:
6689
+ *
6690
+ * ```ts
6691
+ * col.date<string>({ serialize: (raw) => raw.toISOString().split("T")[0] })
6692
+ * ```
6693
+ */
6694
+ date<T extends Date | string = Date>(options: ColDateOptions & {
6695
+ nullable: false;
6696
+ } & TypedSerialize<T> & TypedPrepare<T>): ColumnDef<T>;
6697
+ date<T extends Date | string = Date>(options?: ColDateOptions & TypedSerialize<T | null | undefined> & TypedPrepare<T | null | undefined>): ColumnDef<T | null | undefined>;
6698
+ /**
6699
+ * DATETIME column. Defaults to `Date` because database drivers return
6700
+ * `Date` objects.
6701
+ *
6702
+ * To type as `string`, use `col.datetime<string>()` and provide a
6703
+ * `serialize` function that converts the driver `Date` into a string:
6704
+ *
6705
+ * ```ts
6706
+ * col.datetime<string>({ serialize: (raw) => new Date(raw).toISOString() })
6707
+ * ```
6708
+ */
6709
+ datetime<T extends Date | string = Date>(options: ColDatetimeOptions & {
6710
+ nullable: false;
6711
+ } & TypedSerialize<T> & TypedPrepare<T>): ColumnDef<T>;
6712
+ datetime<T extends Date | string = Date>(options?: ColDatetimeOptions & TypedSerialize<T | null | undefined> & TypedPrepare<T | null | undefined>): ColumnDef<T | null | undefined>;
6713
+ /**
6714
+ * TIMESTAMP column. Defaults to `Date` because database drivers return
6715
+ * `Date` objects.
6716
+ *
6717
+ * To type as `string`, use `col.timestamp<string>()` and provide a
6718
+ * `serialize` function that converts the driver `Date` into a string:
6719
+ *
6720
+ * ```ts
6721
+ * col.timestamp<string>({ serialize: (raw) => new Date(raw).toISOString() })
6722
+ * ```
6723
+ */
6724
+ timestamp<T extends Date | string = Date>(options: ColTimestampOptions & {
6725
+ nullable: false;
6726
+ } & TypedSerialize<T> & TypedPrepare<T>): ColumnDef<T>;
6727
+ timestamp<T extends Date | string = Date>(options?: ColTimestampOptions & TypedSerialize<T | null | undefined> & TypedPrepare<T | null | undefined>): ColumnDef<T | null | undefined>;
6728
+ /**
6729
+ * TIME column. Defaults to `Date` because database drivers return
6730
+ * `Date` objects.
6731
+ *
6732
+ * To type as `string`, use `col.time<string>()` and provide a
6733
+ * `serialize` function that converts the driver `Date` into a string:
6734
+ *
6735
+ * ```ts
6736
+ * col.time<string>({ serialize: (raw) => new Date(raw).toTimeString() })
6737
+ * ```
6738
+ */
6739
+ time<T extends Date | string = Date>(options: ColTimeOptions & {
6740
+ nullable: false;
6741
+ } & TypedSerialize<T> & TypedPrepare<T>): ColumnDef<T>;
6742
+ time<T extends Date | string = Date>(options?: ColTimeOptions & TypedSerialize<T | null | undefined> & TypedPrepare<T | null | undefined>): ColumnDef<T | null | undefined>;
6743
+ /**
6744
+ * JSON/JSONB column. Defaults to `unknown`.
6745
+ * Pass a concrete type for structured JSON data: `col.json<MyType>()`.
6746
+ *
6747
+ * No `serialize` or `prepare` exposed — serialization is handled internally.
6748
+ *
6749
+ * ```ts
6750
+ * col.json<{ theme: string }>({ nullable: false }) // { theme: string }
6751
+ * col.json() // unknown | null | undefined
6752
+ * ```
6753
+ */
6754
+ json<T = unknown>(options: ColJsonOptions & {
6755
+ nullable: false;
6756
+ }): ColumnDef<T>;
6757
+ json<T = unknown>(options?: ColJsonOptions): ColumnDef<T | null | undefined>;
6758
+ /**
6759
+ * UUID column. Auto-generates a UUID if no value is provided on insert.
6760
+ * Type: `string` (nullable-aware). Only `serialize` is exposed.
6761
+ */
6762
+ uuid<O extends ColUuidOptions = ColUuidOptions>(options?: O & TypedSerialize<NullableColumn<string, O>>): ColumnDef<NullableColumn<string, O>>;
6763
+ /**
6764
+ * ULID column. Auto-generates a ULID if no value is provided on insert.
6765
+ * Type: `string` (nullable-aware). Only `serialize` is exposed.
6766
+ */
6767
+ ulid<O extends ColUlidOptions = ColUlidOptions>(options?: O & TypedSerialize<NullableColumn<string, O>>): ColumnDef<NullableColumn<string, O>>;
6768
+ /**
6769
+ * Binary/blob column.
6770
+ * Type: `Buffer | Uint8Array | string` (nullable-aware).
6771
+ * Supports typed `serialize` and `prepare`.
6772
+ */
6773
+ binary<T extends Buffer | Uint8Array | string = Buffer | Uint8Array | string, O extends ColBinaryOptions = ColBinaryOptions>(options?: O & TypedSerialize<NullableColumn<T, O>> & TypedPrepare<NullableColumn<T, O>>): ColumnDef<NullableColumn<T, O>>;
6774
+ /**
6775
+ * Enum column constrained to the given values array.
6776
+ * Type: `values[number]` (nullable-aware).
6777
+ *
6778
+ * ```ts
6779
+ * col.enum(["active", "inactive"] as const) // "active" | "inactive" | null | undefined
6780
+ * col.enum(["active", "inactive"] as const, { nullable: false }) // "active" | "inactive"
6781
+ * ```
6782
+ */
6783
+ enum<const V extends readonly string[], O extends ColEnumOptions = ColEnumOptions>(values: V, options?: O & TypedSerialize<NullableColumn<V[number], O>> & TypedPrepare<NullableColumn<V[number], O>>): ColumnDef<NullableColumn<V[number], O>>;
6784
+ /** Encryption column helpers. */
6785
+ encryption: {
6786
+ /**
6787
+ * Symmetric encryption column (AES). Requires `key` in options.
6788
+ * Type: `string` (nullable-aware). No `serialize` or `prepare` exposed.
6789
+ */
6790
+ symmetric<O extends ColSymmetricOptions = ColSymmetricOptions>(options: O): ColumnDef<NullableColumn<string, O>>;
6791
+ /**
6792
+ * Asymmetric encryption column (RSA). Requires `publicKey` and
6793
+ * `privateKey` in options.
6794
+ * Type: `string` (nullable-aware). No `serialize` or `prepare` exposed.
6795
+ */
6796
+ asymmetric<O extends ColAsymmetricOptions = ColAsymmetricOptions>(options: O): ColumnDef<NullableColumn<string, O>>;
6797
+ };
6798
+ }
6799
+ type AnyModelClass = abstract new (...args: any[]) => Model;
6800
+ type SelfModelInstance = Model & {
6801
+ readonly [__selfBrand]: true;
6802
+ };
6803
+ type SelfToken = abstract new (...args: any[]) => SelfModelInstance;
6804
+ /**
6805
+ * Model callback type for relation definitions.
6806
+ * Accepts either `() => OtherModel` or `(self) => self` for self-referencing
6807
+ * relations (tree structures, parent/child, etc.).
6808
+ */
6809
+ type RelModelCallback<M extends AnyModelClass> = (self: SelfToken) => M;
6810
+ /**
6811
+ * Provides autocomplete for column keys of the related model while still accepting any string
6812
+ */
6813
+ type ForeignKeyOf<M extends AnyModelClass> = ModelKey<InstanceType<M> & Model> | (string & {});
6814
+ /**
6815
+ * Extracts the Model instance type from a through-model callback.
6816
+ */
6817
+ type InferThroughModelInstance<TM> = TM extends () => infer T ? T extends AnyModelClass ? InstanceType<T> & Model : Model : Model;
6818
+ interface RelNamespace {
6819
+ /**
6820
+ * One-to-one relation where the foreign key lives on the **related** model.
6821
+ * The `foreignKey` parameter autocompletes with column keys of `M`.
6822
+ *
6823
+ * Pass `{ nullable: false }` to type the relation as non-nullable.
6824
+ *
6825
+ * ```ts
6826
+ * rel.hasOne(() => Profile, "userId", { nullable: false }) // Profile
6827
+ * rel.hasOne(() => Profile, "userId") // Profile | null | undefined
6828
+ * ```
6829
+ *
6830
+ * @param model Callback returning the related model class (or `(self) => self` for self-referencing).
6831
+ * @param foreignKey Column on the related model that references the current model's primary key.
6832
+ * @param options `{ nullable: false }` to mark the relation as always present.
6833
+ */
6834
+ hasOne<M extends AnyModelClass>(model: RelModelCallback<M>, foreignKey: ForeignKeyOf<M> | undefined, options: {
6835
+ nullable: false;
6836
+ }): RelationDef<InstanceType<M>>;
6837
+ hasOne<M extends AnyModelClass>(model: RelModelCallback<M>, foreignKey?: ForeignKeyOf<M>, options?: RelationNullableOption): RelationDef<InstanceType<M> | null | undefined>;
6838
+ /**
6839
+ * One-to-many relation where the foreign key lives on the **related** model.
6840
+ * The `foreignKey` parameter autocompletes with column keys of `M`.
6841
+ *
6842
+ * Pass `{ nullable: false }` to type the relation as non-nullable (always
6843
+ * returns an array, never `null | undefined`).
6844
+ *
6845
+ * ```ts
6846
+ * rel.hasMany(() => Post, "authorId", { nullable: false }) // Post[]
6847
+ * rel.hasMany(() => Post, "authorId") // Post[] | null | undefined
6848
+ * ```
6849
+ *
6850
+ * @param model Callback returning the related model class (or `(self) => self` for self-referencing).
6851
+ * @param foreignKey Column on the related model that references the current model's primary key.
6852
+ * @param options `{ nullable: false }` to mark the relation as always present.
6853
+ */
6854
+ hasMany<M extends AnyModelClass>(model: RelModelCallback<M>, foreignKey: ForeignKeyOf<M> | undefined, options: {
6855
+ nullable: false;
6856
+ }): RelationDef<InstanceType<M>[]>;
6857
+ hasMany<M extends AnyModelClass>(model: RelModelCallback<M>, foreignKey?: ForeignKeyOf<M>, options?: RelationNullableOption): RelationDef<InstanceType<M>[] | null | undefined>;
6858
+ /**
6859
+ * Inverse one-to-one / many-to-one relation where the foreign key lives
6860
+ * on the **current** model.
6861
+ *
6862
+ * The `foreignKey` parameter autocompletes with column keys of the related
6863
+ * model `M` as a naming hint; any string is still accepted since the
6864
+ * actual column is on the current model.
6865
+ *
6866
+ * Pass `{ nullable: false }` (inside the constraint options) to type the
6867
+ * relation as non-nullable.
6868
+ *
6869
+ * ```ts
6870
+ * rel.belongsTo(() => User, "userId", { nullable: false }) // User
6871
+ * rel.belongsTo(() => User, "userId") // User | null | undefined
6872
+ * rel.belongsTo((self) => self, "parentId") // self-referencing
6873
+ * ```
6874
+ *
6875
+ * @param model Callback returning the related model class (or `(self) => self` for self-referencing).
6876
+ * @param foreignKey Column on the **current** model that references the related model's primary key.
6877
+ * @param options Constraint options (`onDelete`, `onUpdate`, `constraintName`) and `{ nullable: false }`.
6878
+ */
6879
+ belongsTo<M extends AnyModelClass>(model: RelModelCallback<M>, foreignKey: ForeignKeyOf<M> | undefined, options: RelationConstraintOptions & {
6880
+ nullable: false;
6881
+ }): RelationDef<InstanceType<M>>;
6882
+ belongsTo<M extends AnyModelClass>(model: RelModelCallback<M>, foreignKey?: ForeignKeyOf<M>, options?: RelationConstraintOptions & RelationNullableOption): RelationDef<InstanceType<M> | null | undefined>;
6883
+ /**
6884
+ * Many-to-many relation through a pivot (join) table.
6885
+ *
6886
+ * - `throughModel`: either a string (pivot table name) or a callback
6887
+ * returning a Model class (`() => PivotModel`).
6888
+ * - When a Model callback is provided:
6889
+ * - `leftForeignKey` autocompletes with the **through model**'s column
6890
+ * keys (the FK on the pivot table referencing the current model).
6891
+ * - `rightForeignKey` autocompletes with the **related model** `M`'s
6892
+ * column keys (the FK on the pivot table referencing the related model).
6893
+ * - When a plain string is provided, both keys accept any string.
6894
+ *
6895
+ * Pass `{ nullable: false }` to type the relation as non-nullable.
6896
+ *
6897
+ * ```ts
6898
+ * // Through model as callback — typed FK autocomplete
6899
+ * rel.manyToMany(() => Tag, () => PostTag, {
6900
+ * leftForeignKey: "postId", // autocompletes with PostTag keys
6901
+ * rightForeignKey: "tagId", // autocompletes with Tag keys
6902
+ * })
6903
+ *
6904
+ * // Through model as string — plain string FKs
6905
+ * rel.manyToMany(() => Tag, "post_tags", {
6906
+ * leftForeignKey: "post_id",
6907
+ * rightForeignKey: "tag_id",
6908
+ * })
6909
+ * ```
6910
+ *
6911
+ * @param model Callback returning the related model class.
6912
+ * @param throughModel Pivot model callback or table name string.
6913
+ * @param throughModelKeys Foreign key mapping on the pivot table.
6914
+ * @param options Constraint options and `{ nullable: false }`.
6915
+ */
6916
+ manyToMany<M extends AnyModelClass, T extends AnyModelConstructor = AnyModelConstructor, TM extends ThroughModel<T> = ThroughModel<T>>(model: RelModelCallback<M>, throughModel: TM, throughModelKeys: TM extends string ? ManyToManyStringOptions : {
6917
+ leftForeignKey?: ModelKey<InferThroughModelInstance<TM>> | (string & {});
6918
+ rightForeignKey?: ForeignKeyOf<M>;
6919
+ }, options: RelationConstraintOptions & {
6920
+ nullable: false;
6921
+ }): RelationDef<InstanceType<M>[]>;
6922
+ manyToMany<M extends AnyModelClass, T extends AnyModelConstructor = AnyModelConstructor, TM extends ThroughModel<T> = ThroughModel<T>>(model: RelModelCallback<M>, throughModel: TM, throughModelKeys?: TM extends string ? ManyToManyStringOptions : {
6923
+ leftForeignKey?: ModelKey<InferThroughModelInstance<TM>> | (string & {});
6924
+ rightForeignKey?: ForeignKeyOf<M>;
6925
+ }, options?: RelationConstraintOptions & RelationNullableOption): RelationDef<InstanceType<M>[] | null | undefined>;
6926
+ }
6927
+ type IndexDefinition<K extends string = string> = K[] | {
6928
+ columns: K[];
6929
+ name?: string;
6930
+ };
6931
+ type UniqueDefinition<K extends string = string> = K[] | {
6932
+ columns: K[];
6933
+ name?: string;
6934
+ };
6935
+ type CheckDefinition = string | {
6936
+ expression: string;
6937
+ name?: string;
6938
+ };
6939
+ type HooksDefinition<T = any> = {
6940
+ beforeFetch?: (queryBuilder: ModelQueryBuilder<any>) => Promise<void> | void;
6941
+ afterFetch?: (data: T[]) => Promise<T[]> | T[];
6942
+ beforeInsert?: (data: Partial<T>) => Promise<void> | void;
6943
+ beforeInsertMany?: (data: Partial<T>[]) => Promise<void> | void;
6944
+ beforeUpdate?: (queryBuilder: ModelQueryBuilder<any>) => Promise<void> | void;
6945
+ beforeDelete?: (queryBuilder: ModelQueryBuilder<any>) => Promise<void> | void;
6946
+ };
6947
+ type DefineModelOptions<K extends string = string> = {
6948
+ modelCaseConvention?: CaseConvention;
6949
+ databaseCaseConvention?: CaseConvention;
6950
+ softDeleteColumn?: K;
6951
+ softDeleteValue?: boolean | string;
6952
+ };
6953
+ type InferColumns<C extends Record<string, ColumnDef>> = {
6954
+ [K in keyof C]: C[K] extends ColumnDef<infer T> ? T : never;
6955
+ };
6956
+ /**
6957
+ * Detects self-referencing relations (branded with `SelfModelInstance`) and
6958
+ * replaces them with the actual column types of the defining model.
6959
+ * Non-self relations pass through unchanged.
6960
+ */
6961
+ type ResolveSelfRef<T, SelfType> = [T] extends [
6962
+ SelfModelInstance[] | null | undefined
6963
+ ] ? SelfType[] | Extract<T, null | undefined> : [T] extends [SelfModelInstance | null | undefined] ? SelfType | Extract<T, null | undefined> : T;
6964
+ type InferRelations<C extends Record<string, ColumnDef>, R extends Record<string, RelationDef>> = {
6965
+ [K in keyof R]: R[K] extends RelationDef<infer T> ? ResolveSelfRef<T, InferColumns<C> & Model> : never;
6966
+ };
6967
+ /**
6968
+ * Infers the instance type of a model defined with `defineModel`.
6969
+ */
6970
+ type InferModel<C extends Record<string, ColumnDef>, R extends Record<string, RelationDef>> = InferColumns<C> & InferRelations<C, R>;
6971
+ type ModelDefinition<C extends Record<string, ColumnDef> = Record<string, ColumnDef>, R extends Record<string, RelationDef> = Record<string, RelationDef>> = {
6972
+ columns: C;
6973
+ relations?: R;
6974
+ indexes?: IndexDefinition<keyof C & string>[];
6975
+ uniques?: UniqueDefinition<keyof C & string>[];
6976
+ checks?: CheckDefinition[];
6977
+ hooks?: HooksDefinition<InferColumns<C>>;
6978
+ options?: DefineModelOptions<keyof C & string>;
6979
+ };
6980
+ /**
6981
+ * Public statics of `typeof Model` without the abstract constructor flag.
6982
+ */
6983
+ type ConcreteModelStatics = {
6984
+ [K in keyof typeof Model]: (typeof Model)[K];
6985
+ };
6986
+ /**
6987
+ * Union type that accepts both decorator-based model classes (`typeof Model`
6988
+ * subclasses) and programmatic models created via `defineModel`.
6989
+ *
6990
+ * Use this instead of `typeof Model` in any user-facing API that should
6991
+ * accept either kind of model.
6992
+ */
6993
+ type AnyModelConstructor = typeof Model | (ConcreteModelStatics & (new (...args: any[]) => Model));
6994
+ /**
6995
+ * The return type of `defineModel` – a concrete Model constructor whose
6996
+ * instances carry the inferred column + relation properties.
6997
+ *
6998
+ * Uses a mapped type over `typeof Model` so the abstract flag is stripped,
6999
+ * making the result instantiable while keeping all public static members.
7000
+ */
7001
+ type DefinedModel<C extends Record<string, ColumnDef>, R extends Record<string, RelationDef>> = ConcreteModelStatics & {
7002
+ new (): InferModel<C, R> & Model;
7003
+ };
7004
+
6525
7005
  type BaseModelRelationType = {
6526
7006
  onDelete?: OnUpdateOrDelete;
6527
7007
  onUpdate?: OnUpdateOrDelete;
@@ -6768,7 +7248,7 @@ declare function timeOnlyColumn(options?: Omit<DateColumnOptions, "format">): Ty
6768
7248
  * @description Defaults type to jsonb for migration generation
6769
7249
  */
6770
7250
  declare function jsonColumn(options?: Omit<ColumnOptions, "prepare" | "serialize">): TypedPropertyDecorator<unknown>;
6771
- declare function getModelColumns(target: typeof Model): ColumnType[];
7251
+ declare function getModelColumns(target: AnyModelConstructor): ColumnType[];
6772
7252
  /**
6773
7253
  * relations
6774
7254
  */
@@ -6780,22 +7260,22 @@ declare function getModelColumns(target: typeof Model): ColumnType[];
6780
7260
  * belongsTo<typeof Post>(() => User, 'userId')
6781
7261
  * ```
6782
7262
  */
6783
- declare function belongsTo<M extends typeof Model = any, R extends typeof Model = any>(model: () => R, foreignKey?: ModelKey<InstanceType<M>>, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R> | null | undefined>;
6784
- declare function belongsTo<R extends typeof Model = any>(model: () => R, foreignKey?: string, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R> | null | undefined>;
7263
+ declare function belongsTo<M extends AnyModelConstructor = any, R extends AnyModelConstructor = any>(model: () => R, foreignKey?: ModelKey<InstanceType<M>>, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R> | null | undefined>;
7264
+ declare function belongsTo<R extends AnyModelConstructor = any>(model: () => R, foreignKey?: string, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R> | null | undefined>;
6785
7265
  /**
6786
7266
  * @description Establishes a has one relation with the given model
6787
7267
  * @default foreignKey by default will be the singular of the model name plus "_id"
6788
7268
  * @example User will have foreignKey "user_id" on the Post model
6789
7269
  */
6790
- declare function hasOne<T extends typeof Model>(model: () => T, foreignKey?: ModelKey<InstanceType<T>>): TypedPropertyDecorator<InstanceType<T> | null | undefined>;
6791
- declare function hasOne<T extends typeof Model>(model: () => T, foreignKey?: string): TypedPropertyDecorator<InstanceType<T> | null | undefined>;
7270
+ declare function hasOne<T extends AnyModelConstructor>(model: () => T, foreignKey?: ModelKey<InstanceType<T>>): TypedPropertyDecorator<InstanceType<T> | null | undefined>;
7271
+ declare function hasOne<T extends AnyModelConstructor>(model: () => T, foreignKey?: string): TypedPropertyDecorator<InstanceType<T> | null | undefined>;
6792
7272
  /**
6793
7273
  * @description Establishes a has many relation with the given model
6794
7274
  * @default foreignKey by default will be the singular of the model name plus "_id"
6795
7275
  * @example User will have foreignKey "user_id" on the Post model
6796
7276
  */
6797
- declare function hasMany<T extends typeof Model>(model: () => T, foreignKey?: ModelKey<InstanceType<T>>): TypedPropertyDecorator<InstanceType<T>[] | null | undefined>;
6798
- declare function hasMany<T extends typeof Model>(model: () => T, foreignKey?: string): TypedPropertyDecorator<InstanceType<T>[] | null | undefined>;
7277
+ declare function hasMany<T extends AnyModelConstructor>(model: () => T, foreignKey?: ModelKey<InstanceType<T>>): TypedPropertyDecorator<InstanceType<T>[] | null | undefined>;
7278
+ declare function hasMany<T extends AnyModelConstructor>(model: () => T, foreignKey?: string): TypedPropertyDecorator<InstanceType<T>[] | null | undefined>;
6799
7279
  /**
6800
7280
  * @description Establishes a many to many relation with the given model
6801
7281
  * @default foreignKey by default will be the singular of the model that establishes the relation name plus "_id"
@@ -6806,20 +7286,56 @@ declare function hasMany<T extends typeof Model>(model: () => T, foreignKey?: st
6806
7286
  * @param throughModelKeys.rightForeignKey The foreign key of the through model from the related model (the model you are joining to)
6807
7287
  * @example User will have foreignKey "user_id" on the Join table by default
6808
7288
  */
6809
- declare function manyToMany<R extends typeof Model, T extends typeof Model, TM extends ThroughModel<T>>(model: () => R, throughModel: TM, throughModelKeys?: ManyToManyOptions<T, TM>, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R>[] | null | undefined>;
6810
- declare function manyToMany<R extends typeof Model>(model: () => R, throughModel: string | (() => typeof Model), throughModelKeys?: ManyToManyStringOptions, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R>[] | null | undefined>;
6811
- declare function getRelationsMetadata(target: typeof Model): LazyRelationType[];
7289
+ declare function manyToMany<R extends AnyModelConstructor, T extends AnyModelConstructor, TM extends ThroughModel<T>>(model: () => R, throughModel: TM, throughModelKeys?: ManyToManyOptions<T, TM>, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R>[] | null | undefined>;
7290
+ declare function manyToMany<R extends AnyModelConstructor>(model: () => R, throughModel: string | (() => AnyModelConstructor), throughModelKeys?: ManyToManyStringOptions, options?: BaseModelRelationType): TypedPropertyDecorator<InstanceType<R>[] | null | undefined>;
7291
+ declare function getRelationsMetadata(target: AnyModelConstructor): LazyRelationType[];
6812
7292
  /**
6813
7293
  * @description Returns the relations of the model
6814
7294
  */
6815
- declare function getRelations(target: typeof Model): Relation[];
7295
+ declare function getRelations(target: AnyModelConstructor): Relation[];
6816
7296
  /**
6817
7297
  * @description Returns the primary key of the model
6818
7298
  */
6819
- declare function getPrimaryKey(target: typeof Model): string | undefined;
6820
- declare function getIndexes(target: typeof Model): IndexType[];
6821
- declare function getUniques(target: typeof Model): UniqueType[];
6822
- declare function getChecks(target: typeof Model): CheckType[];
7299
+ declare function getPrimaryKey(target: AnyModelConstructor): string | undefined;
7300
+ declare function getIndexes(target: AnyModelConstructor): IndexType[];
7301
+ declare function getUniques(target: AnyModelConstructor): UniqueType[];
7302
+ declare function getChecks(target: AnyModelConstructor): CheckType[];
7303
+
7304
+ declare const col: ColNamespace;
7305
+ declare const rel: RelNamespace;
7306
+ /**
7307
+ * Creates a fully-typed Model subclass programmatically without decorators.
7308
+ *
7309
+ * The returned class is a real `typeof Model` subclass that works with all
7310
+ * existing infrastructure: `SqlDataSource`, `ModelManager`, `ModelQueryBuilder`,
7311
+ * `SchemaDiff` (automatic migrations), hooks, etc.
7312
+ *
7313
+ * @example
7314
+ * ```typescript
7315
+ * import { defineModel, col, rel } from "hysteria-orm";
7316
+ *
7317
+ * const User = defineModel("users", {
7318
+ * columns: {
7319
+ * id: col.increment(),
7320
+ * name: col.string(),
7321
+ * email: col.string({ nullable: false }),
7322
+ * isActive: col.boolean(),
7323
+ * createdAt: col.datetime({ autoCreate: true }),
7324
+ * updatedAt: col.datetime({ autoCreate: true, autoUpdate: true }),
7325
+ * },
7326
+ * relations: {
7327
+ * posts: rel.hasMany(() => Post, "userId"),
7328
+ * profile: rel.hasOne(() => Profile),
7329
+ * },
7330
+ * indexes: [["email"]],
7331
+ * uniques: [["email"]],
7332
+ * hooks: {
7333
+ * beforeFetch(qb) { qb.whereNull("deleted_at"); },
7334
+ * },
7335
+ * });
7336
+ * ```
7337
+ */
7338
+ declare function defineModel<C extends Record<string, ColumnDef>, R extends Record<string, RelationDef> = {}>(table: string, definition: ModelDefinition<C, R>): DefinedModel<C, R>;
6823
7339
 
6824
7340
  type FactoryReturnType<T extends number, O extends Model> = T extends 1 ? O : O[];
6825
7341
 
@@ -6829,7 +7345,7 @@ declare class ModelFactory<M extends Model> {
6829
7345
  /**
6830
7346
  * @description Constructor for the model factory
6831
7347
  */
6832
- constructor(typeofModel: typeof Model, modelData: Partial<M>);
7348
+ constructor(typeofModel: AnyModelConstructor, modelData: Partial<M>);
6833
7349
  /**
6834
7350
  * @description Merges the provided data with the model data
6835
7351
  */
@@ -6841,7 +7357,7 @@ declare class ModelFactory<M extends Model> {
6841
7357
  */
6842
7358
  create<T extends number>(howMany: T): Promise<FactoryReturnType<T, M>>;
6843
7359
  }
6844
- declare const createModelFactory: <M extends Model>(typeofModel: typeof Model, modelData: Partial<ModelWithoutRelations<M>>) => ModelFactory<M>;
7360
+ declare const createModelFactory: <M extends Model>(typeofModel: AnyModelConstructor, modelData: Partial<ModelWithoutRelations<M>>) => ModelFactory<M>;
6845
7361
 
6846
7362
  type Constructor<T = Model> = new (...args: any[]) => T;
6847
7363
  type AbstractConstructor<T = Model> = abstract new (...args: any[]) => T;
@@ -7982,4 +8498,4 @@ declare const generateOpenApiModelWithMetadata: <T extends new () => Model>(mode
7982
8498
  $id?: string;
7983
8499
  }>;
7984
8500
 
7985
- export { type AbstractConstructor, type AdminJsActionOptions, type AdminJsAssets, type AdminJsBranding, type AdminJsInstance, type AdminJsLocale, type AdminJsOptions, type AdminJsPage, type AdminJsPropertyOptions, type AdminJsResourceOptions, type AdminJsSettings, type AnyConstructor, type AsymmetricEncryptionOptions, type BaseModelMethodOptions, type BaseModelRelationType, BaseSeeder, type BigIntFields, type BuildSelectType, type BuildSingleSelectType, type CacheAdapter, type CacheKeys, type CheckType, 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 ComposeBuildSelect, type ComposeSelect, type ConnectionPolicies, type Constructor, type CustomLogger, type DataSourceInput, type DataSourceType, type DateColumnOptions, type DatetimeColumnOptions, type ExcludeMethods, type ExtractColumnName, type ExtractSourceColumn, type FetchHooks, type FindReturnType, type GetColumnType, type GetConnectionReturnType, HysteriaError, InMemoryAdapter, type IncrementFields, type IndexType, type LazyRelationType, type LoggerConfig, type ManyOptions, type ManyToManyOptions, type ManyToManyStringOptions, Migration, type MigrationConfig, type MigrationConfigBase, type MixinColumns, MixinFactory, Model, type ModelDataProperties, type ModelInstanceType, type ModelKey, ModelQueryBuilder, type ModelQueryResult, type ModelRelation, type ModelSelectTuple, type ModelSelectableInput, 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, type RawQueryOptions, RedisCacheAdapter, type RedisFetchable, type RedisStorable, type RelatedInstance, type RelationQueryBuilderType, type ReplicationType, type ReturningColumns, type ReturningKey, Schema, SchemaBuilder, type SeederConfig, type SelectBrand, type SelectableColumn, type SelectedModel, type SlaveAlgorithm, type SlaveContext, 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, type TimestampFields, Transaction, type TransactionExecutionOptions, type TypedPropertyDecorator, type UlidFields, UlidMixin, type UniqueType, type UseCacheReturnType, type UseConnectionInput, type UuidFields, UuidMixin, WriteOperation, type WriteReturnType, belongsTo, bigIntMixin, check, column, createMixin, createModelFactory, defineMigrator, generateOpenApiModel, generateOpenApiModelSchema, generateOpenApiModelWithMetadata, getChecks, getCollectionProperties, getIndexes, getModelColumns, type getPoolReturnType, getPrimaryKey, getRelations, getRelationsMetadata, getUniques, hasMany, hasOne, incrementMixin, index, HysteriaLogger as logger, manyToMany, property, RedisDataSource as redis, timestampMixin, ulidMixin, unique, uuidMixin, view, withPerformance };
8501
+ export { type AbstractConstructor, type AdminJsActionOptions, type AdminJsAssets, type AdminJsBranding, type AdminJsInstance, type AdminJsLocale, type AdminJsOptions, type AdminJsPage, type AdminJsPropertyOptions, type AdminJsResourceOptions, type AdminJsSettings, type AnyConstructor, type AnyModelConstructor, type AsymmetricEncryptionOptions, type BaseModelMethodOptions, type BaseModelRelationType, BaseSeeder, type BigIntFields, type BuildSelectType, type BuildSingleSelectType, type CacheAdapter, type CacheKeys, type CheckType, ClientMigrator, Collection, type ColumnDataTypeOption, type ColumnDataTypeOptionSimple, type ColumnDataTypeOptionWithBinary, type ColumnDataTypeOptionWithDatePrecision, type ColumnDataTypeOptionWithEnum, type ColumnDataTypeOptionWithLength, type ColumnDataTypeOptionWithPrecision, type ColumnDataTypeOptionWithScaleAndPrecision, type ColumnDataTypeOptionWithText, type ColumnDef, type ColumnOptions, type ColumnType, type CommonDataSourceInput, type ComposeBuildSelect, type ComposeSelect, type ConnectionPolicies, type Constructor, type CustomLogger, type DataSourceInput, type DataSourceType, type DateColumnOptions, type DatetimeColumnOptions, type DefinedModel, type ExcludeMethods, type ExtractColumnName, type ExtractSourceColumn, type FetchHooks, type FindReturnType, type GetColumnType, type GetConnectionReturnType, HysteriaError, InMemoryAdapter, type IncrementFields, type IndexType, type LazyRelationType, type LoggerConfig, type ManyOptions, type ManyToManyOptions, type ManyToManyStringOptions, Migration, type MigrationConfig, type MigrationConfigBase, type MixinColumns, MixinFactory, Model, type ModelDataProperties, type ModelInstanceType, type ModelKey, ModelQueryBuilder, type ModelQueryResult, type ModelRelation, type ModelSelectTuple, type ModelSelectableInput, 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 NullableColumn, type NumberModelKey, type OneOptions, type OracleDBDataSourceInput, type OracleDBPoolInstance, type PgPoolClientInstance, type PostgresSqlDataSourceInput, QueryBuilder, type RawModelOptions, RawNode, type RawQueryOptions, RedisCacheAdapter, type RedisFetchable, type RedisStorable, type RelModelCallback, type RelatedInstance, type RelationDef, type RelationNullableOption, type RelationQueryBuilderType, type ReplicationType, type ReturningColumns, type ReturningKey, Schema, SchemaBuilder, type SeederConfig, type SelectBrand, type SelectableColumn, type SelectedModel, type SlaveAlgorithm, type SlaveContext, 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, type TimestampFields, Transaction, type TransactionExecutionOptions, type TypedPrepare, type TypedPropertyDecorator, type TypedSerialize, type UlidFields, UlidMixin, type UniqueType, type UseCacheReturnType, type UseConnectionInput, type UuidFields, UuidMixin, WriteOperation, type WriteReturnType, belongsTo, bigIntMixin, check, col, column, createMixin, createModelFactory, defineMigrator, defineModel, generateOpenApiModel, generateOpenApiModelSchema, generateOpenApiModelWithMetadata, getChecks, getCollectionProperties, getIndexes, getModelColumns, type getPoolReturnType, getPrimaryKey, getRelations, getRelationsMetadata, getUniques, hasMany, hasOne, incrementMixin, index, HysteriaLogger as logger, manyToMany, property, RedisDataSource as redis, rel, timestampMixin, ulidMixin, unique, uuidMixin, view, withPerformance };