express-file-cluster 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/auth/index.cjs +3 -3
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +2 -2
- package/dist/{chunk-ZDM5JHVK.cjs → chunk-2J3HHQKP.cjs} +3 -3
- package/dist/{chunk-ZDM5JHVK.cjs.map → chunk-2J3HHQKP.cjs.map} +1 -1
- package/dist/chunk-2PBMLMO4.js +1386 -0
- package/dist/chunk-2PBMLMO4.js.map +1 -0
- package/dist/chunk-66R7S7J3.cjs +1386 -0
- package/dist/chunk-66R7S7J3.cjs.map +1 -0
- package/dist/{chunk-6OGOVV57.js → chunk-6QNLN6AI.js} +118 -1266
- package/dist/chunk-6QNLN6AI.js.map +1 -0
- package/dist/chunk-BBSZLGZW.js +113 -0
- package/dist/chunk-BBSZLGZW.js.map +1 -0
- package/dist/{chunk-BUBXO7WU.js → chunk-HXV543HZ.js} +10 -3
- package/dist/chunk-HXV543HZ.js.map +1 -0
- package/dist/chunk-QL6EWT4B.cjs +113 -0
- package/dist/chunk-QL6EWT4B.cjs.map +1 -0
- package/dist/{chunk-AZYXQU3Z.cjs → chunk-RGTENTDN.cjs} +239 -1387
- package/dist/chunk-RGTENTDN.cjs.map +1 -0
- package/dist/{chunk-TRC4DUZB.js → chunk-RSZB7VAO.js} +2 -2
- package/dist/{chunk-MGH4VDV3.cjs → chunk-VQSWSYK6.cjs} +10 -3
- package/dist/chunk-VQSWSYK6.cjs.map +1 -0
- package/dist/cli/db-runner.cjs +613 -28
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +611 -26
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +1210 -12
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +1221 -23
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/db.md +1 -0
- package/dist/docs/api-reference/ignite.md +19 -0
- package/dist/docs/api-reference/table.md +3 -0
- package/dist/docs/cli/add.md +136 -0
- package/dist/docs/cli/db.md +25 -2
- package/dist/docs/cli/index.md +10 -1
- package/dist/docs/core-concepts/middleware.md +1 -1
- package/dist/docs/getting-started/index.md +25 -18
- package/dist/docs/getting-started/project-structure.md +6 -7
- package/dist/docs/guides/authentication.md +3 -1
- package/dist/docs/guides/coming-from-prisma.md +75 -0
- package/dist/docs/guides/database.md +5 -2
- package/dist/docs/guides/generated-portals.md +36 -19
- package/dist/docs/guides/mailer.md +7 -10
- package/dist/docs/guides/migrations.md +114 -3
- package/dist/docs/guides/oauth.md +94 -0
- package/dist/docs/guides/rbac.md +5 -40
- package/dist/docs/guides/relations.md +147 -0
- package/dist/docs/guides/which-api.md +50 -0
- package/dist/docs/index.md +7 -3
- package/dist/docs/skills/SKILL.md +3 -3
- package/dist/docs/skills/api-surface.md +1 -0
- package/dist/docs/skills/what-not-to-invent.md +22 -6
- package/dist/index.cjs +20 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/registry/index.json +506 -0
- package/dist/registry/js-mongo/_base.json +1 -0
- package/dist/registry/js-mongo/account-security.json +1 -0
- package/dist/registry/js-mongo/account-settings.json +1 -0
- package/dist/registry/js-mongo/admin-admins.json +1 -0
- package/dist/registry/js-mongo/admin-analytics.json +1 -0
- package/dist/registry/js-mongo/admin-billing.json +1 -0
- package/dist/registry/js-mongo/admin-content.json +1 -0
- package/dist/registry/js-mongo/admin-logs.json +1 -0
- package/dist/registry/js-mongo/admin-support.json +1 -0
- package/dist/registry/js-mongo/admin-system.json +1 -0
- package/dist/registry/js-mongo/admin-users.json +1 -0
- package/dist/registry/js-mongo/admin.json +1 -0
- package/dist/registry/js-mongo/auth.json +1 -0
- package/dist/registry/js-mongo/auth@apple.json +1 -0
- package/dist/registry/js-mongo/auth@google.json +1 -0
- package/dist/registry/js-mongo/billing.json +1 -0
- package/dist/registry/js-mongo/email-client.json +1 -0
- package/dist/registry/js-mongo/email-verification.json +1 -0
- package/dist/registry/js-mongo/files.json +1 -0
- package/dist/registry/js-mongo/forgot-password.json +1 -0
- package/dist/registry/js-mongo/notifications.json +1 -0
- package/dist/registry/js-mongo/support.json +1 -0
- package/dist/registry/js-mongo/user-profile.json +1 -0
- package/dist/registry/js-pg-model/_base.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -0
- package/dist/registry/js-pg-model/account-settings.json +1 -0
- package/dist/registry/js-pg-model/admin-admins.json +1 -0
- package/dist/registry/js-pg-model/admin-analytics.json +1 -0
- package/dist/registry/js-pg-model/admin-billing.json +1 -0
- package/dist/registry/js-pg-model/admin-content.json +1 -0
- package/dist/registry/js-pg-model/admin-logs.json +1 -0
- package/dist/registry/js-pg-model/admin-support.json +1 -0
- package/dist/registry/js-pg-model/admin-system.json +1 -0
- package/dist/registry/js-pg-model/admin-users.json +1 -0
- package/dist/registry/js-pg-model/admin.json +1 -0
- package/dist/registry/js-pg-model/auth.json +1 -0
- package/dist/registry/js-pg-model/auth@apple.json +1 -0
- package/dist/registry/js-pg-model/auth@google.json +1 -0
- package/dist/registry/js-pg-model/billing.json +1 -0
- package/dist/registry/js-pg-model/email-client.json +1 -0
- package/dist/registry/js-pg-model/email-verification.json +1 -0
- package/dist/registry/js-pg-model/files.json +1 -0
- package/dist/registry/js-pg-model/forgot-password.json +1 -0
- package/dist/registry/js-pg-model/notifications.json +1 -0
- package/dist/registry/js-pg-model/support.json +1 -0
- package/dist/registry/js-pg-model/user-profile.json +1 -0
- package/dist/registry/js-pg-table/_base.json +1 -0
- package/dist/registry/js-pg-table/account-security.json +1 -0
- package/dist/registry/js-pg-table/account-settings.json +1 -0
- package/dist/registry/js-pg-table/admin-admins.json +1 -0
- package/dist/registry/js-pg-table/admin-analytics.json +1 -0
- package/dist/registry/js-pg-table/admin-billing.json +1 -0
- package/dist/registry/js-pg-table/admin-content.json +1 -0
- package/dist/registry/js-pg-table/admin-logs.json +1 -0
- package/dist/registry/js-pg-table/admin-support.json +1 -0
- package/dist/registry/js-pg-table/admin-system.json +1 -0
- package/dist/registry/js-pg-table/admin-users.json +1 -0
- package/dist/registry/js-pg-table/admin.json +1 -0
- package/dist/registry/js-pg-table/auth.json +1 -0
- package/dist/registry/js-pg-table/auth@apple.json +1 -0
- package/dist/registry/js-pg-table/auth@google.json +1 -0
- package/dist/registry/js-pg-table/billing.json +1 -0
- package/dist/registry/js-pg-table/email-client.json +1 -0
- package/dist/registry/js-pg-table/email-verification.json +1 -0
- package/dist/registry/js-pg-table/files.json +1 -0
- package/dist/registry/js-pg-table/forgot-password.json +1 -0
- package/dist/registry/js-pg-table/notifications.json +1 -0
- package/dist/registry/js-pg-table/support.json +1 -0
- package/dist/registry/js-pg-table/user-profile.json +1 -0
- package/dist/registry/ts-mongo/_base.json +1 -0
- package/dist/registry/ts-mongo/account-security.json +1 -0
- package/dist/registry/ts-mongo/account-settings.json +1 -0
- package/dist/registry/ts-mongo/admin-admins.json +1 -0
- package/dist/registry/ts-mongo/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo/admin-billing.json +1 -0
- package/dist/registry/ts-mongo/admin-content.json +1 -0
- package/dist/registry/ts-mongo/admin-logs.json +1 -0
- package/dist/registry/ts-mongo/admin-support.json +1 -0
- package/dist/registry/ts-mongo/admin-system.json +1 -0
- package/dist/registry/ts-mongo/admin-users.json +1 -0
- package/dist/registry/ts-mongo/admin.json +1 -0
- package/dist/registry/ts-mongo/auth.json +1 -0
- package/dist/registry/ts-mongo/auth@apple.json +1 -0
- package/dist/registry/ts-mongo/auth@google.json +1 -0
- package/dist/registry/ts-mongo/billing.json +1 -0
- package/dist/registry/ts-mongo/email-client.json +1 -0
- package/dist/registry/ts-mongo/email-verification.json +1 -0
- package/dist/registry/ts-mongo/files.json +1 -0
- package/dist/registry/ts-mongo/forgot-password.json +1 -0
- package/dist/registry/ts-mongo/notifications.json +1 -0
- package/dist/registry/ts-mongo/support.json +1 -0
- package/dist/registry/ts-mongo/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/_base.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -0
- package/dist/registry/ts-pg-model/account-settings.json +1 -0
- package/dist/registry/ts-pg-model/admin-admins.json +1 -0
- package/dist/registry/ts-pg-model/admin-analytics.json +1 -0
- package/dist/registry/ts-pg-model/admin-billing.json +1 -0
- package/dist/registry/ts-pg-model/admin-content.json +1 -0
- package/dist/registry/ts-pg-model/admin-logs.json +1 -0
- package/dist/registry/ts-pg-model/admin-support.json +1 -0
- package/dist/registry/ts-pg-model/admin-system.json +1 -0
- package/dist/registry/ts-pg-model/admin-users.json +1 -0
- package/dist/registry/ts-pg-model/admin.json +1 -0
- package/dist/registry/ts-pg-model/auth.json +1 -0
- package/dist/registry/ts-pg-model/auth@apple.json +1 -0
- package/dist/registry/ts-pg-model/auth@google.json +1 -0
- package/dist/registry/ts-pg-model/billing.json +1 -0
- package/dist/registry/ts-pg-model/email-client.json +1 -0
- package/dist/registry/ts-pg-model/email-verification.json +1 -0
- package/dist/registry/ts-pg-model/files.json +1 -0
- package/dist/registry/ts-pg-model/forgot-password.json +1 -0
- package/dist/registry/ts-pg-model/notifications.json +1 -0
- package/dist/registry/ts-pg-model/support.json +1 -0
- package/dist/registry/ts-pg-model/user-profile.json +1 -0
- package/dist/registry/ts-pg-table/_base.json +1 -0
- package/dist/registry/ts-pg-table/account-security.json +1 -0
- package/dist/registry/ts-pg-table/account-settings.json +1 -0
- package/dist/registry/ts-pg-table/admin-admins.json +1 -0
- package/dist/registry/ts-pg-table/admin-analytics.json +1 -0
- package/dist/registry/ts-pg-table/admin-billing.json +1 -0
- package/dist/registry/ts-pg-table/admin-content.json +1 -0
- package/dist/registry/ts-pg-table/admin-logs.json +1 -0
- package/dist/registry/ts-pg-table/admin-support.json +1 -0
- package/dist/registry/ts-pg-table/admin-system.json +1 -0
- package/dist/registry/ts-pg-table/admin-users.json +1 -0
- package/dist/registry/ts-pg-table/admin.json +1 -0
- package/dist/registry/ts-pg-table/auth.json +1 -0
- package/dist/registry/ts-pg-table/auth@apple.json +1 -0
- package/dist/registry/ts-pg-table/auth@google.json +1 -0
- package/dist/registry/ts-pg-table/billing.json +1 -0
- package/dist/registry/ts-pg-table/email-client.json +1 -0
- package/dist/registry/ts-pg-table/email-verification.json +1 -0
- package/dist/registry/ts-pg-table/files.json +1 -0
- package/dist/registry/ts-pg-table/forgot-password.json +1 -0
- package/dist/registry/ts-pg-table/notifications.json +1 -0
- package/dist/registry/ts-pg-table/support.json +1 -0
- package/dist/registry/ts-pg-table/user-profile.json +1 -0
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/{types-B6lVw4bj.d.ts → types-gyvA7BtO.d.cts} +18 -1
- package/dist/{types-B6lVw4bj.d.cts → types-gyvA7BtO.d.ts} +18 -1
- package/package.json +11 -2
- package/dist/chunk-6OGOVV57.js.map +0 -1
- package/dist/chunk-AZYXQU3Z.cjs.map +0 -1
- package/dist/chunk-BUBXO7WU.js.map +0 -1
- package/dist/chunk-MGH4VDV3.cjs.map +0 -1
- /package/dist/{chunk-TRC4DUZB.js.map → chunk-RSZB7VAO.js.map} +0 -0
|
@@ -6,457 +6,40 @@
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var _chunkMGH4VDV3cjs = require('./chunk-MGH4VDV3.cjs');
|
|
10
9
|
|
|
11
10
|
|
|
12
11
|
|
|
13
|
-
var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
|
|
14
12
|
|
|
15
|
-
// src/errors.ts
|
|
16
|
-
var HttpError = class _HttpError extends Error {
|
|
17
|
-
|
|
18
|
-
constructor(statusCode, message) {
|
|
19
|
-
super(message);
|
|
20
|
-
this.name = "HttpError";
|
|
21
|
-
this.statusCode = statusCode;
|
|
22
|
-
Error.captureStackTrace(this, _HttpError);
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Wraps an unknown caught value into an `HttpError`.
|
|
26
|
-
* If the value is already an `HttpError`, it is returned as-is.
|
|
27
|
-
* Otherwise the `message` from the caught `Error` (or a fallback) is used.
|
|
28
|
-
*
|
|
29
|
-
* @example
|
|
30
|
-
* } catch (err) {
|
|
31
|
-
* throw HttpError.from(err, 500, 'Something went wrong');
|
|
32
|
-
* }
|
|
33
|
-
*/
|
|
34
|
-
static from(err, statusCode = 500, fallback = "Internal Server Error") {
|
|
35
|
-
if (err instanceof _HttpError) return err;
|
|
36
|
-
const message = err instanceof Error ? err.message : fallback;
|
|
37
|
-
return new _HttpError(statusCode, message);
|
|
38
|
-
}
|
|
39
|
-
/** Returns a plain object representation suitable for JSON serialization. */
|
|
40
|
-
toJSON() {
|
|
41
|
-
return {
|
|
42
|
-
statusCode: this.statusCode,
|
|
43
|
-
error: this.name,
|
|
44
|
-
message: this.message
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
function isHttpError(value) {
|
|
49
|
-
return value instanceof HttpError;
|
|
50
|
-
}
|
|
51
13
|
|
|
52
|
-
// src/db/schema.ts
|
|
53
|
-
var _crypto = require('crypto');
|
|
54
|
-
var MODEL_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "object", "objectId", "array"]);
|
|
55
|
-
var TABLE_ONLY_TYPES = /* @__PURE__ */ new Set(["integer", "bigint", "decimal", "uuid", "json"]);
|
|
56
|
-
var TABLE_ONLY_OPTIONS = ["precision", "scale", "nativeEnum", "column", "onDelete"];
|
|
57
|
-
var REFERENTIAL_ACTIONS = /* @__PURE__ */ new Set(["restrict", "cascade", "setNull"]);
|
|
58
|
-
var FOREIGN_KEY_TYPES = /* @__PURE__ */ new Set(["objectId", "uuid", "integer", "bigint"]);
|
|
59
|
-
function isFieldDefinition(value) {
|
|
60
|
-
if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
61
|
-
const type = value.type;
|
|
62
|
-
return typeof type === "string" && (MODEL_TYPES.has(type) || TABLE_ONLY_TYPES.has(type));
|
|
63
|
-
}
|
|
64
|
-
var untyped = () => ({ kind: "json", def: { type: "object" } });
|
|
65
|
-
var SchemaBuilder = class {
|
|
66
|
-
constructor(model, mode) {
|
|
67
|
-
this.model = model;
|
|
68
|
-
this.mode = mode;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
fail(path, message) {
|
|
73
|
-
throw new Error(`[EFC] ${this.model}.${path}: ${message}`);
|
|
74
|
-
}
|
|
75
|
-
checkType(type, path) {
|
|
76
|
-
if (this.mode === "model" && TABLE_ONLY_TYPES.has(type)) {
|
|
77
|
-
this.fail(path, `type '${type}' is PostgreSQL-only \u2014 use defineTable, or a portable type`);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
checkDefinition(def, path, topLevel) {
|
|
81
|
-
this.checkType(def.type, path);
|
|
82
|
-
if (this.mode === "model") {
|
|
83
|
-
for (const opt of TABLE_ONLY_OPTIONS) {
|
|
84
|
-
if (def[opt] !== void 0) this.fail(path, `'${opt}' is a defineTable option`);
|
|
85
|
-
}
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
88
|
-
if ((def.precision !== void 0 || def.scale !== void 0) && def.type !== "decimal") {
|
|
89
|
-
this.fail(path, `'precision' / 'scale' only apply to decimal fields`);
|
|
90
|
-
}
|
|
91
|
-
if (def.scale !== void 0 && def.precision === void 0) {
|
|
92
|
-
this.fail(path, `'scale' needs 'precision'`);
|
|
93
|
-
}
|
|
94
|
-
if (def.nativeEnum && !(def.enum && def.enum.every((v) => typeof v === "string"))) {
|
|
95
|
-
this.fail(path, `'nativeEnum' needs a string 'enum'`);
|
|
96
|
-
}
|
|
97
|
-
if (def.column !== void 0 && !topLevel) {
|
|
98
|
-
this.fail(path, `'column' only applies to top-level fields`);
|
|
99
|
-
}
|
|
100
|
-
if (def.onDelete !== void 0) {
|
|
101
|
-
if (def.ref === void 0) this.fail(path, `'onDelete' needs 'ref'`);
|
|
102
|
-
if (!REFERENTIAL_ACTIONS.has(def.onDelete)) {
|
|
103
|
-
this.fail(path, `onDelete must be 'restrict', 'cascade' or 'setNull'`);
|
|
104
|
-
}
|
|
105
|
-
if (def.onDelete === "setNull" && def.required) {
|
|
106
|
-
this.fail(path, `onDelete: 'setNull' can't clear a required field`);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
if (def.ref !== void 0) {
|
|
110
|
-
const many = def.type === "array";
|
|
111
|
-
if (!topLevel) this.fail(path, `'ref' only applies to top-level fields`);
|
|
112
|
-
if (!FOREIGN_KEY_TYPES.has(many ? String(def.of) : def.type)) {
|
|
113
|
-
this.fail(
|
|
114
|
-
path,
|
|
115
|
-
many ? `a many-to-many 'ref' needs of: objectId, uuid, integer or bigint` : `'ref' needs an id type: objectId, uuid, integer or bigint`
|
|
116
|
-
);
|
|
117
|
-
}
|
|
118
|
-
if (many && def.onDelete !== void 0) {
|
|
119
|
-
this.fail(
|
|
120
|
-
path,
|
|
121
|
-
`'onDelete' doesn't apply to many-to-many refs \u2014 links are always removed with either record`
|
|
122
|
-
);
|
|
123
|
-
}
|
|
124
|
-
if (many && (def.unique || def.index)) {
|
|
125
|
-
this.fail(path, `many-to-many refs are indexed already; 'unique' / 'index' don't apply`);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
item(of, parent, path) {
|
|
130
|
-
if (of === void 0) return untyped();
|
|
131
|
-
if (typeof of === "string") {
|
|
132
|
-
this.checkType(of, path);
|
|
133
|
-
if (of === "object" || of === "json") return untyped();
|
|
134
|
-
const def = {
|
|
135
|
-
type: of,
|
|
136
|
-
...parent.ref !== void 0 && { ref: parent.ref }
|
|
137
|
-
};
|
|
138
|
-
return { kind: "scalar", type: of, def };
|
|
139
|
-
}
|
|
140
|
-
return { kind: "object", fields: this.tree(of, `${path}.$`), def: { type: "object" } };
|
|
141
|
-
}
|
|
142
|
-
field(field, path, topLevel) {
|
|
143
|
-
if (Array.isArray(field)) {
|
|
144
|
-
const inner = field[0];
|
|
145
|
-
return {
|
|
146
|
-
kind: "array",
|
|
147
|
-
item: inner ? { kind: "object", fields: this.tree(inner, `${path}.$`), def: { type: "object" } } : untyped(),
|
|
148
|
-
def: { type: "array" }
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
if (!isFieldDefinition(field)) {
|
|
152
|
-
const type = field.type;
|
|
153
|
-
if (typeof type === "string") this.fail(path, `unknown field type '${type}'`);
|
|
154
|
-
return {
|
|
155
|
-
kind: "object",
|
|
156
|
-
fields: this.tree(field, path),
|
|
157
|
-
def: { type: "object" }
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
const def = field;
|
|
161
|
-
this.checkDefinition(def, path, topLevel);
|
|
162
|
-
if (def.type === "array") return { kind: "array", item: this.item(def.of, def, path), def };
|
|
163
|
-
if (def.type === "object") {
|
|
164
|
-
return def.fields ? { kind: "object", fields: this.tree(def.fields, path), def } : { kind: "json", def };
|
|
165
|
-
}
|
|
166
|
-
if (def.type === "json") return { kind: "json", def };
|
|
167
|
-
return { kind: "scalar", type: def.type, def };
|
|
168
|
-
}
|
|
169
|
-
tree(schema, prefix = "") {
|
|
170
|
-
const out = {};
|
|
171
|
-
for (const [key, field] of Object.entries(schema)) {
|
|
172
|
-
out[key] = this.field(field, prefix ? `${prefix}.${key}` : key, prefix === "");
|
|
173
|
-
}
|
|
174
|
-
return out;
|
|
175
|
-
}
|
|
176
|
-
};
|
|
177
|
-
function normalizeSchema(schema, mode = "model", model = "Model") {
|
|
178
|
-
return new SchemaBuilder(model, mode).tree(schema);
|
|
179
|
-
}
|
|
180
|
-
function timestampFields(options) {
|
|
181
|
-
const ts = _nullishCoalesce(options.timestamps, () => ( true));
|
|
182
|
-
if (ts === false) return {};
|
|
183
|
-
if (ts === true) return { createdAt: "createdAt", updatedAt: "updatedAt" };
|
|
184
|
-
const out = {};
|
|
185
|
-
if (ts.createdAt !== false) out.createdAt = _nullishCoalesce(ts.createdAt, () => ( "createdAt"));
|
|
186
|
-
if (ts.updatedAt !== false) out.updatedAt = _nullishCoalesce(ts.updatedAt, () => ( "updatedAt"));
|
|
187
|
-
return out;
|
|
188
|
-
}
|
|
189
|
-
var STATIC_DEFAULT_OPERATORS = {
|
|
190
|
-
$now: () => /* @__PURE__ */ new Date(),
|
|
191
|
-
$uuid: () => _crypto.randomUUID.call(void 0, ),
|
|
192
|
-
$timestamp: () => Date.now(),
|
|
193
|
-
$shortId: () => _crypto.randomBytes.call(void 0, 12).toString("base64url")
|
|
194
|
-
};
|
|
195
|
-
var FIXED_DEFAULT_OPERATORS = /* @__PURE__ */ new Set(["$now", "$uuid", "$objectId", "$timestamp", "$shortId"]);
|
|
196
|
-
function isCurrentUserOperator(value) {
|
|
197
|
-
return typeof value === "string" && (value === "$currentUser" || value.startsWith("$currentUser."));
|
|
198
|
-
}
|
|
199
|
-
function isDefaultOperator(value) {
|
|
200
|
-
return typeof value === "string" && FIXED_DEFAULT_OPERATORS.has(value) || isCurrentUserOperator(value);
|
|
201
|
-
}
|
|
202
|
-
function resolveDefault(value, objectId) {
|
|
203
|
-
if (!isDefaultOperator(value)) return value;
|
|
204
|
-
if (value === "$objectId") return objectId;
|
|
205
|
-
if (value === "$currentUser") return () => _chunkYL37D6KMcjs.getCurrentUser.call(void 0, );
|
|
206
|
-
if (isCurrentUserOperator(value)) {
|
|
207
|
-
const key = value.slice("$currentUser.".length);
|
|
208
|
-
return () => _optionalChain([_chunkYL37D6KMcjs.getCurrentUser.call(void 0, ), 'optionalAccess', _ => _[key]]);
|
|
209
|
-
}
|
|
210
|
-
return STATIC_DEFAULT_OPERATORS[value];
|
|
211
|
-
}
|
|
212
|
-
function applyDefaults(tree, data, objectId) {
|
|
213
|
-
const out = { ...data };
|
|
214
|
-
for (const [key, node] of Object.entries(tree)) {
|
|
215
|
-
if (out[key] === void 0 && node.def.default !== void 0) {
|
|
216
|
-
const d = resolveDefault(node.def.default, objectId);
|
|
217
|
-
const value = typeof d === "function" ? d() : structuredClone(d);
|
|
218
|
-
if (value !== void 0) out[key] = value;
|
|
219
|
-
}
|
|
220
|
-
if (node.kind === "object" && out[key] != null && typeof out[key] === "object") {
|
|
221
|
-
out[key] = applyDefaults(node.fields, out[key], objectId);
|
|
222
|
-
}
|
|
223
|
-
if (node.kind === "array" && node.item.kind === "object" && Array.isArray(out[key])) {
|
|
224
|
-
const fields = node.item.fields;
|
|
225
|
-
out[key] = out[key].map(
|
|
226
|
-
(v) => v != null && typeof v === "object" ? applyDefaults(fields, v, objectId) : v
|
|
227
|
-
);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
return out;
|
|
231
|
-
}
|
|
232
|
-
var ModelValidationError = class extends HttpError {
|
|
233
|
-
|
|
234
|
-
constructor(model, issues) {
|
|
235
|
-
super(
|
|
236
|
-
400,
|
|
237
|
-
`${model} validation failed: ${issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`
|
|
238
|
-
);
|
|
239
|
-
this.name = "ModelValidationError";
|
|
240
|
-
this.issues = issues;
|
|
241
|
-
}
|
|
242
|
-
};
|
|
243
|
-
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
244
|
-
var INT4 = 2 ** 31;
|
|
245
|
-
var INT8_MIN = -(2n ** 63n);
|
|
246
|
-
var INT8_MAX = 2n ** 63n - 1n;
|
|
247
|
-
var DECIMAL_RE = /^[+-]?(\d+(\.\d*)?|\.\d+)$/;
|
|
248
|
-
function decimalDigits(value) {
|
|
249
|
-
const str = typeof value === "number" ? String(value) : value;
|
|
250
|
-
const [i = "", f = ""] = str.replace(/^[+-]/, "").split(".");
|
|
251
|
-
return { int: i.replace(/^0+/, "").length, frac: f.replace(/0+$/, "").length };
|
|
252
|
-
}
|
|
253
|
-
function typeError(type, def, value) {
|
|
254
|
-
switch (type) {
|
|
255
|
-
case "string":
|
|
256
|
-
return typeof value === "string" ? null : "must be a string";
|
|
257
|
-
case "number":
|
|
258
|
-
return typeof value === "number" && Number.isFinite(value) ? null : "must be a number";
|
|
259
|
-
case "integer":
|
|
260
|
-
return typeof value === "number" && Number.isInteger(value) && value >= -INT4 && value < INT4 ? null : "must be a 32-bit integer";
|
|
261
|
-
case "bigint": {
|
|
262
|
-
const big = typeof value === "bigint" ? value : typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : void 0;
|
|
263
|
-
return big !== void 0 && big >= INT8_MIN && big <= INT8_MAX ? null : "must be a 64-bit integer (bigint)";
|
|
264
|
-
}
|
|
265
|
-
case "decimal": {
|
|
266
|
-
const ok = typeof value === "number" && Number.isFinite(value) || typeof value === "string" && DECIMAL_RE.test(value);
|
|
267
|
-
if (!ok) return "must be a decimal number or numeric string";
|
|
268
|
-
if (def.precision !== void 0) {
|
|
269
|
-
const scale = _nullishCoalesce(def.scale, () => ( 0));
|
|
270
|
-
const { int, frac } = decimalDigits(value);
|
|
271
|
-
if (frac > scale) return `must have at most ${scale} decimal places`;
|
|
272
|
-
if (int > def.precision - scale)
|
|
273
|
-
return `must have at most ${def.precision - scale} digits before the decimal point`;
|
|
274
|
-
}
|
|
275
|
-
return null;
|
|
276
|
-
}
|
|
277
|
-
case "boolean":
|
|
278
|
-
return typeof value === "boolean" ? null : "must be a boolean";
|
|
279
|
-
case "date":
|
|
280
|
-
return !Number.isNaN(new Date(value).getTime()) ? null : "must be a date";
|
|
281
|
-
case "objectId":
|
|
282
|
-
return typeof value === "string" && UUID_RE.test(value) ? null : "must be a valid id";
|
|
283
|
-
case "uuid":
|
|
284
|
-
return typeof value === "string" && UUID_RE.test(value) ? null : "must be a UUID";
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
function compareBound(def, value, bound) {
|
|
288
|
-
if (def.type === "bigint") {
|
|
289
|
-
const a = BigInt(value);
|
|
290
|
-
const b = BigInt(bound instanceof Date ? bound.getTime() : bound);
|
|
291
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
292
|
-
}
|
|
293
|
-
const num = (v) => v instanceof Date ? v.getTime() : def.type === "date" ? new Date(v).getTime() : Number(v);
|
|
294
|
-
return num(value) - num(bound);
|
|
295
|
-
}
|
|
296
|
-
async function checkRules(def, value, path, issues) {
|
|
297
|
-
if (def.enum && !def.enum.includes(value)) {
|
|
298
|
-
issues.push({ path, message: `must be one of: ${def.enum.join(", ")}` });
|
|
299
|
-
}
|
|
300
|
-
const ordered = typeof value === "number" || typeof value === "bigint" || value instanceof Date || def.type === "date" || def.type === "decimal" && typeof value === "string";
|
|
301
|
-
if (ordered) {
|
|
302
|
-
if (def.min !== void 0 && compareBound(def, value, def.min) < 0)
|
|
303
|
-
issues.push({ path, message: `must be >= ${String(def.min)}` });
|
|
304
|
-
if (def.max !== void 0 && compareBound(def, value, def.max) > 0)
|
|
305
|
-
issues.push({ path, message: `must be <= ${String(def.max)}` });
|
|
306
|
-
}
|
|
307
|
-
if (typeof value === "string" && def.type !== "decimal") {
|
|
308
|
-
if (def.minLength !== void 0 && value.length < def.minLength)
|
|
309
|
-
issues.push({ path, message: `must be at least ${def.minLength} characters` });
|
|
310
|
-
if (def.maxLength !== void 0 && value.length > def.maxLength)
|
|
311
|
-
issues.push({ path, message: `must be at most ${def.maxLength} characters` });
|
|
312
|
-
if (def.match && !def.match.test(value))
|
|
313
|
-
issues.push({ path, message: `must match ${String(def.match)}` });
|
|
314
|
-
}
|
|
315
|
-
if (def.validate) {
|
|
316
|
-
const result = await def.validate(value);
|
|
317
|
-
if (result !== true)
|
|
318
|
-
issues.push({ path, message: typeof result === "string" ? result : "is invalid" });
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
async function validateNode(node, value, path, issues, partial) {
|
|
322
|
-
if (value === void 0 || value === null) {
|
|
323
|
-
if (node.def.required && !partial) issues.push({ path, message: "is required" });
|
|
324
|
-
if (node.def.required && partial && value === null)
|
|
325
|
-
issues.push({ path, message: "is required" });
|
|
326
|
-
return;
|
|
327
|
-
}
|
|
328
|
-
switch (node.kind) {
|
|
329
|
-
case "scalar": {
|
|
330
|
-
const err = typeError(node.type, node.def, value);
|
|
331
|
-
if (err) {
|
|
332
|
-
issues.push({ path, message: err });
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
await checkRules(node.def, value, path, issues);
|
|
336
|
-
return;
|
|
337
|
-
}
|
|
338
|
-
case "json":
|
|
339
|
-
await checkRules(node.def, value, path, issues);
|
|
340
|
-
return;
|
|
341
|
-
case "object":
|
|
342
|
-
if (typeof value !== "object" || Array.isArray(value)) {
|
|
343
|
-
issues.push({ path, message: "must be an object" });
|
|
344
|
-
return;
|
|
345
|
-
}
|
|
346
|
-
await validateTree(node.fields, value, issues, false, path);
|
|
347
|
-
await checkRules(node.def, value, path, issues);
|
|
348
|
-
return;
|
|
349
|
-
case "array":
|
|
350
|
-
if (!Array.isArray(value)) {
|
|
351
|
-
issues.push({ path, message: "must be an array" });
|
|
352
|
-
return;
|
|
353
|
-
}
|
|
354
|
-
for (let i = 0; i < value.length; i++) {
|
|
355
|
-
await validateNode(
|
|
356
|
-
{ ...node.item, def: { ...node.item.def, required: true } },
|
|
357
|
-
value[i],
|
|
358
|
-
`${path}.${i}`,
|
|
359
|
-
issues,
|
|
360
|
-
false
|
|
361
|
-
);
|
|
362
|
-
}
|
|
363
|
-
await checkRules(node.def, value, path, issues);
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
async function validateTree(tree, data, issues, partial, prefix = "") {
|
|
367
|
-
for (const [key, node] of Object.entries(tree)) {
|
|
368
|
-
if (partial && !(key in data)) continue;
|
|
369
|
-
await validateNode(node, data[key], prefix ? `${prefix}.${key}` : key, issues, partial);
|
|
370
|
-
}
|
|
371
|
-
return issues;
|
|
372
|
-
}
|
|
373
|
-
function refFields(tree) {
|
|
374
|
-
const refs = /* @__PURE__ */ new Map();
|
|
375
|
-
for (const [key, node] of Object.entries(tree)) {
|
|
376
|
-
if (node.kind === "scalar" && node.type === "objectId" && node.def.ref) {
|
|
377
|
-
refs.set(key, { model: node.def.ref, many: false });
|
|
378
|
-
} else if (node.kind === "array" && node.item.kind === "scalar" && node.item.type === "objectId" && node.def.ref) {
|
|
379
|
-
refs.set(key, { model: node.def.ref, many: true });
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
return refs;
|
|
383
|
-
}
|
|
384
|
-
function sequenceFields(name, tree) {
|
|
385
|
-
const out = [];
|
|
386
|
-
for (const [path, node] of Object.entries(tree)) {
|
|
387
|
-
if (node.def.sequence) {
|
|
388
|
-
out.push({
|
|
389
|
-
path,
|
|
390
|
-
key: typeof node.def.sequence === "string" ? node.def.sequence : `${name}.${path}`
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
return out;
|
|
395
|
-
}
|
|
396
|
-
function nodeAt(tree, path) {
|
|
397
|
-
let node = tree[path[0]];
|
|
398
|
-
for (const part of path.slice(1)) {
|
|
399
|
-
if (!node) return void 0;
|
|
400
|
-
if (node.kind === "object") node = node.fields[part];
|
|
401
|
-
else if (node.kind === "array" && /^\d+$/.test(part)) node = node.item;
|
|
402
|
-
else if (node.kind === "json")
|
|
403
|
-
return node;
|
|
404
|
-
else return void 0;
|
|
405
|
-
}
|
|
406
|
-
return node;
|
|
407
|
-
}
|
|
408
|
-
async function validateAtPath(tree, dotted, value, issues) {
|
|
409
|
-
const node = nodeAt(tree, dotted.split("."));
|
|
410
|
-
if (!node) {
|
|
411
|
-
issues.push({ path: dotted, message: "unknown field" });
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
await validateNode(node, value, dotted, issues, true);
|
|
415
|
-
}
|
|
416
14
|
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
registry.set(model.name, model);
|
|
436
|
-
}
|
|
437
|
-
function getRegisteredModel(name) {
|
|
438
|
-
return registry.get(name);
|
|
439
|
-
}
|
|
440
|
-
function registeredModels() {
|
|
441
|
-
return [...registry.values()];
|
|
442
|
-
}
|
|
443
|
-
var txStorage = new (0, _async_hooks.AsyncLocalStorage)();
|
|
444
|
-
function currentTx() {
|
|
445
|
-
return txStorage.getStore();
|
|
446
|
-
}
|
|
447
|
-
function runInTx(handle, fn) {
|
|
448
|
-
return txStorage.run(handle, fn);
|
|
449
|
-
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
var _chunk66R7S7J3cjs = require('./chunk-66R7S7J3.cjs');
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
var _chunkVQSWSYK6cjs = require('./chunk-VQSWSYK6.cjs');
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
|
|
450
33
|
|
|
451
34
|
// src/db/mongo-model.ts
|
|
452
35
|
var mongoosePromise;
|
|
453
36
|
function loadMongoose() {
|
|
454
37
|
mongoosePromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("mongoose"))).then((mod) => _nullishCoalesce(mod.default, () => ( mod))).then((mg) => {
|
|
455
|
-
|
|
38
|
+
_chunkVQSWSYK6cjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkVQSWSYK6cjs.countStatement));
|
|
456
39
|
return mg;
|
|
457
40
|
}).catch((err) => {
|
|
458
41
|
mongoosePromise = void 0;
|
|
459
|
-
throw
|
|
42
|
+
throw _chunkVQSWSYK6cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
|
|
460
43
|
});
|
|
461
44
|
return mongoosePromise;
|
|
462
45
|
}
|
|
@@ -482,7 +65,7 @@ function rules(node, mg) {
|
|
|
482
65
|
if (d.unique !== void 0) entry["unique"] = d.unique;
|
|
483
66
|
if (d.index !== void 0) entry["index"] = d.index;
|
|
484
67
|
if (d.default !== void 0)
|
|
485
|
-
entry["default"] = resolveDefault(d.default, () => new mg.Types.ObjectId());
|
|
68
|
+
entry["default"] = _chunk66R7S7J3cjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
|
|
486
69
|
if (d.enum !== void 0) entry["enum"] = d.enum;
|
|
487
70
|
if (d.min !== void 0) entry["min"] = d.min;
|
|
488
71
|
if (d.max !== void 0) entry["max"] = d.max;
|
|
@@ -555,8 +138,8 @@ function normalise(value) {
|
|
|
555
138
|
}
|
|
556
139
|
function translateError(model, err) {
|
|
557
140
|
const e = err;
|
|
558
|
-
if (_optionalChain([e, 'optionalAccess',
|
|
559
|
-
throw new ModelValidationError(
|
|
141
|
+
if (_optionalChain([e, 'optionalAccess', _ => _.name]) === "ValidationError" && e.errors) {
|
|
142
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(
|
|
560
143
|
model,
|
|
561
144
|
Object.entries(e.errors).map(([path, v]) => ({
|
|
562
145
|
path,
|
|
@@ -567,20 +150,20 @@ function translateError(model, err) {
|
|
|
567
150
|
}))
|
|
568
151
|
);
|
|
569
152
|
}
|
|
570
|
-
if (_optionalChain([e, 'optionalAccess',
|
|
571
|
-
throw new ModelValidationError(model, [
|
|
153
|
+
if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "CastError") {
|
|
154
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(model, [
|
|
572
155
|
{ path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
|
|
573
156
|
]);
|
|
574
157
|
}
|
|
575
|
-
if (_optionalChain([e, 'optionalAccess',
|
|
158
|
+
if (_optionalChain([e, 'optionalAccess', _3 => _3.code]) === 11e3) {
|
|
576
159
|
const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
|
|
577
|
-
throw new HttpError(409, `${model} with this ${field} already exists`);
|
|
160
|
+
throw new (0, _chunk66R7S7J3cjs.HttpError)(409, `${model} with this ${field} already exists`);
|
|
578
161
|
}
|
|
579
162
|
throw err;
|
|
580
163
|
}
|
|
581
164
|
function isCastErrorOnId(err) {
|
|
582
165
|
const e = err;
|
|
583
|
-
return _optionalChain([e, 'optionalAccess',
|
|
166
|
+
return _optionalChain([e, 'optionalAccess', _4 => _4.name]) === "CastError" && e.path === "_id";
|
|
584
167
|
}
|
|
585
168
|
function mapFilter(filter) {
|
|
586
169
|
if (!filter) return {};
|
|
@@ -600,14 +183,14 @@ function mapSort(sort) {
|
|
|
600
183
|
}
|
|
601
184
|
function mongoModel(name, tree, options) {
|
|
602
185
|
let compiled;
|
|
603
|
-
const model = () => compiled ??=
|
|
186
|
+
const model = () => compiled ??= _chunkVQSWSYK6cjs.untracked.call(void 0,
|
|
604
187
|
() => loadMongoose().then(async (mg) => {
|
|
605
188
|
if (mg.models[name]) return mg.models[name];
|
|
606
189
|
const schema = new mg.Schema(buildTree(tree, mg), {
|
|
607
190
|
timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
|
|
608
191
|
// autoSync: false hands collection and index creation to migrations, on MongoDB too.
|
|
609
|
-
autoIndex: isAutoSync(),
|
|
610
|
-
autoCreate: isAutoSync(),
|
|
192
|
+
autoIndex: _chunk66R7S7J3cjs.isAutoSync.call(void 0, ),
|
|
193
|
+
autoCreate: _chunk66R7S7J3cjs.isAutoSync.call(void 0, ),
|
|
611
194
|
...options.collection !== void 0 && { collection: options.collection }
|
|
612
195
|
});
|
|
613
196
|
for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
|
|
@@ -619,7 +202,7 @@ function mongoModel(name, tree, options) {
|
|
|
619
202
|
...idx.name !== void 0 && { name: idx.name }
|
|
620
203
|
});
|
|
621
204
|
}
|
|
622
|
-
const sequences = sequenceFields(name, tree);
|
|
205
|
+
const sequences = _chunk66R7S7J3cjs.sequenceFields.call(void 0, name, tree);
|
|
623
206
|
if (sequences.length > 0) {
|
|
624
207
|
schema.pre("validate", async function() {
|
|
625
208
|
if (!this.isNew) return;
|
|
@@ -629,7 +212,7 @@ function mongoModel(name, tree, options) {
|
|
|
629
212
|
});
|
|
630
213
|
}
|
|
631
214
|
const M = mg.model(name, schema);
|
|
632
|
-
if (isAutoSync()) {
|
|
215
|
+
if (_chunk66R7S7J3cjs.isAutoSync.call(void 0, )) {
|
|
633
216
|
await M.init().catch((err) => {
|
|
634
217
|
_chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
|
|
635
218
|
{ model: name, err: err.message },
|
|
@@ -641,17 +224,17 @@ function mongoModel(name, tree, options) {
|
|
|
641
224
|
})
|
|
642
225
|
);
|
|
643
226
|
const session = () => {
|
|
644
|
-
const tx = currentTx();
|
|
645
|
-
return _optionalChain([tx, 'optionalAccess',
|
|
227
|
+
const tx = _chunk66R7S7J3cjs.currentTx.call(void 0, );
|
|
228
|
+
return _optionalChain([tx, 'optionalAccess', _5 => _5.engine]) === "mongodb" ? { session: tx.session } : {};
|
|
646
229
|
};
|
|
647
230
|
const applyQueryOptions = (q2, opts) => {
|
|
648
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
649
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
231
|
+
if (_optionalChain([opts, 'optionalAccess', _6 => _6.populate])) q2.populate(opts.populate);
|
|
232
|
+
if (_optionalChain([opts, 'optionalAccess', _7 => _7.select])) q2.select(opts.select.join(" "));
|
|
650
233
|
const f = opts;
|
|
651
|
-
const sort = mapSort(_optionalChain([f, 'optionalAccess',
|
|
234
|
+
const sort = mapSort(_optionalChain([f, 'optionalAccess', _8 => _8.sort]));
|
|
652
235
|
if (sort) q2.sort(sort);
|
|
653
|
-
if (_optionalChain([f, 'optionalAccess',
|
|
654
|
-
if (_optionalChain([f, 'optionalAccess',
|
|
236
|
+
if (_optionalChain([f, 'optionalAccess', _9 => _9.skip]) !== void 0) q2.skip(f.skip);
|
|
237
|
+
if (_optionalChain([f, 'optionalAccess', _10 => _10.limit]) !== void 0) q2.limit(f.limit);
|
|
655
238
|
return q2;
|
|
656
239
|
};
|
|
657
240
|
const guard = async (fn) => {
|
|
@@ -775,6 +358,7 @@ function mongoModel(name, tree, options) {
|
|
|
775
358
|
}),
|
|
776
359
|
raw: () => model(),
|
|
777
360
|
async sync(opts) {
|
|
361
|
+
if (_chunk66R7S7J3cjs.isSyncSuppressed.call(void 0, )) return [];
|
|
778
362
|
const M = await model();
|
|
779
363
|
const changes = [];
|
|
780
364
|
const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
|
|
@@ -782,15 +366,74 @@ function mongoModel(name, tree, options) {
|
|
|
782
366
|
const diff = await M.diffIndexes().catch(() => ({ toDrop: [], toCreate: [] }));
|
|
783
367
|
for (const idx of diff.toDrop) changes.push(`dropIndex ${String(idx)}`);
|
|
784
368
|
for (const idx of diff.toCreate) changes.push(`createIndex ${JSON.stringify(idx)}`);
|
|
785
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
369
|
+
if (_optionalChain([opts, 'optionalAccess', _11 => _11.dryRun])) return changes;
|
|
786
370
|
if (!exists) {
|
|
787
371
|
await M.createCollection().catch((err) => {
|
|
788
|
-
if (_optionalChain([err, 'optionalAccess',
|
|
372
|
+
if (_optionalChain([err, 'optionalAccess', _12 => _12.code]) !== 48) throw err;
|
|
789
373
|
});
|
|
790
374
|
}
|
|
791
375
|
await M.syncIndexes();
|
|
792
376
|
return changes;
|
|
793
377
|
},
|
|
378
|
+
// MongoDB has no columns: a migration creates the collection, builds and drops
|
|
379
|
+
// indexes, and moves `renamedFrom` fields in the stored documents.
|
|
380
|
+
async plan() {
|
|
381
|
+
const M = await model();
|
|
382
|
+
const col = M.collection.collectionName;
|
|
383
|
+
const J = (v) => JSON.stringify(v);
|
|
384
|
+
const on = `db.collection(${J(col)})`;
|
|
385
|
+
const steps = [];
|
|
386
|
+
const exists = (await M.db.db.listCollections({ name: col }).toArray()).length > 0;
|
|
387
|
+
if (!exists) {
|
|
388
|
+
steps.push({
|
|
389
|
+
phase: "main",
|
|
390
|
+
sql: `await db.createCollection(${J(col)}).catch((err) => { if (err?.code !== 48) throw err; });`,
|
|
391
|
+
down: `await db.dropCollection(${J(col)}).catch((err) => { if (err?.code !== 26) throw err; });`
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
const live = exists ? await M.collection.indexes() : [];
|
|
395
|
+
const diff = await M.diffIndexes().catch(() => ({ toDrop: [], toCreate: [] }));
|
|
396
|
+
for (const idx of diff.toDrop) {
|
|
397
|
+
const spec = live.find((i) => i.name === idx);
|
|
398
|
+
const { key, name: idxName, ...rest } = _nullishCoalesce(spec, () => ( {}));
|
|
399
|
+
delete rest["v"];
|
|
400
|
+
steps.push({
|
|
401
|
+
phase: "main",
|
|
402
|
+
sql: `await ${on}.dropIndex(${J(idx)}).catch((err) => { if (err?.code !== 27) throw err; });`,
|
|
403
|
+
...key !== void 0 && {
|
|
404
|
+
down: `await ${on}.createIndex(${J(key)}, ${J({ ...rest, name: idxName })});`
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
for (const [field, node] of Object.entries(tree)) {
|
|
409
|
+
const from = node.def.renamedFrom;
|
|
410
|
+
if (from === void 0) continue;
|
|
411
|
+
const move = (a, b) => `await ${on}.updateMany({ ${J(a)}: { $exists: true }, ${J(b)}: { $exists: false } }, { $rename: { ${J(a)}: ${J(b)} } });`;
|
|
412
|
+
steps.push({ phase: "main", sql: move(from, field), down: move(field, from) });
|
|
413
|
+
}
|
|
414
|
+
const declared = M.schema.indexes();
|
|
415
|
+
for (const keys of diff.toCreate) {
|
|
416
|
+
const found = declared.find(([k]) => J(k) === J(keys));
|
|
417
|
+
const opts = {};
|
|
418
|
+
for (const [k, v] of Object.entries(_nullishCoalesce(_optionalChain([found, 'optionalAccess', _13 => _13[1]]), () => ( {}))))
|
|
419
|
+
if ([
|
|
420
|
+
"unique",
|
|
421
|
+
"sparse",
|
|
422
|
+
"expireAfterSeconds",
|
|
423
|
+
"name",
|
|
424
|
+
"partialFilterExpression",
|
|
425
|
+
"weights"
|
|
426
|
+
].includes(k))
|
|
427
|
+
opts[k] = v;
|
|
428
|
+
const idxName = _nullishCoalesce(opts["name"], () => ( Object.entries(keys).map(([k, v]) => `${k}_${String(v)}`).join("_")));
|
|
429
|
+
steps.push({
|
|
430
|
+
phase: "main",
|
|
431
|
+
sql: `await ${on}.createIndex(${J(keys)}, ${J({ ...opts, name: idxName })});`,
|
|
432
|
+
down: `await ${on}.dropIndex(${J(idxName)}).catch(() => {});`
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
return steps;
|
|
436
|
+
},
|
|
794
437
|
async drop() {
|
|
795
438
|
const M = await model();
|
|
796
439
|
await M.collection.drop().catch((err) => {
|
|
@@ -801,819 +444,25 @@ function mongoModel(name, tree, options) {
|
|
|
801
444
|
}
|
|
802
445
|
|
|
803
446
|
// src/db/mongo.ts
|
|
804
|
-
async function connectMongo(url) {
|
|
447
|
+
async function connectMongo(url, pool = {}) {
|
|
805
448
|
const mg = await loadMongoose();
|
|
806
|
-
await mg.connect(url
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
var drizzlePromise;
|
|
814
|
-
function loadDrizzle() {
|
|
815
|
-
drizzlePromise ??= Promise.all([Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm"))), Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm/pg-core")))]).then(([orm, pgCore]) => ({ sql: orm.sql, pgCore })).catch(() => {
|
|
816
|
-
drizzlePromise = void 0;
|
|
817
|
-
throw new Error("[EFC] drizzle-orm is not installed. Run: npm install pg drizzle-orm");
|
|
818
|
-
});
|
|
819
|
-
return drizzlePromise;
|
|
820
|
-
}
|
|
821
|
-
function tableNameFor(model) {
|
|
822
|
-
const lower = model.toLowerCase();
|
|
823
|
-
if (/[^aeiou]y$/.test(lower)) return lower.slice(0, -1) + "ies";
|
|
824
|
-
if (/(s|x|z|ch|sh)$/.test(lower)) return lower + "es";
|
|
825
|
-
return lower + "s";
|
|
826
|
-
}
|
|
827
|
-
var snakeCase = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
|
|
828
|
-
var q = (ident) => `"${ident.replace(/"/g, '""')}"`;
|
|
829
|
-
var sequenceName = (key) => `efc_seq_${key.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase()}`;
|
|
830
|
-
var literal = (v) => typeof v === "number" ? String(v) : `'${v.replace(/'/g, "''")}'`;
|
|
831
|
-
var syncing = /* @__PURE__ */ new Map();
|
|
832
|
-
var ACTION_SQL = {
|
|
833
|
-
restrict: "RESTRICT",
|
|
834
|
-
cascade: "CASCADE",
|
|
835
|
-
setNull: "SET NULL"
|
|
836
|
-
};
|
|
837
|
-
var ACTION_CODE = {
|
|
838
|
-
restrict: "r",
|
|
839
|
-
cascade: "c",
|
|
840
|
-
setNull: "n"
|
|
841
|
-
};
|
|
842
|
-
var ID_COLUMN = {
|
|
843
|
-
uuid: { kind: "uuid", type: "uuid" },
|
|
844
|
-
serial: { kind: "integer", type: "integer" },
|
|
845
|
-
bigserial: { kind: "bigint", type: "bigint" }
|
|
846
|
-
};
|
|
847
|
-
var modelOfTable = (table) => _nullishCoalesce(_optionalChain([registeredModels, 'call', _15 => _15(), 'access', _16 => _16.find, 'call', _17 => _17((m) => {
|
|
848
|
-
try {
|
|
849
|
-
return _optionalChain([m, 'access', _18 => _18.pgTarget, 'optionalCall', _19 => _19(), 'access', _20 => _20.table]) === table;
|
|
850
|
-
} catch (e2) {
|
|
851
|
-
return false;
|
|
852
|
-
}
|
|
853
|
-
}), 'optionalAccess', _21 => _21.name]), () => ( table));
|
|
854
|
-
function scalarSpec(type, def, native) {
|
|
855
|
-
switch (type) {
|
|
856
|
-
case "string":
|
|
857
|
-
if (native && def.maxLength !== void 0) {
|
|
858
|
-
return {
|
|
859
|
-
kind: "varchar",
|
|
860
|
-
ddl: `varchar(${def.maxLength})`,
|
|
861
|
-
formatted: `character varying(${def.maxLength})`,
|
|
862
|
-
length: def.maxLength
|
|
863
|
-
};
|
|
864
|
-
}
|
|
865
|
-
return { kind: "text", ddl: "text", formatted: "text" };
|
|
866
|
-
case "number":
|
|
867
|
-
return { kind: "double", ddl: "double precision", formatted: "double precision" };
|
|
868
|
-
case "integer":
|
|
869
|
-
return { kind: "integer", ddl: "integer", formatted: "integer" };
|
|
870
|
-
case "bigint":
|
|
871
|
-
return { kind: "bigint", ddl: "bigint", formatted: "bigint", bigintAs: "bigint" };
|
|
872
|
-
case "decimal": {
|
|
873
|
-
if (def.precision === void 0)
|
|
874
|
-
return { kind: "numeric", ddl: "numeric", formatted: "numeric" };
|
|
875
|
-
const t = `numeric(${def.precision},${_nullishCoalesce(def.scale, () => ( 0))})`;
|
|
876
|
-
return {
|
|
877
|
-
kind: "numeric",
|
|
878
|
-
ddl: t,
|
|
879
|
-
formatted: t,
|
|
880
|
-
precision: def.precision,
|
|
881
|
-
scale: _nullishCoalesce(def.scale, () => ( 0))
|
|
882
|
-
};
|
|
449
|
+
await mg.connect(url, {
|
|
450
|
+
...pool.max !== void 0 && { maxPoolSize: pool.max },
|
|
451
|
+
...pool.idleTimeoutMs !== void 0 && { maxIdleTimeMS: pool.idleTimeoutMs },
|
|
452
|
+
...pool.connectionTimeoutMs !== void 0 && {
|
|
453
|
+
serverSelectionTimeoutMS: pool.connectionTimeoutMs,
|
|
454
|
+
waitQueueTimeoutMS: pool.connectionTimeoutMs
|
|
883
455
|
}
|
|
884
|
-
case "boolean":
|
|
885
|
-
return { kind: "boolean", ddl: "boolean", formatted: "boolean" };
|
|
886
|
-
case "date":
|
|
887
|
-
return { kind: "timestamptz", ddl: "timestamptz", formatted: "timestamp with time zone" };
|
|
888
|
-
case "objectId":
|
|
889
|
-
case "uuid":
|
|
890
|
-
return { kind: "uuid", ddl: "uuid", formatted: "uuid" };
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
function pgTable(name, tree, options, config) {
|
|
894
|
-
const snake = config.native && options.naming === "snake_case";
|
|
895
|
-
const table = _nullishCoalesce(options.collection, () => ( tableNameFor(snake ? snakeCase(name) : name)));
|
|
896
|
-
const columnName = (field, def) => _nullishCoalesce(_optionalChain([def, 'optionalAccess', _22 => _22.column]), () => ( (snake ? snakeCase(field) : field)));
|
|
897
|
-
const idKind = config.native && options.id || "uuid";
|
|
898
|
-
if (tree["id"]) throw new Error(`[EFC] ${name}: "id" is the primary key \u2014 don't declare it`);
|
|
899
|
-
const ts = timestampFields(options);
|
|
900
|
-
const sequences = sequenceFields(name, tree);
|
|
901
|
-
const sequenceKeys = new Map(sequences.map((s) => [s.path, s.key]));
|
|
902
|
-
const refs = refFields(tree);
|
|
903
|
-
const columns = /* @__PURE__ */ new Map();
|
|
904
|
-
const joins = /* @__PURE__ */ new Map();
|
|
905
|
-
const idSpec = idKind === "uuid" ? { field: "id", column: "id", kind: "uuid", ddl: "uuid", formatted: "uuid" } : idKind === "serial" ? { field: "id", column: "id", kind: "integer", ddl: "integer", formatted: "integer" } : {
|
|
906
|
-
field: "id",
|
|
907
|
-
column: "id",
|
|
908
|
-
kind: "bigint",
|
|
909
|
-
ddl: "bigint",
|
|
910
|
-
formatted: "bigint",
|
|
911
|
-
bigintAs: "bigint"
|
|
912
|
-
};
|
|
913
|
-
columns.set("id", idSpec);
|
|
914
|
-
for (const [field, node] of Object.entries(tree)) {
|
|
915
|
-
const column = columnName(field, node.def);
|
|
916
|
-
const base = { field, column, node };
|
|
917
|
-
if (sequenceKeys.has(field)) {
|
|
918
|
-
columns.set(field, {
|
|
919
|
-
...base,
|
|
920
|
-
kind: "bigint",
|
|
921
|
-
ddl: "bigint",
|
|
922
|
-
formatted: "bigint",
|
|
923
|
-
bigintAs: "number"
|
|
924
|
-
});
|
|
925
|
-
} else if (node.kind === "scalar") {
|
|
926
|
-
if (config.native && node.def.nativeEnum && node.def.enum) {
|
|
927
|
-
const enumType = `${table}_${column}_enum`;
|
|
928
|
-
columns.set(field, {
|
|
929
|
-
...base,
|
|
930
|
-
kind: "enum",
|
|
931
|
-
ddl: q(enumType),
|
|
932
|
-
formatted: /^[a-z_][a-z0-9_]*$/.test(enumType) ? enumType : q(enumType),
|
|
933
|
-
enumType,
|
|
934
|
-
enumValues: node.def.enum.map(String)
|
|
935
|
-
});
|
|
936
|
-
} else {
|
|
937
|
-
columns.set(field, { ...base, ...scalarSpec(node.type, node.def, config.native) });
|
|
938
|
-
}
|
|
939
|
-
} else if (config.native && node.kind === "array" && node.item.kind === "scalar" && node.def.ref !== void 0) {
|
|
940
|
-
const item = scalarSpec(node.item.type, node.item.def, false).kind;
|
|
941
|
-
joins.set(field, {
|
|
942
|
-
field,
|
|
943
|
-
table: `${table}_${column}`,
|
|
944
|
-
legacyColumn: column,
|
|
945
|
-
target: node.def.ref,
|
|
946
|
-
item,
|
|
947
|
-
ddl: `${item}[]`,
|
|
948
|
-
node
|
|
949
|
-
});
|
|
950
|
-
} else if (config.native && node.kind === "array" && node.item.kind === "scalar") {
|
|
951
|
-
const item = scalarSpec(node.item.type, node.item.def, false);
|
|
952
|
-
columns.set(field, {
|
|
953
|
-
...base,
|
|
954
|
-
...item,
|
|
955
|
-
kind: "array",
|
|
956
|
-
item: item.kind,
|
|
957
|
-
ddl: `${item.ddl}[]`,
|
|
958
|
-
formatted: `${item.formatted}[]`
|
|
959
|
-
});
|
|
960
|
-
} else {
|
|
961
|
-
columns.set(field, { ...base, kind: "jsonb", ddl: "jsonb", formatted: "jsonb" });
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
for (const field of [ts.createdAt, ts.updatedAt]) {
|
|
965
|
-
if (field) {
|
|
966
|
-
columns.set(field, {
|
|
967
|
-
field,
|
|
968
|
-
column: columnName(field),
|
|
969
|
-
kind: "timestamptz",
|
|
970
|
-
ddl: "timestamptz",
|
|
971
|
-
formatted: "timestamp with time zone"
|
|
972
|
-
});
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
const byColumn = new Map([...columns.values()].map((c) => [c.column, c]));
|
|
976
|
-
const builder = (pgCore, kind, spec) => {
|
|
977
|
-
const c = spec.column;
|
|
978
|
-
switch (kind) {
|
|
979
|
-
case "varchar":
|
|
980
|
-
return pgCore.varchar(c, { length: spec.length });
|
|
981
|
-
case "double":
|
|
982
|
-
return pgCore.doublePrecision(c);
|
|
983
|
-
case "integer":
|
|
984
|
-
return pgCore.integer(c);
|
|
985
|
-
case "bigint":
|
|
986
|
-
return pgCore.bigint(c, { mode: _nullishCoalesce(spec.bigintAs, () => ( "bigint")) });
|
|
987
|
-
case "numeric":
|
|
988
|
-
return pgCore.numeric(
|
|
989
|
-
c,
|
|
990
|
-
spec.precision !== void 0 ? { precision: spec.precision, scale: spec.scale } : {}
|
|
991
|
-
);
|
|
992
|
-
case "boolean":
|
|
993
|
-
return pgCore.boolean(c);
|
|
994
|
-
case "timestamptz":
|
|
995
|
-
return pgCore.timestamp(c, { withTimezone: true, mode: "date" });
|
|
996
|
-
case "uuid":
|
|
997
|
-
return pgCore.uuid(c);
|
|
998
|
-
default:
|
|
999
|
-
return pgCore.text(c);
|
|
1000
|
-
}
|
|
1001
|
-
};
|
|
1002
|
-
let compiled;
|
|
1003
|
-
const compile = () => compiled ??= loadDrizzle().then(({ sql, pgCore }) => {
|
|
1004
|
-
const cols = {};
|
|
1005
|
-
for (const [field, spec] of columns) {
|
|
1006
|
-
let c;
|
|
1007
|
-
if (spec.kind === "jsonb") c = pgCore.jsonb(spec.column);
|
|
1008
|
-
else if (spec.kind === "array") c = builder(pgCore, spec.item, spec).array();
|
|
1009
|
-
else c = builder(pgCore, spec.kind, spec);
|
|
1010
|
-
if (field === "id") {
|
|
1011
|
-
c = idKind === "uuid" ? c.primaryKey().defaultRandom() : c.primaryKey().generatedByDefaultAsIdentity();
|
|
1012
|
-
}
|
|
1013
|
-
cols[field] = c;
|
|
1014
|
-
}
|
|
1015
|
-
return { t: pgCore.pgTable(table, cols), sql };
|
|
1016
456
|
});
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
const result = await compile();
|
|
1020
|
-
if (isAutoSync()) {
|
|
1021
|
-
synced ??= reconcile(false).then(
|
|
1022
|
-
(changes) => {
|
|
1023
|
-
if (changes.length)
|
|
1024
|
-
_chunkYL37D6KMcjs.getLogger.call(void 0, ).info({ table, changes: changes.length }, `Synced table ${table}`);
|
|
1025
|
-
},
|
|
1026
|
-
(err) => {
|
|
1027
|
-
synced = void 0;
|
|
1028
|
-
throw err;
|
|
1029
|
-
}
|
|
1030
|
-
);
|
|
1031
|
-
await synced;
|
|
1032
|
-
}
|
|
1033
|
-
return result;
|
|
1034
|
-
};
|
|
1035
|
-
const client = () => {
|
|
1036
|
-
const tx = currentTx();
|
|
1037
|
-
return _optionalChain([tx, 'optionalAccess', _23 => _23.engine]) === "postgresql" ? tx.tx : _chunkMGH4VDV3cjs.getOrm.call(void 0, );
|
|
1038
|
-
};
|
|
1039
|
-
const columnFor = (t, field) => {
|
|
1040
|
-
if (!columns.has(field))
|
|
1041
|
-
throw new ModelValidationError(name, [{ path: field, message: "unknown field" }]);
|
|
1042
|
-
return t[field];
|
|
1043
|
-
};
|
|
1044
|
-
const scalarToDb = (kind, spec, v) => {
|
|
1045
|
-
if (v == null) return v;
|
|
1046
|
-
if (kind === "timestamptz") return v instanceof Date ? v : new Date(v);
|
|
1047
|
-
if (kind === "bigint")
|
|
1048
|
-
return spec.bigintAs === "number" ? Number(v) : BigInt(v);
|
|
1049
|
-
if (kind === "numeric") return String(v);
|
|
1050
|
-
return v;
|
|
1051
|
-
};
|
|
1052
|
-
const toDb = (field, value) => {
|
|
1053
|
-
const spec = columns.get(field);
|
|
1054
|
-
if (!spec || value == null) return value;
|
|
1055
|
-
if (spec.kind === "array") {
|
|
1056
|
-
return Array.isArray(value) ? value.map((v) => scalarToDb(spec.item, spec, v)) : value;
|
|
1057
|
-
}
|
|
1058
|
-
if (spec.kind === "jsonb") return value;
|
|
1059
|
-
return scalarToDb(spec.kind, spec, value);
|
|
1060
|
-
};
|
|
1061
|
-
const revive = (node, value) => {
|
|
1062
|
-
if (value == null) return value;
|
|
1063
|
-
if (node.kind === "scalar") {
|
|
1064
|
-
if (node.type === "date" && typeof value === "string") return new Date(value);
|
|
1065
|
-
return value;
|
|
1066
|
-
}
|
|
1067
|
-
if (node.kind === "array" && Array.isArray(value))
|
|
1068
|
-
return value.map((v) => revive(node.item, v));
|
|
1069
|
-
if (node.kind === "object" && typeof value === "object" && !Array.isArray(value)) {
|
|
1070
|
-
const out = { ...value };
|
|
1071
|
-
for (const [k, child] of Object.entries(node.fields)) {
|
|
1072
|
-
if (out[k] !== void 0) out[k] = revive(child, out[k]);
|
|
1073
|
-
}
|
|
1074
|
-
return out;
|
|
1075
|
-
}
|
|
1076
|
-
return value;
|
|
1077
|
-
};
|
|
1078
|
-
const hasNestedDate = (node) => node.kind === "scalar" ? node.type === "date" : node.kind === "array" ? hasNestedDate(node.item) : node.kind === "object" && Object.values(node.fields).some(hasNestedDate);
|
|
1079
|
-
const datedJson = [...columns.values()].filter(
|
|
1080
|
-
(c) => c.kind === "jsonb" && c.node && hasNestedDate(c.node)
|
|
1081
|
-
);
|
|
1082
|
-
const bigintCols = [...columns.values()].filter(
|
|
1083
|
-
(c) => c.kind === "bigint" && c.bigintAs === "bigint" || c.kind === "array" && c.item === "bigint"
|
|
1084
|
-
);
|
|
1085
|
-
const fromRow = (row) => {
|
|
1086
|
-
const out = {};
|
|
1087
|
-
for (const [k, v] of Object.entries(row)) if (v !== null) out[k] = v;
|
|
1088
|
-
for (const c of datedJson)
|
|
1089
|
-
if (out[c.field] !== void 0) out[c.field] = revive(c.node, out[c.field]);
|
|
1090
|
-
for (const c of bigintCols) {
|
|
1091
|
-
const v = out[c.field];
|
|
1092
|
-
if (typeof v === "string" || typeof v === "number") out[c.field] = BigInt(v);
|
|
1093
|
-
else if (Array.isArray(v)) out[c.field] = v.map((x) => x == null ? x : BigInt(x));
|
|
1094
|
-
}
|
|
1095
|
-
return out;
|
|
1096
|
-
};
|
|
1097
|
-
const fromRawRow = (row) => {
|
|
1098
|
-
const keyed = {};
|
|
1099
|
-
for (const [col, v] of Object.entries(row)) {
|
|
1100
|
-
const spec = byColumn.get(col);
|
|
1101
|
-
if (!spec) continue;
|
|
1102
|
-
keyed[spec.field] = v != null && spec.kind === "timestamptz" && !(v instanceof Date) ? new Date(v) : v;
|
|
1103
|
-
}
|
|
1104
|
-
return fromRow(keyed);
|
|
1105
|
-
};
|
|
1106
|
-
const validate = async (data, partial) => {
|
|
1107
|
-
const issues = [];
|
|
1108
|
-
const checkTree = {};
|
|
1109
|
-
for (const [k, node] of Object.entries(tree)) {
|
|
1110
|
-
checkTree[k] = sequenceKeys.has(k) ? { ...node, def: { ...node.def, required: false } } : node;
|
|
1111
|
-
}
|
|
1112
|
-
await validateTree(checkTree, data, issues, partial);
|
|
1113
|
-
if (issues.length) throw new ModelValidationError(name, issues);
|
|
1114
|
-
};
|
|
1115
|
-
const known = (data) => Object.fromEntries(
|
|
1116
|
-
Object.entries(data).filter(([k]) => {
|
|
1117
|
-
const top = k.split(".")[0];
|
|
1118
|
-
return columns.has(top) || joins.has(top);
|
|
1119
|
-
})
|
|
1120
|
-
);
|
|
1121
|
-
const prepareInsert = async (input) => {
|
|
1122
|
-
const { id, ...rest } = known(input);
|
|
1123
|
-
for (const f of [ts.createdAt, ts.updatedAt]) if (f) delete rest[f];
|
|
1124
|
-
const data = applyDefaults(tree, rest, _crypto.randomUUID);
|
|
1125
|
-
await validate(data, false);
|
|
1126
|
-
const now = /* @__PURE__ */ new Date();
|
|
1127
|
-
if (ts.createdAt) data[ts.createdAt] = now;
|
|
1128
|
-
if (ts.updatedAt) data[ts.updatedAt] = now;
|
|
1129
|
-
if (id !== void 0) data["id"] = id;
|
|
1130
|
-
for (const [k, v] of Object.entries(data)) data[k] = toDb(k, v);
|
|
1131
|
-
return data;
|
|
1132
|
-
};
|
|
1133
|
-
const fieldOfColumn = (column) => _nullishCoalesce(_optionalChain([byColumn, 'access', _24 => _24.get, 'call', _25 => _25(column), 'optionalAccess', _26 => _26.field]), () => ( column));
|
|
1134
|
-
const guard = async (fn) => {
|
|
1135
|
-
try {
|
|
1136
|
-
return await fn();
|
|
1137
|
-
} catch (err) {
|
|
1138
|
-
const e = _nullishCoalesce(err.cause, () => ( err));
|
|
1139
|
-
if (_optionalChain([e, 'optionalAccess', _27 => _27.code]) === "42P01") {
|
|
1140
|
-
throw new Error(
|
|
1141
|
-
`[EFC] ${name}: table "${table}" does not exist \u2014 autoSync is off, so create it with a migration (Model.sync() / efc db sync)`
|
|
1142
|
-
);
|
|
1143
|
-
}
|
|
1144
|
-
if (_optionalChain([e, 'optionalAccess', _28 => _28.code]) === "23505") {
|
|
1145
|
-
const cols = _nullishCoalesce(_optionalChain([/\(([^)]+)\)=/, 'access', _29 => _29.exec, 'call', _30 => _30(_nullishCoalesce(e.detail, () => ( ""))), 'optionalAccess', _31 => _31[1]]), () => ( "field"));
|
|
1146
|
-
const fields = cols.split(",").map((c) => fieldOfColumn(c.trim().replace(/"/g, ""))).join(", ");
|
|
1147
|
-
throw new HttpError(409, `${name} with this ${fields} already exists`);
|
|
1148
|
-
}
|
|
1149
|
-
if (_optionalChain([e, 'optionalAccess', _32 => _32.code]) === "23503" || _optionalChain([e, 'optionalAccess', _33 => _33.code]) === "23001") {
|
|
1150
|
-
const ref = /Key \(([^)]+)\)=\([^)]*\) is not present in table "([^"]+)"/.exec(
|
|
1151
|
-
_nullishCoalesce(e.detail, () => ( ""))
|
|
1152
|
-
);
|
|
1153
|
-
if (ref) {
|
|
1154
|
-
throw new ModelValidationError(name, [
|
|
1155
|
-
{
|
|
1156
|
-
// In a join table: the many-to-many field it backs.
|
|
1157
|
-
path: _nullishCoalesce(joinByTable.get(_nullishCoalesce(e.table, () => ( ""))), () => ( fieldOfColumn(ref[1].replace(/"/g, "")))),
|
|
1158
|
-
message: `${modelOfTable(ref[2])} not found`
|
|
1159
|
-
}
|
|
1160
|
-
]);
|
|
1161
|
-
}
|
|
1162
|
-
const by = _optionalChain([/is (?:still )?referenced from table "([^"]+)"/, 'access', _34 => _34.exec, 'call', _35 => _35(_nullishCoalesce(e.detail, () => ( ""))), 'optionalAccess', _36 => _36[1]]);
|
|
1163
|
-
throw new HttpError(
|
|
1164
|
-
409,
|
|
1165
|
-
`${name} is still referenced${by ? ` by ${modelOfTable(by)}` : ""} \u2014 delete or reassign those records first`
|
|
1166
|
-
);
|
|
1167
|
-
}
|
|
1168
|
-
if (_optionalChain([e, 'optionalAccess', _37 => _37.code]) === "23502")
|
|
1169
|
-
throw new ModelValidationError(name, [
|
|
1170
|
-
{ path: fieldOfColumn(_nullishCoalesce(e.column, () => ( ""))), message: "is required" }
|
|
1171
|
-
]);
|
|
1172
|
-
if (_optionalChain([e, 'optionalAccess', _38 => _38.code]) === "22P02" || _optionalChain([e, 'optionalAccess', _39 => _39.code]) === "22003" || _optionalChain([e, 'optionalAccess', _40 => _40.code]) === "23514")
|
|
1173
|
-
throw new ModelValidationError(name, [{ path: "", message: "invalid value" }]);
|
|
1174
|
-
throw err;
|
|
1175
|
-
}
|
|
1176
|
-
};
|
|
1177
|
-
const JSONB_TO_ARRAY = "efc_jsonb_text_array";
|
|
1178
|
-
const jsonbToArrayFn = `CREATE OR REPLACE FUNCTION ${JSONB_TO_ARRAY}(j jsonb) RETURNS text[] LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN j IS NULL OR jsonb_typeof(j) = 'null' THEN NULL WHEN jsonb_typeof(j) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(j)) ELSE ARRAY[j #>> '{}'] END $$`;
|
|
1179
|
-
const castExpr = (spec, from) => {
|
|
1180
|
-
const c = q(spec.column);
|
|
1181
|
-
if (spec.kind === "jsonb") return `to_jsonb(${c})`;
|
|
1182
|
-
if (spec.kind === "array") {
|
|
1183
|
-
if (from === "jsonb") return `${JSONB_TO_ARRAY}(${c})::${spec.ddl}`;
|
|
1184
|
-
if (from.endsWith("[]")) return `${c}::${spec.ddl}`;
|
|
1185
|
-
return `CASE WHEN ${c} IS NULL THEN NULL ELSE ARRAY[${c}::text]::${spec.ddl} END`;
|
|
1186
|
-
}
|
|
1187
|
-
const scalar = from === "jsonb" ? `(${c} #>> '{}')` : c;
|
|
1188
|
-
if (spec.kind === "enum") return `${scalar}::text::${spec.ddl}`;
|
|
1189
|
-
if (spec.kind === "bigint" || spec.kind === "integer") {
|
|
1190
|
-
return `round(${scalar}::numeric)::${spec.ddl}`;
|
|
1191
|
-
}
|
|
1192
|
-
return `${scalar}::${spec.ddl}`;
|
|
1193
|
-
};
|
|
1194
|
-
const needsTypeChange = (spec, existing) => {
|
|
1195
|
-
if (existing === spec.formatted) return false;
|
|
1196
|
-
if (spec.kind === "varchar") {
|
|
1197
|
-
if (existing === "text") return false;
|
|
1198
|
-
const m = /^character varying\((\d+)\)$/.exec(existing);
|
|
1199
|
-
if (m && Number(m[1]) >= spec.length) return false;
|
|
1200
|
-
}
|
|
1201
|
-
return true;
|
|
1202
|
-
};
|
|
1203
|
-
const enumCheck = (column) => `${table}_${column}_enum`;
|
|
1204
|
-
const fkName = (column) => `${table}_${column}_fkey`;
|
|
1205
|
-
const isForeignKey = (spec) => config.native && _optionalChain([spec, 'access', _41 => _41.node, 'optionalAccess', _42 => _42.kind]) === "scalar" && spec.node.def.ref !== void 0;
|
|
1206
|
-
function resolveTarget(field, targetName, kind, many) {
|
|
1207
|
-
const target = targetName === name ? { table, idKind } : _optionalChain([getRegisteredModel, 'call', _43 => _43(targetName), 'optionalAccess', _44 => _44.pgTarget, 'optionalCall', _45 => _45()]);
|
|
1208
|
-
if (!target) {
|
|
1209
|
-
throw new Error(
|
|
1210
|
-
`[EFC] ${name}.${field} references "${targetName}", which is not defined \u2014 import that model before using ${name}`
|
|
1211
|
-
);
|
|
1212
|
-
}
|
|
1213
|
-
const want = ID_COLUMN[target.idKind];
|
|
1214
|
-
if (kind !== want.kind) {
|
|
1215
|
-
const hint = many ? `{ type: 'array', of: '${want.type}', ref: '${targetName}' }` : `{ type: '${want.type}', ref: '${targetName}' }`;
|
|
1216
|
-
throw new Error(
|
|
1217
|
-
`[EFC] ${name}.${field} references ${targetName}, whose id is ${want.type} (id: '${target.idKind}') \u2014 declare it ${hint}`
|
|
1218
|
-
);
|
|
1219
|
-
}
|
|
1220
|
-
return target;
|
|
1221
|
-
}
|
|
1222
|
-
function foreignKeys() {
|
|
1223
|
-
const out = [];
|
|
1224
|
-
for (const spec of columns.values()) {
|
|
1225
|
-
if (!isForeignKey(spec)) continue;
|
|
1226
|
-
const def = spec.node.def;
|
|
1227
|
-
const target = resolveTarget(spec.field, def.ref, spec.kind, false);
|
|
1228
|
-
out.push({
|
|
1229
|
-
field: spec.field,
|
|
1230
|
-
onTable: table,
|
|
1231
|
-
column: spec.column,
|
|
1232
|
-
name: fkName(spec.column),
|
|
1233
|
-
target: def.ref,
|
|
1234
|
-
targetTable: target.table,
|
|
1235
|
-
action: _nullishCoalesce(def.onDelete, () => ( "restrict"))
|
|
1236
|
-
});
|
|
1237
|
-
}
|
|
1238
|
-
for (const join of joins.values()) {
|
|
1239
|
-
const target = resolveTarget(join.field, join.target, join.item, true);
|
|
1240
|
-
const base = { field: join.field, onTable: join.table, action: "cascade" };
|
|
1241
|
-
out.push(
|
|
1242
|
-
{
|
|
1243
|
-
...base,
|
|
1244
|
-
column: "owner_id",
|
|
1245
|
-
name: `${join.table}_owner_id_fkey`,
|
|
1246
|
-
target: name,
|
|
1247
|
-
targetTable: table
|
|
1248
|
-
},
|
|
1249
|
-
{
|
|
1250
|
-
...base,
|
|
1251
|
-
column: "ref_id",
|
|
1252
|
-
name: `${join.table}_ref_id_fkey`,
|
|
1253
|
-
target: join.target,
|
|
1254
|
-
targetTable: target.table
|
|
1255
|
-
}
|
|
1256
|
-
);
|
|
1257
|
-
}
|
|
1258
|
-
return out;
|
|
1259
|
-
}
|
|
1260
|
-
const joinByTable = new Map([...joins.values()].map((j) => [j.table, j.field]));
|
|
1261
|
-
const managedIndexName = /_(key|idx)$/;
|
|
1262
|
-
function desiredIndexes() {
|
|
1263
|
-
const out = /* @__PURE__ */ new Map();
|
|
1264
|
-
for (const spec of columns.values()) {
|
|
1265
|
-
const def = _optionalChain([spec, 'access', _46 => _46.node, 'optionalAccess', _47 => _47.def]);
|
|
1266
|
-
if (!def) continue;
|
|
1267
|
-
const col = spec.column;
|
|
1268
|
-
if (def.unique) {
|
|
1269
|
-
out.set(
|
|
1270
|
-
`${table}_${col}_key`,
|
|
1271
|
-
`CREATE UNIQUE INDEX ${q(`${table}_${col}_key`)} ON ${q(table)} (${q(col)})`
|
|
1272
|
-
);
|
|
1273
|
-
} else if (def.index || isForeignKey(spec) && def.index !== false) {
|
|
1274
|
-
out.set(
|
|
1275
|
-
`${table}_${col}_idx`,
|
|
1276
|
-
`CREATE INDEX ${q(`${table}_${col}_idx`)} ON ${q(table)} (${q(col)})`
|
|
1277
|
-
);
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
|
|
1281
|
-
const fields = Object.entries(idx.fields).map(
|
|
1282
|
-
([f, d]) => [_nullishCoalesce(_optionalChain([columns, 'access', _48 => _48.get, 'call', _49 => _49(f), 'optionalAccess', _50 => _50.column]), () => ( f)), d]
|
|
1283
|
-
);
|
|
1284
|
-
if (idx.expireAfterSeconds !== void 0) {
|
|
1285
|
-
throw new Error(`[EFC] ${name}: TTL indexes (expireAfterSeconds) are MongoDB-only`);
|
|
1286
|
-
}
|
|
1287
|
-
const idxName = _nullishCoalesce(idx.name, () => ( `${table}_${fields.map(([f]) => f).join("_")}_${idx.unique ? "key" : "idx"}`));
|
|
1288
|
-
if (fields.some(([, d]) => d === "text")) {
|
|
1289
|
-
const doc = fields.map(([f]) => `coalesce(${q(f)}::text, '')`).join(` || ' ' || `);
|
|
1290
|
-
out.set(
|
|
1291
|
-
idxName,
|
|
1292
|
-
`CREATE INDEX ${q(idxName)} ON ${q(table)} USING gin (to_tsvector('simple', ${doc}))`
|
|
1293
|
-
);
|
|
1294
|
-
} else {
|
|
1295
|
-
const cols = fields.map(([f, d]) => `${q(f)} ${d === -1 ? "DESC" : "ASC"}`).join(", ");
|
|
1296
|
-
out.set(
|
|
1297
|
-
idxName,
|
|
1298
|
-
`CREATE ${idx.unique ? "UNIQUE " : ""}INDEX ${q(idxName)} ON ${q(table)} (${cols})`
|
|
1299
|
-
);
|
|
1300
|
-
}
|
|
1301
|
-
}
|
|
1302
|
-
return out;
|
|
1303
|
-
}
|
|
1304
|
-
const tableExists = async (t) => (await _chunkMGH4VDV3cjs.getPool.call(void 0, ).query(
|
|
1305
|
-
`SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1306
|
-
WHERE c.relname = $1 AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
|
|
1307
|
-
[t]
|
|
1308
|
-
)).rowCount > 0;
|
|
1309
|
-
async function reconcile(dryRun) {
|
|
1310
|
-
const fks = foreignKeys();
|
|
1311
|
-
if (dryRun) return reconcileTable(true, fks, /* @__PURE__ */ new Set());
|
|
1312
|
-
let release;
|
|
1313
|
-
const mine = new Promise((resolve) => release = resolve);
|
|
1314
|
-
const prev = syncing.get(table);
|
|
1315
|
-
syncing.set(table, mine);
|
|
1316
|
-
try {
|
|
1317
|
-
const deferred = /* @__PURE__ */ new Set();
|
|
1318
|
-
const tx = currentTx();
|
|
1319
|
-
if (_optionalChain([tx, 'optionalAccess', _51 => _51.engine]) === "postgresql" && fks.length) {
|
|
1320
|
-
for (const fk of fks) deferred.add(fk.name);
|
|
1321
|
-
tx.afterCommit.push(() => {
|
|
1322
|
-
reconcile(false).catch(
|
|
1323
|
-
(err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
|
|
1324
|
-
);
|
|
1325
|
-
});
|
|
1326
|
-
}
|
|
1327
|
-
for (const fk of fks) {
|
|
1328
|
-
if (deferred.has(fk.name)) continue;
|
|
1329
|
-
if (fk.targetTable === table || await tableExists(fk.targetTable)) continue;
|
|
1330
|
-
const running = syncing.get(fk.targetTable);
|
|
1331
|
-
if (running) {
|
|
1332
|
-
deferred.add(fk.name);
|
|
1333
|
-
void running.then(() => reconcile(false)).catch(
|
|
1334
|
-
(err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
|
|
1335
|
-
);
|
|
1336
|
-
} else {
|
|
1337
|
-
await getRegisteredModel(fk.target).sync();
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
return await reconcileTable(false, fks, deferred);
|
|
1341
|
-
} finally {
|
|
1342
|
-
release();
|
|
1343
|
-
if (syncing.get(table) === mine) {
|
|
1344
|
-
if (prev) syncing.set(table, prev);
|
|
1345
|
-
else syncing.delete(table);
|
|
1346
|
-
}
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
async function reconcileTable(dryRun, fks, deferred) {
|
|
1350
|
-
const pool = _chunkMGH4VDV3cjs.getPool.call(void 0, );
|
|
1351
|
-
const conn = await pool.connect();
|
|
1352
|
-
try {
|
|
1353
|
-
await conn.query("BEGIN");
|
|
1354
|
-
await conn.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`efc_sync:${table}`]);
|
|
1355
|
-
const existing = new Map(
|
|
1356
|
-
(await conn.query(
|
|
1357
|
-
`SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable
|
|
1358
|
-
FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1359
|
-
WHERE c.relname = $1 AND n.nspname = current_schema() AND a.attnum > 0 AND NOT a.attisdropped`,
|
|
1360
|
-
[table]
|
|
1361
|
-
)).rows.map((r) => [r.name, { type: r.type, nullable: r.nullable }])
|
|
1362
|
-
);
|
|
1363
|
-
const checks = new Map(
|
|
1364
|
-
(await conn.query(
|
|
1365
|
-
`SELECT con.conname AS name, pg_get_constraintdef(con.oid) AS def
|
|
1366
|
-
FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1367
|
-
WHERE c.relname = $1 AND n.nspname = current_schema() AND con.contype = 'c'`,
|
|
1368
|
-
[table]
|
|
1369
|
-
)).rows.map((r) => [r.name, r.def])
|
|
1370
|
-
);
|
|
1371
|
-
const indexes = new Set(
|
|
1372
|
-
(await conn.query(
|
|
1373
|
-
`SELECT indexname AS name FROM pg_indexes WHERE tablename = $1 AND schemaname = current_schema()`,
|
|
1374
|
-
[table]
|
|
1375
|
-
)).rows.map((r) => r.name)
|
|
1376
|
-
);
|
|
1377
|
-
const liveFks = new Map(
|
|
1378
|
-
(await conn.query(
|
|
1379
|
-
`SELECT con.conname AS name, ft.relname AS target, con.confdeltype AS action, con.convalidated AS valid
|
|
1380
|
-
FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1381
|
-
JOIN pg_class ft ON ft.oid = con.confrelid
|
|
1382
|
-
WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND con.contype = 'f'`,
|
|
1383
|
-
[[table, ...joinByTable.keys()]]
|
|
1384
|
-
)).rows.map((r) => [r.name, r])
|
|
1385
|
-
);
|
|
1386
|
-
const liveJoinTables = new Set(
|
|
1387
|
-
(await conn.query(
|
|
1388
|
-
`SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1389
|
-
WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
|
|
1390
|
-
[[...joinByTable.keys()]]
|
|
1391
|
-
)).rows.map((r) => r.name)
|
|
1392
|
-
);
|
|
1393
|
-
const plan = [];
|
|
1394
|
-
const wantedFks = new Map(fks.map((fk) => [fk.name, fk]));
|
|
1395
|
-
for (const [con, live] of liveFks) {
|
|
1396
|
-
const want = wantedFks.get(con);
|
|
1397
|
-
const ours = [...joinByTable.keys()].some((jt) => con.startsWith(`${jt}_`)) || [...columns.values()].some((c) => c.field !== "id" && fkName(c.column) === con);
|
|
1398
|
-
if (ours && (!want || live.target !== want.targetTable || live.action !== ACTION_CODE[want.action])) {
|
|
1399
|
-
const on = _nullishCoalesce([...joinByTable.keys()].find((jt) => con.startsWith(`${jt}_`)), () => ( table));
|
|
1400
|
-
plan.push(`ALTER TABLE ${q(on)} DROP CONSTRAINT ${q(con)}`);
|
|
1401
|
-
liveFks.delete(con);
|
|
1402
|
-
}
|
|
1403
|
-
}
|
|
1404
|
-
for (const { key } of sequences) {
|
|
1405
|
-
const seq = sequenceName(key);
|
|
1406
|
-
const found = await conn.query(
|
|
1407
|
-
"SELECT 1 FROM pg_class WHERE relkind = $1 AND relname = $2",
|
|
1408
|
-
["S", seq]
|
|
1409
|
-
);
|
|
1410
|
-
if (found.rowCount === 0) plan.push(`CREATE SEQUENCE IF NOT EXISTS ${q(seq)}`);
|
|
1411
|
-
}
|
|
1412
|
-
const enumSpecs = [...columns.values()].filter((c) => c.kind === "enum");
|
|
1413
|
-
if (enumSpecs.length) {
|
|
1414
|
-
const live = /* @__PURE__ */ new Map();
|
|
1415
|
-
for (const r of (await conn.query(
|
|
1416
|
-
`SELECT t.typname AS type, e.enumlabel AS label FROM pg_type t
|
|
1417
|
-
JOIN pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_enum e ON e.enumtypid = t.oid
|
|
1418
|
-
WHERE n.nspname = current_schema() AND t.typname = ANY($1)`,
|
|
1419
|
-
[enumSpecs.map((c) => c.enumType)]
|
|
1420
|
-
)).rows) {
|
|
1421
|
-
const set = _nullishCoalesce(live.get(r.type), () => ( /* @__PURE__ */ new Set()));
|
|
1422
|
-
if (r.label !== null) set.add(r.label);
|
|
1423
|
-
live.set(r.type, set);
|
|
1424
|
-
}
|
|
1425
|
-
for (const spec of enumSpecs) {
|
|
1426
|
-
const have = live.get(spec.enumType);
|
|
1427
|
-
if (!have) {
|
|
1428
|
-
plan.push(
|
|
1429
|
-
`CREATE TYPE ${spec.ddl} AS ENUM (${spec.enumValues.map(literal).join(", ")})`
|
|
1430
|
-
);
|
|
1431
|
-
} else {
|
|
1432
|
-
for (const v of spec.enumValues) {
|
|
1433
|
-
if (!have.has(v))
|
|
1434
|
-
plan.push(`ALTER TYPE ${spec.ddl} ADD VALUE IF NOT EXISTS ${literal(v)}`);
|
|
1435
|
-
}
|
|
1436
|
-
}
|
|
1437
|
-
}
|
|
1438
|
-
}
|
|
1439
|
-
const columnSql = (spec) => {
|
|
1440
|
-
const seq = sequenceKeys.get(spec.field);
|
|
1441
|
-
return `${q(spec.column)} ${spec.ddl}${seq ? ` DEFAULT nextval('${sequenceName(seq)}')` : ""}`;
|
|
1442
|
-
};
|
|
1443
|
-
const idSql = idKind === "uuid" ? `${q("id")} uuid PRIMARY KEY DEFAULT gen_random_uuid()` : `${q("id")} ${idSpec.ddl} GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`;
|
|
1444
|
-
if (existing.size === 0) {
|
|
1445
|
-
const defs = [...columns.values()].map(
|
|
1446
|
-
(spec) => spec.field === "id" ? idSql : columnSql(spec)
|
|
1447
|
-
);
|
|
1448
|
-
plan.push(`CREATE TABLE IF NOT EXISTS ${q(table)} (
|
|
1449
|
-
${defs.join(",\n ")}
|
|
1450
|
-
)`);
|
|
1451
|
-
} else {
|
|
1452
|
-
const alters = [];
|
|
1453
|
-
for (const spec of columns.values()) {
|
|
1454
|
-
const col = existing.get(spec.column);
|
|
1455
|
-
if (!col) {
|
|
1456
|
-
alters.push(`ALTER TABLE ${q(table)} ADD COLUMN ${columnSql(spec)}`);
|
|
1457
|
-
} else if (spec.field !== "id" && needsTypeChange(spec, col.type)) {
|
|
1458
|
-
if (spec.kind === "array" && col.type === "jsonb" && !plan.includes(jsonbToArrayFn))
|
|
1459
|
-
plan.push(jsonbToArrayFn);
|
|
1460
|
-
alters.push(
|
|
1461
|
-
`ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${spec.ddl} USING ${castExpr(spec, col.type)}`
|
|
1462
|
-
);
|
|
1463
|
-
}
|
|
1464
|
-
}
|
|
1465
|
-
plan.push(...new Set(alters));
|
|
1466
|
-
for (const [column, col] of existing) {
|
|
1467
|
-
if (column !== "id" && !col.nullable) {
|
|
1468
|
-
plan.push(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} DROP NOT NULL`);
|
|
1469
|
-
}
|
|
1470
|
-
}
|
|
1471
|
-
}
|
|
1472
|
-
const wantedChecks = /* @__PURE__ */ new Map();
|
|
1473
|
-
for (const spec of columns.values()) {
|
|
1474
|
-
const def = _optionalChain([spec, 'access', _52 => _52.node, 'optionalAccess', _53 => _53.def]);
|
|
1475
|
-
if (_optionalChain([spec, 'access', _54 => _54.node, 'optionalAccess', _55 => _55.kind]) === "scalar" && _optionalChain([def, 'optionalAccess', _56 => _56.enum]) && spec.kind !== "enum") {
|
|
1476
|
-
wantedChecks.set(
|
|
1477
|
-
enumCheck(spec.column),
|
|
1478
|
-
`CHECK (${q(spec.column)} IN (${def.enum.map(literal).join(", ")}))`
|
|
1479
|
-
);
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
for (const [con, def] of checks) {
|
|
1483
|
-
const legacy = con.endsWith("_check") && con.startsWith(`${table}_`);
|
|
1484
|
-
if (con.endsWith("_enum") && con.startsWith(`${table}_`) && !wantedChecks.has(con) || legacy) {
|
|
1485
|
-
plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
|
|
1486
|
-
checks.delete(con);
|
|
1487
|
-
} else if (wantedChecks.has(con)) {
|
|
1488
|
-
const want = wantedChecks.get(con);
|
|
1489
|
-
const values = (d) => [...d.matchAll(/'((?:[^']|'')*)'|(-?\d+(?:\.\d+)?)/g)].map((m) => _nullishCoalesce(m[1], () => ( m[2]))).sort().join("|");
|
|
1490
|
-
if (values(def) !== values(want)) {
|
|
1491
|
-
plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
|
|
1492
|
-
checks.delete(con);
|
|
1493
|
-
}
|
|
1494
|
-
}
|
|
1495
|
-
}
|
|
1496
|
-
for (const [con, def] of wantedChecks) {
|
|
1497
|
-
if (!checks.has(con))
|
|
1498
|
-
plan.push(`ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def} NOT VALID`);
|
|
1499
|
-
}
|
|
1500
|
-
const wantedIndexes = desiredIndexes();
|
|
1501
|
-
for (const idx of indexes) {
|
|
1502
|
-
if (idx !== `${table}_pkey` && idx.startsWith(`${table}_`) && managedIndexName.test(idx) && !wantedIndexes.has(idx)) {
|
|
1503
|
-
plan.push(`DROP INDEX ${q(idx)}`);
|
|
1504
|
-
}
|
|
1505
|
-
}
|
|
1506
|
-
for (const [idx, create] of wantedIndexes) if (!indexes.has(idx)) plan.push(create);
|
|
1507
|
-
const ownerDdl = idSpec.ddl;
|
|
1508
|
-
for (const join of joins.values()) {
|
|
1509
|
-
if (liveJoinTables.has(join.table)) continue;
|
|
1510
|
-
const refDdl = join.item;
|
|
1511
|
-
plan.push(
|
|
1512
|
-
`CREATE TABLE IF NOT EXISTS ${q(join.table)} (
|
|
1513
|
-
${q("owner_id")} ${ownerDdl} NOT NULL,
|
|
1514
|
-
${q("ref_id")} ${refDdl} NOT NULL,
|
|
1515
|
-
${q("position")} integer NOT NULL DEFAULT 0,
|
|
1516
|
-
PRIMARY KEY (${q("owner_id")}, ${q("ref_id")})
|
|
1517
|
-
)`,
|
|
1518
|
-
`CREATE INDEX IF NOT EXISTS ${q(`${join.table}_ref_id_idx`)} ON ${q(join.table)} (${q("ref_id")})`
|
|
1519
|
-
);
|
|
1520
|
-
const legacy = _optionalChain([existing, 'access', _57 => _57.get, 'call', _58 => _58(join.legacyColumn), 'optionalAccess', _59 => _59.type]);
|
|
1521
|
-
if (legacy === "jsonb" || _optionalChain([legacy, 'optionalAccess', _60 => _60.endsWith, 'call', _61 => _61("[]")])) {
|
|
1522
|
-
const c = `o.${q(join.legacyColumn)}`;
|
|
1523
|
-
const items = legacy === "jsonb" ? `jsonb_array_elements_text(CASE WHEN jsonb_typeof(${c}) = 'array' THEN ${c} ELSE '[]'::jsonb END)` : `unnest(${c}::text[])`;
|
|
1524
|
-
const valid = join.item === "uuid" ? `'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'` : `'^-?[0-9]{1,18}$'`;
|
|
1525
|
-
plan.push(
|
|
1526
|
-
`INSERT INTO ${q(join.table)} (${q("owner_id")}, ${q("ref_id")}, ${q("position")}) SELECT o.${q("id")}, x.v::${refDdl}, x.n FROM ${q(table)} o, ${items} WITH ORDINALITY AS x(v, n) WHERE x.v ~ ${valid} ON CONFLICT DO NOTHING`
|
|
1527
|
-
);
|
|
1528
|
-
}
|
|
1529
|
-
}
|
|
1530
|
-
const toValidate = [];
|
|
1531
|
-
for (const fk of fks) {
|
|
1532
|
-
if (deferred.has(fk.name)) continue;
|
|
1533
|
-
const live = liveFks.get(fk.name);
|
|
1534
|
-
if (!live) {
|
|
1535
|
-
plan.push(
|
|
1536
|
-
`ALTER TABLE ${q(fk.onTable)} ADD CONSTRAINT ${q(fk.name)} FOREIGN KEY (${q(fk.column)}) REFERENCES ${q(fk.targetTable)} (${q("id")}) ON DELETE ${ACTION_SQL[fk.action]} NOT VALID`
|
|
1537
|
-
);
|
|
1538
|
-
}
|
|
1539
|
-
if (!_optionalChain([live, 'optionalAccess', _62 => _62.valid])) toValidate.push(fk);
|
|
1540
|
-
}
|
|
1541
|
-
const validations = toValidate.map(
|
|
1542
|
-
(fk) => `ALTER TABLE ${q(fk.onTable)} VALIDATE CONSTRAINT ${q(fk.name)}`
|
|
1543
|
-
);
|
|
1544
|
-
if (!dryRun) {
|
|
1545
|
-
for (const stmt of plan) {
|
|
1546
|
-
try {
|
|
1547
|
-
await conn.query(stmt);
|
|
1548
|
-
} catch (err) {
|
|
1549
|
-
throw new Error(
|
|
1550
|
-
`[EFC] ${name}: syncing table "${table}" failed on: ${stmt}
|
|
1551
|
-
${err.message}`
|
|
1552
|
-
);
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
}
|
|
1556
|
-
await conn.query(dryRun ? "ROLLBACK" : "COMMIT");
|
|
1557
|
-
if (!dryRun) {
|
|
1558
|
-
for (const [i, fk] of toValidate.entries()) {
|
|
1559
|
-
try {
|
|
1560
|
-
await conn.query(validations[i]);
|
|
1561
|
-
} catch (e3) {
|
|
1562
|
-
const orphans = await conn.query(
|
|
1563
|
-
`SELECT count(*) AS n FROM ${q(fk.onTable)} r WHERE ${q(fk.column)} IS NOT NULL
|
|
1564
|
-
AND NOT EXISTS (SELECT 1 FROM ${q(fk.targetTable)} t WHERE t.${q("id")} = r.${q(fk.column)})`
|
|
1565
|
-
).then((r) => _nullishCoalesce(_optionalChain([r, 'access', _63 => _63.rows, 'access', _64 => _64[0], 'optionalAccess', _65 => _65.n]), () => ( "?"))).catch(() => "?");
|
|
1566
|
-
_chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
|
|
1567
|
-
{ table, constraint: fk.name, orphans: Number(orphans) },
|
|
1568
|
-
`${name}.${fk.field}: ${orphans} row(s) reference a missing ${fk.target} \u2014 the foreign key applies to new writes; fix those rows, then run efc db sync to validate it`
|
|
1569
|
-
);
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
}
|
|
1573
|
-
return [...plan, ...validations];
|
|
1574
|
-
} catch (err) {
|
|
1575
|
-
await conn.query("ROLLBACK").catch(() => {
|
|
1576
|
-
});
|
|
1577
|
-
throw err;
|
|
1578
|
-
} finally {
|
|
1579
|
-
conn.release();
|
|
1580
|
-
}
|
|
1581
|
-
}
|
|
1582
|
-
async function drop() {
|
|
1583
|
-
const { sql } = await compile();
|
|
1584
|
-
await client().execute(sql.raw(`DROP TABLE IF EXISTS ${q(table)}`));
|
|
1585
|
-
}
|
|
1586
|
-
return {
|
|
1587
|
-
name,
|
|
1588
|
-
table,
|
|
1589
|
-
tree,
|
|
1590
|
-
idKind,
|
|
1591
|
-
columns,
|
|
1592
|
-
joins,
|
|
1593
|
-
ts,
|
|
1594
|
-
sequenceKeys,
|
|
1595
|
-
refs,
|
|
1596
|
-
compile,
|
|
1597
|
-
ready,
|
|
1598
|
-
client,
|
|
1599
|
-
columnFor,
|
|
1600
|
-
toDb,
|
|
1601
|
-
fromRow,
|
|
1602
|
-
fromRawRow,
|
|
1603
|
-
validate,
|
|
1604
|
-
known,
|
|
1605
|
-
prepareInsert,
|
|
1606
|
-
guard,
|
|
1607
|
-
reconcile,
|
|
1608
|
-
drop
|
|
1609
|
-
};
|
|
457
|
+
_chunkYL37D6KMcjs.getLogger.call(void 0, ).info("MongoDB connected");
|
|
458
|
+
return mg.connection;
|
|
1610
459
|
}
|
|
1611
460
|
|
|
1612
461
|
// src/db/pg-model.ts
|
|
1613
462
|
function pgModel(name, tree, options) {
|
|
1614
|
-
const tbl = pgTable(name, tree, options, { native: false, api: "defineModel" });
|
|
463
|
+
const tbl = _chunk66R7S7J3cjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
|
|
1615
464
|
const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
|
|
1616
|
-
const kindOf = (field) => _optionalChain([columns, 'access',
|
|
465
|
+
const kindOf = (field) => _optionalChain([columns, 'access', _15 => _15.get, 'call', _16 => _16(field), 'optionalAccess', _17 => _17.kind]);
|
|
1617
466
|
function missingField(sql, cond) {
|
|
1618
467
|
const ops = cond !== null && typeof cond === "object" && !Array.isArray(cond) && !(cond instanceof Date) && !(cond instanceof RegExp) ? cond : { $eq: cond };
|
|
1619
468
|
const matches = Object.entries(ops).every(([op, v]) => {
|
|
@@ -1711,7 +560,7 @@ function pgModel(name, tree, options) {
|
|
|
1711
560
|
break;
|
|
1712
561
|
}
|
|
1713
562
|
default:
|
|
1714
|
-
throw new ModelValidationError(name, [
|
|
563
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [
|
|
1715
564
|
{ path, message: `operator ${op} is not supported on PostgreSQL` }
|
|
1716
565
|
]);
|
|
1717
566
|
}
|
|
@@ -1742,8 +591,8 @@ function pgModel(name, tree, options) {
|
|
|
1742
591
|
for (const path of Array.isArray(paths) ? paths : [paths]) {
|
|
1743
592
|
const ref = refs.get(path);
|
|
1744
593
|
if (!ref)
|
|
1745
|
-
throw new ModelValidationError(name, [{ path, message: "is not a populatable ref field" }]);
|
|
1746
|
-
const target = getRegisteredModel(ref.model);
|
|
594
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
|
|
595
|
+
const target = _chunk66R7S7J3cjs.getRegisteredModel.call(void 0, ref.model);
|
|
1747
596
|
if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
|
|
1748
597
|
const ids = [
|
|
1749
598
|
...new Set(
|
|
@@ -1769,24 +618,24 @@ function pgModel(name, tree, options) {
|
|
|
1769
618
|
};
|
|
1770
619
|
async function runFind(filter, opts) {
|
|
1771
620
|
const { t, sql } = await ready();
|
|
1772
|
-
const sel = selection(t, _optionalChain([opts, 'optionalAccess',
|
|
621
|
+
const sel = selection(t, _optionalChain([opts, 'optionalAccess', _18 => _18.select]));
|
|
1773
622
|
let query = (sel ? client().select(sel) : client().select()).from(t);
|
|
1774
623
|
const w = where(sql, t, filter);
|
|
1775
624
|
if (w) query = query.where(w);
|
|
1776
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
625
|
+
if (_optionalChain([opts, 'optionalAccess', _19 => _19.sort])) {
|
|
1777
626
|
const order = Object.entries(opts.sort).filter(([f]) => columns.has(f)).map(([f, dir]) => {
|
|
1778
627
|
const col = columnFor(t, f);
|
|
1779
628
|
return dir === -1 || dir === "desc" ? sql`${col} desc nulls last` : sql`${col} asc nulls first`;
|
|
1780
629
|
});
|
|
1781
630
|
if (order.length) query = query.orderBy(...order);
|
|
1782
631
|
}
|
|
1783
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
1784
|
-
if (_optionalChain([opts, 'optionalAccess',
|
|
632
|
+
if (_optionalChain([opts, 'optionalAccess', _20 => _20.limit]) !== void 0) query = query.limit(opts.limit);
|
|
633
|
+
if (_optionalChain([opts, 'optionalAccess', _21 => _21.skip]) !== void 0) query = query.offset(opts.skip);
|
|
1785
634
|
const rows = (await query).map(fromRow);
|
|
1786
|
-
return populate(rows, _optionalChain([opts, 'optionalAccess',
|
|
635
|
+
return populate(rows, _optionalChain([opts, 'optionalAccess', _22 => _22.populate]));
|
|
1787
636
|
}
|
|
1788
637
|
const strictUpdate = (update) => {
|
|
1789
|
-
const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || nodeAt(tree, path.split(".")) !== void 0);
|
|
638
|
+
const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunk66R7S7J3cjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
|
|
1790
639
|
const out = {};
|
|
1791
640
|
for (const [k, v] of Object.entries(update)) {
|
|
1792
641
|
if (k.startsWith("$") && v !== null && typeof v === "object") {
|
|
@@ -1801,7 +650,7 @@ function pgModel(name, tree, options) {
|
|
|
1801
650
|
const ops = update;
|
|
1802
651
|
for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
|
|
1803
652
|
if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
|
|
1804
|
-
throw new ModelValidationError(name, [
|
|
653
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [
|
|
1805
654
|
{ path: op, message: "update operator is not supported on PostgreSQL" }
|
|
1806
655
|
]);
|
|
1807
656
|
}
|
|
@@ -1814,25 +663,25 @@ function pgModel(name, tree, options) {
|
|
|
1814
663
|
for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
|
|
1815
664
|
for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
|
|
1816
665
|
for (const [k, v] of Object.entries($set))
|
|
1817
|
-
if (k.includes(".")) await validateAtPath(tree, k, v, issues);
|
|
666
|
+
if (k.includes(".")) await _chunk66R7S7J3cjs.validateAtPath.call(void 0, tree, k, v, issues);
|
|
1818
667
|
for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
|
|
1819
|
-
if (k.includes(".")) await validateAtPath(tree, k, null, issues);
|
|
668
|
+
if (k.includes(".")) await _chunk66R7S7J3cjs.validateAtPath.call(void 0, tree, k, null, issues);
|
|
1820
669
|
}
|
|
1821
670
|
for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
|
|
1822
671
|
if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
|
|
1823
|
-
const node = k.includes(".") ? nodeAt(tree, k.split(".")) : tree[k];
|
|
672
|
+
const node = k.includes(".") ? _chunk66R7S7J3cjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
|
|
1824
673
|
if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
|
|
1825
674
|
issues.push({ path: k, message: "$inc only applies to number fields" });
|
|
1826
675
|
}
|
|
1827
676
|
}
|
|
1828
|
-
if (issues.length) throw new ModelValidationError(name, issues);
|
|
677
|
+
if (issues.length) throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, issues);
|
|
1829
678
|
await validate(topLevel, true);
|
|
1830
679
|
const set = {};
|
|
1831
680
|
const nested = /* @__PURE__ */ new Map();
|
|
1832
681
|
const touchedTop = /* @__PURE__ */ new Set();
|
|
1833
682
|
const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
|
|
1834
683
|
const conflict = (path) => {
|
|
1835
|
-
throw new ModelValidationError(name, [{ path, message: "conflicting update paths" }]);
|
|
684
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
|
|
1836
685
|
};
|
|
1837
686
|
const top = (field, value) => {
|
|
1838
687
|
if (touchedTop.has(field) || nested.has(field)) conflict(field);
|
|
@@ -1892,11 +741,11 @@ function pgModel(name, tree, options) {
|
|
|
1892
741
|
if (ts.updatedAt) set[ts.updatedAt] = /* @__PURE__ */ new Date();
|
|
1893
742
|
return set;
|
|
1894
743
|
}
|
|
1895
|
-
const
|
|
744
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1896
745
|
return {
|
|
1897
746
|
find: (filter, opts) => guard(async () => await runFind(filter, opts)),
|
|
1898
747
|
findById: (id, opts) => guard(async () => {
|
|
1899
|
-
if (!
|
|
748
|
+
if (!UUID_RE.test(id)) return null;
|
|
1900
749
|
return await _asyncNullishCoalesce((await runFind({ id }, { ...opts, limit: 1 }))[0], async () => ( null));
|
|
1901
750
|
}),
|
|
1902
751
|
findOne: (filter, opts) => guard(
|
|
@@ -1932,7 +781,7 @@ function pgModel(name, tree, options) {
|
|
|
1932
781
|
);
|
|
1933
782
|
}),
|
|
1934
783
|
update: (id, data) => guard(async () => {
|
|
1935
|
-
if (!
|
|
784
|
+
if (!UUID_RE.test(id)) return null;
|
|
1936
785
|
const { t, sql } = await ready();
|
|
1937
786
|
const set = await buildSet(data);
|
|
1938
787
|
const [row] = await client().update(t).set(set).where(sql`${t.id} = ${id}`).returning();
|
|
@@ -1956,7 +805,7 @@ function pgModel(name, tree, options) {
|
|
|
1956
805
|
return (await query.returning({ id: t.id })).length;
|
|
1957
806
|
}),
|
|
1958
807
|
delete: (id) => guard(async () => {
|
|
1959
|
-
if (!
|
|
808
|
+
if (!UUID_RE.test(id)) return;
|
|
1960
809
|
const { t, sql } = await ready();
|
|
1961
810
|
await client().delete(t).where(sql`${t.id} = ${id}`);
|
|
1962
811
|
}),
|
|
@@ -1978,7 +827,7 @@ function pgModel(name, tree, options) {
|
|
|
1978
827
|
const w = where(sql, t, filter);
|
|
1979
828
|
if (w) query = query.where(w);
|
|
1980
829
|
const [row] = await query;
|
|
1981
|
-
return _nullishCoalesce(_optionalChain([row, 'optionalAccess',
|
|
830
|
+
return _nullishCoalesce(_optionalChain([row, 'optionalAccess', _23 => _23.n]), () => ( 0));
|
|
1982
831
|
}),
|
|
1983
832
|
aggregate() {
|
|
1984
833
|
return Promise.reject(
|
|
@@ -1988,7 +837,8 @@ function pgModel(name, tree, options) {
|
|
|
1988
837
|
);
|
|
1989
838
|
},
|
|
1990
839
|
raw: async () => (await compile()).t,
|
|
1991
|
-
sync: (opts) => tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess',
|
|
840
|
+
sync: (opts) => tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _24 => _24.dryRun]), () => ( false))),
|
|
841
|
+
plan: (opts) => tbl.plan(opts),
|
|
1992
842
|
drop: () => tbl.drop()
|
|
1993
843
|
};
|
|
1994
844
|
}
|
|
@@ -2002,7 +852,7 @@ function defineModel(name, schema, options) {
|
|
|
2002
852
|
return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
|
|
2003
853
|
}
|
|
2004
854
|
function distinctFields(tree, options) {
|
|
2005
|
-
const ts = timestampFields(options);
|
|
855
|
+
const ts = _chunk66R7S7J3cjs.timestampFields.call(void 0, options);
|
|
2006
856
|
const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
|
|
2007
857
|
for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
|
|
2008
858
|
return fields;
|
|
@@ -2027,17 +877,17 @@ var MODEL_OPS = [
|
|
|
2027
877
|
];
|
|
2028
878
|
var sortKey = (v) => v instanceof Date ? v.getTime() : v;
|
|
2029
879
|
function createModel(name, schema, options, native) {
|
|
2030
|
-
const tree = normalizeSchema(schema, "model", name);
|
|
880
|
+
const tree = _chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "model", name);
|
|
2031
881
|
let engineModel;
|
|
2032
882
|
const impl = () => {
|
|
2033
883
|
if (engineModel) return engineModel;
|
|
2034
|
-
const
|
|
2035
|
-
if (native && native.engine !==
|
|
884
|
+
const engine = _chunk66R7S7J3cjs.getDbEngine.call(void 0, );
|
|
885
|
+
if (native && native.engine !== engine) {
|
|
2036
886
|
throw new Error(
|
|
2037
|
-
`[EFC] ${name} is a ${ENGINE_LABEL[native.engine]} ${native.kind} (${native.api}) but the app is connected to ${ENGINE_LABEL[
|
|
887
|
+
`[EFC] ${name} is a ${ENGINE_LABEL[native.engine]} ${native.kind} (${native.api}) but the app is connected to ${ENGINE_LABEL[engine]} \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
|
|
2038
888
|
);
|
|
2039
889
|
}
|
|
2040
|
-
engineModel =
|
|
890
|
+
engineModel = engine === "postgresql" ? pgModel(name, tree, options) : mongoModel(name, tree, options);
|
|
2041
891
|
return engineModel;
|
|
2042
892
|
};
|
|
2043
893
|
const call = (fn) => Promise.resolve().then(() => fn(impl()));
|
|
@@ -2073,7 +923,7 @@ function createModel(name, schema, options, native) {
|
|
|
2073
923
|
try {
|
|
2074
924
|
return await m.create(create);
|
|
2075
925
|
} catch (err) {
|
|
2076
|
-
if (isHttpError(err) && err.statusCode === 409 && !currentTx()) {
|
|
926
|
+
if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunk66R7S7J3cjs.currentTx.call(void 0, )) {
|
|
2077
927
|
const retried = await m.updateOne(filter, update);
|
|
2078
928
|
if (retried) return retried;
|
|
2079
929
|
}
|
|
@@ -2089,25 +939,26 @@ function createModel(name, schema, options, native) {
|
|
|
2089
939
|
sync: (opts) => call((m) => m.sync(opts)),
|
|
2090
940
|
drop: () => call((m) => m.drop())
|
|
2091
941
|
};
|
|
2092
|
-
|
|
2093
|
-
registerModel({
|
|
942
|
+
_chunkVQSWSYK6cjs.traceOps.call(void 0, name, model, MODEL_OPS);
|
|
943
|
+
_chunk66R7S7J3cjs.registerModel.call(void 0, {
|
|
2094
944
|
name,
|
|
2095
945
|
sync: model.sync,
|
|
946
|
+
plan: (opts) => call((m) => m.plan(opts)),
|
|
2096
947
|
drop: model.drop,
|
|
2097
948
|
findByIds: (ids) => model.find({ id: { $in: ids } }),
|
|
2098
|
-
pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( tableNameFor(name))), idKind: "uuid" })
|
|
949
|
+
pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunk66R7S7J3cjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
|
|
2099
950
|
});
|
|
2100
951
|
return model;
|
|
2101
952
|
}
|
|
2102
953
|
|
|
2103
954
|
// src/db/transaction.ts
|
|
2104
955
|
async function transaction(fn) {
|
|
2105
|
-
if (currentTx()) return fn();
|
|
2106
|
-
if (getDbEngine() === "postgresql") {
|
|
956
|
+
if (_chunk66R7S7J3cjs.currentTx.call(void 0, )) return fn();
|
|
957
|
+
if (_chunk66R7S7J3cjs.getDbEngine.call(void 0, ) === "postgresql") {
|
|
2107
958
|
let result;
|
|
2108
959
|
const afterCommit = [];
|
|
2109
|
-
await
|
|
2110
|
-
result = await runInTx({ engine: "postgresql", tx, afterCommit }, fn);
|
|
960
|
+
await _chunkVQSWSYK6cjs.getOrm.call(void 0, ).transaction(async (tx) => {
|
|
961
|
+
result = await _chunk66R7S7J3cjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
|
|
2111
962
|
});
|
|
2112
963
|
for (const run of afterCommit) run();
|
|
2113
964
|
return result;
|
|
@@ -2117,7 +968,7 @@ async function transaction(fn) {
|
|
|
2117
968
|
try {
|
|
2118
969
|
let result;
|
|
2119
970
|
await session.withTransaction(async () => {
|
|
2120
|
-
result = await runInTx({ engine: "mongodb", session }, fn);
|
|
971
|
+
result = await _chunk66R7S7J3cjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
|
|
2121
972
|
});
|
|
2122
973
|
return result;
|
|
2123
974
|
} finally {
|
|
@@ -2126,7 +977,7 @@ async function transaction(fn) {
|
|
|
2126
977
|
}
|
|
2127
978
|
|
|
2128
979
|
// src/db/table-model.ts
|
|
2129
|
-
|
|
980
|
+
var _crypto = require('crypto');
|
|
2130
981
|
var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
|
|
2131
982
|
var NUMERIC_KINDS = /* @__PURE__ */ new Set(["double", "integer", "bigint", "numeric"]);
|
|
2132
983
|
var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof RegExp) && typeof v !== "bigint";
|
|
@@ -2147,7 +998,7 @@ var BACK_ONE_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "
|
|
|
2147
998
|
var BACK_MANY_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "set", "delete", "deleteMany"]);
|
|
2148
999
|
var idJson = (_k, v) => typeof v === "bigint" ? String(v) : v;
|
|
2149
1000
|
var aliasSeq = 0;
|
|
2150
|
-
var
|
|
1001
|
+
var literal = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
2151
1002
|
var JSON_PAIRS_PER_CALL = 50;
|
|
2152
1003
|
var idText = (v) => v == null ? v : String(v);
|
|
2153
1004
|
var dedupe = (items) => {
|
|
@@ -2163,11 +1014,11 @@ var TableRuntime = (_class = class {
|
|
|
2163
1014
|
constructor(name, schema, options) {;_class.prototype.__init.call(this);
|
|
2164
1015
|
this.name = name;
|
|
2165
1016
|
this.options = options;
|
|
2166
|
-
const tree = normalizeSchema(schema, "table", name);
|
|
2167
|
-
this.tbl = pgTable(name, tree, options, { native: true, api: "defineTable" });
|
|
1017
|
+
const tree = _chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "table", name);
|
|
1018
|
+
this.tbl = _chunk66R7S7J3cjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
|
|
2168
1019
|
this.uniqueSets = [["id"]];
|
|
2169
1020
|
for (const spec of this.tbl.columns.values()) {
|
|
2170
|
-
if (_optionalChain([spec, 'access',
|
|
1021
|
+
if (_optionalChain([spec, 'access', _25 => _25.node, 'optionalAccess', _26 => _26.def, 'access', _27 => _27.unique])) this.uniqueSets.push([spec.field]);
|
|
2171
1022
|
}
|
|
2172
1023
|
for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
|
|
2173
1024
|
if (idx.unique) this.uniqueSets.push(Object.keys(idx.fields));
|
|
@@ -2191,7 +1042,7 @@ var TableRuntime = (_class = class {
|
|
|
2191
1042
|
/** Many-to-many fields as list columns, so filters and projections treat them alike. */
|
|
2192
1043
|
__init() {this.joinSpecs = /* @__PURE__ */ new Map()}
|
|
2193
1044
|
fail(path, message) {
|
|
2194
|
-
throw new ModelValidationError(this.name, [{ path, message }]);
|
|
1045
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [{ path, message }]);
|
|
2195
1046
|
}
|
|
2196
1047
|
spec(field) {
|
|
2197
1048
|
return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
|
|
@@ -2202,18 +1053,18 @@ var TableRuntime = (_class = class {
|
|
|
2202
1053
|
/** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
|
|
2203
1054
|
joinExpr(sql, join, owner) {
|
|
2204
1055
|
return sql.raw(
|
|
2205
|
-
`coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${q(join.table)} efc_j where efc_j.owner_id = ${owner}.${q("id")}), '{}'::${join.ddl})`
|
|
1056
|
+
`coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunk66R7S7J3cjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
|
|
2206
1057
|
);
|
|
2207
1058
|
}
|
|
2208
1059
|
col(sql, field, alias) {
|
|
2209
1060
|
const join = this.join(field);
|
|
2210
|
-
if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( q(this.tbl.table))));
|
|
1061
|
+
if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))));
|
|
2211
1062
|
const spec = this.spec(field);
|
|
2212
|
-
return sql.raw(alias ? `${alias}.${q(spec.column)}` : q(spec.column));
|
|
1063
|
+
return sql.raw(alias ? `${alias}.${_chunk66R7S7J3cjs.q.call(void 0, spec.column)}` : _chunk66R7S7J3cjs.q.call(void 0, spec.column));
|
|
2213
1064
|
}
|
|
2214
1065
|
/** SELECT items for the many-to-many fields among `fields`, as text arrays. */
|
|
2215
1066
|
joinColumns(sql, fields, owner) {
|
|
2216
|
-
return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(q(relAlias(f)))}`);
|
|
1067
|
+
return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, relAlias(f)))}`);
|
|
2217
1068
|
}
|
|
2218
1069
|
/** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
|
|
2219
1070
|
selectCols(sql, fields, owner) {
|
|
@@ -2487,7 +1338,7 @@ var TableRuntime = (_class = class {
|
|
|
2487
1338
|
}
|
|
2488
1339
|
/** Checks `where` names a unique key (id, a unique field, or a compound unique index). */
|
|
2489
1340
|
uniqueKey(where, op) {
|
|
2490
|
-
const plain = (f) => _optionalChain([where, 'optionalAccess',
|
|
1341
|
+
const plain = (f) => _optionalChain([where, 'optionalAccess', _28 => _28[f]]) !== void 0 && where[f] !== null && !isPlainObject(where[f]);
|
|
2491
1342
|
const key = this.uniqueSets.find((set) => set.every(plain));
|
|
2492
1343
|
if (!key) {
|
|
2493
1344
|
this.fail(
|
|
@@ -2505,7 +1356,7 @@ var TableRuntime = (_class = class {
|
|
|
2505
1356
|
if (args["cursor"]) {
|
|
2506
1357
|
this.uniqueKey(args["cursor"], "cursor");
|
|
2507
1358
|
const cw = this.where(sql, t, args["cursor"]);
|
|
2508
|
-
const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(q(this.tbl.table))} where ${cw})`;
|
|
1359
|
+
const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${cw})`;
|
|
2509
1360
|
const ors = [];
|
|
2510
1361
|
const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
|
|
2511
1362
|
for (let i = 0; i < order.length; i++) {
|
|
@@ -2518,7 +1369,7 @@ var TableRuntime = (_class = class {
|
|
|
2518
1369
|
ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
|
|
2519
1370
|
}
|
|
2520
1371
|
ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
|
|
2521
|
-
parts.push(sql`exists (select 1 from ${sql.raw(q(this.tbl.table))} where ${cw})`);
|
|
1372
|
+
parts.push(sql`exists (select 1 from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${cw})`);
|
|
2522
1373
|
parts.push(sql`(${sql.join(ors, sql` or `)})`);
|
|
2523
1374
|
}
|
|
2524
1375
|
return parts.length ? sql.join(parts, sql` and `) : sql`true`;
|
|
@@ -2543,9 +1394,9 @@ var TableRuntime = (_class = class {
|
|
|
2543
1394
|
const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
|
|
2544
1395
|
const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
|
|
2545
1396
|
const where = this.readWhere(sql, t, args, order);
|
|
2546
|
-
const from = sql.raw(q(this.tbl.table));
|
|
2547
|
-
const distinct = _optionalChain([args, 'access',
|
|
2548
|
-
if (_optionalChain([distinct, 'optionalAccess',
|
|
1397
|
+
const from = sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table));
|
|
1398
|
+
const distinct = _optionalChain([args, 'access', _29 => _29["distinct"], 'optionalAccess', _30 => _30.filter, 'call', _31 => _31((f) => this.spec(f))]);
|
|
1399
|
+
if (_optionalChain([distinct, 'optionalAccess', _32 => _32.length])) {
|
|
2549
1400
|
const dcols = sql.join(
|
|
2550
1401
|
distinct.map((f) => this.col(sql, f)),
|
|
2551
1402
|
sql`, `
|
|
@@ -2566,14 +1417,14 @@ var TableRuntime = (_class = class {
|
|
|
2566
1417
|
const { t, sql } = await this.ready(args["where"], args["cursor"]);
|
|
2567
1418
|
return this.tbl.guard(async () => {
|
|
2568
1419
|
const fields = this.projection(args);
|
|
2569
|
-
const distinct = _optionalChain([args, 'access',
|
|
1420
|
+
const distinct = _optionalChain([args, 'access', _33 => _33["distinct"], 'optionalAccess', _34 => _34.some, 'call', _35 => _35((f) => this.spec(f))]);
|
|
2570
1421
|
const cols = this.selectCols(
|
|
2571
1422
|
sql,
|
|
2572
1423
|
[.../* @__PURE__ */ new Set(["id", ...fields])],
|
|
2573
1424
|
distinct ? "efc_distinct" : void 0
|
|
2574
1425
|
);
|
|
2575
1426
|
const include = this.includeArg(args);
|
|
2576
|
-
const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : q(this.tbl.table), 1) : [];
|
|
1427
|
+
const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table), 1) : [];
|
|
2577
1428
|
const { query, reversed } = this.readQuery(
|
|
2578
1429
|
sql,
|
|
2579
1430
|
t,
|
|
@@ -2595,7 +1446,7 @@ var TableRuntime = (_class = class {
|
|
|
2595
1446
|
if (this.relationCache) return this.relationCache;
|
|
2596
1447
|
const out = /* @__PURE__ */ new Map();
|
|
2597
1448
|
for (const spec of this.tbl.columns.values()) {
|
|
2598
|
-
const ref = _optionalChain([spec, 'access',
|
|
1449
|
+
const ref = _optionalChain([spec, 'access', _36 => _36.node, 'optionalAccess', _37 => _37.kind]) === "scalar" ? spec.node.def.ref : void 0;
|
|
2599
1450
|
if (ref)
|
|
2600
1451
|
out.set(spec.field, {
|
|
2601
1452
|
name: spec.field,
|
|
@@ -2648,7 +1499,7 @@ var TableRuntime = (_class = class {
|
|
|
2648
1499
|
for (const [name, arg] of Object.entries(include)) {
|
|
2649
1500
|
if (!arg) continue;
|
|
2650
1501
|
const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
|
|
2651
|
-
out.push(sql`${expr} as ${sql.raw(q(incAlias(name)))}`);
|
|
1502
|
+
out.push(sql`${expr} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, incAlias(name)))}`);
|
|
2652
1503
|
}
|
|
2653
1504
|
return out;
|
|
2654
1505
|
}
|
|
@@ -2682,27 +1533,27 @@ var TableRuntime = (_class = class {
|
|
|
2682
1533
|
*/
|
|
2683
1534
|
relationSource(rel, owner, a, j) {
|
|
2684
1535
|
const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
|
|
2685
|
-
const target = `${q(T.tbl.table)} ${a}`;
|
|
2686
|
-
const ownerId = `${owner}.${q("id")}`;
|
|
1536
|
+
const target = `${_chunk66R7S7J3cjs.q.call(void 0, T.tbl.table)} ${a}`;
|
|
1537
|
+
const ownerId = `${owner}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`;
|
|
2687
1538
|
if (rel.via === "fk") {
|
|
2688
1539
|
return {
|
|
2689
1540
|
T,
|
|
2690
1541
|
from: target,
|
|
2691
|
-
cond: `${a}.${q("id")} = ${owner}.${q(rel.column)}`,
|
|
2692
|
-
defaultOrder: `${a}.${q("id")}`
|
|
1542
|
+
cond: `${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${owner}.${_chunk66R7S7J3cjs.q.call(void 0, rel.column)}`,
|
|
1543
|
+
defaultOrder: `${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`
|
|
2693
1544
|
};
|
|
2694
1545
|
}
|
|
2695
1546
|
let from;
|
|
2696
1547
|
let cond;
|
|
2697
1548
|
let defaultOrder;
|
|
2698
1549
|
if (rel.via === "join") {
|
|
2699
|
-
from = `${q(rel.join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.ref_id`;
|
|
1550
|
+
from = `${_chunk66R7S7J3cjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${j}.ref_id`;
|
|
2700
1551
|
cond = `${j}.owner_id = ${ownerId}`;
|
|
2701
1552
|
defaultOrder = `${j}.position`;
|
|
2702
1553
|
} else {
|
|
2703
1554
|
const join = T.tbl.joins.get(rel.foreignKey);
|
|
2704
1555
|
const column = T.tbl.columns.get(rel.foreignKey);
|
|
2705
|
-
const refs = join ? join.target : _optionalChain([column, 'optionalAccess',
|
|
1556
|
+
const refs = join ? join.target : _optionalChain([column, 'optionalAccess', _38 => _38.node, 'optionalAccess', _39 => _39.kind]) === "scalar" && column.node.def.ref;
|
|
2706
1557
|
if (refs !== this.name) {
|
|
2707
1558
|
throw new Error(
|
|
2708
1559
|
`[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} must be a ref to ${this.name}`
|
|
@@ -2714,7 +1565,7 @@ var TableRuntime = (_class = class {
|
|
|
2714
1565
|
`[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
|
|
2715
1566
|
);
|
|
2716
1567
|
}
|
|
2717
|
-
from = `${q(join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.owner_id`;
|
|
1568
|
+
from = `${_chunk66R7S7J3cjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${j}.owner_id`;
|
|
2718
1569
|
cond = `${j}.ref_id = ${ownerId}`;
|
|
2719
1570
|
} else {
|
|
2720
1571
|
if (rel.kind === "one" && !column.node.def.unique) {
|
|
@@ -2723,9 +1574,9 @@ var TableRuntime = (_class = class {
|
|
|
2723
1574
|
);
|
|
2724
1575
|
}
|
|
2725
1576
|
from = target;
|
|
2726
|
-
cond = `${a}.${q(column.column)} = ${ownerId}`;
|
|
1577
|
+
cond = `${a}.${_chunk66R7S7J3cjs.q.call(void 0, column.column)} = ${ownerId}`;
|
|
2727
1578
|
}
|
|
2728
|
-
defaultOrder = `${a}.${q("id")}`;
|
|
1579
|
+
defaultOrder = `${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`;
|
|
2729
1580
|
}
|
|
2730
1581
|
return { T, from, cond, defaultOrder };
|
|
2731
1582
|
}
|
|
@@ -2750,7 +1601,7 @@ var TableRuntime = (_class = class {
|
|
|
2750
1601
|
const where = isPlainObject(w) ? w : { id: w };
|
|
2751
1602
|
const found = await T.findUnique({ where, select: { id: true } });
|
|
2752
1603
|
if (!found) {
|
|
2753
|
-
throw new ModelValidationError(this.name, [
|
|
1604
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [
|
|
2754
1605
|
{ path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
|
|
2755
1606
|
]);
|
|
2756
1607
|
}
|
|
@@ -2842,8 +1693,8 @@ var TableRuntime = (_class = class {
|
|
|
2842
1693
|
try {
|
|
2843
1694
|
await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
|
|
2844
1695
|
} catch (err) {
|
|
2845
|
-
if (isHttpError(err) && err.statusCode === 404) {
|
|
2846
|
-
throw new ModelValidationError(this.name, [
|
|
1696
|
+
if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
|
|
1697
|
+
throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [
|
|
2847
1698
|
{
|
|
2848
1699
|
path: key,
|
|
2849
1700
|
message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
|
|
@@ -2864,29 +1715,35 @@ var TableRuntime = (_class = class {
|
|
|
2864
1715
|
};
|
|
2865
1716
|
after.push(async (owner) => {
|
|
2866
1717
|
if (rel.kind === "one") {
|
|
2867
|
-
if (
|
|
2868
|
-
|
|
1718
|
+
if (_optionalChain([ops, 'optionalAccess', _40 => _40["delete"]])) await T.deleteMany({ where: mine(owner) });
|
|
1719
|
+
if (mode === "update" && (_optionalChain([ops, 'optionalAccess', _41 => _41["create"]]) || _optionalChain([ops, 'optionalAccess', _42 => _42["connect"]]) || _optionalChain([ops, 'optionalAccess', _43 => _43["disconnect"]]))) {
|
|
1720
|
+
if (!_optionalChain([T, 'access', _44 => _44.tbl, 'access', _45 => _45.columns, 'access', _46 => _46.get, 'call', _47 => _47(fk), 'optionalAccess', _48 => _48.node, 'optionalAccess', _49 => _49.def, 'access', _50 => _50.required])) await unlink(owner);
|
|
1721
|
+
else if ((await T.findMany({ where: mine(owner), select: { id: true }, take: 1 })).length) {
|
|
1722
|
+
this.fail(
|
|
1723
|
+
key,
|
|
1724
|
+
`${rel.target}.${fk} is required, so the current ${rel.target} can't be unlinked \u2014 add delete: true to replace it`
|
|
1725
|
+
);
|
|
1726
|
+
}
|
|
2869
1727
|
}
|
|
2870
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
2871
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
2872
|
-
if (_optionalChain([ops, 'optionalAccess', _96 => _96["create"]]) !== void 0) await createChild(owner, ops["create"]);
|
|
1728
|
+
if (_optionalChain([ops, 'optionalAccess', _51 => _51["connect"]]) !== void 0) await link(owner, ops["connect"]);
|
|
1729
|
+
if (_optionalChain([ops, 'optionalAccess', _52 => _52["create"]]) !== void 0) await createChild(owner, ops["create"]);
|
|
2873
1730
|
return;
|
|
2874
1731
|
}
|
|
2875
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
1732
|
+
if (_optionalChain([ops, 'optionalAccess', _53 => _53["set"]]) !== void 0) {
|
|
2876
1733
|
const keep = list(ops["set"]).map(whereOf);
|
|
2877
1734
|
await unlink(owner, keep.length ? { NOT: { OR: keep } } : void 0);
|
|
2878
1735
|
for (const w of keep) await link(owner, w);
|
|
2879
1736
|
}
|
|
2880
|
-
for (const w of list(_optionalChain([ops, 'optionalAccess',
|
|
2881
|
-
for (const w of list(_optionalChain([ops, 'optionalAccess',
|
|
1737
|
+
for (const w of list(_optionalChain([ops, 'optionalAccess', _54 => _54["disconnect"]]))) await unlink(owner, whereOf(w));
|
|
1738
|
+
for (const w of list(_optionalChain([ops, 'optionalAccess', _55 => _55["delete"]])))
|
|
2882
1739
|
await T.deleteMany({ where: { AND: [mine(owner), whereOf(w)] } });
|
|
2883
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
1740
|
+
if (_optionalChain([ops, 'optionalAccess', _56 => _56["deleteMany"]]) !== void 0) {
|
|
2884
1741
|
for (const w of list(ops["deleteMany"])) {
|
|
2885
1742
|
await T.deleteMany({ where: { AND: [mine(owner), ...isPlainObject(w) ? [w] : []] } });
|
|
2886
1743
|
}
|
|
2887
1744
|
}
|
|
2888
|
-
for (const w of list(_optionalChain([ops, 'optionalAccess',
|
|
2889
|
-
for (const c of list(_optionalChain([ops, 'optionalAccess',
|
|
1745
|
+
for (const w of list(_optionalChain([ops, 'optionalAccess', _57 => _57["connect"]]))) await link(owner, w);
|
|
1746
|
+
for (const c of list(_optionalChain([ops, 'optionalAccess', _58 => _58["create"]]))) await createChild(owner, c);
|
|
2890
1747
|
});
|
|
2891
1748
|
}
|
|
2892
1749
|
return { data: out, after };
|
|
@@ -2988,7 +1845,7 @@ var TableRuntime = (_class = class {
|
|
|
2988
1845
|
const a = `efc_f${++aliasSeq}`;
|
|
2989
1846
|
const { T, from, cond } = this.relationSource(
|
|
2990
1847
|
rel,
|
|
2991
|
-
_nullishCoalesce(owner, () => ( q(this.tbl.table))),
|
|
1848
|
+
_nullishCoalesce(owner, () => ( _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))),
|
|
2992
1849
|
a,
|
|
2993
1850
|
`efc_fj${aliasSeq}`
|
|
2994
1851
|
);
|
|
@@ -3030,13 +1887,13 @@ var TableRuntime = (_class = class {
|
|
|
3030
1887
|
const include = this.includeArg(args);
|
|
3031
1888
|
const pairs = [];
|
|
3032
1889
|
for (const f of this.projection(args)) {
|
|
3033
|
-
if (_optionalChain([include, 'optionalAccess',
|
|
3034
|
-
pairs.push(sql`${sql.raw(
|
|
1890
|
+
if (_optionalChain([include, 'optionalAccess', _59 => _59[f]])) continue;
|
|
1891
|
+
pairs.push(sql`${sql.raw(literal(f))}, ${this.jsonValue(sql, f, alias)}`);
|
|
3035
1892
|
}
|
|
3036
1893
|
for (const [name, arg] of Object.entries(_nullishCoalesce(include, () => ( {})))) {
|
|
3037
1894
|
if (!arg) continue;
|
|
3038
1895
|
const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), alias, depth);
|
|
3039
|
-
pairs.push(sql`${sql.raw(
|
|
1896
|
+
pairs.push(sql`${sql.raw(literal(name))}, ${expr}`);
|
|
3040
1897
|
}
|
|
3041
1898
|
if (pairs.length === 0) return sql`'{}'::jsonb`;
|
|
3042
1899
|
const chunks = [];
|
|
@@ -3061,7 +1918,7 @@ var TableRuntime = (_class = class {
|
|
|
3061
1918
|
const include = this.includeArg(args);
|
|
3062
1919
|
const keyed = {};
|
|
3063
1920
|
for (const f of this.projection(args)) {
|
|
3064
|
-
if (_optionalChain([include, 'optionalAccess',
|
|
1921
|
+
if (_optionalChain([include, 'optionalAccess', _60 => _60[f]])) continue;
|
|
3065
1922
|
const v = json[f];
|
|
3066
1923
|
const join = this.join(f);
|
|
3067
1924
|
if (v == null || join) {
|
|
@@ -3129,7 +1986,7 @@ var TableRuntime = (_class = class {
|
|
|
3129
1986
|
}
|
|
3130
1987
|
async orThrow(p) {
|
|
3131
1988
|
const r = await p;
|
|
3132
|
-
if (r === null) throw new HttpError(404, `${this.name} not found`);
|
|
1989
|
+
if (r === null) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
|
|
3133
1990
|
return r;
|
|
3134
1991
|
}
|
|
3135
1992
|
async count(args = {}) {
|
|
@@ -3139,7 +1996,7 @@ var TableRuntime = (_class = class {
|
|
|
3139
1996
|
const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
|
|
3140
1997
|
const exprs = sql.join(
|
|
3141
1998
|
counted.map(
|
|
3142
|
-
([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(q("_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(q(f))}`
|
|
1999
|
+
([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, f))}`
|
|
3143
2000
|
),
|
|
3144
2001
|
sql`, `
|
|
3145
2002
|
);
|
|
@@ -3214,7 +2071,7 @@ var TableRuntime = (_class = class {
|
|
|
3214
2071
|
const specs = this.aggregateSpec(args);
|
|
3215
2072
|
if (specs.length === 0) return {};
|
|
3216
2073
|
const exprs = sql.join(
|
|
3217
|
-
specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`),
|
|
2074
|
+
specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, s.alias))}`),
|
|
3218
2075
|
sql`, `
|
|
3219
2076
|
);
|
|
3220
2077
|
const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
|
|
@@ -3272,7 +2129,7 @@ var TableRuntime = (_class = class {
|
|
|
3272
2129
|
[
|
|
3273
2130
|
...by.map((f) => this.col(sql, f)),
|
|
3274
2131
|
...specs.map(
|
|
3275
|
-
(s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`
|
|
2132
|
+
(s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, s.alias))}`
|
|
3276
2133
|
)
|
|
3277
2134
|
],
|
|
3278
2135
|
sql`, `
|
|
@@ -3296,7 +2153,7 @@ var TableRuntime = (_class = class {
|
|
|
3296
2153
|
}
|
|
3297
2154
|
}
|
|
3298
2155
|
}
|
|
3299
|
-
const query = sql`select ${select} from ${sql.raw(q(this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
|
|
2156
|
+
const query = sql`select ${select} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
|
|
3300
2157
|
by.map((f) => this.col(sql, f)),
|
|
3301
2158
|
sql`, `
|
|
3302
2159
|
)}${having ? sql` having ${having}` : sql``}${orders.length ? sql` order by ${sql.join(orders, sql`, `)}` : sql``}${args["take"] !== void 0 ? sql` limit ${sql.param(args["take"])}` : sql``}${args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``}`;
|
|
@@ -3374,7 +2231,7 @@ var TableRuntime = (_class = class {
|
|
|
3374
2231
|
}
|
|
3375
2232
|
}
|
|
3376
2233
|
}
|
|
3377
|
-
if (issues.length) throw new ModelValidationError(this.name, issues);
|
|
2234
|
+
if (issues.length) throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, issues);
|
|
3378
2235
|
await this.tbl.validate(plain, true);
|
|
3379
2236
|
for (const [field, v] of Object.entries(plain)) {
|
|
3380
2237
|
sets.push(
|
|
@@ -3416,7 +2273,7 @@ var TableRuntime = (_class = class {
|
|
|
3416
2273
|
}
|
|
3417
2274
|
for (const [field, entries] of byField) {
|
|
3418
2275
|
const join = this.join(field);
|
|
3419
|
-
const jt = sql.raw(q(join.table));
|
|
2276
|
+
const jt = sql.raw(_chunk66R7S7J3cjs.q.call(void 0, join.table));
|
|
3420
2277
|
const sets = entries.filter((e) => e.op.mode === "set");
|
|
3421
2278
|
if (sets.length) {
|
|
3422
2279
|
const owners2 = sets.map((e) => idText(e.id));
|
|
@@ -3463,7 +2320,7 @@ var TableRuntime = (_class = class {
|
|
|
3463
2320
|
const idDdl = this.tbl.columns.get("id").ddl;
|
|
3464
2321
|
const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
|
|
3465
2322
|
const parts = joins.map(
|
|
3466
|
-
(j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(q(j.table))} where owner_id = any(${owners}) group by owner_id`
|
|
2323
|
+
(j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
|
|
3467
2324
|
);
|
|
3468
2325
|
const { rows } = await this.exec(sql.join(parts, sql` union all `));
|
|
3469
2326
|
for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
|
|
@@ -3485,7 +2342,7 @@ var TableRuntime = (_class = class {
|
|
|
3485
2342
|
}
|
|
3486
2343
|
insertSql(sql, t, rows) {
|
|
3487
2344
|
const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
|
|
3488
|
-
const head = sql`insert into ${sql.raw(q(this.tbl.table))} (${sql.join(
|
|
2345
|
+
const head = sql`insert into ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} (${sql.join(
|
|
3489
2346
|
fields.map((f) => this.col(sql, f)),
|
|
3490
2347
|
sql`, `
|
|
3491
2348
|
)})`;
|
|
@@ -3564,7 +2421,7 @@ var TableRuntime = (_class = class {
|
|
|
3564
2421
|
const ops = new Map(split.map((x) => [String(x.row["id"]), x.ops]));
|
|
3565
2422
|
for (const record of records) {
|
|
3566
2423
|
for (const join of this.tbl.joins.values()) {
|
|
3567
|
-
const op = _optionalChain([ops, 'access',
|
|
2424
|
+
const op = _optionalChain([ops, 'access', _61 => _61.get, 'call', _62 => _62(String(record["id"])), 'optionalAccess', _63 => _63.find, 'call', _64 => _64((o) => o.field === join.field)]);
|
|
3568
2425
|
record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
|
|
3569
2426
|
}
|
|
3570
2427
|
}
|
|
@@ -3582,7 +2439,7 @@ var TableRuntime = (_class = class {
|
|
|
3582
2439
|
return;
|
|
3583
2440
|
}
|
|
3584
2441
|
const { rows: ids } = await this.exec(
|
|
3585
|
-
sql`select nextval(pg_get_serial_sequence(${sql.param(q(this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
|
|
2442
|
+
sql`select nextval(pg_get_serial_sequence(${sql.param(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
|
|
3586
2443
|
);
|
|
3587
2444
|
missing.forEach((r, i) => {
|
|
3588
2445
|
const id = ids[i]["id"];
|
|
@@ -3611,9 +2468,9 @@ var TableRuntime = (_class = class {
|
|
|
3611
2468
|
const where = this.where(sql, t, args["where"]);
|
|
3612
2469
|
const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
|
|
3613
2470
|
const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
|
|
3614
|
-
const query = sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(q(this.tbl.table))} where ${where} limit 1`;
|
|
2471
|
+
const query = sets.length ? sql`update ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
|
|
3615
2472
|
const [row] = (await this.exec(query)).rows;
|
|
3616
|
-
if (!row) throw new HttpError(404, `${this.name} not found`);
|
|
2473
|
+
if (!row) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
|
|
3617
2474
|
const record = this.fromRaw(t, row);
|
|
3618
2475
|
await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
|
|
3619
2476
|
await this.refreshJoins(sql, [record], joinOps);
|
|
@@ -3634,7 +2491,7 @@ var TableRuntime = (_class = class {
|
|
|
3634
2491
|
const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
|
|
3635
2492
|
const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
|
|
3636
2493
|
const result = await this.exec(
|
|
3637
|
-
sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(q(this.tbl.table))} where ${where}`
|
|
2494
|
+
sets.length ? sql`update ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where}`
|
|
3638
2495
|
);
|
|
3639
2496
|
const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
|
|
3640
2497
|
await this.applyJoins(
|
|
@@ -3658,7 +2515,7 @@ var TableRuntime = (_class = class {
|
|
|
3658
2515
|
if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
|
|
3659
2516
|
}
|
|
3660
2517
|
const { head, values } = this.insertSql(sql, t, [row]);
|
|
3661
|
-
const table = q(this.tbl.table);
|
|
2518
|
+
const table = _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table);
|
|
3662
2519
|
const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
|
|
3663
2520
|
const { joinOps } = update;
|
|
3664
2521
|
let { sets } = update;
|
|
@@ -3679,7 +2536,7 @@ var TableRuntime = (_class = class {
|
|
|
3679
2536
|
const [out] = (await this.exec(
|
|
3680
2537
|
sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
|
|
3681
2538
|
)).rows;
|
|
3682
|
-
if (!out) throw new HttpError(404, `${this.name} not found`);
|
|
2539
|
+
if (!out) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
|
|
3683
2540
|
const record = this.fromRaw(t, out);
|
|
3684
2541
|
if (linked) {
|
|
3685
2542
|
const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
|
|
@@ -3698,9 +2555,9 @@ var TableRuntime = (_class = class {
|
|
|
3698
2555
|
const where = this.where(sql, t, args["where"]);
|
|
3699
2556
|
const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
|
|
3700
2557
|
const [row] = (await this.exec(
|
|
3701
|
-
sql`delete from ${sql.raw(q(this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
|
|
2558
|
+
sql`delete from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
|
|
3702
2559
|
)).rows;
|
|
3703
|
-
if (!row) throw new HttpError(404, `${this.name} not found`);
|
|
2560
|
+
if (!row) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
|
|
3704
2561
|
return this.project(this.fromRaw(t, row), this.projection(args));
|
|
3705
2562
|
});
|
|
3706
2563
|
}
|
|
@@ -3708,7 +2565,7 @@ var TableRuntime = (_class = class {
|
|
|
3708
2565
|
const { t, sql } = await this.ready(args["where"]);
|
|
3709
2566
|
return this.tbl.guard(async () => {
|
|
3710
2567
|
const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
|
|
3711
|
-
const result = await this.tbl.client().execute(sql`delete from ${sql.raw(q(this.tbl.table))} where ${where}`);
|
|
2568
|
+
const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where}`);
|
|
3712
2569
|
return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
|
|
3713
2570
|
});
|
|
3714
2571
|
}
|
|
@@ -3717,10 +2574,10 @@ function relArgs(arg) {
|
|
|
3717
2574
|
return isPlainObject(arg) ? arg : {};
|
|
3718
2575
|
}
|
|
3719
2576
|
function runtimeOf(name, from) {
|
|
3720
|
-
const runtime = _optionalChain([getRegisteredModel
|
|
2577
|
+
const runtime = _optionalChain([_chunk66R7S7J3cjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
|
|
3721
2578
|
if (!runtime) {
|
|
3722
2579
|
throw new Error(
|
|
3723
|
-
getRegisteredModel(name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
|
|
2580
|
+
_chunk66R7S7J3cjs.getRegisteredModel.call(void 0, name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
|
|
3724
2581
|
);
|
|
3725
2582
|
}
|
|
3726
2583
|
return runtime;
|
|
@@ -3740,7 +2597,7 @@ var JSON_OPS = /* @__PURE__ */ new Set([
|
|
|
3740
2597
|
"mode"
|
|
3741
2598
|
]);
|
|
3742
2599
|
function createTable(name, schema, options = {}) {
|
|
3743
|
-
normalizeSchema(schema, "table", name);
|
|
2600
|
+
_chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "table", name);
|
|
3744
2601
|
for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
|
|
3745
2602
|
const where = `[EFC] ${name}.relations.${rel}`;
|
|
3746
2603
|
if (rel in schema) throw new Error(`${where}: a field already has this name`);
|
|
@@ -3755,8 +2612,8 @@ function createTable(name, schema, options = {}) {
|
|
|
3755
2612
|
}
|
|
3756
2613
|
let runtime;
|
|
3757
2614
|
const rt = () => {
|
|
3758
|
-
const
|
|
3759
|
-
if (
|
|
2615
|
+
const engine = _chunk66R7S7J3cjs.getDbEngine.call(void 0, );
|
|
2616
|
+
if (engine !== "postgresql") {
|
|
3760
2617
|
throw new Error(
|
|
3761
2618
|
`[EFC] ${name} is a PostgreSQL table (defineTable) but the app is connected to MongoDB \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
|
|
3762
2619
|
);
|
|
@@ -3775,26 +2632,27 @@ function createTable(name, schema, options = {}) {
|
|
|
3775
2632
|
aggregate: (args) => call((r) => r.aggregate(args)),
|
|
3776
2633
|
groupBy: (args) => call((r) => r.groupBy(args)),
|
|
3777
2634
|
create: (args) => call((r) => r.withInclude(args, (a) => r.createNested(a))),
|
|
3778
|
-
createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
3779
|
-
createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
2635
|
+
createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _67 => _67["data"]]), "createMany"), r.createMany(args, false))),
|
|
2636
|
+
createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _68 => _68["data"]]), "createMany"), r.createMany(args, true))),
|
|
3780
2637
|
update: (args) => call((r) => r.withInclude(args, (a) => r.updateNested(a))),
|
|
3781
|
-
updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
3782
|
-
updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
2638
|
+
updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _69 => _69["data"]]), "updateMany"), r.updateMany(args, false))),
|
|
2639
|
+
updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _70 => _70["data"]]), "updateMany"), r.updateMany(args, true))),
|
|
3783
2640
|
upsert: (args) => call((r) => r.withInclude(args, (a) => r.upsertNested(a))),
|
|
3784
2641
|
delete: (args) => call((r) => r.deleteWithInclude(args)),
|
|
3785
2642
|
deleteMany: (args) => call((r) => r.deleteMany(args)),
|
|
3786
2643
|
raw: () => call(async (r) => (await r.tbl.compile()).t),
|
|
3787
|
-
sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess',
|
|
2644
|
+
sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _71 => _71.dryRun]), () => ( false)))),
|
|
3788
2645
|
drop: () => call((r) => r.tbl.drop())
|
|
3789
2646
|
};
|
|
3790
|
-
|
|
2647
|
+
_chunkVQSWSYK6cjs.traceOps.call(void 0,
|
|
3791
2648
|
name,
|
|
3792
2649
|
model,
|
|
3793
2650
|
Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
|
|
3794
2651
|
);
|
|
3795
|
-
registerModel({
|
|
2652
|
+
_chunk66R7S7J3cjs.registerModel.call(void 0, {
|
|
3796
2653
|
name,
|
|
3797
2654
|
sync: model.sync,
|
|
2655
|
+
plan: (opts) => call((r) => r.tbl.plan(opts)),
|
|
3798
2656
|
drop: model.drop,
|
|
3799
2657
|
findByIds: (ids) => model.findMany({ where: { id: { in: ids } } }),
|
|
3800
2658
|
pgTarget: () => ({ table: rt().tbl.table, idKind: rt().tbl.idKind }),
|
|
@@ -3837,11 +2695,5 @@ var db = new Proxy({}, {
|
|
|
3837
2695
|
|
|
3838
2696
|
|
|
3839
2697
|
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
|
|
3845
|
-
|
|
3846
|
-
exports.HttpError = HttpError; exports.isHttpError = isHttpError; exports.ModelValidationError = ModelValidationError; exports.setDbEngine = setDbEngine; exports.setAutoSync = setAutoSync; exports.registeredModels = registeredModels; exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
|
|
3847
|
-
//# sourceMappingURL=chunk-AZYXQU3Z.cjs.map
|
|
2698
|
+
exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
|
|
2699
|
+
//# sourceMappingURL=chunk-RGTENTDN.cjs.map
|