pqb 0.67.7 → 0.68.1

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
@@ -604,6 +604,17 @@ interface AfterCommitStandaloneHook {
604
604
  declare const makeConnectRetryConfig: (config: AdapterConfigConnectRetryParam) => AdapterConfigConnectRetry;
605
605
  declare const wrapAdapterFnWithConnectRetry: <Fn extends (...args: any[]) => any>(connectRetryConfig: AdapterConfigConnectRetry, fn: Fn) => Fn;
606
606
  declare const getDriverErrorCode: (err: object) => unknown;
607
+ interface SqlJoinExpression<T extends Column.Pick.QueryColumn> extends Expression<T>, ExpressionTypeMethod {}
608
+ declare class SqlJoinExpression<T extends Column.Pick.QueryColumn = Column.Pick.QueryColumn> extends Expression<T> {
609
+ items: readonly unknown[];
610
+ separator?: RawSqlBase | undefined;
611
+ result: {
612
+ value: T;
613
+ };
614
+ q: ExpressionData;
615
+ constructor(items: readonly unknown[], separator?: RawSqlBase | undefined);
616
+ makeSQL(ctx: ToSqlValues, quotedAs?: string): string;
617
+ }
607
618
  /**
608
619
  * Expression for a SQL identifier reference.
609
620
  * Used to safely quote identifiers in raw SQL queries.
@@ -5242,6 +5253,8 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
5242
5253
  then: QueryThenShallowSimplifyArr<ColumnsShape.DefaultOutput<Shape>>;
5243
5254
  windows: EmptyObject;
5244
5255
  relations: EmptyObject;
5256
+ relationsDataForCreate: EmptyObject;
5257
+ relationsDataForCreateOptional: EmptyObject;
5245
5258
  relationQueries: EmptyObject;
5246
5259
  withData: EmptyObject;
5247
5260
  error: new (message: string, length: number, name: QueryErrorName) => QueryError<this>;
@@ -5322,6 +5335,7 @@ interface DbTableConstructor<ColumnTypes> {
5322
5335
  interface DbSqlMethod<ColumnTypes> {
5323
5336
  <T>(...args: StaticSQLArgs): RawSql<Column.Pick.QueryColumnOfType<T>, ColumnTypes>;
5324
5337
  <T>(...args: [DynamicSQLArg<Column.Pick.QueryColumnOfType<T>>]): DynamicRawSQL<Column.Pick.QueryColumnOfType<T>, ColumnTypes>;
5338
+ join<T = unknown>(items: readonly unknown[], separator?: RawSqlBase): SqlJoinExpression<Column.Pick.QueryColumnOfType<T>>;
5325
5339
  ref(name: string): SqlRefExpression;
5326
5340
  unsafe(sql: string | number | boolean): UnsafeSqlExpression;
5327
5341
  }
@@ -5531,6 +5545,37 @@ declare function raw<T = never>(...args: StaticSQLArgs): RawSql<Column.Pick.Quer
5531
5545
  declare function raw<T = never>(...args: [DynamicSQLArg<Column.Pick.QueryColumnOfType<T>>]): DynamicRawSQL<Column.Pick.QueryColumnOfType<T>>;
5532
5546
  interface SqlFn {
5533
5547
  <T, Args extends TemplateLiteralArgs | [sql: string] | [values: RecordUnknown, sql?: string]>(this: T, ...args: Args): Args extends [RecordUnknown] ? (...sql: TemplateLiteralArgs) => RawSql<Column.Pick.QueryColumn, T> : RawSql<Column.Pick.QueryColumn, T>;
5548
+ /**
5549
+ * `sql.join` builds a SQL list from values and expressions.
5550
+ * Plain values are bound as query parameters, while SQL expressions render as SQL.
5551
+ *
5552
+ * Use it for SQL constructs such as `ARRAY[...]`, `IN (...)`, function arguments,
5553
+ * or tuple lists. The default separator is `, `. Provide a SQL expression as the
5554
+ * custom separator when a different separator is needed.
5555
+ *
5556
+ * ```ts
5557
+ * await db.user.whereSql`"id" IN (${sql.join([1, 2, 3])})`;
5558
+ * ```
5559
+ *
5560
+ * ```ts
5561
+ * await db.user.whereSql`
5562
+ * (${sql.join([sql.ref('name'), sql.ref('age')])}) IN (${sql.join(
5563
+ * users.map((user) => sql`(${user.name}, ${user.age})`),
5564
+ * )})
5565
+ * `;
5566
+ * ```
5567
+ *
5568
+ * ```ts
5569
+ * await db.user.select({
5570
+ * displayName: (q) =>
5571
+ * sql<string>`concat(${sql.join(
5572
+ * [q.column('firstName'), q.column('lastName')],
5573
+ * sql` || ' ' || `,
5574
+ * )})`,
5575
+ * });
5576
+ * ```
5577
+ */
5578
+ join<T = unknown>(items: readonly unknown[], separator?: RawSqlBase): SqlJoinExpression<Column.Pick.QueryColumnOfType<T>>;
5534
5579
  /**
5535
5580
  * `sql.ref` quotes a SQL identifier such as a table name, column name, or schema name.
5536
5581
  * Use it when you need to dynamically reference an identifier in raw SQL.
@@ -5790,6 +5835,8 @@ interface Base$1<Value> {
5790
5835
  __hasSelect: true;
5791
5836
  equals: Operator<Value | IsQuery | Expression, BooleanQueryColumn>;
5792
5837
  not: Operator<Value | IsQuery | Expression, BooleanQueryColumn>;
5838
+ isDistinctFrom: Operator<Value | IsQuery | Expression, BooleanQueryColumn>;
5839
+ isNotDistinctFrom: Operator<Value | IsQuery | Expression, BooleanQueryColumn>;
5793
5840
  in: Operator<Value[] | IsQuery | Expression, BooleanQueryColumn>;
5794
5841
  notIn: Operator<Value[] | IsQuery | Expression, BooleanQueryColumn>;
5795
5842
  }
@@ -6568,7 +6615,7 @@ declare namespace Column {
6568
6615
  unique: Name;
6569
6616
  };
6570
6617
  };
6571
- export type Nullable<T extends Column.Pick.ForNullable, InputSchema, OutputSchema, QuerySchema> = { [K in keyof T]: K extends '__type' ? T['__type'] | null : K extends '__inputType' ? T['__inputType'] | null : K extends 'inputSchema' ? InputSchema : K extends '__outputType' ? T['__outputType'] | (unknown extends T['__nullType'] ? null : T['__nullType']) : K extends 'outputSchema' ? OutputSchema : K extends '__queryType' ? T['__queryType'] | null : K extends 'querySchema' ? QuerySchema : K extends 'data' ? T['data'] & DataNullable : K extends 'operators' ? { [K in keyof T['operators']]: K extends 'equals' | 'not' ? Operator<T | null> : T['operators'][K] } : T[K] };
6618
+ export type Nullable<T extends Column.Pick.ForNullable, InputSchema, OutputSchema, QuerySchema> = { [K in keyof T]: K extends '__type' ? T['__type'] | null : K extends '__inputType' ? T['__inputType'] | null : K extends 'inputSchema' ? InputSchema : K extends '__outputType' ? T['__outputType'] | (unknown extends T['__nullType'] ? null : T['__nullType']) : K extends 'outputSchema' ? OutputSchema : K extends '__queryType' ? T['__queryType'] | null : K extends 'querySchema' ? QuerySchema : K extends 'data' ? T['data'] & DataNullable : K extends 'operators' ? { [K in keyof T['operators']]: K extends 'equals' | 'not' | 'isDistinctFrom' | 'isNotDistinctFrom' ? Operator<T | null> : T['operators'][K] } : T[K] };
6572
6619
  export type QueryColumnToNullable<C> = { [K in keyof C]: K extends '__outputType' | '__queryType' ? C[K] | null : C[K] };
6573
6620
  export type QueryColumnToOptional<C> = { [K in keyof C]: K extends '__outputType' ? C[K] | undefined : C[K] };
6574
6621
  interface DataNullable {
@@ -6578,6 +6625,8 @@ declare namespace Column {
6578
6625
  export interface OperatorsNullable<T> {
6579
6626
  equals: Operator<T | null>;
6580
6627
  not: Operator<T | null>;
6628
+ isDistinctFrom: Operator<T | null>;
6629
+ isNotDistinctFrom: Operator<T | null>;
6581
6630
  }
6582
6631
  export type Encode<T, InputSchema, Input> = { [K in keyof T]: K extends '__inputType' ? Input : K extends 'inputSchema' ? InputSchema : T[K] };
6583
6632
  export type Parse<T extends Pick.ForParse, OutputSchema, Output> = { [K in keyof T]: K extends '__outputType' ? null extends T['__type'] ? (Output extends null ? never : Output) | (unknown extends T['__nullType'] ? null : T['__nullType']) : Output : K extends 'outputSchema' ? null extends T['__type'] ? OutputSchema | T['nullSchema'] : OutputSchema : T[K] };
@@ -7803,13 +7852,14 @@ declare class QueryCreateFrom {
7803
7852
  */
7804
7853
  insertForEachFrom<T extends CreateSelf>(this: T, query: IsQuery): InsertManyFromResult<T>;
7805
7854
  }
