hysteria-orm 12.2.2 → 12.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -733,12 +733,14 @@ declare class WhereNode extends QueryNode {
733
733
  column: string;
734
734
  isNegated: boolean;
735
735
  operator: BinaryOperatorType$2;
736
- value: BaseValues$2 | BaseValues$2[];
736
+ value: BaseValues$2 | BaseValues$2[] | BaseValues$2[][];
737
+ /** Set for a row-value `(a, b) in ((1, 2), ...)` predicate, where `value` is a list of tuples. */
738
+ tupleColumns?: string[];
737
739
  chainsWith: "and" | "or";
738
740
  canKeywordBeSeenMultipleTimes: boolean;
739
741
  folder: string;
740
742
  file: string;
741
- constructor(column: string, chainsWith: "and" | "or", isNegated: boolean | undefined, operator: BinaryOperatorType$2, value: BaseValues$2 | BaseValues$2[], isRawValue?: boolean);
743
+ constructor(column: string, chainsWith: "and" | "or", isNegated: boolean | undefined, operator: BinaryOperatorType$2, value: BaseValues$2 | BaseValues$2[] | BaseValues$2[][], isRawValue?: boolean);
742
744
  }
743
745
 
744
746
  type SubqueryOperatorType = "in" | "not in" | "exists" | "not exists" | "between" | "not between" | ">" | "<" | ">=" | "<=" | (string & {});
