orchid-orm 1.78.1 → 1.78.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Adapter, AfterCommitStandaloneHook, AfterHook, BrandColumnsShape, Column, ColumnSchemaConfig, ColumnsShape, ComputedOptionsConfig, ComputedOptionsFactory, CreateData, CreateManyMethodsNames, CreateMethodsNames, CreateSelf, DbSharedOptions, DbSqlMethod, DbTableOptionScopes, DefaultColumnTypes, DefaultSchemaConfig, DeleteMethodsNames, EmptyObject, FromArg, FromResult, Grant, IsQuery, IsolationLevel, MaybeArray, MergeQuery, PickQuerySelectableRelations, QueryAfterHook, QueryBeforeActionHook, QueryBeforeHook, QueryData, QueryHasWhere, QueryOrExpression, QueryReturnType, QuerySchema, QueryScopes, RawSqlBase, RecordUnknown, RelationConfigBase, Rls, RlsPolicy, SelectableFromShape, StorageOptions, TableData, TableDataFn, TableDataItem, TransactionOptions, UpdateData, WhereArg } from "pqb/internal";
1
+ import { Adapter, AfterCommitStandaloneHook, AfterHook, BrandColumnsShape, Column, ColumnSchemaConfig, ColumnsShape, ComputedOptionsConfig, ComputedOptionsFactory, CreateData, CreateManyMethodsNames, CreateMethodsNames, CreateSelf, DbSharedOptions, DbSqlMethod, DbTableOptionScopes, DefaultColumnTypes, DefaultSchemaConfig, DeleteMethodsNames, EmptyObject, FromArg, FromResult, Grant, IsQuery, IsolationLevel, MaybeArray, MergeQuery, PickQuerySelectableRelations, QueryAfterHook, QueryBeforeActionHook, QueryBeforeHook, QueryData, QueryHasWhere, QueryOrExpression, QueryReturnType, QuerySchema, QueryScopes, QueryTake, RawSqlBase, RecordUnknown, RelationConfigBase, Rls, RlsPolicy, SelectAsFnReturnType, SelectResultObj, SelectableFromShape, StorageOptions, TableData, TableDataFn, TableDataItem, TransactionOptions, UpdateData, WhereArg } from "pqb/internal";
2
2
  import { Db, Query } from "pqb";
3
3
  export * from "pqb";
4
4
  interface BelongsToDataForCreate<Name extends string, FK extends string, Required, Q extends Query> {
@@ -243,7 +243,7 @@ interface HasAndBelongsToManyInfo<T extends RelationConfigSelf, Name extends str
243
243
  add?: MaybeArray<WhereArg<Q>>;
244
244
  };
245
245
  }
