express-file-cluster 0.7.1 → 0.8.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.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/chunk-75O3WQKR.cjs +1386 -0
- package/dist/chunk-75O3WQKR.cjs.map +1 -0
- package/dist/{chunk-6OGOVV57.js → chunk-B2I7SYQ3.js} +100 -1261
- package/dist/chunk-B2I7SYQ3.js.map +1 -0
- package/dist/chunk-BBSZLGZW.js +113 -0
- package/dist/chunk-BBSZLGZW.js.map +1 -0
- package/dist/{chunk-AZYXQU3Z.cjs → chunk-FQFKHPLR.cjs} +217 -1378
- package/dist/chunk-FQFKHPLR.cjs.map +1 -0
- package/dist/chunk-OSES7ZQ5.js +1386 -0
- package/dist/chunk-OSES7ZQ5.js.map +1 -0
- package/dist/chunk-QL6EWT4B.cjs +113 -0
- package/dist/chunk-QL6EWT4B.cjs.map +1 -0
- package/dist/cli/db-runner.cjs +611 -26
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +610 -25
- 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/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 +3 -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/index.md +5 -3
- package/dist/docs/skills/SKILL.md +3 -3
- package/dist/docs/skills/what-not-to-invent.md +22 -6
- package/dist/index.cjs +10 -8
- 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 +8 -6
- 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.cts → types-B1tJoI4g.d.cts} +6 -0
- package/dist/{types-B6lVw4bj.d.ts → types-B1tJoI4g.d.ts} +6 -0
- package/package.json +11 -2
- package/dist/chunk-6OGOVV57.js.map +0 -1
- package/dist/chunk-AZYXQU3Z.cjs.map +0 -1
|
@@ -1,453 +1,36 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HttpError,
|
|
3
|
+
ModelValidationError,
|
|
4
|
+
currentTx,
|
|
5
|
+
getDbEngine,
|
|
6
|
+
getRegisteredModel,
|
|
7
|
+
isAutoSync,
|
|
8
|
+
isHttpError,
|
|
9
|
+
isSyncSuppressed,
|
|
10
|
+
nodeAt,
|
|
11
|
+
normalizeSchema,
|
|
12
|
+
pgTable,
|
|
13
|
+
q,
|
|
14
|
+
registerModel,
|
|
15
|
+
resolveDefault,
|
|
16
|
+
runInTx,
|
|
17
|
+
sequenceFields,
|
|
18
|
+
tableNameFor,
|
|
19
|
+
timestampFields,
|
|
20
|
+
validateAtPath
|
|
21
|
+
} from "./chunk-OSES7ZQ5.js";
|
|
1
22
|
import {
|
|
2
23
|
countStatement,
|
|
3
24
|
getOrm,
|
|
4
|
-
getPool,
|
|
5
25
|
notInstalled,
|
|
6
26
|
traceOps,
|
|
7
27
|
untracked,
|
|
8
28
|
whenQueryTracking
|
|
9
29
|
} from "./chunk-BUBXO7WU.js";
|
|
10
30
|
import {
|
|
11
|
-
getCurrentUser,
|
|
12
31
|
getLogger
|
|
13
32
|
} from "./chunk-277BSYVH.js";
|
|
14
33
|
|
|
15
|
-
// src/errors.ts
|
|
16
|
-
var HttpError = class _HttpError extends Error {
|
|
17
|
-
statusCode;
|
|
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
|
-
|
|
52
|
-
// src/db/schema.ts
|
|
53
|
-
import { randomBytes, randomUUID } from "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
|
-
model;
|
|
71
|
-
mode;
|
|
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 = 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 = ts.createdAt ?? "createdAt";
|
|
186
|
-
if (ts.updatedAt !== false) out.updatedAt = ts.updatedAt ?? "updatedAt";
|
|
187
|
-
return out;
|
|
188
|
-
}
|
|
189
|
-
var STATIC_DEFAULT_OPERATORS = {
|
|
190
|
-
$now: () => /* @__PURE__ */ new Date(),
|
|
191
|
-
$uuid: () => randomUUID(),
|
|
192
|
-
$timestamp: () => Date.now(),
|
|
193
|
-
$shortId: () => randomBytes(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 () => getCurrentUser();
|
|
206
|
-
if (isCurrentUserOperator(value)) {
|
|
207
|
-
const key = value.slice("$currentUser.".length);
|
|
208
|
-
return () => getCurrentUser()?.[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
|
-
issues;
|
|
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 = 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
|
-
|
|
417
|
-
// src/db/engine.ts
|
|
418
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
419
|
-
var engine;
|
|
420
|
-
function setDbEngine(value) {
|
|
421
|
-
engine = value;
|
|
422
|
-
}
|
|
423
|
-
function getDbEngine() {
|
|
424
|
-
return engine ?? "mongodb";
|
|
425
|
-
}
|
|
426
|
-
var autoSync = true;
|
|
427
|
-
function setAutoSync(value) {
|
|
428
|
-
autoSync = value;
|
|
429
|
-
}
|
|
430
|
-
function isAutoSync() {
|
|
431
|
-
return autoSync;
|
|
432
|
-
}
|
|
433
|
-
var registry = /* @__PURE__ */ new Map();
|
|
434
|
-
function registerModel(model) {
|
|
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 AsyncLocalStorage();
|
|
444
|
-
function currentTx() {
|
|
445
|
-
return txStorage.getStore();
|
|
446
|
-
}
|
|
447
|
-
function runInTx(handle, fn) {
|
|
448
|
-
return txStorage.run(handle, fn);
|
|
449
|
-
}
|
|
450
|
-
|
|
451
34
|
// src/db/mongo-model.ts
|
|
452
35
|
var mongoosePromise;
|
|
453
36
|
function loadMongoose() {
|
|
@@ -775,6 +358,7 @@ function mongoModel(name, tree, options) {
|
|
|
775
358
|
}),
|
|
776
359
|
raw: () => model(),
|
|
777
360
|
async sync(opts) {
|
|
361
|
+
if (isSyncSuppressed()) 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;
|
|
@@ -791,6 +375,65 @@ function mongoModel(name, tree, options) {
|
|
|
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 } = 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(found?.[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 = 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) => {
|
|
@@ -808,807 +451,6 @@ async function connectMongo(url) {
|
|
|
808
451
|
return mg.connection;
|
|
809
452
|
}
|
|
810
453
|
|
|
811
|
-
// src/db/pg-table.ts
|
|
812
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
813
|
-
var drizzlePromise;
|
|
814
|
-
function loadDrizzle() {
|
|
815
|
-
drizzlePromise ??= Promise.all([import("drizzle-orm"), import("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) => registeredModels().find((m) => {
|
|
848
|
-
try {
|
|
849
|
-
return m.pgTarget?.().table === table;
|
|
850
|
-
} catch {
|
|
851
|
-
return false;
|
|
852
|
-
}
|
|
853
|
-
})?.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},${def.scale ?? 0})`;
|
|
876
|
-
return {
|
|
877
|
-
kind: "numeric",
|
|
878
|
-
ddl: t,
|
|
879
|
-
formatted: t,
|
|
880
|
-
precision: def.precision,
|
|
881
|
-
scale: def.scale ?? 0
|
|
882
|
-
};
|
|
883
|
-
}
|
|
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 = options.collection ?? tableNameFor(snake ? snakeCase(name) : name);
|
|
896
|
-
const columnName = (field, def) => def?.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: 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
|
-
});
|
|
1017
|
-
let synced;
|
|
1018
|
-
const ready = async () => {
|
|
1019
|
-
const result = await compile();
|
|
1020
|
-
if (isAutoSync()) {
|
|
1021
|
-
synced ??= reconcile(false).then(
|
|
1022
|
-
(changes) => {
|
|
1023
|
-
if (changes.length)
|
|
1024
|
-
getLogger().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 tx?.engine === "postgresql" ? tx.tx : getOrm();
|
|
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, randomUUID2);
|
|
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) => byColumn.get(column)?.field ?? column;
|
|
1134
|
-
const guard = async (fn) => {
|
|
1135
|
-
try {
|
|
1136
|
-
return await fn();
|
|
1137
|
-
} catch (err) {
|
|
1138
|
-
const e = err.cause ?? err;
|
|
1139
|
-
if (e?.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 (e?.code === "23505") {
|
|
1145
|
-
const cols = /\(([^)]+)\)=/.exec(e.detail ?? "")?.[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 (e?.code === "23503" || e?.code === "23001") {
|
|
1150
|
-
const ref = /Key \(([^)]+)\)=\([^)]*\) is not present in table "([^"]+)"/.exec(
|
|
1151
|
-
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: joinByTable.get(e.table ?? "") ?? fieldOfColumn(ref[1].replace(/"/g, "")),
|
|
1158
|
-
message: `${modelOfTable(ref[2])} not found`
|
|
1159
|
-
}
|
|
1160
|
-
]);
|
|
1161
|
-
}
|
|
1162
|
-
const by = /is (?:still )?referenced from table "([^"]+)"/.exec(e.detail ?? "")?.[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 (e?.code === "23502")
|
|
1169
|
-
throw new ModelValidationError(name, [
|
|
1170
|
-
{ path: fieldOfColumn(e.column ?? ""), message: "is required" }
|
|
1171
|
-
]);
|
|
1172
|
-
if (e?.code === "22P02" || e?.code === "22003" || e?.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 && spec.node?.kind === "scalar" && spec.node.def.ref !== void 0;
|
|
1206
|
-
function resolveTarget(field, targetName, kind, many) {
|
|
1207
|
-
const target = targetName === name ? { table, idKind } : getRegisteredModel(targetName)?.pgTarget?.();
|
|
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: 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 = spec.node?.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 options.indexes ?? []) {
|
|
1281
|
-
const fields = Object.entries(idx.fields).map(
|
|
1282
|
-
([f, d]) => [columns.get(f)?.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 = 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 getPool().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 (tx?.engine === "postgresql" && fks.length) {
|
|
1320
|
-
for (const fk of fks) deferred.add(fk.name);
|
|
1321
|
-
tx.afterCommit.push(() => {
|
|
1322
|
-
reconcile(false).catch(
|
|
1323
|
-
(err) => getLogger().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) => getLogger().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 = getPool();
|
|
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 = [...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 = 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 = spec.node?.def;
|
|
1475
|
-
if (spec.node?.kind === "scalar" && def?.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) => 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 = existing.get(join.legacyColumn)?.type;
|
|
1521
|
-
if (legacy === "jsonb" || legacy?.endsWith("[]")) {
|
|
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 (!live?.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 {
|
|
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) => r.rows[0]?.n ?? "?").catch(() => "?");
|
|
1566
|
-
getLogger().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
|
-
};
|
|
1610
|
-
}
|
|
1611
|
-
|
|
1612
454
|
// src/db/pg-model.ts
|
|
1613
455
|
function pgModel(name, tree, options) {
|
|
1614
456
|
const tbl = pgTable(name, tree, options, { native: false, api: "defineModel" });
|
|
@@ -1892,11 +734,11 @@ function pgModel(name, tree, options) {
|
|
|
1892
734
|
if (ts.updatedAt) set[ts.updatedAt] = /* @__PURE__ */ new Date();
|
|
1893
735
|
return set;
|
|
1894
736
|
}
|
|
1895
|
-
const
|
|
737
|
+
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
738
|
return {
|
|
1897
739
|
find: (filter, opts) => guard(async () => await runFind(filter, opts)),
|
|
1898
740
|
findById: (id, opts) => guard(async () => {
|
|
1899
|
-
if (!
|
|
741
|
+
if (!UUID_RE.test(id)) return null;
|
|
1900
742
|
return (await runFind({ id }, { ...opts, limit: 1 }))[0] ?? null;
|
|
1901
743
|
}),
|
|
1902
744
|
findOne: (filter, opts) => guard(
|
|
@@ -1932,7 +774,7 @@ function pgModel(name, tree, options) {
|
|
|
1932
774
|
);
|
|
1933
775
|
}),
|
|
1934
776
|
update: (id, data) => guard(async () => {
|
|
1935
|
-
if (!
|
|
777
|
+
if (!UUID_RE.test(id)) return null;
|
|
1936
778
|
const { t, sql } = await ready();
|
|
1937
779
|
const set = await buildSet(data);
|
|
1938
780
|
const [row] = await client().update(t).set(set).where(sql`${t.id} = ${id}`).returning();
|
|
@@ -1956,7 +798,7 @@ function pgModel(name, tree, options) {
|
|
|
1956
798
|
return (await query.returning({ id: t.id })).length;
|
|
1957
799
|
}),
|
|
1958
800
|
delete: (id) => guard(async () => {
|
|
1959
|
-
if (!
|
|
801
|
+
if (!UUID_RE.test(id)) return;
|
|
1960
802
|
const { t, sql } = await ready();
|
|
1961
803
|
await client().delete(t).where(sql`${t.id} = ${id}`);
|
|
1962
804
|
}),
|
|
@@ -1989,6 +831,7 @@ function pgModel(name, tree, options) {
|
|
|
1989
831
|
},
|
|
1990
832
|
raw: async () => (await compile()).t,
|
|
1991
833
|
sync: (opts) => tbl.reconcile(opts?.dryRun ?? false),
|
|
834
|
+
plan: (opts) => tbl.plan(opts),
|
|
1992
835
|
drop: () => tbl.drop()
|
|
1993
836
|
};
|
|
1994
837
|
}
|
|
@@ -2031,13 +874,13 @@ function createModel(name, schema, options, native) {
|
|
|
2031
874
|
let engineModel;
|
|
2032
875
|
const impl = () => {
|
|
2033
876
|
if (engineModel) return engineModel;
|
|
2034
|
-
const
|
|
2035
|
-
if (native && native.engine !==
|
|
877
|
+
const engine = getDbEngine();
|
|
878
|
+
if (native && native.engine !== engine) {
|
|
2036
879
|
throw new Error(
|
|
2037
|
-
`[EFC] ${name} is a ${ENGINE_LABEL[native.engine]} ${native.kind} (${native.api}) but the app is connected to ${ENGINE_LABEL[
|
|
880
|
+
`[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
881
|
);
|
|
2039
882
|
}
|
|
2040
|
-
engineModel =
|
|
883
|
+
engineModel = engine === "postgresql" ? pgModel(name, tree, options) : mongoModel(name, tree, options);
|
|
2041
884
|
return engineModel;
|
|
2042
885
|
};
|
|
2043
886
|
const call = (fn) => Promise.resolve().then(() => fn(impl()));
|
|
@@ -2093,6 +936,7 @@ function createModel(name, schema, options, native) {
|
|
|
2093
936
|
registerModel({
|
|
2094
937
|
name,
|
|
2095
938
|
sync: model.sync,
|
|
939
|
+
plan: (opts) => call((m) => m.plan(opts)),
|
|
2096
940
|
drop: model.drop,
|
|
2097
941
|
findByIds: (ids) => model.find({ id: { $in: ids } }),
|
|
2098
942
|
pgTarget: () => ({ table: options.collection ?? tableNameFor(name), idKind: "uuid" })
|
|
@@ -2126,7 +970,7 @@ async function transaction(fn) {
|
|
|
2126
970
|
}
|
|
2127
971
|
|
|
2128
972
|
// src/db/table-model.ts
|
|
2129
|
-
import { randomUUID
|
|
973
|
+
import { randomUUID } from "crypto";
|
|
2130
974
|
var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
|
|
2131
975
|
var NUMERIC_KINDS = /* @__PURE__ */ new Set(["double", "integer", "bigint", "numeric"]);
|
|
2132
976
|
var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof RegExp) && typeof v !== "bigint";
|
|
@@ -2147,7 +991,7 @@ var BACK_ONE_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "
|
|
|
2147
991
|
var BACK_MANY_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "set", "delete", "deleteMany"]);
|
|
2148
992
|
var idJson = (_k, v) => typeof v === "bigint" ? String(v) : v;
|
|
2149
993
|
var aliasSeq = 0;
|
|
2150
|
-
var
|
|
994
|
+
var literal = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
2151
995
|
var JSON_PAIRS_PER_CALL = 50;
|
|
2152
996
|
var idText = (v) => v == null ? v : String(v);
|
|
2153
997
|
var dedupe = (items) => {
|
|
@@ -3031,12 +1875,12 @@ var TableRuntime = class {
|
|
|
3031
1875
|
const pairs = [];
|
|
3032
1876
|
for (const f of this.projection(args)) {
|
|
3033
1877
|
if (include?.[f]) continue;
|
|
3034
|
-
pairs.push(sql`${sql.raw(
|
|
1878
|
+
pairs.push(sql`${sql.raw(literal(f))}, ${this.jsonValue(sql, f, alias)}`);
|
|
3035
1879
|
}
|
|
3036
1880
|
for (const [name, arg] of Object.entries(include ?? {})) {
|
|
3037
1881
|
if (!arg) continue;
|
|
3038
1882
|
const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), alias, depth);
|
|
3039
|
-
pairs.push(sql`${sql.raw(
|
|
1883
|
+
pairs.push(sql`${sql.raw(literal(name))}, ${expr}`);
|
|
3040
1884
|
}
|
|
3041
1885
|
if (pairs.length === 0) return sql`'{}'::jsonb`;
|
|
3042
1886
|
const chunks = [];
|
|
@@ -3578,7 +2422,7 @@ var TableRuntime = class {
|
|
|
3578
2422
|
const missing = rows.filter((r) => r["id"] === void 0);
|
|
3579
2423
|
if (missing.length === 0) return;
|
|
3580
2424
|
if (this.tbl.idKind === "uuid") {
|
|
3581
|
-
for (const r of missing) r["id"] =
|
|
2425
|
+
for (const r of missing) r["id"] = randomUUID();
|
|
3582
2426
|
return;
|
|
3583
2427
|
}
|
|
3584
2428
|
const { rows: ids } = await this.exec(
|
|
@@ -3755,8 +2599,8 @@ function createTable(name, schema, options = {}) {
|
|
|
3755
2599
|
}
|
|
3756
2600
|
let runtime;
|
|
3757
2601
|
const rt = () => {
|
|
3758
|
-
const
|
|
3759
|
-
if (
|
|
2602
|
+
const engine = getDbEngine();
|
|
2603
|
+
if (engine !== "postgresql") {
|
|
3760
2604
|
throw new Error(
|
|
3761
2605
|
`[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
2606
|
);
|
|
@@ -3795,6 +2639,7 @@ function createTable(name, schema, options = {}) {
|
|
|
3795
2639
|
registerModel({
|
|
3796
2640
|
name,
|
|
3797
2641
|
sync: model.sync,
|
|
2642
|
+
plan: (opts) => call((r) => r.tbl.plan(opts)),
|
|
3798
2643
|
drop: model.drop,
|
|
3799
2644
|
findByIds: (ids) => model.findMany({ where: { id: { in: ids } } }),
|
|
3800
2645
|
pgTarget: () => ({ table: rt().tbl.table, idKind: rt().tbl.idKind }),
|
|
@@ -3830,12 +2675,6 @@ var db = new Proxy({}, {
|
|
|
3830
2675
|
});
|
|
3831
2676
|
|
|
3832
2677
|
export {
|
|
3833
|
-
HttpError,
|
|
3834
|
-
isHttpError,
|
|
3835
|
-
ModelValidationError,
|
|
3836
|
-
setDbEngine,
|
|
3837
|
-
setAutoSync,
|
|
3838
|
-
registeredModels,
|
|
3839
2678
|
connectMongo,
|
|
3840
2679
|
defineModel,
|
|
3841
2680
|
transaction,
|
|
@@ -3844,4 +2683,4 @@ export {
|
|
|
3844
2683
|
getDbClient,
|
|
3845
2684
|
db
|
|
3846
2685
|
};
|
|
3847
|
-
//# sourceMappingURL=chunk-
|
|
2686
|
+
//# sourceMappingURL=chunk-B2I7SYQ3.js.map
|