@@ -756,10 +758,11 @@ declare class WhereSubqueryNode extends QueryNode {
756
758
  declare class WhereGroupNode extends QueryNode {
757
759
  nodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[];
758
760
  chainsWith: "and" | "or";
761
+ isNegated: boolean;
759
762
  canKeywordBeSeenMultipleTimes: boolean;
760
763
  folder: string;
761
764
  file: string;
762
- constructor(nodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[], chainsWith?: "and" | "or");
765
+ constructor(nodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[], chainsWith?: "and" | "or", isNegated?: boolean);
763
766
  }
764
767
 
765
768
  type BaseValues$1 = string | number | boolean | null | SqlFuncNode;
@@ -921,22 +924,26 @@ declare class UnionNode extends QueryNode {
921
924
  query: QueryNode | QueryNode[] | string;
922
925
  isAll: boolean;
923
926
  type: SetOperationType;
927
+ bindings?: any[];
928
+ /** Wraps this branch in parentheses, needed when it carries its own ORDER BY or LIMIT. */
929
+ wrap?: boolean;
924
930
  chainsWith: string;
925
931
  canKeywordBeSeenMultipleTimes: boolean;
926
932
  folder: string;
927
933
  file: string;
928
- constructor(query: QueryNode | QueryNode[] | string, isAll?: boolean, type?: SetOperationType);
934
+ constructor(query: QueryNode | QueryNode[] | string, isAll?: boolean, type?: SetOperationType, bindings?: any[]);
929
935
  }
930
936
 
931
937
  declare class WithNode extends QueryNode {
932
938
  alias: string;
933
939
  body: QueryNode | QueryNode[];
934
940
  clause: string;
941
+ columns?: string[];
935
942
  chainsWith: string;
936
943
  canKeywordBeSeenMultipleTimes: boolean;
937
944
  folder: string;
938
945
  file: string;
939
- constructor(clause: string, alias: string, body: QueryNode | QueryNode[]);
946
+ constructor(clause: string, alias: string, body: QueryNode | QueryNode[], columns?: string[]);
940
947
  }
941
948
 
942
949
  declare abstract class DataSource {
@@ -1831,6 +1838,8 @@ declare class FromNode extends QueryNode {
1831
1838
  alias?: string;
1832
1839
  /** Schema applied to the table reference (e.g. `public.users`). */
1833
1840
  schema?: string;
1841
+ /** PostgreSQL `FROM ONLY`, which skips rows of inheriting tables. */
1842
+ only?: boolean;
1834
1843
  constructor(table: string | QueryNode | QueryNode[], alias?: string);
1835
1844
  }
1836
1845
 
@@ -1929,6 +1938,18 @@ declare class InterpreterUtils {
1929
1938
  * @description Formats the from node for write operations removing the "from" keyword
1930
1939
  */
1931
1940
  getFromForWriteOperations(dbType: SqlDataSourceType, fromNode: FromNode): string;
1941
+ /**
1942
+ * @description Renders the auxiliary source of a write (`update ... from`,
1943
+ * `delete ... using`). Unlike the main write table it keeps its alias, since the
1944
+ * clause is unreadable without one.
1945
+ */
1946
+ getWriteSource(dbType: SqlDataSourceType, fromNode: FromNode, startIndex: number): ReturnType<typeof AstParser.prototype.parse>;
1947
+ /**
1948
+ * @description Renders CTE nodes as a leading `with ...` clause. Used by writes
1949
+ * whose dialect places the CTE inside the statement body (INSERT) rather than
1950
+ * as a sibling node.
1951
+ */
1952
+ renderWithNodes(dbType: SqlDataSourceType, withNodes: WithNode[] | undefined, startIndex: number): ReturnType<typeof AstParser.prototype.parse>;
1932
1953
  }
1933
1954
 
1934
1955
  /**
@@ -1972,6 +1993,67 @@ declare class WriteOperation<T> implements PromiseLike<T> {
1972
1993
  unWrap(): ReturnType<typeof AstParser.prototype.parse>;
1973
1994
  }
1974
1995
 
1996
+ type InsertConflictMode = "update" | "ignore";
1997
+ type InsertConflictConfig = {
1998
+ conflictColumns: string[];
1999
+ mode: InsertConflictMode;
2000
+ columnsToUpdate: string[];
2001
+ /** Raw conflict target, e.g. `(lower(email)) where deleted_at is null`. */
2002
+ conflictTargetRaw?: string;
2003
+ /** Named unique constraint to conflict on. */
2004
+ conflictConstraint?: string;
2005
+ /** Builds the `WHERE` of a `do update` clause. */
2006
+ mergeWhere?: (qb: WhereOnlyQueryBuilder<any>) => void;
2007
+ };
2008
+ /**
2009
+ * @description A WriteOperation for inserts that can be given a conflict action
2010
+ * (`onConflict(...).merge()` or `.ignore()`) before it is awaited.
2011
+ */
2012
+ declare class InsertWriteOperation<T, K extends string = string> extends WriteOperation<T> {
2013
+ private conflictState;
2014
+ private conflictColumns;
2015
+ private conflictTargetRaw;
2016
+ private conflictConstraint;
2017
+ private readonly commit;
2018
+ private readonly insertColumns;
2019
+ private readonly caller;
2020
+ constructor(unWrapFn: () => ReturnType<typeof AstParser.prototype.parse>, toSqlFn: () => ReturnType<typeof AstParser.prototype.parse>, toQueryFn: () => string, executor: () => Promise<T>, commit: (config: InsertConflictConfig) => void, insertColumns: readonly string[], caller: string);
2021
+ /**
2022
+ * @description Sets the conflict target: column(s), a raw expression such as an
2023
+ * index predicate, or a named constraint
2024
+ * @description With no arguments the conflict has no explicit target, which is
2025
+ * only valid with `ignore()`
2026
+ * @description Must be followed by `merge()` or `ignore()`
2027
+ */
2028
+ onConflict(): this;
2029
+ onConflict(column: K): this;
2030
+ onConflict(columns: K[]): this;
2031
+ onConflict(target: RawNode): this;
2032
+ onConflict(options: {
2033
+ constraint: string;
2034
+ }): this;
2035
+ /**
2036
+ * @description Updates the inserted columns when the conflict target already exists
2037
+ * @description Without arguments every inserted column except the conflict target is updated
2038
+ * @description Pass `{ where }` to guard the update, PostgreSQL and SQLite only
2039
+ * @throws HysteriaError if nothing is left to update, use `ignore()` instead
2040
+ */
2041
+ merge(): this;
2042
+ merge(column: K): this;
2043
+ merge(columns: K[]): this;
2044
+ merge(options: {
2045
+ columns?: K[];
2046
+ where?: (qb: WhereOnlyQueryBuilder<any>) => void;
2047
+ }): this;
2048
+ /**
2049
+ * @description Leaves the existing row untouched when the conflict target already exists
2050
+ * @description Works with or without an explicit conflict target
2051
+ */
2052
+ ignore(): this;
2053
+ private requireConflictTarget;
2054
+ private commitConflict;
2055
+ }
2056
+
1975
2057
  type TransactionIsolationLevel = "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
1976
2058
  type StartTransactionOptions = {
1977
2059
  isolationLevel?: TransactionIsolationLevel;
@@ -2052,6 +2134,8 @@ declare class Transaction {
2052
2134
  rollback(options?: TransactionExecutionOptions): Promise<void>;
2053
2135
  /**
2054
2136
  * @description Release the connection, does nothing if the connection is already released
2137
+ * @param failure The COMMIT/ROLLBACK error, forwarded to the adapter so it can
2138
+ * discard the connection instead of returning an unknown-state session to the pool
2055
2139
  */
2056
2140
  private releaseConnection;
2057
2141
  private getIsolationLevelQuery;
@@ -2076,6 +2160,21 @@ type ModelDataProperties = Pick<Model, ExcludeMethods<Model>>;
2076
2160
  * Includes only data columns from the model, excluding foreign keys and relation accessors.
2077
2161
  */
2078
2162
  type ModelWithoutRelations<T extends Model> = Pick<Omit<T, "*">, ExcludeRelations<Omit<T, "*">>> & ModelDataProperties;
2163
+ /**
2164
+ * A JSON mutation helper writes a path rather than a value, so it is accepted only
2165
+ * where the column is JSON: `unknown` from an untyped `col.json()`, or an object
2166
+ * type from a structured `col.jsonb<T>()`.
2167
+ */
2168
+ type JsonMutationFor<V> = [unknown] extends [NonNullable<V>] ? JsonMutationNode : [NonNullable<V>] extends [object] ? JsonMutationNode : never;
2169
+ /**
2170
+ * Values accepted by a model insert or update: the column's own type, or an
2171
+ * expression node such as `sql.rawStatement("LOWER(email)")`. The JSON mutation
2172
+ * helpers (`sql.jsonSet`, `sql.jsonInsert`, `sql.jsonRemove`) are limited to JSON
2173
+ * columns, since they emit a path write rather than a value.
2174
+ */
2175
+ type ModelWriteData<T extends Model> = {
2176
+ [K in keyof ModelWithoutRelations<T>]?: ModelWithoutRelations<T>[K] | RawNode | SqlFuncNode | JsonMutationFor<ModelWithoutRelations<T>[K]>;
2177
+ };
2079
2178
  /**
2080
2179
  * Return type for Model query/mutation methods.
2081
2180
  * Represents data-only properties without any business logic.
@@ -2141,6 +2240,10 @@ type RawModelOptions = {
2141
2240
  * Alias for the table
2142
2241
  */
2143
2242
  alias?: string;
2243
+ /**
2244
+ * @description PostgreSQL only. Renders `from only <table>`, skipping rows of tables that inherit from it
2245
+ */
2246
+ only?: boolean;
2144
2247
  /**
2145
2248
  * @description Convert the column casing before making a Database query, by default preserves what is provided
2146
2249
  */
@@ -2197,17 +2300,25 @@ declare class ModelManager<T extends Model> {
2197
2300
  * @throws {HysteriaError} if the model has no primary key
2198
2301
  */
2199
2302
  findOneByPrimaryKey(value: string | number, returning?: ModelKey<T>[]): Promise<ModelWithoutRelations<T> | null>;
2303
+ /**
2304
+ * @description Places the CTEs ahead of the insert, except on MySQL/MariaDB which only
2305
+ * accept them inline after the column list (rendered by the insert interpreter).
2306
+ */
2307
+ private withInsertNodes;
2200
2308
  /**
2201
2309
  * @description Creates a new record in the database
2202
2310
  * @returns WriteOperation that executes when awaited
2203
2311
  */
2204
- insert(model: Partial<T>, options?: InsertOptions<T>): WriteOperation<ModelWithoutRelations<T>>;
2312
+ insert(model: ModelWriteData<T>, options?: InsertOptions<T>): InsertWriteOperation<ModelWithoutRelations<T>>;
2205
2313
  /**
2206
2314
  * @description Creates multiple records in the database
2207
2315
  * @returns WriteOperation that executes when awaited
2208
2316
  */
2209
- insertMany(models: Partial<T>[], options?: InsertOptions<T>): WriteOperation<ModelWithoutRelations<T>[]>;
2317
+ insertMany(models: ModelWriteData<T>[], options?: InsertOptions<T>): InsertWriteOperation<ModelWithoutRelations<T>[]>;
2318
+ private insertManyInternal;
2210
2319
  upsertMany(conflictColumns: string[], columnsToUpdate: string[], data: ModelWithoutRelations<T>[], options?: UpsertOptions<T>): WriteOperation<ModelWithoutRelations<T>[]>;
2320
+ private executeInsertConflict;
2321
+ private refetchByConflictColumn;
2211
2322
  /**
2212
2323
  * @description Executes a MERGE statement for MSSQL upsert operations
2213
2324
  */
@@ -2235,7 +2346,36 @@ declare class ModelManager<T extends Model> {
2235
2346
  */
2236
2347
  private handleMysqlInsert;
2237
2348
  private handleWhereCondition;
2238
- private applyFieldCondition;
2349
+ }
2350
+
2351
+ declare class JoinNode extends QueryNode {
2352
+ table: string;
2353
+ left: string;
2354
+ right: string;
2355
+ on?: {
2356
+ left?: string;
2357
+ right?: string;
2358
+ operator: string;
2359
+ };
2360
+ chainsWith: string;
2361
+ canKeywordBeSeenMultipleTimes: boolean;
2362
+ folder: string;
2363
+ file: string;
2364
+ type: "inner" | "left" | "right" | "full" | "cross" | "natural";
2365
+ additionalConditions?: (WhereNode | WhereGroupNode | WhereSubqueryNode)[];
2366
+ /** When set, renders `using (cols)` instead of an `on` condition. */
2367
+ using?: string[];
2368
+ /** Schema applied to the joined table reference. */
2369
+ schema?: string;
2370
+ /** Values for the `?` placeholders of a raw join fragment. */
2371
+ bindings?: any[];
2372
+ /** When set, `table` holds the derived table's alias and this holds its body. */
2373
+ subquery?: QueryNode[];
2374
+ constructor(table: string, left: string, right: string, type: "inner" | "left" | "right" | "full" | "cross" | "natural" | undefined, on: {
2375
+ left?: string;
2376
+ right?: string;
2377
+ operator: string;
2378
+ }, isRawValue?: boolean, additionalConditions?: (WhereNode | WhereGroupNode | WhereSubqueryNode)[]);
2239
2379
  }
2240
2380
 
2241
2381
  declare class DeleteNode extends QueryNode {
@@ -2244,6 +2384,10 @@ declare class DeleteNode extends QueryNode {
2244
2384
  canKeywordBeSeenMultipleTimes: boolean;
2245
2385
  folder: string;
2246
2386
  file: string;
2387
+ /** Joins rendered after the table, so MySQL can delete from a join. */
2388
+ joinNodes?: JoinNode[];
2389
+ /** `delete ... using <source>`, rendered by the dialects that accept it. */
2390
+ usingNode?: FromNode;
2247
2391
  constructor(fromNode: FromNode, isRawValue?: boolean);
2248
2392
  }
2249
2393
 
@@ -2290,16 +2434,28 @@ type TableForeignKeyInfo = {
2290
2434
  onUpdate?: string | null;
2291
2435
  };
2292
2436
 
2437
+ type InsertNodeOptions = {
2438
+ withNodes?: WithNode[];
2439
+ source?: QueryNode[];
2440
+ targetColumns?: string[];
2441
+ ignoreInto?: boolean;
2442
+ disambiguateSource?: boolean;
2443
+ };
2293
2444
  declare class InsertNode extends QueryNode {
2294
2445
  fromNode: FromNode;
2295
2446
  records: Record<string, any>[];
2296
2447
  returning?: string[];
2297
2448
  disableReturning: boolean;
2449
+ withNodes?: WithNode[];
2450
+ source?: QueryNode[];
2451
+ targetColumns?: string[];
2452
+ ignoreInto: boolean;
2453
+ disambiguateSource: boolean;
2298
2454
  chainsWith: string;
2299
2455
  canKeywordBeSeenMultipleTimes: boolean;
2300
2456
  folder: string;
2301
2457
  file: string;
2302
- constructor(fromNode: FromNode, records?: Record<string, any>[], returning?: string[], disableReturning?: boolean, isRawValue?: boolean);
2458
+ constructor(fromNode: FromNode, records?: Record<string, any>[], returning?: string[], disableReturning?: boolean, isRawValue?: boolean, options?: InsertNodeOptions);
2303
2459
  }
2304
2460
 
2305
2461
  declare class OnDuplicateNode extends QueryNode {
@@ -2312,6 +2468,12 @@ declare class OnDuplicateNode extends QueryNode {
2312
2468
  canKeywordBeSeenMultipleTimes: boolean;
2313
2469
  folder: string;
2314
2470
  file: string;
2471
+ /** Raw conflict target, rendered in place of the column list. */
2472
+ conflictTargetRaw?: string;
2473
+ /** Named unique constraint to conflict on. */
2474
+ conflictConstraint?: string;
2475
+ /** Guards the `do update` clause; PostgreSQL and SQLite only. */
2476
+ whereNodes?: (WhereNode | WhereGroupNode)[];
2315
2477
  constructor(table: string, conflictColumns: string[], columnsToUpdate: string[], mode?: "update" | "ignore", returning?: string[], isRawValue?: boolean);
2316
2478
  }
2317
2479
 
@@ -2333,13 +2495,19 @@ declare class ReturningNode extends QueryNode {
2333
2495
 
2334
2496
  type UnionCallBack<T extends Model> = (queryBuilder: QueryBuilder<T>) => QueryBuilder<T>;
2335
2497
 
2498
+ type TruncateOptions = {
2499
+ cascade?: boolean;
2500
+ restartIdentity?: boolean;
2501
+ continueIdentity?: boolean;
2502
+ };
2336
2503
  declare class TruncateNode extends QueryNode {
2337
2504
  fromNode: FromNode | string;
2505
+ options?: TruncateOptions;
2338
2506
  chainsWith: string;
2339
2507
  canKeywordBeSeenMultipleTimes: boolean;
2340
2508
  folder: string;
2341
2509
  file: string;
2342
- constructor(fromNode: FromNode | string, isRawValue?: boolean);
2510
+ constructor(fromNode: FromNode | string, isRawValue?: boolean, options?: TruncateOptions);
2343
2511
  }
2344
2512
 
2345
2513
  declare class UpdateNode extends QueryNode {
@@ -2350,9 +2518,51 @@ declare class UpdateNode extends QueryNode {
2350
2518
  canKeywordBeSeenMultipleTimes: boolean;
2351
2519
  folder: string;
2352
2520
  file: string;
2521
+ /** Joins rendered between the table and SET, so MySQL can update from a join. */
2522
+ joinNodes?: JoinNode[];
2523
+ /** `update ... from <source>`, rendered by the dialects that accept it. */
2524
+ fromSourceNode?: FromNode;
2353
2525
  constructor(fromNode: FromNode, columns?: string[], values?: (any | RawNode | SqlFuncNode)[], isRawValue?: boolean);
2354
2526
  }
2355
2527
 
2528
+ type Operation = "SELECT" | "INSERT" | "UPDATE" | "DELETE" | "OTHER";
2529
+ interface QueryContext {
2530
+ id: string;
2531
+ sql: string;
2532
+ params: any[];
2533
+ model?: any;
2534
+ operation?: string;
2535
+ timestamp: number;
2536
+ /** Anything else attached by the caller through `.queryContext()` */
2537
+ [key: string]: any;
2538
+ }
2539
+ /**
2540
+ * Query context extended with execution metadata.
2541
+ * @property duration - Query execution time in milliseconds (ms)
2542
+ */
2543
+ type QueryContextWithDuration = QueryContext & {
2544
+ duration: number;
2545
+ result?: any;
2546
+ };
2547
+ interface QueryObserver {
2548
+ onBeforeQuery?(ctx: QueryContext): Promise<void> | void;
2549
+ onAfterQuery?(ctx: QueryContextWithDuration): Promise<void> | void;
2550
+ onQueryError?(ctx: QueryContext & {
2551
+ error: Error;
2552
+ }): Promise<void> | void;
2553
+ }
2554
+ declare class ObserverChain {
2555
+ private observers;
2556
+ constructor(observers?: QueryObserver[]);
2557
+ add(observer: QueryObserver): void;
2558
+ notifyBefore(ctx: QueryContext): Promise<void>;
2559
+ notifyAfter(ctx: QueryContextWithDuration, result?: any): Promise<void>;
2560
+ notifyError(ctx: QueryContext & {
2561
+ error: Error;
2562
+ }): Promise<void>;
2563
+ }
2564
+ declare const deriveOperationFromQuery: (sql: string) => string;
2565
+
2356
2566
  /**
2357
2567
  * PostgreSQL / CockroachDB: `-- line` or `/* block *\/`.
2358
2568
  */
@@ -2907,6 +3117,12 @@ type SoftDeleteOptions<T> = {
2907
3117
  interface SubQueryable {
2908
3118
  extractQueryNodes(): QueryNode[];
2909
3119
  }
3120
+ /**
3121
+ * @description Which otherwise-select-only clauses a write operation tolerates.
3122
+ */
3123
+ interface WriteClauseAllowances {
3124
+ allowCte?: boolean;
3125
+ }
2910
3126
  declare class QueryBuilder<T extends Model = any, S extends Record<string, any> = Record<string, any>, D extends SqlDataSourceType = SqlDataSourceType> extends JsonQueryBuilder<T, S> implements SubQueryable {
2911
3127
  model: typeof Model;
2912
3128
  protected astParser: AstParser;
@@ -2919,9 +3135,13 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
2919
3135
  protected _interpreterUtils: InterpreterUtils | null;
2920
3136
  protected get interpreterUtils(): InterpreterUtils;
2921
3137
  protected insertNode: InsertNode | null;
3138
+ protected insertNodeSource: QueryNode[] | undefined;
2922
3139
  protected onDuplicateNode: OnDuplicateNode | null;
3140
+ protected insertConflictConfig: InsertConflictConfig | null;
2923
3141
  protected updateNode: UpdateNode | null;
3142
+ protected updateFromNode: FromNode | null;
2924
3143
  protected deleteNode: DeleteNode | null;
3144
+ protected deleteUsingNode: FromNode | null;
2925
3145
  protected returningNode: ReturningNode | null;
2926
3146
  protected truncateNode: TruncateNode | null;
2927
3147
  protected replicationMode: ReplicationType | null;
@@ -2930,6 +3150,8 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
2930
3150
  ms: number;
2931
3151
  cancel: boolean;
2932
3152
  };
3153
+ protected queryContextOptions?: Partial<QueryContext>;
3154
+ protected shouldLogQuery?: boolean;
2933
3155
  constructor(model: typeof Model, sqlDataSource: SqlDataSource);
2934
3156
  /**
2935
3157
  * @description Sets the replication mode for the query builder
@@ -3039,6 +3261,11 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3039
3261
  * @param key - The column to retrieve from the results, must be a Model Column
3040
3262
  */
3041
3263
  pluck<K extends RawModelKey<T>>(key: K): Promise<PluckReturnType<T, K>>;
3264
+ /**
3265
+ * @description Executes the query and retrieves a single column from the first result, or undefined when there is none.
3266
+ * @param key - A selected column, or any Model column when the query selects everything
3267
+ */
3268
+ value<K extends ValueKey<T, S>>(key: K): Promise<PluckReturnType<T, K & RawModelKey<T>>[number] | undefined>;
3042
3269
  /**
3043
3270
  * @description Executes the query and retrieves a single result.
3044
3271
  */
@@ -3143,6 +3370,16 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3143
3370
  timeout(ms: number, options?: {
3144
3371
  cancel?: boolean;
3145
3372
  }): this;
3373
+ /**
3374
+ * @description Attaches extra fields to the query context handed to observers.
3375
+ * `sql`, `params`, `id`, `operation` and `timestamp` are always filled in by the runner.
3376
+ */
3377
+ queryContext(ctx: Partial<QueryContext>): this;
3378
+ /**
3379
+ * @description Logs this query regardless of the data source setting, or silences it
3380
+ * with `false`. Without an argument it turns logging on.
3381
+ */
3382
+ debug(enable?: boolean): this;
3146
3383
  /**
3147
3384
  * @description Prepends a native SQL comment to the select statement, in the
3148
3385
  * syntax of the active dialect (e.g. `-- line`, `/* block *\/`; MySQL adds
@@ -3174,27 +3411,32 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3174
3411
  * because the driver reads it as a bind placeholder even inside a comment.
3175
3412
  */
3176
3413
  private assertValidSqlComment;
3414
+ private resolveSetOperationOptions;
3177
3415
  /**
3178
3416
  * @description Adds a UNION to the query.
3417
+ * @param options.wrap - Wraps the branch in parentheses
3179
3418
  */
3180
- union(query: string, bindings?: any[]): this;
3181
- union(cb: UnionCallBack<T>): this;
3419
+ union(query: string, bindings?: any[], options?: SetOperationOptions): this;
3420
+ union(cb: UnionCallBack<T>, options?: SetOperationOptions): this;
3182
3421
  /**
3183
3422
  * @description Adds a UNION ALL to the query.
3423
+ * @param options.wrap - Wraps the branch in parentheses
3184
3424
  */
3185
- unionAll(query: string, bindings?: any[]): this;
3186
- unionAll(cb: UnionCallBack<T>): this;
3187
- unionAll(queryBuilder: QueryBuilder<any>): this;
3425
+ unionAll(query: string, bindings?: any[], options?: SetOperationOptions): this;
3426
+ unionAll(cb: UnionCallBack<T>, options?: SetOperationOptions): this;
3427
+ unionAll(queryBuilder: QueryBuilder<any>, options?: SetOperationOptions): this;
3188
3428
  /**
3189
3429
  * @description Adds an INTERSECT to the query (keeps only rows present in both queries).
3430
+ * @param options.wrap - Wraps the branch in parentheses
3190
3431
  */
3191
- intersect(query: string): this;
3192
- intersect(cb: UnionCallBack<T>): this;
3432
+ intersect(query: string, bindings?: any[], options?: SetOperationOptions): this;
3433
+ intersect(cb: UnionCallBack<T>, options?: SetOperationOptions): this;
3193
3434
  /**
3194
3435
  * @description Adds an EXCEPT to the query (keeps rows from the first query not present in the second).
3436
+ * @param options.wrap - Wraps the branch in parentheses
3195
3437
  */
3196
- except(query: string): this;
3197
- except(cb: UnionCallBack<T>): this;
3438
+ except(query: string, bindings?: any[], options?: SetOperationOptions): this;
3439
+ except(cb: UnionCallBack<T>, options?: SetOperationOptions): this;
3198
3440
  private resolveSetOperationNodes;
3199
3441
  /**
3200
3442
  * @description Increments the value of a column by a given amount
@@ -3273,10 +3515,17 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3273
3515
  * rewritten to the dialect's placeholders, in order with the rest of the query.
3274
3516
  */
3275
3517
  fromRaw(raw: string, bindings?: any[]): this;
3518
+ /**
3519
+ * @description Renders the FROM clause as `from only <table>`, skipping rows of
3520
+ * tables that inherit from it. PostgreSQL only.
3521
+ */
3522
+ fromOnly(enable?: boolean): this;
3276
3523
  /**
3277
3524
  * @description Adds a CTE to the query using a callback to build the subquery.
3525
+ * @param columns - Optional explicit column list for the CTE (`with t (a, b) as (...)`)
3278
3526
  */
3279
3527
  with(alias: string, cb: (qb: QueryBuilder<T>) => void | SubQueryable): this;
3528
+ with(alias: string, columns: string[], cb: (qb: QueryBuilder<T>) => void | SubQueryable): this;
3280
3529
  /**
3281
3530
  * @description Adds a recursive CTE to the query using a callback to build the subquery.
3282
3531
  * @mssql not supported
@@ -3284,14 +3533,14 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3284
3533
  withRecursive(alias: string, cb: (qb: QueryBuilder<T>) => void | SubQueryable): this;
3285
3534
  /**
3286
3535
  * @description Adds a materialized CTE to the query using a callback to build the subquery.
3287
- * @postgres only
3288
- * @throws HysteriaError if the database type is not postgres or cockroachdb
3536
+ * @postgres/cockroachdb/sqlite only
3537
+ * @throws HysteriaError if the dialect has no `as materialized`
3289
3538
  */
3290
3539
  withMaterialized(alias: string, cb: (qb: QueryBuilder<T>) => void | SubQueryable): this;
3291
3540
  /**
3292
3541
  * @description Adds a non-materialized CTE to the query using a callback to build the subquery.
3293
- * @postgres only
3294
- * @throws HysteriaError if the database type is not postgres or cockroachdb
3542
+ * @postgres/cockroachdb only
3543
+ * @throws HysteriaError if the dialect has no `as not materialized`
3295
3544
  */
3296
3545
  withNotMaterialized(alias: string, cb: (qb: QueryBuilder<T>) => void | SubQueryable): this;
3297
3546
  /**
@@ -3299,15 +3548,27 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3299
3548
  * @param returning - The columns to return from the query, only supported by postgres and cockroachdb - default is "*"
3300
3549
  * @returns WriteOperation that executes when awaited
3301
3550
  */
3302
- insert(data: Record<string, WriteQueryParam>, returning: string[]): WriteOperation<T>;
3303
- insert(data: Record<string, WriteQueryParam>): WriteOperation<void>;
3551
+ insert(data: Record<string, WriteQueryParam>, returning: string[]): InsertWriteOperation<T>;
3552
+ insert(data: Record<string, WriteQueryParam>): InsertWriteOperation<void>;
3304
3553
  /**
3305
3554
  * @description Insert multiple records into a table
3306
3555
  * @param returning - The columns to return from the query, only supported by postgres and cockroachdb - default is "*"
3307
3556
  * @returns WriteOperation that executes when awaited
3308
3557
  */
3309
- insertMany(data: Record<string, WriteQueryParam>[], returning: string[]): WriteOperation<T[]>;
3310
- insertMany(data: Record<string, WriteQueryParam>[]): WriteOperation<void>;
3558
+ insertMany(data: Record<string, WriteQueryParam>[], returning: string[]): InsertWriteOperation<T[]>;
3559
+ insertMany(data: Record<string, WriteQueryParam>[]): InsertWriteOperation<void>;
3560
+ /**
3561
+ * @description Inserts rows in chunks of `chunkSize`, one statement per chunk, for
3562
+ * when a single `insertMany` would exceed the driver's parameter limit
3563
+ * @description The chunks are not wrapped in a transaction; wrap the call in
3564
+ * `sql.transaction(...)` when the whole batch has to be atomic
3565
+ * @returns The rows read back per chunk, empty without `returning`
3566
+ */
3567
+ batchInsert(data: Record<string, WriteQueryParam>[], options?: {
3568
+ chunkSize?: number;
3569
+ returning?: string[];
3570
+ }): Promise<T[]>;
3571
+ protected resolveBatchSize(chunkSize?: number): number;
3311
3572
  /**
3312
3573
  * @description Updates or creates a new record using upsert functionality
3313
3574
  * @param data The data to insert or update
@@ -3325,18 +3586,52 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3325
3586
  * @returns WriteOperation that executes when awaited
3326
3587
  */
3327
3588
  upsertMany<O extends Record<string, any>>(conflictColumns: string[], columnsToUpdate: string[], data: O[], options?: UpsertOptionsRawBuilder): WriteOperation<T[]>;
3589
+ private buildRawUpsert;
3590
+ private buildInsertConflictCommit;
3591
+ /**
3592
+ * @description Inserts the rows produced by a SELECT (or a CTE feeding one) into the table.
3593
+ * @param targetColumns - Optional destination column list; positional when omitted
3594
+ * @param source - A builder (or callback) whose SELECT becomes the insert source
3595
+ * @returns InsertWriteOperation, so `onConflict(...).merge()/.ignore()` chains onto it
3596
+ * @warning Rows come from the database, so no validation, hooks or autoCreate columns run
3597
+ */
3598
+ insertFrom(source: QueryBuilder<any> | ((qb: QueryBuilder<any>) => QueryBuilder<any> | void)): InsertWriteOperation<T[]>;
3599
+ insertFrom<C extends string>(targetColumns: C[], source: QueryBuilder<any> | ((qb: QueryBuilder<any>) => QueryBuilder<any> | void)): InsertWriteOperation<T[]>;
3600
+ protected buildInsertFrom(sourceNodes: QueryNode[], targetColumns?: string[]): InsertWriteOperation<T[]>;
3328
3601
  /**
3329
3602
  * @description Executes a MERGE statement for MSSQL upsert operations (raw query builder)
3330
3603
  */
3331
3604
  private executeMssqlMergeRaw;
3605
+ /**
3606
+ * @description Sets the source of an `update ... from <table>` statement, so the
3607
+ * update can read from another table. Pass a table name, or a callback to build a
3608
+ * subquery with its alias.
3609
+ * @postgres/cockroachdb/mssql only
3610
+ */
3611
+ updateFrom<X extends string>(table: TableFormat<X>, maybeAlias?: string): this;
3612
+ updateFrom(cb: (qb: QueryBuilder<T>) => void | SubQueryable, alias: string): this;
3613
+ /**
3614
+ * @description Sets the source of a `delete ... using <table>` statement, so the
3615
+ * delete can match rows against another table.
3616
+ * @postgres/cockroachdb only
3617
+ */
3618
+ deleteUsing<X extends string>(table: TableFormat<X>, maybeAlias?: string): this;
3619
+ deleteUsing(cb: (qb: QueryBuilder<T>) => void | SubQueryable, alias: string): this;
3620
+ /**
3621
+ * @description Builds a from node outside of the main FROM slot, for the auxiliary
3622
+ * sources a write statement can take (`update ... from`, `delete ... using`).
3623
+ */
3624
+ private buildFromSource;
3332
3625
  /**
3333
3626
  * @description Updates records from a table, you can use raw statements in the data object for literal references to other columns
3334
- * @param data - Object with column-value pairs to update
3627
+ * @param data - Object with column-value pairs to update, or a single column name
3628
+ * @param value - The value when updating a single column
3335
3629
  * @param returning - Optional array of column names to return from the updated rows.
3336
3630
  * **Note:** The `returning` parameter is only supported on PostgreSQL, CockroachDB, SQLite, and MSSQL.
3337
3631
  * For MySQL and MariaDB, do not pass `returning` — the method will return the number of affected rows instead.
3338
3632
  * @returns WriteOperation that resolves to the number of affected rows, or the specified columns if `returning` is provided
3339
3633
  */
3634
+ update(column: string, value: WriteQueryParam, returning?: string[]): WriteOperation<any>;
3340
3635
  update(data: Record<string, WriteQueryParam>, returning?: string[]): WriteOperation<any>;
3341
3636
  /**
3342
3637
  * @description Builds a returning clause for update/delete where the dialect has one.
@@ -3347,10 +3642,11 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3347
3642
  protected withReturningNode<N>(nodes: N[]): (N | ReturningNode)[];
3348
3643
  /**
3349
3644
  * @description Deletes all records from a table
3645
+ * @param options - `RESTART IDENTITY` / `CONTINUE IDENTITY` / `CASCADE` (PostgreSQL and CockroachDB only)
3350
3646
  * @warning This operation does not trigger any hook
3351
3647
  * @returns WriteOperation that executes when awaited
3352
3648
  */
3353
- truncate(): WriteOperation<void>;
3649
+ truncate(options?: TruncateOptions): WriteOperation<void>;
3354
3650
  /**
3355
3651
  * @description Deletes records from a table
3356
3652
  * @param returning - Optional array of column names to return from the deleted rows.
@@ -3406,6 +3702,16 @@ declare class QueryBuilder<T extends Model = any, S extends Record<string, any>
3406
3702
  * @description Removes any with query
3407
3703
  */
3408
3704
  clearWithQuery(): this;
3705
+ /**
3706
+ * @description Rejects clause state that would otherwise be silently dropped on a
3707
+ * write. Thrown at call time so the failure points at the builder call.
3708
+ */
3709
+ protected assertWriteClausesSupported(method: string, { allowCte }?: WriteClauseAllowances): void;
3710
+ /**
3711
+ * @description Single source of truth for a write statement's node list. Preview
3712
+ * (`extractQueryNodes`) and execution both go through it so they cannot diverge.
3713
+ */
3714
+ protected extractWriteNodes(): QueryNode[];
3409
3715
  extractQueryNodes(): QueryNode[];
3410
3716
  protected clearForFunctions(): this;
3411
3717
  /**
@@ -3440,42 +3746,6 @@ type SqlLiteOptions<T extends Model> = {
3440
3746
  customConnection?: GetConnectionReturnType<"sqlite">;
3441
3747
  };
3442
3748
 
3443
- type Operation = "SELECT" | "INSERT" | "UPDATE" | "DELETE" | "OTHER";
3444
- interface QueryContext {
3445
- id: string;
3446
- sql: string;
3447
- params: any[];
3448
- model?: any;
3449
- operation?: string;
3450
- timestamp: number;
3451
- }
3452
- /**
3453
- * Query context extended with execution metadata.
3454
- * @property duration - Query execution time in milliseconds (ms)
3455
- */
3456
- type QueryContextWithDuration = QueryContext & {
3457
- duration: number;
3458
- result?: any;
3459
- };
3460
- interface QueryObserver {
3461
- onBeforeQuery?(ctx: QueryContext): Promise<void> | void;
3462
- onAfterQuery?(ctx: QueryContextWithDuration): Promise<void> | void;
3463
- onQueryError?(ctx: QueryContext & {
3464
- error: Error;
3465
- }): Promise<void> | void;
3466
- }
3467
- declare class ObserverChain {
3468
- private observers;
3469
- constructor(observers?: QueryObserver[]);
3470
- add(observer: QueryObserver): void;
3471
- notifyBefore(ctx: QueryContext): Promise<void>;
3472
- notifyAfter(ctx: QueryContextWithDuration, result?: any): Promise<void>;
3473
- notifyError(ctx: QueryContext & {
3474
- error: Error;
3475
- }): Promise<void>;
3476
- }
3477
- declare const deriveOperationFromQuery: (sql: string) => string;
3478
-
3479
3749
  declare const SQL_DATA_SOURCE_SYMBOL: unique symbol;
3480
3750
  /**
3481
3751
  * @description The SqlDataSource class is the main class for interacting with the database, it's used to create connections, execute queries, and manage transactions
@@ -3632,6 +3902,19 @@ declare class SqlDataSource<D extends SqlDataSourceType = SqlDataSourceType, T e
3632
3902
  private onSlaveServerFailure?;
3633
3903
  private lazyLoad;
3634
3904
  private connecting;
3905
+ /**
3906
+ * @description Clones made from this instance. Used to notice a manual
3907
+ * transaction that is still holding one of their connections, so cache writes
3908
+ * raised on the original can be recognised as happening inside a transaction.
3909
+ */
3910
+ private cloneRegistry;
3911
+ /**
3912
+ * @description Set on a clone to the instance it came from, so it can take itself
3913
+ * out of that instance's clone registry when it disconnects. Clones are short-lived
3914
+ * and a registry that only pruned itself on cache use would retain every clone a
3915
+ * caller that never caches had ever made.
3916
+ */
3917
+ private clonedFrom;
3635
3918
  /**
3636
3919
  * @description Returns the configured slave failure callback
3637
3920
  */
@@ -3696,6 +3979,16 @@ declare class SqlDataSource<D extends SqlDataSourceType = SqlDataSourceType, T e
3696
3979
  * ```
3697
3980
  */
3698
3981
  connect(): Promise<void>;
3982
+ /**
3983
+ * @description Builds the pool. Shared by `connect()` and `ensureConnected()` so both
3984
+ * go through the same in-flight promise rather than racing each other.
3985
+ */
3986
+ private openConnection;
3987
+ /**
3988
+ * @description Closes this instance's pool if there is one, without letting a hang or a
3989
+ * driver error mask the failure that is already in flight.
3990
+ */
3991
+ private closePoolOnFailure;
3699
3992
  /**
3700
3993
  * @description Returns true if the connection is established
3701
3994
  */
@@ -3716,6 +4009,8 @@ declare class SqlDataSource<D extends SqlDataSourceType = SqlDataSourceType, T e
3716
4009
  get models(): ModelsProxy<T, D>;
3717
4010
  /**
3718
4011
  * @description Selects a slave from the pool using the configured algorithm
4012
+ * @description Returns null for a data source holding a pinned connection, such
4013
+ * as a transaction clone, which has to read through that connection.
3719
4014
  * @returns A slave SqlDataSource instance or null if no slaves are available
3720
4015
  */
3721
4016
  getSlave(): SqlDataSource<D, T, C, E> | null;
@@ -3724,8 +4019,18 @@ declare class SqlDataSource<D extends SqlDataSourceType = SqlDataSourceType, T e
3724
4019
  * respecting (in order): explicit global transaction, ALS transaction, then self.
3725
4020
  */
3726
4021
  getTransactionBoundSqlDataSource(): SqlDataSource | null;
4022
+ /**
4023
+ * @description True while this instance has a transaction in flight: the ALS or
4024
+ * global transaction bound to it, or a manual transaction still holding a
4025
+ * connection on one of its clones.
4026
+ */
4027
+ private hasOpenTransaction;
3727
4028
  /**
3728
4029
  * @description Uses the cache adapter to get a value from the cache
4030
+ * @description A miss inside a transaction is not written back: the value was
4031
+ * computed from that transaction's view of the data, which may include rows it
4032
+ * has not committed, so it does not belong in a cache shared with everyone else.
4033
+ * Reads still hit the cache, so a value cached before the transaction is served.
3729
4034
  * @param key The key to get the value from
3730
4035
  * @param args The arguments to pass to the key handler
3731
4036
  */
@@ -3834,9 +4139,10 @@ declare class SqlDataSource<D extends SqlDataSourceType = SqlDataSourceType, T e
3834
4139
  * @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
3835
4140
  * @param options.isolationLevel The isolation level to use for the transaction
3836
4141
  * @sqlite ignores the isolation level
3837
- * @warning SQLite `:memory:` databases use `file::memory:?cache=shared`
3838
- * to allow transaction connections to share the same in-memory database.
3839
- * Without shared cache each connection would see an empty fresh database.
4142
+ * @warning A SQLite `:memory:` database is private to its connection, and a
4143
+ * transaction runs on its own, so it sees an empty database rather than the
4144
+ * tables created on the main connection. Pass `file::memory:?cache=shared`, or
4145
+ * use a file database, when transactions need to read that data.
3840
4146
  */
3841
4147
  transaction(options?: StartTransactionOptions): Promise<Transaction>;
3842
4148
  transaction<T>(cb: (trx: Transaction) => Promise<T>, options?: StartTransactionOptions): Promise<T>;
@@ -4111,32 +4417,6 @@ declare class SelectNode extends QueryNode {
4111
4417
  constructor(column: string | QueryNode | QueryNode[], alias?: string, sqlFunction?: string, isRaw?: boolean, distinct?: boolean);
4112
4418
  }
4113
4419
 
4114
- declare class JoinNode extends QueryNode {
4115
- table: string;
4116
- left: string;
4117
- right: string;
4118
- on?: {
4119
- left?: string;
4120
- right?: string;
4121
- operator: string;
4122
- };
4123
- chainsWith: string;
4124
- canKeywordBeSeenMultipleTimes: boolean;
4125
- folder: string;
4126
- file: string;
4127
- type: "inner" | "left" | "right" | "full" | "cross" | "natural";
4128
- additionalConditions?: (WhereNode | WhereGroupNode | WhereSubqueryNode)[];
4129
- /** When set, renders `using (cols)` instead of an `on` condition. */
4130
- using?: string[];
4131
- /** Schema applied to the joined table reference. */
4132
- schema?: string;
4133
- constructor(table: string, left: string, right: string, type: "inner" | "left" | "right" | "full" | "cross" | "natural" | undefined, on: {
4134
- left?: string;
4135
- right?: string;
4136
- operator: string;
4137
- }, isRawValue?: boolean, additionalConditions?: (WhereNode | WhereGroupNode | WhereSubqueryNode)[]);
4138
- }
4139
-
4140
4420
  declare class GroupByNode extends QueryNode {
4141
4421
  column: string;
4142
4422
  chainsWith: string;
@@ -4148,6 +4428,8 @@ declare class GroupByNode extends QueryNode {
4148
4428
 
4149
4429
  declare class LimitNode extends QueryNode {
4150
4430
  limit: number;
4431
+ /** Inlines the value instead of binding it, so later parameter indexes do not shift. */
4432
+ skipBinding?: boolean;
4151
4433
  chainsWith: string;
4152
4434
  canKeywordBeSeenMultipleTimes: boolean;
4153
4435
  folder: string;
@@ -4157,6 +4439,8 @@ declare class LimitNode extends QueryNode {
4157
4439
 
4158
4440
  declare class OffsetNode extends QueryNode {
4159
4441
  offset: number;
4442
+ /** Inlines the value instead of binding it, so later parameter indexes do not shift. */
4443
+ skipBinding?: boolean;
4160
4444
  chainsWith: string;
4161
4445
  canKeywordBeSeenMultipleTimes: boolean;
4162
4446
  folder: string;
@@ -4167,6 +4451,8 @@ declare class OffsetNode extends QueryNode {
4167
4451
  declare class OrderByNode extends QueryNode {
4168
4452
  column: string;
4169
4453
  direction: "asc" | "desc";
4454
+ /** Explicit null placement, emulated by the dialects that cannot spell it out. */
4455
+ nulls?: "first" | "last";
4170
4456
  chainsWith: string;
4171
4457
  canKeywordBeSeenMultipleTimes: boolean;
4172
4458
  folder: string;
@@ -4520,27 +4806,34 @@ declare abstract class FooterQueryBuilder<T extends Model, S extends Record<stri
4520
4806
  /**
4521
4807
  * @description Adds an order by query
4522
4808
  */
4523
- orderBy(column: ModelKey<T>, order: OrderByChoices): this;
4524
- orderBy<S extends string>(column: SelectableColumn$1<S>, order: OrderByChoices): this;
4809
+ orderBy(column: ModelKey<T>, order: OrderByClause): this;
4810
+ orderBy<S extends string>(column: SelectableColumn$1<S>, order: OrderByClause): this;
4525
4811
  /**
4526
4812
  * @description Adds a raw order by query, ORDER BY clause is not necessary and will be added automatically
4527
4813
  */
4528
4814
  orderByRaw(query: string): this;
4529
4815
  /**
4530
4816
  * @description Adds a limit query
4817
+ * @param options.skipBinding - Inlines the value in the SQL instead of binding it
4531
4818
  */
4532
- limit(limit: number): this;
4819
+ limit(limit: number, options?: {
4820
+ skipBinding?: boolean;
4821
+ }): this;
4533
4822
  /**
4534
4823
  * @description Adds an offset query
4824
+ * @param options.skipBinding - Inlines the value in the SQL instead of binding it
4535
4825
  */
4536
- offset(offset: number): this;
4826
+ offset(offset: number, options?: {
4827
+ skipBinding?: boolean;
4828
+ }): this;
4537
4829
  }
4538
4830
 
4539
4831
  declare class JoinOnQueryBuilder {
4832
+ protected model: typeof Model;
4540
4833
  protected sqlDataSource: SqlDataSource;
4541
4834
  protected whereNodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[];
4542
4835
  protected isNestedCondition: boolean;
4543
- constructor(sqlDataSource: SqlDataSource, isNestedCondition?: boolean);
4836
+ constructor(model: typeof Model, sqlDataSource: SqlDataSource, isNestedCondition?: boolean);
4544
4837
  /**
4545
4838
  * @description Get the where conditions for the join
4546
4839
  */
@@ -4578,6 +4871,34 @@ declare class JoinOnQueryBuilder {
4578
4871
  */
4579
4872
  orWhereNot(column: SelectableColumn$1<string>, operator: BinaryOperatorType$2, value: BaseValues$2): this;
4580
4873
  orWhereNot(column: SelectableColumn$1<string>, value: BaseValues$2): this;
4874
+ /**
4875
+ * @description Adds a condition comparing two columns (`on a.x = b.y`).
4876
+ * @description Both sides need the table prefix when either belongs to an aliased or derived
4877
+ * join target, since there is no model to resolve them against.
4878
+ */
4879
+ whereColumn(column: SelectableColumn$1<string>, operatorOrRef: BinaryOperatorType$2 | SelectableColumn$1<string>, referenceColumn?: SelectableColumn$1<string>): this;
4880
+ /**
4881
+ * @description Adds an AND condition comparing two columns.
4882
+ */
4883
+ andWhereColumn(column: SelectableColumn$1<string>, operatorOrRef: BinaryOperatorType$2 | SelectableColumn$1<string>, referenceColumn?: SelectableColumn$1<string>): this;
4884
+ /**
4885
+ * @description Adds an OR condition comparing two columns.
4886
+ */
4887
+ orWhereColumn(column: SelectableColumn$1<string>, operatorOrRef: BinaryOperatorType$2 | SelectableColumn$1<string>, referenceColumn?: SelectableColumn$1<string>): this;
4888
+ /**
4889
+ * @description Adds a negated condition comparing two columns (`a != b`, or `not (a op b)`
4890
+ * when an explicit operator is given).
4891
+ */
4892
+ whereNotColumn(column: SelectableColumn$1<string>, operatorOrRef: BinaryOperatorType$2 | SelectableColumn$1<string>, referenceColumn?: SelectableColumn$1<string>): this;
4893
+ /**
4894
+ * @description Adds a negated AND condition comparing two columns.
4895
+ */
4896
+ andWhereNotColumn(column: SelectableColumn$1<string>, operatorOrRef: BinaryOperatorType$2 | SelectableColumn$1<string>, referenceColumn?: SelectableColumn$1<string>): this;
4897
+ /**
4898
+ * @description Adds a negated OR condition comparing two columns.
4899
+ */
4900
+ orWhereNotColumn(column: SelectableColumn$1<string>, operatorOrRef: BinaryOperatorType$2 | SelectableColumn$1<string>, referenceColumn?: SelectableColumn$1<string>): this;
4901
+ private pushColumnWhere;
4581
4902
  /**
4582
4903
  * @description Adds a WHERE BETWEEN condition to the query.
4583
4904
  */
@@ -4746,12 +5067,160 @@ declare class JoinOnQueryBuilder {
4746
5067
  * @description Adds an OR raw WHERE condition to the query.
4747
5068
  */
4748
5069
  orWhereRaw(sql: string, bindings?: BaseValues$2[]): this;
5070
+ /**
5071
+ * @description Adds an EXISTS condition to the join ON clause. The nested query defaults to the
5072
+ * joined model's table; use `from` inside the callback to point it elsewhere.
5073
+ */
5074
+ whereExists(cbOrQueryBuilder: (qb: QueryBuilder) => void | QueryBuilder): this;
5075
+ /**
5076
+ * @description Adds an AND EXISTS condition to the join ON clause.
5077
+ */
5078
+ andWhereExists(cbOrQueryBuilder: (qb: QueryBuilder) => void | QueryBuilder): this;
5079
+ /**
5080
+ * @description Adds an OR EXISTS condition to the join ON clause.
5081
+ */
5082
+ orWhereExists(cbOrQueryBuilder: (qb: QueryBuilder) => void | QueryBuilder): this;
5083
+ /**
5084
+ * @description Adds a NOT EXISTS condition to the join ON clause.
5085
+ */
5086
+ whereNotExists(cbOrQueryBuilder: (qb: QueryBuilder) => void | QueryBuilder): this;
5087
+ /**
5088
+ * @description Adds an AND NOT EXISTS condition to the join ON clause.
5089
+ */
5090
+ andWhereNotExists(cbOrQueryBuilder: (qb: QueryBuilder) => void | QueryBuilder): this;
5091
+ /**
5092
+ * @description Adds an OR NOT EXISTS condition to the join ON clause.
5093
+ */
5094
+ orWhereNotExists(cbOrQueryBuilder: (qb: QueryBuilder) => void | QueryBuilder): this;
5095
+ private pushExists;
5096
+ /**
5097
+ * @description JSON predicate: the column's document contains the value (superset). Covers the
5098
+ * `whereJsonContains` and `whereJsonSupersetOf` spellings of the where builder.
5099
+ * @mssql Only exact matches work.
5100
+ */
5101
+ whereJson(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5102
+ /**
5103
+ * @description JSON predicate: the column's document contains the value (AND).
5104
+ */
5105
+ andWhereJson(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5106
+ /**
5107
+ * @description JSON predicate: the column's document contains the value (OR).
5108
+ */
5109
+ orWhereJson(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5110
+ /**
5111
+ * @description JSON predicate: the column's document does not contain the value. Covers the
5112
+ * `whereJsonNotContains` and `whereJsonNotSupersetOf` spellings of the where builder.
5113
+ * @mssql Not supported.
5114
+ */
5115
+ whereNotJson(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5116
+ /**
5117
+ * @description JSON predicate: the column's document does not contain the value (AND).
5118
+ */
5119
+ andWhereNotJson(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5120
+ /**
5121
+ * @description JSON predicate: the column's document does not contain the value (OR).
5122
+ */
5123
+ orWhereNotJson(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5124
+ /**
5125
+ * @description JSON predicate: the column equals an exact JSON object value.
5126
+ */
5127
+ whereJsonObject(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5128
+ /**
5129
+ * @description JSON predicate: the column equals an exact JSON object value (AND).
5130
+ */
5131
+ andWhereJsonObject(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5132
+ /**
5133
+ * @description JSON predicate: the column equals an exact JSON object value (OR).
5134
+ */
5135
+ orWhereJsonObject(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5136
+ /**
5137
+ * @description JSON predicate: the column does not equal an exact JSON object value.
5138
+ */
5139
+ whereNotJsonObject(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5140
+ /**
5141
+ * @description JSON predicate: the column does not equal an exact JSON object value (AND).
5142
+ */
5143
+ andWhereNotJsonObject(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5144
+ /**
5145
+ * @description JSON predicate: the column does not equal an exact JSON object value (OR).
5146
+ */
5147
+ orWhereNotJsonObject(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5148
+ /**
5149
+ * @description JSON predicate: compares the value at a JSON path. This is the ON-clause form of
5150
+ * Knex's `onJsonPathEquals`, and of `whereJsonPath` in the where builder.
5151
+ */
5152
+ whereJsonPath(column: SelectableColumn$1<string>, path: JsonPathInput, operator: BinaryOperatorType$2, value: any): this;
5153
+ /**
5154
+ * @description JSON predicate: compares the value at a JSON path (AND).
5155
+ */
5156
+ andWhereJsonPath(column: SelectableColumn$1<string>, path: JsonPathInput, operator: BinaryOperatorType$2, value: any): this;
5157
+ /**
5158
+ * @description JSON predicate: compares the value at a JSON path (OR).
5159
+ */
5160
+ orWhereJsonPath(column: SelectableColumn$1<string>, path: JsonPathInput, operator: BinaryOperatorType$2, value: any): this;
5161
+ /**
5162
+ * @description JSON predicate: the column's document is a subset of the value.
5163
+ * @postgres/cockroachdb/mysql/mariadb only
5164
+ */
5165
+ whereJsonSubsetOf(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5166
+ /**
5167
+ * @description JSON predicate: the column's document is a subset of the value (AND).
5168
+ */
5169
+ andWhereJsonSubsetOf(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5170
+ /**
5171
+ * @description JSON predicate: the column's document is a subset of the value (OR).
5172
+ */
5173
+ orWhereJsonSubsetOf(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5174
+ /**
5175
+ * @description JSON predicate: the column's document is not a subset of the value.
5176
+ * @postgres/cockroachdb/mysql/mariadb only
5177
+ */
5178
+ whereJsonNotSubsetOf(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5179
+ /**
5180
+ * @description JSON predicate: the column's document is not a subset of the value (AND).
5181
+ */
5182
+ andWhereJsonNotSubsetOf(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5183
+ /**
5184
+ * @description JSON predicate: the column's document is not a subset of the value (OR).
5185
+ */
5186
+ orWhereJsonNotSubsetOf(column: SelectableColumn$1<string>, value: Record<string, any> | any[]): this;
5187
+ /**
5188
+ * @description JSON predicate: the column has none of the given keys.
5189
+ * @postgres/cockroachdb only
5190
+ */
5191
+ whereJsonHasNone(column: SelectableColumn$1<string>, keys: string[]): this;
5192
+ /**
5193
+ * @description JSON predicate: the column has none of the given keys (AND).
5194
+ */
5195
+ andWhereJsonHasNone(column: SelectableColumn$1<string>, keys: string[]): this;
5196
+ /**
5197
+ * @description JSON predicate: the column has none of the given keys (OR).
5198
+ */
5199
+ orWhereJsonHasNone(column: SelectableColumn$1<string>, keys: string[]): this;
5200
+ /**
5201
+ * @description Adds a raw JSON predicate to the join ON clause.
5202
+ */
5203
+ whereJsonRaw(sql: string, bindings?: BaseValues$2[]): this;
5204
+ /**
5205
+ * @description Adds an AND raw JSON predicate to the join ON clause.
5206
+ */
5207
+ andWhereJsonRaw(sql: string, bindings?: BaseValues$2[]): this;
5208
+ /**
5209
+ * @description Adds an OR raw JSON predicate to the join ON clause.
5210
+ */
5211
+ orWhereJsonRaw(sql: string, bindings?: BaseValues$2[]): this;
5212
+ private pushJson;
4749
5213
  }
4750
5214
 
4751
5215
  /**
4752
5216
  * @description Callback type for join conditions
4753
5217
  */
4754
5218
  type JoinOnCallback = (query: JoinOnQueryBuilder) => void;
5219
+ /**
5220
+ * @description Callback building the derived table a join reads from. The joined
5221
+ * alias is required, since every dialect needs one for a derived table.
5222
+ */
5223
+ type JoinSubqueryCallback<T extends Model = Model> = (qb: QueryBuilder<T>) => void | SubQueryable;
4755
5224
  declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string, any> = Record<string, any>> extends FooterQueryBuilder<T, S> {
4756
5225
  protected joinNodes: JoinNode[];
4757
5226
  protected constructor(model: typeof Model, sqlDataSource: SqlDataSource);
@@ -4762,26 +5231,27 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
4762
5231
  /**
4763
5232
  * @description Join a table with the current model, join clause is not necessary and will be added automatically
4764
5233
  */
4765
- joinRaw(query: string): this;
5234
+ joinRaw(query: string, bindings?: any[]): this;
4766
5235
  /**
4767
5236
  * @description Join a table with the current model, join clause is not necessary and will be added automatically
4768
5237
  */
4769
- leftJoinRaw(query: string): this;
5238
+ leftJoinRaw(query: string, bindings?: any[]): this;
4770
5239
  /**
4771
5240
  * @description Join a table with the current model, join clause is not necessary and will be added automatically
4772
5241
  */
4773
- rightJoinRaw(query: string): this;
5242
+ rightJoinRaw(query: string, bindings?: any[]): this;
4774
5243
  /**
4775
5244
  * @description Join a table with the current model, join clause is not necessary and will be added automatically
4776
5245
  */
4777
- fullJoinRaw(query: string): this;
5246
+ fullJoinRaw(query: string, bindings?: any[]): this;
4778
5247
  /**
4779
5248
  * @description Join a table with the current model, join clause is not necessary and will be added automatically
4780
5249
  */
4781
- crossJoinRaw(query: string): this;
5250
+ crossJoinRaw(query: string, bindings?: any[]): this;
4782
5251
  /**
4783
5252
  * @description Performs a CROSS JOIN against a table (non-raw).
4784
5253
  */
5254
+ crossJoin(cb: JoinSubqueryCallback<T>, alias: string): this;
4785
5255
  crossJoin(relationTable: string, alias?: string): this;
4786
5256
  crossJoin<R extends AnyModelConstructor>(relationModel: R): this;
4787
5257
  /**
@@ -4793,7 +5263,7 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
4793
5263
  /**
4794
5264
  * @description Join a table with the current model, join clause is not necessary and will be added automatically
4795
5265
  */
4796
- naturalJoinRaw(query: string): this;
5266
+ naturalJoinRaw(query: string, bindings?: any[]): this;
4797
5267
  /**
4798
5268
  * @alias join
4799
5269
  * @param relationTable - The table to join
@@ -4801,6 +5271,7 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
4801
5271
  * @param primaryColumn - The primary column of the current model, default is caller model primary key if using a Model, if using a Raw Query Builder you must provide the key for the primary table, must be in the format of `table.column`
4802
5272
  * @param operator - The comparison operator to use in the ON clause (default: "=")
4803
5273
  */
5274
+ innerJoin(cb: JoinSubqueryCallback<T>, alias: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4804
5275
  innerJoin(relationTable: string): this;
4805
5276
  innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4806
5277
  innerJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$2): this;
@@ -4817,6 +5288,7 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
4817
5288
  * @param primaryColumn - The primary column of the current model, default is caller model primary key if using a Model, if using a Raw Query Builder you must provide the key for the primary table, must be in the format of `table.column`
4818
5289
  * @param operator - The comparison operator to use in the ON clause (default: "=")
4819
5290
  */
5291
+ join(cb: JoinSubqueryCallback<T>, alias: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4820
5292
  join(relationTable: string): this;
4821
5293
  join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4822
5294
  join(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$2): this;
@@ -4833,6 +5305,7 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
4833
5305
  * @param primaryColumn - The primary column of the current model, default is caller model primary key if using a Model, if using a Raw Query Builder you must provide the key for the primary table, must be in the format of `table.column`
4834
5306
  * @param operator - The comparison operator to use in the ON clause (default: "=")
4835
5307
  */
5308
+ leftJoin(cb: JoinSubqueryCallback<T>, alias: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4836
5309
  leftJoin(relationTable: string): this;
4837
5310
  leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4838
5311
  leftJoin(relationTable: string, referencingColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$2): this;
@@ -4849,6 +5322,7 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
4849
5322
  * @param primaryColumn - The primary column of the current model, default is caller model primary key if using A Model, if using a Raw Query Builder you must provide the key for the primary table
4850
5323
  * @param operator - The comparison operator to use in the ON clause (default: "=")
4851
5324
  */
5325
+ rightJoin(cb: JoinSubqueryCallback<T>, alias: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4852
5326
  rightJoin(relationTable: string): this;
4853
5327
  rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4854
5328
  rightJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$2): this;
@@ -4862,11 +5336,26 @@ declare abstract class JoinQueryBuilder<T extends Model, S extends Record<string
4862
5336
  * @param primaryColumn - The primary column of the current model
4863
5337
  * @param operator - The comparison operator to use in the ON clause (default: "=")
4864
5338
  */
5339
+ fullJoin(cb: JoinSubqueryCallback<T>, alias: string, referencingColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4865
5340
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator?: BinaryOperatorType$2): this;
4866
5341
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn?: JoinableColumn, operator?: BinaryOperatorType$2): this;
4867
5342
  fullJoin<R extends AnyModelConstructor>(relationTable: string | R, referencingColumnOrPrimaryColumn: ModelKey<InstanceType<R>> | JoinableColumn | ModelKey<T>, primaryColumn?: JoinableColumn | ModelKey<T>, operator?: BinaryOperatorType$2): this;
4868
5343
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, operator: BinaryOperatorType$2, callback: JoinOnCallback): this;
4869
5344
  fullJoin(relationTable: string, referencingColumnOrPrimaryColumn: JoinableColumn, primaryColumn: JoinableColumn, callback: JoinOnCallback): this;
5345
+ /**
5346
+ * @description Adds a join whose source is a derived table built by `cb`. The
5347
+ * join node carries the alias as its table, so an unqualified ON column on either
5348
+ * side still resolves against the derived table and the caller's model.
5349
+ */
5350
+ private derivedJoin;
5351
+ /**
5352
+ * @description Aliases for the three outer joins, spelled the way the SQL standard
5353
+ * writes them. Parameters are widened on purpose: `Parameters<>` on an overloaded
5354
+ * method resolves to its last overload only, which rejects the shorter call shapes.
5355
+ */
5356
+ leftOuterJoin(relationTable: string | AnyModelConstructor | JoinSubqueryCallback<T>, referencingColumn?: string, primaryColumn?: string, operatorOrCallback?: BinaryOperatorType$2 | JoinOnCallback, callback?: JoinOnCallback): this;
5357
+ rightOuterJoin(relationTable: string | AnyModelConstructor | JoinSubqueryCallback<T>, referencingColumn?: string, primaryColumn?: string, operatorOrCallback?: BinaryOperatorType$2 | JoinOnCallback, callback?: JoinOnCallback): this;
5358
+ fullOuterJoin(relationTable: string | AnyModelConstructor | JoinSubqueryCallback<T>, referencingColumn?: string, primaryColumn?: string, operatorOrCallback?: BinaryOperatorType$2 | JoinOnCallback, callback?: JoinOnCallback): this;
4870
5359
  }
4871
5360
 
4872
5361
  declare class SelectQueryBuilder<T extends Model, S extends Record<string, any> = Record<string, any>> extends JoinQueryBuilder<T, S> {
@@ -5033,6 +5522,14 @@ declare class SelectQueryBuilder<T extends Model, S extends Record<string, any>
5033
5522
  selectJsonRaw<A extends string>(raw: string, alias: A): this;
5034
5523
  }
5035
5524
 
5525
+ /**
5526
+ * @description The `{ column: value }` / `{ column: { op, value } }` shorthand, with
5527
+ * `$and` and `$or` keys for grouping. Shared by `find()` and the builder's `where()`.
5528
+ * @description Typed against the model's columns; a raw table builder passes `any`,
5529
+ * which accepts every key and value.
5530
+ */
5531
+ type ObjectWhereCondition<T = any> = WhereType<T>;
5532
+
5036
5533
  declare abstract class WhereQueryBuilder<T extends Model, S extends Record<string, any> = Record<string, any>> extends SelectQueryBuilder<T, S> {
5037
5534
  protected whereNodes: (WhereNode | WhereGroupNode | WhereSubqueryNode)[];
5038
5535
  protected havingNodes: HavingNode[];
@@ -5050,10 +5547,15 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5050
5547
  * @warning The value is checked for truthiness, so false, 0, "", etc. will be considered falsy. Use strictWhen for null or undefined only cases.
5051
5548
  */
5052
5549
  when(value: any, cb: (query: this) => void): this;
5550
+ /**
5551
+ * @description Applies a reusable query scope, forwarding any extra arguments to it.
5552
+ */
5553
+ modify<A extends any[]>(cb: (query: this, ...args: A) => void, ...args: A): this;
5053
5554
  /**
5054
5555
  * @description Adds a WHERE condition to the query.
5055
5556
  */
5056
5557
  where(cb: (queryBuilder: WhereOnlyQueryBuilder<T>) => void): this;
5558
+ where(conditions: ObjectWhereCondition<T>): this;
5057
5559
  where(column: string, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5058
5560
  where(column: string, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5059
5561
  where<K extends ModelKey<T>>(column: K, operator: BinaryOperatorType$2, value: WhereColumnValue<T, K>): this;
@@ -5064,6 +5566,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5064
5566
  * @description Adds an AND WHERE condition to the query.
5065
5567
  */
5066
5568
  andWhere(cb: (queryBuilder: WhereOnlyQueryBuilder<T>) => void): this;
5569
+ andWhere(conditions: ObjectWhereCondition<T>): this;
5067
5570
  andWhere(column: string, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5068
5571
  andWhere(column: string, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5069
5572
  andWhere<K extends ModelKey<T>>(column: K, operator: BinaryOperatorType$2, value: WhereColumnValue<T, K>): this;
@@ -5074,6 +5577,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5074
5577
  * @description Adds an OR WHERE condition to the query.
5075
5578
  */
5076
5579
  orWhere(cb: (queryBuilder: WhereOnlyQueryBuilder<T>) => void): this;
5580
+ orWhere(conditions: ObjectWhereCondition<T>): this;
5077
5581
  orWhere(column: string, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5078
5582
  orWhere(column: string, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5079
5583
  orWhere<K extends ModelKey<T>>(column: K, operator: BinaryOperatorType$2, value: WhereColumnValue<T, K>): this;
@@ -5126,7 +5630,9 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5126
5630
  private pushNotColumnWhere;
5127
5631
  /**
5128
5632
  * @description Adds a negated WHERE condition to the query.
5633
+ * @description With a single callback the whole group is negated: `not (a or b)`
5129
5634
  */
5635
+ whereNot(cb: (queryBuilder: WhereOnlyQueryBuilder<T>) => void): this;
5130
5636
  whereNot(column: string, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5131
5637
  whereNot(column: string, operator: SubqueryOperatorType, subQuery: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5132
5638
  whereNot<K extends ModelKey<T>>(column: K, operator: BinaryOperatorType$2, value: WhereColumnValue<T, K>): this;
@@ -5245,6 +5751,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5245
5751
  * @description Adds a WHERE IN condition to the query.
5246
5752
  * @warning If the array is empty, it will add an impossible condition.
5247
5753
  */
5754
+ whereIn(columns: string[], values: any[][]): this;
5248
5755
  whereIn(column: string, values: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5249
5756
  whereIn<K extends ModelKey<T>>(column: K, values: T[StripTablePrefix<K & string> & keyof T][]): this;
5250
5757
  whereIn<K extends `${string}.${string}`>(column: K, values: ResolveWhereValue<T, K>[]): this;
@@ -5252,6 +5759,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5252
5759
  * @description Adds an AND WHERE IN condition to the query.
5253
5760
  * @warning If the array is empty, it will add an impossible condition.
5254
5761
  */
5762
+ andWhereIn(columns: string[], values: any[][]): this;
5255
5763
  andWhereIn(column: string, values: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5256
5764
  andWhereIn<K extends ModelKey<T>>(column: K, values: T[StripTablePrefix<K & string> & keyof T][]): this;
5257
5765
  andWhereIn<K extends `${string}.${string}`>(column: K, values: ResolveWhereValue<T, K>[]): this;
@@ -5259,6 +5767,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5259
5767
  * @description Adds an OR WHERE IN condition to the query.
5260
5768
  * @warning If the array is empty, it will add an impossible condition.
5261
5769
  */
5770
+ orWhereIn(columns: string[], values: any[][]): this;
5262
5771
  orWhereIn(column: string, values: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5263
5772
  orWhereIn<K extends ModelKey<T>>(column: K, values: T[StripTablePrefix<K & string> & keyof T][]): this;
5264
5773
  orWhereIn<K extends `${string}.${string}`>(column: K, values: ResolveWhereValue<T, K>[]): this;
@@ -5266,6 +5775,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5266
5775
  * @description Adds a WHERE NOT IN condition to the query.
5267
5776
  * @warning If the array is empty, it will add an obvious condition to make it true.
5268
5777
  */
5778
+ whereNotIn(columns: string[], values: any[][]): this;
5269
5779
  whereNotIn(column: string, values: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5270
5780
  whereNotIn<K extends ModelKey<T>>(column: K, values: T[StripTablePrefix<K & string> & keyof T][]): this;
5271
5781
  whereNotIn<K extends `${string}.${string}`>(column: K, values: ResolveWhereValue<T, K>[]): this;
@@ -5273,6 +5783,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5273
5783
  * @description Adds an OR WHERE NOT IN condition to the query.
5274
5784
  * @warning If the array is empty, it will add an obvious condition to make it true.
5275
5785
  */
5786
+ andWhereNotIn(columns: string[], values: any[][]): this;
5276
5787
  andWhereNotIn(column: string, values: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5277
5788
  andWhereNotIn<K extends ModelKey<T>>(column: K, values: T[StripTablePrefix<K & string> & keyof T][]): this;
5278
5789
  andWhereNotIn<K extends `${string}.${string}`>(column: K, values: ResolveWhereValue<T, K>[]): this;
@@ -5280,6 +5791,7 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5280
5791
  * @description Adds an OR WHERE NOT IN condition to the query.
5281
5792
  * @warning If the array is empty, it will add an obvious condition to make it true.
5282
5793
  */
5794
+ orWhereNotIn(columns: string[], values: any[][]): this;
5283
5795
  orWhereNotIn(column: string, values: QueryBuilder<T> | ((subQuery: QueryBuilder<T>) => void | SubQueryable)): this;
5284
5796
  orWhereNotIn<K extends ModelKey<T>>(column: K, values: T[StripTablePrefix<K & string> & keyof T][]): this;
5285
5797
  orWhereNotIn<K extends `${string}.${string}`>(column: K, values: ResolveWhereValue<T, K>[]): this;
@@ -5485,6 +5997,11 @@ declare abstract class WhereQueryBuilder<T extends Model, S extends Record<strin
5485
5997
  private buildSubQuery;
5486
5998
  private andWhereSubQuery;
5487
5999
  private orWhereSubQuery;
6000
+ /**
6001
+ * @description Row-value `in`/`not in`: `(a, b) in ((1, 2), (3, 4))`, which the
6002
+ * dialects that support it evaluate as a tuple comparison.
6003
+ */
6004
+ private pushTupleIn;
5488
6005
  private andWhereGroup;
5489
6006
  private orWhereGroup;
5490
6007
  }
@@ -5640,6 +6157,12 @@ declare class JsonQueryBuilder<T extends Model, S extends Record<string, any> =
5640
6157
  }
5641
6158
 
5642
6159
  type PluckReturnType<T extends Model, K extends RawModelKey<T>> = T[StripTablePrefix<K & string> & keyof T] extends infer U ? U[] : never;
6160
+ /**
6161
+ * Key accepted by `value()`. A narrowed selection leaves only its own columns
6162
+ * readable, which is what `select()` already returned as the result shape.
6163
+ * An untyped result falls back to every model column.
6164
+ */
6165
+ type ValueKey<T extends Model, S extends Record<string, any>> = string extends keyof S ? RawModelKey<T> : keyof S & string;
5643
6166
  /**
5644
6167
  * Common SQL functions with intellisense support.
5645
6168
  * Provides autocomplete for standard SQL aggregate and scalar functions,
@@ -5757,6 +6280,13 @@ type HasRawStarOrEmpty<Columns extends readonly Selectable[]> = Columns["length"
5757
6280
  type BuildRawSelectType<Columns extends readonly Selectable[]> = HasRawStarOrEmpty<Columns> extends true ? Record<string, any> : UnionToIntersection$1<{
5758
6281
  [K in keyof Columns]: BuildRawSingleSelectType<Columns[K]>;
5759
6282
  }[number]> extends infer Result ? Result extends Record<string, any> ? keyof Result extends never ? Record<string, any> : Result & RawSelectBrand : Record<string, any> : Record<string, any>;
6283
+ /**
6284
+ * Options for the set operations (`union`, `unionAll`, `intersect`, `except`).
6285
+ */
6286
+ type SetOperationOptions = {
6287
+ /** Parenthesizes that branch, so its own `ORDER BY` or `LIMIT` stays scoped to it. */
6288
+ wrap?: boolean;
6289
+ };
5760
6290
  /**
5761
6291
  * Composes a new selection with the existing selection state for raw queries.
5762
6292
  *
@@ -5885,7 +6415,14 @@ interface DriverAdapter<D extends SqlDataSourceType = SqlDataSourceType, M exten
5885
6415
  createPool(): Promise<void> | void;
5886
6416
  closePool(): Promise<void>;
5887
6417
  reserveConnection(): Promise<GetConnectionReturnType<D>> | GetConnectionReturnType<D>;
5888
- releaseConnection(connection?: GetConnectionReturnType<D>): Promise<void> | void;
6418
+ /**
6419
+ * @description Returns a reserved connection to the pool. When `error` is
6420
+ * given the caller is reporting why the connection is being given up (a failed
6421
+ * COMMIT or ROLLBACK), and the adapter should discard it rather than pool it:
6422
+ * the session state after that failure is unknown, so the next query must not
6423
+ * inherit it. Adapters whose connection cannot be discarded may ignore it.
6424
+ */
6425
+ releaseConnection(connection?: GetConnectionReturnType<D>, error?: unknown): Promise<void> | void;
5889
6426
  beginTransaction(connection: GetConnectionReturnType<D>, options: BeginTransactionOptions<D>): Promise<void>;
5890
6427
  commitTransaction(connection: GetConnectionReturnType<D>, options: EndTransactionOptions<D>): Promise<void>;
5891
6428
  rollbackTransaction(connection: GetConnectionReturnType<D>, options: EndTransactionOptions<D>): Promise<void>;
@@ -6089,6 +6626,15 @@ type SlaveContext = {
6089
6626
  password: string;
6090
6627
  database: string;
6091
6628
  };
6629
+ /**
6630
+ * @description Context passed to `onPoolError` describing the pool that reported a failure.
6631
+ */
6632
+ type PoolErrorContext = {
6633
+ type: SqlDataSourceType;
6634
+ host: string;
6635
+ port: number;
6636
+ database: string;
6637
+ };
6092
6638
  /**
6093
6639
  * @description The input type for the SqlDataSource constructor
6094
6640
  * @description The connectionPolicies object is used to configure the connection policies for the sql data source
@@ -6139,6 +6685,18 @@ type SqlDataSourceInputShape<D extends SqlDataSourceType, T extends Record<strin
6139
6685
  * against strings must switch to a numeric comparison.
6140
6686
  */
6141
6687
  coerceNumericTypes?: boolean;
6688
+ /**
6689
+ * @description Called when a pooled connection fails while it sits idle.
6690
+ * @description The driver has already removed the client from the pool by the
6691
+ * time this fires, so the handler reports the failure; it cannot rescue the
6692
+ * connection. A handler that throws is caught and logged rather than reaching
6693
+ * the process.
6694
+ * @description Only the node `pg` driver (postgres, cockroachdb) surfaces
6695
+ * pool-level errors. The other drivers report connection failures on the
6696
+ * query that hit them, so this is never called there.
6697
+ * @default the error is logged and the pool keeps serving other clients
6698
+ */
6699
+ onPoolError?: (error: Error, context: PoolErrorContext) => void | Promise<void>;
6142
6700
  /**
6143
6701
  * @description The replication configuration for the sql data source, it's used to configure the replication for the sql data source
6144
6702
  */
@@ -6285,6 +6843,7 @@ type UpsertOptions<T extends Model> = {
6285
6843
  };
6286
6844
  type InsertOptions<T extends Model> = {
6287
6845
  returning?: ReturningKey<T>[];
6846
+ withNodes?: WithNode[];
6288
6847
  };
6289
6848
  type ExcludeRelations<T> = {
6290
6849
  [K in keyof T]: K extends "__tableName" ? never : T[K] extends NullableAndUndefinable<Model> | NullableAndUndefinable<Model[]> | ((...args: any[]) => any) ? never : K;
@@ -6423,10 +6982,17 @@ type WhereColumnValue<T extends Model, K extends ModelKey<T>> = T[StripTablePref
6423
6982
  type ResolveWhereValue<T extends Model, K extends string> = K extends ModelKey<T> ? T[StripTablePrefix<K> & keyof T] | null | SqlFuncNode : BaseValues$2;
6424
6983
  type ModelRelation<T extends Model> = OnlyRelations<T>;
6425
6984
  type OrderByChoices = "asc" | "desc";
6985
+ /**
6986
+ * @description Either a bare direction, or a direction with an explicit null placement.
6987
+ */
6988
+ type OrderByClause = OrderByChoices | {
6989
+ direction: OrderByChoices;
6990
+ nulls?: "first" | "last";
6991
+ };
6426
6992
  type OrderByType<T extends Model> = {
6427
- [K in keyof T as K extends "__tableName" ? never : K]?: OrderByChoices;
6993
+ [K in keyof T as K extends "__tableName" ? never : K]?: OrderByClause;
6428
6994
  } & {
6429
- [K in string]?: OrderByChoices;
6995
+ [K in string]?: OrderByClause;
6430
6996
  };
6431
6997
  type FindOneType<T extends Model, S extends ModelKey<T>[] = any[], R extends ModelRelation<T>[] = never[]> = {
6432
6998
  select?: S;
@@ -6865,7 +7431,7 @@ type UpdateOptions = {};
6865
7431
  /**
6866
7432
  * @description Due to query limitations some query builder methods may not be available in a RelationQueryBuilder
6867
7433
  */
6868
- type RelationQueryBuilderType<T extends Model, A extends Record<string, any> = {}, R extends Record<string, any> = {}> = Omit<ModelQueryBuilder<T, A, R>, "increment" | "decrement" | "paginate" | "pluck" | "truncate" | "many" | "one" | "oneOrFail" | "insert" | "insertMany" | "update" | "delete" | "softDelete" | "getSum" | "getAvg" | "getMin" | "getMax" | "getCount" | "getMin" | "getMax" | "getCount">;
7434
+ type RelationQueryBuilderType<T extends Model, A extends Record<string, any> = {}, R extends Record<string, any> = {}> = Omit<ModelQueryBuilder<T, A, R>, "increment" | "decrement" | "paginate" | "pluck" | "value" | "truncate" | "many" | "one" | "oneOrFail" | "insert" | "insertMany" | "batchInsert" | "update" | "delete" | "softDelete" | "getSum" | "getAvg" | "getMin" | "getMax" | "getCount" | "getMin" | "getMax" | "getCount">;
6869
7435
 
6870
7436
  declare class ModelQueryBuilder<T extends Model, S extends Record<string, any> = ModelWithoutRelations<T>, R extends Record<string, any> = {}, D extends SqlDataSourceType = SqlDataSourceType> extends QueryBuilder<T, Record<string, any>, D> {
6871
7437
  relation: Relation;
@@ -6909,17 +7475,37 @@ declare class ModelQueryBuilder<T extends Model, S extends Record<string, any> =
6909
7475
  /**
6910
7476
  * @description Inserts a new record into the database.
6911
7477
  */
6912
- insert<const Ret extends readonly (RawModelKey<T> | "*")[] = never[]>(modelData: Partial<ModelWithoutRelations<T>>, options?: {
7478
+ insert<const Ret extends readonly (RawModelKey<T> | "*")[] = never[]>(modelData: ModelWriteData<T>, options?: {
6913
7479
  returning?: Ret;
6914
7480
  trx?: Transaction;
6915
- }): WriteOperation<ReturningResult<T, Ret>>;
7481
+ }): InsertWriteOperation<ReturningResult<T, Ret>, Extract<ModelKey<T>, string>>;
6916
7482
  /**
6917
7483
  * @description Inserts multiple records into the database.
6918
7484
  */
6919
- insertMany<const Ret extends readonly (RawModelKey<T> | "*")[] = never[]>(modelsData: Partial<ModelWithoutRelations<T>>[], options?: {
7485
+ insertMany<const Ret extends readonly (RawModelKey<T> | "*")[] = never[]>(modelsData: ModelWriteData<T>[], options?: {
6920
7486
  returning?: Ret;
6921
7487
  trx?: Transaction;
6922
- }): WriteOperation<ReturningResultMany<T, Ret>>;
7488
+ }): InsertWriteOperation<ReturningResultMany<T, Ret>, Extract<ModelKey<T>, string>>;
7489
+ /**
7490
+ * @description Inserts rows in chunks of `chunkSize`, one statement per chunk.
7491
+ * @description The chunks are not wrapped in a transaction; wrap the call in
7492
+ * `sql.transaction(...)` when the whole batch has to be atomic.
7493
+ * @returns The returned columns, or the number of inserted rows without `returning`
7494
+ */
7495
+ batchInsert<const Ret extends readonly (RawModelKey<T> | "*")[] = never[]>(modelsData: ModelWriteData<T>[], options?: {
7496
+ chunkSize?: number;
7497
+ returning?: Ret;
7498
+ trx?: Transaction;
7499
+ }): Promise<[Ret] extends [never[]] ? number : ReturningResultMany<T, Ret>>;
7500
+ /**
7501
+ * @description Inserts the rows produced by a SELECT (or a CTE feeding one) into the table.
7502
+ * @param targetColumns - Optional destination model columns; positional when omitted
7503
+ * @param source - A model builder (or callback) whose SELECT becomes the insert source
7504
+ * @returns InsertWriteOperation, so `onConflict(...).merge()/.ignore()` chains onto it
7505
+ * @warning Rows come from the database, so no validation, hooks or autoCreate columns run
7506
+ */
7507
+ insertFrom(source: ModelQueryBuilder<any> | ((qb: ModelQueryBuilder<any>) => ModelQueryBuilder<any> | void)): InsertWriteOperation<T[]>;
7508
+ insertFrom<C extends ModelKey<T>>(targetColumns: C[], source: ModelQueryBuilder<any> | ((qb: ModelQueryBuilder<any>) => ModelQueryBuilder<any> | void)): InsertWriteOperation<T[]>;
6923
7509
  /**
6924
7510
  * @description Upserts a record (insert or update on conflict).
6925
7511
  */
@@ -7017,8 +7603,9 @@ declare class ModelQueryBuilder<T extends Model, S extends Record<string, any> =
7017
7603
  }): Promise<void>;
7018
7604
  /**
7019
7605
  * @description Truncates the table by deleting all records.
7606
+ * @param options - `RESTART IDENTITY` / `CONTINUE IDENTITY` / `CASCADE` (PostgreSQL and CockroachDB only)
7020
7607
  */
7021
- truncate(): WriteOperation<void>;
7608
+ truncate(options?: TruncateOptions): WriteOperation<void>;
7022
7609
  /**
7023
7610
  * @description Updates records matching the current query conditions.
7024
7611
  * @param data - The columns and values to update.
@@ -7026,7 +7613,10 @@ declare class ModelQueryBuilder<T extends Model, S extends Record<string, any> =
7026
7613
  * @param options.returning - Columns to return from updated rows. Only supported on PostgreSQL, CockroachDB, SQLite, and MSSQL. Not available on MySQL or MariaDB.
7027
7614
  * @returns WriteOperation resolving to the number of affected rows, or the returned columns if `returning` is specified (supported databases only).
7028
7615
  */
7029
- update<const Ret extends ReturningParam<T, D> = never[]>(data: Partial<ModelWithoutRelations<T>>, options?: UpdateOptions & {
7616
+ update<const Ret extends ReturningParam<T, D> = never[]>(column: ModelKey<T> & string, value: WriteQueryParam, options?: UpdateOptions & {
7617
+ returning?: Ret;
7618
+ }): WriteOperation<MutationReturningResult<T, Ret>>;
7619
+ update<const Ret extends ReturningParam<T, D> = never[]>(data: ModelWriteData<T>, options?: UpdateOptions & {
7030
7620
  returning?: Ret;
7031
7621
  }): WriteOperation<MutationReturningResult<T, Ret>>;
7032
7622
  softDelete(options?: SoftDeleteOptions<T>): WriteOperation<number>;
@@ -8439,7 +9029,7 @@ declare class InMemoryAdapter implements CacheAdapter {
8439
9029
  }
8440
9030
 
8441
9031
  declare class RedisCacheAdapter implements CacheAdapter {
8442
- redisInstance: Redis;
9032
+ redisInstance: Redis | undefined;
8443
9033
  private ioRedisOptions;
8444
9034
  constructor(ioRedisOptions: RedisOptions);
8445
9035
  private getClient;
@@ -9036,6 +9626,7 @@ declare class Schema {
9036
9626
  dropIndex(indexName: string, table?: string): void;
9037
9627
  /**
9038
9628
  * @description Adds a primary key to a table
9629
+ * @throws HysteriaError if sqlite database, which cannot add a primary key to an existing table
9039
9630
  */
9040
9631
  addPrimaryKey(table: string, columns: string[]): void;
9041
9632
  /**
@@ -9162,7 +9753,7 @@ declare abstract class BaseSeeder {
9162
9753
  abstract run(): Promise<void>;
9163
9754
  }
9164
9755
 
9165
- type HysteriaErrorCode = "VALIDATION_ERROR" | "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_STRENGTH_NOT_SUPPORTED_IN_${string}` | "QUERY_TIMEOUT" | `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" | "NOT_MATERIALIZED_CTE_NOT_SUPPORTED" | "USING_REQUIRES_JOIN" | "USING_NOT_SUPPORTED_IN_MSSQL" | "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" | "ORDER_BY_REQUIRED" | "ORDER_BY_RAW_NOT_SUPPORTED" | "INVALID_SQL_COMMENT" | "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" | `BETTER_AUTH_MISSING_ID_${string}` | `BETTER_AUTH_INVALID_INCREMENT_${string}` | "ZOD_ENGINE_NOT_LOADED" | "ATOMIC_DATASOURCE_RESOLUTION_FAILED" | "ATOMIC_INVALID_METHOD" | "ATOMIC_CLS_DISABLED" | `SCOPE_NOT_FOUND_${string}`;
9756
+ type HysteriaErrorCode = "VALIDATION_ERROR" | "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_STRENGTH_NOT_SUPPORTED_IN_${string}` | "QUERY_TIMEOUT" | `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" | "NOT_MATERIALIZED_CTE_NOT_SUPPORTED" | "ONLY_NOT_SUPPORTED" | "USING_REQUIRES_JOIN" | "USING_CONFLICTS_WITH_ON_CONDITIONS" | "USING_NOT_SUPPORTED_IN_MSSQL" | "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" | "ORDER_BY_REQUIRED" | "ORDER_BY_RAW_NOT_SUPPORTED" | "INVALID_SQL_COMMENT" | "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" | `BETTER_AUTH_MISSING_ID_${string}` | `BETTER_AUTH_INVALID_INCREMENT_${string}` | "ZOD_ENGINE_NOT_LOADED" | "ATOMIC_DATASOURCE_RESOLUTION_FAILED" | "ATOMIC_INVALID_METHOD" | "ATOMIC_CLS_DISABLED" | `SCOPE_NOT_FOUND_${string}` | "ON_CONFLICT_REQUIRES_MERGE_OR_IGNORE" | "MERGE_REQUIRES_ON_CONFLICT" | "MERGE_REQUIRES_COLUMNS" | "ON_CONFLICT_COLUMNS_REQUIRED" | "JOIN_NOT_SUPPORTED_ON_WRITE" | "ORDER_BY_LIMIT_NOT_SUPPORTED_ON_WRITE" | "SELECT_ONLY_CLAUSE_ON_WRITE" | "CTE_NOT_SUPPORTED_ON_INSERT" | "CTE_NOT_SUPPORTED_ON_TRUNCATE" | "CTE_NOT_SUPPORTED_ON_WRITE" | "TRUNCATE_OPTION_NOT_SUPPORTED" | "UPDATE_REQUIRES_COLUMNS" | "UPDATE_FROM_NOT_SUPPORTED" | "DELETE_USING_NOT_SUPPORTED" | "MERGE_WHERE_NOT_SUPPORTED" | "INVALID_BATCH_SIZE" | "ORDER_BY_NULLS_WITH_CURSOR_NOT_SUPPORTED" | "WHERE_TUPLE_COLUMNS_REQUIRED";
9166
9757
 
9167
9758
  declare class HysteriaError extends Error {
9168
9759
  code: HysteriaErrorCode;
@@ -9325,4 +9916,4 @@ type BetterAuthAdapterConfig = Partial<Pick<AdapterFactoryConfig, "usePlural" |
9325
9916
  */
9326
9917
  declare function betterAuthAdapter(sql: SqlDataSource, config?: BetterAuthAdapterConfig): (options: BetterAuthOptions) => DBAdapter;
9327
9918
 
9328
- export { type AdminJsActionOptions, type AdminJsAssets, type AdminJsBranding, type AdminJsInstance, type AdminJsLocale, type AdminJsOptions, type AdminJsPage, type AdminJsPropertyOptions, type AdminJsResourceOptions, type AdminJsSettings, type AllowedDrivers, type AnyModelConstructor, type AnySqlDataSourceInput, type AtomicOptions, type BaseModelMethodOptions, BaseSeeder, type BeginTransactionOptions, type BetterAuthAdapterConfig, type BuildSelectType, type BuildSingleSelectType, type BuiltinDriverName, type CacheAdapter, type CacheKeys, ClientMigrator, type ColCharOptions, type ColComputedOptions, type ColJsonbOptions, type ColMediumIntOptions, type ColSmallIntOptions, type ColTinyIntOptions, type ColVarbinaryOptions, Collection, type CollectionDefinition, type ColumnDef, type CommonDataSourceInput, type ComposeBuildSelect, type ComposeSelect, type ComputedColumnDef, type ConnectionPolicies, type CreateSchemaResult, type CustomLogger, type DataSourceInput, type DataSourceType, type DateAutoHook, type DefinedCollection, type DefinedModel, type DefinedView, type DriverAdapter, type DriverAdapterFactory, type DriverAdapterFactoryContext, type EndTransactionOptions, type ExcludeMethods, type ExecuteOptions, type ExtractColumnName, type ExtractSourceColumn, type FindReturnType, type GetColumnType, type GetConnectionReturnType, HysteriaError, type HysteriaErrorCode, InMemoryAdapter, type InferPK, type IntrospectedColumn, type IntrospectedForeignKey, type IntrospectedSchema, type IntrospectedTable, type JsEnvironmentValue, type JsonPathInput, type JsonPaths, type LoadOptions, type LoggerConfig, Migration, type MigrationConfig, type MigrationConfigBase, type MigrationLockConfig, type ModelColumns, type ModelDataProperties, type ModelInstanceType, type ModelKey, ModelQueryBuilder, type ModelQueryResult, type ModelRelation, type ModelSelectTuple, type ModelSelectableInput, type ModelStream, type ModelWithoutRelations, type ModelsProxy, MongoDataSource, type MongoDataSourceInput$1 as MongoDataSourceInput, type MssqlComment, type MssqlConnectionInstance, type MssqlDataSourceInput, type MssqlPoolInstance, type MutationReturningResult, type MySqlComment, type MysqlConnectionInstance, type MysqlSqlDataSourceInput, type NotNullableMysqlSqlDataSourceInput, type NotNullableOracleMssqlDataSourceInput, type NotNullablePostgresSqlDataSourceInput, type NotNullableSqliteDataSourceInput, type NullableColumn, type NumberModelKey, ObserverChain, ObserverChainWrapper, type Operation, type PgComment, type PgPoolClientInstance, type PingResult, type PlatformAdapter, type PlatformFs, type PlatformPath, PlatformUnsupportedError, type PostgresSqlDataSourceInput, type PrimaryColumnDef, type PropNamespace, type PropertyDef, QueryBuilder, type QueryContext, type QueryContextWithDuration, type QueryObserver, type RawModelKey, type RawModelOptions, RawNode, type RawQueryOptions, RedisCacheAdapter, type RedisFetchable, type RedisStorable, type RelatedInstance, type RelationDef, type RelationDefinitions, type RelationHelpers, type RelationLoadStrategy, type RelationQueryBuilderType, type ReplicationType, type ResolveColumnType, type ResolveJsonPathType, type ResolvedJsEnvironment, type ReturningColumns, type ReturningKey, type ReturningParam, type ReturningResult, type ReturningResultMany, type ReturningSupported, Schema, SchemaBuilder, type SchemaLookup, type SchemaRelDef, type SeederConfig, type SelectBrand, type SelectableColumn, type SelectedModel, type SlaveAlgorithm, type SlaveContext, type SqlCloneOptions, type SqlComment, SqlDataSource, type SqlDataSourceInput, type SqlDataSourceModel, type SqlDataSourceType, type SqlDriverSpecificOptions, SqlFuncNode, type SqlFuncRenderer, type SqlHint, type SqlPoolType, type Sqlite3ConnectionOptions, type SqliteComment, type SqliteConnectionInstance, type SqliteDataSourceInput, type StartTransactionOptions, type StripTablePrefix, type SubQueryable, type TableFormat, Transaction, type TransactionExecutionOptions, type TypedDefault, type TypedJsonPathInput, type TypedPrepare, type TypedSerialize, type UseCacheReturnType, type UseConnectionInput, type ValidationContext, ValidationError, type ValidationResult, type Validator, type ViewDefinition, WriteOperation, type WriteReturnType, atomic, betterAuthAdapter, col, createSchema, defineCollection, defineMigrator, defineModel, defineModelFactory, defineRelations, defineView, deriveOperationFromQuery, email, enumValidator, generateOpenApiModel, generateOpenApiModelSchema, generateOpenApiModelWithMetadata, type getPoolReturnType, loadPlatform, HysteriaLogger as logger, max, maxLength, min, minLength, pattern, prop, RedisDataSource as redis, registerDriverAdapter, registerSqlFuncRenderer, required, sqlFunc, url };
9919
+ export { type AdminJsActionOptions, type AdminJsAssets, type AdminJsBranding, type AdminJsInstance, type AdminJsLocale, type AdminJsOptions, type AdminJsPage, type AdminJsPropertyOptions, type AdminJsResourceOptions, type AdminJsSettings, type AllowedDrivers, type AnyModelConstructor, type AnySqlDataSourceInput, type AtomicOptions, type BaseModelMethodOptions, BaseSeeder, type BeginTransactionOptions, type BetterAuthAdapterConfig, type BuildSelectType, type BuildSingleSelectType, type BuiltinDriverName, type CacheAdapter, type CacheKeys, ClientMigrator, type ColCharOptions, type ColComputedOptions, type ColJsonbOptions, type ColMediumIntOptions, type ColSmallIntOptions, type ColTinyIntOptions, type ColVarbinaryOptions, Collection, type CollectionDefinition, type ColumnDef, type CommonDataSourceInput, type ComposeBuildSelect, type ComposeSelect, type ComputedColumnDef, type ConnectionPolicies, type CreateSchemaResult, type CustomLogger, type DataSourceInput, type DataSourceType, type DateAutoHook, type DefinedCollection, type DefinedModel, type DefinedView, type DriverAdapter, type DriverAdapterFactory, type DriverAdapterFactoryContext, type EndTransactionOptions, type ExcludeMethods, type ExecuteOptions, type ExtractColumnName, type ExtractSourceColumn, type FindReturnType, type GetColumnType, type GetConnectionReturnType, HysteriaError, type HysteriaErrorCode, InMemoryAdapter, type InferPK, type InsertConflictConfig, type InsertConflictMode, InsertWriteOperation, type IntrospectedColumn, type IntrospectedForeignKey, type IntrospectedSchema, type IntrospectedTable, type JsEnvironmentValue, type JsonMutationFor, type JsonPathInput, type JsonPaths, type LoadOptions, type LoggerConfig, Migration, type MigrationConfig, type MigrationConfigBase, type MigrationLockConfig, type ModelColumns, type ModelDataProperties, type ModelInstanceType, type ModelKey, ModelQueryBuilder, type ModelQueryResult, type ModelRelation, type ModelSelectTuple, type ModelSelectableInput, type ModelStream, type ModelWithoutRelations, type ModelWriteData, type ModelsProxy, MongoDataSource, type MongoDataSourceInput$1 as MongoDataSourceInput, type MssqlComment, type MssqlConnectionInstance, type MssqlDataSourceInput, type MssqlPoolInstance, type MutationReturningResult, type MySqlComment, type MysqlConnectionInstance, type MysqlSqlDataSourceInput, type NotNullableMysqlSqlDataSourceInput, type NotNullableOracleMssqlDataSourceInput, type NotNullablePostgresSqlDataSourceInput, type NotNullableSqliteDataSourceInput, type NullableColumn, type NumberModelKey, ObserverChain, ObserverChainWrapper, type Operation, type PgComment, type PgPoolClientInstance, type PingResult, type PlatformAdapter, type PlatformFs, type PlatformPath, PlatformUnsupportedError, type PoolErrorContext, type PostgresSqlDataSourceInput, type PrimaryColumnDef, type PropNamespace, type PropertyDef, QueryBuilder, type QueryContext, type QueryContextWithDuration, type QueryObserver, type RawModelKey, type RawModelOptions, RawNode, type RawQueryOptions, RedisCacheAdapter, type RedisFetchable, type RedisStorable, type RelatedInstance, type RelationDef, type RelationDefinitions, type RelationHelpers, type RelationLoadStrategy, type RelationQueryBuilderType, type ReplicationType, type ResolveColumnType, type ResolveJsonPathType, type ResolvedJsEnvironment, type ReturningColumns, type ReturningKey, type ReturningParam, type ReturningResult, type ReturningResultMany, type ReturningSupported, Schema, SchemaBuilder, type SchemaLookup, type SchemaRelDef, type SeederConfig, type SelectBrand, type SelectableColumn, type SelectedModel, type SlaveAlgorithm, type SlaveContext, type SqlCloneOptions, type SqlComment, SqlDataSource, type SqlDataSourceInput, type SqlDataSourceModel, type SqlDataSourceType, type SqlDriverSpecificOptions, SqlFuncNode, type SqlFuncRenderer, type SqlHint, type SqlPoolType, type Sqlite3ConnectionOptions, type SqliteComment, type SqliteConnectionInstance, type SqliteDataSourceInput, type StartTransactionOptions, type StripTablePrefix, type SubQueryable, type TableFormat, Transaction, type TransactionExecutionOptions, type TypedDefault, type TypedJsonPathInput, type TypedPrepare, type TypedSerialize, type UseCacheReturnType, type UseConnectionInput, type ValidationContext, ValidationError, type ValidationResult, type Validator, type ViewDefinition, WriteOperation, type WriteReturnType, atomic, betterAuthAdapter, col, createSchema, defineCollection, defineMigrator, defineModel, defineModelFactory, defineRelations, defineView, deriveOperationFromQuery, email, enumValidator, generateOpenApiModel, generateOpenApiModelSchema, generateOpenApiModelWithMetadata, type getPoolReturnType, loadPlatform, HysteriaLogger as logger, max, maxLength, min, minLength, pattern, prop, RedisDataSource as redis, registerDriverAdapter, registerSqlFuncRenderer, required, sqlFunc, url };