pqb 0.70.0 → 0.71.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/dist/index.d.ts CHANGED
@@ -642,7 +642,7 @@ interface ColumnSchemaGetterTableClass {
642
642
  type ColumnSchemaGetterColumns<T extends ColumnSchemaGetterTableClass> = T['prototype']['columns']['shape'];
643
643
  interface ColumnTypeSchemaArg {
644
644
  __schemaType: unknown;
645
- nullable<T extends Column.Pick.ForNullable>(this: T): Column.Modifiers.Nullable<T, unknown, unknown, unknown>;
645
+ nullable: unknown;
646
646
  encode: unknown;
647
647
  parse: unknown;
648
648
  parseNull: unknown;
@@ -1064,7 +1064,7 @@ interface NumberColumnData extends BaseNumberData, Column.Data {
1064
1064
  identity?: TableData.Identity;
1065
1065
  }
1066
1066
  interface SerialColumnData extends NumberColumnData {
1067
- default: Expression;
1067
+ default: true;
1068
1068
  }
1069
1069
  declare abstract class NumberBaseColumn<Schema extends ColumnSchemaConfig, SchemaType extends Schema['__schemaType']> extends Column {
1070
1070
  __schema: Schema;
@@ -1109,27 +1109,26 @@ declare class DecimalColumn<Schema extends ColumnSchemaConfig> extends NumberAsS
1109
1109
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1110
1110
  toSQL(): string;
1111
1111
  }
1112
- type IdentityColumn<T extends Column.Pick.Data> = Column.Modifiers.Default<T, Expression>;
1113
1112
  declare class SmallIntColumn<Schema extends ColumnSchemaConfig> extends IntegerBaseColumn<Schema> {
1114
1113
  dataType: "int2";
1115
1114
  querySchema: ReturnType<Schema['int']>;
1116
1115
  constructor(schema: Schema);
1117
1116
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1118
- identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): IdentityColumn<T>;
1117
+ identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): Column.Modifiers.HasDefault<T>;
1119
1118
  }
1120
1119
  declare class IntegerColumn<Schema extends ColumnSchemaConfig> extends IntegerBaseColumn<Schema> {
1121
1120
  dataType: "int4";
1122
1121
  querySchema: ReturnType<Schema['int']>;
1123
1122
  constructor(schema: Schema);
1124
1123
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1125
- identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): IdentityColumn<T>;
1124
+ identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): Column.Modifiers.HasDefault<T>;
1126
1125
  }
1127
1126
  declare class BigIntColumn<Schema extends ColumnSchemaConfig> extends NumberAsStringBaseColumn<Schema, string | number | bigint> {
1128
1127
  dataType: "int8";
1129
1128
  querySchema: ReturnType<Schema['stringSchema']>;
1130
1129
  constructor(schema: Schema);
1131
1130
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1132
- identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): IdentityColumn<T>;
1131
+ identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): Column.Modifiers.HasDefault<T>;
1133
1132
  }
1134
1133
  declare class RealColumn<Schema extends ColumnSchemaConfig> extends NumberBaseColumn<Schema, ReturnType<Schema['number']>> {
1135
1134
  dataType: "float4";
@@ -1332,6 +1331,7 @@ declare class JSONTextColumn<T, Schema extends ColumnTypeSchemaArg, InputSchema
1332
1331
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1333
1332
  }
