pqb 0.38.6 → 0.38.8

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/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { PoolConfig, Pool, PoolClient } from 'pg';
2
2
  import * as orchid_core from 'orchid-core';
3
- import { QueryResultRow, AdapterConfigBase, AdapterBase, QueryInput, SingleSqlItem, Sql, RecordUnknown, RecordKeyTrue, EmptyObject, QueryBaseCommon, QueryColumns, QueryMetaBase, QueryReturnType, QueryThen, Expression, MaybeArray, TemplateLiteralArgs, QueryColumn, MaybePromise, FnUnknownToUnknown, RecordString, ColumnsShapeBase, ColumnsParsers, PickQueryTable, BatchParsers, HookSelect, QueryLogObject, QueryLogger, QueryDataTransform, ExpressionChain, PickQueryShape, PickQueryTableMetaResult, EmptyTuple, PickQueryMeta, PickQueryMetaResultReturnType, QueryColumnToNullable, SelectableBase, PickQueryMetaShape, PickQueryTableMetaResultShape, PickQueryMetaResultWindows, PickOutputTypeAndOperators, PickQueryResult, ExpressionData, ValExpression, PickOutputType, SQLQueryArgs, ColumnSchemaConfig, DateColumnData, ColumnToCodeCtx, Code, TimeInterval, ColumnTypeSchemaArg, ColumnDataBase, ArrayMethodsData, RawSQLBase, RawSQLValues, ExpressionTypeMethod, DynamicSQLArg, StaticSQLArgs, ForeignKeyTable, ColumnNameOfTable, BaseNumberData, PickColumnBaseData, ColumnWithDefault, StringTypeData, PrimaryKeyColumn, ParseColumn, EncodeColumn, QueryColumnsInit, QueryLogOptions, DefaultSelectColumns, DbBase, QueryCatch, TransactionState, ColumnTypeBase, PickQueryUniqueProperties, PickQueryMetaResult, IsQuery, PickQueryTableMetaResultInputType, getValueKey, PickQueryResultUniqueColumns, QueryInternalBase, PickQueryReturnType, PickType, ColumnShapeOutput, OperatorsNullable, PickQueryMetaReturnType, UniqueColumn, TimestampHelpers, Codes, ColumnDataCheckBase } from 'orchid-core';
3
+ import { QueryResultRow, AdapterConfigBase, AdapterBase, QueryInput, SingleSqlItem, Sql, RecordUnknown, RecordKeyTrue, EmptyObject, QueryBaseCommon, QueryColumns, QueryMetaBase, QueryReturnType, QueryThen, Expression, MaybeArray, TemplateLiteralArgs, QueryColumn, MaybePromise, FnUnknownToUnknown, RecordString, ColumnsShapeBase, ColumnsParsers, PickQueryTable, BatchParsers, HookSelect, QueryLogObject, QueryLogger, QueryDataTransform, ExpressionChain, PickQueryShape, ColumnSchemaConfig, RawSQLBase, RawSQLValues, ExpressionTypeMethod, DynamicSQLArg, ExpressionData, StaticSQLArgs, SQLQueryArgs, PickQueryTableMetaResult, EmptyTuple, PickQueryMeta, PickQueryMetaResultReturnType, QueryColumnToNullable, SelectableBase, PickQueryMetaShape, PickQueryTableMetaResultShape, PickQueryMetaResultWindows, PickOutputTypeAndOperators, PickQueryResult, ValExpression, PickOutputType, DateColumnData, ColumnToCodeCtx, Code, TimeInterval, ColumnTypeSchemaArg, ColumnDataBase, ArrayMethodsData, ForeignKeyTable, ColumnNameOfTable, BaseNumberData, PickColumnBaseData, ColumnWithDefault, StringTypeData, PrimaryKeyColumn, ParseColumn, EncodeColumn, QueryColumnsInit, QueryLogOptions, DefaultSelectColumns, DbBase, QueryCatch, TransactionState, ColumnTypeBase, PickQueryUniqueProperties, PickQueryMetaResult, IsQuery, PickQueryTableMetaResultInputType, getValueKey, PickQueryResultUniqueColumns, QueryInternalBase, PickQueryReturnType, PickType, ColumnShapeOutput, OperatorsNullable, PickQueryMetaReturnType, UniqueColumn, TimestampHelpers, Codes, ColumnDataCheckBase } from 'orchid-core';
4
4
  import { inspect } from 'node:util';
