orchid-orm 1.65.0 → 1.66.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
@@ -1,4 +1,5 @@
1
- import { Column, TableData, ColumnsShape, Query, SelectableFromShape, CreateManyMethodsNames, QueryHasWhere, RelationConfigBase, QueryManyTake, QueryManyTakeOptional, EmptyObject, CreateData, UpdateData, WhereArg, CreateMethodsNames, MaybeArray, JoinQueryMethod, DeleteMethodsNames, Db, IsolationLevel, TransactionOptions, AfterCommitStandaloneHook, AdapterBase, FromArg, FromResult, StorageOptions, DbSharedOptions, QuerySchema, ShapeColumnPrimaryKeys, ShapeUniqueColumns, TableDataItemsUniqueColumns, TableDataItemsUniqueColumnTuples, UniqueConstraints, TableDataItemsUniqueConstraints, ComputedColumnsFromOptions, MapTableScopesOption, TableDataItem, ComputedOptionsFactory, RecordUnknown, ShallowSimplify, ComputedOptionsConfig, QueryOrExpression, QueryData, IsQuery, TableDataFn, DbTableOptionScopes, QueryScopes, ColumnSchemaConfig, DbSqlMethod, DefaultSchemaConfig, DefaultColumnTypes, QueryBeforeHook, QueryBeforeActionHook, QueryAfterHook, AfterHook, MergeQuery, QueryReturnType } from 'pqb/internal';
1
+ import { Column, TableData, ColumnsShape, Query, RelationConfigBase, QueryManyTake, QueryManyTakeOptional, EmptyObject, CreateData, UpdateData, WhereArg, SelectableFromShape, CreateManyMethodsNames, QueryHasWhere, CreateMethodsNames, MaybeArray, JoinQueryMethod, DeleteMethodsNames, IsolationLevel, TransactionOptions, AfterCommitStandaloneHook, AdapterBase, FromArg, FromResult, StorageOptions, DbSharedOptions, ColumnSchemaConfig, DbSqlMethod, TableDataItem, QueryData, IsQuery, TableDataFn, ComputedOptionsFactory, DbTableOptionScopes, QueryScopes, RecordUnknown, QueryBeforeHook, QueryAfterHook, QueryBeforeActionHook, AfterHook, ShallowSimplify, ShapeColumnPrimaryKeys, ShapeUniqueColumns, TableDataItemsUniqueColumns, TableDataItemsUniqueColumnTuples, UniqueConstraints, TableDataItemsUniqueConstraints, ComputedColumnsFromOptions, MapTableScopesOption, ComputedOptionsConfig, QueryOrExpression, DefaultSchemaConfig, DefaultColumnTypes, QueryReturnType, MergeQuery } from 'pqb/internal';
2
+ import { Db, QuerySchema } from 'pqb';
2
3
  export * from 'pqb';
3
4
 