1334
1333
  interface DefaultSchemaConfig extends ColumnSchemaConfig<Column> {
1334
+ nullable<T extends Column.Pick.ForNullable>(this: T): Column.Modifiers.Nullable<T>;
1335
1335
  parse<T extends Column.Pick.ForParse, Output>(this: T, fn: (input: T['__type']) => Output): Column.Modifiers.Parse<T, unknown, Output>;
1336
1336
  parseNull<T extends Column.Pick.ForParseNull, Output>(this: T, fn: () => Output): Column.Modifiers.ParseNull<T, unknown, Output>;
1337
1337
  encode<T extends Column.Pick.Type, Input>(this: T, fn: (input: Input) => unknown): Column.Modifiers.Encode<T, unknown, Input>;
@@ -1730,7 +1730,7 @@ declare class UUIDColumn<Schema extends ColumnSchemaConfig> extends Column {
1730
1730
  T & {
1731
1731
  data: {
1732
1732
  primaryKey: Name;
1733
- default: RawSqlBase;
1733
+ default: true;
1734
1734
  };
1735
1735
  };
1736
1736
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
@@ -1782,8 +1782,8 @@ declare class BooleanColumn<Schema extends ColumnSchemaConfig> extends Column {
1782
1782
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1783
1783
  }
1784
1784
  interface Timestamps<T extends Column.Pick.Data> {
1785
- createdAt: Column.Modifiers.Default<T, RawSqlBase>;
1786
- updatedAt: Column.Modifiers.Default<T, RawSqlBase>;
1785
+ createdAt: Column.Modifiers.HasDefault<T>;
1786
+ updatedAt: Column.Modifiers.HasDefault<T>;
1787
1787
  }
1788
1788
  interface TimestampHelpers {
1789
1789
  /**
@@ -1866,7 +1866,7 @@ interface DefaultColumnTypes<SchemaConfig extends ColumnSchemaConfig> extends Ti
1866
1866
  decimal: SchemaConfig['decimal'];
1867
1867
  real: SchemaConfig['real'];
1868
1868
  doublePrecision: SchemaConfig['doublePrecision'];
1869
- identity(options?: TableData.Identity): IdentityColumn<ReturnType<SchemaConfig['integer']>>;
1869
+ identity(options?: TableData.Identity): Column.Modifiers.HasDefault<ReturnType<SchemaConfig['integer']>>;
1870
1870
  smallSerial: SchemaConfig['smallSerial'];
1871
1871
  serial: SchemaConfig['serial'];
1872
1872
  bigSerial: SchemaConfig['bigSerial'];
@@ -5038,6 +5038,10 @@ interface DbTableOptions<ColumnTypes, Table extends string | undefined, Shape ex
5038
5038
  * Exclude a table-like definition from migration DDL generation.
5039
5039
  */
5040
5040
  generatorIgnore?: true | undefined;
5041
+ /**
5042
+ * Database relation name. The public `table` name remains a query alias.
5043
+ */
5044
+ nameInDb?: string;
5041
5045
  /**
5042
5046
  * Computed SQL or JS columns definitions
5043
5047
  */
@@ -5066,7 +5070,7 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
5066
5070
  } ? true : undefined;
5067
5071
  __hasSelect: boolean;
5068
5072
  __hasWhere: boolean;
5069
- __defaults: { [K in { [K in keyof Shape]: unknown extends Shape[K]['data']['default'] ? never : K }[keyof Shape]]: true };
5073
+ __defaults: { [K in { [K in keyof Shape]: Shape[K]['data']['default'] extends true ? K : never }[keyof Shape]]: true };
5070
5074
  __scopes: { [K in keyof MapTableScopesOption<Options>]: true };
5071
5075
  __defaultSelect: ColumnsShape.DefaultSelectKeys<Shape>;
5072
5076
  baseQuery: Query;
@@ -6603,7 +6607,8 @@ declare namespace Column {
6603
6607
  unique: Name;
6604
6608
  };
6605
6609
  };
6606
- 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['__queryType'] | null, T> : T['operators'][K] } : T[K] };
6610
+ export type Nullable<T extends Column.Pick.ForNullable> = { [K in keyof T]: K extends '__type' ? T['__type'] | null : K extends '__inputType' ? T['__inputType'] | null : K extends '__outputType' ? T['__outputType'] | (unknown extends T['__nullType'] ? null : T['__nullType']) : K extends '__queryType' ? T['__queryType'] | null : K extends 'data' ? T['data'] & DataNullable : K extends 'operators' ? { [K in keyof T['operators']]: K extends 'equals' | 'not' | 'isDistinctFrom' | 'isNotDistinctFrom' ? Operator<T['__queryType'] | null, T> : T['operators'][K] } : T[K] };
6611
+ export type NullableWithSchema<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['__queryType'] | null, T> : T['operators'][K] } : T[K] };
6607
6612
  export type QueryColumnToNullable<C> = { [K in keyof C]: K extends '__outputType' | '__queryType' ? C[K] | null : C[K] };
