pqb 0.70.0 → 0.71.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
@@ -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;
@@ -714,7 +714,7 @@ declare namespace TableData {
714
714
  name?: string;
715
715
  }
716
716
  export interface ColumnIndex {
717
- options: Index.ColumnArg & Index.Options;
717
+ options: Index.ColumnOptionsData;
718
718
  }
719
719
  export interface ColumnExclude extends ColumnIndex {
720
720
  with: string;
@@ -765,7 +765,11 @@ declare namespace TableData {
765
765
  order?: string;
766
766
  weight?: SearchWeight;
767
767
  }
768
- export interface UniqueOptionsArg<Name extends string = string> {
768
+ /**
769
+ * Controls when Postgres checks a unique constraint.
770
+ */
771
+ export type UniqueDeferrable = false | 'immediate' | 'deferred';
772
+ export interface BaseUniqueOptionsArg<Name extends string = string> {
769
773
  name?: Name;
770
774
  nullsNotDistinct?: boolean;
771
775
  using?: string;
@@ -775,23 +779,45 @@ declare namespace TableData {
775
779
  where?: string;
776
780
  dropMode?: DropMode;
777
781
  }
778
- export interface OptionsArg extends UniqueOptionsArg {
782
+ export interface UniqueOptionsArg<Name extends string = string> extends BaseUniqueOptionsArg<Name> {
783
+ /**
784
+ * Makes this unique definition a deferrable Postgres constraint.
785
+ */
786
+ deferrable?: UniqueDeferrable;
787
+ }
788
+ export interface NonUniqueIndexOptionsArg<Name extends string = string> extends BaseUniqueOptionsArg<Name> {
789
+ unique?: false;
790
+ deferrable?: never;
791
+ }
792
+ export interface UniqueIndexOptionsArg<Name extends string = string> extends UniqueOptionsArg<Name> {
793
+ unique: true;
794
+ }
795
+ export type OptionsArg<Name extends string = string> = NonUniqueIndexOptionsArg<Name> | UniqueIndexOptionsArg<Name>;
796
+ export type TsVectorArg = OptionsArg & TsVectorOptions;
797
+ export interface Options extends UniqueOptionsArg, TsVectorOptions {
779
798
  unique?: boolean;
780
799
  }
781
- export interface TsVectorArg extends OptionsArg, TsVectorOptions {}
782
- export type Options = TsVectorArg;
783
800
  export interface UniqueColumnArg<Name extends string = string> extends ColumnOptions, UniqueOptionsArg<Name> {
784
801
  expression?: string;
785
802
  }
786
- export interface ColumnArg extends UniqueColumnArg {
787
- unique?: boolean;
803
+ export interface NonUniqueColumnArg<Name extends string = string> extends ColumnOptions, BaseUniqueOptionsArg<Name> {
804
+ expression?: string;
805
+ unique?: false;
806
+ deferrable?: never;
807
+ }
808
+ export interface UniqueIndexColumnArg<Name extends string = string> extends UniqueColumnArg<Name> {
809
+ unique: true;
788
810
  }
811
+ export interface ColumnOptionsData extends ColumnOptions, Options {
812
+ expression?: string;
813
+ }
814
+ export type ColumnArg<Name extends string = string> = NonUniqueColumnArg<Name> | UniqueIndexColumnArg<Name>;
789
815
  interface TsVectorOptions {
790
816
  language?: string;
791
817
  languageColumn?: string;
792
818
  tsVector?: boolean;
793
819
  }
794
- export interface TsVectorColumnArg extends ColumnArg, TsVectorOptions {}
820
+ export type TsVectorColumnArg = ColumnArg & TsVectorOptions;
795
821
  export interface ExpressionOptions extends ColumnOptions {
796
822
  expression: string;
797
823
  }
@@ -1064,7 +1090,7 @@ interface NumberColumnData extends BaseNumberData, Column.Data {
1064
1090
  identity?: TableData.Identity;
1065
1091
  }
1066
1092
  interface SerialColumnData extends NumberColumnData {
1067
- default: Expression;
1093
+ default: true;
1068
1094
  }
1069
1095
  declare abstract class NumberBaseColumn<Schema extends ColumnSchemaConfig, SchemaType extends Schema['__schemaType']> extends Column {
1070
1096
  __schema: Schema;
@@ -1109,27 +1135,26 @@ declare class DecimalColumn<Schema extends ColumnSchemaConfig> extends NumberAsS
1109
1135
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1110
1136
  toSQL(): string;
1111
1137
  }
1112
- type IdentityColumn<T extends Column.Pick.Data> = Column.Modifiers.Default<T, Expression>;
1113
1138
  declare class SmallIntColumn<Schema extends ColumnSchemaConfig> extends IntegerBaseColumn<Schema> {
1114
1139
  dataType: "int2";
1115
1140
  querySchema: ReturnType<Schema['int']>;
1116
1141
  constructor(schema: Schema);
1117
1142
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1118
- identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): IdentityColumn<T>;
1143
+ identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): Column.Modifiers.HasDefault<T>;
1119
1144
  }
1120
1145
  declare class IntegerColumn<Schema extends ColumnSchemaConfig> extends IntegerBaseColumn<Schema> {
1121
1146
  dataType: "int4";
1122
1147
  querySchema: ReturnType<Schema['int']>;
1123
1148
  constructor(schema: Schema);
1124
1149
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1125
- identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): IdentityColumn<T>;
1150
+ identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): Column.Modifiers.HasDefault<T>;
1126
1151
  }
1127
1152
  declare class BigIntColumn<Schema extends ColumnSchemaConfig> extends NumberAsStringBaseColumn<Schema, string | number | bigint> {
1128
1153
  dataType: "int8";
1129
1154
  querySchema: ReturnType<Schema['stringSchema']>;
1130
1155
  constructor(schema: Schema);
1131
1156
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1132
- identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): IdentityColumn<T>;
1157
+ identity<T extends Column.Pick.Data>(this: T, options?: TableData.Identity): Column.Modifiers.HasDefault<T>;
1133
1158
  }
