pqb 0.20.1 → 0.21.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
@@ -332,6 +332,7 @@ type CommonQueryData = {
332
332
  */
333
333
  originalQuery?: Query;
334
334
  scopes: Record<string, QueryScopeData>;
335
+ all?: true;
335
336
  };
336
337
  type SelectQueryData = CommonQueryData & {
337
338
  type: undefined;
@@ -2102,12 +2103,70 @@ declare class ScopeMethods {
2102
2103
  *
2103
2104
  * ```ts
2104
2105
  * // SomeTable has a default scope, ignore it for this query:
2105
- * await db.some.unScope('default');
2106
+ * await db.some.unscope('default');
2106
2107
  * ```
2107
2108
  *
2108
2109
  * @param scope - name of the scope to remove from the query
2109
2110
  */
2110
- unScope<T extends QueryBase>(this: T, scope: keyof T['meta']['scopes']): T;
2111
+ unscope<T extends QueryBase>(this: T, scope: keyof T['meta']['scopes']): T;
2112
+ }
2113
+
2114
+ type SoftDeleteOption<Shape extends ColumnsShapeBase> = true | keyof Shape;
2115
+ type QueryWithSoftDelete = Query & {
2116
+ meta: {
2117
+ scopes: {
2118
+ nonDeleted: unknown;
2119
+ };
2120
+ };
2121
+ };
2122
+ /**
2123
+ * `softDelete` configures the table to set `deletedAt` to current time instead of deleting records.
2124
+ * All queries on such table will filter out deleted records by default.
2125
+ *
2126
+ * ```ts
2127
+ * import { BaseTable } from './baseTable';
2128
+ *
2129
+ * export class SomeTable extends BaseTable {
2130
+ * readonly table = 'some';
2131
+ * columns = this.setColumns((t) => ({
2132
+ * id: t.identity().primaryKey(),
2133
+ * deletedAt: t.timestamp().nullable(),
2134
+ * }));
2135
+ *
2136
+ * // true is for using `deletedAt` column
2137
+ * readonly softDelete = true;
2138
+ * // or provide a different column name
2139
+ * readonly softDelete = 'myDeletedAt';
2140
+ * }
2141
+ *
2142
+ * const db = orchidORM(
2143
+ * { databaseURL: '...' },
2144
+ * {
2145
+ * someTable: SomeTable,
2146
+ * },
2147
+ * );
2148
+ *
2149
+ * // deleted records are ignored by default
2150
+ * const onlyNonDeleted = await db.someTable;
2151
+ * ```
2152
+ */
2153
+ declare class SoftDeleteMethods {
2154
+ /**
2155
+ * `includeDeleted` disables the default `deletedAt` filter:
2156
+ *
2157
+ * ```ts
2158
+ * const allRecords = await db.someTable.includeDeleted();
2159
+ * ```
2160
+ */
2161
+ includeDeleted<T extends QueryWithSoftDelete>(this: T): T;
2162
+ /**
2163
+ * `hardDelete` deletes records bypassing the `softDelete` behavior:
2164
+ *
2165
+ * ```ts
2166
+ * await db.someTable.find(1).hardDelete();
2167
+ * ```
2168
+ */
2169
+ hardDelete<T extends QueryWithSoftDelete>(this: T, ..._args: DeleteArgs<T>): DeleteResult<T>;
2111
2170
  }
2112
2171
 
2113
2172
  type NoPrimaryKeyOption = 'error' | 'warning' | 'ignore';
@@ -2130,6 +2189,10 @@ type DbTableOptions<Table extends string | undefined, Shape extends ColumnsShape
2130
2189
  * See {@link ScopeMethods}
2131
2190
  */
2132
2191
  scopes?: DbTableOptionScopes<Table, Shape>;
2192
+ /**
2193
+ * See {@link SoftDeleteMethods}
2194
+ */
2195
+ softDelete?: SoftDeleteOption<Shape>;
2133
2196
  } & QueryLogOptions;
2134
2197
  /**
2135
2198
  * See {@link ScopeMethods}
@@ -2227,9 +2290,10 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
2227
2290
  */
2228
2291
  queryArrays<R extends any[] = any[]>(...args: SQLQueryArgs): Promise<QueryArraysResult<R>>;
