@getstrata/core 2.2.48 → 2.2.50
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/CHANGELOG.md +11 -0
- package/dist/core/audit/exportStore.d.ts +17 -0
- package/dist/core/cache/redisCacheScript.d.ts +2 -0
- package/dist/core/database/baseRepository.d.ts +0 -1
- package/dist/core/database/model.d.ts +6 -113
- package/dist/core/database/modelAttributes.d.ts +17 -0
- package/dist/core/database/modelQuery.d.ts +139 -0
- package/dist/core/database/modelRegistry.d.ts +34 -0
- package/dist/core/database/relationQueries.d.ts +20 -0
- package/dist/core/http/middleware.d.ts +2 -2
- package/dist/core/http/routeMiddleware.d.ts +1 -1
- package/dist/core/mail/mailer.d.ts +1 -4
- package/dist/core/mail/smtpMessage.d.ts +7 -0
- package/dist/core/queue/redisListScripts.d.ts +5 -0
- package/dist/core/queue/redisStreamsScripts.d.ts +11 -0
- package/dist/core/scheduler/leaseScript.d.ts +2 -0
- package/dist/entries/audit/exportAuditLogs.js +63 -58
- package/dist/entries/auth/scimAuthMiddleware.js +31 -20
- package/dist/entries/cache/createCacheStore.js +2 -1
- package/dist/entries/facades.js +103 -101
- package/dist/entries/http/routeMiddleware.js +3 -3
- package/dist/entries/jobs/exportAuditLogsJob.js +63 -58
- package/dist/entries/mail/mailer.js +103 -101
- package/dist/entries/queue/createAppQueue.js +277 -271
- package/dist/entries/queue/publicQueue.js +277 -271
- package/dist/entries/queue/queueMetrics.js +277 -271
- package/dist/entries/queue/redisQueue.js +277 -271
- package/dist/index.js +1482 -1428
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4503,6 +4503,33 @@ function buildConditionalWriteQuery(table, operation, changes, options, returnin
|
|
|
4503
4503
|
};
|
|
4504
4504
|
}
|
|
4505
4505
|
|
|
4506
|
+
// ../../src/core/database/relationQueries.ts
|
|
4507
|
+
init_dialect();
|
|
4508
|
+
function buildThroughWhere(table, options, parentIds) {
|
|
4509
|
+
const parameters = [...parentIds];
|
|
4510
|
+
const { clause } = buildQueryWhereClause(table, options, options.whereNodes, parameters);
|
|
4511
|
+
return {
|
|
4512
|
+
text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
|
|
4513
|
+
params: parameters.slice(parentIds.length)
|
|
4514
|
+
};
|
|
4515
|
+
}
|
|
4516
|
+
function buildHasManyThroughQuery(table, relation, parentIds, options) {
|
|
4517
|
+
const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
|
|
4518
|
+
const farTable = table.name;
|
|
4519
|
+
const columns = table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
|
|
4520
|
+
const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
|
|
4521
|
+
const { text: extraWhere, params: extraParams } = buildThroughWhere(table, options, parentIds);
|
|
4522
|
+
const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
|
|
4523
|
+
return { text: sql, params: [...parentIds, ...extraParams] };
|
|
4524
|
+
}
|
|
4525
|
+
function buildPivotLookupQuery(relation, parentIds) {
|
|
4526
|
+
const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
|
|
4527
|
+
return {
|
|
4528
|
+
text: `SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`,
|
|
4529
|
+
params: parentIds
|
|
4530
|
+
};
|
|
4531
|
+
}
|
|
4532
|
+
|
|
4506
4533
|
// ../../src/core/database/relationships.ts
|
|
4507
4534
|
function hasMany(definition) {
|
|
4508
4535
|
return {
|
|
@@ -5809,26 +5836,10 @@ class BaseRepository {
|
|
|
5809
5836
|
throw new Error("A related model scope joins the through table twice; use an explicitly aliased correlated predicate instead.");
|
|
5810
5837
|
}
|
|
5811
5838
|
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
5812
|
-
const
|
|
5813
|
-
const
|
|
5814
|
-
const columns = this.table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
|
|
5815
|
-
const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
|
|
5816
|
-
const { text: extraWhere, params: extraParams } = this.buildThroughWhere(options, parentIds);
|
|
5817
|
-
const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
|
|
5818
|
-
const children = await this.connection.unsafe(sql, [
|
|
5819
|
-
...parentIds,
|
|
5820
|
-
...extraParams
|
|
5821
|
-
]);
|
|
5839
|
+
const { text, params } = buildHasManyThroughQuery(this.table, relation, parentIds, options);
|
|
5840
|
+
const children = await this.connection.unsafe(text, params);
|
|
5822
5841
|
return indexHasManyThroughRelation(parents, children, relation);
|
|
5823
5842
|
}
|
|
5824
|
-
buildThroughWhere(options, parentIds) {
|
|
5825
|
-
const parameters = [...parentIds];
|
|
5826
|
-
const { clause } = buildQueryWhereClause(this.table, options, options.whereNodes, parameters);
|
|
5827
|
-
return {
|
|
5828
|
-
text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
|
|
5829
|
-
params: parameters.slice(parentIds.length)
|
|
5830
|
-
};
|
|
5831
|
-
}
|
|
5832
5843
|
async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
|
|
5833
5844
|
if (children.length === 0) {
|
|
5834
5845
|
return new Map;
|
|
@@ -5894,8 +5905,8 @@ class BaseRepository {
|
|
|
5894
5905
|
return indexBelongsToManyRelation(parents, [], [], relation);
|
|
5895
5906
|
}
|
|
5896
5907
|
const parentIds = [...new Set(parents.map((parent) => parent[relation.parentKey]))];
|
|
5897
|
-
const
|
|
5898
|
-
const pivotRows = await this.connection.unsafe(
|
|
5908
|
+
const { text, params } = buildPivotLookupQuery(relation, parentIds);
|
|
5909
|
+
const pivotRows = await this.connection.unsafe(text, params);
|
|
5899
5910
|
if (pivotRows.length === 0) {
|
|
5900
5911
|
return indexBelongsToManyRelation(parents, [], [], relation);
|
|
5901
5912
|
}
|
|
@@ -5990,6 +6001,8 @@ function createTokenAbilityChecker() {
|
|
|
5990
6001
|
}
|
|
5991
6002
|
// ../../src/core/cache/redisCacheStore.ts
|
|
5992
6003
|
var {RedisClient } = globalThis.Bun;
|
|
6004
|
+
|
|
6005
|
+
// ../../src/core/cache/redisCacheScript.ts
|
|
5993
6006
|
var CACHE_SCRIPT = `
|
|
5994
6007
|
local expected = {'hash', 'zset', 'zset', 'hash', 'zset'}
|
|
5995
6008
|
for i, key in ipairs(KEYS) do
|
|
@@ -6189,6 +6202,7 @@ end
|
|
|
6189
6202
|
return redis.error_reply('Unknown cache operation')
|
|
6190
6203
|
`;
|
|
6191
6204
|
|
|
6205
|
+
// ../../src/core/cache/redisCacheStore.ts
|
|
6192
6206
|
class RedisCacheStore {
|
|
6193
6207
|
redisUrl;
|
|
6194
6208
|
ttlMs;
|
|
@@ -8036,482 +8050,667 @@ async function freshDatabase(db, migrations, options = {}) {
|
|
|
8036
8050
|
await runFresh();
|
|
8037
8051
|
}
|
|
8038
8052
|
// ../../src/core/database/model.ts
|
|
8039
|
-
import { isDeepStrictEqual } from "util";
|
|
8040
8053
|
init_deferredModelEvents();
|
|
8041
8054
|
|
|
8042
|
-
// ../../src/core/database/
|
|
8043
|
-
|
|
8044
|
-
|
|
8045
|
-
|
|
8046
|
-
|
|
8047
|
-
|
|
8048
|
-
|
|
8049
|
-
function asWhere(where) {
|
|
8050
|
-
return where;
|
|
8055
|
+
// ../../src/core/database/modelAttributes.ts
|
|
8056
|
+
import { isDeepStrictEqual } from "util";
|
|
8057
|
+
function snapshotAttributes(values) {
|
|
8058
|
+
return Object.fromEntries(Object.entries(values).map(([key, value]) => [
|
|
8059
|
+
key,
|
|
8060
|
+
Buffer.isBuffer(value) ? Buffer.from(value) : structuredClone(value)
|
|
8061
|
+
]));
|
|
8051
8062
|
}
|
|
8052
|
-
function
|
|
8053
|
-
|
|
8054
|
-
return owner.get(ownerKey);
|
|
8055
|
-
}
|
|
8056
|
-
if (owner && typeof owner === "object" && "id" in owner && owner.id !== undefined) {
|
|
8057
|
-
return owner.id;
|
|
8058
|
-
}
|
|
8059
|
-
throw new Error("belongsTo.associate() requires a related model or { id }.");
|
|
8063
|
+
function changedAttributes(values, original) {
|
|
8064
|
+
return Object.fromEntries(Object.entries(values).filter(([key, value]) => !(key in original) || !isDeepStrictEqual(value, original[key])));
|
|
8060
8065
|
}
|
|
8061
|
-
|
|
8062
|
-
|
|
8066
|
+
var PASSWORD_HASH_PATTERN = /^\$(?:2[aby]?|argon2(?:i|d|id)?)\$/;
|
|
8067
|
+
function isAlreadyHashed(value) {
|
|
8068
|
+
return PASSWORD_HASH_PATTERN.test(value);
|
|
8063
8069
|
}
|
|
8064
|
-
function
|
|
8065
|
-
if (
|
|
8066
|
-
return
|
|
8070
|
+
async function hashCastValue(value) {
|
|
8071
|
+
if (value === null || value === undefined)
|
|
8072
|
+
return value;
|
|
8073
|
+
const plain = String(value);
|
|
8074
|
+
if (isAlreadyHashed(plain)) {
|
|
8075
|
+
return plain;
|
|
8067
8076
|
}
|
|
8068
|
-
return
|
|
8069
|
-
}
|
|
8070
|
-
function scopedRelatedQuery(model, repository = model.repository()) {
|
|
8071
|
-
const query = repository.query();
|
|
8072
|
-
const scopedModel = model;
|
|
8073
|
-
return scopedModel.scopeQuery?.(query) ?? query;
|
|
8074
|
-
}
|
|
8075
|
-
function relatedOptions(model, filters, options = {}) {
|
|
8076
|
-
const query = scopedRelatedQuery(model);
|
|
8077
|
-
for (const filter of filters)
|
|
8078
|
-
query.where(filter);
|
|
8079
|
-
return { ...query.getOptions(), ...options };
|
|
8080
|
-
}
|
|
8081
|
-
function relatedRead(model, connection, binding, filters, options = {}) {
|
|
8082
|
-
const query = scopedRelatedQuery(model, model.repository().withConnection(connection));
|
|
8083
|
-
query.where(binding).protectWhere();
|
|
8084
|
-
for (const filter of filters)
|
|
8085
|
-
query.where(filter);
|
|
8086
|
-
if (options.orderBy)
|
|
8087
|
-
query.orderBy(options.orderBy);
|
|
8088
|
-
if (options.limit !== undefined)
|
|
8089
|
-
query.limit(options.limit);
|
|
8090
|
-
return query;
|
|
8077
|
+
return await hashPassword(plain);
|
|
8091
8078
|
}
|
|
8092
|
-
function
|
|
8093
|
-
|
|
8094
|
-
|
|
8095
|
-
throw new Error("A related model scope joins a reserved relation table; use an explicitly aliased correlated predicate instead.");
|
|
8079
|
+
function hydrateValue(value, cast) {
|
|
8080
|
+
if (value === null || value === undefined) {
|
|
8081
|
+
return value;
|
|
8096
8082
|
}
|
|
8097
|
-
|
|
8098
|
-
|
|
8099
|
-
|
|
8100
|
-
|
|
8101
|
-
|
|
8102
|
-
|
|
8103
|
-
|
|
8104
|
-
|
|
8105
|
-
|
|
8106
|
-
|
|
8107
|
-
|
|
8108
|
-
|
|
8109
|
-
|
|
8110
|
-
|
|
8111
|
-
|
|
8112
|
-
|
|
8113
|
-
constructor(parent, related, relation) {
|
|
8114
|
-
this.parent = parent;
|
|
8115
|
-
this.related = related;
|
|
8116
|
-
this.relation = relation;
|
|
8083
|
+
switch (cast) {
|
|
8084
|
+
case "date":
|
|
8085
|
+
case "datetime":
|
|
8086
|
+
return value instanceof Date ? value : new Date(String(value));
|
|
8087
|
+
case "json":
|
|
8088
|
+
return typeof value === "string" ? JSON.parse(value) : value;
|
|
8089
|
+
case "bool":
|
|
8090
|
+
case "boolean":
|
|
8091
|
+
return value === true || value === 1 || value === "1" || value === "true";
|
|
8092
|
+
case "integer":
|
|
8093
|
+
case "int":
|
|
8094
|
+
return value === "" ? null : Number(value);
|
|
8095
|
+
case "hashed":
|
|
8096
|
+
return value;
|
|
8097
|
+
default:
|
|
8098
|
+
return value;
|
|
8117
8099
|
}
|
|
8118
|
-
|
|
8119
|
-
|
|
8120
|
-
|
|
8100
|
+
}
|
|
8101
|
+
function dehydrateValue(value, cast) {
|
|
8102
|
+
if (cast === "hashed")
|
|
8103
|
+
return hashCastValue(value);
|
|
8104
|
+
if (value === null || value === undefined) {
|
|
8105
|
+
return value;
|
|
8121
8106
|
}
|
|
8122
|
-
|
|
8123
|
-
|
|
8124
|
-
|
|
8107
|
+
switch (cast) {
|
|
8108
|
+
case "date":
|
|
8109
|
+
case "datetime":
|
|
8110
|
+
return value instanceof Date ? value : new Date(String(value));
|
|
8111
|
+
case "json":
|
|
8112
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
8113
|
+
case "bool":
|
|
8114
|
+
case "boolean":
|
|
8115
|
+
return Boolean(value);
|
|
8116
|
+
case "integer":
|
|
8117
|
+
case "int":
|
|
8118
|
+
return value === "" ? null : Number(value);
|
|
8119
|
+
default:
|
|
8120
|
+
return value;
|
|
8125
8121
|
}
|
|
8126
|
-
|
|
8127
|
-
|
|
8128
|
-
|
|
8122
|
+
}
|
|
8123
|
+
function filterMassAssignable(fillable, guarded, input) {
|
|
8124
|
+
if (fillable === undefined && guarded === undefined && Object.keys(input).length > 0) {
|
|
8125
|
+
throw new Error("Mass assignment is not configured for this model. Declare static $fillable = [...] to allow specific columns, or static $guarded = [] to allow all of them.");
|
|
8129
8126
|
}
|
|
8130
|
-
|
|
8131
|
-
|
|
8127
|
+
const resolvedGuarded = guarded ?? true;
|
|
8128
|
+
if (fillable && fillable.length > 0) {
|
|
8129
|
+
const allowed = new Set(fillable);
|
|
8130
|
+
return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
|
|
8132
8131
|
}
|
|
8133
|
-
|
|
8134
|
-
|
|
8135
|
-
const rows = Array.isArray(value) ? value : [];
|
|
8136
|
-
return rows.map((item) => this.related.newFromRecord(item));
|
|
8132
|
+
if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
|
|
8133
|
+
return {};
|
|
8137
8134
|
}
|
|
8138
|
-
|
|
8139
|
-
|
|
8140
|
-
|
|
8141
|
-
|
|
8142
|
-
|
|
8135
|
+
const blocked = new Set(resolvedGuarded);
|
|
8136
|
+
return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
|
|
8137
|
+
}
|
|
8138
|
+
function applyCasts(values, casts, direction) {
|
|
8139
|
+
const entries = Object.entries(casts);
|
|
8140
|
+
if (entries.length === 0) {
|
|
8141
|
+
return direction === "hydrate" ? values : Promise.resolve(values);
|
|
8143
8142
|
}
|
|
8144
|
-
|
|
8145
|
-
|
|
8143
|
+
const result = { ...values };
|
|
8144
|
+
if (direction === "hydrate") {
|
|
8145
|
+
for (const [key, cast] of entries) {
|
|
8146
|
+
if (key in result && cast)
|
|
8147
|
+
result[key] = hydrateValue(result[key], cast);
|
|
8148
|
+
}
|
|
8149
|
+
return result;
|
|
8146
8150
|
}
|
|
8147
|
-
async
|
|
8148
|
-
const
|
|
8149
|
-
|
|
8151
|
+
return (async () => {
|
|
8152
|
+
const hashes = [];
|
|
8153
|
+
for (const [key, cast] of entries) {
|
|
8154
|
+
if (!(key in result) || !cast)
|
|
8155
|
+
continue;
|
|
8156
|
+
if (cast === "hashed") {
|
|
8157
|
+
const current = result[key];
|
|
8158
|
+
hashes.push(hashCastValue(current).then((hashed) => {
|
|
8159
|
+
result[key] = hashed;
|
|
8160
|
+
}));
|
|
8161
|
+
continue;
|
|
8162
|
+
}
|
|
8163
|
+
result[key] = dehydrateValue(result[key], cast);
|
|
8164
|
+
}
|
|
8165
|
+
await Promise.all(hashes);
|
|
8166
|
+
return result;
|
|
8167
|
+
})();
|
|
8168
|
+
}
|
|
8169
|
+
function applyTimestampsOnCreate(columns, values, enabled) {
|
|
8170
|
+
if (!enabled) {
|
|
8171
|
+
return values;
|
|
8150
8172
|
}
|
|
8151
|
-
|
|
8152
|
-
|
|
8153
|
-
|
|
8173
|
+
const now = new Date;
|
|
8174
|
+
const result = { ...values };
|
|
8175
|
+
if (columns.includes("created_at")) {
|
|
8176
|
+
result.created_at = now;
|
|
8154
8177
|
}
|
|
8155
|
-
|
|
8156
|
-
|
|
8178
|
+
if (columns.includes("updated_at")) {
|
|
8179
|
+
result.updated_at = now;
|
|
8157
8180
|
}
|
|
8158
|
-
|
|
8159
|
-
|
|
8181
|
+
return result;
|
|
8182
|
+
}
|
|
8183
|
+
function applyTimestampsOnUpdate(columns, values, enabled) {
|
|
8184
|
+
if (!enabled) {
|
|
8185
|
+
return values;
|
|
8160
8186
|
}
|
|
8161
|
-
|
|
8162
|
-
|
|
8187
|
+
const result = { ...values };
|
|
8188
|
+
if (columns.includes("updated_at")) {
|
|
8189
|
+
result.updated_at = new Date;
|
|
8163
8190
|
}
|
|
8164
|
-
|
|
8165
|
-
|
|
8191
|
+
return result;
|
|
8192
|
+
}
|
|
8193
|
+
|
|
8194
|
+
// ../../src/core/database/modelRegistry.ts
|
|
8195
|
+
var modelGlobalScopes = new WeakMap;
|
|
8196
|
+
var modelBooted = new WeakSet;
|
|
8197
|
+
var modelRepositories = new WeakMap;
|
|
8198
|
+
var modelRepositoryFactories = new WeakMap;
|
|
8199
|
+
var namedModels = new Map;
|
|
8200
|
+
var modelObservers = new WeakMap;
|
|
8201
|
+
async function runObservers(model, hook) {
|
|
8202
|
+
const observers = modelObservers.get(model.constructor) ?? [];
|
|
8203
|
+
for (const observer of observers) {
|
|
8204
|
+
const handler = observer[hook];
|
|
8205
|
+
if (handler && await handler(model) === false) {
|
|
8206
|
+
return false;
|
|
8207
|
+
}
|
|
8166
8208
|
}
|
|
8167
|
-
|
|
8168
|
-
|
|
8169
|
-
|
|
8170
|
-
|
|
8209
|
+
return true;
|
|
8210
|
+
}
|
|
8211
|
+
function nameModel(model) {
|
|
8212
|
+
const { name, $morphClass } = model;
|
|
8213
|
+
if (name)
|
|
8214
|
+
namedModels.set(name, model);
|
|
8215
|
+
if ($morphClass)
|
|
8216
|
+
namedModels.set($morphClass, model);
|
|
8217
|
+
}
|
|
8218
|
+
function resolveModelRepository(model) {
|
|
8219
|
+
const existing = modelRepositories.get(model);
|
|
8220
|
+
if (existing)
|
|
8221
|
+
return existing;
|
|
8222
|
+
for (let current = model;current; current = Object.getPrototypeOf(current)) {
|
|
8223
|
+
const factory = modelRepositoryFactories.get(current);
|
|
8224
|
+
if (!factory)
|
|
8225
|
+
continue;
|
|
8226
|
+
const repository = factory();
|
|
8227
|
+
modelRepositories.set(model, repository);
|
|
8228
|
+
nameModel(model);
|
|
8229
|
+
return repository;
|
|
8171
8230
|
}
|
|
8172
|
-
|
|
8173
|
-
|
|
8174
|
-
|
|
8175
|
-
|
|
8176
|
-
|
|
8177
|
-
|
|
8178
|
-
|
|
8179
|
-
|
|
8180
|
-
|
|
8181
|
-
|
|
8182
|
-
|
|
8231
|
+
throw new Error(`${model.name}.repository() is not implemented.`);
|
|
8232
|
+
}
|
|
8233
|
+
function registerModelClass(name, model) {
|
|
8234
|
+
namedModels.set(name, model);
|
|
8235
|
+
}
|
|
8236
|
+
function registerModelRepositoryFactory(model, factory) {
|
|
8237
|
+
modelRepositoryFactories.set(model, factory);
|
|
8238
|
+
}
|
|
8239
|
+
function bindModelRepository(model, repository) {
|
|
8240
|
+
modelRepositories.set(model, repository);
|
|
8241
|
+
}
|
|
8242
|
+
function findNamedModel(name) {
|
|
8243
|
+
return namedModels.get(name);
|
|
8244
|
+
}
|
|
8245
|
+
function getModelObservers(model) {
|
|
8246
|
+
return modelObservers.get(model);
|
|
8247
|
+
}
|
|
8248
|
+
function restoreModelObservers(model, observers) {
|
|
8249
|
+
if (observers)
|
|
8250
|
+
modelObservers.set(model, observers);
|
|
8251
|
+
else
|
|
8252
|
+
modelObservers.delete(model);
|
|
8253
|
+
}
|
|
8254
|
+
function observeModel(model, observer) {
|
|
8255
|
+
const existing = modelObservers.get(model) ?? [];
|
|
8256
|
+
modelObservers.set(model, [...existing, observer]);
|
|
8257
|
+
}
|
|
8258
|
+
function ensureBooted(model) {
|
|
8259
|
+
if (modelBooted.has(model)) {
|
|
8260
|
+
return;
|
|
8183
8261
|
}
|
|
8184
|
-
|
|
8185
|
-
|
|
8262
|
+
nameModel(model);
|
|
8263
|
+
modelBooted.add(model);
|
|
8264
|
+
const scopes = modelGlobalScopes.get(model);
|
|
8265
|
+
const observers = getModelObservers(model);
|
|
8266
|
+
const boot = model.boot;
|
|
8267
|
+
if (typeof boot === "function") {
|
|
8268
|
+
try {
|
|
8269
|
+
boot.call(model);
|
|
8270
|
+
} catch (error) {
|
|
8271
|
+
modelBooted.delete(model);
|
|
8272
|
+
if (scopes)
|
|
8273
|
+
modelGlobalScopes.set(model, scopes);
|
|
8274
|
+
else
|
|
8275
|
+
modelGlobalScopes.delete(model);
|
|
8276
|
+
restoreModelObservers(model, observers);
|
|
8277
|
+
throw error;
|
|
8278
|
+
}
|
|
8186
8279
|
}
|
|
8187
8280
|
}
|
|
8281
|
+
function getGlobalScopes(model) {
|
|
8282
|
+
return modelGlobalScopes.get(model) ?? [];
|
|
8283
|
+
}
|
|
8284
|
+
function addModelGlobalScope(model, scope) {
|
|
8285
|
+
ensureBooted(model);
|
|
8286
|
+
const existing = modelGlobalScopes.get(model) ?? [];
|
|
8287
|
+
modelGlobalScopes.set(model, [
|
|
8288
|
+
...existing,
|
|
8289
|
+
scope
|
|
8290
|
+
]);
|
|
8291
|
+
}
|
|
8188
8292
|
|
|
8189
|
-
|
|
8190
|
-
|
|
8191
|
-
|
|
8192
|
-
|
|
8193
|
-
|
|
8194
|
-
|
|
8195
|
-
|
|
8196
|
-
|
|
8197
|
-
|
|
8198
|
-
|
|
8199
|
-
|
|
8200
|
-
|
|
8201
|
-
|
|
8202
|
-
|
|
8203
|
-
|
|
8204
|
-
|
|
8293
|
+
// ../../src/core/database/modelQuery.ts
|
|
8294
|
+
function modelStatics(model) {
|
|
8295
|
+
return model;
|
|
8296
|
+
}
|
|
8297
|
+
function flattenRelationNames(relations) {
|
|
8298
|
+
const names = [];
|
|
8299
|
+
for (const item of relations) {
|
|
8300
|
+
if (typeof item === "string") {
|
|
8301
|
+
if (item.length > 0) {
|
|
8302
|
+
names.push(item);
|
|
8303
|
+
}
|
|
8304
|
+
continue;
|
|
8305
|
+
}
|
|
8306
|
+
if (Array.isArray(item)) {
|
|
8307
|
+
for (const nested of item) {
|
|
8308
|
+
if (typeof nested === "string" && nested.length > 0) {
|
|
8309
|
+
names.push(nested);
|
|
8310
|
+
}
|
|
8311
|
+
}
|
|
8312
|
+
}
|
|
8205
8313
|
}
|
|
8206
|
-
|
|
8207
|
-
|
|
8208
|
-
|
|
8314
|
+
return names;
|
|
8315
|
+
}
|
|
8316
|
+
function isLoadableModel(value) {
|
|
8317
|
+
return Boolean(value && typeof value === "object" && typeof value.load === "function" && typeof value.loaded === "function" && typeof value.setLoaded === "function");
|
|
8318
|
+
}
|
|
8319
|
+
async function eagerLoadOnModels(models, paths) {
|
|
8320
|
+
if (models.length === 0 || paths.length === 0) {
|
|
8321
|
+
return;
|
|
8209
8322
|
}
|
|
8210
|
-
|
|
8211
|
-
|
|
8323
|
+
const grouped = new Map;
|
|
8324
|
+
for (const path of paths) {
|
|
8325
|
+
const [head, ...rest] = path.split(".");
|
|
8326
|
+
if (!head) {
|
|
8327
|
+
continue;
|
|
8328
|
+
}
|
|
8329
|
+
const nested = rest.join(".");
|
|
8330
|
+
const existing = grouped.get(head) ?? [];
|
|
8331
|
+
if (nested) {
|
|
8332
|
+
existing.push(nested);
|
|
8333
|
+
}
|
|
8334
|
+
grouped.set(head, existing);
|
|
8212
8335
|
}
|
|
8213
|
-
|
|
8214
|
-
const
|
|
8215
|
-
|
|
8336
|
+
await Promise.all([...grouped.entries()].map(async ([head, nested]) => {
|
|
8337
|
+
const unloaded = models.filter((model) => model.loaded(head) === undefined);
|
|
8338
|
+
if (unloaded.length > 0) {
|
|
8339
|
+
const first = unloaded[0];
|
|
8340
|
+
if (!first) {
|
|
8341
|
+
return;
|
|
8342
|
+
}
|
|
8343
|
+
const method = first[head];
|
|
8344
|
+
if (typeof method !== "function") {
|
|
8345
|
+
throw new Error(`${first.constructor.name} has no relation method ${head}().`);
|
|
8346
|
+
}
|
|
8347
|
+
const relationQuery = method.call(first);
|
|
8348
|
+
const query = first.getRepository().query();
|
|
8349
|
+
relationQuery.applyEagerLoad(query, head);
|
|
8350
|
+
const attached = await query.attachToRows(unloaded.map((model) => model.toObject()));
|
|
8351
|
+
for (const [index, model] of unloaded.entries()) {
|
|
8352
|
+
const row = attached[index] ?? model.toObject();
|
|
8353
|
+
model.setLoaded(head, relationQuery.hydrateEager(row, head));
|
|
8354
|
+
}
|
|
8355
|
+
}
|
|
8356
|
+
if (nested.length === 0) {
|
|
8357
|
+
return;
|
|
8358
|
+
}
|
|
8359
|
+
const children = models.flatMap((model) => {
|
|
8360
|
+
const loaded = model.loaded(head);
|
|
8361
|
+
return Array.isArray(loaded) ? loaded : loaded ? [loaded] : [];
|
|
8362
|
+
});
|
|
8363
|
+
await eagerLoadOnModels(children.filter(isLoadableModel), nested);
|
|
8364
|
+
}));
|
|
8365
|
+
}
|
|
8366
|
+
async function loadNested(model, path) {
|
|
8367
|
+
await eagerLoadOnModels([model], [path]);
|
|
8368
|
+
}
|
|
8369
|
+
function castPluckedValue(modelClass, column, value) {
|
|
8370
|
+
const cast = modelStatics(modelClass).$casts?.[column];
|
|
8371
|
+
return cast ? hydrateValue(value, cast) : value;
|
|
8372
|
+
}
|
|
8373
|
+
|
|
8374
|
+
class ModelProjection {
|
|
8375
|
+
load;
|
|
8376
|
+
page;
|
|
8377
|
+
constructor(load, page) {
|
|
8378
|
+
this.load = load;
|
|
8379
|
+
this.page = page;
|
|
8216
8380
|
}
|
|
8217
|
-
|
|
8218
|
-
return this.
|
|
8381
|
+
keysetPaginate(options) {
|
|
8382
|
+
return this.page(options);
|
|
8219
8383
|
}
|
|
8220
|
-
|
|
8221
|
-
return this.
|
|
8384
|
+
get() {
|
|
8385
|
+
return this.load();
|
|
8222
8386
|
}
|
|
8223
8387
|
async first() {
|
|
8224
|
-
return this.
|
|
8225
|
-
}
|
|
8226
|
-
async count() {
|
|
8227
|
-
return this.inner.count();
|
|
8228
|
-
}
|
|
8229
|
-
async pluck(column, keyBy) {
|
|
8230
|
-
const query = this.inner.limit(1);
|
|
8231
|
-
return keyBy === undefined ? query.pluck(column) : query.pluck(column, keyBy);
|
|
8232
|
-
}
|
|
8233
|
-
async value(column) {
|
|
8234
|
-
return this.inner.limit(1).value(column);
|
|
8235
|
-
}
|
|
8236
|
-
then(onfulfilled, onrejected) {
|
|
8237
|
-
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
8238
|
-
}
|
|
8239
|
-
async create(attributes = {}) {
|
|
8240
|
-
return this.inner.create(attributes);
|
|
8241
|
-
}
|
|
8242
|
-
async save(related) {
|
|
8243
|
-
return this.inner.save(related);
|
|
8388
|
+
return (await this.load(1))[0] ?? null;
|
|
8244
8389
|
}
|
|
8245
8390
|
}
|
|
8246
8391
|
|
|
8247
|
-
class
|
|
8248
|
-
|
|
8249
|
-
|
|
8250
|
-
|
|
8251
|
-
|
|
8252
|
-
|
|
8253
|
-
|
|
8254
|
-
constructor(parent, related, relation) {
|
|
8255
|
-
this.parent = parent;
|
|
8256
|
-
this.related = related;
|
|
8257
|
-
this.relation = relation;
|
|
8392
|
+
class ModelQuery {
|
|
8393
|
+
modelClass;
|
|
8394
|
+
query;
|
|
8395
|
+
eager = [];
|
|
8396
|
+
constructor(modelClass, query) {
|
|
8397
|
+
this.modelClass = modelClass;
|
|
8398
|
+
this.query = query;
|
|
8258
8399
|
}
|
|
8259
|
-
|
|
8260
|
-
this.
|
|
8400
|
+
with(...relations) {
|
|
8401
|
+
const statics = modelStatics(this.modelClass);
|
|
8402
|
+
ensureBooted(this.modelClass);
|
|
8403
|
+
const dummy = statics.newFromRecord({}, false);
|
|
8404
|
+
for (const path of flattenRelationNames(relations)) {
|
|
8405
|
+
const name = path.split(".")[0] ?? path;
|
|
8406
|
+
const method = dummy[name];
|
|
8407
|
+
if (typeof method !== "function") {
|
|
8408
|
+
throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
|
|
8409
|
+
}
|
|
8410
|
+
const relationQuery = method.call(dummy);
|
|
8411
|
+
this.eager.push({ name, path, relationQuery });
|
|
8412
|
+
relationQuery.applyEagerLoad(this.query, name);
|
|
8413
|
+
}
|
|
8261
8414
|
return this;
|
|
8262
8415
|
}
|
|
8263
|
-
|
|
8264
|
-
this.
|
|
8416
|
+
where(input) {
|
|
8417
|
+
this.query.where(input);
|
|
8265
8418
|
return this;
|
|
8266
8419
|
}
|
|
8267
|
-
|
|
8268
|
-
|
|
8420
|
+
orWhere(input) {
|
|
8421
|
+
this.query.orWhere(input);
|
|
8422
|
+
return this;
|
|
8269
8423
|
}
|
|
8270
|
-
|
|
8271
|
-
|
|
8272
|
-
return
|
|
8424
|
+
whereDynamic(input) {
|
|
8425
|
+
this.query.where(input);
|
|
8426
|
+
return this;
|
|
8273
8427
|
}
|
|
8274
|
-
|
|
8275
|
-
|
|
8276
|
-
|
|
8277
|
-
|
|
8278
|
-
|
|
8428
|
+
select(...columns) {
|
|
8429
|
+
return new ModelProjection(async (limit) => {
|
|
8430
|
+
const rows = await this.query.project(columns, limit);
|
|
8431
|
+
return rows.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"));
|
|
8432
|
+
}, async (options) => {
|
|
8433
|
+
const page = await this.query.projectKeyset(columns, options);
|
|
8434
|
+
return {
|
|
8435
|
+
...page,
|
|
8436
|
+
data: page.data.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"))
|
|
8437
|
+
};
|
|
8438
|
+
});
|
|
8279
8439
|
}
|
|
8280
|
-
|
|
8281
|
-
|
|
8282
|
-
|
|
8283
|
-
return null;
|
|
8284
|
-
}
|
|
8285
|
-
const row = await query.first();
|
|
8286
|
-
return row ? this.related.newFromRecord(row) : null;
|
|
8440
|
+
lockForUpdate(options = {}) {
|
|
8441
|
+
this.query.lockForUpdate(options);
|
|
8442
|
+
return this;
|
|
8287
8443
|
}
|
|
8288
|
-
|
|
8289
|
-
|
|
8444
|
+
sharedLock(options = {}) {
|
|
8445
|
+
this.query.sharedLock(options);
|
|
8446
|
+
return this;
|
|
8290
8447
|
}
|
|
8291
|
-
|
|
8292
|
-
|
|
8448
|
+
orderBy(orderBy) {
|
|
8449
|
+
this.query.orderBy(orderBy);
|
|
8450
|
+
return this;
|
|
8293
8451
|
}
|
|
8294
|
-
|
|
8295
|
-
|
|
8452
|
+
limit(limit) {
|
|
8453
|
+
this.query.limit(limit);
|
|
8454
|
+
return this;
|
|
8296
8455
|
}
|
|
8297
|
-
|
|
8298
|
-
|
|
8299
|
-
|
|
8300
|
-
return null;
|
|
8301
|
-
}
|
|
8302
|
-
return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({ [this.relation.ownerKey]: foreign }), this.extraWhere, this.extraOptions);
|
|
8456
|
+
offset(offset) {
|
|
8457
|
+
this.query.offset(offset);
|
|
8458
|
+
return this;
|
|
8303
8459
|
}
|
|
8304
|
-
|
|
8305
|
-
|
|
8460
|
+
whereNull(column) {
|
|
8461
|
+
this.query.whereNull(column);
|
|
8462
|
+
return this;
|
|
8306
8463
|
}
|
|
8307
|
-
|
|
8308
|
-
|
|
8309
|
-
|
|
8310
|
-
});
|
|
8464
|
+
whereNotNull(column) {
|
|
8465
|
+
this.query.whereNotNull(column);
|
|
8466
|
+
return this;
|
|
8311
8467
|
}
|
|
8312
|
-
|
|
8313
|
-
|
|
8314
|
-
|
|
8315
|
-
});
|
|
8468
|
+
whereIn(column, values) {
|
|
8469
|
+
this.query.whereIn(column, values);
|
|
8470
|
+
return this;
|
|
8316
8471
|
}
|
|
8317
|
-
|
|
8318
|
-
|
|
8319
|
-
|
|
8320
|
-
}
|
|
8321
|
-
function hasRepeatedId(ids) {
|
|
8322
|
-
const seen = new Set;
|
|
8323
|
-
for (const id of ids) {
|
|
8324
|
-
const key = pivotIdKey(id);
|
|
8325
|
-
if (seen.has(key))
|
|
8326
|
-
return true;
|
|
8327
|
-
seen.add(key);
|
|
8472
|
+
whereNotIn(column, values) {
|
|
8473
|
+
this.query.whereNotIn(column, values);
|
|
8474
|
+
return this;
|
|
8328
8475
|
}
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8332
|
-
return ids.every((id) => typeof id === "bigint" && id >= BigInt(Number.MIN_SAFE_INTEGER) && id <= BigInt(Number.MAX_SAFE_INTEGER) || typeof id === "number" && Number.isSafeInteger(id) || typeof id === "string" && /^(?:0|-?[1-9]\d*)$/.test(id) && Number.isSafeInteger(Number(id)));
|
|
8333
|
-
}
|
|
8334
|
-
function isConfiguredConnection(connection) {
|
|
8335
|
-
const bound = getBoundDatabaseConnection();
|
|
8336
|
-
return connection === repositoryConnection || (bound ? connection === bound : isDefaultDatabaseConnection(connection));
|
|
8337
|
-
}
|
|
8338
|
-
|
|
8339
|
-
class BelongsToManyRelationQuery {
|
|
8340
|
-
parent;
|
|
8341
|
-
related;
|
|
8342
|
-
relation;
|
|
8343
|
-
kind = "belongsToMany";
|
|
8344
|
-
extraWhere = [];
|
|
8345
|
-
extraOptions = {};
|
|
8346
|
-
pivotValues = {};
|
|
8347
|
-
constructor(parent, related, relation) {
|
|
8348
|
-
this.parent = parent;
|
|
8349
|
-
this.related = related;
|
|
8350
|
-
this.relation = relation;
|
|
8476
|
+
groupBy(groupBy) {
|
|
8477
|
+
this.query.groupBy(groupBy);
|
|
8478
|
+
return this;
|
|
8351
8479
|
}
|
|
8352
|
-
|
|
8353
|
-
this.
|
|
8480
|
+
having(having) {
|
|
8481
|
+
this.query.having(having);
|
|
8354
8482
|
return this;
|
|
8355
8483
|
}
|
|
8356
|
-
|
|
8357
|
-
this.
|
|
8484
|
+
join(left, right) {
|
|
8485
|
+
this.query.join(left, right);
|
|
8358
8486
|
return this;
|
|
8359
8487
|
}
|
|
8360
|
-
|
|
8361
|
-
|
|
8488
|
+
leftJoin(left, right) {
|
|
8489
|
+
this.query.leftJoin(left, right);
|
|
8490
|
+
return this;
|
|
8362
8491
|
}
|
|
8363
|
-
|
|
8364
|
-
|
|
8492
|
+
async paginate(options) {
|
|
8493
|
+
const { data, meta } = await this.query.paginate(options);
|
|
8494
|
+
return { data: await this.hydrateRows(data), meta };
|
|
8495
|
+
}
|
|
8496
|
+
whereExists(sql, params = []) {
|
|
8497
|
+
this.query.whereExists(sql, params);
|
|
8365
8498
|
return this;
|
|
8366
8499
|
}
|
|
8367
|
-
|
|
8368
|
-
|
|
8369
|
-
|
|
8370
|
-
return rows.map((item) => this.related.newFromRecord(item));
|
|
8500
|
+
whereNotExists(sql, params = []) {
|
|
8501
|
+
this.query.whereNotExists(sql, params);
|
|
8502
|
+
return this;
|
|
8371
8503
|
}
|
|
8372
|
-
|
|
8373
|
-
|
|
8374
|
-
const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.pivotTable]);
|
|
8375
|
-
const sql = `SELECT 1 FROM ${quoteIdentifier(relatedTable)} INNER JOIN ${quoteIdentifier(this.relation.pivotTable)} ON ${qualifyColumn(this.relation.pivotTable, this.relation.relatedPivotKey)} = ${qualifyColumn(relatedTable, this.relation.relatedKey)}${extra.joins} WHERE ${qualifyColumn(this.relation.pivotTable, this.relation.foreignPivotKey)} = ${qualifyColumn(parentTable, this.relation.parentKey)}${extra.sql}`;
|
|
8376
|
-
return { sql, params: extra.params };
|
|
8504
|
+
whereHas(name, constrain) {
|
|
8505
|
+
return this.constrainExists(name, constrain, false);
|
|
8377
8506
|
}
|
|
8378
|
-
|
|
8379
|
-
|
|
8380
|
-
return isConfiguredConnection(connection) ? getActiveDatabaseConnection(connection) : connection;
|
|
8507
|
+
has(name) {
|
|
8508
|
+
return this.constrainExists(name, undefined, false);
|
|
8381
8509
|
}
|
|
8382
|
-
|
|
8383
|
-
|
|
8384
|
-
if (isConfiguredConnection(connection) || hasActiveDatabaseConnection() && connection === getActiveDatabaseConnection(connection)) {
|
|
8385
|
-
await runInTransaction(work);
|
|
8386
|
-
return;
|
|
8387
|
-
}
|
|
8388
|
-
if (typeof connection.begin !== "function") {
|
|
8389
|
-
await work(connection);
|
|
8390
|
-
return;
|
|
8391
|
-
}
|
|
8392
|
-
await connection.begin(work);
|
|
8510
|
+
doesntHave(name) {
|
|
8511
|
+
return this.constrainExists(name, undefined, true);
|
|
8393
8512
|
}
|
|
8394
|
-
|
|
8395
|
-
|
|
8396
|
-
const rows = query ? await query.get() : [];
|
|
8397
|
-
return rows.map((row) => this.related.newFromRecord(row));
|
|
8513
|
+
whereDoesntHave(name, constrain) {
|
|
8514
|
+
return this.constrainExists(name, constrain, true);
|
|
8398
8515
|
}
|
|
8399
|
-
|
|
8400
|
-
|
|
8401
|
-
return
|
|
8516
|
+
withHasMany(...args) {
|
|
8517
|
+
this.query.withHasMany(...args);
|
|
8518
|
+
return this;
|
|
8402
8519
|
}
|
|
8403
|
-
|
|
8404
|
-
|
|
8405
|
-
return
|
|
8520
|
+
withBelongsTo(...args) {
|
|
8521
|
+
this.query.withBelongsTo(...args);
|
|
8522
|
+
return this;
|
|
8406
8523
|
}
|
|
8407
|
-
|
|
8408
|
-
|
|
8524
|
+
withBelongsToMany(...args) {
|
|
8525
|
+
this.query.withBelongsToMany(...args);
|
|
8526
|
+
return this;
|
|
8409
8527
|
}
|
|
8410
|
-
|
|
8411
|
-
|
|
8412
|
-
return
|
|
8528
|
+
withMorphMany(...args) {
|
|
8529
|
+
this.query.withMorphMany(...args);
|
|
8530
|
+
return this;
|
|
8413
8531
|
}
|
|
8414
|
-
|
|
8415
|
-
|
|
8416
|
-
|
|
8417
|
-
if (pivotRows.length === 0) {
|
|
8418
|
-
return null;
|
|
8419
|
-
}
|
|
8420
|
-
const relatedIds = [
|
|
8421
|
-
...new Set(pivotRows.map((row) => row[this.relation.relatedPivotKey]))
|
|
8422
|
-
];
|
|
8423
|
-
return relatedRead(this.related, this.connection(), asWhere({ [this.relation.relatedKey]: relatedIds }), this.extraWhere, this.extraOptions);
|
|
8532
|
+
withMorphOne(...args) {
|
|
8533
|
+
this.query.withMorphOne(...args);
|
|
8534
|
+
return this;
|
|
8424
8535
|
}
|
|
8425
|
-
|
|
8426
|
-
|
|
8536
|
+
withMorphTo(...args) {
|
|
8537
|
+
this.query.withMorphTo(...args);
|
|
8538
|
+
return this;
|
|
8427
8539
|
}
|
|
8428
|
-
|
|
8429
|
-
|
|
8430
|
-
|
|
8431
|
-
return;
|
|
8432
|
-
await this.atomically((connection) => this.insertPivotRows(connection, list));
|
|
8540
|
+
withHasManyThrough(...args) {
|
|
8541
|
+
this.query.withHasManyThrough(...args);
|
|
8542
|
+
return this;
|
|
8433
8543
|
}
|
|
8434
|
-
|
|
8435
|
-
|
|
8436
|
-
|
|
8437
|
-
return;
|
|
8438
|
-
await this.atomically(async (connection) => {
|
|
8439
|
-
if (!canBatchPivotToggle(list) || hasRepeatedId(list)) {
|
|
8440
|
-
for (const id of list)
|
|
8441
|
-
await this.toggleOne(connection, id);
|
|
8442
|
-
return;
|
|
8443
|
-
}
|
|
8444
|
-
const parentId = this.parent.get(this.relation.parentKey);
|
|
8445
|
-
const relatedColumn = quoteIdentifier(String(this.relation.relatedPivotKey));
|
|
8446
|
-
const parentColumn = quoteIdentifier(String(this.relation.foreignPivotKey));
|
|
8447
|
-
const placeholders = list.map((_, index) => currentSqlDialect().placeholder(index + 2));
|
|
8448
|
-
const existing = await connection.unsafe(`SELECT ${relatedColumn} FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${parentColumn} = ${currentSqlDialect().placeholder(1)} AND ${relatedColumn} IN (${placeholders.join(", ")})`, [parentId, ...list]);
|
|
8449
|
-
const existingIds = new Set(existing.map((row) => pivotIdKey(row[String(this.relation.relatedPivotKey)])));
|
|
8450
|
-
const present = list.filter((id) => existingIds.has(pivotIdKey(id)));
|
|
8451
|
-
const missing = list.filter((id) => !existingIds.has(pivotIdKey(id)));
|
|
8452
|
-
if (present.length > 0)
|
|
8453
|
-
await this.deletePivotRows(connection, present);
|
|
8454
|
-
if (missing.length > 0)
|
|
8455
|
-
await this.insertPivotRows(connection, missing);
|
|
8456
|
-
});
|
|
8544
|
+
withTrashed() {
|
|
8545
|
+
this.query.withTrashed();
|
|
8546
|
+
return this;
|
|
8457
8547
|
}
|
|
8458
|
-
|
|
8459
|
-
|
|
8460
|
-
|
|
8461
|
-
await this.connection().unsafe(`DELETE FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)}`, [parentId]);
|
|
8462
|
-
return;
|
|
8463
|
-
}
|
|
8464
|
-
const list = Array.isArray(ids) ? ids : [ids];
|
|
8465
|
-
if (list.length === 0)
|
|
8466
|
-
return;
|
|
8467
|
-
await this.deletePivotRows(this.connection(), list);
|
|
8548
|
+
onlyTrashed() {
|
|
8549
|
+
this.query.onlyTrashed();
|
|
8550
|
+
return this;
|
|
8468
8551
|
}
|
|
8469
|
-
async
|
|
8470
|
-
|
|
8471
|
-
const existing = await connection.unsafe(`SELECT 1 FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)} AND ${quoteIdentifier(String(this.relation.relatedPivotKey))} = ${currentSqlDialect().placeholder(2)} LIMIT 1`, [parentId, id]);
|
|
8472
|
-
if (existing.length > 0)
|
|
8473
|
-
await this.deletePivotRows(connection, [id]);
|
|
8474
|
-
else
|
|
8475
|
-
await this.insertPivotRows(connection, [id]);
|
|
8552
|
+
async get() {
|
|
8553
|
+
return await this.hydrateRows(await this.query.get());
|
|
8476
8554
|
}
|
|
8477
|
-
async
|
|
8478
|
-
const
|
|
8479
|
-
|
|
8480
|
-
const extraColumns = extraKeys.length > 0 ? `, ${extraKeys.map((key) => quoteIdentifier(key)).join(", ")}` : "";
|
|
8481
|
-
const extraValues = extraKeys.map((key) => this.pivotValues[key]);
|
|
8482
|
-
const width = 2 + extraKeys.length;
|
|
8483
|
-
const tuples = list.map((_, row) => {
|
|
8484
|
-
const slots = Array.from({ length: width }, (__, column) => currentSqlDialect().placeholder(row * width + column + 1));
|
|
8485
|
-
return `(${slots.join(", ")})`;
|
|
8486
|
-
});
|
|
8487
|
-
const params = [];
|
|
8488
|
-
for (const id of list)
|
|
8489
|
-
params.push(parentId, id, ...extraValues);
|
|
8490
|
-
await connection.unsafe(`INSERT INTO ${quoteIdentifier(this.relation.pivotTable)} (${quoteIdentifier(String(this.relation.foreignPivotKey))}, ${quoteIdentifier(String(this.relation.relatedPivotKey))}${extraColumns}) VALUES ${tuples.join(", ")}`, params);
|
|
8555
|
+
async keysetPaginate(options) {
|
|
8556
|
+
const page = await this.query.keysetPaginate(options);
|
|
8557
|
+
return { ...page, data: await this.hydrateRows(page.data) };
|
|
8491
8558
|
}
|
|
8492
|
-
async
|
|
8493
|
-
const
|
|
8494
|
-
const
|
|
8495
|
-
|
|
8559
|
+
async hydrateRows(rows) {
|
|
8560
|
+
const statics = modelStatics(this.modelClass);
|
|
8561
|
+
const models = [];
|
|
8562
|
+
for (const row of rows) {
|
|
8563
|
+
const model = statics.newFromRecord(row, true);
|
|
8564
|
+
for (const { name, relationQuery } of this.eager) {
|
|
8565
|
+
model.setLoaded(name, relationQuery.hydrateEager(row, name));
|
|
8566
|
+
}
|
|
8567
|
+
models.push(model);
|
|
8568
|
+
}
|
|
8569
|
+
await Promise.all(models.map((model) => runObservers(model, "retrieved")));
|
|
8570
|
+
const nested = this.eager.filter((item) => item.path.includes(".")).map((item) => item.path);
|
|
8571
|
+
await eagerLoadOnModels(models.filter(isLoadableModel), nested);
|
|
8572
|
+
return models;
|
|
8496
8573
|
}
|
|
8497
|
-
async
|
|
8498
|
-
|
|
8499
|
-
|
|
8500
|
-
|
|
8574
|
+
async first() {
|
|
8575
|
+
this.query.limit(1);
|
|
8576
|
+
const models = await this.get();
|
|
8577
|
+
return models[0] ?? null;
|
|
8578
|
+
}
|
|
8579
|
+
async count() {
|
|
8580
|
+
return this.query.count();
|
|
8581
|
+
}
|
|
8582
|
+
async pluck(column, keyBy) {
|
|
8583
|
+
if (keyBy === undefined) {
|
|
8584
|
+
const values = await this.query.pluck(column);
|
|
8585
|
+
return values.map((value) => castPluckedValue(this.modelClass, column, value));
|
|
8586
|
+
}
|
|
8587
|
+
const keyed = await this.query.pluck(column, keyBy);
|
|
8588
|
+
const result = new Map;
|
|
8589
|
+
for (const [key, value] of keyed) {
|
|
8590
|
+
result.set(castPluckedValue(this.modelClass, keyBy, key), castPluckedValue(this.modelClass, column, value));
|
|
8501
8591
|
}
|
|
8592
|
+
return result;
|
|
8502
8593
|
}
|
|
8503
|
-
async
|
|
8504
|
-
const
|
|
8505
|
-
|
|
8506
|
-
|
|
8594
|
+
async value(column) {
|
|
8595
|
+
const value = await this.query.value(column);
|
|
8596
|
+
return castPluckedValue(this.modelClass, column, value);
|
|
8597
|
+
}
|
|
8598
|
+
async find(id) {
|
|
8599
|
+
const primaryKey = resolveModelRepository(this.modelClass).getTable().primaryKey;
|
|
8600
|
+
return this.whereDynamic({ [primaryKey]: id }).first();
|
|
8601
|
+
}
|
|
8602
|
+
async findOrFail(id, errorFactory) {
|
|
8603
|
+
const model = await this.find(id);
|
|
8604
|
+
if (model) {
|
|
8605
|
+
return model;
|
|
8606
|
+
}
|
|
8607
|
+
throw errorFactory?.(id) ?? new NotFoundError(`${this.modelClass.name} ${String(id)} not found.`);
|
|
8608
|
+
}
|
|
8609
|
+
then(onfulfilled, onrejected) {
|
|
8610
|
+
return this.get().then(onfulfilled ?? undefined, onrejected ?? undefined);
|
|
8611
|
+
}
|
|
8612
|
+
withCount(name, alias = `${name}_count`) {
|
|
8613
|
+
const statics = modelStatics(this.modelClass);
|
|
8614
|
+
ensureBooted(this.modelClass);
|
|
8615
|
+
const repository = resolveModelRepository(this.modelClass);
|
|
8616
|
+
const dummy = statics.newFromRecord({});
|
|
8617
|
+
const method = dummy[name];
|
|
8618
|
+
if (typeof method !== "function") {
|
|
8619
|
+
throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
|
|
8620
|
+
}
|
|
8621
|
+
const relationQuery = method.call(dummy);
|
|
8622
|
+
const exists = relationQuery.toExistsClause(repository.getTable().name);
|
|
8623
|
+
if (!exists.sql.startsWith("SELECT 1 ")) {
|
|
8624
|
+
throw new Error(`Cannot count relation ${name}: unexpected subquery shape.`);
|
|
8625
|
+
}
|
|
8626
|
+
this.query.withSubqueryCount(alias, `SELECT COUNT(*) ${exists.sql.slice("SELECT 1 ".length)}`, exists.params);
|
|
8627
|
+
return this;
|
|
8628
|
+
}
|
|
8629
|
+
constrainExists(name, constrain, not) {
|
|
8630
|
+
const statics = modelStatics(this.modelClass);
|
|
8631
|
+
ensureBooted(this.modelClass);
|
|
8632
|
+
const repository = resolveModelRepository(this.modelClass);
|
|
8633
|
+
const dummy = statics.newFromRecord({});
|
|
8634
|
+
const method = dummy[name];
|
|
8635
|
+
if (typeof method !== "function") {
|
|
8636
|
+
throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
|
|
8637
|
+
}
|
|
8638
|
+
const relationQuery = method.call(dummy);
|
|
8639
|
+
constrain?.(relationQuery);
|
|
8640
|
+
const exists = relationQuery.toExistsClause(repository.getTable().name);
|
|
8641
|
+
return not ? this.whereNotExists(exists.sql, exists.params) : this.whereExists(exists.sql, exists.params);
|
|
8507
8642
|
}
|
|
8508
8643
|
}
|
|
8509
8644
|
|
|
8510
|
-
|
|
8645
|
+
// ../../src/core/database/relationQuery.ts
|
|
8646
|
+
init_boundConnection();
|
|
8647
|
+
init_connectionContext();
|
|
8648
|
+
init_defaultConnection();
|
|
8649
|
+
init_dialect();
|
|
8650
|
+
init_repositoryConnection();
|
|
8651
|
+
init_transaction();
|
|
8652
|
+
function asWhere(where) {
|
|
8653
|
+
return where;
|
|
8654
|
+
}
|
|
8655
|
+
function ownerId(owner, ownerKey) {
|
|
8656
|
+
if (typeof owner.get === "function") {
|
|
8657
|
+
return owner.get(ownerKey);
|
|
8658
|
+
}
|
|
8659
|
+
if (owner && typeof owner === "object" && "id" in owner && owner.id !== undefined) {
|
|
8660
|
+
return owner.id;
|
|
8661
|
+
}
|
|
8662
|
+
throw new Error("belongsTo.associate() requires a related model or { id }.");
|
|
8663
|
+
}
|
|
8664
|
+
function thenGet(get, onfulfilled, onrejected) {
|
|
8665
|
+
return get().then(onfulfilled ?? undefined, onrejected ?? undefined);
|
|
8666
|
+
}
|
|
8667
|
+
function pluckFromQuery(query, column, keyBy) {
|
|
8668
|
+
if (!query) {
|
|
8669
|
+
return Promise.resolve(keyBy === undefined ? [] : new Map);
|
|
8670
|
+
}
|
|
8671
|
+
return keyBy === undefined ? query.pluck(column) : query.pluck(column, keyBy);
|
|
8672
|
+
}
|
|
8673
|
+
function scopedRelatedQuery(model, repository = model.repository()) {
|
|
8674
|
+
const query = repository.query();
|
|
8675
|
+
const scopedModel = model;
|
|
8676
|
+
return scopedModel.scopeQuery?.(query) ?? query;
|
|
8677
|
+
}
|
|
8678
|
+
function relatedOptions(model, filters, options = {}) {
|
|
8679
|
+
const query = scopedRelatedQuery(model);
|
|
8680
|
+
for (const filter of filters)
|
|
8681
|
+
query.where(filter);
|
|
8682
|
+
return { ...query.getOptions(), ...options };
|
|
8683
|
+
}
|
|
8684
|
+
function relatedRead(model, connection, binding, filters, options = {}) {
|
|
8685
|
+
const query = scopedRelatedQuery(model, model.repository().withConnection(connection));
|
|
8686
|
+
query.where(binding).protectWhere();
|
|
8687
|
+
for (const filter of filters)
|
|
8688
|
+
query.where(filter);
|
|
8689
|
+
if (options.orderBy)
|
|
8690
|
+
query.orderBy(options.orderBy);
|
|
8691
|
+
if (options.limit !== undefined)
|
|
8692
|
+
query.limit(options.limit);
|
|
8693
|
+
return query;
|
|
8694
|
+
}
|
|
8695
|
+
function relatedConditions(model, filters, options = {}, parameters = [], reservedTables = []) {
|
|
8696
|
+
const compiled = relatedOptions(model, filters, options);
|
|
8697
|
+
if (compiled.joins?.some((join) => reservedTables.includes(join.table))) {
|
|
8698
|
+
throw new Error("A related model scope joins a reserved relation table; use an explicitly aliased correlated predicate instead.");
|
|
8699
|
+
}
|
|
8700
|
+
const extra = buildQueryWhereClause(model.repository().getTable(), compiled, compiled.whereNodes, parameters);
|
|
8701
|
+
const predicate = extra.clause.replace(/^ WHERE /, "");
|
|
8702
|
+
return {
|
|
8703
|
+
sql: predicate ? ` AND (${predicate})` : "",
|
|
8704
|
+
joins: buildJoinClause(compiled.joins),
|
|
8705
|
+
params: extra.params
|
|
8706
|
+
};
|
|
8707
|
+
}
|
|
8708
|
+
|
|
8709
|
+
class HasManyRelationQuery {
|
|
8511
8710
|
parent;
|
|
8512
8711
|
related;
|
|
8513
8712
|
relation;
|
|
8514
|
-
kind = "
|
|
8713
|
+
kind = "hasMany";
|
|
8515
8714
|
extraWhere = [];
|
|
8516
8715
|
extraOptions = {};
|
|
8517
8716
|
constructor(parent, related, relation) {
|
|
@@ -8523,8 +8722,16 @@ class MorphManyRelationQuery {
|
|
|
8523
8722
|
this.extraWhere.push({ ...where });
|
|
8524
8723
|
return this;
|
|
8525
8724
|
}
|
|
8725
|
+
orderBy(orderBy) {
|
|
8726
|
+
this.extraOptions = { ...this.extraOptions, orderBy };
|
|
8727
|
+
return this;
|
|
8728
|
+
}
|
|
8729
|
+
limit(limit) {
|
|
8730
|
+
this.extraOptions = { ...this.extraOptions, limit };
|
|
8731
|
+
return this;
|
|
8732
|
+
}
|
|
8526
8733
|
applyEagerLoad(query, alias) {
|
|
8527
|
-
query.
|
|
8734
|
+
query.withHasMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
|
|
8528
8735
|
}
|
|
8529
8736
|
hydrateEager(row, alias) {
|
|
8530
8737
|
const value = row[alias] ?? [];
|
|
@@ -8533,25 +8740,19 @@ class MorphManyRelationQuery {
|
|
|
8533
8740
|
}
|
|
8534
8741
|
toExistsClause(parentTable) {
|
|
8535
8742
|
const childTable = this.related.repository().getTable().name;
|
|
8536
|
-
const extra = relatedConditions(this.related, [
|
|
8537
|
-
|
|
8538
|
-
...this.extraWhere
|
|
8539
|
-
], this.extraOptions, [], [parentTable]);
|
|
8540
|
-
const sql = `SELECT 1 FROM ${quoteIdentifier(childTable)}${extra.joins} WHERE ${qualifyColumn(childTable, this.relation.morphIdKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
|
|
8743
|
+
const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable]);
|
|
8744
|
+
const sql = `SELECT 1 FROM ${quoteIdentifier(childTable)}${extra.joins} WHERE ${qualifyColumn(childTable, this.relation.foreignKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
|
|
8541
8745
|
return { sql, params: extra.params };
|
|
8542
8746
|
}
|
|
8543
8747
|
scopedQuery() {
|
|
8544
|
-
return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({
|
|
8545
|
-
[this.relation.morphTypeKey]: this.relation.morphType,
|
|
8546
|
-
[this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
|
|
8547
|
-
}), this.extraWhere);
|
|
8748
|
+
return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({ [this.relation.foreignKey]: this.parent.get(this.relation.localKey) }), this.extraWhere, this.extraOptions);
|
|
8548
8749
|
}
|
|
8549
8750
|
async get() {
|
|
8550
8751
|
const rows = await this.scopedQuery().get();
|
|
8551
8752
|
return rows.map((row) => this.related.newFromRecord(row));
|
|
8552
8753
|
}
|
|
8553
8754
|
async first() {
|
|
8554
|
-
const rows = await this.get();
|
|
8755
|
+
const rows = await this.limit(1).get();
|
|
8555
8756
|
return rows[0] ?? null;
|
|
8556
8757
|
}
|
|
8557
8758
|
async count() {
|
|
@@ -8568,31 +8769,47 @@ class MorphManyRelationQuery {
|
|
|
8568
8769
|
}
|
|
8569
8770
|
async create(attributes = {}) {
|
|
8570
8771
|
return this.related.create(attributes, {
|
|
8571
|
-
[this.relation.
|
|
8572
|
-
[this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
|
|
8772
|
+
[this.relation.foreignKey]: this.parent.get(this.relation.localKey)
|
|
8573
8773
|
});
|
|
8574
8774
|
}
|
|
8775
|
+
async save(related) {
|
|
8776
|
+
const forced = {
|
|
8777
|
+
[this.relation.foreignKey]: this.parent.get(this.relation.localKey)
|
|
8778
|
+
};
|
|
8779
|
+
const savable = related;
|
|
8780
|
+
if (typeof savable.save === "function") {
|
|
8781
|
+
savable.mergeAttributes?.(forced);
|
|
8782
|
+
await savable.save();
|
|
8783
|
+
return related;
|
|
8784
|
+
}
|
|
8785
|
+
return this.create(related);
|
|
8786
|
+
}
|
|
8787
|
+
async createMany(records) {
|
|
8788
|
+
return Promise.all(records.map((attributes) => this.create(attributes)));
|
|
8789
|
+
}
|
|
8575
8790
|
}
|
|
8576
8791
|
|
|
8577
|
-
class
|
|
8792
|
+
class HasOneRelationQuery {
|
|
8578
8793
|
relation;
|
|
8579
|
-
kind = "
|
|
8794
|
+
kind = "hasOne";
|
|
8580
8795
|
inner;
|
|
8581
8796
|
constructor(parent, related, relation) {
|
|
8582
8797
|
this.relation = relation;
|
|
8583
|
-
this.inner = new
|
|
8584
|
-
type: "
|
|
8798
|
+
this.inner = new HasManyRelationQuery(parent, related, {
|
|
8799
|
+
type: "hasMany",
|
|
8585
8800
|
name: relation.name,
|
|
8586
8801
|
localKey: relation.localKey,
|
|
8587
|
-
|
|
8588
|
-
morphIdKey: relation.morphIdKey,
|
|
8589
|
-
morphType: relation.morphType
|
|
8802
|
+
foreignKey: relation.foreignKey
|
|
8590
8803
|
});
|
|
8591
8804
|
}
|
|
8592
8805
|
where(where) {
|
|
8593
8806
|
this.inner.where(where);
|
|
8594
8807
|
return this;
|
|
8595
8808
|
}
|
|
8809
|
+
orderBy(orderBy) {
|
|
8810
|
+
this.inner.orderBy(orderBy);
|
|
8811
|
+
return this;
|
|
8812
|
+
}
|
|
8596
8813
|
applyEagerLoad(query, alias) {
|
|
8597
8814
|
this.inner.applyEagerLoad(query, alias);
|
|
8598
8815
|
}
|
|
@@ -8604,7 +8821,7 @@ class MorphOneRelationQuery {
|
|
|
8604
8821
|
return this.inner.toExistsClause(parentTable);
|
|
8605
8822
|
}
|
|
8606
8823
|
async get() {
|
|
8607
|
-
return this.inner.first();
|
|
8824
|
+
return this.inner.limit(1).first();
|
|
8608
8825
|
}
|
|
8609
8826
|
async first() {
|
|
8610
8827
|
return this.get();
|
|
@@ -8613,10 +8830,11 @@ class MorphOneRelationQuery {
|
|
|
8613
8830
|
return this.inner.count();
|
|
8614
8831
|
}
|
|
8615
8832
|
async pluck(column, keyBy) {
|
|
8616
|
-
|
|
8833
|
+
const query = this.inner.limit(1);
|
|
8834
|
+
return keyBy === undefined ? query.pluck(column) : query.pluck(column, keyBy);
|
|
8617
8835
|
}
|
|
8618
8836
|
async value(column) {
|
|
8619
|
-
return this.inner.value(column);
|
|
8837
|
+
return this.inner.limit(1).value(column);
|
|
8620
8838
|
}
|
|
8621
8839
|
then(onfulfilled, onrejected) {
|
|
8622
8840
|
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
@@ -8624,53 +8842,43 @@ class MorphOneRelationQuery {
|
|
|
8624
8842
|
async create(attributes = {}) {
|
|
8625
8843
|
return this.inner.create(attributes);
|
|
8626
8844
|
}
|
|
8845
|
+
async save(related) {
|
|
8846
|
+
return this.inner.save(related);
|
|
8847
|
+
}
|
|
8627
8848
|
}
|
|
8628
8849
|
|
|
8629
|
-
class
|
|
8850
|
+
class BelongsToRelationQuery {
|
|
8630
8851
|
parent;
|
|
8631
|
-
|
|
8852
|
+
related;
|
|
8632
8853
|
relation;
|
|
8633
|
-
kind = "
|
|
8854
|
+
kind = "belongsTo";
|
|
8634
8855
|
extraWhere = [];
|
|
8635
|
-
|
|
8856
|
+
extraOptions = {};
|
|
8857
|
+
constructor(parent, related, relation) {
|
|
8636
8858
|
this.parent = parent;
|
|
8637
|
-
this.
|
|
8859
|
+
this.related = related;
|
|
8638
8860
|
this.relation = relation;
|
|
8639
8861
|
}
|
|
8640
8862
|
where(where) {
|
|
8641
8863
|
this.extraWhere.push({ ...where });
|
|
8642
8864
|
return this;
|
|
8643
8865
|
}
|
|
8866
|
+
orderBy(orderBy) {
|
|
8867
|
+
this.extraOptions = { ...this.extraOptions, orderBy };
|
|
8868
|
+
return this;
|
|
8869
|
+
}
|
|
8644
8870
|
applyEagerLoad(query, alias) {
|
|
8645
|
-
|
|
8646
|
-
type,
|
|
8647
|
-
model.repository()
|
|
8648
|
-
]));
|
|
8649
|
-
query.withMorphTo(alias, this.relation, repositories, {}, new Map(Object.entries(this.relatedByType).map(([type, model]) => [
|
|
8650
|
-
type,
|
|
8651
|
-
relatedOptions(model, this.extraWhere)
|
|
8652
|
-
])));
|
|
8871
|
+
query.withBelongsTo(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
|
|
8653
8872
|
}
|
|
8654
8873
|
hydrateEager(row, alias) {
|
|
8655
|
-
|
|
8874
|
+
const value = row[alias];
|
|
8875
|
+
return value ? this.related.newFromRecord(value) : value;
|
|
8656
8876
|
}
|
|
8657
8877
|
toExistsClause(parentTable) {
|
|
8658
|
-
const
|
|
8659
|
-
const
|
|
8660
|
-
|
|
8661
|
-
|
|
8662
|
-
}
|
|
8663
|
-
const branches = Object.entries(this.relatedByType).map(([type, related]) => {
|
|
8664
|
-
params.push(type);
|
|
8665
|
-
const discriminator = currentSqlDialect().placeholder(params.length);
|
|
8666
|
-
const table = related.repository().getTable();
|
|
8667
|
-
const extra = relatedConditions(related, this.extraWhere, {}, params, [parentTable]);
|
|
8668
|
-
return `(${qualifyColumn(parentTable, this.relation.morphTypeKey)} = ${discriminator} AND EXISTS (SELECT 1 FROM ${quoteIdentifier(table.name)}${extra.joins} WHERE ${qualifyColumn(table.name, table.primaryKey)} = ${qualifyColumn(parentTable, this.relation.morphIdKey)}${extra.sql}))`;
|
|
8669
|
-
});
|
|
8670
|
-
return {
|
|
8671
|
-
sql: `SELECT 1 WHERE ${branches.length > 0 ? branches.join(" OR ") : "1 = 0"}`,
|
|
8672
|
-
params
|
|
8673
|
-
};
|
|
8878
|
+
const relatedTable = this.related.repository().getTable().name;
|
|
8879
|
+
const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable]);
|
|
8880
|
+
const sql = `SELECT 1 FROM ${quoteIdentifier(relatedTable)}${extra.joins} WHERE ${qualifyColumn(relatedTable, this.relation.ownerKey)} = ${qualifyColumn(parentTable, this.relation.foreignKey)}${extra.sql}`;
|
|
8881
|
+
return { sql, params: extra.params };
|
|
8674
8882
|
}
|
|
8675
8883
|
async get() {
|
|
8676
8884
|
const query = this.relatedQuery();
|
|
@@ -8678,7 +8886,10 @@ class MorphToRelationQuery {
|
|
|
8678
8886
|
return null;
|
|
8679
8887
|
}
|
|
8680
8888
|
const row = await query.first();
|
|
8681
|
-
return row ? this.
|
|
8889
|
+
return row ? this.related.newFromRecord(row) : null;
|
|
8890
|
+
}
|
|
8891
|
+
async first() {
|
|
8892
|
+
return this.get();
|
|
8682
8893
|
}
|
|
8683
8894
|
async pluck(column, keyBy) {
|
|
8684
8895
|
return pluckFromQuery(this.relatedQuery(), column, keyBy);
|
|
@@ -8686,31 +8897,56 @@ class MorphToRelationQuery {
|
|
|
8686
8897
|
async value(column) {
|
|
8687
8898
|
return this.relatedQuery()?.value(column) ?? null;
|
|
8688
8899
|
}
|
|
8689
|
-
relatedForCurrentType() {
|
|
8690
|
-
const type = String(this.parent.get(this.relation.morphTypeKey) ?? "");
|
|
8691
|
-
return this.relatedByType[type];
|
|
8692
|
-
}
|
|
8693
8900
|
relatedQuery() {
|
|
8694
|
-
const
|
|
8695
|
-
|
|
8696
|
-
if (!related || id === null || id === undefined) {
|
|
8901
|
+
const foreign = this.parent.get(this.relation.foreignKey);
|
|
8902
|
+
if (foreign === null || foreign === undefined) {
|
|
8697
8903
|
return null;
|
|
8698
8904
|
}
|
|
8699
|
-
|
|
8700
|
-
return relatedRead(related, this.parent.getRepository().getConnection(), asWhere({ [table.primaryKey]: id }), this.extraWhere);
|
|
8905
|
+
return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({ [this.relation.ownerKey]: foreign }), this.extraWhere, this.extraOptions);
|
|
8701
8906
|
}
|
|
8702
8907
|
then(onfulfilled, onrejected) {
|
|
8703
8908
|
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
8704
8909
|
}
|
|
8910
|
+
async associate(owner) {
|
|
8911
|
+
await this.parent.getRepository().updateById(this.parent.id, {
|
|
8912
|
+
[this.relation.foreignKey]: ownerId(owner, this.relation.ownerKey)
|
|
8913
|
+
});
|
|
8914
|
+
}
|
|
8915
|
+
async dissociate() {
|
|
8916
|
+
await this.parent.getRepository().updateById(this.parent.id, {
|
|
8917
|
+
[this.relation.foreignKey]: null
|
|
8918
|
+
});
|
|
8919
|
+
}
|
|
8920
|
+
}
|
|
8921
|
+
function pivotIdKey(id) {
|
|
8922
|
+
return typeof id === "number" || typeof id === "bigint" ? String(id) : id;
|
|
8923
|
+
}
|
|
8924
|
+
function hasRepeatedId(ids) {
|
|
8925
|
+
const seen = new Set;
|
|
8926
|
+
for (const id of ids) {
|
|
8927
|
+
const key = pivotIdKey(id);
|
|
8928
|
+
if (seen.has(key))
|
|
8929
|
+
return true;
|
|
8930
|
+
seen.add(key);
|
|
8931
|
+
}
|
|
8932
|
+
return false;
|
|
8933
|
+
}
|
|
8934
|
+
function canBatchPivotToggle(ids) {
|
|
8935
|
+
return ids.every((id) => typeof id === "bigint" && id >= BigInt(Number.MIN_SAFE_INTEGER) && id <= BigInt(Number.MAX_SAFE_INTEGER) || typeof id === "number" && Number.isSafeInteger(id) || typeof id === "string" && /^(?:0|-?[1-9]\d*)$/.test(id) && Number.isSafeInteger(Number(id)));
|
|
8936
|
+
}
|
|
8937
|
+
function isConfiguredConnection(connection) {
|
|
8938
|
+
const bound = getBoundDatabaseConnection();
|
|
8939
|
+
return connection === repositoryConnection || (bound ? connection === bound : isDefaultDatabaseConnection(connection));
|
|
8705
8940
|
}
|
|
8706
8941
|
|
|
8707
|
-
class
|
|
8942
|
+
class BelongsToManyRelationQuery {
|
|
8708
8943
|
parent;
|
|
8709
8944
|
related;
|
|
8710
8945
|
relation;
|
|
8711
|
-
kind = "
|
|
8946
|
+
kind = "belongsToMany";
|
|
8712
8947
|
extraWhere = [];
|
|
8713
8948
|
extraOptions = {};
|
|
8949
|
+
pivotValues = {};
|
|
8714
8950
|
constructor(parent, related, relation) {
|
|
8715
8951
|
this.parent = parent;
|
|
8716
8952
|
this.related = related;
|
|
@@ -8724,12 +8960,12 @@ class HasManyThroughRelationQuery {
|
|
|
8724
8960
|
this.extraOptions = { ...this.extraOptions, orderBy };
|
|
8725
8961
|
return this;
|
|
8726
8962
|
}
|
|
8727
|
-
limit(limit) {
|
|
8728
|
-
this.extraOptions = { ...this.extraOptions, limit };
|
|
8729
|
-
return this;
|
|
8730
|
-
}
|
|
8731
8963
|
applyEagerLoad(query, alias) {
|
|
8732
|
-
query.
|
|
8964
|
+
query.withBelongsToMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
|
|
8965
|
+
}
|
|
8966
|
+
withPivotValues(values) {
|
|
8967
|
+
this.pivotValues = { ...this.pivotValues, ...values };
|
|
8968
|
+
return this;
|
|
8733
8969
|
}
|
|
8734
8970
|
hydrateEager(row, alias) {
|
|
8735
8971
|
const value = row[alias] ?? [];
|
|
@@ -8737,667 +8973,481 @@ class HasManyThroughRelationQuery {
|
|
|
8737
8973
|
return rows.map((item) => this.related.newFromRecord(item));
|
|
8738
8974
|
}
|
|
8739
8975
|
toExistsClause(parentTable) {
|
|
8740
|
-
const
|
|
8741
|
-
const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.
|
|
8742
|
-
const sql = `SELECT 1 FROM ${quoteIdentifier(
|
|
8976
|
+
const relatedTable = this.related.repository().getTable().name;
|
|
8977
|
+
const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.pivotTable]);
|
|
8978
|
+
const sql = `SELECT 1 FROM ${quoteIdentifier(relatedTable)} INNER JOIN ${quoteIdentifier(this.relation.pivotTable)} ON ${qualifyColumn(this.relation.pivotTable, this.relation.relatedPivotKey)} = ${qualifyColumn(relatedTable, this.relation.relatedKey)}${extra.joins} WHERE ${qualifyColumn(this.relation.pivotTable, this.relation.foreignPivotKey)} = ${qualifyColumn(parentTable, this.relation.parentKey)}${extra.sql}`;
|
|
8743
8979
|
return { sql, params: extra.params };
|
|
8744
8980
|
}
|
|
8981
|
+
connection() {
|
|
8982
|
+
const connection = this.parent.getRepository().getConnection();
|
|
8983
|
+
return isConfiguredConnection(connection) ? getActiveDatabaseConnection(connection) : connection;
|
|
8984
|
+
}
|
|
8985
|
+
async atomically(work) {
|
|
8986
|
+
const connection = this.connection();
|
|
8987
|
+
if (isConfiguredConnection(connection) || hasActiveDatabaseConnection() && connection === getActiveDatabaseConnection(connection)) {
|
|
8988
|
+
await runInTransaction(work);
|
|
8989
|
+
return;
|
|
8990
|
+
}
|
|
8991
|
+
if (typeof connection.begin !== "function") {
|
|
8992
|
+
await work(connection);
|
|
8993
|
+
return;
|
|
8994
|
+
}
|
|
8995
|
+
await connection.begin(work);
|
|
8996
|
+
}
|
|
8745
8997
|
async get() {
|
|
8746
|
-
const
|
|
8998
|
+
const query = await this.relatedQuery();
|
|
8999
|
+
const rows = query ? await query.get() : [];
|
|
8747
9000
|
return rows.map((row) => this.related.newFromRecord(row));
|
|
8748
9001
|
}
|
|
8749
9002
|
async first() {
|
|
8750
|
-
const rows = await this.
|
|
9003
|
+
const rows = await this.get();
|
|
8751
9004
|
return rows[0] ?? null;
|
|
8752
9005
|
}
|
|
8753
9006
|
async count() {
|
|
8754
|
-
const
|
|
8755
|
-
return
|
|
9007
|
+
const query = await this.relatedQuery();
|
|
9008
|
+
return query ? query.count() : 0;
|
|
8756
9009
|
}
|
|
8757
9010
|
async pluck(column, keyBy) {
|
|
8758
|
-
|
|
8759
|
-
return keyBy === undefined ? projectPluck(rows, column) : projectPluck(rows, column, keyBy);
|
|
9011
|
+
return pluckFromQuery(await this.relatedQuery(), column, keyBy);
|
|
8760
9012
|
}
|
|
8761
9013
|
async value(column) {
|
|
8762
|
-
const
|
|
8763
|
-
return
|
|
9014
|
+
const query = await this.relatedQuery();
|
|
9015
|
+
return query ? query.value(column) : null;
|
|
8764
9016
|
}
|
|
8765
|
-
async
|
|
8766
|
-
|
|
8767
|
-
|
|
8768
|
-
|
|
9017
|
+
async relatedQuery() {
|
|
9018
|
+
const parentId = this.parent.get(this.relation.parentKey);
|
|
9019
|
+
const pivotRows = await this.connection().unsafe(`SELECT * FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)}`, [parentId]);
|
|
9020
|
+
if (pivotRows.length === 0) {
|
|
9021
|
+
return null;
|
|
9022
|
+
}
|
|
9023
|
+
const relatedIds = [
|
|
9024
|
+
...new Set(pivotRows.map((row) => row[this.relation.relatedPivotKey]))
|
|
9025
|
+
];
|
|
9026
|
+
return relatedRead(this.related, this.connection(), asWhere({ [this.relation.relatedKey]: relatedIds }), this.extraWhere, this.extraOptions);
|
|
8769
9027
|
}
|
|
8770
9028
|
then(onfulfilled, onrejected) {
|
|
8771
9029
|
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
8772
9030
|
}
|
|
8773
|
-
|
|
8774
|
-
|
|
8775
|
-
|
|
8776
|
-
|
|
8777
|
-
|
|
8778
|
-
key,
|
|
8779
|
-
Buffer.isBuffer(value) ? Buffer.from(value) : structuredClone(value)
|
|
8780
|
-
]));
|
|
8781
|
-
}
|
|
8782
|
-
function changedAttributes(values, original) {
|
|
8783
|
-
return Object.fromEntries(Object.entries(values).filter(([key, value]) => !(key in original) || !isDeepStrictEqual(value, original[key])));
|
|
8784
|
-
}
|
|
8785
|
-
var modelRepositories = new WeakMap;
|
|
8786
|
-
var modelRepositoryFactories = new WeakMap;
|
|
8787
|
-
var namedModels = new Map;
|
|
8788
|
-
var modelGlobalScopes = new WeakMap;
|
|
8789
|
-
var modelObservers = new WeakMap;
|
|
8790
|
-
var modelBooted = new WeakSet;
|
|
8791
|
-
function flattenRelationNames(relations) {
|
|
8792
|
-
const names = [];
|
|
8793
|
-
for (const item of relations) {
|
|
8794
|
-
if (typeof item === "string") {
|
|
8795
|
-
if (item.length > 0) {
|
|
8796
|
-
names.push(item);
|
|
8797
|
-
}
|
|
8798
|
-
continue;
|
|
8799
|
-
}
|
|
8800
|
-
if (Array.isArray(item)) {
|
|
8801
|
-
for (const nested of item) {
|
|
8802
|
-
if (typeof nested === "string" && nested.length > 0) {
|
|
8803
|
-
names.push(nested);
|
|
8804
|
-
}
|
|
8805
|
-
}
|
|
8806
|
-
}
|
|
8807
|
-
}
|
|
8808
|
-
return names;
|
|
8809
|
-
}
|
|
8810
|
-
async function runObservers(model, hook) {
|
|
8811
|
-
const observers = modelObservers.get(model.constructor) ?? [];
|
|
8812
|
-
for (const observer of observers) {
|
|
8813
|
-
const handler = observer[hook];
|
|
8814
|
-
if (handler && await handler(model) === false) {
|
|
8815
|
-
return false;
|
|
8816
|
-
}
|
|
8817
|
-
}
|
|
8818
|
-
return true;
|
|
8819
|
-
}
|
|
8820
|
-
function accessorName(key) {
|
|
8821
|
-
const pascal = key.replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
|
|
8822
|
-
return `get${pascal.charAt(0).toUpperCase()}${pascal.slice(1)}Attribute`;
|
|
8823
|
-
}
|
|
8824
|
-
function isLoadableModel(value) {
|
|
8825
|
-
return Boolean(value && typeof value === "object" && typeof value.load === "function" && typeof value.loaded === "function" && typeof value.setLoaded === "function");
|
|
8826
|
-
}
|
|
8827
|
-
async function eagerLoadOnModels(models, paths) {
|
|
8828
|
-
if (models.length === 0 || paths.length === 0) {
|
|
8829
|
-
return;
|
|
8830
|
-
}
|
|
8831
|
-
const grouped = new Map;
|
|
8832
|
-
for (const path of paths) {
|
|
8833
|
-
const [head, ...rest] = path.split(".");
|
|
8834
|
-
if (!head) {
|
|
8835
|
-
continue;
|
|
8836
|
-
}
|
|
8837
|
-
const nested = rest.join(".");
|
|
8838
|
-
const existing = grouped.get(head) ?? [];
|
|
8839
|
-
if (nested) {
|
|
8840
|
-
existing.push(nested);
|
|
8841
|
-
}
|
|
8842
|
-
grouped.set(head, existing);
|
|
9031
|
+
async attach(ids) {
|
|
9032
|
+
const list = Array.isArray(ids) ? ids : [ids];
|
|
9033
|
+
if (list.length === 0)
|
|
9034
|
+
return;
|
|
9035
|
+
await this.atomically((connection) => this.insertPivotRows(connection, list));
|
|
8843
9036
|
}
|
|
8844
|
-
|
|
8845
|
-
const
|
|
8846
|
-
if (
|
|
8847
|
-
|
|
8848
|
-
|
|
9037
|
+
async toggle(ids) {
|
|
9038
|
+
const list = Array.isArray(ids) ? ids : [ids];
|
|
9039
|
+
if (list.length === 0)
|
|
9040
|
+
return;
|
|
9041
|
+
await this.atomically(async (connection) => {
|
|
9042
|
+
if (!canBatchPivotToggle(list) || hasRepeatedId(list)) {
|
|
9043
|
+
for (const id of list)
|
|
9044
|
+
await this.toggleOne(connection, id);
|
|
8849
9045
|
return;
|
|
8850
9046
|
}
|
|
8851
|
-
const
|
|
8852
|
-
|
|
8853
|
-
|
|
8854
|
-
|
|
8855
|
-
const
|
|
8856
|
-
const
|
|
8857
|
-
|
|
8858
|
-
const
|
|
8859
|
-
|
|
8860
|
-
|
|
8861
|
-
|
|
8862
|
-
|
|
8863
|
-
}
|
|
8864
|
-
if (nested.length === 0) {
|
|
8865
|
-
return;
|
|
8866
|
-
}
|
|
8867
|
-
const children = models.flatMap((model) => {
|
|
8868
|
-
const loaded = model.loaded(head);
|
|
8869
|
-
return Array.isArray(loaded) ? loaded : loaded ? [loaded] : [];
|
|
9047
|
+
const parentId = this.parent.get(this.relation.parentKey);
|
|
9048
|
+
const relatedColumn = quoteIdentifier(String(this.relation.relatedPivotKey));
|
|
9049
|
+
const parentColumn = quoteIdentifier(String(this.relation.foreignPivotKey));
|
|
9050
|
+
const placeholders = list.map((_, index) => currentSqlDialect().placeholder(index + 2));
|
|
9051
|
+
const existing = await connection.unsafe(`SELECT ${relatedColumn} FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${parentColumn} = ${currentSqlDialect().placeholder(1)} AND ${relatedColumn} IN (${placeholders.join(", ")})`, [parentId, ...list]);
|
|
9052
|
+
const existingIds = new Set(existing.map((row) => pivotIdKey(row[String(this.relation.relatedPivotKey)])));
|
|
9053
|
+
const present = list.filter((id) => existingIds.has(pivotIdKey(id)));
|
|
9054
|
+
const missing = list.filter((id) => !existingIds.has(pivotIdKey(id)));
|
|
9055
|
+
if (present.length > 0)
|
|
9056
|
+
await this.deletePivotRows(connection, present);
|
|
9057
|
+
if (missing.length > 0)
|
|
9058
|
+
await this.insertPivotRows(connection, missing);
|
|
8870
9059
|
});
|
|
8871
|
-
await eagerLoadOnModels(children.filter(isLoadableModel), nested);
|
|
8872
|
-
}));
|
|
8873
|
-
}
|
|
8874
|
-
async function loadNested(model, path) {
|
|
8875
|
-
await eagerLoadOnModels([model], [path]);
|
|
8876
|
-
}
|
|
8877
|
-
function nameModel(model) {
|
|
8878
|
-
const { name, $morphClass } = model;
|
|
8879
|
-
if (name)
|
|
8880
|
-
namedModels.set(name, model);
|
|
8881
|
-
if ($morphClass)
|
|
8882
|
-
namedModels.set($morphClass, model);
|
|
8883
|
-
}
|
|
8884
|
-
function resolveModelRepository(model) {
|
|
8885
|
-
const existing = modelRepositories.get(model);
|
|
8886
|
-
if (existing)
|
|
8887
|
-
return existing;
|
|
8888
|
-
for (let current = model;current; current = Object.getPrototypeOf(current)) {
|
|
8889
|
-
const factory = modelRepositoryFactories.get(current);
|
|
8890
|
-
if (!factory)
|
|
8891
|
-
continue;
|
|
8892
|
-
const repository = factory();
|
|
8893
|
-
modelRepositories.set(model, repository);
|
|
8894
|
-
nameModel(model);
|
|
8895
|
-
return repository;
|
|
8896
9060
|
}
|
|
8897
|
-
|
|
8898
|
-
|
|
8899
|
-
|
|
8900
|
-
|
|
8901
|
-
|
|
8902
|
-
}
|
|
8903
|
-
modelRepositoryFactories.set(TableModel, () => new baseRepository_default(table));
|
|
8904
|
-
return TableModel;
|
|
8905
|
-
}
|
|
8906
|
-
function bootModels(models) {
|
|
8907
|
-
const names = new Map;
|
|
8908
|
-
for (const model of models) {
|
|
8909
|
-
const { name, $morphClass } = model;
|
|
8910
|
-
for (const alias of [name, $morphClass]) {
|
|
8911
|
-
if (!alias)
|
|
8912
|
-
continue;
|
|
8913
|
-
const existing = names.get(alias);
|
|
8914
|
-
if (existing && existing !== model)
|
|
8915
|
-
throw new Error(`Duplicate model name [${alias}].`);
|
|
8916
|
-
names.set(alias, model);
|
|
8917
|
-
}
|
|
8918
|
-
}
|
|
8919
|
-
for (const model of models)
|
|
8920
|
-
nameModel(model);
|
|
8921
|
-
for (const model of models) {
|
|
8922
|
-
resolveModelRepository(model);
|
|
8923
|
-
ensureBooted(model);
|
|
8924
|
-
}
|
|
8925
|
-
}
|
|
8926
|
-
function registerModelClass(name, model) {
|
|
8927
|
-
namedModels.set(name, model);
|
|
8928
|
-
}
|
|
8929
|
-
function resolveRelated(related) {
|
|
8930
|
-
if (typeof related === "string") {
|
|
8931
|
-
const found = namedModels.get(related);
|
|
8932
|
-
if (!found) {
|
|
8933
|
-
throw new Error(`Model [${related}] is not registered. Call registerModelClass() first.`);
|
|
8934
|
-
}
|
|
8935
|
-
return found;
|
|
8936
|
-
}
|
|
8937
|
-
if (typeof related === "function" && typeof related.repository !== "function") {
|
|
8938
|
-
return related();
|
|
8939
|
-
}
|
|
8940
|
-
return related;
|
|
8941
|
-
}
|
|
8942
|
-
function inferRelationMethodName(callee) {
|
|
8943
|
-
const stack = new Error().stack ?? "";
|
|
8944
|
-
let seenCallee = false;
|
|
8945
|
-
for (const line of stack.split(`
|
|
8946
|
-
`)) {
|
|
8947
|
-
const match = /at (?:async )?(?:[^.\s]+\.)?(\w+)/.exec(line);
|
|
8948
|
-
const name = match?.[1];
|
|
8949
|
-
if (!name || name === "Error" || name === "inferRelationMethodName") {
|
|
8950
|
-
continue;
|
|
8951
|
-
}
|
|
8952
|
-
if (!seenCallee) {
|
|
8953
|
-
if (name === callee) {
|
|
8954
|
-
seenCallee = true;
|
|
8955
|
-
}
|
|
8956
|
-
continue;
|
|
8957
|
-
}
|
|
8958
|
-
if (name !== callee) {
|
|
8959
|
-
return name;
|
|
8960
|
-
}
|
|
8961
|
-
}
|
|
8962
|
-
return;
|
|
8963
|
-
}
|
|
8964
|
-
function morphClassOf(model) {
|
|
8965
|
-
const statics = modelStatics(model.constructor === Function ? model : model.constructor);
|
|
8966
|
-
return statics.$morphClass ?? (model.constructor === Function ? model.name : model.constructor.name);
|
|
8967
|
-
}
|
|
8968
|
-
function modelStatics(model) {
|
|
8969
|
-
return model;
|
|
8970
|
-
}
|
|
8971
|
-
function ensureBooted(model) {
|
|
8972
|
-
if (modelBooted.has(model)) {
|
|
8973
|
-
return;
|
|
8974
|
-
}
|
|
8975
|
-
nameModel(model);
|
|
8976
|
-
modelBooted.add(model);
|
|
8977
|
-
const scopes = modelGlobalScopes.get(model);
|
|
8978
|
-
const observers = modelObservers.get(model);
|
|
8979
|
-
const boot = model.boot;
|
|
8980
|
-
if (typeof boot === "function") {
|
|
8981
|
-
try {
|
|
8982
|
-
boot.call(model);
|
|
8983
|
-
} catch (error) {
|
|
8984
|
-
modelBooted.delete(model);
|
|
8985
|
-
if (scopes)
|
|
8986
|
-
modelGlobalScopes.set(model, scopes);
|
|
8987
|
-
else
|
|
8988
|
-
modelGlobalScopes.delete(model);
|
|
8989
|
-
if (observers)
|
|
8990
|
-
modelObservers.set(model, observers);
|
|
8991
|
-
else
|
|
8992
|
-
modelObservers.delete(model);
|
|
8993
|
-
throw error;
|
|
8994
|
-
}
|
|
8995
|
-
}
|
|
8996
|
-
}
|
|
8997
|
-
function getGlobalScopes(model) {
|
|
8998
|
-
return modelGlobalScopes.get(model) ?? [];
|
|
8999
|
-
}
|
|
9000
|
-
var PASSWORD_HASH_PATTERN = /^\$(?:2[aby]?|argon2(?:i|d|id)?)\$/;
|
|
9001
|
-
function isAlreadyHashed(value) {
|
|
9002
|
-
return PASSWORD_HASH_PATTERN.test(value);
|
|
9003
|
-
}
|
|
9004
|
-
async function hashCastValue(value) {
|
|
9005
|
-
if (value === null || value === undefined)
|
|
9006
|
-
return value;
|
|
9007
|
-
const plain = String(value);
|
|
9008
|
-
if (isAlreadyHashed(plain)) {
|
|
9009
|
-
return plain;
|
|
9010
|
-
}
|
|
9011
|
-
return await hashPassword(plain);
|
|
9012
|
-
}
|
|
9013
|
-
function hydrateValue(value, cast) {
|
|
9014
|
-
if (value === null || value === undefined) {
|
|
9015
|
-
return value;
|
|
9016
|
-
}
|
|
9017
|
-
switch (cast) {
|
|
9018
|
-
case "date":
|
|
9019
|
-
case "datetime":
|
|
9020
|
-
return value instanceof Date ? value : new Date(String(value));
|
|
9021
|
-
case "json":
|
|
9022
|
-
return typeof value === "string" ? JSON.parse(value) : value;
|
|
9023
|
-
case "bool":
|
|
9024
|
-
case "boolean":
|
|
9025
|
-
return value === true || value === 1 || value === "1" || value === "true";
|
|
9026
|
-
case "integer":
|
|
9027
|
-
case "int":
|
|
9028
|
-
return value === "" ? null : Number(value);
|
|
9029
|
-
case "hashed":
|
|
9030
|
-
return value;
|
|
9031
|
-
default:
|
|
9032
|
-
return value;
|
|
9033
|
-
}
|
|
9034
|
-
}
|
|
9035
|
-
function dehydrateValue(value, cast) {
|
|
9036
|
-
if (cast === "hashed")
|
|
9037
|
-
return hashCastValue(value);
|
|
9038
|
-
if (value === null || value === undefined) {
|
|
9039
|
-
return value;
|
|
9040
|
-
}
|
|
9041
|
-
switch (cast) {
|
|
9042
|
-
case "date":
|
|
9043
|
-
case "datetime":
|
|
9044
|
-
return value instanceof Date ? value : new Date(String(value));
|
|
9045
|
-
case "json":
|
|
9046
|
-
return typeof value === "string" ? value : JSON.stringify(value);
|
|
9047
|
-
case "bool":
|
|
9048
|
-
case "boolean":
|
|
9049
|
-
return Boolean(value);
|
|
9050
|
-
case "integer":
|
|
9051
|
-
case "int":
|
|
9052
|
-
return value === "" ? null : Number(value);
|
|
9053
|
-
default:
|
|
9054
|
-
return value;
|
|
9055
|
-
}
|
|
9056
|
-
}
|
|
9057
|
-
function filterMassAssignable(fillable, guarded, input) {
|
|
9058
|
-
if (fillable === undefined && guarded === undefined && Object.keys(input).length > 0) {
|
|
9059
|
-
throw new Error("Mass assignment is not configured for this model. Declare static $fillable = [...] to allow specific columns, or static $guarded = [] to allow all of them.");
|
|
9060
|
-
}
|
|
9061
|
-
const resolvedGuarded = guarded ?? true;
|
|
9062
|
-
if (fillable && fillable.length > 0) {
|
|
9063
|
-
const allowed = new Set(fillable);
|
|
9064
|
-
return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
|
|
9065
|
-
}
|
|
9066
|
-
if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
|
|
9067
|
-
return {};
|
|
9068
|
-
}
|
|
9069
|
-
const blocked = new Set(resolvedGuarded);
|
|
9070
|
-
return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
|
|
9071
|
-
}
|
|
9072
|
-
function applyCasts(values, casts, direction) {
|
|
9073
|
-
const entries = Object.entries(casts);
|
|
9074
|
-
if (entries.length === 0) {
|
|
9075
|
-
return direction === "hydrate" ? values : Promise.resolve(values);
|
|
9076
|
-
}
|
|
9077
|
-
const result = { ...values };
|
|
9078
|
-
if (direction === "hydrate") {
|
|
9079
|
-
for (const [key, cast] of entries) {
|
|
9080
|
-
if (key in result && cast)
|
|
9081
|
-
result[key] = hydrateValue(result[key], cast);
|
|
9061
|
+
async detach(ids) {
|
|
9062
|
+
const parentId = this.parent.get(this.relation.parentKey);
|
|
9063
|
+
if (ids === undefined) {
|
|
9064
|
+
await this.connection().unsafe(`DELETE FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)}`, [parentId]);
|
|
9065
|
+
return;
|
|
9082
9066
|
}
|
|
9083
|
-
|
|
9067
|
+
const list = Array.isArray(ids) ? ids : [ids];
|
|
9068
|
+
if (list.length === 0)
|
|
9069
|
+
return;
|
|
9070
|
+
await this.deletePivotRows(this.connection(), list);
|
|
9084
9071
|
}
|
|
9085
|
-
|
|
9086
|
-
const
|
|
9087
|
-
|
|
9088
|
-
|
|
9089
|
-
|
|
9090
|
-
|
|
9091
|
-
|
|
9092
|
-
hashes.push(hashCastValue(current).then((hashed) => {
|
|
9093
|
-
result[key] = hashed;
|
|
9094
|
-
}));
|
|
9095
|
-
continue;
|
|
9096
|
-
}
|
|
9097
|
-
result[key] = dehydrateValue(result[key], cast);
|
|
9098
|
-
}
|
|
9099
|
-
await Promise.all(hashes);
|
|
9100
|
-
return result;
|
|
9101
|
-
})();
|
|
9102
|
-
}
|
|
9103
|
-
function castPluckedValue(modelClass, column, value) {
|
|
9104
|
-
const cast = modelStatics(modelClass).$casts?.[column];
|
|
9105
|
-
return cast ? hydrateValue(value, cast) : value;
|
|
9106
|
-
}
|
|
9107
|
-
function applyTimestampsOnCreate(columns, values, enabled) {
|
|
9108
|
-
if (!enabled) {
|
|
9109
|
-
return values;
|
|
9072
|
+
async toggleOne(connection, id) {
|
|
9073
|
+
const parentId = this.parent.get(this.relation.parentKey);
|
|
9074
|
+
const existing = await connection.unsafe(`SELECT 1 FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)} AND ${quoteIdentifier(String(this.relation.relatedPivotKey))} = ${currentSqlDialect().placeholder(2)} LIMIT 1`, [parentId, id]);
|
|
9075
|
+
if (existing.length > 0)
|
|
9076
|
+
await this.deletePivotRows(connection, [id]);
|
|
9077
|
+
else
|
|
9078
|
+
await this.insertPivotRows(connection, [id]);
|
|
9110
9079
|
}
|
|
9111
|
-
|
|
9112
|
-
|
|
9113
|
-
|
|
9114
|
-
|
|
9080
|
+
async insertPivotRows(connection, list) {
|
|
9081
|
+
const parentId = this.parent.get(this.relation.parentKey);
|
|
9082
|
+
const extraKeys = Object.keys(this.pivotValues);
|
|
9083
|
+
const extraColumns = extraKeys.length > 0 ? `, ${extraKeys.map((key) => quoteIdentifier(key)).join(", ")}` : "";
|
|
9084
|
+
const extraValues = extraKeys.map((key) => this.pivotValues[key]);
|
|
9085
|
+
const width = 2 + extraKeys.length;
|
|
9086
|
+
const tuples = list.map((_, row) => {
|
|
9087
|
+
const slots = Array.from({ length: width }, (__, column) => currentSqlDialect().placeholder(row * width + column + 1));
|
|
9088
|
+
return `(${slots.join(", ")})`;
|
|
9089
|
+
});
|
|
9090
|
+
const params = [];
|
|
9091
|
+
for (const id of list)
|
|
9092
|
+
params.push(parentId, id, ...extraValues);
|
|
9093
|
+
await connection.unsafe(`INSERT INTO ${quoteIdentifier(this.relation.pivotTable)} (${quoteIdentifier(String(this.relation.foreignPivotKey))}, ${quoteIdentifier(String(this.relation.relatedPivotKey))}${extraColumns}) VALUES ${tuples.join(", ")}`, params);
|
|
9115
9094
|
}
|
|
9116
|
-
|
|
9117
|
-
|
|
9095
|
+
async deletePivotRows(connection, list) {
|
|
9096
|
+
const parentId = this.parent.get(this.relation.parentKey);
|
|
9097
|
+
const placeholders = list.map((_, index) => currentSqlDialect().placeholder(index + 2));
|
|
9098
|
+
await connection.unsafe(`DELETE FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)} AND ${quoteIdentifier(String(this.relation.relatedPivotKey))} IN (${placeholders.join(", ")})`, [parentId, ...list]);
|
|
9118
9099
|
}
|
|
9119
|
-
|
|
9120
|
-
|
|
9121
|
-
|
|
9122
|
-
|
|
9123
|
-
|
|
9100
|
+
async sync(ids) {
|
|
9101
|
+
await this.detach();
|
|
9102
|
+
if (ids.length > 0) {
|
|
9103
|
+
await this.attach(ids);
|
|
9104
|
+
}
|
|
9124
9105
|
}
|
|
9125
|
-
|
|
9126
|
-
|
|
9127
|
-
|
|
9106
|
+
async create(attributes = {}) {
|
|
9107
|
+
const related = await this.related.create(attributes);
|
|
9108
|
+
await this.attach(related.id);
|
|
9109
|
+
return related;
|
|
9128
9110
|
}
|
|
9129
|
-
return result;
|
|
9130
9111
|
}
|
|
9131
9112
|
|
|
9132
|
-
class
|
|
9133
|
-
|
|
9134
|
-
|
|
9135
|
-
|
|
9136
|
-
|
|
9137
|
-
|
|
9113
|
+
class MorphManyRelationQuery {
|
|
9114
|
+
parent;
|
|
9115
|
+
related;
|
|
9116
|
+
relation;
|
|
9117
|
+
kind = "morphMany";
|
|
9118
|
+
extraWhere = [];
|
|
9119
|
+
extraOptions = {};
|
|
9120
|
+
constructor(parent, related, relation) {
|
|
9121
|
+
this.parent = parent;
|
|
9122
|
+
this.related = related;
|
|
9123
|
+
this.relation = relation;
|
|
9138
9124
|
}
|
|
9139
|
-
|
|
9140
|
-
|
|
9125
|
+
where(where) {
|
|
9126
|
+
this.extraWhere.push({ ...where });
|
|
9127
|
+
return this;
|
|
9141
9128
|
}
|
|
9142
|
-
|
|
9143
|
-
|
|
9129
|
+
applyEagerLoad(query, alias) {
|
|
9130
|
+
query.withMorphMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
|
|
9144
9131
|
}
|
|
9145
|
-
|
|
9146
|
-
|
|
9132
|
+
hydrateEager(row, alias) {
|
|
9133
|
+
const value = row[alias] ?? [];
|
|
9134
|
+
const rows = Array.isArray(value) ? value : [];
|
|
9135
|
+
return rows.map((item) => this.related.newFromRecord(item));
|
|
9147
9136
|
}
|
|
9148
|
-
|
|
9149
|
-
|
|
9150
|
-
|
|
9151
|
-
|
|
9152
|
-
|
|
9153
|
-
|
|
9154
|
-
|
|
9155
|
-
|
|
9156
|
-
this.query = query;
|
|
9137
|
+
toExistsClause(parentTable) {
|
|
9138
|
+
const childTable = this.related.repository().getTable().name;
|
|
9139
|
+
const extra = relatedConditions(this.related, [
|
|
9140
|
+
asWhere({ [this.relation.morphTypeKey]: this.relation.morphType }),
|
|
9141
|
+
...this.extraWhere
|
|
9142
|
+
], this.extraOptions, [], [parentTable]);
|
|
9143
|
+
const sql = `SELECT 1 FROM ${quoteIdentifier(childTable)}${extra.joins} WHERE ${qualifyColumn(childTable, this.relation.morphIdKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
|
|
9144
|
+
return { sql, params: extra.params };
|
|
9157
9145
|
}
|
|
9158
|
-
|
|
9159
|
-
|
|
9160
|
-
|
|
9161
|
-
|
|
9162
|
-
|
|
9163
|
-
const name = path.split(".")[0] ?? path;
|
|
9164
|
-
const method = dummy[name];
|
|
9165
|
-
if (typeof method !== "function") {
|
|
9166
|
-
throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
|
|
9167
|
-
}
|
|
9168
|
-
const relationQuery = method.call(dummy);
|
|
9169
|
-
this.eager.push({ name, path, relationQuery });
|
|
9170
|
-
relationQuery.applyEagerLoad(this.query, name);
|
|
9171
|
-
}
|
|
9172
|
-
return this;
|
|
9146
|
+
scopedQuery() {
|
|
9147
|
+
return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({
|
|
9148
|
+
[this.relation.morphTypeKey]: this.relation.morphType,
|
|
9149
|
+
[this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
|
|
9150
|
+
}), this.extraWhere);
|
|
9173
9151
|
}
|
|
9174
|
-
|
|
9175
|
-
this.
|
|
9176
|
-
return this;
|
|
9152
|
+
async get() {
|
|
9153
|
+
const rows = await this.scopedQuery().get();
|
|
9154
|
+
return rows.map((row) => this.related.newFromRecord(row));
|
|
9177
9155
|
}
|
|
9178
|
-
|
|
9179
|
-
this.
|
|
9180
|
-
return
|
|
9156
|
+
async first() {
|
|
9157
|
+
const rows = await this.get();
|
|
9158
|
+
return rows[0] ?? null;
|
|
9181
9159
|
}
|
|
9182
|
-
|
|
9183
|
-
this.
|
|
9184
|
-
return this;
|
|
9160
|
+
async count() {
|
|
9161
|
+
return this.scopedQuery().count();
|
|
9185
9162
|
}
|
|
9186
|
-
|
|
9187
|
-
return
|
|
9188
|
-
const rows = await this.query.project(columns, limit);
|
|
9189
|
-
return rows.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"));
|
|
9190
|
-
}, async (options) => {
|
|
9191
|
-
const page = await this.query.projectKeyset(columns, options);
|
|
9192
|
-
return {
|
|
9193
|
-
...page,
|
|
9194
|
-
data: page.data.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"))
|
|
9195
|
-
};
|
|
9196
|
-
});
|
|
9163
|
+
async pluck(column, keyBy) {
|
|
9164
|
+
return pluckFromQuery(this.scopedQuery(), column, keyBy);
|
|
9197
9165
|
}
|
|
9198
|
-
|
|
9199
|
-
this.
|
|
9200
|
-
return this;
|
|
9166
|
+
async value(column) {
|
|
9167
|
+
return this.scopedQuery().value(column);
|
|
9201
9168
|
}
|
|
9202
|
-
|
|
9203
|
-
this.
|
|
9204
|
-
return this;
|
|
9169
|
+
then(onfulfilled, onrejected) {
|
|
9170
|
+
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
9205
9171
|
}
|
|
9206
|
-
|
|
9207
|
-
this.
|
|
9208
|
-
|
|
9172
|
+
async create(attributes = {}) {
|
|
9173
|
+
return this.related.create(attributes, {
|
|
9174
|
+
[this.relation.morphTypeKey]: this.relation.morphType,
|
|
9175
|
+
[this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
|
|
9176
|
+
});
|
|
9209
9177
|
}
|
|
9210
|
-
|
|
9211
|
-
|
|
9212
|
-
|
|
9178
|
+
}
|
|
9179
|
+
|
|
9180
|
+
class MorphOneRelationQuery {
|
|
9181
|
+
relation;
|
|
9182
|
+
kind = "morphOne";
|
|
9183
|
+
inner;
|
|
9184
|
+
constructor(parent, related, relation) {
|
|
9185
|
+
this.relation = relation;
|
|
9186
|
+
this.inner = new MorphManyRelationQuery(parent, related, {
|
|
9187
|
+
type: "morphMany",
|
|
9188
|
+
name: relation.name,
|
|
9189
|
+
localKey: relation.localKey,
|
|
9190
|
+
morphTypeKey: relation.morphTypeKey,
|
|
9191
|
+
morphIdKey: relation.morphIdKey,
|
|
9192
|
+
morphType: relation.morphType
|
|
9193
|
+
});
|
|
9213
9194
|
}
|
|
9214
|
-
|
|
9215
|
-
this.
|
|
9195
|
+
where(where) {
|
|
9196
|
+
this.inner.where(where);
|
|
9216
9197
|
return this;
|
|
9217
9198
|
}
|
|
9218
|
-
|
|
9219
|
-
this.
|
|
9220
|
-
return this;
|
|
9199
|
+
applyEagerLoad(query, alias) {
|
|
9200
|
+
this.inner.applyEagerLoad(query, alias);
|
|
9221
9201
|
}
|
|
9222
|
-
|
|
9223
|
-
this.
|
|
9224
|
-
return
|
|
9202
|
+
hydrateEager(row, alias) {
|
|
9203
|
+
const hydrated = this.inner.hydrateEager(row, alias);
|
|
9204
|
+
return hydrated[0];
|
|
9225
9205
|
}
|
|
9226
|
-
|
|
9227
|
-
this.
|
|
9228
|
-
return this;
|
|
9206
|
+
toExistsClause(parentTable) {
|
|
9207
|
+
return this.inner.toExistsClause(parentTable);
|
|
9229
9208
|
}
|
|
9230
|
-
|
|
9231
|
-
this.
|
|
9232
|
-
return this;
|
|
9209
|
+
async get() {
|
|
9210
|
+
return this.inner.first();
|
|
9233
9211
|
}
|
|
9234
|
-
|
|
9235
|
-
this.
|
|
9236
|
-
return this;
|
|
9212
|
+
async first() {
|
|
9213
|
+
return this.get();
|
|
9237
9214
|
}
|
|
9238
|
-
|
|
9239
|
-
this.
|
|
9240
|
-
|
|
9215
|
+
async count() {
|
|
9216
|
+
return this.inner.count();
|
|
9217
|
+
}
|
|
9218
|
+
async pluck(column, keyBy) {
|
|
9219
|
+
return keyBy === undefined ? this.inner.pluck(column) : this.inner.pluck(column, keyBy);
|
|
9241
9220
|
}
|
|
9242
|
-
|
|
9243
|
-
this.
|
|
9244
|
-
return this;
|
|
9221
|
+
async value(column) {
|
|
9222
|
+
return this.inner.value(column);
|
|
9245
9223
|
}
|
|
9246
|
-
|
|
9247
|
-
this.
|
|
9248
|
-
return this;
|
|
9224
|
+
then(onfulfilled, onrejected) {
|
|
9225
|
+
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
9249
9226
|
}
|
|
9250
|
-
async
|
|
9251
|
-
|
|
9252
|
-
return { data: await this.hydrateRows(data), meta };
|
|
9227
|
+
async create(attributes = {}) {
|
|
9228
|
+
return this.inner.create(attributes);
|
|
9253
9229
|
}
|
|
9254
|
-
|
|
9255
|
-
|
|
9256
|
-
|
|
9230
|
+
}
|
|
9231
|
+
|
|
9232
|
+
class MorphToRelationQuery {
|
|
9233
|
+
parent;
|
|
9234
|
+
relatedByType;
|
|
9235
|
+
relation;
|
|
9236
|
+
kind = "morphTo";
|
|
9237
|
+
extraWhere = [];
|
|
9238
|
+
constructor(parent, relatedByType, relation) {
|
|
9239
|
+
this.parent = parent;
|
|
9240
|
+
this.relatedByType = relatedByType;
|
|
9241
|
+
this.relation = relation;
|
|
9257
9242
|
}
|
|
9258
|
-
|
|
9259
|
-
this.
|
|
9243
|
+
where(where) {
|
|
9244
|
+
this.extraWhere.push({ ...where });
|
|
9260
9245
|
return this;
|
|
9261
9246
|
}
|
|
9262
|
-
|
|
9263
|
-
|
|
9247
|
+
applyEagerLoad(query, alias) {
|
|
9248
|
+
const repositories = new Map(Object.entries(this.relatedByType).map(([type, model]) => [
|
|
9249
|
+
type,
|
|
9250
|
+
model.repository()
|
|
9251
|
+
]));
|
|
9252
|
+
query.withMorphTo(alias, this.relation, repositories, {}, new Map(Object.entries(this.relatedByType).map(([type, model]) => [
|
|
9253
|
+
type,
|
|
9254
|
+
relatedOptions(model, this.extraWhere)
|
|
9255
|
+
])));
|
|
9264
9256
|
}
|
|
9265
|
-
|
|
9266
|
-
return
|
|
9257
|
+
hydrateEager(row, alias) {
|
|
9258
|
+
return row[alias];
|
|
9267
9259
|
}
|
|
9268
|
-
|
|
9269
|
-
|
|
9260
|
+
toExistsClause(parentTable) {
|
|
9261
|
+
const params = [];
|
|
9262
|
+
const type = this.parent.get(this.relation.morphTypeKey);
|
|
9263
|
+
if (type !== undefined && type !== null && !this.relatedByType[String(type)]) {
|
|
9264
|
+
return { sql: "SELECT 1 WHERE 1 = 0", params };
|
|
9265
|
+
}
|
|
9266
|
+
const branches = Object.entries(this.relatedByType).map(([type, related]) => {
|
|
9267
|
+
params.push(type);
|
|
9268
|
+
const discriminator = currentSqlDialect().placeholder(params.length);
|
|
9269
|
+
const table = related.repository().getTable();
|
|
9270
|
+
const extra = relatedConditions(related, this.extraWhere, {}, params, [parentTable]);
|
|
9271
|
+
return `(${qualifyColumn(parentTable, this.relation.morphTypeKey)} = ${discriminator} AND EXISTS (SELECT 1 FROM ${quoteIdentifier(table.name)}${extra.joins} WHERE ${qualifyColumn(table.name, table.primaryKey)} = ${qualifyColumn(parentTable, this.relation.morphIdKey)}${extra.sql}))`;
|
|
9272
|
+
});
|
|
9273
|
+
return {
|
|
9274
|
+
sql: `SELECT 1 WHERE ${branches.length > 0 ? branches.join(" OR ") : "1 = 0"}`,
|
|
9275
|
+
params
|
|
9276
|
+
};
|
|
9270
9277
|
}
|
|
9271
|
-
|
|
9272
|
-
|
|
9278
|
+
async get() {
|
|
9279
|
+
const query = this.relatedQuery();
|
|
9280
|
+
if (!query) {
|
|
9281
|
+
return null;
|
|
9282
|
+
}
|
|
9283
|
+
const row = await query.first();
|
|
9284
|
+
return row ? this.relatedForCurrentType()?.newFromRecord(row) ?? null : null;
|
|
9273
9285
|
}
|
|
9274
|
-
|
|
9275
|
-
this.
|
|
9276
|
-
return this;
|
|
9286
|
+
async pluck(column, keyBy) {
|
|
9287
|
+
return pluckFromQuery(this.relatedQuery(), column, keyBy);
|
|
9277
9288
|
}
|
|
9278
|
-
|
|
9279
|
-
this.
|
|
9280
|
-
return this;
|
|
9289
|
+
async value(column) {
|
|
9290
|
+
return this.relatedQuery()?.value(column) ?? null;
|
|
9281
9291
|
}
|
|
9282
|
-
|
|
9283
|
-
this.
|
|
9284
|
-
return this;
|
|
9292
|
+
relatedForCurrentType() {
|
|
9293
|
+
const type = String(this.parent.get(this.relation.morphTypeKey) ?? "");
|
|
9294
|
+
return this.relatedByType[type];
|
|
9285
9295
|
}
|
|
9286
|
-
|
|
9287
|
-
this.
|
|
9288
|
-
|
|
9296
|
+
relatedQuery() {
|
|
9297
|
+
const id = this.parent.get(this.relation.morphIdKey);
|
|
9298
|
+
const related = this.relatedForCurrentType();
|
|
9299
|
+
if (!related || id === null || id === undefined) {
|
|
9300
|
+
return null;
|
|
9301
|
+
}
|
|
9302
|
+
const table = related.repository().getTable();
|
|
9303
|
+
return relatedRead(related, this.parent.getRepository().getConnection(), asWhere({ [table.primaryKey]: id }), this.extraWhere);
|
|
9289
9304
|
}
|
|
9290
|
-
|
|
9291
|
-
this.
|
|
9292
|
-
return this;
|
|
9305
|
+
then(onfulfilled, onrejected) {
|
|
9306
|
+
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
9293
9307
|
}
|
|
9294
|
-
|
|
9295
|
-
|
|
9296
|
-
|
|
9308
|
+
}
|
|
9309
|
+
|
|
9310
|
+
class HasManyThroughRelationQuery {
|
|
9311
|
+
parent;
|
|
9312
|
+
related;
|
|
9313
|
+
relation;
|
|
9314
|
+
kind = "hasManyThrough";
|
|
9315
|
+
extraWhere = [];
|
|
9316
|
+
extraOptions = {};
|
|
9317
|
+
constructor(parent, related, relation) {
|
|
9318
|
+
this.parent = parent;
|
|
9319
|
+
this.related = related;
|
|
9320
|
+
this.relation = relation;
|
|
9297
9321
|
}
|
|
9298
|
-
|
|
9299
|
-
this.
|
|
9322
|
+
where(where) {
|
|
9323
|
+
this.extraWhere.push({ ...where });
|
|
9300
9324
|
return this;
|
|
9301
9325
|
}
|
|
9302
|
-
|
|
9303
|
-
this.
|
|
9326
|
+
orderBy(orderBy) {
|
|
9327
|
+
this.extraOptions = { ...this.extraOptions, orderBy };
|
|
9304
9328
|
return this;
|
|
9305
9329
|
}
|
|
9306
|
-
|
|
9307
|
-
this.
|
|
9330
|
+
limit(limit) {
|
|
9331
|
+
this.extraOptions = { ...this.extraOptions, limit };
|
|
9308
9332
|
return this;
|
|
9309
9333
|
}
|
|
9310
|
-
|
|
9311
|
-
|
|
9334
|
+
applyEagerLoad(query, alias) {
|
|
9335
|
+
query.withHasManyThrough(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
|
|
9312
9336
|
}
|
|
9313
|
-
|
|
9314
|
-
const
|
|
9315
|
-
|
|
9337
|
+
hydrateEager(row, alias) {
|
|
9338
|
+
const value = row[alias] ?? [];
|
|
9339
|
+
const rows = Array.isArray(value) ? value : [];
|
|
9340
|
+
return rows.map((item) => this.related.newFromRecord(item));
|
|
9316
9341
|
}
|
|
9317
|
-
|
|
9318
|
-
const
|
|
9319
|
-
const
|
|
9320
|
-
|
|
9321
|
-
|
|
9322
|
-
|
|
9323
|
-
|
|
9324
|
-
|
|
9325
|
-
|
|
9326
|
-
}
|
|
9327
|
-
await Promise.all(models.map((model) => runObservers(model, "retrieved")));
|
|
9328
|
-
const nested = this.eager.filter((item) => item.path.includes(".")).map((item) => item.path);
|
|
9329
|
-
await eagerLoadOnModels(models.filter(isLoadableModel), nested);
|
|
9330
|
-
return models;
|
|
9342
|
+
toExistsClause(parentTable) {
|
|
9343
|
+
const farTable = this.related.repository().getTable().name;
|
|
9344
|
+
const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.throughTable]);
|
|
9345
|
+
const sql = `SELECT 1 FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(this.relation.throughTable)} ON ${qualifyColumn(this.relation.throughTable, this.relation.secondLocalKey)} = ${qualifyColumn(farTable, this.relation.secondKey)}${extra.joins} WHERE ${qualifyColumn(this.relation.throughTable, this.relation.firstKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
|
|
9346
|
+
return { sql, params: extra.params };
|
|
9347
|
+
}
|
|
9348
|
+
async get() {
|
|
9349
|
+
const rows = await this.farRows();
|
|
9350
|
+
return rows.map((row) => this.related.newFromRecord(row));
|
|
9331
9351
|
}
|
|
9332
9352
|
async first() {
|
|
9333
|
-
this.
|
|
9334
|
-
|
|
9335
|
-
return models[0] ?? null;
|
|
9353
|
+
const rows = await this.limit(1).get();
|
|
9354
|
+
return rows[0] ?? null;
|
|
9336
9355
|
}
|
|
9337
9356
|
async count() {
|
|
9338
|
-
|
|
9357
|
+
const rows = await this.get();
|
|
9358
|
+
return rows.length;
|
|
9339
9359
|
}
|
|
9340
9360
|
async pluck(column, keyBy) {
|
|
9341
|
-
|
|
9342
|
-
|
|
9343
|
-
return values.map((value) => castPluckedValue(this.modelClass, column, value));
|
|
9344
|
-
}
|
|
9345
|
-
const keyed = await this.query.pluck(column, keyBy);
|
|
9346
|
-
const result = new Map;
|
|
9347
|
-
for (const [key, value] of keyed) {
|
|
9348
|
-
result.set(castPluckedValue(this.modelClass, keyBy, key), castPluckedValue(this.modelClass, column, value));
|
|
9349
|
-
}
|
|
9350
|
-
return result;
|
|
9361
|
+
const rows = await this.farRows();
|
|
9362
|
+
return keyBy === undefined ? projectPluck(rows, column) : projectPluck(rows, column, keyBy);
|
|
9351
9363
|
}
|
|
9352
9364
|
async value(column) {
|
|
9353
|
-
const
|
|
9354
|
-
return
|
|
9355
|
-
}
|
|
9356
|
-
async find(id) {
|
|
9357
|
-
const primaryKey = resolveModelRepository(this.modelClass).getTable().primaryKey;
|
|
9358
|
-
return this.whereDynamic({ [primaryKey]: id }).first();
|
|
9365
|
+
const values = await this.limit(1).pluck(column);
|
|
9366
|
+
return values[0] ?? null;
|
|
9359
9367
|
}
|
|
9360
|
-
async
|
|
9361
|
-
|
|
9362
|
-
|
|
9363
|
-
|
|
9364
|
-
}
|
|
9365
|
-
throw errorFactory?.(id) ?? new NotFoundError(`${this.modelClass.name} ${String(id)} not found.`);
|
|
9368
|
+
async farRows() {
|
|
9369
|
+
return this.related.repository().withConnection(this.parent.getRepository().getConnection()).findHasManyThrough(this.parent.get(this.relation.localKey), this.relation, {
|
|
9370
|
+
...relatedOptions(this.related, this.extraWhere, this.extraOptions)
|
|
9371
|
+
});
|
|
9366
9372
|
}
|
|
9367
9373
|
then(onfulfilled, onrejected) {
|
|
9368
|
-
return this.get()
|
|
9374
|
+
return thenGet(() => this.get(), onfulfilled, onrejected);
|
|
9369
9375
|
}
|
|
9370
|
-
|
|
9371
|
-
|
|
9372
|
-
|
|
9373
|
-
|
|
9374
|
-
|
|
9375
|
-
|
|
9376
|
-
|
|
9377
|
-
|
|
9376
|
+
}
|
|
9377
|
+
|
|
9378
|
+
// ../../src/core/database/model.ts
|
|
9379
|
+
function accessorName(key) {
|
|
9380
|
+
const pascal = key.replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
|
|
9381
|
+
return `get${pascal.charAt(0).toUpperCase()}${pascal.slice(1)}Attribute`;
|
|
9382
|
+
}
|
|
9383
|
+
function defineModel(table) {
|
|
9384
|
+
|
|
9385
|
+
class TableModel extends Model {
|
|
9386
|
+
}
|
|
9387
|
+
registerModelRepositoryFactory(TableModel, () => new baseRepository_default(table));
|
|
9388
|
+
return TableModel;
|
|
9389
|
+
}
|
|
9390
|
+
function bootModels(models) {
|
|
9391
|
+
const names = new Map;
|
|
9392
|
+
for (const model of models) {
|
|
9393
|
+
const { name, $morphClass } = model;
|
|
9394
|
+
for (const alias of [name, $morphClass]) {
|
|
9395
|
+
if (!alias)
|
|
9396
|
+
continue;
|
|
9397
|
+
const existing = names.get(alias);
|
|
9398
|
+
if (existing && existing !== model)
|
|
9399
|
+
throw new Error(`Duplicate model name [${alias}].`);
|
|
9400
|
+
names.set(alias, model);
|
|
9378
9401
|
}
|
|
9379
|
-
|
|
9380
|
-
|
|
9381
|
-
|
|
9382
|
-
|
|
9402
|
+
}
|
|
9403
|
+
for (const model of models)
|
|
9404
|
+
nameModel(model);
|
|
9405
|
+
for (const model of models) {
|
|
9406
|
+
resolveModelRepository(model);
|
|
9407
|
+
ensureBooted(model);
|
|
9408
|
+
}
|
|
9409
|
+
}
|
|
9410
|
+
function resolveRelated(related) {
|
|
9411
|
+
if (typeof related === "string") {
|
|
9412
|
+
const found = findNamedModel(related);
|
|
9413
|
+
if (!found) {
|
|
9414
|
+
throw new Error(`Model [${related}] is not registered. Call registerModelClass() first.`);
|
|
9383
9415
|
}
|
|
9384
|
-
|
|
9385
|
-
return this;
|
|
9416
|
+
return found;
|
|
9386
9417
|
}
|
|
9387
|
-
|
|
9388
|
-
|
|
9389
|
-
|
|
9390
|
-
|
|
9391
|
-
|
|
9392
|
-
|
|
9393
|
-
|
|
9394
|
-
|
|
9418
|
+
if (typeof related === "function" && typeof related.repository !== "function") {
|
|
9419
|
+
return related();
|
|
9420
|
+
}
|
|
9421
|
+
return related;
|
|
9422
|
+
}
|
|
9423
|
+
function inferRelationMethodName(callee) {
|
|
9424
|
+
const stack = new Error().stack ?? "";
|
|
9425
|
+
let seenCallee = false;
|
|
9426
|
+
for (const line of stack.split(`
|
|
9427
|
+
`)) {
|
|
9428
|
+
const match = /at (?:async )?(?:[^.\s]+\.)?(\w+)/.exec(line);
|
|
9429
|
+
const name = match?.[1];
|
|
9430
|
+
if (!name || name === "Error" || name === "inferRelationMethodName") {
|
|
9431
|
+
continue;
|
|
9432
|
+
}
|
|
9433
|
+
if (!seenCallee) {
|
|
9434
|
+
if (name === callee) {
|
|
9435
|
+
seenCallee = true;
|
|
9436
|
+
}
|
|
9437
|
+
continue;
|
|
9438
|
+
}
|
|
9439
|
+
if (name !== callee) {
|
|
9440
|
+
return name;
|
|
9395
9441
|
}
|
|
9396
|
-
const relationQuery = method.call(dummy);
|
|
9397
|
-
constrain?.(relationQuery);
|
|
9398
|
-
const exists = relationQuery.toExistsClause(repository.getTable().name);
|
|
9399
|
-
return not ? this.whereNotExists(exists.sql, exists.params) : this.whereExists(exists.sql, exists.params);
|
|
9400
9442
|
}
|
|
9443
|
+
return;
|
|
9444
|
+
}
|
|
9445
|
+
function morphClassOf(model) {
|
|
9446
|
+
const statics = modelStatics2(model.constructor === Function ? model : model.constructor);
|
|
9447
|
+
return statics.$morphClass ?? (model.constructor === Function ? model.name : model.constructor.name);
|
|
9448
|
+
}
|
|
9449
|
+
function modelStatics2(model) {
|
|
9450
|
+
return model;
|
|
9401
9451
|
}
|
|
9402
9452
|
|
|
9403
9453
|
class Model {
|
|
@@ -9421,14 +9471,14 @@ class Model {
|
|
|
9421
9471
|
this.attributes = attributes;
|
|
9422
9472
|
this.repository = repository;
|
|
9423
9473
|
this._exists = exists;
|
|
9424
|
-
this.attributes =
|
|
9474
|
+
this.attributes = modelStatics2(this.constructor).hydrateAttributes(attributes);
|
|
9425
9475
|
this.originalAttributes = snapshotAttributes(this.attributes);
|
|
9426
9476
|
}
|
|
9427
9477
|
acceptPersistedAttributes(record) {
|
|
9428
9478
|
const original = this.originalAttributes;
|
|
9429
9479
|
const beforeWrite = snapshotAttributes(this.attributes);
|
|
9430
9480
|
const existed = this._exists;
|
|
9431
|
-
this.attributes =
|
|
9481
|
+
this.attributes = modelStatics2(this.constructor).hydrateAttributes(record);
|
|
9432
9482
|
this.originalAttributes = snapshotAttributes(this.attributes);
|
|
9433
9483
|
const written = this.originalAttributes;
|
|
9434
9484
|
this._exists = true;
|
|
@@ -9457,7 +9507,7 @@ class Model {
|
|
|
9457
9507
|
return { ...this.attributes };
|
|
9458
9508
|
}
|
|
9459
9509
|
toArray() {
|
|
9460
|
-
const ModelClass =
|
|
9510
|
+
const ModelClass = modelStatics2(this.constructor);
|
|
9461
9511
|
const hidden = new Set([...ModelClass.$hidden ?? [], ...this.hiddenOverrides]);
|
|
9462
9512
|
const visible = this.visibleOverrides.length > 0 ? this.visibleOverrides : ModelClass.$visible;
|
|
9463
9513
|
const data = { ...this.attributes };
|
|
@@ -9506,30 +9556,24 @@ class Model {
|
|
|
9506
9556
|
return resolveModelRepository(this).getTable().primaryKey;
|
|
9507
9557
|
}
|
|
9508
9558
|
static hydrateAttributes(attributes) {
|
|
9509
|
-
const casts =
|
|
9559
|
+
const casts = modelStatics2(this).$casts ?? {};
|
|
9510
9560
|
return applyCasts(attributes, casts, "hydrate");
|
|
9511
9561
|
}
|
|
9512
9562
|
static dehydrateAttributes(attributes) {
|
|
9513
|
-
const casts =
|
|
9563
|
+
const casts = modelStatics2(this).$casts ?? {};
|
|
9514
9564
|
return applyCasts(attributes, casts, "dehydrate");
|
|
9515
9565
|
}
|
|
9516
9566
|
static fromRecord(record, repository, exists = true) {
|
|
9517
|
-
const statics =
|
|
9567
|
+
const statics = modelStatics2(this);
|
|
9518
9568
|
const hydrated = statics.hydrateAttributes(record);
|
|
9519
9569
|
return new statics(hydrated, repository, exists);
|
|
9520
9570
|
}
|
|
9521
9571
|
static boot() {}
|
|
9522
9572
|
static observe(observer) {
|
|
9523
|
-
|
|
9524
|
-
modelObservers.set(this, [...existing, observer]);
|
|
9573
|
+
observeModel(this, observer);
|
|
9525
9574
|
}
|
|
9526
9575
|
static addGlobalScope(_name, scope) {
|
|
9527
|
-
|
|
9528
|
-
const existing = modelGlobalScopes.get(this) ?? [];
|
|
9529
|
-
modelGlobalScopes.set(this, [
|
|
9530
|
-
...existing,
|
|
9531
|
-
scope
|
|
9532
|
-
]);
|
|
9576
|
+
addModelGlobalScope(this, scope);
|
|
9533
9577
|
}
|
|
9534
9578
|
static repository() {
|
|
9535
9579
|
const repository = resolveModelRepository(this);
|
|
@@ -9551,13 +9595,13 @@ class Model {
|
|
|
9551
9595
|
}
|
|
9552
9596
|
static newFromRecord(record, exists = true) {
|
|
9553
9597
|
const repository = resolveModelRepository(this);
|
|
9554
|
-
return
|
|
9598
|
+
return modelStatics2(this).fromRecord(record, repository, exists);
|
|
9555
9599
|
}
|
|
9556
9600
|
static newFromTrustedRecord(record, exists = true) {
|
|
9557
|
-
return
|
|
9601
|
+
return modelStatics2(this).newFromRecord(record, exists);
|
|
9558
9602
|
}
|
|
9559
9603
|
static async create(attributes, forced = {}) {
|
|
9560
|
-
const statics =
|
|
9604
|
+
const statics = modelStatics2(this);
|
|
9561
9605
|
ensureBooted(this);
|
|
9562
9606
|
const repository = resolveModelRepository(this);
|
|
9563
9607
|
const table = repository.getTable();
|
|
@@ -9591,7 +9635,7 @@ class Model {
|
|
|
9591
9635
|
return Model.query.call(this).onlyTrashed();
|
|
9592
9636
|
}
|
|
9593
9637
|
static async chunk(count, callback) {
|
|
9594
|
-
const statics =
|
|
9638
|
+
const statics = modelStatics2(this);
|
|
9595
9639
|
ensureBooted(this);
|
|
9596
9640
|
await Model.query.call(this).query.chunk(count, async (rows) => {
|
|
9597
9641
|
return await callback(rows.map((row) => statics.newFromRecord(row, true)));
|
|
@@ -9601,7 +9645,7 @@ class Model {
|
|
|
9601
9645
|
return Model.query.call(this).keysetPaginate(options);
|
|
9602
9646
|
}
|
|
9603
9647
|
static async cursorPaginate(options) {
|
|
9604
|
-
const statics =
|
|
9648
|
+
const statics = modelStatics2(this);
|
|
9605
9649
|
ensureBooted(this);
|
|
9606
9650
|
const page = await Model.query.call(this).query.cursorPaginate({
|
|
9607
9651
|
perPage: options.perPage,
|
|
@@ -9670,7 +9714,7 @@ class Model {
|
|
|
9670
9714
|
if (existing) {
|
|
9671
9715
|
return existing;
|
|
9672
9716
|
}
|
|
9673
|
-
return
|
|
9717
|
+
return modelStatics2(this).newFromRecord({ ...where, ...values }, false);
|
|
9674
9718
|
}
|
|
9675
9719
|
static async firstOrCreate(where, values = {}) {
|
|
9676
9720
|
const findExisting = () => Model.firstWhere.call(this, where);
|
|
@@ -9699,9 +9743,8 @@ class Model {
|
|
|
9699
9743
|
return Model.create.call(this, { ...where, ...values });
|
|
9700
9744
|
}
|
|
9701
9745
|
async save() {
|
|
9702
|
-
const ModelClass =
|
|
9746
|
+
const ModelClass = modelStatics2(this.constructor);
|
|
9703
9747
|
const timestamps = ModelClass.$timestamps ?? true;
|
|
9704
|
-
const casts = ModelClass.$casts ?? {};
|
|
9705
9748
|
const table = this.repository.getTable();
|
|
9706
9749
|
const updating = this.$exists;
|
|
9707
9750
|
if (await runObservers(this, "saving") === false) {
|
|
@@ -9716,7 +9759,7 @@ class Model {
|
|
|
9716
9759
|
await runObservers(this, "saved");
|
|
9717
9760
|
return this;
|
|
9718
9761
|
}
|
|
9719
|
-
const changes = applyTimestampsOnUpdate(table.columns, await
|
|
9762
|
+
const changes = applyTimestampsOnUpdate(table.columns, await ModelClass.dehydrateAttributes(dirty), timestamps);
|
|
9720
9763
|
const record = await this.repository.updateByIdOrThrow(this.id, changes);
|
|
9721
9764
|
this.acceptPersistedAttributes(record);
|
|
9722
9765
|
await runObservers(this, "updated");
|
|
@@ -9733,7 +9776,7 @@ class Model {
|
|
|
9733
9776
|
return this;
|
|
9734
9777
|
}
|
|
9735
9778
|
async update(changes) {
|
|
9736
|
-
const ModelClass =
|
|
9779
|
+
const ModelClass = modelStatics2(this.constructor);
|
|
9737
9780
|
const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, changes);
|
|
9738
9781
|
Object.assign(this.attributes, assignable);
|
|
9739
9782
|
return await this.save();
|
|
@@ -9910,7 +9953,7 @@ class Model {
|
|
|
9910
9953
|
}
|
|
9911
9954
|
}
|
|
9912
9955
|
function registerModelRepository(model, repository) {
|
|
9913
|
-
|
|
9956
|
+
bindModelRepository(model, repository);
|
|
9914
9957
|
nameModel(model);
|
|
9915
9958
|
ensureBooted(model);
|
|
9916
9959
|
return model;
|
|
@@ -10985,30 +11028,7 @@ class SqlOutbox {
|
|
|
10985
11028
|
});
|
|
10986
11029
|
}
|
|
10987
11030
|
}
|
|
10988
|
-
// ../../src/core/mail/
|
|
10989
|
-
function resolveSmtpConfig() {
|
|
10990
|
-
const host = process.env.MAIL_HOST?.trim();
|
|
10991
|
-
if (!host) {
|
|
10992
|
-
throw new Error('MAIL_DRIVER="smtp" requires MAIL_HOST to be set.');
|
|
10993
|
-
}
|
|
10994
|
-
const from = process.env.MAIL_FROM?.trim();
|
|
10995
|
-
if (!from) {
|
|
10996
|
-
throw new Error('MAIL_DRIVER="smtp" requires MAIL_FROM to be set.');
|
|
10997
|
-
}
|
|
10998
|
-
const port = Number(process.env.MAIL_PORT ?? "587");
|
|
10999
|
-
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
11000
|
-
throw new Error('Environment variable "MAIL_PORT" must be a positive integer.');
|
|
11001
|
-
}
|
|
11002
|
-
return {
|
|
11003
|
-
host,
|
|
11004
|
-
port,
|
|
11005
|
-
from,
|
|
11006
|
-
secure: (process.env.MAIL_SECURE ?? "false") === "true",
|
|
11007
|
-
...process.env.MAIL_TIMEOUT_MS !== undefined ? { timeoutMs: smtpTimeout(Number(process.env.MAIL_TIMEOUT_MS)) } : {},
|
|
11008
|
-
...process.env.MAIL_USERNAME?.trim() ? { username: process.env.MAIL_USERNAME.trim() } : {},
|
|
11009
|
-
...process.env.MAIL_PASSWORD?.trim() ? { password: process.env.MAIL_PASSWORD.trim() } : {}
|
|
11010
|
-
};
|
|
11011
|
-
}
|
|
11031
|
+
// ../../src/core/mail/smtpMessage.ts
|
|
11012
11032
|
var EMAIL_SHAPE = /^[^\s@\r\n]+@[^\s@\r\n]+\.[^\s@\r\n]+$/u;
|
|
11013
11033
|
function assertSafeSmtpField(value, field) {
|
|
11014
11034
|
if (/[\r\n]/u.test(value)) {
|
|
@@ -11034,12 +11054,111 @@ function assertSafeSmtpAddress(value, field) {
|
|
|
11034
11054
|
smtpEnvelopeAddress(value, field);
|
|
11035
11055
|
return assertSafeSmtpField(value, field).trim();
|
|
11036
11056
|
}
|
|
11037
|
-
function redactMailBody(body) {
|
|
11038
|
-
return body.replace(/https?:\/\/[^\s]+/giu, "[redacted-url]").replace(/[?&](token|signature|expires|code)=[^&\s]+/giu, "[redacted-query]");
|
|
11039
|
-
}
|
|
11040
11057
|
function encodeBase64(value) {
|
|
11041
11058
|
return Buffer.from(value, "utf8").toString("base64");
|
|
11042
11059
|
}
|
|
11060
|
+
function encodeSmtpHeader(value) {
|
|
11061
|
+
if (/^[\x20-\x7e]{0,60}$/u.test(value))
|
|
11062
|
+
return value;
|
|
11063
|
+
const words = [];
|
|
11064
|
+
let part = "";
|
|
11065
|
+
for (const character of value) {
|
|
11066
|
+
if (Buffer.byteLength(part + character, "utf8") > 45) {
|
|
11067
|
+
words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
|
|
11068
|
+
part = "";
|
|
11069
|
+
}
|
|
11070
|
+
part += character;
|
|
11071
|
+
}
|
|
11072
|
+
if (part)
|
|
11073
|
+
words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
|
|
11074
|
+
return words.join(`\r
|
|
11075
|
+
`);
|
|
11076
|
+
}
|
|
11077
|
+
function smtpAddressHeader(value) {
|
|
11078
|
+
if (!value.includes("<"))
|
|
11079
|
+
return value;
|
|
11080
|
+
const name = value.slice(0, value.lastIndexOf("<")).trim();
|
|
11081
|
+
const address = smtpEnvelopeAddress(value, "address");
|
|
11082
|
+
if (!name)
|
|
11083
|
+
return address;
|
|
11084
|
+
const encoded = encodeSmtpHeader(name);
|
|
11085
|
+
const display = encoded.startsWith("=?UTF-8?B?") ? encoded : `"${encoded.replace(/[\\"]/gu, "\\$&")}"`;
|
|
11086
|
+
return `${display} <${address}>`;
|
|
11087
|
+
}
|
|
11088
|
+
function smtpMimePart(type, value) {
|
|
11089
|
+
const normalized = value.replace(/\r\n|\r|\n/gu, `\r
|
|
11090
|
+
`);
|
|
11091
|
+
const base64 = /[^\t\r\n\x20-\x7e]/u.test(normalized) || normalized.split(`\r
|
|
11092
|
+
`).some((line) => line.length > 998);
|
|
11093
|
+
return [
|
|
11094
|
+
`Content-Type: ${type}; charset=utf-8`,
|
|
11095
|
+
`Content-Transfer-Encoding: ${base64 ? "base64" : "7bit"}`,
|
|
11096
|
+
"",
|
|
11097
|
+
base64 ? (encodeBase64(normalized).match(/.{1,76}/gu) ?? []).join(`\r
|
|
11098
|
+
`) : normalized
|
|
11099
|
+
];
|
|
11100
|
+
}
|
|
11101
|
+
function buildSmtpPayload(from, message) {
|
|
11102
|
+
const headers = [
|
|
11103
|
+
`From: ${smtpAddressHeader(assertSafeSmtpAddress(from, "from"))}`,
|
|
11104
|
+
`To: ${smtpAddressHeader(assertSafeSmtpAddress(message.to, "to"))}`,
|
|
11105
|
+
`Subject: ${encodeSmtpHeader(assertSafeSmtpField(message.subject, "subject"))}`,
|
|
11106
|
+
"MIME-Version: 1.0"
|
|
11107
|
+
];
|
|
11108
|
+
let lines;
|
|
11109
|
+
if (message.html) {
|
|
11110
|
+
let boundary;
|
|
11111
|
+
do {
|
|
11112
|
+
boundary = `strata-${crypto.randomUUID()}`;
|
|
11113
|
+
} while (message.body.includes(boundary) || message.html.includes(boundary));
|
|
11114
|
+
lines = [
|
|
11115
|
+
...headers,
|
|
11116
|
+
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
|
11117
|
+
"",
|
|
11118
|
+
`--${boundary}`,
|
|
11119
|
+
...smtpMimePart("text/plain", message.body),
|
|
11120
|
+
`--${boundary}`,
|
|
11121
|
+
...smtpMimePart("text/html", message.html),
|
|
11122
|
+
`--${boundary}--`,
|
|
11123
|
+
""
|
|
11124
|
+
];
|
|
11125
|
+
} else
|
|
11126
|
+
lines = [...headers, ...smtpMimePart("text/plain", message.body)];
|
|
11127
|
+
const content = lines.join(`\r
|
|
11128
|
+
`).replace(/(^|\r\n)\./gu, "$1..");
|
|
11129
|
+
return `${content}${content.endsWith(`\r
|
|
11130
|
+
`) ? "" : `\r
|
|
11131
|
+
`}.\r
|
|
11132
|
+
`;
|
|
11133
|
+
}
|
|
11134
|
+
|
|
11135
|
+
// ../../src/core/mail/mailer.ts
|
|
11136
|
+
function resolveSmtpConfig() {
|
|
11137
|
+
const host = process.env.MAIL_HOST?.trim();
|
|
11138
|
+
if (!host) {
|
|
11139
|
+
throw new Error('MAIL_DRIVER="smtp" requires MAIL_HOST to be set.');
|
|
11140
|
+
}
|
|
11141
|
+
const from = process.env.MAIL_FROM?.trim();
|
|
11142
|
+
if (!from) {
|
|
11143
|
+
throw new Error('MAIL_DRIVER="smtp" requires MAIL_FROM to be set.');
|
|
11144
|
+
}
|
|
11145
|
+
const port = Number(process.env.MAIL_PORT ?? "587");
|
|
11146
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
11147
|
+
throw new Error('Environment variable "MAIL_PORT" must be a positive integer.');
|
|
11148
|
+
}
|
|
11149
|
+
return {
|
|
11150
|
+
host,
|
|
11151
|
+
port,
|
|
11152
|
+
from,
|
|
11153
|
+
secure: (process.env.MAIL_SECURE ?? "false") === "true",
|
|
11154
|
+
...process.env.MAIL_TIMEOUT_MS !== undefined ? { timeoutMs: smtpTimeout(Number(process.env.MAIL_TIMEOUT_MS)) } : {},
|
|
11155
|
+
...process.env.MAIL_USERNAME?.trim() ? { username: process.env.MAIL_USERNAME.trim() } : {},
|
|
11156
|
+
...process.env.MAIL_PASSWORD?.trim() ? { password: process.env.MAIL_PASSWORD.trim() } : {}
|
|
11157
|
+
};
|
|
11158
|
+
}
|
|
11159
|
+
function redactMailBody(body) {
|
|
11160
|
+
return body.replace(/https?:\/\/[^\s]+/giu, "[redacted-url]").replace(/[?&](token|signature|expires|code)=[^&\s]+/giu, "[redacted-query]");
|
|
11161
|
+
}
|
|
11043
11162
|
function smtpTimeout(value = 1e4) {
|
|
11044
11163
|
if (!Number.isSafeInteger(value) || value < 1 || value > 2147483647) {
|
|
11045
11164
|
throw new RangeError("SMTP timeoutMs must be a positive integer within the timer range.");
|
|
@@ -11268,80 +11387,6 @@ async function defaultSmtpTransport(config, message) {
|
|
|
11268
11387
|
socket?.end();
|
|
11269
11388
|
}
|
|
11270
11389
|
}
|
|
11271
|
-
function encodeSmtpHeader(value) {
|
|
11272
|
-
if (/^[\x20-\x7e]{0,60}$/u.test(value))
|
|
11273
|
-
return value;
|
|
11274
|
-
const words = [];
|
|
11275
|
-
let part = "";
|
|
11276
|
-
for (const character of value) {
|
|
11277
|
-
if (Buffer.byteLength(part + character, "utf8") > 45) {
|
|
11278
|
-
words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
|
|
11279
|
-
part = "";
|
|
11280
|
-
}
|
|
11281
|
-
part += character;
|
|
11282
|
-
}
|
|
11283
|
-
if (part)
|
|
11284
|
-
words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
|
|
11285
|
-
return words.join(`\r
|
|
11286
|
-
`);
|
|
11287
|
-
}
|
|
11288
|
-
function smtpAddressHeader(value) {
|
|
11289
|
-
if (!value.includes("<"))
|
|
11290
|
-
return value;
|
|
11291
|
-
const name = value.slice(0, value.lastIndexOf("<")).trim();
|
|
11292
|
-
const address = smtpEnvelopeAddress(value, "address");
|
|
11293
|
-
if (!name)
|
|
11294
|
-
return address;
|
|
11295
|
-
const encoded = encodeSmtpHeader(name);
|
|
11296
|
-
const display = encoded.startsWith("=?UTF-8?B?") ? encoded : `"${encoded.replace(/[\\"]/gu, "\\$&")}"`;
|
|
11297
|
-
return `${display} <${address}>`;
|
|
11298
|
-
}
|
|
11299
|
-
function smtpMimePart(type, value) {
|
|
11300
|
-
const normalized = value.replace(/\r\n|\r|\n/gu, `\r
|
|
11301
|
-
`);
|
|
11302
|
-
const base64 = /[^\t\r\n\x20-\x7e]/u.test(normalized) || normalized.split(`\r
|
|
11303
|
-
`).some((line) => line.length > 998);
|
|
11304
|
-
return [
|
|
11305
|
-
`Content-Type: ${type}; charset=utf-8`,
|
|
11306
|
-
`Content-Transfer-Encoding: ${base64 ? "base64" : "7bit"}`,
|
|
11307
|
-
"",
|
|
11308
|
-
base64 ? (encodeBase64(normalized).match(/.{1,76}/gu) ?? []).join(`\r
|
|
11309
|
-
`) : normalized
|
|
11310
|
-
];
|
|
11311
|
-
}
|
|
11312
|
-
function buildSmtpPayload(from, message) {
|
|
11313
|
-
const headers = [
|
|
11314
|
-
`From: ${smtpAddressHeader(assertSafeSmtpAddress(from, "from"))}`,
|
|
11315
|
-
`To: ${smtpAddressHeader(assertSafeSmtpAddress(message.to, "to"))}`,
|
|
11316
|
-
`Subject: ${encodeSmtpHeader(assertSafeSmtpField(message.subject, "subject"))}`,
|
|
11317
|
-
"MIME-Version: 1.0"
|
|
11318
|
-
];
|
|
11319
|
-
let lines;
|
|
11320
|
-
if (message.html) {
|
|
11321
|
-
let boundary;
|
|
11322
|
-
do {
|
|
11323
|
-
boundary = `strata-${crypto.randomUUID()}`;
|
|
11324
|
-
} while (message.body.includes(boundary) || message.html.includes(boundary));
|
|
11325
|
-
lines = [
|
|
11326
|
-
...headers,
|
|
11327
|
-
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
|
11328
|
-
"",
|
|
11329
|
-
`--${boundary}`,
|
|
11330
|
-
...smtpMimePart("text/plain", message.body),
|
|
11331
|
-
`--${boundary}`,
|
|
11332
|
-
...smtpMimePart("text/html", message.html),
|
|
11333
|
-
`--${boundary}--`,
|
|
11334
|
-
""
|
|
11335
|
-
];
|
|
11336
|
-
} else
|
|
11337
|
-
lines = [...headers, ...smtpMimePart("text/plain", message.body)];
|
|
11338
|
-
const content = lines.join(`\r
|
|
11339
|
-
`).replace(/(^|\r\n)\./gu, "$1..");
|
|
11340
|
-
return `${content}${content.endsWith(`\r
|
|
11341
|
-
`) ? "" : `\r
|
|
11342
|
-
`}.\r
|
|
11343
|
-
`;
|
|
11344
|
-
}
|
|
11345
11390
|
|
|
11346
11391
|
class LogMailDriver {
|
|
11347
11392
|
async send(message) {
|
|
@@ -12867,16 +12912,16 @@ function isMethodRouteMap(value) {
|
|
|
12867
12912
|
}
|
|
12868
12913
|
function composeMiddleware(...middleware) {
|
|
12869
12914
|
return (handler) => {
|
|
12870
|
-
return async (request) => {
|
|
12915
|
+
return async (request, ...arguments_) => {
|
|
12871
12916
|
let index = 0;
|
|
12872
12917
|
const dispatch = async () => {
|
|
12873
12918
|
if (index >= middleware.length) {
|
|
12874
|
-
return await handler(request);
|
|
12919
|
+
return await handler(request, ...arguments_);
|
|
12875
12920
|
}
|
|
12876
12921
|
const current = middleware[index];
|
|
12877
12922
|
index += 1;
|
|
12878
12923
|
if (!current) {
|
|
12879
|
-
return await handler(request);
|
|
12924
|
+
return await handler(request, ...arguments_);
|
|
12880
12925
|
}
|
|
12881
12926
|
return await current(request, dispatch);
|
|
12882
12927
|
};
|
|
@@ -14765,6 +14810,143 @@ async function runQueueJob(envelope, failedJobs, options = {}) {
|
|
|
14765
14810
|
// ../../src/core/queue/redisQueue.ts
|
|
14766
14811
|
var {RedisClient: RedisClient4 } = globalThis.Bun;
|
|
14767
14812
|
|
|
14813
|
+
// ../../src/core/queue/redisListScripts.ts
|
|
14814
|
+
var SCRIPT_HEADER = `
|
|
14815
|
+
local function checkType(key, expected)
|
|
14816
|
+
local actual = redis.call('TYPE', key).ok
|
|
14817
|
+
if actual ~= 'none' and actual ~= expected then
|
|
14818
|
+
return redis.error_reply('Unexpected queue key type: ' .. key)
|
|
14819
|
+
end
|
|
14820
|
+
end
|
|
14821
|
+
local function nowMs()
|
|
14822
|
+
local time = redis.call('TIME')
|
|
14823
|
+
return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
|
|
14824
|
+
end
|
|
14825
|
+
`;
|
|
14826
|
+
var RESERVE_JOB = `${SCRIPT_HEADER}
|
|
14827
|
+
local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
|
|
14828
|
+
if err then return err end
|
|
14829
|
+
local payload = redis.call('LINDEX', KEYS[1], -1)
|
|
14830
|
+
if not payload then return nil end
|
|
14831
|
+
local record = cjson.encode({strataReservation=1, id=ARGV[1], owner=ARGV[2], payload=payload})
|
|
14832
|
+
local lease = cjson.encode({owner=ARGV[2], expiresAt=nowMs()+tonumber(ARGV[3])})
|
|
14833
|
+
redis.call('LPUSH', KEYS[2], record)
|
|
14834
|
+
redis.call('HSET', KEYS[3], ARGV[1], lease)
|
|
14835
|
+
redis.call('RPOP', KEYS[1])
|
|
14836
|
+
return record
|
|
14837
|
+
`;
|
|
14838
|
+
var RENEW_OR_ACK = `${SCRIPT_HEADER}
|
|
14839
|
+
local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'hash') or checkType(KEYS[3], 'list')
|
|
14840
|
+
if err then return err end
|
|
14841
|
+
local raw = redis.call('HGET', KEYS[2], ARGV[1])
|
|
14842
|
+
if not raw then return 0 end
|
|
14843
|
+
local ok, lease = pcall(cjson.decode, raw)
|
|
14844
|
+
local now = nowMs()
|
|
14845
|
+
if not ok or type(lease) ~= 'table' or lease.owner ~= ARGV[2] or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now then
|
|
14846
|
+
return 0
|
|
14847
|
+
end
|
|
14848
|
+
if ARGV[4] == 'renew' then
|
|
14849
|
+
redis.call('HSET', KEYS[2], ARGV[1], cjson.encode({owner=ARGV[2], expiresAt=now+tonumber(ARGV[5])}))
|
|
14850
|
+
return 1
|
|
14851
|
+
end
|
|
14852
|
+
if ARGV[4] == 'quarantine' then redis.call('LPUSH', KEYS[3], ARGV[6]) end
|
|
14853
|
+
local removed = redis.call('LREM', KEYS[1], 1, ARGV[3])
|
|
14854
|
+
redis.call('HDEL', KEYS[2], ARGV[1])
|
|
14855
|
+
return removed
|
|
14856
|
+
`;
|
|
14857
|
+
var RECLAIM_JOBS = `${SCRIPT_HEADER}
|
|
14858
|
+
local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
|
|
14859
|
+
if err then return err end
|
|
14860
|
+
local now = nowMs()
|
|
14861
|
+
local reclaimed = 0
|
|
14862
|
+
for _, record in ipairs(redis.call('LRANGE', KEYS[2], 0, -1)) do
|
|
14863
|
+
local payload, field = record, record
|
|
14864
|
+
local modern = false
|
|
14865
|
+
local ok, reservation = pcall(cjson.decode, record)
|
|
14866
|
+
if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
|
|
14867
|
+
payload, field, modern = reservation.payload, reservation.id, true
|
|
14868
|
+
end
|
|
14869
|
+
local raw = redis.call('HGET', KEYS[3], field)
|
|
14870
|
+
local expired = true
|
|
14871
|
+
if raw then
|
|
14872
|
+
if modern then
|
|
14873
|
+
local leaseOk, lease = pcall(cjson.decode, raw)
|
|
14874
|
+
expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
|
|
14875
|
+
else
|
|
14876
|
+
local reservedAt = tonumber(raw)
|
|
14877
|
+
expired = not reservedAt or now - reservedAt >= tonumber(ARGV[1])
|
|
14878
|
+
end
|
|
14879
|
+
end
|
|
14880
|
+
if expired then
|
|
14881
|
+
redis.call('LPUSH', KEYS[1], payload)
|
|
14882
|
+
redis.call('LREM', KEYS[2], 1, record)
|
|
14883
|
+
redis.call('HDEL', KEYS[3], field)
|
|
14884
|
+
reclaimed = reclaimed + 1
|
|
14885
|
+
end
|
|
14886
|
+
end
|
|
14887
|
+
return reclaimed
|
|
14888
|
+
`;
|
|
14889
|
+
var POLL_LIST_PRIORITIES = `${SCRIPT_HEADER}
|
|
14890
|
+
local owner = ARGV[1]
|
|
14891
|
+
local visibility = ARGV[2]
|
|
14892
|
+
local reservationId = ARGV[3]
|
|
14893
|
+
local reclaim = ARGV[4] == '1'
|
|
14894
|
+
local function reclaimQueue(listKey, processingKey, leaseKey)
|
|
14895
|
+
local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
|
|
14896
|
+
if err then return err end
|
|
14897
|
+
local now = nowMs()
|
|
14898
|
+
for _, record in ipairs(redis.call('LRANGE', processingKey, 0, -1)) do
|
|
14899
|
+
local payload, field = record, record
|
|
14900
|
+
local modern = false
|
|
14901
|
+
local ok, reservation = pcall(cjson.decode, record)
|
|
14902
|
+
if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
|
|
14903
|
+
payload, field, modern = reservation.payload, reservation.id, true
|
|
14904
|
+
end
|
|
14905
|
+
local raw = redis.call('HGET', leaseKey, field)
|
|
14906
|
+
local expired = true
|
|
14907
|
+
if raw then
|
|
14908
|
+
if modern then
|
|
14909
|
+
local leaseOk, lease = pcall(cjson.decode, raw)
|
|
14910
|
+
expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
|
|
14911
|
+
else
|
|
14912
|
+
local reservedAt = tonumber(raw)
|
|
14913
|
+
expired = not reservedAt or now - reservedAt >= tonumber(visibility)
|
|
14914
|
+
end
|
|
14915
|
+
end
|
|
14916
|
+
if expired then
|
|
14917
|
+
redis.call('LPUSH', listKey, payload)
|
|
14918
|
+
redis.call('LREM', processingKey, 1, record)
|
|
14919
|
+
redis.call('HDEL', leaseKey, field)
|
|
14920
|
+
end
|
|
14921
|
+
end
|
|
14922
|
+
end
|
|
14923
|
+
local function reserveQueue(listKey, processingKey, leaseKey)
|
|
14924
|
+
local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
|
|
14925
|
+
if err then return err end
|
|
14926
|
+
local payload = redis.call('LINDEX', listKey, -1)
|
|
14927
|
+
if not payload then return nil end
|
|
14928
|
+
local record = cjson.encode({strataReservation=1, id=reservationId, owner=owner, payload=payload})
|
|
14929
|
+
local lease = cjson.encode({owner=owner, expiresAt=nowMs()+tonumber(visibility)})
|
|
14930
|
+
redis.call('LPUSH', processingKey, record)
|
|
14931
|
+
redis.call('HSET', leaseKey, reservationId, lease)
|
|
14932
|
+
redis.call('RPOP', listKey)
|
|
14933
|
+
return record
|
|
14934
|
+
end
|
|
14935
|
+
local count = #KEYS / 3
|
|
14936
|
+
if reclaim then
|
|
14937
|
+
for i = 1, count do
|
|
14938
|
+
local err = reclaimQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
|
|
14939
|
+
if err then return err end
|
|
14940
|
+
end
|
|
14941
|
+
end
|
|
14942
|
+
for i = 1, count do
|
|
14943
|
+
local record = reserveQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
|
|
14944
|
+
if type(record) == 'string' then return {'1', tostring(i), record} end
|
|
14945
|
+
if record then return record end
|
|
14946
|
+
end
|
|
14947
|
+
return {'0'}
|
|
14948
|
+
`;
|
|
14949
|
+
|
|
14768
14950
|
// ../../src/core/queue/redisQueueKeys.ts
|
|
14769
14951
|
function queueListKey() {
|
|
14770
14952
|
return namespacedRedisKey("queue:default");
|
|
@@ -14795,22 +14977,8 @@ function queueKeyForPriority(priority = "default") {
|
|
|
14795
14977
|
|
|
14796
14978
|
// ../../src/core/queue/redisStreams.ts
|
|
14797
14979
|
var {RedisClient: RedisClient3 } = globalThis.Bun;
|
|
14798
|
-
|
|
14799
|
-
|
|
14800
|
-
return `${queueKey}:stream`;
|
|
14801
|
-
}
|
|
14802
|
-
function streamDeadLetterKey(queueKey) {
|
|
14803
|
-
return `${streamQueueKey(queueKey)}:invalid`;
|
|
14804
|
-
}
|
|
14805
|
-
function streamRetryKey(queueKey) {
|
|
14806
|
-
return `${streamQueueKey(queueKey)}:retries`;
|
|
14807
|
-
}
|
|
14808
|
-
function streamControlKey(key, jobId) {
|
|
14809
|
-
const prefix = `${streamQueueKey(key)}/`;
|
|
14810
|
-
if (!jobId.startsWith(prefix) || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(jobId.slice(prefix.length)))
|
|
14811
|
-
throw new Error("Invalid cancellable Streams job ID");
|
|
14812
|
-
return `${streamQueueKey(key)}:control:${jobId.slice(prefix.length)}`;
|
|
14813
|
-
}
|
|
14980
|
+
|
|
14981
|
+
// ../../src/core/queue/redisStreamsScripts.ts
|
|
14814
14982
|
var ENQUEUE_CONTROLLED = `
|
|
14815
14983
|
local kind = redis.call('TYPE', KEYS[1]).ok
|
|
14816
14984
|
if kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream admission key type') end
|
|
@@ -14829,6 +14997,127 @@ if payload and redis.call('ZSCORE', KEYS[2], payload) then redis.call('ZADD', KE
|
|
|
14829
14997
|
redis.call('HSET', KEYS[1], 'state', 'cancelled')
|
|
14830
14998
|
return 1
|
|
14831
14999
|
`;
|
|
15000
|
+
var SCHEDULE_RETRY = `
|
|
15001
|
+
local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
|
|
15002
|
+
if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
|
|
15003
|
+
local kind = redis.call('TYPE', KEYS[2]).ok
|
|
15004
|
+
if kind ~= 'none' and kind ~= 'zset' then return redis.error_reply('Invalid stream retry key type') end
|
|
15005
|
+
if ARGV[8] == '1' then
|
|
15006
|
+
local state = redis.call('HGET', KEYS[3], 'state')
|
|
15007
|
+
if state == 'cancelled' then return redis.error_reply('Streams job cancelled') end
|
|
15008
|
+
if state ~= 'active' then return redis.error_reply('Missing or invalid Streams control state') end
|
|
15009
|
+
end
|
|
15010
|
+
local now = redis.call('TIME')
|
|
15011
|
+
local due = tonumber(now[1])*1000 + math.floor(tonumber(now[2])/1000) + tonumber(ARGV[5])
|
|
15012
|
+
if ARGV[7] ~= '' then due = math.min(due, tonumber(ARGV[7])) end
|
|
15013
|
+
redis.call('ZADD', KEYS[2], due, ARGV[6])
|
|
15014
|
+
if ARGV[8] == '1' then redis.call('HSET', KEYS[3], 'retryPayload', ARGV[6]) end
|
|
15015
|
+
redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
|
|
15016
|
+
redis.call('XDEL', KEYS[1], ARGV[2])
|
|
15017
|
+
if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
|
|
15018
|
+
return 1
|
|
15019
|
+
`;
|
|
15020
|
+
var POLL_STREAM_PRIORITIES = `
|
|
15021
|
+
local group = ARGV[1]
|
|
15022
|
+
local owner = ARGV[2]
|
|
15023
|
+
local visibility = ARGV[3]
|
|
15024
|
+
local function payloadOf(fields)
|
|
15025
|
+
for index = 1, #fields, 2 do
|
|
15026
|
+
if fields[index] == 'payload' and type(fields[index + 1]) == 'string' then return fields[index + 1] end
|
|
15027
|
+
end
|
|
15028
|
+
return ''
|
|
15029
|
+
end
|
|
15030
|
+
local cursors = {}
|
|
15031
|
+
for i = 1, #KEYS / 2 do cursors[i] = ARGV[3 + i] end
|
|
15032
|
+
for i = 1, #KEYS / 2 do
|
|
15033
|
+
local stream = KEYS[(i - 1) * 2 + 1]
|
|
15034
|
+
local retries = KEYS[(i - 1) * 2 + 2]
|
|
15035
|
+
local cursor = ARGV[3 + i]
|
|
15036
|
+
local streamKind = redis.call('TYPE', stream).ok
|
|
15037
|
+
local retryKind = redis.call('TYPE', retries).ok
|
|
15038
|
+
if streamKind ~= 'none' and streamKind ~= 'stream' then return redis.error_reply('Invalid stream retry promotion key type') end
|
|
15039
|
+
if retryKind ~= 'none' and retryKind ~= 'zset' then return redis.error_reply('Invalid stream retry promotion key type') end
|
|
15040
|
+
if streamKind == 'stream' then
|
|
15041
|
+
local now = redis.call('TIME')
|
|
15042
|
+
local due = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
|
|
15043
|
+
local ready = redis.call('ZRANGE', retries, '-inf', due, 'BYSCORE', 'LIMIT', 0, 100)
|
|
15044
|
+
for _, payload in ipairs(ready) do
|
|
15045
|
+
redis.call('XADD', stream, '*', 'payload', payload)
|
|
15046
|
+
redis.call('ZREM', retries, payload)
|
|
15047
|
+
end
|
|
15048
|
+
local window = redis.call('XPENDING', stream, group, cursor, '+', 10)
|
|
15049
|
+
local claimed = redis.call('XAUTOCLAIM', stream, group, owner, visibility, cursor, 'COUNT', 1)
|
|
15050
|
+
for _, entry in ipairs(window) do
|
|
15051
|
+
if entry[2] ~= owner and #redis.call('XPENDING', stream, group, '-', '+', 1, entry[2]) == 0 then
|
|
15052
|
+
redis.call('XGROUP', 'DELCONSUMER', stream, group, entry[2])
|
|
15053
|
+
end
|
|
15054
|
+
end
|
|
15055
|
+
if #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
|
|
15056
|
+
redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
|
|
15057
|
+
end
|
|
15058
|
+
cursors[i] = claimed[1]
|
|
15059
|
+
if #claimed[2] > 0 then
|
|
15060
|
+
return {'1', tostring(i), claimed[2][1][1], payloadOf(claimed[2][1][2]), unpack(cursors)}
|
|
15061
|
+
end
|
|
15062
|
+
local fresh = redis.call('XREADGROUP', 'GROUP', group, owner, 'COUNT', 1, 'STREAMS', stream, '>')
|
|
15063
|
+
if not fresh and #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
|
|
15064
|
+
redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
|
|
15065
|
+
end
|
|
15066
|
+
if fresh and #fresh > 0 and #fresh[1][2] > 0 then
|
|
15067
|
+
return {'1', tostring(i), fresh[1][2][1][1], payloadOf(fresh[1][2][1][2]), unpack(cursors)}
|
|
15068
|
+
end
|
|
15069
|
+
end
|
|
15070
|
+
end
|
|
15071
|
+
return {'0', unpack(cursors)}
|
|
15072
|
+
`;
|
|
15073
|
+
var ASSERT_DRAINED = `
|
|
15074
|
+
if redis.call('LLEN', KEYS[1]) > 0 or redis.call('LLEN', KEYS[2]) > 0 or redis.call('HLEN', KEYS[3]) > 0 then
|
|
15075
|
+
return redis.error_reply('Legacy queue state requires maintenance conversion before Streams activation')
|
|
15076
|
+
end
|
|
15077
|
+
return 1
|
|
15078
|
+
`;
|
|
15079
|
+
var UPDATE_STREAM = `
|
|
15080
|
+
local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
|
|
15081
|
+
if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
|
|
15082
|
+
if ARGV[7] == '1' then
|
|
15083
|
+
local kind = redis.call('TYPE', KEYS[3]).ok
|
|
15084
|
+
if kind ~= 'none' and kind ~= 'hash' then return redis.error_reply('Invalid stream control key type') end
|
|
15085
|
+
end
|
|
15086
|
+
if ARGV[5] == 'renew' then
|
|
15087
|
+
local claimed = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[3], 0, ARGV[2], 'JUSTID')
|
|
15088
|
+
return #claimed
|
|
15089
|
+
end
|
|
15090
|
+
if ARGV[5] == 'quarantine' then
|
|
15091
|
+
local kind = redis.call('TYPE', KEYS[2]).ok
|
|
15092
|
+
if kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream quarantine key type') end
|
|
15093
|
+
redis.call('XADD', KEYS[2], '*', 'sourceId', ARGV[2], 'payload', ARGV[6])
|
|
15094
|
+
end
|
|
15095
|
+
local acknowledged = redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
|
|
15096
|
+
if acknowledged == 1 then
|
|
15097
|
+
redis.call('XDEL', KEYS[1], ARGV[2])
|
|
15098
|
+
if ARGV[7] == '1' then redis.call('DEL', KEYS[3]) end
|
|
15099
|
+
end
|
|
15100
|
+
if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
|
|
15101
|
+
return acknowledged
|
|
15102
|
+
`;
|
|
15103
|
+
|
|
15104
|
+
// ../../src/core/queue/redisStreams.ts
|
|
15105
|
+
var STREAM_GROUP = "strata-workers-v1";
|
|
15106
|
+
function streamQueueKey(queueKey) {
|
|
15107
|
+
return `${queueKey}:stream`;
|
|
15108
|
+
}
|
|
15109
|
+
function streamDeadLetterKey(queueKey) {
|
|
15110
|
+
return `${streamQueueKey(queueKey)}:invalid`;
|
|
15111
|
+
}
|
|
15112
|
+
function streamRetryKey(queueKey) {
|
|
15113
|
+
return `${streamQueueKey(queueKey)}:retries`;
|
|
15114
|
+
}
|
|
15115
|
+
function streamControlKey(key, jobId) {
|
|
15116
|
+
const prefix = `${streamQueueKey(key)}/`;
|
|
15117
|
+
if (!jobId.startsWith(prefix) || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(jobId.slice(prefix.length)))
|
|
15118
|
+
throw new Error("Invalid cancellable Streams job ID");
|
|
15119
|
+
return `${streamQueueKey(key)}:control:${jobId.slice(prefix.length)}`;
|
|
15120
|
+
}
|
|
14832
15121
|
async function cancelStreamJob(client, key, jobId) {
|
|
14833
15122
|
return Number(await client.send("EVAL", [
|
|
14834
15123
|
CANCEL_STREAM,
|
|
@@ -14882,26 +15171,6 @@ function watchStreamDeadline(client, deadlineAtMs, remainingMs, expire, fail) {
|
|
|
14882
15171
|
clearTimeout(timer);
|
|
14883
15172
|
};
|
|
14884
15173
|
}
|
|
14885
|
-
var SCHEDULE_RETRY = `
|
|
14886
|
-
local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
|
|
14887
|
-
if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
|
|
14888
|
-
local kind = redis.call('TYPE', KEYS[2]).ok
|
|
14889
|
-
if kind ~= 'none' and kind ~= 'zset' then return redis.error_reply('Invalid stream retry key type') end
|
|
14890
|
-
if ARGV[8] == '1' then
|
|
14891
|
-
local state = redis.call('HGET', KEYS[3], 'state')
|
|
14892
|
-
if state == 'cancelled' then return redis.error_reply('Streams job cancelled') end
|
|
14893
|
-
if state ~= 'active' then return redis.error_reply('Missing or invalid Streams control state') end
|
|
14894
|
-
end
|
|
14895
|
-
local now = redis.call('TIME')
|
|
14896
|
-
local due = tonumber(now[1])*1000 + math.floor(tonumber(now[2])/1000) + tonumber(ARGV[5])
|
|
14897
|
-
if ARGV[7] ~= '' then due = math.min(due, tonumber(ARGV[7])) end
|
|
14898
|
-
redis.call('ZADD', KEYS[2], due, ARGV[6])
|
|
14899
|
-
if ARGV[8] == '1' then redis.call('HSET', KEYS[3], 'retryPayload', ARGV[6]) end
|
|
14900
|
-
redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
|
|
14901
|
-
redis.call('XDEL', KEYS[1], ARGV[2])
|
|
14902
|
-
if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
|
|
14903
|
-
return 1
|
|
14904
|
-
`;
|
|
14905
15174
|
async function scheduleStreamRetry(client, key, reservation, envelope, delayMs) {
|
|
14906
15175
|
if (!Number.isSafeInteger(delayMs) || delayMs < 0 || delayMs > Number.MAX_SAFE_INTEGER / 2)
|
|
14907
15176
|
throw new Error("Invalid Streams retry delay");
|
|
@@ -14923,59 +15192,6 @@ async function scheduleStreamRetry(client, key, reservation, envelope, delayMs)
|
|
|
14923
15192
|
if (Number(scheduled) !== 1)
|
|
14924
15193
|
throw new Error("Queue lease lost while scheduling retry");
|
|
14925
15194
|
}
|
|
14926
|
-
var POLL_STREAM_PRIORITIES = `
|
|
14927
|
-
local group = ARGV[1]
|
|
14928
|
-
local owner = ARGV[2]
|
|
14929
|
-
local visibility = ARGV[3]
|
|
14930
|
-
local function payloadOf(fields)
|
|
14931
|
-
for index = 1, #fields, 2 do
|
|
14932
|
-
if fields[index] == 'payload' and type(fields[index + 1]) == 'string' then return fields[index + 1] end
|
|
14933
|
-
end
|
|
14934
|
-
return ''
|
|
14935
|
-
end
|
|
14936
|
-
local cursors = {}
|
|
14937
|
-
for i = 1, #KEYS / 2 do cursors[i] = ARGV[3 + i] end
|
|
14938
|
-
for i = 1, #KEYS / 2 do
|
|
14939
|
-
local stream = KEYS[(i - 1) * 2 + 1]
|
|
14940
|
-
local retries = KEYS[(i - 1) * 2 + 2]
|
|
14941
|
-
local cursor = ARGV[3 + i]
|
|
14942
|
-
local streamKind = redis.call('TYPE', stream).ok
|
|
14943
|
-
local retryKind = redis.call('TYPE', retries).ok
|
|
14944
|
-
if streamKind ~= 'none' and streamKind ~= 'stream' then return redis.error_reply('Invalid stream retry promotion key type') end
|
|
14945
|
-
if retryKind ~= 'none' and retryKind ~= 'zset' then return redis.error_reply('Invalid stream retry promotion key type') end
|
|
14946
|
-
if streamKind == 'stream' then
|
|
14947
|
-
local now = redis.call('TIME')
|
|
14948
|
-
local due = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
|
|
14949
|
-
local ready = redis.call('ZRANGE', retries, '-inf', due, 'BYSCORE', 'LIMIT', 0, 100)
|
|
14950
|
-
for _, payload in ipairs(ready) do
|
|
14951
|
-
redis.call('XADD', stream, '*', 'payload', payload)
|
|
14952
|
-
redis.call('ZREM', retries, payload)
|
|
14953
|
-
end
|
|
14954
|
-
local window = redis.call('XPENDING', stream, group, cursor, '+', 10)
|
|
14955
|
-
local claimed = redis.call('XAUTOCLAIM', stream, group, owner, visibility, cursor, 'COUNT', 1)
|
|
14956
|
-
for _, entry in ipairs(window) do
|
|
14957
|
-
if entry[2] ~= owner and #redis.call('XPENDING', stream, group, '-', '+', 1, entry[2]) == 0 then
|
|
14958
|
-
redis.call('XGROUP', 'DELCONSUMER', stream, group, entry[2])
|
|
14959
|
-
end
|
|
14960
|
-
end
|
|
14961
|
-
if #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
|
|
14962
|
-
redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
|
|
14963
|
-
end
|
|
14964
|
-
cursors[i] = claimed[1]
|
|
14965
|
-
if #claimed[2] > 0 then
|
|
14966
|
-
return {'1', tostring(i), claimed[2][1][1], payloadOf(claimed[2][1][2]), unpack(cursors)}
|
|
14967
|
-
end
|
|
14968
|
-
local fresh = redis.call('XREADGROUP', 'GROUP', group, owner, 'COUNT', 1, 'STREAMS', stream, '>')
|
|
14969
|
-
if not fresh and #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
|
|
14970
|
-
redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
|
|
14971
|
-
end
|
|
14972
|
-
if fresh and #fresh > 0 and #fresh[1][2] > 0 then
|
|
14973
|
-
return {'1', tostring(i), fresh[1][2][1][1], payloadOf(fresh[1][2][1][2]), unpack(cursors)}
|
|
14974
|
-
end
|
|
14975
|
-
end
|
|
14976
|
-
end
|
|
14977
|
-
return {'0', unpack(cursors)}
|
|
14978
|
-
`;
|
|
14979
15195
|
async function pollStreamPriorities(client, queueKeys, owner, cursors) {
|
|
14980
15196
|
const keys = [];
|
|
14981
15197
|
for (const key of queueKeys)
|
|
@@ -15019,12 +15235,6 @@ async function readStreamQueueDepth(client, key) {
|
|
|
15019
15235
|
streamRetryKey(key)
|
|
15020
15236
|
]));
|
|
15021
15237
|
}
|
|
15022
|
-
var ASSERT_DRAINED = `
|
|
15023
|
-
if redis.call('LLEN', KEYS[1]) > 0 or redis.call('LLEN', KEYS[2]) > 0 or redis.call('HLEN', KEYS[3]) > 0 then
|
|
15024
|
-
return redis.error_reply('Legacy queue state requires maintenance conversion before Streams activation')
|
|
15025
|
-
end
|
|
15026
|
-
return 1
|
|
15027
|
-
`;
|
|
15028
15238
|
async function assertLegacyDrained(client, key) {
|
|
15029
15239
|
await client.send("EVAL", [
|
|
15030
15240
|
ASSERT_DRAINED,
|
|
@@ -15034,30 +15244,6 @@ async function assertLegacyDrained(client, key) {
|
|
|
15034
15244
|
`${key}:processing:leases`
|
|
15035
15245
|
]);
|
|
15036
15246
|
}
|
|
15037
|
-
var UPDATE_STREAM = `
|
|
15038
|
-
local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
|
|
15039
|
-
if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
|
|
15040
|
-
if ARGV[7] == '1' then
|
|
15041
|
-
local kind = redis.call('TYPE', KEYS[3]).ok
|
|
15042
|
-
if kind ~= 'none' and kind ~= 'hash' then return redis.error_reply('Invalid stream control key type') end
|
|
15043
|
-
end
|
|
15044
|
-
if ARGV[5] == 'renew' then
|
|
15045
|
-
local claimed = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[3], 0, ARGV[2], 'JUSTID')
|
|
15046
|
-
return #claimed
|
|
15047
|
-
end
|
|
15048
|
-
if ARGV[5] == 'quarantine' then
|
|
15049
|
-
local kind = redis.call('TYPE', KEYS[2]).ok
|
|
15050
|
-
if kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream quarantine key type') end
|
|
15051
|
-
redis.call('XADD', KEYS[2], '*', 'sourceId', ARGV[2], 'payload', ARGV[6])
|
|
15052
|
-
end
|
|
15053
|
-
local acknowledged = redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
|
|
15054
|
-
if acknowledged == 1 then
|
|
15055
|
-
redis.call('XDEL', KEYS[1], ARGV[2])
|
|
15056
|
-
if ARGV[7] == '1' then redis.call('DEL', KEYS[3]) end
|
|
15057
|
-
end
|
|
15058
|
-
if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
|
|
15059
|
-
return acknowledged
|
|
15060
|
-
`;
|
|
15061
15247
|
async function ensureStreamGroup(client, key) {
|
|
15062
15248
|
await assertLegacyDrained(client, key);
|
|
15063
15249
|
try {
|
|
@@ -15375,141 +15561,6 @@ function queueProcessingKey(queueKey) {
|
|
|
15375
15561
|
function queueProcessingLeaseKey(queueKey) {
|
|
15376
15562
|
return `${queueKey}:processing:leases`;
|
|
15377
15563
|
}
|
|
15378
|
-
var SCRIPT_HEADER = `
|
|
15379
|
-
local function checkType(key, expected)
|
|
15380
|
-
local actual = redis.call('TYPE', key).ok
|
|
15381
|
-
if actual ~= 'none' and actual ~= expected then
|
|
15382
|
-
return redis.error_reply('Unexpected queue key type: ' .. key)
|
|
15383
|
-
end
|
|
15384
|
-
end
|
|
15385
|
-
local function nowMs()
|
|
15386
|
-
local time = redis.call('TIME')
|
|
15387
|
-
return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
|
|
15388
|
-
end
|
|
15389
|
-
`;
|
|
15390
|
-
var RESERVE_JOB = `${SCRIPT_HEADER}
|
|
15391
|
-
local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
|
|
15392
|
-
if err then return err end
|
|
15393
|
-
local payload = redis.call('LINDEX', KEYS[1], -1)
|
|
15394
|
-
if not payload then return nil end
|
|
15395
|
-
local record = cjson.encode({strataReservation=1, id=ARGV[1], owner=ARGV[2], payload=payload})
|
|
15396
|
-
local lease = cjson.encode({owner=ARGV[2], expiresAt=nowMs()+tonumber(ARGV[3])})
|
|
15397
|
-
redis.call('LPUSH', KEYS[2], record)
|
|
15398
|
-
redis.call('HSET', KEYS[3], ARGV[1], lease)
|
|
15399
|
-
redis.call('RPOP', KEYS[1])
|
|
15400
|
-
return record
|
|
15401
|
-
`;
|
|
15402
|
-
var RENEW_OR_ACK = `${SCRIPT_HEADER}
|
|
15403
|
-
local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'hash') or checkType(KEYS[3], 'list')
|
|
15404
|
-
if err then return err end
|
|
15405
|
-
local raw = redis.call('HGET', KEYS[2], ARGV[1])
|
|
15406
|
-
if not raw then return 0 end
|
|
15407
|
-
local ok, lease = pcall(cjson.decode, raw)
|
|
15408
|
-
local now = nowMs()
|
|
15409
|
-
if not ok or type(lease) ~= 'table' or lease.owner ~= ARGV[2] or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now then
|
|
15410
|
-
return 0
|
|
15411
|
-
end
|
|
15412
|
-
if ARGV[4] == 'renew' then
|
|
15413
|
-
redis.call('HSET', KEYS[2], ARGV[1], cjson.encode({owner=ARGV[2], expiresAt=now+tonumber(ARGV[5])}))
|
|
15414
|
-
return 1
|
|
15415
|
-
end
|
|
15416
|
-
if ARGV[4] == 'quarantine' then redis.call('LPUSH', KEYS[3], ARGV[6]) end
|
|
15417
|
-
local removed = redis.call('LREM', KEYS[1], 1, ARGV[3])
|
|
15418
|
-
redis.call('HDEL', KEYS[2], ARGV[1])
|
|
15419
|
-
return removed
|
|
15420
|
-
`;
|
|
15421
|
-
var RECLAIM_JOBS = `${SCRIPT_HEADER}
|
|
15422
|
-
local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
|
|
15423
|
-
if err then return err end
|
|
15424
|
-
local now = nowMs()
|
|
15425
|
-
local reclaimed = 0
|
|
15426
|
-
for _, record in ipairs(redis.call('LRANGE', KEYS[2], 0, -1)) do
|
|
15427
|
-
local payload, field = record, record
|
|
15428
|
-
local modern = false
|
|
15429
|
-
local ok, reservation = pcall(cjson.decode, record)
|
|
15430
|
-
if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
|
|
15431
|
-
payload, field, modern = reservation.payload, reservation.id, true
|
|
15432
|
-
end
|
|
15433
|
-
local raw = redis.call('HGET', KEYS[3], field)
|
|
15434
|
-
local expired = true
|
|
15435
|
-
if raw then
|
|
15436
|
-
if modern then
|
|
15437
|
-
local leaseOk, lease = pcall(cjson.decode, raw)
|
|
15438
|
-
expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
|
|
15439
|
-
else
|
|
15440
|
-
local reservedAt = tonumber(raw)
|
|
15441
|
-
expired = not reservedAt or now - reservedAt >= tonumber(ARGV[1])
|
|
15442
|
-
end
|
|
15443
|
-
end
|
|
15444
|
-
if expired then
|
|
15445
|
-
redis.call('LPUSH', KEYS[1], payload)
|
|
15446
|
-
redis.call('LREM', KEYS[2], 1, record)
|
|
15447
|
-
redis.call('HDEL', KEYS[3], field)
|
|
15448
|
-
reclaimed = reclaimed + 1
|
|
15449
|
-
end
|
|
15450
|
-
end
|
|
15451
|
-
return reclaimed
|
|
15452
|
-
`;
|
|
15453
|
-
var POLL_LIST_PRIORITIES = `${SCRIPT_HEADER}
|
|
15454
|
-
local owner = ARGV[1]
|
|
15455
|
-
local visibility = ARGV[2]
|
|
15456
|
-
local reservationId = ARGV[3]
|
|
15457
|
-
local reclaim = ARGV[4] == '1'
|
|
15458
|
-
local function reclaimQueue(listKey, processingKey, leaseKey)
|
|
15459
|
-
local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
|
|
15460
|
-
if err then return err end
|
|
15461
|
-
local now = nowMs()
|
|
15462
|
-
for _, record in ipairs(redis.call('LRANGE', processingKey, 0, -1)) do
|
|
15463
|
-
local payload, field = record, record
|
|
15464
|
-
local modern = false
|
|
15465
|
-
local ok, reservation = pcall(cjson.decode, record)
|
|
15466
|
-
if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
|
|
15467
|
-
payload, field, modern = reservation.payload, reservation.id, true
|
|
15468
|
-
end
|
|
15469
|
-
local raw = redis.call('HGET', leaseKey, field)
|
|
15470
|
-
local expired = true
|
|
15471
|
-
if raw then
|
|
15472
|
-
if modern then
|
|
15473
|
-
local leaseOk, lease = pcall(cjson.decode, raw)
|
|
15474
|
-
expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
|
|
15475
|
-
else
|
|
15476
|
-
local reservedAt = tonumber(raw)
|
|
15477
|
-
expired = not reservedAt or now - reservedAt >= tonumber(visibility)
|
|
15478
|
-
end
|
|
15479
|
-
end
|
|
15480
|
-
if expired then
|
|
15481
|
-
redis.call('LPUSH', listKey, payload)
|
|
15482
|
-
redis.call('LREM', processingKey, 1, record)
|
|
15483
|
-
redis.call('HDEL', leaseKey, field)
|
|
15484
|
-
end
|
|
15485
|
-
end
|
|
15486
|
-
end
|
|
15487
|
-
local function reserveQueue(listKey, processingKey, leaseKey)
|
|
15488
|
-
local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
|
|
15489
|
-
if err then return err end
|
|
15490
|
-
local payload = redis.call('LINDEX', listKey, -1)
|
|
15491
|
-
if not payload then return nil end
|
|
15492
|
-
local record = cjson.encode({strataReservation=1, id=reservationId, owner=owner, payload=payload})
|
|
15493
|
-
local lease = cjson.encode({owner=owner, expiresAt=nowMs()+tonumber(visibility)})
|
|
15494
|
-
redis.call('LPUSH', processingKey, record)
|
|
15495
|
-
redis.call('HSET', leaseKey, reservationId, lease)
|
|
15496
|
-
redis.call('RPOP', listKey)
|
|
15497
|
-
return record
|
|
15498
|
-
end
|
|
15499
|
-
local count = #KEYS / 3
|
|
15500
|
-
if reclaim then
|
|
15501
|
-
for i = 1, count do
|
|
15502
|
-
local err = reclaimQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
|
|
15503
|
-
if err then return err end
|
|
15504
|
-
end
|
|
15505
|
-
end
|
|
15506
|
-
for i = 1, count do
|
|
15507
|
-
local record = reserveQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
|
|
15508
|
-
if type(record) == 'string' then return {'1', tostring(i), record} end
|
|
15509
|
-
if record then return record end
|
|
15510
|
-
end
|
|
15511
|
-
return {'0'}
|
|
15512
|
-
`;
|
|
15513
15564
|
function queueInvalidKey(queueKey) {
|
|
15514
15565
|
return `${queueKey}:invalid`;
|
|
15515
15566
|
}
|
|
@@ -15815,6 +15866,8 @@ import { createHash as createHash7 } from "crypto";
|
|
|
15815
15866
|
// ../../src/core/scheduler/leases.ts
|
|
15816
15867
|
import { createHash as createHash6 } from "crypto";
|
|
15817
15868
|
var {RedisClient: RedisClient6 } = globalThis.Bun;
|
|
15869
|
+
|
|
15870
|
+
// ../../src/core/scheduler/leaseScript.ts
|
|
15818
15871
|
var LEASE_SCRIPT = `
|
|
15819
15872
|
for _, key in ipairs(KEYS) do
|
|
15820
15873
|
local kind = redis.call('TYPE', key).ok
|
|
@@ -15842,6 +15895,7 @@ else return redis.error_reply('Unexpected scheduler action') end
|
|
|
15842
15895
|
return 1
|
|
15843
15896
|
`;
|
|
15844
15897
|
|
|
15898
|
+
// ../../src/core/scheduler/leases.ts
|
|
15845
15899
|
class RedisSchedulerLeaseStore {
|
|
15846
15900
|
client;
|
|
15847
15901
|
owned;
|