5
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
6
 
@@ -591,6 +591,33 @@ declare class UnhandledTypeError extends OrchidOrmInternalError {
591
591
  constructor(query: Query, value: never);
592
592
  }
593
593
 
594
+ declare const templateLiteralToSQL: (template: TemplateLiteralArgs, ctx: ToSQLCtx, quotedAs?: string) => string;
595
+ declare class RawSQL<T extends QueryColumn, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>> extends RawSQLBase<T, ColumnTypes> {
596
+ columnTypes: ColumnTypes;
597
+ constructor(sql: string | TemplateLiteralArgs, values?: RawSQLValues, type?: T);
598
+ makeSQL(ctx: ToSQLCtx, quotedAs?: string): string;
599
+ }
600
+ interface DynamicRawSQL<T extends QueryColumn> extends Expression<T>, ExpressionTypeMethod {
601
+ }
602
+ declare class DynamicRawSQL<T extends QueryColumn, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>> extends Expression<T> {
603
+ fn: DynamicSQLArg<T>;
604
+ columnTypes: ColumnTypes;
605
+ result: {
606
+ value: T;
607
+ };
608
+ q: ExpressionData;
609
+ constructor(fn: DynamicSQLArg<T>);
610
+ makeSQL(ctx: ToSQLCtx, quotedAs?: string): string;
611
+ }
612
+ declare function raw<T = never>(...args: StaticSQLArgs): RawSQL<QueryColumn<T>>;
613
+ declare function raw<T = never>(...args: [DynamicSQLArg<QueryColumn<T>>]): DynamicRawSQL<QueryColumn<T>>;
614
+ declare const countSelect: RawSQL<QueryColumn<unknown, any>, DefaultColumnTypes<ColumnSchemaConfig<orchid_core.ColumnTypeBase<orchid_core.ColumnTypeSchemaArg, unknown, any, any, unknown, unknown, any, unknown, any, orchid_core.ColumnDataBase>>>>[];
615
+ declare function sqlQueryArgsToExpression(args: SQLQueryArgs): RawSQL<QueryColumn>;
616
+ interface SqlFn {
617
+ <T, Args extends [sql: TemplateStringsArray, ...values: unknown[]] | [sql: string] | [values: RecordUnknown, sql?: string]>(this: T, ...args: Args): Args extends [RecordUnknown] ? (...sql: TemplateLiteralArgs) => RawSQLBase<QueryColumn, T> : RawSQLBase<QueryColumn, T>;
618
+ }
619
+ declare const sqlFn: SqlFn;
620
+
594
621
  type WithSelectable<W extends WithDataItem> = keyof W['shape'] | `${W['table']}.${keyof W['shape'] & string}`;