7806
- interface CreateSelf extends PickQueryHasSelect, PickQueryDefaults, PickQueryResult, PickQueryRelations, PickQueryWithData, PickQueryReturnType, PickQueryShape, PickQueryUniqueProperties, PickQueryInputType, Query.Pick.IsNotReadOnly {}
7855
+ interface CreateSelf extends PickQueryHasSelect, PickQueryDefaults, PickQueryResult, PickQueryRelations, PickQueryRelationsDataForCreate, PickQueryRelationsDataForCreateOptional, PickQueryWithData, PickQueryReturnType, PickQueryShape, PickQueryUniqueProperties, PickQueryInputType, Query.Pick.IsNotReadOnly {}
7807
7856
  type CreateData<T extends CreateSelf> = EmptyObject extends T['relations'] ? CreateDataWithDefaults<T, keyof T['__defaults']> : CreateRelationsData<T>;
7808
7857
  type CreateDataWithDefaults<T extends CreateSelf, Defaults extends PropertyKey> = { [K in keyof T['__inputType'] as K extends Defaults ? never : K]: K extends Defaults ? never : CreateColumn<T, K> } & { [K in Defaults]?: K extends keyof T['__inputType'] ? CreateColumn<T, K> : never };
7809
7858
  type CreateDataWithDefaultsForRelations<T extends CreateSelf, Defaults extends keyof T['__inputType'], OmitFKeys extends PropertyKey> = { [K in keyof T['__inputType'] as K extends Defaults | OmitFKeys ? never : K]: K extends Defaults | OmitFKeys ? never : CreateColumn<T, K> } & { [K in Defaults as K extends OmitFKeys ? never : K]?: CreateColumn<T, K> };
7810
7859
  type CreateColumn<T extends CreateSelf, K extends keyof T['__inputType']> = T['__inputType'][K] | ((q: T) => QueryOrExpression<T['__inputType'][K]>);