246
- interface TableFactoryOptions<SchemaConfig extends ColumnSchemaConfig, ColumnTypes> {
246
+ interface CommonTableFactoryOptions<SchemaConfig extends ColumnSchemaConfig, ColumnTypes> {
247
247
  schemaConfig?: () => SchemaConfig;
248
248
  columnTypes?: ColumnTypes | ((t: DefaultColumnTypes<SchemaConfig>) => ColumnTypes);
249
249
  snakeCase?: boolean;
@@ -254,6 +254,14 @@ interface TableFactoryOptions<SchemaConfig extends ColumnSchemaConfig, ColumnTyp
254
254
  language?: string;
255
255
  autoForeignKeys?: boolean | TableData.References.BaseOptions;
256
256
  }
257
+ interface TableFactoryOptions<SchemaConfig extends ColumnSchemaConfig, ColumnTypes> extends CommonTableFactoryOptions<SchemaConfig, ColumnTypes> {
258
+ /** Default database schema for tables created by this factory. */
259
+ schema?: QuerySchema;
260
+ /** Default no-primary-key setting for tables created by this factory. */
261
+ noPrimaryKey?: boolean;
262
+ /** Default migration-generation ignore setting for tables created by this factory. */
263
+ generatorIgnore?: boolean;
264
+ }
257
265
  interface OrmTable<Id extends string, Table extends string, Columns extends ColumnsShape, Relations, ColumnTypes = unknown, Computed = undefined, Scopes extends RecordUnknown | undefined = undefined, SoftDelete extends true | string | undefined = undefined, SchemaConfig extends ColumnSchemaConfig = DefaultSchemaConfig, Data extends MaybeArray<TableDataItem> = never, ReadOnly extends boolean | undefined = boolean | undefined> {
258
266
  data: {
259
267
  id: Id;
@@ -447,7 +455,7 @@ declare namespace OrmTable {
447
455
  /**
448
456
  * Exclude this table from generated migration DDL reconciliation.
449
457
  */
450
- generatorIgnore?: true;
458
+ generatorIgnore?: boolean;
451
459
  /**
452
460
  * Auto-create foreign keys for relations of this table.
453
461
  */
@@ -466,6 +474,11 @@ declare namespace OrmTable {
466
474
  export interface DefineTable<SchemaConfig extends ColumnSchemaConfig, ColumnTypes> {
467
475
  <Table extends string, Columns extends ColumnsShape>(table: Table, t: (columnTypes: ColumnTypes) => Columns): OrmTable<Table, Table, Columns, undefined, ColumnTypes, undefined, undefined, undefined, SchemaConfig, never, undefined>;
468
476
  <Table extends string, const Options extends DefineTableOptions, Columns extends ColumnsShape>(table: Table, options: Options, t: (columnTypes: ColumnTypes) => Columns): OrmTable<DefineTableId<Table, Options>, Table, Columns, undefined, ColumnTypes, undefined, undefined, undefined, SchemaConfig, never, DefineTableReadOnly<Options>>;
477
+ /**
478
+ * Creates a table-definition helper with inherited factory options.
479
+ * Options provided here replace the corresponding parent options.
480
+ */
481
+ extend<ExtendedSchemaConfig extends ColumnSchemaConfig = SchemaConfig, ExtendedColumnTypes = ColumnTypes>(options: TableFactoryOptions<ExtendedSchemaConfig, ExtendedColumnTypes>): DefineTable<ExtendedSchemaConfig, ExtendedColumnTypes>;
469
482
  /**
470
483
  * Returns the file path where the table factory was defined.
471
484
  * Uses stack trace analysis to determine the caller's file path.
@@ -933,6 +946,7 @@ declare function afterCommit(this: {
933
946
  interface FromQuery extends Query {
934
947
  returnType: 'all';
935
948
  }
949
+ type OrmSelectArg = Record<string, () => SelectAsFnReturnType>;
936
950
  interface OrchidORMQueryHelper<Q extends Query, Args extends unknown[], Result> {
937
951
  <T extends Query>(q: T & {
938
952
  table: Q['table'];
@@ -1102,6 +1116,21 @@ interface OrchidORMMethods {
1102
1116
  * @param args - SQL template literal, or an object { raw: string, values?: unknown[] }
1103
1117
  */
1104
1118
  $queryArrays: Db['queryArrays'];
1119
+ /**
1120
+ * Use `$select` to select independent query and expression results in a single SQL query.
1121
+ * Each value is a callback returning a query or SQL expression. The helper returns a
1122
+ * single-result query, so it can be awaited directly or further composed.
1123
+ *
1124
+ * ```ts
1125
+ * const result = await db.$select({
1126
+ * userCount: () => db.user.count(),
1127
+ * one: () => sql<number>`1::int`,
1128
+ * });
1129
+ *
1130
+ * // { userCount: number; one: number }
1131
+ * ```
1132
+ */
1133
+ $select<Obj extends OrmSelectArg>(selection: Obj): QueryTake<SelectResultObj<Db, Obj>>;
1105
1134
  /**
1106
1135
  * See {@link FromMethods.from}
1107
1136
  */
@@ -1316,7 +1345,7 @@ interface ORMTableInput extends PickORMTableInputColumnsAndComputed {
1316
1345
  * Keep this table-like definition available at runtime, but exclude it from
1317
1346
  * generated migration DDL reconciliation.
1318
1347
  */
1319
- generatorIgnore?: true;
1348
+ generatorIgnore?: boolean;
1320
1349
  table?: string;
1321
1350
  noPrimaryKey?: boolean;
1322
1351
  name?: string;
@@ -1631,7 +1660,7 @@ interface BaseMaterializedViewInstance<ColumnTypes> extends BaseTableInstance<Co
1631
1660
  readonly materialized: true;
1632
1661
  withData?: boolean;
1633
1662
  }
1634
- declare function createBaseTable<SchemaConfig extends ColumnSchemaConfig = DefaultSchemaConfig, ColumnTypes = DefaultColumnTypes<SchemaConfig>>({ schemaConfig, columnTypes: columnTypesArg, snakeCase, filePath: filePathArg, nowSQL, exportAs, language, autoForeignKeys }?: TableFactoryOptions<SchemaConfig, ColumnTypes>): BaseTableClass<SchemaConfig, ColumnTypes>;
1663
+ declare function createBaseTable<SchemaConfig extends ColumnSchemaConfig = DefaultSchemaConfig, ColumnTypes = DefaultColumnTypes<SchemaConfig>>({ schemaConfig, columnTypes: columnTypesArg, snakeCase, filePath: filePathArg, nowSQL, exportAs, language, autoForeignKeys }?: CommonTableFactoryOptions<SchemaConfig, ColumnTypes>): BaseTableClass<SchemaConfig, ColumnTypes>;
1635
1664
  type QueryMethods<T extends Query> = Record<string, (q: T, ...args: any[]) => any>;
1636
1665
  type QueryOne<T extends Query> = { [K in keyof T]: K extends 'returnType' ? Exclude<QueryReturnType, 'all' | undefined> : T[K]; };
1637
1666
  interface MethodsBase<T extends Query> {
@@ -1648,4 +1677,4 @@ declare const createRepo: <T extends Query, Methods extends MethodsBase<T>>(tabl
1648
1677
  table: T['table'];
1649
1678
  shape: T['shape'];
1650
1679
  }>(q: Q) => Query & Q & MapMethods<T, Methods>) & T, Methods>;
1651
- export { BaseMaterializedViewInstance, BaseTableClass, BaseTableInstance, BaseViewInstance, DefaultSelect, FromQuery, Insertable, MapMethods, MapQueryMethods, MethodsBase, ORMTableInput, OrchidORM, OrchidORMBundle, OrchidORMDbTables, OrchidORMSetupOptions, OrchidORMTables, OrchidOrmParam, OrmLegacyTableForTypeHelpers, OrmTable, OrmTableForTypeHelpers, OrmTableThunks, PickORMTableComputed, PickORMTableInputColumns, PickORMTableInputColumnsAndComputed, Queryable, Repo, Selectable, SetColumnsResult, Table$1 as Table, TableClass, TableInfo, TableInstance, TableQueryBuilder, Updatable, bundleOrchidORM, bundleOrchidORMTables, createBaseTable, createRepo, createTableFactory, defineRls, makeOrchidOrmDbWithAdapter, orchidORMWithAdapter, setGrants };
1680
+ export { BaseMaterializedViewInstance, BaseTableClass, BaseTableInstance, BaseViewInstance, type CommonTableFactoryOptions, DefaultSelect, FromQuery, Insertable, MapMethods, MapQueryMethods, MethodsBase, ORMTableInput, OrchidORM, OrchidORMBundle, OrchidORMDbTables, OrchidORMSetupOptions, OrchidORMTables, OrchidOrmParam, OrmLegacyTableForTypeHelpers, OrmTable, OrmTableForTypeHelpers, OrmTableThunks, PickORMTableComputed, PickORMTableInputColumns, PickORMTableInputColumnsAndComputed, Queryable, Repo, Selectable, SetColumnsResult, Table$1 as Table, TableClass, TableFactoryOptions, TableInfo, TableInstance, TableQueryBuilder, Updatable, bundleOrchidORM, bundleOrchidORMTables, createBaseTable, createRepo, createTableFactory, defineRls, makeOrchidOrmDbWithAdapter, orchidORMWithAdapter, setGrants };
package/dist/index.js CHANGED
@@ -343,11 +343,11 @@ const createTableFactory = (options) => {
343
343
  id,
344
344
  table,
345
345
  nameInDb,
346
- schema: tableOptions?.schema,
347
- noPrimaryKey: tableOptions?.noPrimaryKey,
346
+ schema: tableOptions?.schema ?? options?.schema,
347
+ noPrimaryKey: tableOptions?.noPrimaryKey ?? options?.noPrimaryKey,
348
348
  snakeCase,
349
349
  comment: tableOptions?.comment,
350
- generatorIgnore: tableOptions?.generatorIgnore,
350
+ generatorIgnore: tableOptions?.generatorIgnore ?? options?.generatorIgnore,
351
351
  readOnly: tableOptions?.readOnly,
352
352
  columns: {
353
353
  shape,
@@ -460,6 +460,10 @@ const createTableFactory = (options) => {
460
460
  defineTable.nowSQL = options?.nowSQL;
461
461
  defineTable.snakeCase = options?.snakeCase;
462
462
  defineTable.language = options?.language;
463
+ defineTable.extend = (extendedOptions) => createTableFactory({
464
+ ...options,
465
+ ...extendedOptions
466
+ }).defineTable;
463
467
  const defineView = ((name, optionsOrT, maybeT) => {
464
468
  const viewOptions = typeof optionsOrT === "function" ? void 0 : optionsOrT;
465
469
  const materialized = viewOptions?.materialized;
@@ -587,6 +591,12 @@ const makeNestedUpdateUpsertData = (upsert, setIds) => ({
587
591
  ...setIds
588
592
  }
589
593
  });
594
+ const queryUnionAll = async (queries, indexAs) => {
595
+ const records = await queries[0].unionAll(...queries.slice(1));
596
+ const result = Array(queries.length);
597
+ for (const record of records) result[record[indexAs]] = record;
598
+ return result;
599
+ };
590
600
  const makeRawSqlPlaceholders = (length) => {
591
601
  return Array.from({ length }, () => new pqb_internal.RawSql(""));
592
602
  };
@@ -1460,22 +1470,23 @@ const nestedInsert$1 = ({ query, primaryKeys, foreignKeys }) => {
1460
1470
  let connected;
1461
1471
  if (items.length) {
1462
1472
  const queries = [];
1473
+ const indexAs = (0, pqb_internal.getFreeAlias)(t.shape, "i");
1463
1474
  for (let i = 0, len = items.length; i < len; i++) {
1464
1475
  const [selfData, { connectOrCreate }] = items[i];
1465
1476
  for (const item of connectOrCreate) {
1466
1477
  const obj = {};
1467
1478
  for (let i = 0; i < len; i++) obj[foreignKeys[i]] = selfData[primaryKeys[i]];
1468
- queries.push((0, pqb_internal._queryUpdate)(t.where(item.where), obj));
1479
+ queries.push((0, pqb_internal._querySelect)((0, pqb_internal._queryUpdate)(t.where(item.where), obj), [{ [indexAs]: new pqb_internal.RawSql(String(queries.length)) }]));
1469
1480
  }
1470
1481
  }
1471
- connected = await Promise.all(queries);
1482
+ connected = await queryUnionAll(queries, indexAs);
1472
1483
  } else connected = [];
1473
1484
  let connectedI = 0;
1474
1485
  items.length = 0;
1475
1486
  for (const item of data) if (item[1].connectOrCreate) {
1476
1487
  const length = item[1].connectOrCreate.length;
1477
1488
  connectedI += length;
1478
- for (let i = length; i > 0; i--) if (connected[connectedI - i] === 0) {
1489
+ for (let i = length; i > 0; i--) if (!connected[connectedI - i]) {
1479
1490
  items.push(item);
1480
1491
  break;
1481
1492
  }
@@ -1491,7 +1502,7 @@ const nestedInsert$1 = ({ query, primaryKeys, foreignKeys }) => {
1491
1502
  ...obj
1492
1503
  });
1493
1504
  if (connectOrCreate) {
1494
- for (const item of connectOrCreate) if (connected[connectedI++] === 0) records.push({
1505
+ for (const item of connectOrCreate) if (!connected[connectedI++]) records.push({
1495
1506
  ...item.create,
1496
1507
  ...obj
1497
1508
  });
@@ -1499,23 +1510,20 @@ const nestedInsert$1 = ({ query, primaryKeys, foreignKeys }) => {
1499
1510
  }
1500
1511
  await (0, pqb_internal._queryCreateMany)(t, records);
1501
1512
  }
1502
- items.length = 0;
1503
- for (const item of data) if (item[1].upsert) items.push(item);
1504
- if (items.length) {
1505
- const queries = [];
1506
- for (const [selfData, { upsert }] of items) {
1507
- const foreignKeyValues = {};
1508
- for (let i = 0; i < len; i++) foreignKeyValues[foreignKeys[i]] = selfData[primaryKeys[i]];
1509
- for (const item of (0, pqb_internal.toArray)(upsert)) queries.push((0, pqb_internal._queryUpsert)(t.clone().where(item.findBy), {
1510
- update: {
1511
- ...item.update,
1512
- ...foreignKeyValues
1513
- },
1514
- create: makeNestedUpdateUpsertData(item, foreignKeyValues).create
1515
- }));
1516
- }
1517
- await Promise.all(queries);
1513
+ const queries = [];
1514
+ for (const [selfData, { upsert }] of data) {
1515
+ if (!upsert) continue;
1516
+ const obj = {};
1517
+ for (let i = 0; i < len; i++) obj[foreignKeys[i]] = selfData[primaryKeys[i]];
1518
+ for (const item of (0, pqb_internal.toArray)(upsert)) queries.push((0, pqb_internal._queryUpsert)(t.clone().where(item.findBy), {
1519
+ update: {
1520
+ ...item.update,
1521
+ ...obj
1522
+ },
1523
+ create: makeNestedUpdateUpsertData(item, obj).create
1524
+ }));
1518
1525
  }
1526
+ if (queries.length) await queries[0].unionAll(...queries.slice(1));
1519
1527
  });
1520
1528
  };
1521
1529
  const hasManyCreate = (key, state, nestedInsertFn, self, ctx, items, rowIndexes, count) => {
@@ -1960,16 +1968,18 @@ const nestedInsert = ({ relatedTableQuery, joinTableQuery, primaryKeys, foreignK
1960
1968
  let connected;
1961
1969
  if (items.length) {
1962
1970
  const queries = [];
1963
- for (const [, { connect }] of items) for (const item of connect) queries.push((0, pqb_internal._queryFindBy)(t.select(...throughPrimaryKeys), item));
1964
- connected = await Promise.all(queries);
1971
+ const indexAs = (0, pqb_internal.getFreeAlias)(t.shape, "i");
1972
+ for (const [, { connect }] of items) for (const item of connect) queries.push((0, pqb_internal._queryFindBy)(t.select(...throughPrimaryKeys, { [indexAs]: new pqb_internal.RawSql(String(queries.length)) }), item));
1973
+ connected = await queryUnionAll(queries, indexAs);
1965
1974
  } else connected = [];
1966
1975
  items.length = 0;
1967
1976
  for (const item of data) if (item[1].connectOrCreate) items.push(item);
1968
1977
  let connectOrCreated;
1969
1978
  if (items.length) {
1970
1979
  const queries = [];
1971
- for (const [, { connectOrCreate }] of items) for (const item of connectOrCreate) queries.push((0, pqb_internal._queryFindByOptional)(t.select(...throughPrimaryKeys), item.where));
1972
- connectOrCreated = await Promise.all(queries);
1980
+ const indexAs = (0, pqb_internal.getFreeAlias)(t.shape, "i");
1981
+ for (const [, { connectOrCreate }] of items) for (const item of connectOrCreate) queries.push((0, pqb_internal._queryFindByOptional)(t.select(...throughPrimaryKeys, { [indexAs]: new pqb_internal.RawSql(String(queries.length)) }), item.where));
1982
+ connectOrCreated = await queryUnionAll(queries, indexAs);
1973
1983
  } else connectOrCreated = [];
1974
1984
  let connectOrCreateI = 0;
1975
1985
  items.length = 0;
@@ -2755,6 +2765,7 @@ const privateOrchidORMWithAdapter = ({ log, logger, autoPreparedStatements, noPr
2755
2765
  $withRecursive: qb.withRecursive.bind(qb),
2756
2766
  $withSql: qb.withSql.bind(qb),
2757
2767
  $from: qb.from.bind(qb),
2768
+ $select: ((selection) => qb.select(selection).take()),
2758
2769
  $close: adapter.close.bind(adapter),
2759
2770
  $withOptions: qb.withOptions.bind(qb)
2760
2771
  };