6608
6613
  export type QueryColumnToOptional<C> = { [K in keyof C]: K extends '__outputType' ? C[K] | undefined : C[K] };
6609
6614
  interface DataNullable {
@@ -6619,8 +6624,7 @@ declare namespace Column {
6619
6624
  export type Encode<T, InputSchema, Input> = { [K in keyof T]: K extends '__inputType' ? Input : K extends 'inputSchema' ? InputSchema : T[K] };
6620
6625
  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] };
6621
6626
  export type ParseNull<T extends Column.Pick.ForParseNull, NullSchema, NullType> = { [K in keyof T]: K extends '__outputType' ? null extends T['__type'] ? Exclude<T['__outputType'], null> | NullType : T['__outputType'] : K extends '__nullType' ? NullType : K extends 'outputSchema' ? null extends T['__type'] ? T['outputSchema'] | NullSchema : T['outputSchema'] : K extends 'nullSchema' ? NullSchema : T[K] };
6622
- type DefaultData<T extends Column.Data, Value> = { [K in keyof T]: K extends 'default' ? Value extends null ? never : Value : K extends 'optional' ? true : T[K] };
6623
- export type Default<T extends Column.Pick.Data, Value> = { [K in keyof T]: K extends 'data' ? DefaultData<T['data'], Value> : T[K] };
6627
+ export type HasDefault<T extends Column.Pick.Data> = T & Column.Data.Default;
6624
6628
  type DefaultSelectData<T extends Column.Data, Value> = { [K in keyof T]: K extends 'explicitSelect' ? Value extends true ? false : true : T[K] };
6625
6629
  export type DefaultSelect<T extends Column.Pick.Data, Value extends boolean> = { [K in keyof T]: K extends 'data' ? DefaultSelectData<T['data'], Value> : T[K] };
