@guren/orm 2.15.1 → 2.16.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 +34 -2
- package/dist/index.js +102 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -68,6 +68,10 @@ declare function applyAccessors<T extends PlainObject>(record: T, accessors?: Ac
|
|
|
68
68
|
/** Apply mutators to data before persistence, returning a new object. */
|
|
69
69
|
declare function applyMutators(data: PlainObject, mutators?: MutatorDefinitions): PlainObject;
|
|
70
70
|
//#endregion
|
|
71
|
+
//#region src/increment-amount.d.ts
|
|
72
|
+
/** What an adapter adds to a column; a string must match `DECIMAL_LITERAL`. */
|
|
73
|
+
type IncrementValue = number | bigint | string;
|
|
74
|
+
//#endregion
|
|
71
75
|
//#region src/internal-keys.d.ts
|
|
72
76
|
/**
|
|
73
77
|
* What `Model`, `QueryBuilder` and the adapters share without importing each
|
|
@@ -106,6 +110,12 @@ type AvgValue<TValue> = unknown extends TValue ? number | string : NonNullable<T
|
|
|
106
110
|
* A text column is a `string` too, which the type cannot tell from `numeric`.
|
|
107
111
|
*/
|
|
108
112
|
type NumericFieldKey<TRecord extends PlainObject> = string extends keyof TRecord ? string : { [K in FieldKey<TRecord>]: [SumValue<TRecord[K]>] extends [never] ? never : K; }[FieldKey<TRecord>];
|
|
113
|
+
/**
|
|
114
|
+
* What `increment()`/`decrement()` add: a plain number, or the column's own
|
|
115
|
+
* kind ({@link SumValue}), so a `numeric`/`decimal` column takes a decimal string.
|
|
116
|
+
* A text column is a `string` too; the adapter refuses that one at runtime.
|
|
117
|
+
*/
|
|
118
|
+
type IncrementAmount<TValue> = [SumValue<TValue>] extends [never] ? never : SumValue<TValue> | number;
|
|
109
119
|
/** A Drizzle select builder as `toDrizzle(query)` needs it: something to add a where clause to. */
|
|
110
120
|
type DrizzleWhereable = {
|
|
111
121
|
where: (...args: any[]) => unknown;
|
|
@@ -304,6 +314,19 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
304
314
|
* would be a supported way to bypass mass-assignment protection entirely.
|
|
305
315
|
*/
|
|
306
316
|
[PREPARED_UPDATE](payload: PlainObject): Promise<TRecord>;
|
|
317
|
+
/**
|
|
318
|
+
* `field = field + amount` in one statement, so concurrent calls lose no
|
|
319
|
+
* count; resolves to the number of rows changed. Scopes apply as in
|
|
320
|
+
* `update()`; `fillable`, mutators and hooks do not, since code names the
|
|
321
|
+
* column. A `NULL` stays `NULL`.
|
|
322
|
+
*/
|
|
323
|
+
increment<TKey extends NumericFieldKey<TRecord>>(field: TKey, amount?: IncrementAmount<TRecord[TKey]>): Promise<number>;
|
|
324
|
+
/**
|
|
325
|
+
* `increment()` with `amount` subtracted. A condition makes it a guard.
|
|
326
|
+
* @example await Product.where({ id }).where('stock', '>=', 2).decrement('stock', 2) // 0: not enough stock
|
|
327
|
+
*/
|
|
328
|
+
decrement<TKey extends NumericFieldKey<TRecord>>(field: TKey, amount?: IncrementAmount<TRecord[TKey]>): Promise<number>;
|
|
329
|
+
private addToColumn;
|
|
307
330
|
/**
|
|
308
331
|
* The object-where a basic adapter takes; a condition the flat object cannot
|
|
309
332
|
* carry (an OR group, an operator, two values on one field) refuses rather
|
|
@@ -402,6 +425,11 @@ interface ORMAdapterAdvanced extends ORMAdapter {
|
|
|
402
425
|
count: number;
|
|
403
426
|
}>>;
|
|
404
427
|
updateAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
428
|
+
/**
|
|
429
|
+
* `UPDATE ... SET field = field + amount` under `conditions`, resolving to
|
|
430
|
+
* the number of rows changed. A string `amount` is a decimal literal.
|
|
431
|
+
*/
|
|
432
|
+
incrementAdvanced?(table: unknown, conditions: WhereCondition[], field: string, amount: IncrementValue, writeOptions?: AdapterQueryOptions): Promise<number>;
|
|
405
433
|
deleteAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], writeOptions?: AdapterQueryOptions): Promise<number | PlainObject | void>;
|
|
406
434
|
}
|
|
407
435
|
//#endregion
|
|
@@ -802,6 +830,10 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
802
830
|
*/
|
|
803
831
|
static forceUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
804
832
|
protected static runUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean, set?: PlainObject): Promise<TRecordFor<T>>;
|
|
833
|
+
/** `QueryBuilder.increment()` for the rows matching `where`; fires no model events. */
|
|
834
|
+
static increment<T extends typeof Model, K extends NumericFieldKey<TRecordFor<T>>>(this: T, where: WhereClauseFor<T>, field: K, amount?: IncrementAmount<TRecordFor<T>[K]>, writeOptions?: ModelWriteOptions): Promise<number>;
|
|
835
|
+
/** `increment()` with `amount` subtracted. */
|
|
836
|
+
static decrement<T extends typeof Model, K extends NumericFieldKey<TRecordFor<T>>>(this: T, where: WhereClauseFor<T>, field: K, amount?: IncrementAmount<TRecordFor<T>[K]>, writeOptions?: ModelWriteOptions): Promise<number>;
|
|
805
837
|
static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
|
|
806
838
|
/**
|
|
807
839
|
* Runs `write` between the `deleting` and `deleted` events, for `delete()`
|
|
@@ -1068,7 +1100,7 @@ type DrizzleLikeInsertResult = {
|
|
|
1068
1100
|
type DrizzleLikeUpdate = {
|
|
1069
1101
|
set: (record: PlainObject) => DrizzleLikeUpdate;
|
|
1070
1102
|
where: (clause: unknown) => DrizzleLikeUpdate;
|
|
1071
|
-
returning?: () => Promise<unknown[]>;
|
|
1103
|
+
returning?: (selection?: Record<string, unknown>) => Promise<unknown[]>;
|
|
1072
1104
|
};
|
|
1073
1105
|
type DrizzleLikeDelete = {
|
|
1074
1106
|
where: (clause: unknown) => DrizzleLikeDelete;
|
|
@@ -1439,4 +1471,4 @@ declare function serializeRecord(record: PlainObject, options: {
|
|
|
1439
1471
|
/** Serialize an array of records. */
|
|
1440
1472
|
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1441
1473
|
//#endregion
|
|
1442
|
-
export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, type DatabaseDescription, DestructiveMigrationError, type DestructiveMigrationMode, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type ModelSetOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
|
1474
|
+
export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, type DatabaseDescription, DestructiveMigrationError, type DestructiveMigrationMode, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type IncrementAmount, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type ModelSetOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
package/dist/index.js
CHANGED
|
@@ -498,6 +498,19 @@ async function loadRelationChildren({ modelName, records, definition, head, tail
|
|
|
498
498
|
applyRelatedReadTransforms(related, children, projected);
|
|
499
499
|
}
|
|
500
500
|
//#endregion
|
|
501
|
+
//#region src/increment-amount.ts
|
|
502
|
+
/** A decimal as every dialect reads it unquoted; the only string an adapter may inline. */
|
|
503
|
+
const DECIMAL_LITERAL = /^-?\d+(?:\.\d+)?$/;
|
|
504
|
+
/** Refuses anything but a finite number, a bigint or a `DECIMAL_LITERAL` string. */
|
|
505
|
+
function signedAmount(caller, amount, negate) {
|
|
506
|
+
if (typeof amount === "bigint" || typeof amount === "number" && Number.isFinite(amount)) return negate ? -amount : amount;
|
|
507
|
+
if (typeof amount === "string" && DECIMAL_LITERAL.test(amount)) {
|
|
508
|
+
if (!negate) return amount;
|
|
509
|
+
return amount.startsWith("-") ? amount.slice(1) : `-${amount}`;
|
|
510
|
+
}
|
|
511
|
+
throw new TypeError(`${caller}() takes a finite number, a bigint, or a decimal string such as '10.50'; got ${typeof amount === "string" ? JSON.stringify(amount) : String(amount)}.`);
|
|
512
|
+
}
|
|
513
|
+
//#endregion
|
|
501
514
|
//#region src/where-conditions.ts
|
|
502
515
|
/**
|
|
503
516
|
* True when the caller wrote filters and every one of them was `undefined`.
|
|
@@ -1001,6 +1014,53 @@ async function resolveWithReturning(query) {
|
|
|
1001
1014
|
row: void 0
|
|
1002
1015
|
};
|
|
1003
1016
|
}
|
|
1017
|
+
/** A string-typed column that still holds a number: `numeric`/`decimal` (unsigned too) and a bigint in string mode. */
|
|
1018
|
+
const NUMERIC_STRING_DETAILS = /* @__PURE__ */ new Set([
|
|
1019
|
+
"numeric",
|
|
1020
|
+
"unumeric",
|
|
1021
|
+
"int64",
|
|
1022
|
+
"uint64"
|
|
1023
|
+
]);
|
|
1024
|
+
/**
|
|
1025
|
+
* Refuses `column + amount` where SQL would not add: SQLite stores `'one' + 1`
|
|
1026
|
+
* as `1` and `1.5` in an integer column, both without an error. `dataType` is
|
|
1027
|
+
* `number int32`, `number uint32`, `bigint int64`, `string numeric`, `string`,
|
|
1028
|
+
* `boolean`, `object date`, …; a `custom` column is the database's to judge.
|
|
1029
|
+
*/
|
|
1030
|
+
function assertAddable(column, field, amount) {
|
|
1031
|
+
const dataType = column.dataType;
|
|
1032
|
+
if (typeof dataType !== "string") return;
|
|
1033
|
+
const [kind, detail = ""] = dataType.split(" ");
|
|
1034
|
+
if (kind === "string" ? !NUMERIC_STRING_DETAILS.has(detail) : kind === "boolean" || kind === "object" || kind === "array") throw new TypeError(`DrizzleAdapter: cannot add to "${field}", a ${dataType} column; increment() and decrement() take a numeric column.`);
|
|
1035
|
+
if ((typeof amount === "number" ? !Number.isInteger(amount) : typeof amount === "string" && amount.includes(".")) && /^u?int\d/.test(detail)) throw new TypeError(`DrizzleAdapter: cannot add ${String(amount)} to "${field}", an integer column.`);
|
|
1036
|
+
}
|
|
1037
|
+
/** `String(number)` of a finite number, a bigint, or a decimal string: digits, one point, an exponent. */
|
|
1038
|
+
const NUMERIC_LITERAL = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/;
|
|
1039
|
+
/**
|
|
1040
|
+
* The amount as a SQL literal. A bound amount reaches each driver in its own
|
|
1041
|
+
* encoding: D1 takes no bigint, the Data API sends one as a string, and MySQL
|
|
1042
|
+
* reads a bound string as a double, which a `decimal` column cannot afford.
|
|
1043
|
+
*/
|
|
1044
|
+
function amountLiteral(amount) {
|
|
1045
|
+
const literal = String(amount);
|
|
1046
|
+
if (typeof amount === "string" ? !DECIMAL_LITERAL.test(literal) : !NUMERIC_LITERAL.test(literal)) throw new TypeError(`DrizzleAdapter: increment amount ${JSON.stringify(literal)} is not a numeric literal.`);
|
|
1047
|
+
return sql.raw(literal);
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Runs an update and counts the rows it changed: the RETURNING rows where the
|
|
1051
|
+
* dialect has them (`column` keeps each one small), else the driver's header,
|
|
1052
|
+
* which mysql2 resolves as `[ResultSetHeader, fields]`.
|
|
1053
|
+
*/
|
|
1054
|
+
async function countChangedRows(query, column) {
|
|
1055
|
+
if (typeof query.returning === "function") return (await query.returning({ value: column })).length;
|
|
1056
|
+
const result = await resolveMutation(query);
|
|
1057
|
+
const header = Array.isArray(result) ? result[0] : result;
|
|
1058
|
+
for (const key of ["affectedRows", "rowsAffected"]) {
|
|
1059
|
+
const value = header?.[key];
|
|
1060
|
+
if (typeof value === "number") return value;
|
|
1061
|
+
}
|
|
1062
|
+
throw new Error("DrizzleAdapter: the write ran, but the driver reported no count of the rows it changed.");
|
|
1063
|
+
}
|
|
1004
1064
|
const DrizzleAdapter = {
|
|
1005
1065
|
configure: configureConnection,
|
|
1006
1066
|
getDatabase() {
|
|
@@ -1143,6 +1203,17 @@ const DrizzleAdapter = {
|
|
|
1143
1203
|
return await resolveMutation(finalQuery);
|
|
1144
1204
|
});
|
|
1145
1205
|
},
|
|
1206
|
+
async incrementAdvanced(table, conditions, field, amount, writeOptions) {
|
|
1207
|
+
return connection().run(writeOptions, async (db) => {
|
|
1208
|
+
if (!db.update) throw new Error("DrizzleAdapter: configured database does not support updates.");
|
|
1209
|
+
const delta = amountLiteral(amount);
|
|
1210
|
+
const column = resolveColumn(table, field);
|
|
1211
|
+
assertAddable(column, field, amount);
|
|
1212
|
+
const data = { [field]: sql`${column} + ${delta}` };
|
|
1213
|
+
const clause = buildDrizzleConditions(table, conditions);
|
|
1214
|
+
return countChangedRows(clause ? db.update(table).set(data).where(clause) : db.update(table).set(data), column);
|
|
1215
|
+
});
|
|
1216
|
+
},
|
|
1146
1217
|
async deleteAdvanced(table, conditions, writeOptions) {
|
|
1147
1218
|
return connection().run(writeOptions, async (db) => {
|
|
1148
1219
|
if (!db.delete) throw new Error("DrizzleAdapter: configured database does not support deletes.");
|
|
@@ -1621,6 +1692,28 @@ var QueryBuilder = class QueryBuilder {
|
|
|
1621
1692
|
return adapter.update(this.table, this.simpleWhereFor("update"), payload, { trx: this.options.trx });
|
|
1622
1693
|
}
|
|
1623
1694
|
/**
|
|
1695
|
+
* `field = field + amount` in one statement, so concurrent calls lose no
|
|
1696
|
+
* count; resolves to the number of rows changed. Scopes apply as in
|
|
1697
|
+
* `update()`; `fillable`, mutators and hooks do not, since code names the
|
|
1698
|
+
* column. A `NULL` stays `NULL`.
|
|
1699
|
+
*/
|
|
1700
|
+
async increment(field, amount) {
|
|
1701
|
+
return this.addToColumn("increment", field, amount);
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* `increment()` with `amount` subtracted. A condition makes it a guard.
|
|
1705
|
+
* @example await Product.where({ id }).where('stock', '>=', 2).decrement('stock', 2) // 0: not enough stock
|
|
1706
|
+
*/
|
|
1707
|
+
async decrement(field, amount) {
|
|
1708
|
+
return this.addToColumn("decrement", field, amount);
|
|
1709
|
+
}
|
|
1710
|
+
async addToColumn(method, field, amount) {
|
|
1711
|
+
const signed = signedAmount(`${this.modelClass.name}.${method}`, amount === void 0 ? 1 : amount, method === "decrement");
|
|
1712
|
+
const adapter = this.assertWritable("update");
|
|
1713
|
+
if (typeof adapter.incrementAdvanced !== "function") throw new Error(`${this.modelClass.name}: ${method}() needs an adapter that implements incrementAdvanced.`);
|
|
1714
|
+
return adapter.incrementAdvanced(this.table, this.effectiveConditions(), field, signed, { trx: this.options.trx });
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1624
1717
|
* The object-where a basic adapter takes; a condition the flat object cannot
|
|
1625
1718
|
* carry (an OR group, an operator, two values on one field) refuses rather
|
|
1626
1719
|
* than writing with it dropped.
|
|
@@ -2557,9 +2650,18 @@ var Model = class Model {
|
|
|
2557
2650
|
const lifecycle = modelLifecycle(this.name, "update", this.hooks, this.observers);
|
|
2558
2651
|
await lifecycle.before(payload);
|
|
2559
2652
|
const result = await this.newQuery(writeOptions).where(where)[PREPARED_UPDATE](payload);
|
|
2653
|
+
if (result == null) return result;
|
|
2560
2654
|
await lifecycle.after(result);
|
|
2561
2655
|
return this.applyReadTransforms(result);
|
|
2562
2656
|
}
|
|
2657
|
+
/** `QueryBuilder.increment()` for the rows matching `where`; fires no model events. */
|
|
2658
|
+
static async increment(where, field, amount, writeOptions) {
|
|
2659
|
+
return this.newQuery(writeOptions).where(where).increment(field, amount);
|
|
2660
|
+
}
|
|
2661
|
+
/** `increment()` with `amount` subtracted. */
|
|
2662
|
+
static async decrement(where, field, amount, writeOptions) {
|
|
2663
|
+
return this.newQuery(writeOptions).where(where).decrement(field, amount);
|
|
2664
|
+
}
|
|
2563
2665
|
static async delete(where, writeOptions) {
|
|
2564
2666
|
if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
|
|
2565
2667
|
return this[LIFECYCLE_DELETE](where, "delete", () => this.newQuery(writeOptions).where(where).delete());
|