595
622
  /**
596
623
  * The first argument of all `join` and `joinLateral` methods.
@@ -1719,11 +1746,13 @@ declare class ExpressionMethods {
1719
1746
  * Only for referencing a column in the query's table. For referencing joined table's columns, see [ref](#ref).
1720
1747
  *
1721
1748
  * ```ts
1749
+ * import { sql } from './baseTable';
1750
+ *
1722
1751
  * await db.table.select({
1723
1752
  * // select `("table"."id" = 1 OR "table"."name" = 'name') AS "one"`,
1724
1753
  * // returns a boolean
1725
1754
  * one: (q) =>
1726
- * q.sql<boolean>`${q.column('id')} = ${1} OR ${q.column('name')} = ${'name'}`,
1755
+ * sql<boolean>`${q.column('id')} = ${1} OR ${q.column('name')} = ${'name'}`,
1727
1756
  *
1728
1757
  * // selects the same as above, but by building a query
1729
1758
  * two: (q) => q.column('id').equals(1).or(q.column('name').equals('name')),
@@ -1738,11 +1767,13 @@ declare class ExpressionMethods {
1738
1767
  * and other dynamically defined columns.
1739
1768
  *
1740
1769
  * ```ts
1770
+ * import { sql } from './baseTable';
1771
+ *
1741
1772
  * await db.table.join('otherTable').select({
1742
1773
  * // select `("otherTable"."id" = 1 OR "otherTable"."name" = 'name') AS "one"`,
1743
1774
  * // returns a boolean
1744
1775
  * one: (q) =>
1745
- * q.sql<boolean>`${q.ref('otherTable.id')} = ${1} OR ${q.ref(
1776
+ * sql<boolean>`${q.ref('otherTable.id')} = ${1} OR ${q.ref(
1746
1777
  * 'otherTable.name',
1747
1778
  * )} = ${'name'}`,
1748
1779
  *
@@ -1890,6 +1921,8 @@ declare class Where {
1890
1921
  * Constructing `WHERE` conditions:
1891
1922
  *
1892
1923
  * ```ts
1924
+ * import { sql } from './baseTable'
1925
+ *
1893
1926
  * db.table.where({
1894
1927
  * // column of the current table
1895
1928
  * name: 'John',
@@ -1906,8 +1939,8 @@ declare class Where {
1906
1939
  * // where column equals to raw SQL
1907
1940
  * // import `sql` from your `BaseTable`
1908
1941
  * column: sql`sql expression`,
1909
- * // or use `(q) => q.sql` for the same
1910
- * column2: (q) => q.sql`sql expression`,
1942
+ * // or use `(q) => sql` for the same
1943
+ * column2: (q) => sql`sql expression`,
1911
1944
  *
1912
1945
  * // reference other columns in such a way:
1913
1946
  * firstName: (q) => q.ref('lastName'),
@@ -2667,33 +2700,6 @@ declare class JSONTextColumn<Schema extends ColumnSchemaConfig> extends ColumnTy
2667
2700
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
2668
2701
  }
2669
2702
 
2670
- declare const templateLiteralToSQL: (template: TemplateLiteralArgs, ctx: ToSQLCtx, quotedAs?: string) => string;
2671
- declare class RawSQL<T extends QueryColumn, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>> extends RawSQLBase<T, ColumnTypes> {
2672
- columnTypes: ColumnTypes;
2673
- constructor(sql: string | TemplateLiteralArgs, values?: RawSQLValues, type?: T);
2674
- makeSQL(ctx: ToSQLCtx, quotedAs?: string): string;
2675
- }
2676
- interface DynamicRawSQL<T extends QueryColumn> extends Expression<T>, ExpressionTypeMethod {
2677
- }
2678
- declare class DynamicRawSQL<T extends QueryColumn, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>> extends Expression<T> {
2679
- fn: DynamicSQLArg<T>;
2680
- columnTypes: ColumnTypes;
2681
- result: {
2682
- value: T;
2683
- };
2684
- q: ExpressionData;
2685
- constructor(fn: DynamicSQLArg<T>);
2686
- makeSQL(ctx: ToSQLCtx, quotedAs?: string): string;
2687
- }
2688
- declare function raw<T = never>(...args: StaticSQLArgs): RawSQL<QueryColumn<T>>;
2689
- declare function raw<T = never>(...args: [DynamicSQLArg<QueryColumn<T>>]): DynamicRawSQL<QueryColumn<T>>;
2690
- declare const countSelect: RawSQL<QueryColumn<unknown, any>, DefaultColumnTypes<ColumnSchemaConfig<orchid_core.ColumnTypeBase<orchid_core.ColumnTypeSchemaArg, unknown, any, any, unknown, unknown, any, unknown, any, orchid_core.ColumnDataBase>>>>[];
2691
- declare function sqlQueryArgsToExpression(args: SQLQueryArgs): RawSQL<QueryColumn>;
2692
- interface SqlFn {
2693
- <T, Args extends [sql: TemplateStringsArray, ...values: unknown[]] | [sql: string] | [values: RecordUnknown, sql?: string]>(this: T, ...args: Args): Args extends [RecordUnknown] ? (...sql: TemplateLiteralArgs) => RawSQLBase<QueryColumn, T> : RawSQLBase<QueryColumn, T>;
2694
- }
2695
- declare const sqlFn: SqlFn;
2696
-
2697
2703
  interface TableData {
2698
2704
  primaryKey?: TableData.PrimaryKey;
2699
2705
  indexes?: TableData.Index[];
@@ -2881,7 +2887,7 @@ declare abstract class IntegerBaseColumn<Schema extends ColumnSchemaConfig> exte
2881
2887
  data: NumberColumnData;
2882
2888
  constructor(schema: Schema);
2883
2889
  }
2884
- declare abstract class NumberAsStringBaseColumn<Schema extends ColumnSchemaConfig> extends ColumnType<Schema, string, ReturnType<Schema['stringSchema']>, OperatorsNumber> {
2890
+ declare abstract class NumberAsStringBaseColumn<Schema extends ColumnSchemaConfig, InputType = string | number> extends ColumnType<Schema, string, ReturnType<Schema['stringSchema']>, OperatorsNumber, InputType> {
2885
2891
  operators: OperatorsNumber;
2886
2892
  data: ColumnData;
2887
2893
  constructor(schema: Schema);
@@ -2913,7 +2919,7 @@ declare class IntegerColumn<Schema extends ColumnSchemaConfig> extends IntegerBa
2913
2919
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
2914
2920
  identity<T extends ColumnType>(this: T, options?: TableData.Identity): IdentityColumn<T>;
2915
2921
  }
2916
- declare class BigIntColumn<Schema extends ColumnSchemaConfig> extends NumberAsStringBaseColumn<Schema> {
2922
+ declare class BigIntColumn<Schema extends ColumnSchemaConfig> extends NumberAsStringBaseColumn<Schema, string | number | bigint> {
2917
2923
  dataType: "int8";
2918
2924
  constructor(schema: Schema);
2919
2925
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
@@ -3444,6 +3450,8 @@ type MapTableScopesOption<T> = T extends {
3444
3450
  interface DbResult<ColumnTypes> extends Db<string, never, never, never, never, never, ColumnTypes>, DbTableConstructor<ColumnTypes> {
3445
3451
  adapter: Adapter;
3446
3452
  close: Adapter['close'];
3453
+ sql<T = unknown>(...args: StaticSQLArgs): RawSQL<QueryColumn<T>, ColumnTypes>;
3454
+ sql<T = unknown>(...args: [DynamicSQLArg<QueryColumn<T>>]): DynamicRawSQL<QueryColumn<T>, ColumnTypes>;
3447
3455
  }
3448
3456
  /**
3449
3457
  * If you'd like to use the query builder of OrchidORM as a standalone tool, install `pqb` package and use `createDb` to initialize it.
@@ -4198,6 +4206,8 @@ declare class Create {
4198
4206
  * Each column may accept a specific value, a raw SQL, or a query that returns a single value.
4199
4207
  *
4200
4208
  * ```ts
4209
+ * import { sql } from './baseTable';
4210
+ *
4201
4211
  * const oneRecord = await db.table.create({
4202
4212
  * name: 'John',
4203
4213
  * password: '1234',
@@ -4209,7 +4219,7 @@ declare class Create {
4209
4219
  *
4210
4220
  * await db.table.create({
4211
4221
  * // raw SQL
4212
- * column1: (q) => q.sql`'John' || ' ' || 'Doe'`,
4222
+ * column1: () => sql`'John' || ' ' || 'Doe'`,
4213
4223
  *
4214
4224
  * // query that returns a single value
4215
4225
  * // returning multiple values will result in Postgres error
@@ -4614,7 +4624,7 @@ declare class OnConflictQueryBuilder<T extends CreateSelf, Arg extends OnConflic
4614
4624
  *
4615
4625
  * If the table has columns with **dynamic** default values, such values will be applied as well.
4616
4626
  *
4617
- * You can exclude certain columns from being merged by passing the `exclude` option.
4627
+ * You can exclude certain columns from being merged by passing the `except` option.
4618
4628
  *
4619
4629
  * ```ts
4620
4630
  * // merge the full data
@@ -4904,7 +4914,9 @@ declare class Having {
4904
4914
  * Arguments of the aggregate function and of the comparison can be raw SQL:
4905
4915
  *
4906
4916
  * ```ts
4907
- * db.table.having((q) => q.count(q.sql('coalesce(one, two)')).gte(q.sql`2 + 2`));
4917
+ * import { sql } from './baseTable';
4918
+ *
4919
+ * db.table.having((q) => q.count(sql('coalesce(one, two)')).gte(sql`2 + 2`));
4908
4920
  * ```
4909
4921
  *
4910
4922
  * @param args - raw SQL template string or one or multiple callbacks returning a boolean expression
@@ -5189,6 +5201,8 @@ declare class Select {
5189
5201
  * The last argument can be an object. Keys of the object are column aliases, value can be a column name, sub-query, or raw SQL expression.
5190
5202
  *
5191
5203
  * ```ts
5204
+ * import { sql } from './baseTable'
5205
+ *
5192
5206
  * // select columns of the table:
5193
5207
  * db.table.select('id', 'name', { idAlias: 'id' });
5194
5208
  *
@@ -5216,9 +5230,9 @@ declare class Select {
5216
5230
  * raw: sql`1 + 2`.type((t) => t.integer()),
5217
5231
  * });
5218
5232
  *
5219
- * // same raw SQL query as above, but raw value is returned from a callback
5233
+ * // same raw SQL query as above, but the sql is returned from a callback
5220
5234
  * db.table.select({
5221
- * raw: (q) => q.sql`1 + 2`.type((t) => t.integer()),
5235
+ * raw: () => sql`1 + 2`.type((t) => t.integer()),
5222
5236
  * });
5223
5237
  * ```
5224
5238
  *
@@ -5296,7 +5310,7 @@ declare class SqlMethod<ColumnTypes> {
5296
5310
  *
5297
5311
  * ```ts
5298
5312
  * const subQuery = db.someTable.select({
5299
- * sum: (q) => q.sql`$a + $b`.type((t) => t.decimal()).values({ a: 1, b: 2 }),
5313
+ * sum: () => sql`$a + $b`.type((t) => t.decimal()).values({ a: 1, b: 2 }),
5300
5314
  * });
5301
5315
  *
5302
5316
  * // `gt`, `gte`, `min`, `lt`, `lte`, `max` in `where`
@@ -5403,6 +5417,7 @@ declare class SqlMethod<ColumnTypes> {
5403
5417
  * sql`($one + $two) / $one`.type((t) => t.numeric()).values({ one: 1, two: 2 });
5404
5418
  * ```
5405
5419
  *
5420
+ * @deprecated use `sql` exported from the `createBaseTable` (see "define a base table" in the docs)
5406
5421
  * @param args - template literal or an object { raw: string }
5407
5422
  * @return object that has `type` and `values` methods
5408
5423
  */