7811
- type CreateRelationsData<T extends CreateSelf> = CreateDataWithDefaultsForRelations<T, keyof T['__defaults'], T['relations'][keyof T['relations']]['omitForeignKeyInCreate']> & CreateRelationsDataOmittingFKeys<T, T['relations'][keyof T['relations']]['dataForCreate']>;
7812
- type CreateRelationsDataOmittingFKeys<T extends CreateSelf, Union> = (Union extends RelationConfigDataForCreate ? (u: Union['columns'] extends keyof T['__defaults'] ? Pick<CreateDataWithDefaults<T, keyof T['__defaults']>, Union['columns']> & Partial<Union['nested']> : (Pick<{ [P in keyof T['__inputType']]: CreateColumn<T, P> }, Union['columns'] & keyof T['__inputType']> & { [K in keyof Union['nested']]?: never }) | Union['nested']) => void : (u: Union) => void) extends ((u: infer Obj) => void) ? Obj : never;
7860
+ type CreateRelationsData<T extends CreateSelf> = CreateDataWithDefaultsForRelations<T, keyof T['__defaults'], T['relations'][keyof T['relations']]['omitForeignKeyInCreate']> & CreateRelationsDataOmittingFKeys<T, T['relationsDataForCreate']> & T['relationsDataForCreateOptional'];
7861
+ type CreateRelationsDataOmittingFKeys<T extends CreateSelf, Data> = EmptyObject extends Data ? EmptyObject : { [K in keyof Data]: CreateRelationDataOmittingFKeys<T, Data[K]> }[keyof Data] extends ((u: infer Obj) => void) ? Obj : never;
7862
+ type CreateRelationDataOmittingFKeys<T extends CreateSelf, Union> = (u: Union extends RelationConfigDataForCreate ? Union['columns'] extends keyof T['__defaults'] ? Pick<CreateDataWithDefaults<T, keyof T['__defaults']>, Union['columns']> & Partial<Union['nested']> : (Pick<{ [P in keyof T['__inputType']]: CreateColumn<T, P> }, Union['columns'] & keyof T['__inputType']> & { [K in keyof Union['nested']]?: never }) | Union['nested'] : Union) => void;
7813
7863
  type CreateResult<T extends CreateSelf, Data> = T extends {
7814
7864
  isCount: true;
7815
7865
  } ? T : T['returnType'] extends undefined | 'all' ? SetQueryReturnsOneResult<T, NarrowCreateResult<T, Data>> : T['returnType'] extends 'pluck' ? SetQueryReturnsColumnResult<T, NarrowCreateResult<T, Data>> : SetQueryResult<T, NarrowCreateResult<T, Data>>;
@@ -10612,6 +10662,8 @@ interface Query extends IsQuery, PickQueryTable, PickQueryShape, PickQuerySelect
10612
10662
  catch: QueryCatch;
10613
10663
  windows: EmptyObject;
10614
10664
  relations: RelationsBase;
10665
+ relationsDataForCreate: RelationsDataForCreateBase;
10666
+ relationsDataForCreateOptional: RelationsDataForCreateOptionalBase;
10615
10667
  relationQueries: IsQueries;
10616
10668
  error: new (message: string, length: number, name: QueryErrorName) => QueryError;
10617
10669
  __readOnly: true | undefined;