2229
2292
  }
2230
- type DbTableConstructor<ColumnTypes> = <Table extends string, Shape extends ColumnsShapeBase, Options extends DbTableOptions<Table, Shape>>(table: Table, shape?: ((t: ColumnTypes) => Shape) | Shape, options?: Options) => Db<Table, Shape, EmptyObject, ColumnTypes, Shape, Options extends {
2231
- scopes: CoreQueryScopes;
2232
- } ? Options['scopes'] : EmptyObject>;
2293
+ type DbTableConstructor<ColumnTypes> = <Table extends string, Shape extends ColumnsShapeBase, Options extends DbTableOptions<Table, Shape>>(table: Table, shape?: ((t: ColumnTypes) => Shape) | Shape, options?: Options) => Db<Table, Shape, EmptyObject, ColumnTypes, Shape, MapTableScopesOption<Options['scopes'], Options['softDelete']>>;
2294
+ type MapTableScopesOption<Scopes extends CoreQueryScopes | undefined, SoftDelete extends true | PropertyKey | undefined> = {
2295
+ [K in keyof Scopes | (SoftDelete extends true | PropertyKey ? 'nonDeleted' : never)]: unknown;
2296
+ };
2233
2297
  type DbResult<ColumnTypes> = Db<string, Record<string, never>, EmptyObject, ColumnTypes> & DbTableConstructor<ColumnTypes> & {
2234
2298
  adapter: Adapter;
2235
2299
  close: Adapter['close'];
@@ -3425,16 +3489,6 @@ type DeleteMethodsNames = 'del' | '_del' | 'delete' | '_delete';
3425
3489
  type DeleteArgs<T extends Query> = T['meta']['hasWhere'] extends true ? [] : [never];
3426
3490
  type DeleteResult<T extends Query> = T['meta']['hasSelect'] extends true ? SetQueryKind<T, 'delete'> : SetQueryReturnsRowCount<SetQueryKind<T, 'delete'>>;
3427
3491
  declare class Delete {
3428
- /**
3429
- * Alias for `delete` method
3430
- *
3431
- * @deprecated use `delete` instead, this method will be removed
3432
- */
3433
- del<T extends Query>(this: T, ..._args: DeleteArgs<T>): DeleteResult<T>;
3434
- /**
3435
- * @deprecated use `_del` instead, this method will be removed
3436
- */
3437
- _del<T extends Query>(this: T, ..._args: DeleteArgs<T>): DeleteResult<T>;
3438
3492
  /**
3439
3493
  * It is aliased to `del` because `delete` is a reserved word in JavaScript.
3440
3494
  *
@@ -5345,7 +5399,7 @@ declare class ColumnRefExpression<T extends ColumnTypeBase> extends Expression<T
5345
5399
  constructor(_type: T, name: string);
5346
5400
  makeSQL(ctx: ToSQLCtx, quotedAs?: string): string;
5347
5401
  }
5348
- interface QueryMethods<ColumnTypes> extends Omit<AsMethods, 'result'>, AggregateMethods, Select, From, Join, With, Union, Omit<JsonModifiers, 'result'>, JsonMethods, Create, Update, Delete, Transaction, For, ColumnInfoMethods, Omit<Where, 'result'>, SearchMethods, Clear, Having, Then, QueryLog, Omit<QueryHooks, 'result'>, QueryUpsertOrCreate, QueryGet, MergeQueryMethods, RawSqlMethods<ColumnTypes>, CopyMethods, TransformMethods, ScopeMethods {
5402
+ interface QueryMethods<ColumnTypes> extends Omit<AsMethods, 'result'>, AggregateMethods, Select, From, Join, With, Union, Omit<JsonModifiers, 'result'>, JsonMethods, Create, Update, Delete, Transaction, For, ColumnInfoMethods, Omit<Where, 'result'>, SearchMethods, Clear, Having, Then, QueryLog, Omit<QueryHooks, 'result'>, QueryUpsertOrCreate, QueryGet, MergeQueryMethods, RawSqlMethods<ColumnTypes>, CopyMethods, TransformMethods, ScopeMethods, SoftDeleteMethods {
5349
5403
  }
5350
5404
  declare class QueryMethods<ColumnTypes> {
5351
5405
  /**
@@ -7329,4 +7383,4 @@ declare module 'orchid-core' {
7329
7383
  }
7330
7384
  declare function addComputedColumns<T extends Query, Computed extends ComputedColumnsBase<T>>(q: T, computed: Computed): QueryWithComputed<T, Computed>;
7331
7385
 
7332
- export { Adapter, AdapterConfig, AdapterOptions, AddQueryDefaults, AddQuerySelect, AddQueryWith, AfterHook, AggregateMethods, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, AsMethods, BaseOperators, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanNullable, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnExpression, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnRefExpression, ColumnType, ColumnsObject, ColumnsShape, CommonQueryData, ComputedColumnsBase, CopyMethods, CopyOptions, CopyQueryData, Create, CreateColumn, CreateCtx, CreateData, CreateKind, CreateMethodsNames, CreateRelationDataOmittingFKeys, CreateRelationsData, CreateRelationsDataOmittingFKeys, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableConstructor, DbTableOptionScopes, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteMethodsNames, DeleteQueryData, DomainColumn, DoublePrecisionColumn, DropMode, DynamicRawSQL, EnumColumn, ExpressionOutput, FnExpression, FnExpressionArgs, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, GetStringArg, GroupArg, Having, HavingItem, HookAction, HookSelect, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinOverrides, JoinResult, JoinedParsers, JoinedShapes, JsonItem, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operator, Operators, OrCreateArg, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, OrderTsQueryConfig, Over, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryAfterHook, QueryArraysResult, QueryBase, QueryBeforeHook, QueryData, QueryDefaultReturnData, QueryError, QueryErrorName, QueryGet, QueryHelperResult, QueryHookSelect, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QueryScopeData, QueryScopes, QuerySourceItem, QueryTransform, QueryTransformFn, QueryUpsertOrCreate, QueryWithComputed, QueryWithTable, RawSQL, RawSqlMethods, RealColumn, RelationConfigBase, RelationConfigDataForCreate, RelationJoinQuery, RelationQuery, RelationQueryBase, RelationsBase, RelationsChain, SearchArg, SearchMethods, SearchWeight, Select, SelectArg, SelectAs, SelectItem, SelectQueryData, SelectSubQueryResult, SelectableBase, SelectableFromShape, SelectableOfType, SelectableOrExpression, SelectableOrExpressionOfType, SerialColumn, SerialColumnData, SetQueryKind, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumn, SetQueryReturnsColumnInfo, SetQueryReturnsColumnOptional, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsPluckColumn, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSQLCtx, ToSQLOptions, Transaction, TransactionAdapter, TransactionOptions, TransformMethods, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertArg, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereNotArgs, WhereOnItem, WhereOnJoinItem, WhereQueryBase, WhereQueryBuilder, WhereResult, WhereSearchItem, WhereSearchResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addComputedColumns, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryOn, addWhere, addWhereIn, addWhereNot, anyShape, checkIfASimpleQuery, cloneQuery, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, countSelect, createDb, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, raw, referencesArgsToCode, resetTableData, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
7386
+ export { Adapter, AdapterConfig, AdapterOptions, AddQueryDefaults, AddQuerySelect, AddQueryWith, AfterHook, AggregateMethods, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, AsMethods, BaseOperators, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanNullable, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnExpression, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnRefExpression, ColumnType, ColumnsObject, ColumnsShape, CommonQueryData, ComputedColumnsBase, CopyMethods, CopyOptions, CopyQueryData, Create, CreateColumn, CreateCtx, CreateData, CreateKind, CreateMethodsNames, CreateRelationDataOmittingFKeys, CreateRelationsData, CreateRelationsDataOmittingFKeys, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableConstructor, DbTableOptionScopes, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteArgs, DeleteMethodsNames, DeleteQueryData, DeleteResult, DomainColumn, DoublePrecisionColumn, DropMode, DynamicRawSQL, EnumColumn, ExpressionOutput, FnExpression, FnExpressionArgs, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, GetStringArg, GroupArg, Having, HavingItem, HookAction, HookSelect, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinOverrides, JoinResult, JoinedParsers, JoinedShapes, JsonItem, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MapTableScopesOption, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operator, Operators, OrCreateArg, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, OrderTsQueryConfig, Over, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryAfterHook, QueryArraysResult, QueryBase, QueryBeforeHook, QueryData, QueryDefaultReturnData, QueryError, QueryErrorName, QueryGet, QueryHelperResult, QueryHookSelect, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QueryScopeData, QueryScopes, QuerySourceItem, QueryTransform, QueryTransformFn, QueryUpsertOrCreate, QueryWithComputed, QueryWithTable, RawSQL, RawSqlMethods, RealColumn, RelationConfigBase, RelationConfigDataForCreate, RelationJoinQuery, RelationQuery, RelationQueryBase, RelationsBase, RelationsChain, SearchArg, SearchMethods, SearchWeight, Select, SelectArg, SelectAs, SelectItem, SelectQueryData, SelectSubQueryResult, SelectableBase, SelectableFromShape, SelectableOfType, SelectableOrExpression, SelectableOrExpressionOfType, SerialColumn, SerialColumnData, SetQueryKind, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumn, SetQueryReturnsColumnInfo, SetQueryReturnsColumnOptional, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsPluckColumn, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSQLCtx, ToSQLOptions, Transaction, TransactionAdapter, TransactionOptions, TransformMethods, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateArg, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertArg, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereNotArgs, WhereOnItem, WhereOnJoinItem, WhereQueryBase, WhereQueryBuilder, WhereResult, WhereSearchItem, WhereSearchResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addComputedColumns, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryOn, addWhere, addWhereIn, addWhereNot, anyShape, checkIfASimpleQuery, cloneQuery, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, countSelect, createDb, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, raw, referencesArgsToCode, resetTableData, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
package/dist/index.js CHANGED
@@ -2468,7 +2468,7 @@ const setQueryObjectValue = (q, object, key, value) => {
2468
2468
  return q;
2469
2469
  };
2470
2470
  const throwIfNoWhere = (q, method) => {
2471
- if (!q.q.or && !q.q.and) {
2471
+ if (!q.q.or && !q.q.and && !q.q.all) {
2472
2472
  throw new OrchidOrmInternalError(
2473
2473
  q,
2474
2474
  `Dangerous ${method} without conditions`
@@ -5587,9 +5587,6 @@ class OnConflictQueryBuilder {
5587
5587
  }
5588
5588
  }
5589
5589
 
5590
- const del = (self) => {
5591
- return _del(self.clone());
5592
- };
5593
5590
  const _del = (q) => {
5594
5591
  if (!q.q.select) {
5595
5592
  if (q.q.returnType === "oneOrThrow" || q.q.returnType === "valueOrThrow") {
@@ -5602,20 +5599,6 @@ const _del = (q) => {
5602
5599
  return q;
5603
5600
  };
5604
5601
  class Delete {
5605
- /**
5606
- * Alias for `delete` method
5607
- *
5608
- * @deprecated use `delete` instead, this method will be removed
5609
- */
5610
- del(..._args) {
5611
- return del(this);
5612
- }
5613
- /**
5614
- * @deprecated use `_del` instead, this method will be removed
5615
- */
5616
- _del(..._args) {
5617
- return _del(this);
5618
- }
5619
5602
  /**
5620
5603
  * It is aliased to `del` because `delete` is a reserved word in JavaScript.
5621
5604
  *
@@ -5666,7 +5649,7 @@ class Delete {
5666
5649
  */
5667
5650
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
5668
5651
  delete(..._args) {
5669
- return del(this);
5652
+ return _del(this.clone());
5670
5653
  }
5671
5654
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
5672
5655
  _delete(..._args) {
@@ -9362,12 +9345,12 @@ class ScopeMethods {
9362
9345
  *
9363
9346
  * ```ts
9364
9347
  * // SomeTable has a default scope, ignore it for this query:
9365
- * await db.some.unScope('default');
9348
+ * await db.some.unscope('default');
9366
9349
  * ```
9367
9350
  *
9368
9351
  * @param scope - name of the scope to remove from the query
9369
9352
  */
9370
- unScope(scope) {
9353
+ unscope(scope) {
9371
9354
  var _a;
9372
9355
  const q = this.clone();
9373
9356
  const data = q.q;
@@ -9390,6 +9373,59 @@ class ScopeMethods {
9390
9373
  }
9391
9374
  }
9392
9375
 
9376
+ function enableSoftDelete(q, table, shape, softDelete, scopes) {
9377
+ var _a, _b;
9378
+ const column = softDelete === true ? "deletedAt" : softDelete;
9379
+ if (!shape[column]) {
9380
+ throw new Error(
9381
+ `Table ${table} is missing ${column} column which is required for soft delete`
9382
+ );
9383
+ }
9384
+ const scope = {
9385
+ and: [{ [column]: null }]
9386
+ };
9387
+ scopes.deleted = scope;
9388
+ pushQueryValue(q, "and", scope.and[0]);
9389
+ ((_b = (_a = q.q).scopes) != null ? _b : _a.scopes = {}).nonDeleted = scope;
9390
+ const _del = _softDelete(column);
9391
+ q.baseQuery.delete = function() {
9392
+ return _del.call(this.clone());
9393
+ };
9394
+ q.baseQuery._delete = _del;
9395
+ }
9396
+ const nowSql = new RawSQL("now()");
9397
+ const _softDelete = (column) => {
9398
+ const set = { [column]: nowSql };
9399
+ return function() {
9400
+ return this._update(set);
9401
+ };
9402
+ };
9403
+ const { _delete } = Delete.prototype;
9404
+ class SoftDeleteMethods {
9405
+ /**
9406
+ * `includeDeleted` disables the default `deletedAt` filter:
9407
+ *
9408
+ * ```ts
9409
+ * const allRecords = await db.someTable.includeDeleted();
9410
+ * ```
9411
+ */
9412
+ includeDeleted() {
9413
+ return this.unscope("nonDeleted");
9414
+ }
9415
+ /**
9416
+ * `hardDelete` deletes records bypassing the `softDelete` behavior:
9417
+ *
9418
+ * ```ts
9419
+ * await db.someTable.find(1).hardDelete();
9420
+ * ```
9421
+ */
9422
+ hardDelete(..._args) {
9423
+ return _delete.call(
9424
+ this.clone().unscope("nonDeleted")
9425
+ );
9426
+ }
9427
+ }
9428
+
9393
9429
  class ColumnRefExpression extends orchidCore.Expression {
9394
9430
  constructor(_type, name) {
9395
9431
  super();
@@ -9414,9 +9450,8 @@ class QueryMethods {
9414
9450
  return this.clone()._all();
9415
9451
  }
9416
9452
  _all() {
9417
- var _a, _b;
9418
9453
  this.q.returnType = "all";
9419
- (_b = (_a = this.q).and) != null ? _b : _a.and = [];
9454
+ this.q.all = true;
9420
9455
  return this;
9421
9456
  }
9422
9457
  /**
@@ -10027,7 +10062,8 @@ orchidCore.applyMixins(QueryMethods, [
10027
10062
  RawSqlMethods,
10028
10063
  CopyMethods,
10029
10064
  TransformMethods,
10030
- ScopeMethods
10065
+ ScopeMethods,
10066
+ SoftDeleteMethods
10031
10067
  ]);
10032
10068
 
10033
10069
  var __defProp = Object.defineProperty;
@@ -10071,7 +10107,8 @@ class Db {
10071
10107
  this.columnTypes = columnTypes2;
10072
10108
  var _a, _b;
10073
10109
  const self = this;
10074
- const scopes = options.scopes ? {} : orchidCore.emptyObject;
10110
+ const { softDelete } = options;
10111
+ const scopes = options.scopes || softDelete ? {} : orchidCore.emptyObject;
10075
10112
  const tableData = getTableData();
10076
10113
  this.internal = __spreadProps(__spreadValues({}, tableData), {
10077
10114
  transactionStorage,
@@ -10193,6 +10230,9 @@ class Db {
10193
10230
  this.q.scopes = { default: scopes.default };
10194
10231
  }
10195
10232
  }
10233
+ if (softDelete) {
10234
+ enableSoftDelete(this, table, shape, softDelete, scopes);
10235
+ }
10196
10236
  }
10197
10237
  [node_util.inspect.custom]() {
10198
10238
  return `QueryObject<${this.table}>`;