@@ -5443,77 +5458,228 @@ type WithSqlResult<T extends PickQueryWithDataColumnTypes, Name extends string,
5443
5458
  };
5444
5459
  declare class WithMethods {
5445
5460
  /**
5446
- * Add Common Table Expression (CTE) to the query.
5461
+ * Use `with` to add a Common Table Expression (CTE) to the query.
5462
+ *
5463
+ * `with` can be chained to any table on `db` instance, or to `db.$queryBuilder`,
5464
+ * note that in the latter case it won't have customized column types to use for typing SQL.
5447
5465
  *
5448
5466
  * ```ts
5449
- * import { columnTypes } from 'orchid-orm';
5450
- * import { NumberColumn } from './number';
5467
+ * import { sql } from './baseTable';
5451
5468
  *
5452
- * // .with optionally accepts such options:
5453
- * type WithOptions = {
5454
- * // list of columns returned by this WITH statement
5455
- * // by default all columns from provided column shape will be included
5456
- * // true is for default behavior
5457
- * columns?: string[] | boolean;
5469
+ * // can access custom columns when using off a table
5470
+ * db.anyTable.with('x', (q) =>
5471
+ * q.select({ column: (q) => sql`123`.type((t) => t.customColumn()) }),
5472
+ * );
5458
5473
  *
5459
- * // Adds RECURSIVE keyword:
5460
- * recursive?: true;
5474
+ * // only default columns are available when using off `$queryBuilder`
5475
+ * db.$queryBuilder.with('x', (q) =>
5476
+ * q.select({ column: (q) => sql`123`.type((t) => t.integer()) }),
5477
+ * );
5478
+ * ```
5461
5479
  *
5462
- * // Adds MATERIALIZED keyword:
5463
- * materialized?: true;
5480
+ * `with` accepts query objects, callbacks returning query objects, and custom SQL expressions returned from callbacks.
5464
5481
  *
5465
- * // Adds NOT MATERIALIZED keyword:
5466
- * notMaterialized?: true;
5467
- * };
5482
+ * ```ts
5483
+ * import { sql } from './baseTable';
5468
5484
  *
5469
- * // accepts columns shape and a raw expression:
5470
- * db.table.with(
5471
- * 'alias',
5472
- * {
5473
- * id: columnTypes.integer(),
5474
- * name: columnTypes.text(3, 100),
5475
- * },
5476
- * sql`SELECT id, name FROM "someTable"`,
5477
- * );
5485
+ * db.table
5486
+ * .with(
5487
+ * 'alias',
5488
+ * // define CTE by building a query
5489
+ * db.table.select('one', 'two', 'three').where({ x: 123 }),
5490
+ * )
5491
+ * .from('alias')
5492
+ * .select('one')
5493
+ * .where({ two: 123 });
5478
5494
  *
5479
- * // accepts query:
5480
- * db.table.with('alias', db.table.all());
5495
+ * // 2nd argument can be a callback accepting a query builder
5496
+ * db.table
5497
+ * .with('alias', (q) =>
5498
+ * // select a custom sql
5499
+ * q.select({ column: (q) => sql`123`.type((t) => t.integer()) }),
5500
+ * )
5501
+ * .from('alias')
5502
+ * .select('column')
5503
+ * .where({ column: 123 });
5481
5504
  *
5482
- * // accepts a callback for a query builder:
5483
- * db.table.with('alias', (qb) =>
5484
- * qb.select({ one: sql`1`.type((t) => t.integer()) }),
5485
- * );
5505
+ * // 2nd argument can be used for options
5506
+ * db.table
5507
+ * .with(
5508
+ * 'alias',
5509
+ * {
5510
+ * // all parameters are optional
5511
+ * materialized: true,
5512
+ * notMaterialized: true,
5513
+ * },
5514
+ * db.table,
5515
+ * )
5516
+ * .from('alias');
5517
+ * ```
5486
5518
  *
5487
- * // All mentioned forms can accept options as a second argument:
5488
- * db.table.with(
5489
- * 'alias',
5490
- * {
5491
- * recursive: true,
5492
- * materialized: true,
5493
- * },
5494
- * rawOrQueryOrCallback,
5495
- * );
5519
+ * One `WITH` expression can reference the other:
5520
+ *
5521
+ * ```ts
5522
+ * db.$queryBuilder
5523
+ * .with('a', db.table.select('id', 'name'))
5524
+ * .with('b', (q) => q.from('a').where({ key: 'value' }))
5525
+ * .from('b');
5496
5526
  * ```
5497
5527
  *
5498
- * Defined `WITH` table can be used in `.from` or `.join` with all the type safeness:
5528
+ * Defined `WITH` expression can be used in `.from` or `.join` with all the type safeness:
5499
5529
  *
5500
5530
  * ```ts
5501
- * db.table.with('alias', db.table.all()).from('alias').select('alias.id');
5531
+ * db.table.with('alias', db.table).from('alias').select('alias.id');
5502
5532
  *
5503
- * db.table
5504
- * .with('alias', db.table.all())
5505
- * .join('alias', 'alias.id', 'user.id')
5506
- * .select('alias.id');
5533
+ * db.firstTable
5534
+ * .with('secondTable', db.secondTable)
5535
+ * .join('secondTable', 'secondTable.someId', 'firstTable.id')
5536
+ * .select('firstTable.column', 'secondTable.column');
5507
5537
  * ```
5508
5538
  */
5509
5539
  with<T extends PickQueryMetaWithDataColumnTypes, Name extends string, Q>(this: T, name: Name, query: Q | ((q: WithQueryBuilder<T>) => Q)): WithResult<T, Name, Q extends Query ? Q : never>;
5510
5540
  with<T extends PickQueryMetaWithDataColumnTypes, Name extends string, Q extends Query>(this: T, name: Name, options: WithArgsOptions, query: Q | ((q: WithQueryBuilder<T>) => Q)): WithResult<T, Name, Q>;
5541
+ /**
5542
+ * It is priceless for fetching tree-like structures, or any other recursive cases.
5543
+ *
5544
+ * For example, it is useful for loading a tree of categories, where one category can include many other categories.
5545
+ *
5546
+ * Similarly to [with](#with), `withRecursive` can be chained to any table or `db.$queryBuilder`.
5547
+ *
5548
+ * For the first example, consider the employee table, an employee may or may not have a manager.
5549
+ *
5550
+ * ```ts
5551
+ * class Employee extends BaseTable {
5552
+ * readonly table = 'employee';
5553
+ * columns = this.setColumns((t) => ({
5554
+ * id: t.identity().primaryKey(),
5555
+ * name: t.string(),
5556
+ * managerId: t.integer().nullable(),
5557
+ * }));
5558
+ * }
5559
+ * ```
5560
+ *
5561
+ * The task is to load all subordinates of the manager with the id 1.
5562
+ *
5563
+ * ```ts
5564
+ * db.$queryBuilder
5565
+ * .withRecursive(
5566
+ * 'subordinates',
5567
+ * // the base, anchor query: find the manager to begin recursion with
5568
+ * Employee.select('id', 'name', 'managerId').find(1),
5569
+ * // recursive query:
5570
+ * // find employees whos managerId is id from the surrounding subordinates CTE
5571
+ * (q) =>
5572
+ * q
5573
+ * .from(Employee)
5574
+ * .select('id', 'name', 'managerId')
5575
+ * .join('subordinates', 'subordinates.id', 'profile.managerId'),
5576
+ * )
5577
+ * .from('subordinates');
5578
+ * ```
5579
+ *
5580
+ * As being shown, `withRecursive` accepts one query to begin with, and a second query in a callback that can reference the surrounding table expression "subordinates".
5581
+ *
5582
+ * These two queries are joined with `UNION ALL` by default.
5583
+ *
5584
+ * You can customize it by passing options after the name.
5585
+ *
5586
+ * ```ts
5587
+ * db.$queryBuilder
5588
+ * .withRecursive(
5589
+ * 'subordinates',
5590
+ * {
5591
+ * // all parameters are optional
5592
+ * union: 'UNION',
5593
+ * materialized: true,
5594
+ * notMaterialized: true,
5595
+ * },
5596
+ * // ...snip
5597
+ * )
5598
+ * .from('subordinates');
5599
+ * ```
5600
+ *
5601
+ * Recursive query can be constructed with basic SQL instructions only, without referencing other tables.
5602
+ * In the following example, we recursively select numbers from 1 to 100, and additionally apply n > 10 filter in the end.
5603
+ *
5604
+ * ```ts
5605
+ * import { sql } from './baseTable';
5606
+ *
5607
+ * db.$queryBuilder
5608
+ * .withRecursive(
5609
+ * 't',
5610
+ * // select `1 AS n` for the base query
5611
+ * (q) => q.select({ n: (q) => sql`1`.type((t) => t.integer()) }),
5612
+ * // select `n + 1 AS n` for the recursive part
5613
+ * (q) =>
5614
+ * q
5615
+ * .from('t')
5616
+ * // type can be omitted here because it was defined in the base query
5617
+ * .select({ n: (q) => sql`n + 1` })
5618
+ * .where({ n: { lt: 100 } }),
5619
+ * )
5620
+ * .from('t')
5621
+ * .where({ n: { gt: 10 } });
5622
+ * ```
5623
+ */
5511
5624
  withRecursive<T extends PickQueryMetaWithDataColumnTypes, Name extends string, Q extends Query, Result = WithResult<T, Name, Q>>(this: T, name: Name, base: Q | ((qb: WithQueryBuilder<T>) => Q), recursive: (qb: {
5512
5625
  [K in keyof Result]: K extends 'result' ? Q['result'] : Result[K];
5513
5626
  }) => Query): Result;
5514
5627
  withRecursive<T extends PickQueryMetaWithDataColumnTypes, Name extends string, Q extends Query, Result = WithResult<T, Name, Q>>(this: T, name: Name, options: WithRecursiveOptions, base: Q | ((qb: WithQueryBuilder<T>) => Q), recursive: (qb: {
5515
5628
  [K in keyof Result]: K extends 'result' ? Q['result'] : Result[K];
5516
5629
  }) => Query): Result;
5630
+ /**
5631
+ * Use `withSql` to add a Common Table Expression (CTE) based on a custom SQL.
5632
+ *
5633
+ * Similarly to [with](#with), `withRecursive` can be chained to any table or `db.$queryBuilder`.
5634
+ *
5635
+ * ```ts
5636
+ * import { sql } from './baseTable';
5637
+ *
5638
+ * db.table
5639
+ * .withSql(
5640
+ * 'alias',
5641
+ * // define column types of the expression:
5642
+ * (t) => ({
5643
+ * one: t.integer(),
5644
+ * two: t.string(),
5645
+ * }),
5646
+ * // define SQL expression:
5647
+ * (q) => sql`(VALUES (1, 'two')) t(one, two)`,
5648
+ * )
5649
+ * // is not prefixed in the middle of a query chain
5650
+ * .withSql(
5651
+ * 'second',
5652
+ * (t) => ({
5653
+ * x: t.integer(),
5654
+ * }),
5655
+ * (q) => sql`(VALUES (1)) t(x)`,
5656
+ * )
5657
+ * .from('alias');
5658
+ * ```
5659
+ *
5660
+ * Options can be passed via a second argument:
5661
+ *
5662
+ * ```ts
5663
+ * import { sql } from './baseTable';
5664
+ *
5665
+ * db.table
5666
+ * .withSql(
5667
+ * 'alias',
5668
+ * {
5669
+ * // all parameters are optional
5670
+ * recursive: true,
5671
+ * materialized: true,
5672
+ * notMaterialized: true,
5673
+ * },
5674
+ * (t) => ({
5675
+ * one: t.integer(),
5676
+ * two: t.string(),
5677
+ * }),
5678
+ * (q) => sql`(VALUES (1, 'two')) t(one, two)`,
5679
+ * )
5680
+ * .from('alias');
5681
+ * ```
5682
+ */
5517
5683
  withSql<T extends PickQueryWithDataColumnTypes, Name extends string, Shape extends ColumnsShapeBase>(this: T, name: Name, options: WithOptions, shape: (t: T['columnTypes']) => Shape, expr: (q: T) => Expression): WithSqlResult<T, Name, Shape>;
5518
5684
  withSql<T extends PickQueryWithDataColumnTypes, Name extends string, Shape extends ColumnsShapeBase>(this: T, name: Name, shape: (t: T['columnTypes']) => Shape, expr: (q: T) => Expression): WithSqlResult<T, Name, Shape>;
5519
5685
  }