1134
1159
  declare class RealColumn<Schema extends ColumnSchemaConfig> extends NumberBaseColumn<Schema, ReturnType<Schema['number']>> {
1135
1160
  dataType: "float4";
@@ -1332,6 +1357,7 @@ declare class JSONTextColumn<T, Schema extends ColumnTypeSchemaArg, InputSchema
1332
1357
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1333
1358
  }
1334
1359
  interface DefaultSchemaConfig extends ColumnSchemaConfig<Column> {
1360
+ nullable<T extends Column.Pick.ForNullable>(this: T): Column.Modifiers.Nullable<T>;
1335
1361
  parse<T extends Column.Pick.ForParse, Output>(this: T, fn: (input: T['__type']) => Output): Column.Modifiers.Parse<T, unknown, Output>;
1336
1362
  parseNull<T extends Column.Pick.ForParseNull, Output>(this: T, fn: () => Output): Column.Modifiers.ParseNull<T, unknown, Output>;
1337
1363
  encode<T extends Column.Pick.Type, Input>(this: T, fn: (input: Input) => unknown): Column.Modifiers.Encode<T, unknown, Input>;
@@ -1730,7 +1756,7 @@ declare class UUIDColumn<Schema extends ColumnSchemaConfig> extends Column {
1730
1756
  T & {
1731
1757
  data: {
1732
1758
  primaryKey: Name;
1733
- default: RawSqlBase;
1759
+ default: true;
1734
1760
  };
1735
1761
  };
1736
1762
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
@@ -1782,8 +1808,8 @@ declare class BooleanColumn<Schema extends ColumnSchemaConfig> extends Column {
1782
1808
  toCode(ctx: ColumnToCodeCtx, key: string): Code;
1783
1809
  }
1784
1810
  interface Timestamps<T extends Column.Pick.Data> {
1785
- createdAt: Column.Modifiers.Default<T, RawSqlBase>;
1786
- updatedAt: Column.Modifiers.Default<T, RawSqlBase>;
1811
+ createdAt: Column.Modifiers.HasDefault<T>;
1812
+ updatedAt: Column.Modifiers.HasDefault<T>;
1787
1813
  }
1788
1814
  interface TimestampHelpers {
1789
1815
  /**
@@ -1866,7 +1892,7 @@ interface DefaultColumnTypes<SchemaConfig extends ColumnSchemaConfig> extends Ti
1866
1892
  decimal: SchemaConfig['decimal'];
1867
1893
  real: SchemaConfig['real'];
1868
1894
  doublePrecision: SchemaConfig['doublePrecision'];
1869
- identity(options?: TableData.Identity): IdentityColumn<ReturnType<SchemaConfig['integer']>>;
1895
+ identity(options?: TableData.Identity): Column.Modifiers.HasDefault<ReturnType<SchemaConfig['integer']>>;
1870
1896
  smallSerial: SchemaConfig['smallSerial'];
1871
1897
  serial: SchemaConfig['serial'];
1872
1898
  bigSerial: SchemaConfig['bigSerial'];
@@ -5038,6 +5064,10 @@ interface DbTableOptions<ColumnTypes, Table extends string | undefined, Shape ex
5038
5064
  * Exclude a table-like definition from migration DDL generation.
5039
5065
  */
5040
5066
  generatorIgnore?: true | undefined;
5067
+ /**
5068
+ * Database relation name. The public `table` name remains a query alias.
5069
+ */
5070
+ nameInDb?: string;
5041
5071
  /**
5042
5072
  * Computed SQL or JS columns definitions
5043
5073
  */
@@ -5066,7 +5096,7 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
5066
5096
  } ? true : undefined;
5067
5097
  __hasSelect: boolean;
5068
5098
  __hasWhere: boolean;
5069
- __defaults: { [K in { [K in keyof Shape]: unknown extends Shape[K]['data']['default'] ? never : K }[keyof Shape]]: true };
5099
+ __defaults: { [K in { [K in keyof Shape]: Shape[K]['data']['default'] extends true ? K : never }[keyof Shape]]: true };
5070
5100
  __scopes: { [K in keyof MapTableScopesOption<Options>]: true };
5071
5101
  __defaultSelect: ColumnsShape.DefaultSelectKeys<Shape>;
5072
5102
  baseQuery: Query;
@@ -6603,7 +6633,8 @@ declare namespace Column {
6603
6633
  unique: Name;
6604
6634
  };
6605
6635
  };
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] };
6636
+ 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] };
6637
+ 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
6638
  export type QueryColumnToNullable<C> = { [K in keyof C]: K extends '__outputType' | '__queryType' ? C[K] | null : C[K] };