@@ -10711,7 +10763,6 @@ interface RelationConfigBase extends IsQuery {
10711
10763
  queryRelated(params: unknown): unknown;
10712
10764
  modifyRelatedQuery?(relatedQuery: IsQuery): (query: IsQuery) => void;
10713
10765
  omitForeignKeyInCreate: PropertyKey;
10714
- dataForCreate: unknown;
10715
10766
  dataForUpdate: unknown;
10716
10767
  dataForUpdateOne: unknown;
10717
10768
  primaryKeys: string[];
@@ -10721,7 +10772,13 @@ interface RelationConfigDataForCreate {
10721
10772
  nested: RecordUnknown;
10722
10773
  }
10723
10774
  interface RelationsBase {
10724
- [K: string]: RelationConfigBase;
10775
+ [relationName: string]: RelationConfigBase;
10776
+ }
10777
+ interface RelationsDataForCreateBase {
10778
+ [relationName: string]: unknown;
10779
+ }
10780
+ interface RelationsDataForCreateOptionalBase {
10781
+ [relationName: string]: unknown;
10725
10782
  }
10726
10783
  type RelationQueryMaybeSingle<T extends RelationConfigBase> = T['returnsOne'] extends true ? T['required'] extends true ? QueryManyTake<T['query']> : QueryManyTakeOptional<T['query']> : T['query'];
10727
10784
  interface PickQueryTable {
@@ -10811,6 +10868,12 @@ interface PickQueryWindows {
10811
10868
  interface PickQueryRelations {
10812
10869
  relations: RelationsBase;
10813
10870
  }
10871
+ interface PickQueryRelationsDataForCreate {
10872
+ relationsDataForCreate: RelationsDataForCreateBase;
10873
+ }
10874
+ interface PickQueryRelationsDataForCreateOptional {
10875
+ relationsDataForCreateOptional: RelationsDataForCreateOptionalBase;
10876
+ }
10814
10877
  interface PickQueryColumTypes {
10815
10878
  columnTypes: unknown;
10816
10879
  }
package/dist/index.js CHANGED
@@ -338,6 +338,29 @@ const templateLiteralSQLToCode = (sql) => {
338
338
  code += parts[i];
339
339
  return code + "`";
340
340
  };
341
+ var SqlJoinExpression = class extends Expression {
342
+ constructor(items, separator) {
343
+ super();
344
+ this.items = items;
345
+ this.separator = separator;
346
+ this.result = { value: emptyObject };
347
+ this.q = { expr: this };
348
+ }
349
+ makeSQL(ctx, quotedAs) {
350
+ let sql = "";
351
+ for (let i = 0; i < this.items.length; i++) {
352
+ if (i > 0) sql += this.separator ? this.separator.toSQL(ctx, quotedAs) : ", ";
353
+ const item = this.items[i];
354
+ if (item instanceof Expression) sql += item.toSQL(ctx, quotedAs);
355
+ else {
356
+ ctx.values.push(item);
357
+ sql += `$${ctx.values.length}`;
358
+ }
359
+ }
360
+ return sql;
361
+ }
362
+ };
363
+ SqlJoinExpression.prototype.type = ExpressionTypeMethod.prototype.type;
341
364
  /**
342
365
  * Expression for a SQL identifier reference.
343
366
  * Used to safely quote identifiers in raw SQL queries.
@@ -458,6 +481,7 @@ const sqlFn = ((...args) => {
458
481
  return (...args) => new RawSql(args, arg);
459
482
  });
460
483
  sqlFn.ref = (name) => new SqlRefExpression(name);
484
+ sqlFn.join = (items, separator) => new SqlJoinExpression(items, separator);
461
485
  sqlFn.unsafe = (sql) => new UnsafeSqlExpression(sql);
462
486
  var UnsafeSqlExpression = class extends Expression {
463
487
  constructor(sql) {
@@ -1841,6 +1865,8 @@ const quoteLikeValue = (arg, ctx, quotedAs, jsonArray) => {
1841
1865
  const base = {
1842
1866
  equals: make((key, value, ctx, quotedAs) => value === null ? `${key} IS NULL` : `${key} = ${quoteValue(value, ctx, quotedAs)}`),
1843
1867
  not: make((key, value, ctx, quotedAs) => value === null ? `${key} IS NOT NULL` : `${key} <> ${quoteValue(value, ctx, quotedAs)}`),
1868
+ isDistinctFrom: make((key, value, ctx, quotedAs) => `${key} IS DISTINCT FROM ${quoteValue(value, ctx, quotedAs)}`),
1869
+ isNotDistinctFrom: make((key, value, ctx, quotedAs) => `${key} IS NOT DISTINCT FROM ${quoteValue(value, ctx, quotedAs)}`),
1844
1870
  in: make((key, value, ctx, quotedAs) => Array.isArray(value) && !value.length ? "false" : `${key} IN ${quoteValue(value, ctx, quotedAs, true)}`),
1845
1871
  notIn: make((key, value, ctx, quotedAs) => Array.isArray(value) && !value.length ? "true" : `NOT ${key} IN ${quoteValue(value, ctx, quotedAs, true)}`)
1846
1872
  };
@@ -1872,9 +1898,11 @@ const ordinalText = {
1872
1898
  };
1873
1899
  const encodeJsonPath = (ctx, path) => addValue(ctx.values, `{${Array.isArray(path) ? path.join(", ") : path}}`);
1874
1900
  const jsonPathQueryOp = (key, [path, options], ctx) => `jsonb_path_query_first(${key}, ${addValue(ctx.values, path)}${options?.vars ? `, ${addValue(ctx.values, JSON.stringify(options.vars))}${options.silent ? ", true" : ""}` : options?.silent ? ", NULL, true" : ""})`;
1901
+ const shouldEncodeJson = (ctx) => ctx.q.adapter.driverAdapter.schemaConfig?.jsonEncodedByDriver === false;
1875
1902
  const quoteJsonValue = (arg, ctx, quotedAs, IN) => {
1876
1903
  if (arg && typeof arg === "object") {
1877
- if (IN && Array.isArray(arg)) return `(${arg.map((value) => addValue(ctx.values, JSON.stringify(value)) + "::jsonb").join(", ")})`;
1904
+ if (IN && Array.isArray(arg)) return `(${arg.map((value) => shouldEncodeJson(ctx) ? addValue(ctx.values, JSON.stringify(value)) : addValue(ctx.values, value)).join(", ")})`;
1905
+ if (Array.isArray(arg)) return shouldEncodeJson(ctx) ? addValue(ctx.values, JSON.stringify(arg)) : addValue(ctx.values, arg);
1878
1906
  if (isExpression(arg)) return "to_jsonb(" + arg.toSQL(ctx, quotedAs) + ")";
1879
1907
  if ("toSQL" in arg) return `to_jsonb((${moveMutativeQueryToCte$1(ctx, arg)}))`;
1880
1908
  }
@@ -1899,6 +1927,8 @@ const Operators = {
1899
1927
  ...ord,
1900
1928
  equals: make((key, value, ctx, quotedAs) => value === null ? `nullif(${key}, 'null'::jsonb) IS NULL` : `${key} = ${quoteJsonValue(value, ctx, quotedAs)}`),
1901
1929
  not: make((key, value, ctx, quotedAs) => value === null ? `nullif(${key}, 'null'::jsonb) IS NOT NULL` : `${key} != ${quoteJsonValue(value, ctx, quotedAs)}`),
1930
+ isDistinctFrom: make((key, value, ctx, quotedAs) => `${key} IS DISTINCT FROM ${quoteJsonValue(value, ctx, quotedAs)}`),
1931
+ isNotDistinctFrom: make((key, value, ctx, quotedAs) => `${key} IS NOT DISTINCT FROM ${quoteJsonValue(value, ctx, quotedAs)}`),
1902
1932
  in: make((key, value, ctx, quotedAs) => Array.isArray(value) && !value.length ? "false" : `${key} IN ${quoteJsonValue(value, ctx, quotedAs, true)}`),
1903
1933
  notIn: make((key, value, ctx, quotedAs) => Array.isArray(value) && !value.length ? "true" : `NOT ${key} IN ${quoteJsonValue(value, ctx, quotedAs, true)}`),
1904
1934
  jsonPathQueryFirst: Object.assign(function(path, options) {
@@ -6514,130 +6544,75 @@ const resolveSubQueryCallback = (q, cb) => {
6514
6544
  _setSubQueryAliases(arg);
6515
6545
  return cb(arg);
6516
6546
  };
6517
- /**
6518
- * Acts as {@link simpleExistingColumnToSQL} except that the column is optional and will return quoted key if no column.
6519
- */
6520
- function simpleColumnToSQL(ctx, key, column, quotedAs) {
6521
- if (!column) return `"${key}"`;
6522
- const { data } = column;
6523
- return data.computed ? `(${data.computed.toSQL(ctx, quotedAs)})` : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
6524
- }
6525
- function simpleExistingColumnToSQL(ctx, key, column, quotedAs) {
6526
- const { data } = column;
6527
- return data.computed ? `(${data.computed.toSQL(ctx, quotedAs)})` : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
6528
- }
6529
- const columnToSql = (ctx, data, shape, column, quotedAs, select) => {
6530
- let index = column.indexOf(".");
6531
- if (index === -1) {
6532
- const joinAs = data.valuesJoinedAs?.[column];
6533
- if (joinAs) {
6534
- column = joinAs + "." + column;
6535
- index = joinAs.length;
6536
- }
6537
- }
6538
- if (index !== -1) return columnWithDotToSql(ctx, data, shape, column, index, quotedAs, select);
6539
- return simpleColumnToSQL(ctx, column, shape[column], quotedAs);
6540
- };
6541
- const selectedColumnToSql = (ctx, data, shape, column, quotedAs) => {
6542
- const index = column.indexOf(".");
6543
- return index !== -1 ? selectedColumnWithDotToSql(ctx, data, shape, column, index, quotedAs) : selectedSimpleColumnToSql(ctx, column, shape[column], quotedAs);
6544
- };
6545
- const selectedSimpleColumnToSql = (ctx, key, column, quotedAs) => {
6546
- if (!column) return `"${key}"`;
6547
- const { data } = column;
6548
- return data.selectSql ? `(${data.selectSql.toSQL(ctx, quotedAs)})` : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
6549
- };
6550
- /**
6551
- * in a case when ordering or grouping by a column which was selected as expression:
6552
- * ```ts
6553
- * table.select({ x: (q) => q.sum('x') }).group('x').order('x')
6554
- * ```
6555
- * the column must not be prefixed with a table name.
6556
- */
6557
- const maybeSelectedColumnToSql = (ctx, data, column, quotedAs) => {
6558
- const index = column.indexOf(".");
6559
- if (index !== -1) return columnWithDotToSql(ctx, data, data.shape, column, index, quotedAs);
6560
- else {
6561
- if (data.joinedShapes?.[column]) return `"${column}"."${column}"`;
6562
- if (data.select) {
6563
- for (const s of data.select) if (typeof s === "object" && "selectAs" in s) {
6564
- if (column in s.selectAs) return simpleColumnToSQL(ctx, column, data.shape[column]);
6547
+ function simpleColumnToSQL(ctx, queryData, shape, key, column, quotedAs, select, as, jsonList, useSelectList, skipSelectSql) {
6548
+ let sql;
6549
+ let dontAlias;
6550
+ if (useSelectList && queryData.select) {
6551
+ for (const s of queryData.select) if (typeof s === "object" && "selectAs" in s) {
6552
+ if (key in s.selectAs) {
6553
+ dontAlias = true;
6554
+ sql = simpleColumnToSQL(ctx, queryData, shape, key, shape[key]);
6555
+ break;
6565
6556
  }
6566
6557
  }
6567
- return simpleColumnToSQL(ctx, column, data.shape[column], quotedAs);
6568
6558
  }
6569
- };
6570
- const columnWithDotToSql = (ctx, data, shape, column, index, quotedAs, select) => {
6571
- const table = column.slice(0, index);
6572
- const key = column.slice(index + 1);
6573
- if (key === "*") {
6574
- const shape = data.joinedShapes?.[table];
6575
- return shape ? select ? makeRowToJson(ctx, table, shape, true) : `"${table}".*` : column;
6576
- }
6577
- const tableName = _getQueryAliasOrName(data, table);
6578
- const quoted = `"${table}"`;
6579
- const col = quoted === quotedAs ? shape[key] : data.joinedShapes?.[tableName]?.[key];
6580
- if (col) {
6581
- if (col.data.name) return `"${tableName}"."${col.data.name}"`;
6582
- if (col.data.computed) return `(${col.data.computed.toSQL(ctx, quoted)})`;
6583
- return `"${tableName}"."${key}"`;
6584
- }
6585
- return `"${tableName}"."${key}"`;
6586
- };
6587
- const selectedColumnWithDotToSql = (ctx, data, shape, column, index, quotedAs) => {
6588
- const table = column.slice(0, index);
6589
- const key = column.slice(index + 1);
6590
- if (key === "*") {
6591
- const shape = data.joinedShapes?.[table];
6592
- return shape ? makeRowToJson(ctx, table, shape, true) : column;
6593
- }
6594
- const tableName = _getQueryAliasOrName(data, table);
6595
- const quoted = `"${table}"`;
6596
- const col = quoted === quotedAs ? shape[key] : data.joinedShapes?.[tableName]?.[key];
6597
- if (col) {
6598
- if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quoted)})`;
6599
- if (col.data.name) return `"${tableName}"."${col.data.name}"`;
6559
+ if (!sql) if (!column) {
6560
+ dontAlias = key === as;
6561
+ sql = `${quotedAs ? `${quotedAs}.` : ""}"${key}"`;
6562
+ } else {
6563
+ if (jsonList && as) jsonList[as] = column && getSelectedColumnData(column);
6564
+ const { data } = column;
6565
+ if (select && data.selectSql && !skipSelectSql) sql = `(${data.selectSql.toSQL(ctx, quotedAs)})`;
6566
+ else if (data.computed) sql = `(${data.computed.toSQL(ctx, quotedAs)})`;
6567
+ else {
6568
+ const name = data.name || key;
6569
+ dontAlias = name === as;
6570
+ sql = `${quotedAs ? `${quotedAs}.` : ""}"${name}"`;
6571
+ }
6600
6572
  }
6601
- return `"${tableName}"."${key}"`;
6602
- };
6603
- const columnToSqlWithAs = (ctx, data, column, as, quotedAs, select, jsonList) => {
6604
- const index = column.indexOf(".");
6605
- return index !== -1 ? tableColumnToSqlWithAs(ctx, data, column, column.slice(0, index), column.slice(index + 1), as, quotedAs, select, jsonList) : ownColumnToSqlWithAs(ctx, data, column, as, quotedAs, select, jsonList);
6606
- };
6607
- const tableColumnToSqlWithAs = (ctx, data, column, table, key, as, quotedAs, select, jsonList) => {
6573
+ if (as && !dontAlias) sql = `${sql} "${as}"`;
6574
+ return sql;
6575
+ }
6576
+ const tableColumnToSql = (ctx, data, shape, table, key, quotedAs, select, as, jsonList) => {
6577
+ let sql;
6578
+ let dontAlias;
6608
6579
  if (key === "*") {
6609
- if (jsonList) jsonList[as] = void 0;
6580
+ if (jsonList && as) jsonList[as] = void 0;
6610
6581
  const shape = data.joinedShapes?.[table];
6611
- if (shape) {
6612
- if (select) return makeRowToJson(ctx, table, shape, true) + ` "${as}"`;
6613
- return `"${table}"."${table}" "${as}"`;
6582
+ if (shape) sql = select ? makeRowToJson(ctx, table, shape, true) : `"${table}".*`;
6583
+ else {
6584
+ sql = `"${table}"."${key}"`;
6585
+ dontAlias = true;
6586
+ }
6587
+ } else {
6588
+ const tableName = _getQueryAliasOrName(data, table);
6589
+ const quoted = `"${table}"`;
6590
+ const col = quoted === quotedAs ? shape[key] : data.joinedShapes?.[tableName]?.[key];
6591
+ if (jsonList && as) jsonList[as] = col && getSelectedColumnData(col);
6592
+ if (col?.data.selectSql) sql = `(${col.data.selectSql.toSQL(ctx, quoted)})`;
6593
+ else if (col?.data.name) sql = `"${tableName}"."${col.data.name}"`;
6594
+ else if (col?.data.computed) sql = `(${col.data.computed.toSQL(ctx, quoted)})`;
6595
+ else {
6596
+ sql = `"${tableName}"."${key}"`;
6597
+ dontAlias = key === as;
6614
6598
  }
6615
- return column;
6616
- }
6617
- const tableName = _getQueryAliasOrName(data, table);
6618
- const quoted = `"${table}"`;
6619
- const col = quoted === quotedAs ? data.shape[key] : data.joinedShapes?.[tableName][key];
6620
- if (jsonList) jsonList[as] = col && getSelectedColumnData(col);
6621
- if (col) {
6622
- if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quoted)}) "${as}"`;
6623
- if (col.data.name && col.data.name !== key) return `"${tableName}"."${col.data.name}" "${as}"`;
6624
6599
  }
6625
- return `"${tableName}"."${key}"${key === as ? "" : ` "${as}"`}`;
6600
+ if (as && !dontAlias) sql = `${sql} "${as}"`;
6601
+ return sql;
6626
6602
  };
6627
- const ownColumnToSqlWithAs = (ctx, data, column, as, quotedAs, select, jsonList) => {
6628
- if (!select && data.joinedShapes?.[column]) {
6629
- if (jsonList) jsonList[as] = void 0;
6630
- return `"${column}"."${column}" "${as}"`;
6631
- }
6632
- const col = data.shape[column];
6633
- if (jsonList) jsonList[as] = col && getSelectedColumnData(col);
6634
- if (col) {
6635
- if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quotedAs)}) "${as}"`;
6636
- if (col.data.name && col.data.name !== column) return `${quotedAs ? `${quotedAs}.` : ""}"${col.data.name}"${col.data.name === as ? "" : ` "${as}"`}`;
6603
+ const columnToSql = (ctx, data, shape, column, quotedAs, select, as, jsonList, useSelectList) => {
6604
+ let index = column.indexOf(".");
6605
+ if (index === -1 && !select) {
6606
+ const joinAs = data.valuesJoinedAs?.[column];
6607
+ if (joinAs) {
6608
+ column = joinAs + "." + column;
6609
+ index = joinAs.length;
6610
+ }
6637
6611
  }
6638
- return `${quotedAs ? `${quotedAs}.` : ""}"${column}"${column === as ? "" : ` "${as}"`}`;
6612
+ if (index !== -1) return tableColumnToSql(ctx, data, shape, column.slice(0, index), column.slice(index + 1), quotedAs, select, as, jsonList);
6613
+ return simpleColumnToSQL(ctx, data, shape, column, shape[column], quotedAs, select, as, jsonList, useSelectList);
6639
6614
  };
6640
- const rawOrColumnToSql = (ctx, data, expr, quotedAs, shape = data.shape, select) => {
6615
+ const rawOrColumnToSql = (ctx, data, shape, expr, quotedAs, select) => {
6641
6616
  return typeof expr === "string" ? columnToSql(ctx, data, shape, expr, quotedAs, select) : expr.toSQL(ctx, quotedAs);
6642
6617
  };
6643
6618
  const processJoinItem = (ctx, table, query, args, quotedAs) => {
@@ -6747,7 +6722,7 @@ const getConditionsFor3Or4LengthItem = (ctx, query, target, quotedAs, args, join
6747
6722
  const [leftColumn, opOrRightColumn, maybeRightColumn] = args;
6748
6723
  const op = maybeRightColumn ? opOrRightColumn : "=";
6749
6724
  const rightColumn = maybeRightColumn ? maybeRightColumn : opOrRightColumn;
6750
- return `${rawOrColumnToSql(ctx, query, leftColumn, target, joinShape)} ${op} ${rawOrColumnToSql(ctx, query, rightColumn, quotedAs, query.shape)}`;
6725
+ return `${rawOrColumnToSql(ctx, query, joinShape, leftColumn, target)} ${op} ${rawOrColumnToSql(ctx, query, query.shape, rightColumn, quotedAs)}`;
6751
6726
  };
6752
6727
  const getObjectOrRawConditions = (ctx, query, data, quotedAs, joinAs, joinShape) => {
6753
6728
  if (data === true) return "true";
@@ -6757,7 +6732,7 @@ const getObjectOrRawConditions = (ctx, query, data, quotedAs, joinAs, joinShape)
6757
6732
  const shape = query.shape;
6758
6733
  for (const key in data) {
6759
6734
  const value = data[key];
6760
- pairs.push(`${columnToSql(ctx, query, joinShape, key, joinAs)} = ${rawOrColumnToSql(ctx, query, value, quotedAs, shape)}`);
6735
+ pairs.push(`${columnToSql(ctx, query, joinShape, key, joinAs)} = ${rawOrColumnToSql(ctx, query, shape, value, quotedAs)}`);
6761
6736
  }
6762
6737
  return pairs.join(", ");
6763
6738
  }
@@ -6789,7 +6764,7 @@ var SelectItemExpression = class extends Expression {
6789
6764
  }
6790
6765
  makeSQL(ctx, quotedAs) {
6791
6766
  const q = this.q;
6792
- return typeof this.item === "string" ? this.item === "*" ? selectAllSql(q, quotedAs, void 0, ctx).join(", ") : selectedColumnToSql(ctx, q, q.shape, this.item, quotedAs) : this.item.toSQL(ctx, quotedAs);
6767
+ return typeof this.item === "string" ? this.item === "*" ? selectAllSql(q, quotedAs, void 0, ctx).join(", ") : columnToSql(ctx, q, q.shape, this.item, quotedAs, true) : this.item.toSQL(ctx, quotedAs);
6793
6768
  }
6794
6769
  };
6795
6770
  const _getSelectableColumn = (q, arg) => {
@@ -7082,13 +7057,13 @@ const selectToSqlList = (ctx, table, query, quotedAs, hookSelect = query.hookSel
7082
7057
  (selected ??= {})[key] = `"${tableName}"`;
7083
7058
  (selectedAs ??= {})[key] = key;
7084
7059
  }
7085
- sql = tableColumnToSqlWithAs(ctx, table.q, item, tableName, key, key === "*" ? tableName : key, quotedAs, true, jsonList);
7060
+ sql = tableColumnToSql(ctx, table.q, table.q.shape, tableName, key, quotedAs, true, key === "*" ? tableName : key, jsonList);
7086
7061
  } else {
7087
7062
  if (hookSelect?.get(item)) {
7088
7063
  (selected ??= {})[item] = quotedAs;
7089
7064
  (selectedAs ??= {})[item] = item;
7090
7065
  }
7091
- sql = ownColumnToSqlWithAs(ctx, table.q, item, item, quotedAs, true, jsonList);
7066
+ sql = simpleColumnToSQL(ctx, table.q, table.q.shape, item, table.q.shape[item], quotedAs, true, item, jsonList);
7092
7067
  }
7093
7068
  }
7094
7069
  list.push(sql);
@@ -7110,7 +7085,7 @@ const selectToSqlList = (ctx, table, query, quotedAs, hookSelect = query.hookSel
7110
7085
  }
7111
7086
  else if (value) {
7112
7087
  if (hookSelect) (selectedAs ??= {})[value] = as;
7113
- list.push(columnToSqlWithAs(ctx, table.q, value, as, quotedAs, true, jsonList));
7088
+ list.push(columnToSql(ctx, table.q, table.q.shape, value, quotedAs, true, as, jsonList));
7114
7089
  aliases?.push(as);
7115
7090
  }
7116
7091
  }
@@ -7146,12 +7121,12 @@ const selectToSqlList = (ctx, table, query, quotedAs, hookSelect = query.hookSel
7146
7121
  quotedTable = `"${tableName}"`;
7147
7122
  columnName = select.slice(index + 1);
7148
7123
  col = table.q.joinedShapes?.[tableName]?.[columnName];
7149
- sql = selectedColumnToSql(ctx, table.q, table.q.shape, select, void 0);
7124
+ sql = columnToSql(ctx, table.q, table.q.shape, select, void 0, true);
7150
7125
  } else {
7151
7126
  quotedTable = quotedAs;
7152
7127
  columnName = select;
7153
7128
  col = query.shape[select];
7154
- sql = selectedColumnToSql(ctx, table.q, query.shape, select, quotedAs);
7129
+ sql = columnToSql(ctx, table.q, query.shape, select, quotedAs, true);
7155
7130
  }
7156
7131
  } else {
7157
7132
  columnName = column;
@@ -7425,7 +7400,7 @@ const whereExprOrQuery = (ctx, ands, query, key, value, quotedAs) => {
7425
7400
  else {
7426
7401
  let column = query.shape[key];
7427
7402
  let quotedColumn;
7428
- if (column) quotedColumn = simpleExistingColumnToSQL(ctx, key, column, quotedAs);
7403
+ if (column) quotedColumn = simpleColumnToSQL(ctx, query, query.shape, key, column, quotedAs);
7429
7404
  else if (!column) {
7430
7405
  const index = key.indexOf(".");
7431
7406
  if (index !== -1) {
@@ -7433,7 +7408,7 @@ const whereExprOrQuery = (ctx, ands, query, key, value, quotedAs) => {
7433
7408
  const quoted = `"${table}"`;
7434
7409
  const name = key.slice(index + 1);
7435
7410
  column = quotedAs === quoted ? query.shape[name] : query.joinedShapes?.[table]?.[name];
7436
- quotedColumn = simpleColumnToSQL(ctx, name, column, quoted);
7411
+ quotedColumn = simpleColumnToSQL(ctx, query, query.shape, name, column, quoted);
7437
7412
  } else {
7438
7413
  column = query.joinedShapes?.[key]?.value;
7439
7414
  quotedColumn = `"${key}"."${key}"`;
@@ -7993,13 +7968,13 @@ const addOrder = (ctx, data, column, quotedAs, dir) => {
7993
7968
  const order = dir || (!search.order || search.order === true ? emptyObject : search.order);
7994
7969
  return `${order.coverDensity ? "ts_rank_cd" : "ts_rank"}(${order.weights ? `${addValue(ctx.values, `{${order.weights}}`)}, ` : ""}${search.vectorSQL}, "${column}"${order.normalization !== void 0 ? `, ${addValue(ctx.values, order.normalization)}` : ""}) ${order.dir || "DESC"}`;
7995
7970
  }
7996
- return `${maybeSelectedColumnToSql(ctx, data, column, quotedAs)} ${dir || "ASC"}`;
7971
+ return `${columnToSql(ctx, data, data.shape, column, quotedAs, void 0, void 0, void 0, true)} ${dir || "ASC"}`;
7997
7972
  };
7998
7973
  const windowToSql = (ctx, data, window, quotedAs) => {
7999
7974
  if (typeof window === "string") return `"${window}"`;
8000
7975
  if (isExpression(window)) return `(${window.toSQL(ctx, quotedAs)})`;
8001
7976
  const sql = [];
8002
- if (window.partitionBy) sql.push(`PARTITION BY ${Array.isArray(window.partitionBy) ? window.partitionBy.map((partitionBy) => rawOrColumnToSql(ctx, data, partitionBy, quotedAs)).join(", ") : rawOrColumnToSql(ctx, data, window.partitionBy, quotedAs)}`);
7977
+ if (window.partitionBy) sql.push(`PARTITION BY ${Array.isArray(window.partitionBy) ? window.partitionBy.map((partitionBy) => rawOrColumnToSql(ctx, data, data.shape, partitionBy, quotedAs)).join(", ") : rawOrColumnToSql(ctx, data, data.shape, window.partitionBy, quotedAs)}`);
8003
7978
  if (window.order) sql.push(`ORDER BY ${orderByToSql(ctx, data, window.order, quotedAs)}`);
8004
7979
  return `(${sql.join(" ")})`;
8005
7980
  };
@@ -8066,7 +8041,7 @@ var FnExpression = class extends Expression {
8066
8041
  const fnArgToSql = (ctx, data, arg, quotedAs) => {
8067
8042
  if (typeof arg === "string") {
8068
8043
  if (arg.endsWith(".*") || data.valuesJoinedAs?.[arg]) return columnToSql(ctx, data, data.shape, arg, quotedAs);
8069
- return selectedColumnToSql(ctx, data, data.shape, arg, quotedAs);
8044
+ return columnToSql(ctx, data, data.shape, arg, quotedAs, true);
8070
8045
  }
8071
8046
  return arg.toSQL(ctx, quotedAs);
8072
8047
  };
@@ -9421,7 +9396,7 @@ var OnConflictQueryBuilder = class {
9421
9396
  const pushDistinctSql = (ctx, table, distinct, quotedAs) => {
9422
9397
  ctx.sql.push("DISTINCT");
9423
9398
  if (distinct.length) {
9424
- const columns = distinct?.map((item) => rawOrColumnToSql(ctx, table.q, item, quotedAs));
9399
+ const columns = distinct?.map((item) => rawOrColumnToSql(ctx, table.q, table.q.shape, item, quotedAs));
9425
9400
  ctx.sql.push(`ON (${columns?.join(", ") || ""})`);
9426
9401
  }
9427
9402
  };
@@ -12331,7 +12306,7 @@ var ColumnRefExpression = class extends Expression {
12331
12306
  Object.assign(this, value.operators);
12332
12307
  }
12333
12308
  makeSQL(ctx, quotedAs) {
12334
- return simpleExistingColumnToSQL(ctx, this.name, this.result.value, quotedAs);
12309
+ return simpleColumnToSQL(ctx, emptyObject, emptyObject, this.name, this.result.value, quotedAs, void 0, void 0, void 0, void 0, true);
12335
12310
  }
12336
12311
  };
12337
12312
  var OrExpression = class extends Expression {
@@ -14260,6 +14235,7 @@ function _createDbSqlMethod(columnTypes) {
14260
14235
  return sql;
14261
14236
  });
14262
14237
  fn.ref = sqlFn.ref;
14238
+ fn.join = sqlFn.join;
14263
14239
  fn.unsafe = sqlFn.unsafe;
14264
14240
  return fn;
14265
14241
  }