@@ -5531,13 +5697,15 @@ declare class Union {
5531
5697
  * Creates a union query, takes one or more queries or SQL expressions.
5532
5698
  *
5533
5699
  * ```ts
5700
+ * import { sql } from './baseTable';
5701
+ *
5534
5702
  * // The first query of the union
5535
5703
  * db.one
5536
5704
  * .select('id', 'name')
5537
5705
  * // add two more queries to the union
5538
5706
  * .union(
5539
5707
  * db.two.select('id', 'name'),
5540
- * (q = q.sql`SELECT id, name FROM "thirdTable"`),
5708
+ * (q = sql`SELECT id, name FROM "thirdTable"`),
5541
5709
  * )
5542
5710
  * // sub-sequent `union` is equivalent to passing multiple queries into a single `union`
5543
5711
  * .union(db.three.select('id', 'name'));
@@ -5628,10 +5796,10 @@ type UpdateArg<T extends UpdateSelf> = T['meta']['hasWhere'] extends true ? Upda
5628
5796
  type UpdateRawArgs<T extends UpdateSelf> = T['meta']['hasWhere'] extends true ? SQLQueryArgs : never;
5629
5797
  type UpdateResult<T extends UpdateSelf> = T['meta']['hasSelect'] extends true ? SetQueryKind<T, 'update'> : SetQueryReturnsRowCount<T, 'update'>;
5630
5798
  type NumericColumns<T extends PickQueryShape> = {
5631
- [K in keyof T['shape']]: T['shape'][K]['type'] extends number | null ? K : T['shape'][K] extends NumberAsStringBaseColumn<ColumnSchemaConfig> ? K : never;
5799
+ [K in keyof T['shape']]: Exclude<T['shape'][K]['queryType'], string> extends number | bigint | null ? K : never;
5632
5800
  }[keyof T['shape']];
5633
5801
  type ChangeCountArg<T extends PickQueryShape> = NumericColumns<T> | {
5634
- [K in NumericColumns<T>]?: T['shape'][K]['type'] extends number | null ? number : string;
5802
+ [K in NumericColumns<T>]?: T['shape'][K]['type'] extends number | null ? number : number | string | bigint;
5635
5803
  };
5636
5804
  interface UpdateCtx {
5637
5805
  queries?: ((queryResult: QueryResult) => Promise<void>)[];
@@ -5674,6 +5842,8 @@ declare class Update {
5674
5842
  * and [jsonRemove](/guide/advanced-queries.html#jsonremove) for a JSON column (see `jsonColumn` below).
5675
5843
  *
5676
5844
  * ```ts
5845
+ * import { sql } from './baseTable';
5846
+ *
5677
5847
  * // returns number of updated records by default
5678
5848
  * const updatedCount = await db.table
5679
5849
  * .where({ name: 'old name' })
@@ -5699,7 +5869,7 @@ declare class Update {
5699
5869
  * column1: 123,
5700
5870
  *
5701
5871
  * // use raw SQL to update the column
5702
- * column2: (q) => q.sql`2 + 2`,
5872
+ * column2: () => sql`2 + 2`,
5703
5873
  *
5704
5874
  * // use query that returns a single value
5705
5875
  * // returning multiple values will result in Postgres error