6626
6630
  export interface IsAppReadOnly {
@@ -6720,6 +6724,7 @@ declare namespace Column {
6720
6724
  interface TableParamInstance {
6721
6725
  schema?: string;
6722
6726
  table: string;
6727
+ nameInDb?: string;
6723
6728
  columns: PickQueryShape;
6724
6729
  }
6725
6730
  interface TableParam {
@@ -6811,6 +6816,12 @@ declare namespace Column {
6811
6816
  skipValueToArray?: boolean;
6812
6817
  }
6813
6818
  export namespace Data {
6819
+ interface Default {
6820
+ data: {
6821
+ default: true;
6822
+ optional: true;
6823
+ };
6824
+ }
6814
6825
  interface Check {
6815
6826
  sql: RawSqlBase;
6816
6827
  name?: string;
@@ -6837,7 +6848,7 @@ declare namespace Column {
6837
6848
  export type AsTypeArg<Schema> = AsTypeArgWithType<Schema> | AsTypeArgWithoutType<Schema>;
6838
6849
  export {};
6839
6850
  }
6840
- declare function makeColumnNullable<T extends Column.Pick.ForNullable, InputSchema, OutputSchema, QuerySchema>(column: T, inputSchema: InputSchema, outputSchema: OutputSchema, querySchema: QuerySchema): Column.Modifiers.Nullable<T, InputSchema, OutputSchema, QuerySchema>;
6851
+ declare function makeColumnNullable<T extends Column.Pick.ForNullable, InputSchema, OutputSchema, QuerySchema>(column: T, inputSchema: InputSchema, outputSchema: OutputSchema, querySchema: QuerySchema): Column.Modifiers.NullableWithSchema<T, InputSchema, OutputSchema, QuerySchema>;
6841
6852
  declare const setColumnData: <T extends Column.Pick.Data, K extends keyof T["data"]>(q: T, key: K, value: T["data"][K]) => T;
6842
6853
  declare const setDataValue: <T extends Column.Pick.Data, Key extends string, Value>(item: T, key: Key, value: Value, params?: Column.Error.StringOrMessage) => T;
6843
6854
  declare function setCurrentColumnName(name: string): void;
@@ -6887,13 +6898,13 @@ declare abstract class Column {
6887
6898
  *
6888
6899
  * @param value - default value or a function returning a value
6889
6900
  */
6890
- default<T extends Column.Pick.DataAndInputType, Value extends T['__inputType'] | null | RawSqlBase | (() => T['__inputType'])>(this: T, value: Value): Column.Modifiers.Default<T, Value>;
6901
+ default<T extends Column.Pick.DataAndInputType, Value extends T['__inputType'] | null | RawSqlBase | (() => T['__inputType'])>(this: T, value: Value): Column.Modifiers.HasDefault<T>;
6891
6902
  /**
6892
6903
  * Use `hasDefault` to let the column be omitted when creating records.
6893
6904
  *
6894
6905
  * It's better to use {@link default} instead so the value is explicit and serves as a hint.
6895
6906
  */
6896
- hasDefault<T extends Column.Pick.Data>(this: T): Column.Modifiers.Default<T, RawSqlBase>;
6907
+ hasDefault<T extends Column.Pick.Data>(this: T): Column.Modifiers.HasDefault<T>;
6897
6908
  /**
6898
6909
  * Set a database-level validation check to a column. `check` accepts a raw SQL.
6899
6910
  *
@@ -8960,6 +8971,7 @@ interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelec
8960
8971
  type: QueryType;
8961
8972
  adapter: Adapter;
8962
8973
  selectShape: ColumnsShape;
8974
+ nameInDb?: string;
8963
8975
  handleResult: HandleResult;
8964
8976
  catch?: boolean;
8965
8977
  returnType: QueryReturnType;
package/dist/index.js CHANGED
@@ -170,7 +170,7 @@ const toPascalCase = (str) => {
170
170
  * @param str - string to translate
171
171
  */
172
172
  const toSnakeCase = (str) => {
173
- return str.replace(/[A-Z]/g, (a) => `_${a.toLowerCase()}`);
173
+ return str.replace(/[A-Z]/g, (a, i) => `${i ? "_" : ""}${a.toLowerCase()}`);
174
174
  };
175
175
  /**
176
176
  * Compare two values deeply.
@@ -6625,12 +6625,12 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
6625
6625
  ctx.aliasValue = aliasValue;
6626
6626
  } else if ("j" in args) {
6627
6627
  const { j, s, r } = args;
6628
- const tableName = typeof j.q.from === "string" ? j.q.from : j.table;
6629
- const joinTable = requireTableOrStringFrom(j);
6628
+ const joinTable = j.q.nameInDb || requireTableOrStringFrom(j);
6630
6629
  target = quoteFromWithSchema(getQuerySchema$1(j), joinTable);
6631
6630
  const as = j.q.as;
6632
6631
  const joinAs = `"${as}"`;
6633
- if (as !== tableName) target += ` ${joinAs}`;
6632
+ const alias = getQueryRelationAliasForAs(j, as);
6633
+ if (alias) target += ` ${alias}`;
6634
6634
  if (r && s) target = subJoinToSql(ctx, j, `"${joinTable}"`, !forbidLateral, joinAs, true);
6635
6635
  else on = whereToSql(ctx, j, j.q, joinAs);
6636
6636
  } else if ("w" in args) {
@@ -6688,16 +6688,16 @@ const getArgQueryTarget = (ctx, first, lateral, joinSubQuery, cloned) => {
6688
6688
  const quotedFrom = typeof joinQuery.from === "string" ? `"${joinQuery.from}"` : void 0;
6689
6689
  let joinAs = quotedFrom || `"${first.table}"`;
6690
6690
  const qAs = joinQuery.as ? `"${joinQuery.as}"` : void 0;
6691
- const addAs = qAs && qAs !== joinAs;
6691
+ const aliasToAdd = getQueryRelationAliasForAs(first, joinQuery.as);
6692
6692
  if (joinSubQuery) return {
6693
6693
  target: subJoinToSql(ctx, first, joinAs, lateral, qAs, cloned),
6694
- joinAs: addAs ? qAs : joinAs
6694
+ joinAs: qAs || joinAs
6695
6695
  };
6696
6696
  else {
6697
6697
  let target = quotedFrom || quoteTableWithSchema(first);
6698
- if (addAs) {
6699
- joinAs = qAs;
6700
- target += ` ${qAs}`;
6698
+ if (aliasToAdd) {
6699
+ joinAs = aliasToAdd;
6700
+ target += ` ${aliasToAdd}`;
6701
6701
  }
6702
6702
  return {
6703
6703
  target,
@@ -7455,14 +7455,18 @@ const makeInsertSql = (ctx, q, query, quotedAs, isSubSql) => {
7455
7455
  }
7456
7456
  }
7457
7457
  const hasNonSelect = ctx.hasNonSelect;
7458
+ const returningQuotedAs = query.as ? `"${query.as}"` : quotedAs;
7459
+ const insertAlias = getQueryRelationAliasForAs(q, query.as);
7460
+ quotedAs = insertAlias || quotedAs;
7458
7461
  const sqlState = {
7459
7462
  ctx,
7460
7463
  q,
7461
7464
  query,
7462
7465
  quotedAs,
7466
+ returningQuotedAs,
7463
7467
  isSubSql,
7464
7468
  returningPos: 0,
7465
- insertSql: `INSERT INTO ${quoteTableWithSchema(q)}${quotedColumns.length ? "(" + quotedColumns.join(", ") + ")" : ""}`
7469
+ insertSql: `INSERT INTO ${quoteTableWithSchema(q)}${insertAlias ? ` AS ${insertAlias}` : ""}${quotedColumns.length ? "(" + quotedColumns.join(", ") + ")" : ""}`
7466
7470
  };
7467
7471
  ctx.sql.push(null, null);
7468
7472
  const hasOnConflictWhere = pushOnConflictSql(ctx, q, query, quotedAs, columns, quotedColumns, runtimeDefaultColumns);
@@ -7575,7 +7579,7 @@ const applySqlState = (sqlState) => {
7575
7579
  const insertSql = sqlState.selectFromSql ? sqlState.insertSql + sqlState.selectFromSql : sqlState.insertSql;
7576
7580
  const wrapInCte = getShouldWrapMainQueryInCte(ctx, sqlState.query, "insert", sqlState.isSubSql);
7577
7581
  if ("valuesSql" in sqlState) ctx.sql[1] = sqlState.valuesPrepend + sqlState.valuesSql.join(", ") + sqlState.valuesAppend;
7578
- const returning = makeReturningSql(ctx, sqlState.q, sqlState.query, sqlState.quotedAs, sqlState.relationSelectState, "Create", void 0, sqlState.isSubSql || !!ctx.topCtx.cteHooks);
7582
+ const returning = makeReturningSql(ctx, sqlState.q, sqlState.query, sqlState.returningQuotedAs, sqlState.relationSelectState, "Create", void 0, sqlState.isSubSql || !!ctx.topCtx.cteHooks);
7579
7583
  if (returning) ctx.sql[sqlState.returningPos] = "RETURNING " + returning;
7580
7584
  ctx.sql[0] = insertSql;
7581
7585
  if (wrapInCte) wrapMainQueryInCte(ctx, sqlState.query);
@@ -7736,8 +7740,9 @@ const pushUpdateSql = (ctx, query, q, quotedAs, isSubSql) => {
7736
7740
  }
7737
7741
  };
7738
7742
  const pushUpdateSqlWithoutValuesJoinedAs = (ctx, query, q, quotedAs, isSubSql) => {
7739
- const quotedTable = `"${query.table || q.from}"`;
7740
7743
  const from = quoteTableWithSchema(query);
7744
+ const alias = getQueryRelationAliasForAs(query, q.as);
7745
+ quotedAs = alias || quotedAs;
7741
7746
  const set = [];
7742
7747
  const hookSet = q.hookUpdateSet ? Object.fromEntries(q.hookUpdateSet.flatMap((item) => Object.entries(item))) : emptyObject;
7743
7748
  const relationSelectState = newMutativeQueriesSelectRelationsSqlState(query);
@@ -7752,7 +7757,7 @@ const pushUpdateSqlWithoutValuesJoinedAs = (ctx, query, q, quotedAs, isSubSql) =
7752
7757
  if (!set.length) pushSelectForEmptySet(ctx, query, q, quotedAs, from, isSubSql, updateManyValuesSql, relationSelectState);
7753
7758
  else {
7754
7759
  ctx.sql.push(`UPDATE ${from}`);
7755
- if (quotedTable !== quotedAs) ctx.sql.push(quotedAs);
7760
+ if (alias) ctx.sql.push(alias);
7756
7761
  ctx.sql.push("SET", set.join(", "));
7757
7762
  let fromWhereSql;
7758
7763
  if (updateManyValuesSql) {
@@ -7769,6 +7774,8 @@ const pushSelectForEmptySet = (ctx, query, q, quotedAs, from, isSubSql, updateMa
7769
7774
  if (!q.select) q.select = countSelect;
7770
7775
  pushUpdateReturning(ctx, query, q, quotedAs, "SELECT", relationSelectState, isSubSql);
7771
7776
  let fromSql = `FROM ${from}`;
7777
+ const alias = getQueryRelationAliasForAs(query, q.as);
7778
+ if (alias) fromSql += ` ${alias}`;
7772
7779
  if (updateManyValuesSql) fromSql += `, ${updateManyValuesSql}`;
7773
7780
  ctx.sql.push(fromSql);
7774
7781
  pushWhereStatementSql(ctx, query, q, quotedAs);
@@ -7883,7 +7890,8 @@ const throwOnDifferentColumns = (query, keysSet, row, i) => {
7883
7890
  const pushDeleteSql = (ctx, query, q, quotedAs, isSubSql) => {
7884
7891
  const from = quoteTableWithSchema(query);
7885
7892
  ctx.sql.push(`DELETE FROM ${from}`);
7886
- if (q.as && query.table !== q.as) ctx.sql.push(quotedAs);
7893
+ const alias = getQueryRelationAliasForAs(query, q.as);
7894
+ if (alias) ctx.sql.push(alias);
7887
7895
  const relationSelectState = newMutativeQueriesSelectRelationsSqlState(query);
7888
7896
  let returning = makeReturningSql(ctx, query, q, quotedAs, relationSelectState, "Delete", void 0, isSubSql);
7889
7897
  const selectRelations = handleDeleteSelectRelationsSqlState(ctx, query, relationSelectState);
@@ -9468,7 +9476,8 @@ const getFrom = (ctx, query, data, quotedAs) => {
9468
9476
  return fromToSql(ctx, query, data, from, quotedAs);
9469
9477
  }
9470
9478
  let sql = quoteTableWithSchema(query);
9471
- if (data.as && query.table !== data.as) sql += ` ${quotedAs}`;
9479
+ const alias = getQueryRelationAliasForAs(query, data.as);
9480
+ if (alias) sql += ` ${alias}`;
9472
9481
  if (data.only) sql = `ONLY ${sql}`;
9473
9482
  return sql;
9474
9483
  };
@@ -9480,7 +9489,7 @@ const fromToSql = (ctx, query, data, from, quotedAs) => {
9480
9489
  only = from.q.only;
9481
9490
  if (!from.table) sql = `(${moveMutativeQueryToCte(ctx, from)})`;
9482
9491
  else if (!checkIfASimpleQuery(from)) sql = `(${moveMutativeQueryToCte(ctx, from)}) ${quotedAs || `"${getQueryAs(from)}"`}`;
9483
- else sql = quoteTableWithSchema(from);
9492
+ else sql = quoteTableWithSchemaAndAlias(from);
9484
9493
  fromQuery = from;
9485
9494
  }
9486
9495
  else sql = quoteFromWithSchema(getQuerySchema$1(query), from);
@@ -9781,7 +9790,18 @@ const requireTableOrStringFrom = (query) => {
9781
9790
  if (!table) throw new OrchidOrmInternalError(query, "The query object does not have a table and doesn't define a `from` string");
9782
9791
  return table;
9783
9792
  };
9784
- const quoteTableWithSchema = (query) => quoteFromWithSchema(getQuerySchema$1(query), requireTableOrStringFrom(query));
9793
+ const getQueryRelationAlias = (query) => query.table && query.q.nameInDb && query.table !== query.q.nameInDb ? `"${query.table}"` : void 0;
9794
+ const getQueryRelationAliasForAs = (query, as) => {
9795
+ if (!as) return getQueryRelationAlias(query);
9796
+ const nameInDb = query.q.nameInDb || requireTableOrStringFrom(query);
9797
+ return nameInDb && as !== nameInDb ? `"${as}"` : void 0;
9798
+ };
9799
+ const quoteTableWithSchema = (query) => quoteFromWithSchema(getQuerySchema$1(query), query.q.nameInDb || requireTableOrStringFrom(query));
9800
+ const quoteTableWithSchemaAndAlias = (query) => {
9801
+ const table = quoteTableWithSchema(query);
9802
+ const alias = getQueryRelationAlias(query);
9803
+ return alias ? `${table} ${alias}` : table;
9804
+ };
9785
9805
  const quoteFromWithSchema = (schema, table) => {
9786
9806
  const s = typeof schema === "function" ? schema() : schema;
9787
9807
  return s ? `"${s}"."${table}"` : `"${table}"`;
@@ -10049,7 +10069,7 @@ const _joinLateral = (self, type, joinQuery, as, innerJoinLateral) => {
10049
10069
  const joinedAs = getQueryAs(query);
10050
10070
  setObjectValueImmutable(joinQuery.q, "joinedShapes", joinedAs, query.q.selectShape);
10051
10071
  }
10052
- const shape = getShapeFromSelect(joinQuery, true);
10072
+ const shape = joinQuery.table && joinQuery.q.joinedShapes?.[joinQuery.table] || joinQuery.q.joinedShapes?.[joinAs] || getShapeFromSelect(joinQuery, true);
10053
10073
  setObjectValueImmutable(query.q, "joinedShapes", joinAs, shape);
10054
10074
  if (joinValue) setObjectValueImmutable(query.q, "valuesJoinedAs", joinAs, joinValueAs);
10055
10075
  setObjectValueImmutable(query.q, "joinedParsers", joinValueAs || joinAs, getQueryParsers(joinQuery));
@@ -13895,6 +13915,7 @@ const performQuery = async (q, args, method) => {
13895
13915
  throw err;
13896
13916
  }
13897
13917
  };
13918
+ const getTableNameInDb = (table, nameInDb, snakeCase) => table && (nameInDb || (snakeCase ? toSnakeCase(table) : table));
13898
13919
  var Db = class extends QueryMethods {
13899
13920
  constructor(adapterNotInTransaction, qb, table = void 0, shape, columnTypes, asyncStorage, options, tableData = {}, viewData) {
13900
13921
  super();
@@ -13972,6 +13993,7 @@ var Db = class extends QueryMethods {
13972
13993
  this.q = {
13973
13994
  adapter: adapterNotInTransaction,
13974
13995
  selectShape: shape,
13996
+ nameInDb: getTableNameInDb(table, options.nameInDb, snakeCase),
13975
13997
  handleResult,
13976
13998
  logger,
13977
13999
  log: logParamToLogObject(logger, options.log),
@@ -14308,7 +14330,7 @@ const _initQueryBuilder = (adapter, columnTypes, asyncStorage, commonOptions, op
14308
14330
  const makeColumnInfoSql = (query, column) => {
14309
14331
  const values = [];
14310
14332
  const schema = getQuerySchema(query);
14311
- let text = `SELECT * FROM information_schema.columns WHERE table_name = ${addValue(values, query.table)} AND table_catalog = current_database() AND table_schema = ${schema ? addValue(values, schema) : "current_schema()"}`;
14333
+ let text = `SELECT * FROM information_schema.columns WHERE table_name = ${addValue(values, query.q.nameInDb || query.table)} AND table_catalog = current_database() AND table_schema = ${schema ? addValue(values, schema) : "current_schema()"}`;
14312
14334
  if (column) text += ` AND column_name = ${addValue(values, query.shape[column]?.data.name || column)}`;
14313
14335
  return {
14314
14336
  text,