4
5
  interface RelationRefsOptions<Column extends PropertyKey = string, Shape extends Column.Shape.QueryInit = Column.Shape.QueryInit> {
@@ -299,11 +300,45 @@ interface OrchidORMMethods {
299
300
  */
300
301
  $from<Arg extends MaybeArray<FromArg<Query>>>(arg: Arg): FromResult<FromQuery, Arg>;
301
302
  /**
302
- * `$withOptions` supports overriding `log` and `schema`.
303
+ * `$withOptions` supports overriding `log`, `schema`, `role`, and `setConfig`.
303
304
  *
304
305
  * - `log`: boolean, enables or disables logging in the scope of the callback.
305
306
  * - `schema`: set a **default** schema, note that it does not override
306
307
  * if you already have a schema set in the ORM config or for a specific table.
308
+ * - `role`: string, switches the Postgres role for the duration of the callback.
309
+ * Used for row-level security policies.
310
+ * - `setConfig`: object with string, number, or boolean values, sets Postgres custom
311
+ * settings for the duration of the callback. Use dotted names like `app.tenant_id`.
312
+ * Values are normalized to strings internally.
313
+ *
314
+ * SQL session options (`role` and `setConfig`) cannot be nested.
315
+ * If an outer scope already has `role` or `setConfig`, attempting to set them again
316
+ * in a nested `$withOptions` call will throw an error.
317
+ * Nested scopes that only change `log` or `schema` will inherit the outer SQL session context.
318
+ *
319
+ * Explicit transactions inside the callback inherit the same SQL session context:
320
+ *
321
+ * ```ts
322
+ * await db.$withOptions(
323
+ * {
324
+ * role: 'app_user',
325
+ * setConfig: {
326
+ * 'app.tenant_id': tenantId,
327
+ * 'app.user_id': userId,
328
+ * },
329
+ * },
330
+ * async () => {
331
+ * const project = await db.project.find(projectId);
332
+ *
333
+ * await db.$transaction(async () => {
334
+ * // This query runs in the transaction with the same role and config
335
+ * await db.project.find(projectId).update({ lastViewedAt: new Date() });
336
+ * });
337
+ * },
338
+ * );
339
+ * ```
340
+ *
341
+ * Basic usage with `log` and `schema`:
307
342
  *
308
343
  * ```ts
309
344
  * await db.$withOptions({ log: true, schema: 'custom' }, async () => {
@@ -750,8 +785,9 @@ type MapMethods<T extends Query, Methods extends MethodsBase<T>> = {
750
785
  };
751
786
  type Repo<T extends Query, Methods extends MethodsBase<T>> = T & MapMethods<T, Methods>;
752
787
  declare const createRepo: <T extends Query, Methods extends MethodsBase<T>>(table: T, methods: Methods) => Repo<(<Q extends {
753
- table: T['table'];
754
- shape: T['shape'];
788
+ table: T["table"];
789
+ shape: T["shape"];
755
790
  }>(q: Q) => Query & Q & MapMethods<T, Methods>) & T, Methods>;
756
791
 
757
- export { type BaseTableClass, type BaseTableInstance, type DefaultSelect, type Insertable, type MapMethods, type MapQueryMethods, type MethodsBase, type ORMTableInput, type OrchidORM, type OrchidOrmParam, type Queryable, type Repo, type Selectable, type SetColumnsResult, type Table, type TableClass, type TableClasses, type TableInfo, type TableToDb, type Updatable, createBaseTable, createRepo, orchidORMWithAdapter };
792
+ export { createBaseTable, createRepo, orchidORMWithAdapter };
793
+ export type { BaseTableClass, BaseTableInstance, DefaultSelect, FromQuery, Insertable, MapMethods, MapQueryMethods, MethodsBase, ORMTableInput, OrchidORM, OrchidOrmParam, Queryable, Repo, Selectable, SetColumnsResult, Table, TableClass, TableClasses, TableInfo, TableToDb, Updatable };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var internal = require('pqb/internal');
4
- var node_async_hooks = require('node:async_hooks');
5
4
  var pqb = require('pqb');
5
+ var node_async_hooks = require('node:async_hooks');
6
6
 
7
7
  function createBaseTable({
8
8
  schemaConfig = internal.defaultSchemaConfig,
@@ -144,6 +144,7 @@ function createBaseTable({
144
144
  internal.applyMixins(base, [internal.QueryHooks]);
145
145
  base.prototype.types = columnTypes;
146
146
  base.prototype.snakeCase = snakeCase;
147
+ base.prototype.language = language;
147
148
  base.prototype.autoForeignKeys = autoForeignKeys === true ? {} : autoForeignKeys || void 0;
148
149
  return base;
149
150
  }
@@ -417,7 +418,7 @@ class BelongsToVirtualColumn extends internal.VirtualColumn {
417
418
  var _a;
418
419
  const value = item[key];
419
420
  const kind = value.create ? "create" : value.connect ? "connect" : "connectOrCreate";
420
- if (kind) {
421
+ {
421
422
  const nestedCreateItem = (_a = nestedCreateItems ?? (nestedCreateItems = {}))[kind] ?? (_a[kind] = {
422
423
  items: [],
423
424
  values: []
@@ -725,7 +726,7 @@ class HasOneVirtualColumn extends internal.VirtualColumn {
725
726
  var _a;
726
727
  const value = item[this.key];
727
728
  const kind = value.create ? "create" : value.connect ? "connect" : "connectOrCreate";
728
- if (kind) {
729
+ {
729
730
  const nestedCreateItem = (_a = nestedCreateItems ?? (nestedCreateItems = {}))[kind] ?? (_a[kind] = {
730
731
  indexes: [],
731
732
  items: [],
@@ -1443,7 +1444,7 @@ const nestedUpdate$1 = ({ query, primaryKeys, foreignKeys }) => {
1443
1444
  }
1444
1445
  if (params.add) {
1445
1446
  if (data.length > 1) {
1446
- throw new internal.OrchidOrmInternalError(
1447
+ throw new pqb.OrchidOrmInternalError(
1447
1448
  query,
1448
1449
  "`connect` is not available when updating multiple records, it is only applicable for a single record update"
1449
1450
  );
@@ -1458,7 +1459,7 @@ const nestedUpdate$1 = ({ query, primaryKeys, foreignKeys }) => {
1458
1459
  obj
1459
1460
  );
1460
1461
  if (count < relatedWheres.length) {
1461
- throw new internal.OrchidOrmInternalError(
1462
+ throw new pqb.OrchidOrmInternalError(
1462
1463
  query,
1463
1464
  `Expected to find at least ${relatedWheres.length} record(s) based on \`add\` conditions, but found ${count}`
1464
1465
  );
@@ -1726,7 +1727,7 @@ const makeHasAndBelongsToManyMethod = (tableConfig, table, qb, relation, relatio
1726
1727
  data
1727
1728
  );
1728
1729
  if (createdCount === 0) {
1729
- throw new internal.NotFoundError(baseQuery2);
1730
+ throw new pqb.NotFoundError(baseQuery2);
1730
1731
  }
1731
1732
  }
1732
1733
  );
@@ -2023,14 +2024,14 @@ const nestedUpdate = (state) => {
2023
2024
  )
2024
2025
  ).onConflict(joinTableColumns).merge([state.foreignKeys[0]]);
2025
2026
  if (count < data.length * relatedWheres.length) {
2026
- throw new internal.OrchidOrmInternalError(
2027
+ throw new pqb.OrchidOrmInternalError(
2027
2028
  query,
2028
2029
  `Expected to find at least ${relatedWheres.length} record(s) based on \`add\` conditions, but found ${count / data.length}`
2029
2030
  );
2030
2031
  }
2031
2032
  } catch (err) {
2032
2033
  if (err.code === "42P10") {
2033
- throw new internal.OrchidOrmInternalError(
2034
+ throw new pqb.OrchidOrmInternalError(
2034
2035
  query,
2035
2036
  `"${state.joinTableQuery.table}" must have a primary key or a unique index on columns (${joinTableColumns.join(
2036
2037
  ", "
@@ -2319,7 +2320,7 @@ const orchidORMWithAdapter = ({
2319
2320
  computed: table.computed,
2320
2321
  nowSQL: tableClass.nowSQL
2321
2322
  };
2322
- const dbTable = new internal.Db(
2323
+ const dbTable = new pqb.Db(
2323
2324
  adapter,
2324
2325
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
2325
2326
  qb,