6608
6639
  export type QueryColumnToOptional<C> = { [K in keyof C]: K extends '__outputType' ? C[K] | undefined : C[K] };
6609
6640
  interface DataNullable {
@@ -6619,8 +6650,7 @@ declare namespace Column {
6619
6650
  export type Encode<T, InputSchema, Input> = { [K in keyof T]: K extends '__inputType' ? Input : K extends 'inputSchema' ? InputSchema : T[K] };
6620
6651
  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
6652
  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] };
6653
+ export type HasDefault<T extends Column.Pick.Data> = T & Column.Data.Default;
6624
6654
  type DefaultSelectData<T extends Column.Data, Value> = { [K in keyof T]: K extends 'explicitSelect' ? Value extends true ? false : true : T[K] };
6625
6655
  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
6656
  export interface IsAppReadOnly {
@@ -6720,6 +6750,7 @@ declare namespace Column {
6720
6750
  interface TableParamInstance {
6721
6751
  schema?: string;
6722
6752
  table: string;
6753
+ nameInDb?: string;
6723
6754
  columns: PickQueryShape;
6724
6755
  }
6725
6756
  interface TableParam {
@@ -6811,6 +6842,12 @@ declare namespace Column {
6811
6842
  skipValueToArray?: boolean;
6812
6843
  }
6813
6844
  export namespace Data {
6845
+ interface Default {
6846
+ data: {
6847
+ default: true;
6848
+ optional: true;
6849
+ };
6850
+ }
6814
6851
  interface Check {
6815
6852
  sql: RawSqlBase;
6816
6853
  name?: string;
@@ -6837,7 +6874,7 @@ declare namespace Column {
6837
6874
  export type AsTypeArg<Schema> = AsTypeArgWithType<Schema> | AsTypeArgWithoutType<Schema>;
6838
6875
  export {};
6839
6876
  }
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>;
6877
+ 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
6878
  declare const setColumnData: <T extends Column.Pick.Data, K extends keyof T["data"]>(q: T, key: K, value: T["data"][K]) => T;
6842
6879
  declare const setDataValue: <T extends Column.Pick.Data, Key extends string, Value>(item: T, key: Key, value: Value, params?: Column.Error.StringOrMessage) => T;
6843
6880
  declare function setCurrentColumnName(name: string): void;
@@ -6887,13 +6924,13 @@ declare abstract class Column {
6887
6924
  *
6888
6925
  * @param value - default value or a function returning a value
6889
6926
  */
6890
- default<T extends Column.Pick.DataAndInputType, Value extends T['__inputType'] | null | RawSqlBase | (() => T['__inputType'])>(this: T, value: Value): Column.Modifiers.Default<T, Value>;
6927
+ default<T extends Column.Pick.DataAndInputType, Value extends T['__inputType'] | null | RawSqlBase | (() => T['__inputType'])>(this: T, value: Value): Column.Modifiers.HasDefault<T>;
6891
6928
  /**
6892
6929
  * Use `hasDefault` to let the column be omitted when creating records.
6893
6930
  *
6894
6931
  * It's better to use {@link default} instead so the value is explicit and serves as a hint.
6895
6932
  */
6896
- hasDefault<T extends Column.Pick.Data>(this: T): Column.Modifiers.Default<T, RawSqlBase>;
6933
+ hasDefault<T extends Column.Pick.Data>(this: T): Column.Modifiers.HasDefault<T>;
6897
6934
  /**
6898
6935
  * Set a database-level validation check to a column. `check` accepts a raw SQL.
6899
6936
  *
@@ -7586,7 +7623,7 @@ declare abstract class Column {
7586
7623
  data: Column['data'];
7587
7624
  dataType: string;
7588
7625
  }>(this: T, ...args: [options?: TableData.Index.TsVectorColumnArg]): T;
7589
- unique<T extends Column.Pick.Data, const Options extends TableData.Index.ColumnArg>(this: T, ...args: [options?: Options]): T & Column.Modifiers.IsUnique<Options['name'] & string>;
7626
+ unique<T extends Column.Pick.Data, const Options extends TableData.Index.UniqueColumnArg>(this: T, ...args: [options?: Options]): T & Column.Modifiers.IsUnique<Options['name'] & string>;
7590
7627
  /**
7591
7628
  * Add [EXCLUDE constraint](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-EXCLUDE) to the column.
7592
7629
  *
@@ -8960,6 +8997,7 @@ interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelec
8960
8997
  type: QueryType;
8961
8998
  adapter: Adapter;
8962
8999
  selectShape: ColumnsShape;
9000
+ nameInDb?: string;
8963
9001
  handleResult: HandleResult;
8964
9002
  catch?: boolean;
8965
9003
  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.
@@ -1436,6 +1436,7 @@ const indexInnerToCode = (index, t) => {
1436
1436
  "name",
1437
1437
  "using",
1438
1438
  "nullsNotDistinct",
1439
+ "deferrable",
1439
1440
  "include",
1440
1441
  "with",
1441
1442
  "tablespace",
@@ -1617,6 +1618,7 @@ const columnIndexesToCode = (items) => {
1617
1618
  options.using && `using: ${singleQuote(options.using)},`,
1618
1619
  options.include && `include: ${typeof options.include === "string" ? singleQuote(options.include) : `[${options.include.map(singleQuote).join(", ")}]`},`,
1619
1620
  options.nullsNotDistinct && `nullsNotDistinct: true,`,
1621
+ options.deferrable && `deferrable: ${singleQuote(options.deferrable)},`,
1620
1622
  options.with && `with: ${singleQuote(options.with)},`,
1621
1623
  options.tablespace && `tablespace: ${singleQuote(options.tablespace)},`,
1622
1624
  options.where && `where: ${singleQuote(options.where)},`
@@ -5619,20 +5621,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery, shape, whereExists,
5619
5621
  const args0 = args.length ? args[0] : returnArg;
5620
5622
  if (typeof args0 === "function") {
5621
5623
  let q = first;
5622
- if (q.joinQueryAfterCallback) {
5623
- let base = q.baseQuery;
5624
- if (q.q.as) base = base.as(q.q.as);
5625
- const { q: query } = q.joinQueryAfterCallback(base, joinTo);
5626
- if (query.and || query.or || query.scopes) {
5627
- q = _clone(q);
5628
- if (query.and) pushQueryArrayImmutable(q, "and", query.and);
5629
- if (query.or) pushQueryArrayImmutable(q, "or", query.or);
5630
- if (query.scopes) q.q.scopes = {
5631
- ...q.q.scopes,
5632
- ...query.scopes
5633
- };
5634
- }
5635
- }
5624
+ if (q.joinQueryAfterCallback) q = q.joinQueryAfterCallback(q, joinTo);
5636
5625
  const joinedShapes = {
5637
5626
  ...joinTo.q.joinedShapes,
5638
5627
  [joinTo.q.as || joinTo.table]: joinTo.shape
@@ -6625,12 +6614,12 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
6625
6614
  ctx.aliasValue = aliasValue;
6626
6615
  } else if ("j" in args) {
6627
6616
  const { j, s, r } = args;
6628
- const tableName = typeof j.q.from === "string" ? j.q.from : j.table;
6629
- const joinTable = requireTableOrStringFrom(j);
6617
+ const joinTable = j.q.nameInDb || requireTableOrStringFrom(j);
6630
6618
  target = quoteFromWithSchema(getQuerySchema$1(j), joinTable);
6631
6619
  const as = j.q.as;
6632
6620
  const joinAs = `"${as}"`;
6633
- if (as !== tableName) target += ` ${joinAs}`;
6621
+ const alias = getQueryRelationAliasForAs(j, as);
6622
+ if (alias) target += ` ${alias}`;
6634
6623
  if (r && s) target = subJoinToSql(ctx, j, `"${joinTable}"`, !forbidLateral, joinAs, true);
6635
6624
  else on = whereToSql(ctx, j, j.q, joinAs);
6636
6625
  } else if ("w" in args) {
@@ -6688,16 +6677,16 @@ const getArgQueryTarget = (ctx, first, lateral, joinSubQuery, cloned) => {
6688
6677
  const quotedFrom = typeof joinQuery.from === "string" ? `"${joinQuery.from}"` : void 0;
6689
6678
  let joinAs = quotedFrom || `"${first.table}"`;
6690
6679
  const qAs = joinQuery.as ? `"${joinQuery.as}"` : void 0;
6691
- const addAs = qAs && qAs !== joinAs;
6680
+ const aliasToAdd = getQueryRelationAliasForAs(first, joinQuery.as);
6692
6681
  if (joinSubQuery) return {
6693
6682
  target: subJoinToSql(ctx, first, joinAs, lateral, qAs, cloned),
6694
- joinAs: addAs ? qAs : joinAs
6683
+ joinAs: qAs || joinAs
6695
6684
  };
6696
6685
  else {
6697
6686
  let target = quotedFrom || quoteTableWithSchema(first);
6698
- if (addAs) {
6699
- joinAs = qAs;
6700
- target += ` ${qAs}`;
6687
+ if (aliasToAdd) {
6688
+ joinAs = aliasToAdd;
6689
+ target += ` ${aliasToAdd}`;
6701
6690
  }
6702
6691
  return {
6703
6692
  target,
@@ -7455,14 +7444,18 @@ const makeInsertSql = (ctx, q, query, quotedAs, isSubSql) => {
7455
7444
  }
7456
7445
  }
7457
7446
  const hasNonSelect = ctx.hasNonSelect;
7447
+ const returningQuotedAs = query.as ? `"${query.as}"` : quotedAs;
7448
+ const insertAlias = getQueryRelationAliasForAs(q, query.as);
7449
+ quotedAs = insertAlias || quotedAs;
7458
7450
  const sqlState = {
7459
7451
  ctx,
7460
7452
  q,
7461
7453
  query,
7462
7454
  quotedAs,
7455
+ returningQuotedAs,
7463
7456
  isSubSql,
7464
7457
  returningPos: 0,
7465
- insertSql: `INSERT INTO ${quoteTableWithSchema(q)}${quotedColumns.length ? "(" + quotedColumns.join(", ") + ")" : ""}`
7458
+ insertSql: `INSERT INTO ${quoteTableWithSchema(q)}${insertAlias ? ` AS ${insertAlias}` : ""}${quotedColumns.length ? "(" + quotedColumns.join(", ") + ")" : ""}`
7466
7459
  };
7467
7460
  ctx.sql.push(null, null);
7468
7461
  const hasOnConflictWhere = pushOnConflictSql(ctx, q, query, quotedAs, columns, quotedColumns, runtimeDefaultColumns);
@@ -7575,7 +7568,7 @@ const applySqlState = (sqlState) => {
7575
7568
  const insertSql = sqlState.selectFromSql ? sqlState.insertSql + sqlState.selectFromSql : sqlState.insertSql;
7576
7569
  const wrapInCte = getShouldWrapMainQueryInCte(ctx, sqlState.query, "insert", sqlState.isSubSql);
7577
7570
  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);
7571
+ const returning = makeReturningSql(ctx, sqlState.q, sqlState.query, sqlState.returningQuotedAs, sqlState.relationSelectState, "Create", void 0, sqlState.isSubSql || !!ctx.topCtx.cteHooks);
7579
7572
  if (returning) ctx.sql[sqlState.returningPos] = "RETURNING " + returning;
7580
7573
  ctx.sql[0] = insertSql;
7581
7574
  if (wrapInCte) wrapMainQueryInCte(ctx, sqlState.query);
@@ -7736,8 +7729,9 @@ const pushUpdateSql = (ctx, query, q, quotedAs, isSubSql) => {
7736
7729
  }
7737
7730
  };
7738
7731
  const pushUpdateSqlWithoutValuesJoinedAs = (ctx, query, q, quotedAs, isSubSql) => {
7739
- const quotedTable = `"${query.table || q.from}"`;
7740
7732
  const from = quoteTableWithSchema(query);
7733
+ const alias = getQueryRelationAliasForAs(query, q.as);
7734
+ quotedAs = alias || quotedAs;
7741
7735
  const set = [];
7742
7736
  const hookSet = q.hookUpdateSet ? Object.fromEntries(q.hookUpdateSet.flatMap((item) => Object.entries(item))) : emptyObject;
7743
7737
  const relationSelectState = newMutativeQueriesSelectRelationsSqlState(query);
@@ -7752,7 +7746,7 @@ const pushUpdateSqlWithoutValuesJoinedAs = (ctx, query, q, quotedAs, isSubSql) =
7752
7746
  if (!set.length) pushSelectForEmptySet(ctx, query, q, quotedAs, from, isSubSql, updateManyValuesSql, relationSelectState);
7753
7747
  else {
7754
7748
  ctx.sql.push(`UPDATE ${from}`);
7755
- if (quotedTable !== quotedAs) ctx.sql.push(quotedAs);
7749
+ if (alias) ctx.sql.push(alias);
7756
7750
  ctx.sql.push("SET", set.join(", "));
7757
7751
  let fromWhereSql;
7758
7752
  if (updateManyValuesSql) {
@@ -7769,6 +7763,8 @@ const pushSelectForEmptySet = (ctx, query, q, quotedAs, from, isSubSql, updateMa
7769
7763
  if (!q.select) q.select = countSelect;
7770
7764
  pushUpdateReturning(ctx, query, q, quotedAs, "SELECT", relationSelectState, isSubSql);
7771
7765
  let fromSql = `FROM ${from}`;
7766
+ const alias = getQueryRelationAliasForAs(query, q.as);
7767
+ if (alias) fromSql += ` ${alias}`;
7772
7768
  if (updateManyValuesSql) fromSql += `, ${updateManyValuesSql}`;
7773
7769
  ctx.sql.push(fromSql);
7774
7770
  pushWhereStatementSql(ctx, query, q, quotedAs);
@@ -7883,7 +7879,8 @@ const throwOnDifferentColumns = (query, keysSet, row, i) => {
7883
7879
  const pushDeleteSql = (ctx, query, q, quotedAs, isSubSql) => {
7884
7880
  const from = quoteTableWithSchema(query);
7885
7881
  ctx.sql.push(`DELETE FROM ${from}`);
7886
- if (q.as && query.table !== q.as) ctx.sql.push(quotedAs);
7882
+ const alias = getQueryRelationAliasForAs(query, q.as);
7883
+ if (alias) ctx.sql.push(alias);
7887
7884
  const relationSelectState = newMutativeQueriesSelectRelationsSqlState(query);
7888
7885
  let returning = makeReturningSql(ctx, query, q, quotedAs, relationSelectState, "Delete", void 0, isSubSql);
7889
7886
  const selectRelations = handleDeleteSelectRelationsSqlState(ctx, query, relationSelectState);
@@ -9468,7 +9465,8 @@ const getFrom = (ctx, query, data, quotedAs) => {
9468
9465
  return fromToSql(ctx, query, data, from, quotedAs);
9469
9466
  }
9470
9467
  let sql = quoteTableWithSchema(query);
9471
- if (data.as && query.table !== data.as) sql += ` ${quotedAs}`;
9468
+ const alias = getQueryRelationAliasForAs(query, data.as);
9469
+ if (alias) sql += ` ${alias}`;
9472
9470
  if (data.only) sql = `ONLY ${sql}`;
9473
9471
  return sql;
9474
9472
  };
@@ -9480,7 +9478,7 @@ const fromToSql = (ctx, query, data, from, quotedAs) => {
9480
9478
  only = from.q.only;
9481
9479
  if (!from.table) sql = `(${moveMutativeQueryToCte(ctx, from)})`;
9482
9480
  else if (!checkIfASimpleQuery(from)) sql = `(${moveMutativeQueryToCte(ctx, from)}) ${quotedAs || `"${getQueryAs(from)}"`}`;
9483
- else sql = quoteTableWithSchema(from);
9481
+ else sql = quoteTableWithSchemaAndAlias(from);
9484
9482
  fromQuery = from;
9485
9483
  }
9486
9484
  else sql = quoteFromWithSchema(getQuerySchema$1(query), from);
@@ -9781,7 +9779,18 @@ const requireTableOrStringFrom = (query) => {
9781
9779
  if (!table) throw new OrchidOrmInternalError(query, "The query object does not have a table and doesn't define a `from` string");
9782
9780
  return table;
9783
9781
  };
9784
- const quoteTableWithSchema = (query) => quoteFromWithSchema(getQuerySchema$1(query), requireTableOrStringFrom(query));
9782
+ const getQueryRelationAlias = (query) => query.table && query.q.nameInDb && query.table !== query.q.nameInDb ? `"${query.table}"` : void 0;
9783
+ const getQueryRelationAliasForAs = (query, as) => {
9784
+ if (!as) return getQueryRelationAlias(query);
9785
+ const nameInDb = query.q.nameInDb || requireTableOrStringFrom(query);
9786
+ return nameInDb && as !== nameInDb ? `"${as}"` : void 0;
9787
+ };
9788
+ const quoteTableWithSchema = (query) => quoteFromWithSchema(getQuerySchema$1(query), query.q.nameInDb || requireTableOrStringFrom(query));
9789
+ const quoteTableWithSchemaAndAlias = (query) => {
9790
+ const table = quoteTableWithSchema(query);
9791
+ const alias = getQueryRelationAlias(query);
9792
+ return alias ? `${table} ${alias}` : table;
9793
+ };
9785
9794
  const quoteFromWithSchema = (schema, table) => {
9786
9795
  const s = typeof schema === "function" ? schema() : schema;
9787
9796
  return s ? `"${s}"."${table}"` : `"${table}"`;
@@ -10049,7 +10058,7 @@ const _joinLateral = (self, type, joinQuery, as, innerJoinLateral) => {
10049
10058
  const joinedAs = getQueryAs(query);
10050
10059
  setObjectValueImmutable(joinQuery.q, "joinedShapes", joinedAs, query.q.selectShape);
10051
10060
  }
10052
- const shape = getShapeFromSelect(joinQuery, true);
10061
+ const shape = joinQuery.table && joinQuery.q.joinedShapes?.[joinQuery.table] || joinQuery.q.joinedShapes?.[joinAs] || getShapeFromSelect(joinQuery, true);
10053
10062
  setObjectValueImmutable(query.q, "joinedShapes", joinAs, shape);
10054
10063
  if (joinValue) setObjectValueImmutable(query.q, "valuesJoinedAs", joinAs, joinValueAs);
10055
10064
  setObjectValueImmutable(query.q, "joinedParsers", joinValueAs || joinAs, getQueryParsers(joinQuery));
@@ -10949,6 +10958,7 @@ const processNestedSelectPathEntry = (batches, path, thisKey, thisReturnType, i,
10949
10958
  key: thisKey
10950
10959
  });
10951
10960
  else {
10961
+ if (!data) return;
10952
10962
  const { key, returnType } = path[++i];
10953
10963
  if (!thisReturnType || thisReturnType === "all") for (const row of data) processNestedSelectPathEntry(batches, path, key, returnType, i, last, row);
10954
10964
  else processNestedSelectPathEntry(batches, path, key, returnType, i, last, data);
@@ -13895,6 +13905,7 @@ const performQuery = async (q, args, method) => {
13895
13905
  throw err;
13896
13906
  }
13897
13907
  };
13908
+ const getTableNameInDb = (table, nameInDb, snakeCase) => table && (nameInDb || (snakeCase ? toSnakeCase(table) : table));
13898
13909
  var Db = class extends QueryMethods {
13899
13910
  constructor(adapterNotInTransaction, qb, table = void 0, shape, columnTypes, asyncStorage, options, tableData = {}, viewData) {
13900
13911
  super();
@@ -13972,6 +13983,7 @@ var Db = class extends QueryMethods {
13972
13983
  this.q = {
13973
13984
  adapter: adapterNotInTransaction,
13974
13985
  selectShape: shape,
13986
+ nameInDb: getTableNameInDb(table, options.nameInDb, snakeCase),
13975
13987
  handleResult,
13976
13988
  logger,
13977
13989
  log: logParamToLogObject(logger, options.log),
@@ -14308,7 +14320,7 @@ const _initQueryBuilder = (adapter, columnTypes, asyncStorage, commonOptions, op
14308
14320
  const makeColumnInfoSql = (query, column) => {
14309
14321
  const values = [];
14310
14322
  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()"}`;
14323
+ 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
14324
  if (column) text += ` AND column_name = ${addValue(values, query.shape[column]?.data.name || column)}`;
14313
14325
  return {
14314
14326
  text,