@zenstackhq/cli 3.5.6 → 3.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,3452 @@
1
+ import { createRequire } from "node:module";
2
+ import { ZModelCodeGenerator, ZModelLanguageMetaData, formatDocument, loadDocument } from "@zenstackhq/language";
3
+ import colors from "colors";
4
+ import { Command, CommanderError, Option } from "commander";
5
+ import "dotenv/config";
6
+ import { DataModel, Enum, isDataSource, isEnum, isInvocationExpr, isLiteralExpr, isPlugin } from "@zenstackhq/language/ast";
7
+ import path from "node:path";
8
+ import { invariant, lowerCaseFirst, singleDebounce } from "@zenstackhq/common-helpers";
9
+ import { PrismaSchemaGenerator, TsSchemaGenerator } from "@zenstackhq/sdk";
10
+ import { createJiti } from "jiti";
11
+ import crypto, { createHash, randomUUID } from "node:crypto";
12
+ import fs from "node:fs";
13
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
+ import terminalLink from "terminal-link";
15
+ import { z } from "zod";
16
+ import ora from "ora";
17
+ import { execSync } from "child_process";
18
+ import { fileURLToPath as fileURLToPath$1 } from "url";
19
+ import { DataFieldAttributeFactory, DataFieldFactory, DataModelFactory, EnumFactory } from "@zenstackhq/language/factory";
20
+ import { AstUtils } from "langium";
21
+ import { getLiteral, getLiteralArray, getStringLiteral } from "@zenstackhq/language/utils";
22
+ import { watch } from "chokidar";
23
+ import semver from "semver";
24
+ import { detect, resolveCommand } from "package-manager-detector";
25
+ import { execaCommand } from "execa";
26
+ import { ZenStackClient } from "@zenstackhq/orm";
27
+ import { MysqlDialect } from "@zenstackhq/orm/dialects/mysql";
28
+ import { PostgresDialect } from "@zenstackhq/orm/dialects/postgres";
29
+ import { SqliteDialect } from "@zenstackhq/orm/dialects/sqlite";
30
+ import { RPCApiHandler } from "@zenstackhq/server/api";
31
+ import { ZenStackMiddleware } from "@zenstackhq/server/express";
32
+ import cors from "cors";
33
+ import express from "express";
34
+ import { init } from "mixpanel";
35
+ import * as os$1 from "os";
36
+ import process$1, { env } from "node:process";
37
+ import os from "node:os";
38
+ //#region \0rolldown/runtime.js
39
+ var __defProp = Object.defineProperty;
40
+ var __exportAll = (all, no_symbols) => {
41
+ let target = {};
42
+ for (var name in all) __defProp(target, name, {
43
+ get: all[name],
44
+ enumerable: true
45
+ });
46
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
47
+ return target;
48
+ };
49
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
50
+ //#endregion
51
+ //#region src/cli-error.ts
52
+ /**
53
+ * Indicating an error during CLI execution
54
+ */
55
+ var CliError = class extends Error {};
56
+ //#endregion
57
+ //#region src/actions/action-utils.ts
58
+ function getSchemaFile(file) {
59
+ if (file) {
60
+ if (!fs.existsSync(file)) throw new CliError(`Schema file not found: ${file}`);
61
+ return file;
62
+ }
63
+ const pkgJsonConfig = getPkgJsonConfig(process.cwd());
64
+ if (pkgJsonConfig.schema) {
65
+ if (!fs.existsSync(pkgJsonConfig.schema)) throw new CliError(`Schema file not found: ${pkgJsonConfig.schema}`);
66
+ if (fs.statSync(pkgJsonConfig.schema).isDirectory()) {
67
+ const schemaPath = path.join(pkgJsonConfig.schema, "schema.zmodel");
68
+ if (!fs.existsSync(schemaPath)) throw new CliError(`Schema file not found: ${schemaPath}`);
69
+ return schemaPath;
70
+ } else return pkgJsonConfig.schema;
71
+ }
72
+ if (fs.existsSync("./schema.zmodel")) return "./schema.zmodel";
73
+ else if (fs.existsSync("./zenstack/schema.zmodel")) return "./zenstack/schema.zmodel";
74
+ else throw new CliError("Schema file not found in default locations (\"./schema.zmodel\" or \"./zenstack/schema.zmodel\").");
75
+ }
76
+ async function loadSchemaDocument(schemaFile, opts = {}) {
77
+ const returnServices = opts.returnServices ?? false;
78
+ const loadResult = await loadDocument(schemaFile, [], opts.mergeImports ?? true);
79
+ if (!loadResult.success) {
80
+ loadResult.errors.forEach((err) => {
81
+ console.error(colors.red(err));
82
+ });
83
+ throw new CliError("Schema contains errors. See above for details.");
84
+ }
85
+ loadResult.warnings.forEach((warn) => {
86
+ console.warn(colors.yellow(warn));
87
+ });
88
+ if (returnServices) return {
89
+ model: loadResult.model,
90
+ services: loadResult.services
91
+ };
92
+ return loadResult.model;
93
+ }
94
+ function handleSubProcessError$1(err) {
95
+ if (err instanceof Error && "status" in err && typeof err.status === "number") process.exit(err.status);
96
+ else process.exit(1);
97
+ }
98
+ async function generateTempPrismaSchema(zmodelPath, opts = {}) {
99
+ const { folder: folderOpt, randomName = false } = opts;
100
+ const model = await loadSchemaDocument(zmodelPath);
101
+ if (!model.declarations.some(isDataSource)) throw new CliError("Schema must define a datasource");
102
+ const prismaSchema = await new PrismaSchemaGenerator(model).generate();
103
+ const folder = folderOpt ?? path.dirname(zmodelPath);
104
+ const fileName = randomName ? `~schema.${crypto.randomUUID()}.prisma` : "~schema.prisma";
105
+ const prismaSchemaFile = path.resolve(folder, fileName);
106
+ fs.writeFileSync(prismaSchemaFile, prismaSchema);
107
+ return prismaSchemaFile;
108
+ }
109
+ function getPkgJsonConfig(startPath) {
110
+ const result = {
111
+ schema: void 0,
112
+ output: void 0,
113
+ seed: void 0
114
+ };
115
+ const pkgJsonFile = findUp(["package.json"], startPath, false);
116
+ if (!pkgJsonFile) return result;
117
+ let pkgJson = void 0;
118
+ try {
119
+ pkgJson = JSON.parse(fs.readFileSync(pkgJsonFile, "utf8"));
120
+ } catch {
121
+ return result;
122
+ }
123
+ if (pkgJson.zenstack && typeof pkgJson.zenstack === "object") {
124
+ result.schema = pkgJson.zenstack.schema && typeof pkgJson.zenstack.schema === "string" ? path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.schema) : void 0;
125
+ result.output = pkgJson.zenstack.output && typeof pkgJson.zenstack.output === "string" ? path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.output) : void 0;
126
+ result.seed = typeof pkgJson.zenstack.seed === "string" && pkgJson.zenstack.seed ? pkgJson.zenstack.seed : void 0;
127
+ }
128
+ return result;
129
+ }
130
+ function findUp(names, cwd = process.cwd(), multiple = false, result = []) {
131
+ if (!names.some((name) => !!name)) return;
132
+ const target = names.find((name) => fs.existsSync(path.join(cwd, name)));
133
+ if (multiple === false && target) return path.resolve(cwd, target);
134
+ if (target) result.push(path.resolve(cwd, target));
135
+ const up = path.resolve(cwd, "..");
136
+ if (up === cwd) return multiple && result.length > 0 ? result : void 0;
137
+ return findUp(names, up, multiple, result);
138
+ }
139
+ async function requireDataSourceUrl(schemaFile) {
140
+ if (!(await loadSchemaDocument(schemaFile)).declarations.find(isDataSource)?.fields.some((f) => f.name === "url")) throw new CliError("The schema's \"datasource\" must have a \"url\" field to use this command.");
141
+ }
142
+ function getOutputPath(options, schemaFile) {
143
+ if (options.output) return options.output;
144
+ const pkgJsonConfig = getPkgJsonConfig(process.cwd());
145
+ if (pkgJsonConfig.output) return pkgJsonConfig.output;
146
+ else return path.dirname(schemaFile);
147
+ }
148
+ async function getZenStackPackages(searchPath) {
149
+ const pkgJsonFile = findUp(["package.json"], searchPath, false);
150
+ if (!pkgJsonFile) return [];
151
+ let pkgJson;
152
+ try {
153
+ pkgJson = JSON.parse(fs.readFileSync(pkgJsonFile, "utf8"));
154
+ } catch {
155
+ return [];
156
+ }
157
+ const packages = Array.from(new Set([...Object.keys(pkgJson.dependencies ?? {}), ...Object.keys(pkgJson.devDependencies ?? {})].filter((p) => p.startsWith("@zenstackhq/")))).sort();
158
+ const require = createRequire(pkgJsonFile);
159
+ return packages.map((pkg) => {
160
+ try {
161
+ const depPkgJson = require(`${pkg}/package.json`);
162
+ if (depPkgJson.private) return;
163
+ return {
164
+ pkg,
165
+ version: depPkgJson.version
166
+ };
167
+ } catch {
168
+ return {
169
+ pkg,
170
+ version: void 0
171
+ };
172
+ }
173
+ }).filter((p) => !!p);
174
+ }
175
+ function getPluginProvider(plugin) {
176
+ const providerField = plugin.fields.find((f) => f.name === "provider");
177
+ invariant(providerField, `Plugin ${plugin.name} does not have a provider field`);
178
+ return providerField.value.value;
179
+ }
180
+ async function loadPluginModule(provider, basePath) {
181
+ if (provider.toLowerCase().endsWith(".zmodel")) return;
182
+ let moduleSpec = provider;
183
+ if (moduleSpec.startsWith(".")) moduleSpec = path.resolve(basePath, moduleSpec);
184
+ const importAsEsm = async (spec) => {
185
+ try {
186
+ const result = (await import(spec)).default;
187
+ return typeof result?.generate === "function" ? result : void 0;
188
+ } catch (err) {
189
+ throw new CliError(`Failed to load plugin module from ${spec}: ${err.message}`);
190
+ }
191
+ };
192
+ const jiti = createJiti(pathToFileURL(basePath).toString());
193
+ const importAsTs = async (spec) => {
194
+ try {
195
+ const result = await jiti.import(spec, { default: true });
196
+ return typeof result?.generate === "function" ? result : void 0;
197
+ } catch (err) {
198
+ throw new CliError(`Failed to load plugin module from ${spec}: ${err.message}`);
199
+ }
200
+ };
201
+ const esmSuffixes = [".js", ".mjs"];
202
+ const tsSuffixes = [".ts", ".mts"];
203
+ if (fs.existsSync(moduleSpec) && fs.statSync(moduleSpec).isFile()) {
204
+ if (esmSuffixes.some((suffix) => moduleSpec.endsWith(suffix))) return await importAsEsm(pathToFileURL(moduleSpec).toString());
205
+ if (tsSuffixes.some((suffix) => moduleSpec.endsWith(suffix))) return await importAsTs(moduleSpec);
206
+ }
207
+ for (const suffix of esmSuffixes) {
208
+ const indexPath = path.join(moduleSpec, `index${suffix}`);
209
+ if (fs.existsSync(indexPath)) return await importAsEsm(pathToFileURL(indexPath).toString());
210
+ }
211
+ for (const suffix of tsSuffixes) {
212
+ const indexPath = path.join(moduleSpec, `index${suffix}`);
213
+ if (fs.existsSync(indexPath)) return await importAsTs(indexPath);
214
+ }
215
+ try {
216
+ const result = await jiti.import(moduleSpec, { default: true });
217
+ return typeof result.generate === "function" ? result : void 0;
218
+ } catch {}
219
+ try {
220
+ const mod = await import(moduleSpec);
221
+ return typeof mod.default?.generate === "function" ? mod.default : void 0;
222
+ } catch (err) {
223
+ const errorCode = err?.code;
224
+ if (errorCode === "ERR_MODULE_NOT_FOUND" || errorCode === "MODULE_NOT_FOUND") throw new CliError(`Cannot find plugin module "${provider}". Please make sure the package exists.`);
225
+ throw new CliError(`Failed to load plugin module "${provider}": ${err.message}`);
226
+ }
227
+ }
228
+ const FETCH_CLI_MAX_TIME = 1e3;
229
+ const CLI_CONFIG_ENDPOINT = "https://zenstack.dev/config/cli-v3.json";
230
+ const usageTipsSchema = z.object({ notifications: z.array(z.object({
231
+ title: z.string(),
232
+ url: z.url().optional(),
233
+ active: z.boolean()
234
+ })) });
235
+ /**
236
+ * Starts the usage tips fetch in the background. Returns a callback that, when invoked check if the fetch
237
+ * is complete. If not complete, it will wait until the max time is reached. After that, if fetch is still
238
+ * not complete, just return.
239
+ */
240
+ function startUsageTipsFetch() {
241
+ let fetchedData = void 0;
242
+ let fetchComplete = false;
243
+ const start = Date.now();
244
+ const controller = new AbortController();
245
+ fetch(CLI_CONFIG_ENDPOINT, {
246
+ headers: { accept: "application/json" },
247
+ signal: controller.signal
248
+ }).then(async (res) => {
249
+ if (!res.ok) return;
250
+ const data = await res.json();
251
+ const parseResult = usageTipsSchema.safeParse(data);
252
+ if (parseResult.success) fetchedData = parseResult.data;
253
+ }).catch(() => {}).finally(() => {
254
+ fetchComplete = true;
255
+ });
256
+ return async () => {
257
+ const elapsed = Date.now() - start;
258
+ if (!fetchComplete && elapsed < FETCH_CLI_MAX_TIME) await new Promise((resolve) => setTimeout(resolve, FETCH_CLI_MAX_TIME - elapsed));
259
+ if (!fetchComplete) {
260
+ controller.abort();
261
+ return;
262
+ }
263
+ if (!fetchedData) return;
264
+ const activeItems = fetchedData.notifications.filter((item) => item.active);
265
+ if (activeItems.length > 0) {
266
+ const item = activeItems[Math.floor(Math.random() * activeItems.length)];
267
+ if (item.url) console.log(terminalLink(item.title, item.url));
268
+ else console.log(item.title);
269
+ }
270
+ };
271
+ }
272
+ //#endregion
273
+ //#region src/actions/check.ts
274
+ /**
275
+ * CLI action for checking a schema's validity.
276
+ */
277
+ async function run$8(options) {
278
+ const schemaFile = getSchemaFile(options.schema);
279
+ try {
280
+ await checkPluginResolution(schemaFile, await loadSchemaDocument(schemaFile));
281
+ console.log(colors.green("✓ Schema validation completed successfully."));
282
+ } catch (error) {
283
+ console.error(colors.red("✗ Schema validation failed."));
284
+ throw error;
285
+ }
286
+ }
287
+ async function checkPluginResolution(schemaFile, model) {
288
+ const plugins = model.declarations.filter(isPlugin);
289
+ for (const plugin of plugins) {
290
+ const provider = getPluginProvider(plugin);
291
+ if (!provider.startsWith("@core/")) {
292
+ const pluginSourcePath = plugin.$cstNode?.parent?.element.$document?.uri?.fsPath ?? schemaFile;
293
+ await loadPluginModule(provider, path.dirname(pluginSourcePath));
294
+ }
295
+ }
296
+ }
297
+ //#endregion
298
+ //#region src/utils/exec-utils.ts
299
+ /**
300
+ * Utility for executing command synchronously and prints outputs on current console
301
+ */
302
+ function execSync$1(cmd, options) {
303
+ const { env, ...restOptions } = options ?? {};
304
+ const mergedEnv = env ? {
305
+ ...process.env,
306
+ ...env
307
+ } : void 0;
308
+ execSync(cmd, {
309
+ encoding: "utf-8",
310
+ stdio: options?.stdio ?? "inherit",
311
+ env: mergedEnv,
312
+ ...restOptions
313
+ });
314
+ }
315
+ /**
316
+ * Utility for running package commands through npx/bunx
317
+ */
318
+ function execPackage(cmd, options) {
319
+ execSync$1(`${process?.versions?.["bun"] ? "bunx" : "npx"} ${cmd}`, options);
320
+ }
321
+ /**
322
+ * Utility for running prisma commands
323
+ */
324
+ function execPrisma(args, options) {
325
+ let prismaPath;
326
+ try {
327
+ if (typeof import.meta.resolve === "function") prismaPath = fileURLToPath$1(import.meta.resolve("prisma/build/index.js"));
328
+ else prismaPath = __require.resolve("prisma/build/index.js");
329
+ } catch {}
330
+ const _options = {
331
+ ...options,
332
+ env: {
333
+ ...options?.env,
334
+ PRISMA_HIDE_UPDATE_MESSAGE: "1"
335
+ }
336
+ };
337
+ if (!prismaPath) {
338
+ execPackage(`prisma ${args}`, _options);
339
+ return;
340
+ }
341
+ execSync$1(`node "${prismaPath}" ${args}`, _options);
342
+ }
343
+ //#endregion
344
+ //#region src/actions/pull/utils.ts
345
+ function isDatabaseManagedAttribute(name) {
346
+ return [
347
+ "@relation",
348
+ "@id",
349
+ "@unique"
350
+ ].includes(name) || name.startsWith("@db.");
351
+ }
352
+ function getDatasource(model) {
353
+ const datasource = model.declarations.find((d) => d.$type === "DataSource");
354
+ if (!datasource) throw new CliError("No datasource declaration found in the schema.");
355
+ const urlField = datasource.fields.find((f) => f.name === "url");
356
+ if (!urlField) throw new CliError(`No url field found in the datasource declaration.`);
357
+ let url = getStringLiteral(urlField.value);
358
+ if (!url && isInvocationExpr(urlField.value)) {
359
+ const envName = getStringLiteral(urlField.value.args[0]?.value);
360
+ if (!envName) throw new CliError("The url field must be a string literal or an env().");
361
+ if (!process.env[envName]) throw new CliError(`Environment variable ${envName} is not set, please set it to the database connection string.`);
362
+ url = process.env[envName];
363
+ }
364
+ if (!url) throw new CliError("The url field must be a string literal or an env().");
365
+ if (url.startsWith("file:")) {
366
+ url = new URL(url, `file:${model.$document.uri.path}`).pathname;
367
+ if (process.platform === "win32" && url[0] === "/") url = url.slice(1);
368
+ }
369
+ const defaultSchemaField = datasource.fields.find((f) => f.name === "defaultSchema");
370
+ const defaultSchema = defaultSchemaField && getStringLiteral(defaultSchemaField.value) || "public";
371
+ const schemasField = datasource.fields.find((f) => f.name === "schemas");
372
+ const schemas = schemasField && getLiteralArray(schemasField.value)?.filter((s) => s !== void 0) || [];
373
+ const provider = getStringLiteral(datasource.fields.find((f) => f.name === "provider")?.value);
374
+ if (!provider) throw new CliError(`Datasource "${datasource.name}" is missing a "provider" field.`);
375
+ return {
376
+ name: datasource.name,
377
+ provider,
378
+ url,
379
+ defaultSchema,
380
+ schemas,
381
+ allSchemas: [defaultSchema, ...schemas]
382
+ };
383
+ }
384
+ function getDbName(decl, includeSchema = false) {
385
+ if (!("attributes" in decl)) return decl.name;
386
+ const schemaAttr = decl.attributes.find((a) => a.decl.ref?.name === "@@schema");
387
+ let schema = "public";
388
+ if (schemaAttr) {
389
+ const schemaAttrValue = schemaAttr.args[0]?.value;
390
+ if (schemaAttrValue?.$type === "StringLiteral") schema = schemaAttrValue.value;
391
+ }
392
+ const formatName = (name) => `${schema && includeSchema ? `${schema}.` : ""}${name}`;
393
+ const nameAttr = decl.attributes.find((a) => a.decl.ref?.name === "@@map" || a.decl.ref?.name === "@map");
394
+ if (!nameAttr) return formatName(decl.name);
395
+ const attrValue = nameAttr.args[0]?.value;
396
+ if (attrValue?.$type !== "StringLiteral") return formatName(decl.name);
397
+ return formatName(attrValue.value);
398
+ }
399
+ function getRelationFkName(decl) {
400
+ return ((decl?.attributes.find((a) => a.decl.ref?.name === "@relation"))?.args.find((a) => a.name === "map")?.value)?.value;
401
+ }
402
+ /**
403
+ * Gets the FK field names from the @relation attribute's `fields` argument.
404
+ * Returns a sorted, comma-separated string of field names for comparison.
405
+ * e.g., @relation(fields: [userId], references: [id]) -> "userId"
406
+ * e.g., @relation(fields: [postId, tagId], references: [id, id]) -> "postId,tagId"
407
+ */
408
+ function getRelationFieldsKey(decl) {
409
+ const relationAttr = decl?.attributes.find((a) => a.decl.ref?.name === "@relation");
410
+ if (!relationAttr) return void 0;
411
+ const fieldsArg = relationAttr.args.find((a) => a.name === "fields")?.value;
412
+ if (!fieldsArg || fieldsArg.$type !== "ArrayExpr") return void 0;
413
+ const fieldNames = fieldsArg.items.filter((item) => item.$type === "ReferenceExpr").map((item) => item.target?.$refText || item.target?.ref?.name).filter((name) => !!name).sort();
414
+ return fieldNames.length > 0 ? fieldNames.join(",") : void 0;
415
+ }
416
+ function getDeclarationRef(type, name, services) {
417
+ const node = services.shared.workspace.IndexManager.allElements(type).find((m) => m.node && getDbName(m.node) === name)?.node;
418
+ if (!node) throw new CliError(`Declaration not found: ${name}`);
419
+ return node;
420
+ }
421
+ function getEnumRef(name, services) {
422
+ return getDeclarationRef("Enum", name, services);
423
+ }
424
+ function getAttributeRef(name, services) {
425
+ return getDeclarationRef("Attribute", name, services);
426
+ }
427
+ function getFunctionRef(name, services) {
428
+ return getDeclarationRef("FunctionDecl", name, services);
429
+ }
430
+ /**
431
+ * Normalize a default value string for a Float field.
432
+ * - Integer strings get `.0` appended
433
+ * - Decimal strings are preserved as-is
434
+ */
435
+ function normalizeFloatDefault(val) {
436
+ if (/^-?\d+$/.test(val)) return (ab) => ab.NumberLiteral.setValue(val + ".0");
437
+ if (/^-?\d+\.\d+$/.test(val)) return (ab) => ab.NumberLiteral.setValue(val);
438
+ return (ab) => ab.NumberLiteral.setValue(val);
439
+ }
440
+ /**
441
+ * Normalize a default value string for a Decimal field.
442
+ * - Integer strings get `.00` appended
443
+ * - Decimal strings are normalized to minimum 2 decimal places, stripping excess trailing zeros
444
+ */
445
+ function normalizeDecimalDefault(val) {
446
+ if (/^-?\d+$/.test(val)) return (ab) => ab.NumberLiteral.setValue(val + ".00");
447
+ if (/^-?\d+\.\d+$/.test(val)) {
448
+ const [integerPart, fractionalPart] = val.split(".");
449
+ let normalized = fractionalPart.replace(/0+$/, "");
450
+ if (normalized.length < 2) normalized = normalized.padEnd(2, "0");
451
+ return (ab) => ab.NumberLiteral.setValue(`${integerPart}.${normalized}`);
452
+ }
453
+ return (ab) => ab.NumberLiteral.setValue(val);
454
+ }
455
+ //#endregion
456
+ //#region src/actions/pull/casing.ts
457
+ function resolveNameCasing(casing, originalName) {
458
+ let name = originalName;
459
+ const fieldPrefix = /[0-9]/g.test(name.charAt(0)) ? "_" : "";
460
+ switch (casing) {
461
+ case "pascal":
462
+ name = toPascalCase(originalName);
463
+ break;
464
+ case "camel":
465
+ name = toCamelCase(originalName);
466
+ break;
467
+ case "snake":
468
+ name = toSnakeCase(originalName);
469
+ break;
470
+ }
471
+ return {
472
+ modified: name !== originalName || fieldPrefix !== "",
473
+ name: `${fieldPrefix}${name}`
474
+ };
475
+ }
476
+ function isAllUpperCase(str) {
477
+ return str === str.toUpperCase();
478
+ }
479
+ function toPascalCase(str) {
480
+ if (isAllUpperCase(str)) return str;
481
+ return str.replace(/[_\- ]+(\w)/g, (_, c) => c.toUpperCase()).replace(/^\w/, (c) => c.toUpperCase());
482
+ }
483
+ function toCamelCase(str) {
484
+ if (isAllUpperCase(str)) return str;
485
+ return str.replace(/[_\- ]+(\w)/g, (_, c) => c.toUpperCase()).replace(/^\w/, (c) => c.toLowerCase());
486
+ }
487
+ function toSnakeCase(str) {
488
+ if (isAllUpperCase(str)) return str;
489
+ return str.replace(/[- ]+/g, "_").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
490
+ }
491
+ //#endregion
492
+ //#region src/actions/pull/index.ts
493
+ function syncEnums({ dbEnums, model, oldModel, provider, options, services, defaultSchema }) {
494
+ if (provider.isSupportedFeature("NativeEnum")) for (const dbEnum of dbEnums) {
495
+ const { modified, name } = resolveNameCasing(options.modelCasing, dbEnum.enum_type);
496
+ if (modified) console.log(colors.gray(`Mapping enum ${dbEnum.enum_type} to ${name}`));
497
+ const factory = new EnumFactory().setName(name);
498
+ if (modified || options.alwaysMap) factory.addAttribute((builder) => builder.setDecl(getAttributeRef("@@map", services)).addArg((argBuilder) => argBuilder.StringLiteral.setValue(dbEnum.enum_type)));
499
+ dbEnum.values.forEach((v) => {
500
+ const { name, modified } = resolveNameCasing(options.fieldCasing, v);
501
+ factory.addField((builder) => {
502
+ builder.setName(name);
503
+ if (modified || options.alwaysMap) builder.addAttribute((builder) => builder.setDecl(getAttributeRef("@map", services)).addArg((argBuilder) => argBuilder.StringLiteral.setValue(v)));
504
+ return builder;
505
+ });
506
+ });
507
+ if (dbEnum.schema_name && dbEnum.schema_name !== "" && dbEnum.schema_name !== defaultSchema) factory.addAttribute((b) => b.setDecl(getAttributeRef("@@schema", services)).addArg((a) => a.StringLiteral.setValue(dbEnum.schema_name)));
508
+ model.declarations.push(factory.get({ $container: model }));
509
+ }
510
+ else {
511
+ const dummyBuildReference = (_node, _property, _refNode, refText) => ({ $refText: refText });
512
+ oldModel.declarations.filter((d) => isEnum(d)).forEach((d) => {
513
+ const copy = AstUtils.copyAstNode(d, dummyBuildReference);
514
+ copy.$container = model;
515
+ model.declarations.push(copy);
516
+ });
517
+ }
518
+ }
519
+ function syncTable({ model, provider, table, services, options, defaultSchema }) {
520
+ const idAttribute = getAttributeRef("@id", services);
521
+ const modelIdAttribute = getAttributeRef("@@id", services);
522
+ const uniqueAttribute = getAttributeRef("@unique", services);
523
+ const modelUniqueAttribute = getAttributeRef("@@unique", services);
524
+ const fieldMapAttribute = getAttributeRef("@map", services);
525
+ const tableMapAttribute = getAttributeRef("@@map", services);
526
+ const modelindexAttribute = getAttributeRef("@@index", services);
527
+ const relations = [];
528
+ const { name, modified } = resolveNameCasing(options.modelCasing, table.name);
529
+ const multiPk = table.columns.filter((c) => c.pk).length > 1;
530
+ const modelFactory = new DataModelFactory().setName(name).setIsView(table.type === "view");
531
+ modelFactory.setContainer(model);
532
+ if (modified || options.alwaysMap) modelFactory.addAttribute((builder) => builder.setDecl(tableMapAttribute).addArg((argBuilder) => argBuilder.StringLiteral.setValue(table.name)));
533
+ const fkGroups = /* @__PURE__ */ new Map();
534
+ table.columns.forEach((column) => {
535
+ if (column.foreign_key_table && column.foreign_key_name) {
536
+ const group = fkGroups.get(column.foreign_key_name) ?? [];
537
+ group.push(column);
538
+ fkGroups.set(column.foreign_key_name, group);
539
+ }
540
+ });
541
+ for (const [fkName, fkColumns] of fkGroups) {
542
+ const firstCol = fkColumns[0];
543
+ const isSingleColumnPk = fkColumns.length === 1 && !multiPk && firstCol.pk;
544
+ const isUniqueRelation = fkColumns.length === 1 && firstCol.unique || isSingleColumnPk;
545
+ relations.push({
546
+ schema: table.schema,
547
+ table: table.name,
548
+ columns: fkColumns.map((c) => c.name),
549
+ type: "one",
550
+ fk_name: fkName,
551
+ foreign_key_on_delete: firstCol.foreign_key_on_delete,
552
+ foreign_key_on_update: firstCol.foreign_key_on_update,
553
+ nullable: firstCol.nullable,
554
+ references: {
555
+ schema: firstCol.foreign_key_schema,
556
+ table: firstCol.foreign_key_table,
557
+ columns: fkColumns.map((c) => c.foreign_key_column),
558
+ type: isUniqueRelation ? "one" : "many"
559
+ }
560
+ });
561
+ }
562
+ table.columns.forEach((column) => {
563
+ const { name, modified } = resolveNameCasing(options.fieldCasing, column.name);
564
+ const builtinType = provider.getBuiltinType(column.datatype);
565
+ modelFactory.addField((builder) => {
566
+ builder.setName(name);
567
+ builder.setType((typeBuilder) => {
568
+ typeBuilder.setArray(builtinType.isArray);
569
+ typeBuilder.setOptional(builtinType.isArray ? false : column.nullable);
570
+ if (column.computed) typeBuilder.setUnsupported((unsupportedBuilder) => unsupportedBuilder.setValue((lt) => lt.StringLiteral.setValue(column.datatype)));
571
+ else if (column.datatype === "enum") {
572
+ const ref = model.declarations.find((d) => isEnum(d) && getDbName(d) === column.datatype_name);
573
+ if (!ref) throw new CliError(`Enum ${column.datatype_name} not found`);
574
+ typeBuilder.setReference(ref);
575
+ } else if (builtinType.type !== "Unsupported") typeBuilder.setType(builtinType.type);
576
+ else typeBuilder.setUnsupported((unsupportedBuilder) => unsupportedBuilder.setValue((lt) => lt.StringLiteral.setValue(column.datatype)));
577
+ return typeBuilder;
578
+ });
579
+ if (column.pk && !multiPk) builder.addAttribute((b) => b.setDecl(idAttribute));
580
+ provider.getFieldAttributes({
581
+ fieldName: column.name,
582
+ fieldType: builtinType.type,
583
+ datatype: column.datatype,
584
+ length: column.length,
585
+ precision: column.precision,
586
+ services
587
+ }).forEach(builder.addAttribute.bind(builder));
588
+ if (column.default && !column.computed) {
589
+ const defaultExprBuilder = provider.getDefaultValue({
590
+ fieldType: builtinType.type,
591
+ datatype: column.datatype,
592
+ datatype_name: column.datatype_name,
593
+ defaultValue: column.default,
594
+ services,
595
+ enums: model.declarations.filter((d) => d.$type === "Enum")
596
+ });
597
+ if (defaultExprBuilder) {
598
+ const defaultAttr = new DataFieldAttributeFactory().setDecl(getAttributeRef("@default", services)).addArg(defaultExprBuilder);
599
+ builder.addAttribute(defaultAttr);
600
+ }
601
+ }
602
+ if (column.unique && !column.pk) builder.addAttribute((b) => {
603
+ b.setDecl(uniqueAttribute);
604
+ if (!(!column.unique_name || column.unique_name === `${table.name}_${column.name}_key` || column.unique_name === column.name)) b.addArg((ab) => ab.StringLiteral.setValue(column.unique_name), "map");
605
+ return b;
606
+ });
607
+ if (modified || options.alwaysMap) builder.addAttribute((ab) => ab.setDecl(fieldMapAttribute).addArg((ab) => ab.StringLiteral.setValue(column.name)));
608
+ return builder;
609
+ });
610
+ });
611
+ const pkColumns = table.columns.filter((c) => c.pk).map((c) => c.name);
612
+ if (multiPk) modelFactory.addAttribute((builder) => builder.setDecl(modelIdAttribute).addArg((argBuilder) => {
613
+ const arrayExpr = argBuilder.ArrayExpr;
614
+ pkColumns.forEach((c) => {
615
+ const ref = modelFactory.node.fields.find((f) => getDbName(f) === c);
616
+ if (!ref) throw new CliError(`Field ${c} not found`);
617
+ arrayExpr.addItem((itemBuilder) => itemBuilder.ReferenceExpr.setTarget(ref));
618
+ });
619
+ return arrayExpr;
620
+ }));
621
+ if (!(table.columns.some((c) => c.unique || c.pk) || table.indexes.some((i) => i.unique))) {
622
+ modelFactory.addAttribute((a) => a.setDecl(getAttributeRef("@@ignore", services)));
623
+ modelFactory.addComment("/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Zenstack Client.");
624
+ }
625
+ table.indexes.reverse().sort((a, b) => {
626
+ if (a.unique && !b.unique) return -1;
627
+ if (!a.unique && b.unique) return 1;
628
+ return 0;
629
+ }).forEach((index) => {
630
+ if (index.predicate) {
631
+ console.warn(colors.yellow(`These constraints are not supported by Zenstack. Read more: https://pris.ly/d/check-constraints\n- Model: "${table.name}", constraint: "${index.name}"`));
632
+ return;
633
+ }
634
+ if (index.columns.find((c) => c.expression)) {
635
+ console.warn(colors.yellow(`These constraints are not supported by Zenstack. Read more: https://pris.ly/d/check-constraints\n- Model: "${table.name}", constraint: "${index.name}"`));
636
+ return;
637
+ }
638
+ if (index.primary) return;
639
+ if (index.columns.length === 1 && (index.columns.find((c) => pkColumns.includes(c.name)) || index.unique)) return;
640
+ modelFactory.addAttribute((builder) => {
641
+ const attr = builder.setDecl(index.unique ? modelUniqueAttribute : modelindexAttribute).addArg((argBuilder) => {
642
+ const arrayExpr = argBuilder.ArrayExpr;
643
+ index.columns.forEach((c) => {
644
+ const ref = modelFactory.node.fields.find((f) => getDbName(f) === c.name);
645
+ if (!ref) throw new CliError(`Column ${c.name} not found in model ${table.name}`);
646
+ arrayExpr.addItem((itemBuilder) => {
647
+ const refExpr = itemBuilder.ReferenceExpr.setTarget(ref);
648
+ if (c.order && c.order !== "ASC") refExpr.addArg((ab) => ab.StringLiteral.setValue("DESC"), "sort");
649
+ return refExpr;
650
+ });
651
+ });
652
+ return arrayExpr;
653
+ });
654
+ const suffix = index.unique ? "_key" : "_idx";
655
+ if (index.name !== `${table.name}_${index.columns.map((c) => c.name).join("_")}${suffix}`) attr.addArg((argBuilder) => argBuilder.StringLiteral.setValue(index.name), "map");
656
+ return attr;
657
+ });
658
+ });
659
+ if (table.schema && table.schema !== "" && table.schema !== defaultSchema) modelFactory.addAttribute((b) => b.setDecl(getAttributeRef("@@schema", services)).addArg((a) => a.StringLiteral.setValue(table.schema)));
660
+ model.declarations.push(modelFactory.node);
661
+ return relations;
662
+ }
663
+ function syncRelation({ model, relation, services, options, selfRelation, similarRelations }) {
664
+ const idAttribute = getAttributeRef("@id", services);
665
+ const uniqueAttribute = getAttributeRef("@unique", services);
666
+ const relationAttribute = getAttributeRef("@relation", services);
667
+ const fieldMapAttribute = getAttributeRef("@map", services);
668
+ const tableMapAttribute = getAttributeRef("@@map", services);
669
+ const includeRelationName = selfRelation || similarRelations > 0;
670
+ if (!idAttribute || !uniqueAttribute || !relationAttribute || !fieldMapAttribute || !tableMapAttribute) throw new CliError("Cannot find required attributes in the model.");
671
+ const sourceModel = model.declarations.find((d) => d.$type === "DataModel" && getDbName(d) === relation.table);
672
+ if (!sourceModel) return;
673
+ const sourceFields = [];
674
+ for (const colName of relation.columns) {
675
+ const idx = sourceModel.fields.findIndex((f) => getDbName(f) === colName);
676
+ const field = sourceModel.fields[idx];
677
+ if (!field) return;
678
+ sourceFields.push({
679
+ field,
680
+ index: idx
681
+ });
682
+ }
683
+ const targetModel = model.declarations.find((d) => d.$type === "DataModel" && getDbName(d) === relation.references.table);
684
+ if (!targetModel) return;
685
+ const targetFields = [];
686
+ for (const colName of relation.references.columns) {
687
+ const field = targetModel.fields.find((f) => getDbName(f) === colName);
688
+ if (!field) return;
689
+ targetFields.push(field);
690
+ }
691
+ const firstSourceField = sourceFields[0].field;
692
+ const firstSourceFieldId = sourceFields[0].index;
693
+ const firstColumn = relation.columns[0];
694
+ const fieldPrefix = /[0-9]/g.test(sourceModel.name.charAt(0)) ? "_" : "";
695
+ const relationName = `${relation.table}${similarRelations > 0 ? `_${firstColumn}` : ""}To${relation.references.table}`;
696
+ const sourceNameFromReference = firstSourceField.name.toLowerCase().endsWith("id") ? `${resolveNameCasing(options.fieldCasing, firstSourceField.name.slice(0, -2)).name}${relation.type === "many" ? "s" : ""}` : void 0;
697
+ const sourceFieldFromReference = sourceModel.fields.find((f) => f.name === sourceNameFromReference);
698
+ let { name: sourceFieldName } = resolveNameCasing(options.fieldCasing, similarRelations > 0 ? `${fieldPrefix}${lowerCaseFirst(sourceModel.name)}_${firstColumn}` : `${(!sourceFieldFromReference ? sourceNameFromReference : void 0) || lowerCaseFirst(resolveNameCasing(options.fieldCasing, targetModel.name).name)}${relation.type === "many" ? "s" : ""}`);
699
+ if (sourceModel.fields.find((f) => f.name === sourceFieldName)) sourceFieldName = `${sourceFieldName}To${lowerCaseFirst(targetModel.name)}_${relation.references.columns[0]}`;
700
+ const sourceFieldFactory = new DataFieldFactory().setContainer(sourceModel).setName(sourceFieldName).setType((tb) => tb.setOptional(relation.nullable).setArray(relation.type === "many").setReference(targetModel));
701
+ sourceFieldFactory.addAttribute((ab) => {
702
+ ab.setDecl(relationAttribute);
703
+ if (includeRelationName) ab.addArg((ab) => ab.StringLiteral.setValue(relationName));
704
+ ab.addArg((ab) => {
705
+ const arrayExpr = ab.ArrayExpr;
706
+ for (const { field } of sourceFields) arrayExpr.addItem((aeb) => aeb.ReferenceExpr.setTarget(field));
707
+ return arrayExpr;
708
+ }, "fields");
709
+ ab.addArg((ab) => {
710
+ const arrayExpr = ab.ArrayExpr;
711
+ for (const field of targetFields) arrayExpr.addItem((aeb) => aeb.ReferenceExpr.setTarget(field));
712
+ return arrayExpr;
713
+ }, "references");
714
+ const onDeleteDefault = relation.nullable ? "SET NULL" : "RESTRICT";
715
+ if (relation.foreign_key_on_delete && relation.foreign_key_on_delete !== onDeleteDefault) {
716
+ const enumRef = getEnumRef("ReferentialAction", services);
717
+ if (!enumRef) throw new CliError("ReferentialAction enum not found");
718
+ const enumFieldRef = enumRef.fields.find((f) => f.name.toLowerCase() === relation.foreign_key_on_delete.replace(/ /g, "").toLowerCase());
719
+ if (!enumFieldRef) throw new CliError(`ReferentialAction ${relation.foreign_key_on_delete} not found`);
720
+ ab.addArg((a) => a.ReferenceExpr.setTarget(enumFieldRef), "onDelete");
721
+ }
722
+ if (relation.foreign_key_on_update && relation.foreign_key_on_update !== "CASCADE") {
723
+ const enumRef = getEnumRef("ReferentialAction", services);
724
+ if (!enumRef) throw new CliError("ReferentialAction enum not found");
725
+ const enumFieldRef = enumRef.fields.find((f) => f.name.toLowerCase() === relation.foreign_key_on_update.replace(/ /g, "").toLowerCase());
726
+ if (!enumFieldRef) throw new CliError(`ReferentialAction ${relation.foreign_key_on_update} not found`);
727
+ ab.addArg((a) => a.ReferenceExpr.setTarget(enumFieldRef), "onUpdate");
728
+ }
729
+ const defaultFkName = `${relation.table}_${relation.columns.join("_")}_fkey`;
730
+ if (relation.fk_name && relation.fk_name !== defaultFkName) ab.addArg((ab) => ab.StringLiteral.setValue(relation.fk_name), "map");
731
+ return ab;
732
+ });
733
+ sourceModel.fields.splice(firstSourceFieldId, 0, sourceFieldFactory.node);
734
+ const oppositeFieldPrefix = /[0-9]/g.test(targetModel.name.charAt(0)) ? "_" : "";
735
+ let { name: oppositeFieldName } = resolveNameCasing(options.fieldCasing, similarRelations > 0 ? `${oppositeFieldPrefix}${lowerCaseFirst(sourceModel.name)}_${firstColumn}` : `${lowerCaseFirst(resolveNameCasing(options.fieldCasing, sourceModel.name).name)}${relation.references.type === "many" ? "s" : ""}`);
736
+ if (targetModel.fields.find((f) => f.name === oppositeFieldName)) ({name: oppositeFieldName} = resolveNameCasing(options.fieldCasing, `${lowerCaseFirst(sourceModel.name)}_${firstColumn}To${relation.references.table}_${relation.references.columns[0]}`));
737
+ const targetFieldFactory = new DataFieldFactory().setContainer(targetModel).setName(oppositeFieldName).setType((tb) => tb.setOptional(relation.references.type === "one").setArray(relation.references.type === "many").setReference(sourceModel));
738
+ if (includeRelationName) targetFieldFactory.addAttribute((ab) => ab.setDecl(relationAttribute).addArg((ab) => ab.StringLiteral.setValue(relationName)));
739
+ targetModel.fields.push(targetFieldFactory.node);
740
+ }
741
+ /**
742
+ * Consolidates per-column enums back to shared enums when possible.
743
+ *
744
+ * MySQL doesn't have named enum types — each column gets a synthetic enum
745
+ * (e.g., `UserStatus`, `GroupStatus`). When the original schema used a shared
746
+ * enum (e.g., `Status`) across multiple fields, this function detects the
747
+ * mapping via field references and consolidates the synthetic enums back into
748
+ * the original shared enum so the merge phase can match them correctly.
749
+ */
750
+ function consolidateEnums({ newModel, oldModel }) {
751
+ const newEnums = newModel.declarations.filter((d) => isEnum(d));
752
+ const newDataModels = newModel.declarations.filter((d) => d.$type === "DataModel");
753
+ const oldDataModels = oldModel.declarations.filter((d) => d.$type === "DataModel");
754
+ const enumMapping = /* @__PURE__ */ new Map();
755
+ for (const newEnum of newEnums) for (const newDM of newDataModels) {
756
+ for (const field of newDM.fields) {
757
+ if (field.$type !== "DataField" || field.type.reference?.ref !== newEnum) continue;
758
+ const oldDM = oldDataModels.find((d) => getDbName(d) === getDbName(newDM));
759
+ if (!oldDM) continue;
760
+ const oldField = oldDM.fields.find((f) => getDbName(f) === getDbName(field));
761
+ if (!oldField || oldField.$type !== "DataField" || !oldField.type.reference?.ref) continue;
762
+ const oldEnum = oldField.type.reference.ref;
763
+ if (!isEnum(oldEnum)) continue;
764
+ enumMapping.set(newEnum, oldEnum);
765
+ break;
766
+ }
767
+ if (enumMapping.has(newEnum)) break;
768
+ }
769
+ const reverseMapping = /* @__PURE__ */ new Map();
770
+ for (const [newEnum, oldEnum] of enumMapping) {
771
+ if (!reverseMapping.has(oldEnum)) reverseMapping.set(oldEnum, []);
772
+ reverseMapping.get(oldEnum).push(newEnum);
773
+ }
774
+ for (const [oldEnum, newEnumsGroup] of reverseMapping) {
775
+ const keepEnum = newEnumsGroup[0];
776
+ if (newEnumsGroup.length === 1 && keepEnum.name === oldEnum.name) continue;
777
+ const oldValues = new Set(oldEnum.fields.map((f) => getDbName(f)));
778
+ if (!newEnumsGroup.every((ne) => {
779
+ const newValues = new Set(ne.fields.map((f) => getDbName(f)));
780
+ return oldValues.size === newValues.size && [...oldValues].every((v) => newValues.has(v));
781
+ })) continue;
782
+ keepEnum.name = oldEnum.name;
783
+ keepEnum.attributes = oldEnum.attributes.map((attr) => {
784
+ return {
785
+ ...attr,
786
+ $container: keepEnum
787
+ };
788
+ });
789
+ for (let i = 1; i < newEnumsGroup.length; i++) {
790
+ const idx = newModel.declarations.indexOf(newEnumsGroup[i]);
791
+ if (idx >= 0) newModel.declarations.splice(idx, 1);
792
+ }
793
+ for (const newDM of newDataModels) for (const field of newDM.fields) {
794
+ if (field.$type !== "DataField") continue;
795
+ const ref = field.type.reference?.ref;
796
+ if (ref && newEnumsGroup.includes(ref)) field.type.reference = {
797
+ ref: keepEnum,
798
+ $refText: keepEnum.name
799
+ };
800
+ }
801
+ console.log(colors.gray(`Consolidated enum${newEnumsGroup.length > 1 ? "s" : ""} ${newEnumsGroup.map((e) => e.name).join(", ")} → ${oldEnum.name}`));
802
+ }
803
+ }
804
+ //#endregion
805
+ //#region src/actions/pull/provider/mysql.ts
806
+ function normalizeGenerationExpression(typeDef) {
807
+ return typeDef.replace(/_([0-9A-Za-z_]+)\\?'/g, "'").replace(/\\'/g, "'");
808
+ }
809
+ const mysql = {
810
+ isSupportedFeature(feature) {
811
+ switch (feature) {
812
+ case "NativeEnum": return true;
813
+ default: return false;
814
+ }
815
+ },
816
+ getBuiltinType(type) {
817
+ const t = (type || "").toLowerCase().trim();
818
+ const isArray = false;
819
+ switch (t) {
820
+ case "tinyint":
821
+ case "smallint":
822
+ case "mediumint":
823
+ case "int":
824
+ case "integer": return {
825
+ type: "Int",
826
+ isArray
827
+ };
828
+ case "bigint": return {
829
+ type: "BigInt",
830
+ isArray
831
+ };
832
+ case "decimal":
833
+ case "numeric": return {
834
+ type: "Decimal",
835
+ isArray
836
+ };
837
+ case "float":
838
+ case "double":
839
+ case "real": return {
840
+ type: "Float",
841
+ isArray
842
+ };
843
+ case "boolean":
844
+ case "bool": return {
845
+ type: "Boolean",
846
+ isArray
847
+ };
848
+ case "char":
849
+ case "varchar":
850
+ case "tinytext":
851
+ case "text":
852
+ case "mediumtext":
853
+ case "longtext": return {
854
+ type: "String",
855
+ isArray
856
+ };
857
+ case "date":
858
+ case "time":
859
+ case "datetime":
860
+ case "timestamp":
861
+ case "year": return {
862
+ type: "DateTime",
863
+ isArray
864
+ };
865
+ case "binary":
866
+ case "varbinary":
867
+ case "tinyblob":
868
+ case "blob":
869
+ case "mediumblob":
870
+ case "longblob": return {
871
+ type: "Bytes",
872
+ isArray
873
+ };
874
+ case "json": return {
875
+ type: "Json",
876
+ isArray
877
+ };
878
+ default:
879
+ if (t.startsWith("enum(")) return {
880
+ type: "String",
881
+ isArray
882
+ };
883
+ if (t.startsWith("set(")) return {
884
+ type: "String",
885
+ isArray
886
+ };
887
+ return {
888
+ type: "Unsupported",
889
+ isArray
890
+ };
891
+ }
892
+ },
893
+ getDefaultDatabaseType(type) {
894
+ switch (type) {
895
+ case "String": return {
896
+ type: "varchar",
897
+ precision: 191
898
+ };
899
+ case "Boolean": return { type: "boolean" };
900
+ case "Int": return { type: "int" };
901
+ case "BigInt": return { type: "bigint" };
902
+ case "Float": return { type: "double" };
903
+ case "Decimal": return {
904
+ type: "decimal",
905
+ precision: 65
906
+ };
907
+ case "DateTime": return {
908
+ type: "datetime",
909
+ precision: 3
910
+ };
911
+ case "Json": return { type: "json" };
912
+ case "Bytes": return { type: "longblob" };
913
+ }
914
+ },
915
+ async introspect(connectionString, options) {
916
+ const connection = await (await import("mysql2/promise")).createConnection(connectionString);
917
+ try {
918
+ const databaseName = new URL(connectionString).pathname.replace("/", "");
919
+ if (!databaseName) throw new CliError("Database name not found in connection string");
920
+ const [tableRows] = await connection.execute(getTableIntrospectionQuery(), [databaseName]);
921
+ const tables = [];
922
+ for (const row of tableRows) {
923
+ const columns = typeof row.columns === "string" ? JSON.parse(row.columns) : row.columns;
924
+ const indexes = typeof row.indexes === "string" ? JSON.parse(row.indexes) : row.indexes;
925
+ const sortedColumns = (columns || []).sort((a, b) => (a.ordinal_position ?? 0) - (b.ordinal_position ?? 0)).map((col) => {
926
+ if (col.datatype === "enum" && col.datatype_name) return {
927
+ ...col,
928
+ datatype_name: resolveNameCasing(options.modelCasing, col.datatype_name).name
929
+ };
930
+ if (col.computed && typeof col.datatype === "string") return {
931
+ ...col,
932
+ datatype: normalizeGenerationExpression(col.datatype)
933
+ };
934
+ return col;
935
+ });
936
+ const filteredIndexes = (indexes || []).filter((idx) => !(idx.columns.length === 1 && idx.name === `${row.name}_${idx.columns[0]?.name}_fkey`));
937
+ tables.push({
938
+ schema: "",
939
+ name: row.name,
940
+ type: row.type,
941
+ definition: row.definition,
942
+ columns: sortedColumns,
943
+ indexes: filteredIndexes
944
+ });
945
+ }
946
+ const [enumRows] = await connection.execute(getEnumIntrospectionQuery(), [databaseName]);
947
+ return {
948
+ tables,
949
+ enums: enumRows.map((row) => {
950
+ const values = parseEnumValues(row.column_type);
951
+ const syntheticName = `${row.table_name}_${row.column_name}`;
952
+ const { name } = resolveNameCasing(options.modelCasing, syntheticName);
953
+ return {
954
+ schema_name: "",
955
+ enum_type: name,
956
+ values
957
+ };
958
+ })
959
+ };
960
+ } finally {
961
+ await connection.end();
962
+ }
963
+ },
964
+ getDefaultValue({ defaultValue, fieldType, datatype, datatype_name, services, enums }) {
965
+ const val = defaultValue.trim();
966
+ if (val.toUpperCase() === "NULL") return null;
967
+ if (datatype === "enum" && datatype_name) {
968
+ const enumDef = enums.find((e) => getDbName(e) === datatype_name);
969
+ if (enumDef) {
970
+ const enumValue = val.startsWith("'") && val.endsWith("'") ? val.slice(1, -1) : val;
971
+ const enumField = enumDef.fields.find((f) => getDbName(f) === enumValue);
972
+ if (enumField) return (ab) => ab.ReferenceExpr.setTarget(enumField);
973
+ }
974
+ }
975
+ switch (fieldType) {
976
+ case "DateTime":
977
+ if (/^CURRENT_TIMESTAMP(\(\d*\))?$/i.test(val) || val.toLowerCase() === "current_timestamp()" || val.toLowerCase() === "now()") return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("now", services));
978
+ return (ab) => ab.StringLiteral.setValue(val);
979
+ case "Int":
980
+ case "BigInt":
981
+ if (val.toLowerCase() === "auto_increment") return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("autoincrement", services));
982
+ return (ab) => ab.NumberLiteral.setValue(val);
983
+ case "Float": return normalizeFloatDefault(val);
984
+ case "Decimal": return normalizeDecimalDefault(val);
985
+ case "Boolean": return (ab) => ab.BooleanLiteral.setValue(val.toLowerCase() === "true" || val === "1" || val === "b'1'");
986
+ case "String":
987
+ if (val.toLowerCase() === "uuid()") return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("uuid", services));
988
+ return (ab) => ab.StringLiteral.setValue(val);
989
+ case "Json": return (ab) => ab.StringLiteral.setValue(val);
990
+ case "Bytes": return (ab) => ab.StringLiteral.setValue(val);
991
+ }
992
+ if (val.includes("(") && val.includes(")")) return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("dbgenerated", services)).addArg((a) => a.setValue((v) => v.StringLiteral.setValue(val)));
993
+ console.warn(`Unsupported default value type: "${defaultValue}" for field type "${fieldType}". Skipping default value.`);
994
+ return null;
995
+ },
996
+ getFieldAttributes({ fieldName, fieldType, datatype, length, precision, services }) {
997
+ const factories = [];
998
+ if (fieldType === "DateTime" && (fieldName.toLowerCase() === "updatedat" || fieldName.toLowerCase() === "updated_at")) factories.push(new DataFieldAttributeFactory().setDecl(getAttributeRef("@updatedAt", services)));
999
+ const dbAttr = services.shared.workspace.IndexManager.allElements("Attribute").find((d) => d.name.toLowerCase() === `@db.${datatype.toLowerCase()}`)?.node;
1000
+ const defaultDatabaseType = this.getDefaultDatabaseType(fieldType);
1001
+ if (dbAttr && defaultDatabaseType && (defaultDatabaseType.type !== datatype || defaultDatabaseType.precision && defaultDatabaseType.precision !== (length ?? precision))) {
1002
+ const dbAttrFactory = new DataFieldAttributeFactory().setDecl(dbAttr);
1003
+ const sizeValue = length ?? precision;
1004
+ if (sizeValue !== void 0 && sizeValue !== null) dbAttrFactory.addArg((a) => a.NumberLiteral.setValue(sizeValue));
1005
+ factories.push(dbAttrFactory);
1006
+ }
1007
+ return factories;
1008
+ }
1009
+ };
1010
+ function getTableIntrospectionQuery() {
1011
+ return `
1012
+ -- Main query: one row per table/view with columns and indexes as nested JSON arrays.
1013
+ -- Uses INFORMATION_SCHEMA which is MySQL's standard metadata catalog.
1014
+ SELECT
1015
+ t.TABLE_NAME AS \`name\`, -- table or view name
1016
+ CASE t.TABLE_TYPE -- map MySQL table type strings to our internal types
1017
+ WHEN 'BASE TABLE' THEN 'table'
1018
+ WHEN 'VIEW' THEN 'view'
1019
+ ELSE NULL
1020
+ END AS \`type\`,
1021
+ CASE -- for views, retrieve the SQL definition
1022
+ WHEN t.TABLE_TYPE = 'VIEW' THEN v.VIEW_DEFINITION
1023
+ ELSE NULL
1024
+ END AS \`definition\`,
1025
+
1026
+ -- ===== COLUMNS subquery =====
1027
+ -- Wraps an ordered subquery in JSON_ARRAYAGG to produce a JSON array of column objects.
1028
+ (
1029
+ SELECT JSON_ARRAYAGG(col_json)
1030
+ FROM (
1031
+ SELECT JSON_OBJECT(
1032
+ 'ordinal_position', c.ORDINAL_POSITION, -- column position (used for sorting)
1033
+ 'name', c.COLUMN_NAME, -- column name
1034
+
1035
+ -- datatype: for generated/computed columns, construct the full DDL-like type definition
1036
+ -- (e.g., "int GENERATED ALWAYS AS (col1 + col2) STORED") so it can be rendered as
1037
+ -- Unsupported("..."); special-case tinyint(1) as 'boolean' (MySQL's boolean convention);
1038
+ -- otherwise use the DATA_TYPE (e.g., 'int', 'varchar', 'datetime').
1039
+ 'datatype', CASE
1040
+ WHEN c.GENERATION_EXPRESSION IS NOT NULL AND c.GENERATION_EXPRESSION != '' THEN
1041
+ CONCAT(
1042
+ c.COLUMN_TYPE,
1043
+ ' GENERATED ALWAYS AS (',
1044
+ c.GENERATION_EXPRESSION,
1045
+ ') ',
1046
+ CASE
1047
+ WHEN c.EXTRA LIKE '%STORED GENERATED%' THEN 'STORED'
1048
+ ELSE 'VIRTUAL'
1049
+ END
1050
+ )
1051
+ WHEN c.DATA_TYPE = 'tinyint' AND c.COLUMN_TYPE = 'tinyint(1)' THEN 'boolean'
1052
+ ELSE c.DATA_TYPE
1053
+ END,
1054
+
1055
+ -- datatype_name: for enum columns, generate a synthetic name "TableName_ColumnName"
1056
+ -- (MySQL doesn't have named enum types like PostgreSQL)
1057
+ 'datatype_name', CASE
1058
+ WHEN c.DATA_TYPE = 'enum' THEN CONCAT(t.TABLE_NAME, '_', c.COLUMN_NAME)
1059
+ ELSE NULL
1060
+ END,
1061
+
1062
+ 'datatype_schema', '', -- MySQL doesn't support multi-schema
1063
+ 'length', c.CHARACTER_MAXIMUM_LENGTH, -- max length for string types (e.g., VARCHAR(255) -> 255)
1064
+ 'precision', COALESCE(c.NUMERIC_PRECISION, c.DATETIME_PRECISION), -- numeric or datetime precision
1065
+
1066
+ 'nullable', c.IS_NULLABLE = 'YES', -- true if column allows NULL
1067
+
1068
+ -- default: for auto_increment columns, report 'auto_increment' instead of NULL;
1069
+ -- otherwise use the COLUMN_DEFAULT value
1070
+ 'default', CASE
1071
+ WHEN c.EXTRA LIKE '%auto_increment%' THEN 'auto_increment'
1072
+ ELSE c.COLUMN_DEFAULT
1073
+ END,
1074
+
1075
+ 'pk', c.COLUMN_KEY = 'PRI', -- true if column is part of the primary key
1076
+
1077
+ -- unique: true if the column has a single-column unique index.
1078
+ -- COLUMN_KEY = 'UNI' covers most cases, but may not be set when the column
1079
+ -- also participates in other indexes (showing 'MUL' instead on some MySQL versions).
1080
+ -- Also check INFORMATION_SCHEMA.STATISTICS for single-column unique indexes
1081
+ -- (NON_UNIQUE = 0) to match the PostgreSQL introspection behavior.
1082
+ 'unique', (
1083
+ c.COLUMN_KEY = 'UNI'
1084
+ OR EXISTS (
1085
+ SELECT 1
1086
+ FROM INFORMATION_SCHEMA.STATISTICS s_uni
1087
+ WHERE s_uni.TABLE_SCHEMA = c.TABLE_SCHEMA
1088
+ AND s_uni.TABLE_NAME = c.TABLE_NAME
1089
+ AND s_uni.COLUMN_NAME = c.COLUMN_NAME
1090
+ AND s_uni.NON_UNIQUE = 0
1091
+ AND s_uni.INDEX_NAME != 'PRIMARY'
1092
+ AND (
1093
+ SELECT COUNT(*)
1094
+ FROM INFORMATION_SCHEMA.STATISTICS s_cnt
1095
+ WHERE s_cnt.TABLE_SCHEMA = s_uni.TABLE_SCHEMA
1096
+ AND s_cnt.TABLE_NAME = s_uni.TABLE_NAME
1097
+ AND s_cnt.INDEX_NAME = s_uni.INDEX_NAME
1098
+ ) = 1
1099
+ )
1100
+ ),
1101
+ 'unique_name', (
1102
+ SELECT COALESCE(
1103
+ CASE WHEN c.COLUMN_KEY = 'UNI' THEN c.COLUMN_NAME ELSE NULL END,
1104
+ (
1105
+ SELECT s_uni.INDEX_NAME
1106
+ FROM INFORMATION_SCHEMA.STATISTICS s_uni
1107
+ WHERE s_uni.TABLE_SCHEMA = c.TABLE_SCHEMA
1108
+ AND s_uni.TABLE_NAME = c.TABLE_NAME
1109
+ AND s_uni.COLUMN_NAME = c.COLUMN_NAME
1110
+ AND s_uni.NON_UNIQUE = 0
1111
+ AND s_uni.INDEX_NAME != 'PRIMARY'
1112
+ AND (
1113
+ SELECT COUNT(*)
1114
+ FROM INFORMATION_SCHEMA.STATISTICS s_cnt
1115
+ WHERE s_cnt.TABLE_SCHEMA = s_uni.TABLE_SCHEMA
1116
+ AND s_cnt.TABLE_NAME = s_uni.TABLE_NAME
1117
+ AND s_cnt.INDEX_NAME = s_uni.INDEX_NAME
1118
+ ) = 1
1119
+ LIMIT 1
1120
+ )
1121
+ )
1122
+ ),
1123
+
1124
+ -- computed: true if column has a generation expression (virtual or stored)
1125
+ 'computed', c.GENERATION_EXPRESSION IS NOT NULL AND c.GENERATION_EXPRESSION != '',
1126
+
1127
+ -- options: for enum columns, the full COLUMN_TYPE string (e.g., "enum('a','b','c')")
1128
+ -- which gets parsed into individual values later
1129
+ 'options', CASE
1130
+ WHEN c.DATA_TYPE = 'enum' THEN c.COLUMN_TYPE
1131
+ ELSE NULL
1132
+ END,
1133
+
1134
+ -- Foreign key info (NULL if column is not part of a FK)
1135
+ 'foreign_key_schema', NULL, -- MySQL doesn't support cross-schema FKs here
1136
+ 'foreign_key_table', kcu_fk.REFERENCED_TABLE_NAME, -- referenced table
1137
+ 'foreign_key_column', kcu_fk.REFERENCED_COLUMN_NAME, -- referenced column
1138
+ 'foreign_key_name', kcu_fk.CONSTRAINT_NAME, -- FK constraint name
1139
+ 'foreign_key_on_update', rc.UPDATE_RULE, -- referential action on update (CASCADE, SET NULL, etc.)
1140
+ 'foreign_key_on_delete', rc.DELETE_RULE -- referential action on delete
1141
+ ) AS col_json
1142
+
1143
+ FROM INFORMATION_SCHEMA.COLUMNS c -- one row per column in the database
1144
+
1145
+ -- Join KEY_COLUMN_USAGE to find foreign key references for this column.
1146
+ -- Filter to only FK entries (REFERENCED_TABLE_NAME IS NOT NULL).
1147
+ LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu_fk
1148
+ ON c.TABLE_SCHEMA = kcu_fk.TABLE_SCHEMA
1149
+ AND c.TABLE_NAME = kcu_fk.TABLE_NAME
1150
+ AND c.COLUMN_NAME = kcu_fk.COLUMN_NAME
1151
+ AND kcu_fk.REFERENCED_TABLE_NAME IS NOT NULL
1152
+
1153
+ -- Join REFERENTIAL_CONSTRAINTS to get ON UPDATE / ON DELETE rules for the FK.
1154
+ LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
1155
+ ON kcu_fk.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
1156
+ AND kcu_fk.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
1157
+
1158
+ WHERE c.TABLE_SCHEMA = t.TABLE_SCHEMA
1159
+ AND c.TABLE_NAME = t.TABLE_NAME
1160
+ ORDER BY c.ORDINAL_POSITION -- preserve original column order
1161
+ ) AS cols_ordered
1162
+ ) AS \`columns\`,
1163
+
1164
+ -- ===== INDEXES subquery =====
1165
+ -- Aggregates all indexes for this table into a JSON array.
1166
+ (
1167
+ SELECT JSON_ARRAYAGG(idx_json)
1168
+ FROM (
1169
+ SELECT JSON_OBJECT(
1170
+ 'name', s.INDEX_NAME, -- index name (e.g., 'PRIMARY', 'idx_email')
1171
+ 'method', s.INDEX_TYPE, -- index type (e.g., 'BTREE', 'HASH', 'FULLTEXT')
1172
+ 'unique', s.NON_UNIQUE = 0, -- NON_UNIQUE=0 means it IS unique
1173
+ 'primary', s.INDEX_NAME = 'PRIMARY', -- MySQL names the PK index 'PRIMARY'
1174
+ 'valid', TRUE, -- MySQL doesn't expose index validity status
1175
+ 'ready', TRUE, -- MySQL doesn't expose index readiness status
1176
+ 'partial', FALSE, -- MySQL doesn't support partial indexes
1177
+ 'predicate', NULL, -- no WHERE clause on indexes in MySQL
1178
+
1179
+ -- Index columns: nested subquery for columns in this index
1180
+ 'columns', (
1181
+ SELECT JSON_ARRAYAGG(idx_col_json)
1182
+ FROM (
1183
+ SELECT JSON_OBJECT(
1184
+ 'name', s2.COLUMN_NAME, -- column name in the index
1185
+ 'expression', NULL, -- MySQL doesn't expose expression indexes via STATISTICS
1186
+ -- COLLATION: 'A' = ascending, 'D' = descending, NULL = not sorted
1187
+ 'order', CASE s2.COLLATION WHEN 'A' THEN 'ASC' WHEN 'D' THEN 'DESC' ELSE NULL END,
1188
+ 'nulls', NULL -- MySQL doesn't expose NULLS FIRST/LAST
1189
+ ) AS idx_col_json
1190
+ FROM INFORMATION_SCHEMA.STATISTICS s2 -- one row per column per index
1191
+ WHERE s2.TABLE_SCHEMA = s.TABLE_SCHEMA
1192
+ AND s2.TABLE_NAME = s.TABLE_NAME
1193
+ AND s2.INDEX_NAME = s.INDEX_NAME
1194
+ ORDER BY s2.SEQ_IN_INDEX -- preserve column order within the index
1195
+ ) AS idx_cols_ordered
1196
+ )
1197
+ ) AS idx_json
1198
+ FROM (
1199
+ -- Deduplicate: STATISTICS has one row per (index, column), but we need one row per index.
1200
+ -- DISTINCT on INDEX_NAME gives us one entry per index with its metadata.
1201
+ SELECT DISTINCT INDEX_NAME, INDEX_TYPE, NON_UNIQUE, TABLE_SCHEMA, TABLE_NAME
1202
+ FROM INFORMATION_SCHEMA.STATISTICS
1203
+ WHERE TABLE_SCHEMA = t.TABLE_SCHEMA AND TABLE_NAME = t.TABLE_NAME
1204
+ ) s
1205
+ ) AS idxs_ordered
1206
+ ) AS \`indexes\`
1207
+
1208
+ -- === Main FROM: INFORMATION_SCHEMA.TABLES lists all tables and views ===
1209
+ FROM INFORMATION_SCHEMA.TABLES t
1210
+ -- Join VIEWS to get VIEW_DEFINITION for view tables
1211
+ LEFT JOIN INFORMATION_SCHEMA.VIEWS v
1212
+ ON t.TABLE_SCHEMA = v.TABLE_SCHEMA AND t.TABLE_NAME = v.TABLE_NAME
1213
+ WHERE t.TABLE_SCHEMA = ? -- only the target database
1214
+ AND t.TABLE_TYPE IN ('BASE TABLE', 'VIEW') -- exclude system tables like SYSTEM VIEW
1215
+ AND t.TABLE_NAME <> '_prisma_migrations' -- exclude Prisma migration tracking table
1216
+ ORDER BY t.TABLE_NAME;
1217
+ `;
1218
+ }
1219
+ function getEnumIntrospectionQuery() {
1220
+ return `
1221
+ SELECT
1222
+ c.TABLE_NAME AS table_name, -- table containing the enum column
1223
+ c.COLUMN_NAME AS column_name, -- column name
1224
+ c.COLUMN_TYPE AS column_type -- full type string including values (e.g., "enum('val1','val2')")
1225
+ FROM INFORMATION_SCHEMA.COLUMNS c
1226
+ WHERE c.TABLE_SCHEMA = ? -- only the target database
1227
+ AND c.DATA_TYPE = 'enum' -- only enum columns
1228
+ ORDER BY c.TABLE_NAME, c.COLUMN_NAME;
1229
+ `;
1230
+ }
1231
+ /**
1232
+ * Parse enum values from MySQL COLUMN_TYPE string like "enum('val1','val2','val3')"
1233
+ */
1234
+ function parseEnumValues(columnType) {
1235
+ const match = columnType.match(/^enum\((.+)\)$/i);
1236
+ if (!match || !match[1]) return [];
1237
+ const valuesString = match[1];
1238
+ const values = [];
1239
+ let current = "";
1240
+ let inQuote = false;
1241
+ let i = 0;
1242
+ while (i < valuesString.length) {
1243
+ const char = valuesString[i];
1244
+ if (char === "'" && !inQuote) {
1245
+ inQuote = true;
1246
+ i++;
1247
+ continue;
1248
+ }
1249
+ if (char === "'" && inQuote) {
1250
+ if (valuesString[i + 1] === "'") {
1251
+ current += "'";
1252
+ i += 2;
1253
+ continue;
1254
+ }
1255
+ values.push(current);
1256
+ current = "";
1257
+ inQuote = false;
1258
+ i++;
1259
+ while (i < valuesString.length && (valuesString[i] === "," || valuesString[i] === " ")) i++;
1260
+ continue;
1261
+ }
1262
+ if (inQuote) current += char;
1263
+ i++;
1264
+ }
1265
+ return values;
1266
+ }
1267
+ //#endregion
1268
+ //#region src/actions/pull/provider/postgresql.ts
1269
+ /**
1270
+ * Maps PostgreSQL internal type names to their standard SQL names for comparison.
1271
+ * This is used to normalize type names when checking against default database types.
1272
+ */
1273
+ const pgTypnameToStandard = {
1274
+ int2: "smallint",
1275
+ int4: "integer",
1276
+ int8: "bigint",
1277
+ float4: "real",
1278
+ float8: "double precision",
1279
+ bool: "boolean",
1280
+ bpchar: "character",
1281
+ numeric: "decimal"
1282
+ };
1283
+ /**
1284
+ * Standard bit widths for integer/float types that shouldn't be added as precision arguments.
1285
+ * PostgreSQL returns these as precision values, but they're implicit for the type.
1286
+ */
1287
+ const standardTypePrecisions = {
1288
+ int2: 16,
1289
+ smallint: 16,
1290
+ int4: 32,
1291
+ integer: 32,
1292
+ int8: 64,
1293
+ bigint: 64,
1294
+ float4: 24,
1295
+ real: 24,
1296
+ float8: 53,
1297
+ "double precision": 53
1298
+ };
1299
+ /**
1300
+ * Maps PostgreSQL typnames (from pg_type.typname) to ZenStack native type attribute names.
1301
+ * PostgreSQL introspection returns internal type names like 'int2', 'int4', 'float8', 'bpchar',
1302
+ * but ZenStack attributes are named @db.SmallInt, @db.Integer, @db.DoublePrecision, @db.Char, etc.
1303
+ */
1304
+ const pgTypnameToZenStackNativeType = {
1305
+ int2: "SmallInt",
1306
+ smallint: "SmallInt",
1307
+ int4: "Integer",
1308
+ integer: "Integer",
1309
+ int8: "BigInt",
1310
+ bigint: "BigInt",
1311
+ numeric: "Decimal",
1312
+ decimal: "Decimal",
1313
+ float4: "Real",
1314
+ real: "Real",
1315
+ float8: "DoublePrecision",
1316
+ "double precision": "DoublePrecision",
1317
+ bool: "Boolean",
1318
+ boolean: "Boolean",
1319
+ text: "Text",
1320
+ varchar: "VarChar",
1321
+ "character varying": "VarChar",
1322
+ bpchar: "Char",
1323
+ character: "Char",
1324
+ uuid: "Uuid",
1325
+ date: "Date",
1326
+ time: "Time",
1327
+ timetz: "Timetz",
1328
+ timestamp: "Timestamp",
1329
+ timestamptz: "Timestamptz",
1330
+ bytea: "ByteA",
1331
+ json: "Json",
1332
+ jsonb: "JsonB",
1333
+ xml: "Xml",
1334
+ inet: "Inet",
1335
+ bit: "Bit",
1336
+ varbit: "VarBit",
1337
+ oid: "Oid",
1338
+ money: "Money",
1339
+ citext: "Citext"
1340
+ };
1341
+ const postgresql = {
1342
+ isSupportedFeature(feature) {
1343
+ return ["Schema", "NativeEnum"].includes(feature);
1344
+ },
1345
+ getBuiltinType(type) {
1346
+ const t = (type || "").toLowerCase();
1347
+ const isArray = t.startsWith("_");
1348
+ switch (t.replace(/^_/, "")) {
1349
+ case "int2":
1350
+ case "smallint":
1351
+ case "int4":
1352
+ case "integer": return {
1353
+ type: "Int",
1354
+ isArray
1355
+ };
1356
+ case "int8":
1357
+ case "bigint": return {
1358
+ type: "BigInt",
1359
+ isArray
1360
+ };
1361
+ case "numeric":
1362
+ case "decimal": return {
1363
+ type: "Decimal",
1364
+ isArray
1365
+ };
1366
+ case "float4":
1367
+ case "real":
1368
+ case "float8":
1369
+ case "double precision": return {
1370
+ type: "Float",
1371
+ isArray
1372
+ };
1373
+ case "bool":
1374
+ case "boolean": return {
1375
+ type: "Boolean",
1376
+ isArray
1377
+ };
1378
+ case "text":
1379
+ case "varchar":
1380
+ case "bpchar":
1381
+ case "character varying":
1382
+ case "character": return {
1383
+ type: "String",
1384
+ isArray
1385
+ };
1386
+ case "uuid": return {
1387
+ type: "String",
1388
+ isArray
1389
+ };
1390
+ case "date":
1391
+ case "time":
1392
+ case "timetz":
1393
+ case "timestamp":
1394
+ case "timestamptz": return {
1395
+ type: "DateTime",
1396
+ isArray
1397
+ };
1398
+ case "bytea": return {
1399
+ type: "Bytes",
1400
+ isArray
1401
+ };
1402
+ case "json":
1403
+ case "jsonb": return {
1404
+ type: "Json",
1405
+ isArray
1406
+ };
1407
+ default: return {
1408
+ type: "Unsupported",
1409
+ isArray
1410
+ };
1411
+ }
1412
+ },
1413
+ async introspect(connectionString, options) {
1414
+ const { Client } = await import("pg");
1415
+ const client = new Client({ connectionString });
1416
+ await client.connect();
1417
+ try {
1418
+ const { rows: tables } = await client.query(tableIntrospectionQuery);
1419
+ const { rows: enums } = await client.query(enumIntrospectionQuery);
1420
+ const filteredTables = tables.filter((t) => options.schemas.includes(t.schema));
1421
+ return {
1422
+ enums: enums.filter((e) => options.schemas.includes(e.schema_name)),
1423
+ tables: filteredTables
1424
+ };
1425
+ } finally {
1426
+ await client.end();
1427
+ }
1428
+ },
1429
+ getDefaultDatabaseType(type) {
1430
+ switch (type) {
1431
+ case "String": return { type: "text" };
1432
+ case "Boolean": return { type: "boolean" };
1433
+ case "Int": return { type: "integer" };
1434
+ case "BigInt": return { type: "bigint" };
1435
+ case "Float": return { type: "double precision" };
1436
+ case "Decimal": return { type: "decimal" };
1437
+ case "DateTime": return {
1438
+ type: "timestamp",
1439
+ precision: 3
1440
+ };
1441
+ case "Json": return { type: "jsonb" };
1442
+ case "Bytes": return { type: "bytea" };
1443
+ }
1444
+ },
1445
+ getDefaultValue({ defaultValue, fieldType, datatype, datatype_name, services, enums }) {
1446
+ const val = defaultValue.trim();
1447
+ if (datatype === "enum" && datatype_name) {
1448
+ const enumDef = enums.find((e) => getDbName(e) === datatype_name);
1449
+ if (enumDef) {
1450
+ const enumValue = val.replace(/'/g, "").split("::")[0]?.trim();
1451
+ const enumField = enumDef.fields.find((f) => getDbName(f) === enumValue);
1452
+ if (enumField) return (ab) => ab.ReferenceExpr.setTarget(enumField);
1453
+ }
1454
+ return typeCastingConvert({
1455
+ defaultValue,
1456
+ enums,
1457
+ val,
1458
+ services
1459
+ });
1460
+ }
1461
+ switch (fieldType) {
1462
+ case "DateTime":
1463
+ if (val === "CURRENT_TIMESTAMP" || val === "now()") return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("now", services));
1464
+ if (val.includes("::")) return typeCastingConvert({
1465
+ defaultValue,
1466
+ enums,
1467
+ val,
1468
+ services
1469
+ });
1470
+ return (ab) => ab.StringLiteral.setValue(val);
1471
+ case "Int":
1472
+ case "BigInt":
1473
+ if (val.startsWith("nextval(")) return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("autoincrement", services));
1474
+ if (val.includes("::")) return typeCastingConvert({
1475
+ defaultValue,
1476
+ enums,
1477
+ val,
1478
+ services
1479
+ });
1480
+ return (ab) => ab.NumberLiteral.setValue(val);
1481
+ case "Float":
1482
+ if (val.includes("::")) return typeCastingConvert({
1483
+ defaultValue,
1484
+ enums,
1485
+ val,
1486
+ services
1487
+ });
1488
+ return normalizeFloatDefault(val);
1489
+ case "Decimal":
1490
+ if (val.includes("::")) return typeCastingConvert({
1491
+ defaultValue,
1492
+ enums,
1493
+ val,
1494
+ services
1495
+ });
1496
+ return normalizeDecimalDefault(val);
1497
+ case "Boolean": return (ab) => ab.BooleanLiteral.setValue(val === "true");
1498
+ case "String":
1499
+ if (val.includes("::")) return typeCastingConvert({
1500
+ defaultValue,
1501
+ enums,
1502
+ val,
1503
+ services
1504
+ });
1505
+ if (val.startsWith("'") && val.endsWith("'")) return (ab) => ab.StringLiteral.setValue(val.slice(1, -1).replace(/''/g, "'"));
1506
+ return (ab) => ab.StringLiteral.setValue(val);
1507
+ case "Json":
1508
+ if (val.includes("::")) return typeCastingConvert({
1509
+ defaultValue,
1510
+ enums,
1511
+ val,
1512
+ services
1513
+ });
1514
+ return (ab) => ab.StringLiteral.setValue(val);
1515
+ case "Bytes":
1516
+ if (val.includes("::")) return typeCastingConvert({
1517
+ defaultValue,
1518
+ enums,
1519
+ val,
1520
+ services
1521
+ });
1522
+ return (ab) => ab.StringLiteral.setValue(val);
1523
+ }
1524
+ if (val.includes("(") && val.includes(")")) return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("dbgenerated", services)).addArg((a) => a.setValue((v) => v.StringLiteral.setValue(val)));
1525
+ console.warn(`Unsupported default value type: "${defaultValue}" for field type "${fieldType}". Skipping default value.`);
1526
+ return null;
1527
+ },
1528
+ getFieldAttributes({ fieldName, fieldType, datatype, length, precision, services }) {
1529
+ const factories = [];
1530
+ if (fieldType === "DateTime" && (fieldName.toLowerCase() === "updatedat" || fieldName.toLowerCase() === "updated_at")) factories.push(new DataFieldAttributeFactory().setDecl(getAttributeRef("@updatedAt", services)));
1531
+ const nativeTypeName = pgTypnameToZenStackNativeType[datatype.toLowerCase()] ?? datatype;
1532
+ const dbAttr = services.shared.workspace.IndexManager.allElements("Attribute").find((d) => d.name.toLowerCase() === `@db.${nativeTypeName.toLowerCase()}`)?.node;
1533
+ const defaultDatabaseType = this.getDefaultDatabaseType(fieldType);
1534
+ const normalizedDatatype = pgTypnameToStandard[datatype.toLowerCase()] ?? datatype.toLowerCase();
1535
+ const standardPrecision = standardTypePrecisions[datatype.toLowerCase()];
1536
+ const isStandardPrecision = standardPrecision !== void 0 && precision === standardPrecision;
1537
+ if (dbAttr && defaultDatabaseType && (defaultDatabaseType.type !== normalizedDatatype || defaultDatabaseType.precision && defaultDatabaseType.precision !== (length ?? precision))) {
1538
+ const dbAttrFactory = new DataFieldAttributeFactory().setDecl(dbAttr);
1539
+ if ((length || precision) && !isStandardPrecision) dbAttrFactory.addArg((a) => a.NumberLiteral.setValue(length || precision));
1540
+ factories.push(dbAttrFactory);
1541
+ }
1542
+ return factories;
1543
+ }
1544
+ };
1545
+ const enumIntrospectionQuery = `
1546
+ SELECT
1547
+ n.nspname AS schema_name, -- schema the enum belongs to (e.g., 'public')
1548
+ t.typname AS enum_type, -- enum type name as defined in CREATE TYPE
1549
+ coalesce(json_agg(e.enumlabel ORDER BY e.enumsortorder), '[]') AS values -- ordered list of enum labels as JSON array
1550
+ FROM pg_type t -- pg_type: catalog of all data types
1551
+ JOIN pg_enum e ON t.oid = e.enumtypid -- pg_enum: one row per enum label; join to get labels for this enum type
1552
+ JOIN pg_namespace n ON n.oid = t.typnamespace -- pg_namespace: schema info; join to get the schema name
1553
+ GROUP BY schema_name, enum_type -- one row per enum type, with all labels aggregated
1554
+ ORDER BY schema_name, enum_type;`;
1555
+ const tableIntrospectionQuery = `
1556
+ -- Main query: one row per table/view with columns and indexes as nested JSON arrays.
1557
+ -- Joins pg_class (tables/views) with pg_namespace (schemas).
1558
+ SELECT
1559
+ "ns"."nspname" AS "schema", -- schema name (e.g., 'public')
1560
+ "cls"."relname" AS "name", -- table or view name
1561
+ CASE "cls"."relkind" -- relkind: 'r' = ordinary table, 'v' = view
1562
+ WHEN 'r' THEN 'table'
1563
+ WHEN 'v' THEN 'view'
1564
+ ELSE NULL
1565
+ END AS "type",
1566
+ CASE -- for views, retrieve the SQL definition
1567
+ WHEN "cls"."relkind" = 'v' THEN pg_get_viewdef("cls"."oid", true)
1568
+ ELSE NULL
1569
+ END AS "definition",
1570
+
1571
+ -- ===== COLUMNS subquery =====
1572
+ -- Aggregates all columns for this table into a JSON array.
1573
+ (
1574
+ SELECT coalesce(json_agg(agg), '[]')
1575
+ FROM (
1576
+ SELECT
1577
+ "att"."attname" AS "name", -- column name
1578
+
1579
+ -- datatype: if the type is an enum, report 'enum';
1580
+ -- if the column is generated/computed, construct the full DDL-like type definition
1581
+ -- (e.g., "text GENERATED ALWAYS AS (expr) STORED") so it can be rendered as Unsupported("...");
1582
+ -- otherwise use the pg_type name.
1583
+ CASE
1584
+ WHEN EXISTS (
1585
+ SELECT 1 FROM "pg_catalog"."pg_enum" AS "e"
1586
+ WHERE "e"."enumtypid" = "typ"."oid"
1587
+ ) THEN 'enum'
1588
+ WHEN "att"."attgenerated" != '' THEN
1589
+ format_type("att"."atttypid", "att"."atttypmod")
1590
+ || ' GENERATED ALWAYS AS ('
1591
+ || pg_get_expr("def"."adbin", "def"."adrelid")
1592
+ || ') '
1593
+ || CASE "att"."attgenerated"
1594
+ WHEN 's' THEN 'STORED'
1595
+ WHEN 'v' THEN 'VIRTUAL'
1596
+ ELSE 'STORED'
1597
+ END
1598
+ ELSE "typ"."typname"::text -- internal type name (e.g., 'int4', 'varchar', 'text'); cast to text to prevent CASE from coercing result to name type (max 63 chars)
1599
+ END AS "datatype",
1600
+
1601
+ -- datatype_name: for enums only, the actual enum type name (used to look up the enum definition)
1602
+ CASE
1603
+ WHEN EXISTS (
1604
+ SELECT 1 FROM "pg_catalog"."pg_enum" AS "e"
1605
+ WHERE "e"."enumtypid" = "typ"."oid"
1606
+ ) THEN "typ"."typname"
1607
+ ELSE NULL
1608
+ END AS "datatype_name",
1609
+
1610
+ "tns"."nspname" AS "datatype_schema", -- schema where the data type is defined
1611
+ "c"."character_maximum_length" AS "length", -- max length for char/varchar types (from information_schema)
1612
+ COALESCE("c"."numeric_precision", "c"."datetime_precision") AS "precision", -- numeric or datetime precision
1613
+
1614
+ -- Foreign key info (NULL if column is not part of a FK constraint)
1615
+ "fk_ns"."nspname" AS "foreign_key_schema", -- schema of the referenced table
1616
+ "fk_cls"."relname" AS "foreign_key_table", -- referenced table name
1617
+ "fk_att"."attname" AS "foreign_key_column", -- referenced column name
1618
+ "fk_con"."conname" AS "foreign_key_name", -- FK constraint name
1619
+
1620
+ -- FK referential actions: decode single-char codes to human-readable strings
1621
+ CASE "fk_con"."confupdtype"
1622
+ WHEN 'a' THEN 'NO ACTION'
1623
+ WHEN 'r' THEN 'RESTRICT'
1624
+ WHEN 'c' THEN 'CASCADE'
1625
+ WHEN 'n' THEN 'SET NULL'
1626
+ WHEN 'd' THEN 'SET DEFAULT'
1627
+ ELSE NULL
1628
+ END AS "foreign_key_on_update",
1629
+ CASE "fk_con"."confdeltype"
1630
+ WHEN 'a' THEN 'NO ACTION'
1631
+ WHEN 'r' THEN 'RESTRICT'
1632
+ WHEN 'c' THEN 'CASCADE'
1633
+ WHEN 'n' THEN 'SET NULL'
1634
+ WHEN 'd' THEN 'SET DEFAULT'
1635
+ ELSE NULL
1636
+ END AS "foreign_key_on_delete",
1637
+
1638
+ -- pk: true if this column is part of the table's primary key constraint
1639
+ "pk_con"."conkey" IS NOT NULL AS "pk",
1640
+
1641
+ -- unique: true if the column has a single-column UNIQUE constraint OR a single-column unique index
1642
+ (
1643
+ -- Check for a single-column UNIQUE constraint (contype = 'u')
1644
+ EXISTS (
1645
+ SELECT 1
1646
+ FROM "pg_catalog"."pg_constraint" AS "u_con"
1647
+ WHERE "u_con"."contype" = 'u' -- 'u' = unique constraint
1648
+ AND "u_con"."conrelid" = "cls"."oid" -- on this table
1649
+ AND array_length("u_con"."conkey", 1) = 1 -- single-column only
1650
+ AND "att"."attnum" = ANY ("u_con"."conkey") -- this column is in the constraint
1651
+ )
1652
+ OR
1653
+ -- Check for a single-column unique index (may exist without an explicit constraint)
1654
+ EXISTS (
1655
+ SELECT 1
1656
+ FROM "pg_catalog"."pg_index" AS "u_idx"
1657
+ WHERE "u_idx"."indrelid" = "cls"."oid" -- on this table
1658
+ AND "u_idx"."indisunique" = TRUE -- it's a unique index
1659
+ AND "u_idx"."indnkeyatts" = 1 -- single key column
1660
+ AND "att"."attnum" = ANY ("u_idx"."indkey"::int2[]) -- this column is the key
1661
+ )
1662
+ ) AS "unique",
1663
+
1664
+ -- unique_name: the name of the unique constraint or index (whichever exists first)
1665
+ (
1666
+ SELECT COALESCE(
1667
+ -- Try constraint name first
1668
+ (
1669
+ SELECT "u_con"."conname"
1670
+ FROM "pg_catalog"."pg_constraint" AS "u_con"
1671
+ WHERE "u_con"."contype" = 'u'
1672
+ AND "u_con"."conrelid" = "cls"."oid"
1673
+ AND array_length("u_con"."conkey", 1) = 1
1674
+ AND "att"."attnum" = ANY ("u_con"."conkey")
1675
+ LIMIT 1
1676
+ ),
1677
+ -- Fall back to unique index name
1678
+ (
1679
+ SELECT "u_idx_cls"."relname"
1680
+ FROM "pg_catalog"."pg_index" AS "u_idx"
1681
+ JOIN "pg_catalog"."pg_class" AS "u_idx_cls" ON "u_idx"."indexrelid" = "u_idx_cls"."oid"
1682
+ WHERE "u_idx"."indrelid" = "cls"."oid"
1683
+ AND "u_idx"."indisunique" = TRUE
1684
+ AND "u_idx"."indnkeyatts" = 1
1685
+ AND "att"."attnum" = ANY ("u_idx"."indkey"::int2[])
1686
+ LIMIT 1
1687
+ )
1688
+ )
1689
+ ) AS "unique_name",
1690
+
1691
+ "att"."attgenerated" != '' AS "computed", -- true if column is a generated/computed column
1692
+ -- For generated columns, pg_attrdef stores the generation expression (not a default),
1693
+ -- so we must null it out to avoid emitting a spurious @default(dbgenerated(...)) attribute.
1694
+ CASE
1695
+ WHEN "att"."attgenerated" != '' THEN NULL
1696
+ ELSE pg_get_expr("def"."adbin", "def"."adrelid")
1697
+ END AS "default", -- column default expression as text (e.g., 'nextval(...)', '0', 'now()')
1698
+ "att"."attnotnull" != TRUE AS "nullable", -- true if column allows NULL values
1699
+
1700
+ -- options: for enum columns, aggregates all allowed enum labels into a JSON array
1701
+ coalesce(
1702
+ (
1703
+ SELECT json_agg("enm"."enumlabel") AS "o"
1704
+ FROM "pg_catalog"."pg_enum" AS "enm"
1705
+ WHERE "enm"."enumtypid" = "typ"."oid"
1706
+ ),
1707
+ '[]'
1708
+ ) AS "options"
1709
+
1710
+ -- === FROM / JOINs for the columns subquery ===
1711
+
1712
+ -- pg_attribute: one row per table column (attnum >= 0 excludes system columns)
1713
+ FROM "pg_catalog"."pg_attribute" AS "att"
1714
+
1715
+ -- pg_type: data type of the column (e.g., int4, text, custom_enum)
1716
+ INNER JOIN "pg_catalog"."pg_type" AS "typ" ON "typ"."oid" = "att"."atttypid"
1717
+
1718
+ -- pg_namespace for the type: needed to determine which schema the type lives in
1719
+ INNER JOIN "pg_catalog"."pg_namespace" AS "tns" ON "tns"."oid" = "typ"."typnamespace"
1720
+
1721
+ -- information_schema.columns: provides length/precision info not easily available from pg_catalog
1722
+ LEFT JOIN "information_schema"."columns" AS "c" ON "c"."table_schema" = "ns"."nspname"
1723
+ AND "c"."table_name" = "cls"."relname"
1724
+ AND "c"."column_name" = "att"."attname"
1725
+
1726
+ -- pg_constraint (primary key): join on contype='p' to detect if column is part of PK
1727
+ LEFT JOIN "pg_catalog"."pg_constraint" AS "pk_con" ON "pk_con"."contype" = 'p'
1728
+ AND "pk_con"."conrelid" = "cls"."oid"
1729
+ AND "att"."attnum" = ANY ("pk_con"."conkey")
1730
+
1731
+ -- pg_constraint (foreign key): join on contype='f' to get FK details for this column
1732
+ LEFT JOIN "pg_catalog"."pg_constraint" AS "fk_con" ON "fk_con"."contype" = 'f'
1733
+ AND "fk_con"."conrelid" = "cls"."oid"
1734
+ AND "att"."attnum" = ANY ("fk_con"."conkey")
1735
+
1736
+ -- pg_class for FK target table: resolve the referenced table's OID to its name
1737
+ LEFT JOIN "pg_catalog"."pg_class" AS "fk_cls" ON "fk_cls"."oid" = "fk_con"."confrelid"
1738
+
1739
+ -- pg_namespace for FK target: get the schema of the referenced table
1740
+ LEFT JOIN "pg_catalog"."pg_namespace" AS "fk_ns" ON "fk_ns"."oid" = "fk_cls"."relnamespace"
1741
+
1742
+ -- pg_attribute for FK target column: resolve the referenced column number to its name.
1743
+ -- Use array_position to correlate by position: find this source column's index in conkey,
1744
+ -- then pick the referenced attnum at that same index from confkey.
1745
+ -- This ensures composite FKs correctly map each source column to its corresponding target column.
1746
+ LEFT JOIN "pg_catalog"."pg_attribute" AS "fk_att" ON "fk_att"."attrelid" = "fk_cls"."oid"
1747
+ AND "fk_att"."attnum" = "fk_con"."confkey"[array_position("fk_con"."conkey", "att"."attnum")]
1748
+
1749
+ -- pg_attrdef: column defaults; adbin contains the internal expression, decoded via pg_get_expr()
1750
+ LEFT JOIN "pg_catalog"."pg_attrdef" AS "def" ON "def"."adrelid" = "cls"."oid" AND "def"."adnum" = "att"."attnum"
1751
+
1752
+ WHERE
1753
+ "att"."attrelid" = "cls"."oid" -- only columns belonging to this table
1754
+ AND "att"."attnum" >= 0 -- exclude system columns (ctid, xmin, etc. have attnum < 0)
1755
+ AND "att"."attisdropped" != TRUE -- exclude dropped (deleted) columns
1756
+ ORDER BY "att"."attnum" -- preserve original column order
1757
+ ) AS agg
1758
+ ) AS "columns",
1759
+
1760
+ -- ===== INDEXES subquery =====
1761
+ -- Aggregates all indexes for this table into a JSON array.
1762
+ (
1763
+ SELECT coalesce(json_agg(agg), '[]')
1764
+ FROM (
1765
+ SELECT
1766
+ "idx_cls"."relname" AS "name", -- index name
1767
+ "am"."amname" AS "method", -- access method (e.g., 'btree', 'hash', 'gin', 'gist')
1768
+ "idx"."indisunique" AS "unique", -- true if unique index
1769
+ "idx"."indisprimary" AS "primary", -- true if this is the PK index
1770
+ "idx"."indisvalid" AS "valid", -- false during concurrent index builds
1771
+ "idx"."indisready" AS "ready", -- true when index is ready for inserts
1772
+ ("idx"."indpred" IS NOT NULL) AS "partial", -- true if index has a WHERE clause (partial index)
1773
+ pg_get_expr("idx"."indpred", "idx"."indrelid") AS "predicate", -- the WHERE clause expression for partial indexes
1774
+
1775
+ -- Index columns: iterate over each position in the index key array
1776
+ (
1777
+ SELECT json_agg(
1778
+ json_build_object(
1779
+ -- 'name': column name, or for expression indexes the expression text
1780
+ 'name', COALESCE("att"."attname", pg_get_indexdef("idx"."indexrelid", "s"."i", true)),
1781
+ -- 'expression': non-null only for expression-based index columns (e.g., lower(name))
1782
+ 'expression', CASE WHEN "att"."attname" IS NULL THEN pg_get_indexdef("idx"."indexrelid", "s"."i", true) ELSE NULL END,
1783
+ -- 'order': sort direction; bit 0 of indoption = 1 means DESC
1784
+ 'order', CASE ((( "idx"."indoption"::int2[] )["s"."i"] & 1)) WHEN 1 THEN 'DESC' ELSE 'ASC' END,
1785
+ -- 'nulls': null ordering; bit 1 of indoption = 1 means NULLS FIRST
1786
+ 'nulls', CASE (((( "idx"."indoption"::int2[] )["s"."i"] >> 1) & 1)) WHEN 1 THEN 'NULLS FIRST' ELSE 'NULLS LAST' END
1787
+ )
1788
+ ORDER BY "s"."i" -- preserve column order within the index
1789
+ )
1790
+ -- generate_subscripts creates one row per index key position (1-based)
1791
+ FROM generate_subscripts("idx"."indkey"::int2[], 1) AS "s"("i")
1792
+ -- Join to pg_attribute to resolve column numbers to names
1793
+ -- NULL attname means it's an expression index column
1794
+ LEFT JOIN "pg_catalog"."pg_attribute" AS "att"
1795
+ ON "att"."attrelid" = "cls"."oid"
1796
+ AND "att"."attnum" = ("idx"."indkey"::int2[])["s"."i"]
1797
+ ) AS "columns"
1798
+
1799
+ FROM "pg_catalog"."pg_index" AS "idx" -- pg_index: one row per index
1800
+ JOIN "pg_catalog"."pg_class" AS "idx_cls" ON "idx"."indexrelid" = "idx_cls"."oid" -- index's own pg_class entry (for the name)
1801
+ JOIN "pg_catalog"."pg_am" AS "am" ON "idx_cls"."relam" = "am"."oid" -- access method catalog
1802
+ WHERE "idx"."indrelid" = "cls"."oid" -- only indexes on this table
1803
+ ORDER BY "idx_cls"."relname"
1804
+ ) AS agg
1805
+ ) AS "indexes"
1806
+
1807
+ -- === Main FROM: pg_class (tables and views) joined with pg_namespace (schemas) ===
1808
+ FROM "pg_catalog"."pg_class" AS "cls"
1809
+ INNER JOIN "pg_catalog"."pg_namespace" AS "ns" ON "cls"."relnamespace" = "ns"."oid"
1810
+ WHERE
1811
+ "ns"."nspname" !~ '^pg_' -- exclude PostgreSQL internal schemas (pg_catalog, pg_toast, etc.)
1812
+ AND "ns"."nspname" != 'information_schema' -- exclude the information_schema
1813
+ AND "cls"."relkind" IN ('r', 'v') -- only tables ('r') and views ('v')
1814
+ AND "cls"."relname" !~ '^pg_' -- exclude system tables starting with pg_
1815
+ AND "cls"."relname" !~ '_prisma_migrations' -- exclude Prisma migration tracking table
1816
+ ORDER BY "ns"."nspname", "cls"."relname" ASC;
1817
+ `;
1818
+ function typeCastingConvert({ defaultValue, enums, val, services }) {
1819
+ const [value, type] = val.replace(/'/g, "").split("::").map((s) => s.trim());
1820
+ switch (type) {
1821
+ case "character varying":
1822
+ case "uuid":
1823
+ case "json":
1824
+ case "jsonb":
1825
+ case "text":
1826
+ if (value === "NULL") return null;
1827
+ return (ab) => ab.StringLiteral.setValue(value);
1828
+ case "real": return (ab) => ab.NumberLiteral.setValue(value);
1829
+ default: {
1830
+ const enumDef = enums.find((e) => getDbName(e, true) === type);
1831
+ if (!enumDef) return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("dbgenerated", services)).addArg((a) => a.setValue((v) => v.StringLiteral.setValue(val)));
1832
+ const enumField = enumDef.fields.find((v) => getDbName(v) === value);
1833
+ if (!enumField) throw new CliError(`Enum value ${value} not found in enum ${type} for default value ${defaultValue}`);
1834
+ return (ab) => ab.ReferenceExpr.setTarget(enumField);
1835
+ }
1836
+ }
1837
+ }
1838
+ //#endregion
1839
+ //#region src/actions/pull/provider/sqlite.ts
1840
+ const sqlite = {
1841
+ isSupportedFeature(feature) {
1842
+ switch (feature) {
1843
+ case "Schema": return false;
1844
+ case "NativeEnum": return false;
1845
+ default: return false;
1846
+ }
1847
+ },
1848
+ getBuiltinType(type) {
1849
+ const t = (type || "").toLowerCase().trim().replace(/\(.*\)$/, "").trim();
1850
+ const isArray = false;
1851
+ switch (t) {
1852
+ case "integer":
1853
+ case "int":
1854
+ case "tinyint":
1855
+ case "smallint":
1856
+ case "mediumint":
1857
+ case "int2":
1858
+ case "int8": return {
1859
+ type: "Int",
1860
+ isArray
1861
+ };
1862
+ case "bigint":
1863
+ case "unsigned big int": return {
1864
+ type: "BigInt",
1865
+ isArray
1866
+ };
1867
+ case "text":
1868
+ case "varchar":
1869
+ case "char":
1870
+ case "character":
1871
+ case "varying character":
1872
+ case "nchar":
1873
+ case "native character":
1874
+ case "nvarchar":
1875
+ case "clob": return {
1876
+ type: "String",
1877
+ isArray
1878
+ };
1879
+ case "blob": return {
1880
+ type: "Bytes",
1881
+ isArray
1882
+ };
1883
+ case "real":
1884
+ case "float":
1885
+ case "double":
1886
+ case "double precision": return {
1887
+ type: "Float",
1888
+ isArray
1889
+ };
1890
+ case "numeric":
1891
+ case "decimal": return {
1892
+ type: "Decimal",
1893
+ isArray
1894
+ };
1895
+ case "datetime":
1896
+ case "date":
1897
+ case "time":
1898
+ case "timestamp": return {
1899
+ type: "DateTime",
1900
+ isArray
1901
+ };
1902
+ case "json":
1903
+ case "jsonb": return {
1904
+ type: "Json",
1905
+ isArray
1906
+ };
1907
+ case "boolean":
1908
+ case "bool": return {
1909
+ type: "Boolean",
1910
+ isArray
1911
+ };
1912
+ default:
1913
+ if (!t) return {
1914
+ type: "Bytes",
1915
+ isArray
1916
+ };
1917
+ if (t.includes("int")) return {
1918
+ type: "Int",
1919
+ isArray
1920
+ };
1921
+ if (t.includes("char") || t.includes("clob") || t.includes("text")) return {
1922
+ type: "String",
1923
+ isArray
1924
+ };
1925
+ if (t.includes("blob")) return {
1926
+ type: "Bytes",
1927
+ isArray
1928
+ };
1929
+ if (t.includes("real") || t.includes("floa") || t.includes("doub")) return {
1930
+ type: "Float",
1931
+ isArray
1932
+ };
1933
+ return {
1934
+ type: "Unsupported",
1935
+ isArray
1936
+ };
1937
+ }
1938
+ },
1939
+ getDefaultDatabaseType() {},
1940
+ async introspect(connectionString, _options) {
1941
+ const SQLite = (await import("better-sqlite3")).default;
1942
+ const db = new SQLite(connectionString, { readonly: true });
1943
+ try {
1944
+ const all = (sql) => {
1945
+ return db.prepare(sql).all();
1946
+ };
1947
+ const tablesRaw = all("SELECT name, type, sql AS definition FROM sqlite_schema WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' AND name <> '_prisma_migrations' ORDER BY name");
1948
+ const autoIncrementTables = /* @__PURE__ */ new Set();
1949
+ for (const t of tablesRaw) if (t.type === "table" && t.definition) {
1950
+ if (/\bAUTOINCREMENT\b/i.test(t.definition)) autoIncrementTables.add(t.name);
1951
+ }
1952
+ const tables = [];
1953
+ for (const t of tablesRaw) {
1954
+ const tableName = t.name;
1955
+ const schema = "";
1956
+ const hasAutoIncrement = autoIncrementTables.has(tableName);
1957
+ const columnsInfo = all(`PRAGMA table_xinfo('${tableName.replace(/'/g, "''")}')`);
1958
+ const idxList = all(`PRAGMA index_list('${tableName.replace(/'/g, "''")}')`).filter((r) => !r.name.startsWith("sqlite_autoindex_"));
1959
+ const uniqueSingleColumn = /* @__PURE__ */ new Set();
1960
+ const uniqueIndexRows = idxList.filter((r) => r.unique === 1 && r.partial !== 1);
1961
+ for (const idx of uniqueIndexRows) {
1962
+ const idxCols = all(`PRAGMA index_info('${idx.name.replace(/'/g, "''")}')`);
1963
+ if (idxCols.length === 1 && idxCols[0]?.name) uniqueSingleColumn.add(idxCols[0].name);
1964
+ }
1965
+ const indexes = idxList.map((idx) => {
1966
+ const idxCols = all(`PRAGMA index_info('${idx.name.replace(/'/g, "''")}')`);
1967
+ return {
1968
+ name: idx.name,
1969
+ method: null,
1970
+ unique: idx.unique === 1,
1971
+ primary: false,
1972
+ valid: true,
1973
+ ready: true,
1974
+ partial: idx.partial === 1,
1975
+ predicate: idx.partial === 1 ? "[partial]" : null,
1976
+ columns: idxCols.map((col) => ({
1977
+ name: col.name,
1978
+ expression: null,
1979
+ order: null,
1980
+ nulls: null
1981
+ }))
1982
+ };
1983
+ });
1984
+ const fkRows = all(`PRAGMA foreign_key_list('${tableName.replace(/'/g, "''")}')`);
1985
+ const fkConstraintNames = /* @__PURE__ */ new Map();
1986
+ if (t.definition) {
1987
+ const fkRegex = /CONSTRAINT\s+(?:["'`]([^"'`]+)["'`]|(\w+))\s+FOREIGN\s+KEY\s*\(([^)]+)\)/gi;
1988
+ let match;
1989
+ while ((match = fkRegex.exec(t.definition)) !== null) {
1990
+ const constraintName = match[1] || match[2];
1991
+ const columnList = match[3];
1992
+ if (constraintName && columnList) {
1993
+ const columns = columnList.split(",").map((col) => col.trim().replace(/^["'`]|["'`]$/g, ""));
1994
+ for (const col of columns) if (col) fkConstraintNames.set(col, constraintName);
1995
+ }
1996
+ }
1997
+ }
1998
+ const fkByColumn = /* @__PURE__ */ new Map();
1999
+ for (const fk of fkRows) fkByColumn.set(fk.from, {
2000
+ foreign_key_schema: "",
2001
+ foreign_key_table: fk.table || null,
2002
+ foreign_key_column: fk.to || null,
2003
+ foreign_key_name: fkConstraintNames.get(fk.from) ?? null,
2004
+ foreign_key_on_update: fk.on_update ?? null,
2005
+ foreign_key_on_delete: fk.on_delete ?? null
2006
+ });
2007
+ const generatedColDefs = t.definition ? extractColumnTypeDefs(t.definition) : /* @__PURE__ */ new Map();
2008
+ const columns = [];
2009
+ for (const c of columnsInfo) {
2010
+ const hidden = c.hidden ?? 0;
2011
+ if (hidden === 1) continue;
2012
+ const isGenerated = hidden === 2 || hidden === 3;
2013
+ const fk = fkByColumn.get(c.name);
2014
+ let defaultValue = c.dflt_value;
2015
+ if (hasAutoIncrement && c.pk) defaultValue = "autoincrement";
2016
+ let datatype = c.type || "";
2017
+ if (isGenerated) {
2018
+ const fullDef = generatedColDefs.get(c.name);
2019
+ if (fullDef) datatype = fullDef;
2020
+ }
2021
+ columns.push({
2022
+ name: c.name,
2023
+ datatype,
2024
+ datatype_name: null,
2025
+ length: null,
2026
+ precision: null,
2027
+ datatype_schema: schema,
2028
+ foreign_key_schema: fk?.foreign_key_schema ?? null,
2029
+ foreign_key_table: fk?.foreign_key_table ?? null,
2030
+ foreign_key_column: fk?.foreign_key_column ?? null,
2031
+ foreign_key_name: fk?.foreign_key_name ?? null,
2032
+ foreign_key_on_update: fk?.foreign_key_on_update ?? null,
2033
+ foreign_key_on_delete: fk?.foreign_key_on_delete ?? null,
2034
+ pk: !!c.pk,
2035
+ computed: isGenerated,
2036
+ nullable: c.notnull !== 1,
2037
+ default: defaultValue,
2038
+ unique: uniqueSingleColumn.has(c.name),
2039
+ unique_name: null
2040
+ });
2041
+ }
2042
+ tables.push({
2043
+ schema,
2044
+ name: tableName,
2045
+ columns,
2046
+ type: t.type,
2047
+ definition: t.definition,
2048
+ indexes
2049
+ });
2050
+ }
2051
+ return {
2052
+ tables,
2053
+ enums: []
2054
+ };
2055
+ } finally {
2056
+ db.close();
2057
+ }
2058
+ },
2059
+ getDefaultValue({ defaultValue, fieldType, services, enums }) {
2060
+ const val = defaultValue.trim();
2061
+ switch (fieldType) {
2062
+ case "DateTime":
2063
+ if (val === "CURRENT_TIMESTAMP" || val === "now()") return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("now", services));
2064
+ return (ab) => ab.StringLiteral.setValue(val);
2065
+ case "Int":
2066
+ case "BigInt":
2067
+ if (val === "autoincrement") return (ab) => ab.InvocationExpr.setFunction(getFunctionRef("autoincrement", services));
2068
+ return (ab) => ab.NumberLiteral.setValue(val);
2069
+ case "Float": return normalizeFloatDefault(val);
2070
+ case "Decimal": return normalizeDecimalDefault(val);
2071
+ case "Boolean": return (ab) => ab.BooleanLiteral.setValue(val === "true" || val === "1");
2072
+ case "String":
2073
+ if (val.startsWith("'") && val.endsWith("'")) {
2074
+ const strippedName = val.slice(1, -1);
2075
+ const enumDef = enums.find((e) => e.fields.find((v) => getDbName(v) === strippedName));
2076
+ if (enumDef) {
2077
+ const enumField = enumDef.fields.find((v) => getDbName(v) === strippedName);
2078
+ if (enumField) return (ab) => ab.ReferenceExpr.setTarget(enumField);
2079
+ }
2080
+ return (ab) => ab.StringLiteral.setValue(strippedName);
2081
+ }
2082
+ return (ab) => ab.StringLiteral.setValue(val);
2083
+ case "Json": return (ab) => ab.StringLiteral.setValue(val);
2084
+ case "Bytes": return (ab) => ab.StringLiteral.setValue(val);
2085
+ }
2086
+ console.warn(`Unsupported default value type: "${defaultValue}" for field type "${fieldType}". Skipping default value.`);
2087
+ return null;
2088
+ },
2089
+ getFieldAttributes({ fieldName, fieldType, services }) {
2090
+ const factories = [];
2091
+ if (fieldType === "DateTime" && (fieldName.toLowerCase() === "updatedat" || fieldName.toLowerCase() === "updated_at")) factories.push(new DataFieldAttributeFactory().setDecl(getAttributeRef("@updatedAt", services)));
2092
+ return factories;
2093
+ }
2094
+ };
2095
+ /**
2096
+ * Extract column type definitions from a CREATE TABLE DDL statement.
2097
+ * Returns a map of column name → full type definition string (everything after the column name).
2098
+ * Used to get the complete type including GENERATED ALWAYS AS (...) STORED/VIRTUAL for generated columns.
2099
+ */
2100
+ function extractColumnTypeDefs(ddl) {
2101
+ const openIdx = ddl.indexOf("(");
2102
+ if (openIdx === -1) return /* @__PURE__ */ new Map();
2103
+ let depth = 1;
2104
+ let closeIdx = -1;
2105
+ for (let i = openIdx + 1; i < ddl.length; i++) if (ddl[i] === "(") depth++;
2106
+ else if (ddl[i] === ")") {
2107
+ depth--;
2108
+ if (depth === 0) {
2109
+ closeIdx = i;
2110
+ break;
2111
+ }
2112
+ }
2113
+ if (closeIdx === -1) return /* @__PURE__ */ new Map();
2114
+ const content = ddl.substring(openIdx + 1, closeIdx);
2115
+ const defs = [];
2116
+ let current = "";
2117
+ depth = 0;
2118
+ for (const char of content) {
2119
+ if (char === "(") depth++;
2120
+ else if (char === ")") depth--;
2121
+ else if (char === "," && depth === 0) {
2122
+ defs.push(current.trim());
2123
+ current = "";
2124
+ continue;
2125
+ }
2126
+ current += char;
2127
+ }
2128
+ if (current.trim()) defs.push(current.trim());
2129
+ const result = /* @__PURE__ */ new Map();
2130
+ for (const def of defs) {
2131
+ const nameMatch = def.match(/^(?:["'`]([^"'`]+)["'`]|(\w+))\s+(.+)/s);
2132
+ if (nameMatch) {
2133
+ const name = nameMatch[1] || nameMatch[2];
2134
+ const typeDef = nameMatch[3];
2135
+ if (name && typeDef) result.set(name, typeDef.trim());
2136
+ }
2137
+ }
2138
+ return result;
2139
+ }
2140
+ //#endregion
2141
+ //#region src/actions/pull/provider/index.ts
2142
+ const providers = {
2143
+ mysql,
2144
+ postgresql,
2145
+ sqlite
2146
+ };
2147
+ //#endregion
2148
+ //#region src/actions/db.ts
2149
+ /**
2150
+ * CLI action for db related commands
2151
+ */
2152
+ async function run$7(command, options) {
2153
+ switch (command) {
2154
+ case "push":
2155
+ await runPush(options);
2156
+ break;
2157
+ case "pull":
2158
+ await runPull(options);
2159
+ break;
2160
+ }
2161
+ }
2162
+ async function runPush(options) {
2163
+ const schemaFile = getSchemaFile(options.schema);
2164
+ await requireDataSourceUrl(schemaFile);
2165
+ const prismaSchemaFile = await generateTempPrismaSchema(schemaFile, { randomName: options.randomPrismaSchemaName });
2166
+ try {
2167
+ const cmd = [
2168
+ "db push",
2169
+ ` --schema "${prismaSchemaFile}"`,
2170
+ options.acceptDataLoss ? " --accept-data-loss" : "",
2171
+ options.forceReset ? " --force-reset" : "",
2172
+ " --skip-generate"
2173
+ ].join("");
2174
+ try {
2175
+ execPrisma(cmd);
2176
+ } catch (err) {
2177
+ handleSubProcessError$1(err);
2178
+ }
2179
+ } finally {
2180
+ if (fs.existsSync(prismaSchemaFile)) fs.unlinkSync(prismaSchemaFile);
2181
+ }
2182
+ }
2183
+ async function runPull(options) {
2184
+ const spinner = ora();
2185
+ try {
2186
+ const schemaFile = getSchemaFile(options.schema);
2187
+ const outPath = options.output ? path.resolve(options.output) : void 0;
2188
+ const treatAsFile = !!outPath && (fs.existsSync(outPath) && fs.lstatSync(outPath).isFile() || path.extname(outPath) !== "");
2189
+ const { model, services } = await loadSchemaDocument(schemaFile, {
2190
+ returnServices: true,
2191
+ mergeImports: treatAsFile
2192
+ });
2193
+ const SUPPORTED_PROVIDERS = Object.keys(providers);
2194
+ const datasource = getDatasource(model);
2195
+ if (!SUPPORTED_PROVIDERS.includes(datasource.provider)) throw new CliError(`Unsupported datasource provider: ${datasource.provider}`);
2196
+ const provider = providers[datasource.provider];
2197
+ if (!provider) throw new CliError(`No introspection provider found for: ${datasource.provider}`);
2198
+ spinner.start("Introspecting database...");
2199
+ const { enums, tables } = await provider.introspect(datasource.url, {
2200
+ schemas: datasource.allSchemas,
2201
+ modelCasing: options.modelCasing
2202
+ });
2203
+ spinner.succeed("Database introspected");
2204
+ console.log(colors.blue("Syncing schema..."));
2205
+ const newModel = {
2206
+ $type: "Model",
2207
+ $container: void 0,
2208
+ $containerProperty: void 0,
2209
+ $containerIndex: void 0,
2210
+ declarations: [...model.declarations.filter((d) => ["DataSource"].includes(d.$type))],
2211
+ imports: model.imports
2212
+ };
2213
+ syncEnums({
2214
+ dbEnums: enums,
2215
+ model: newModel,
2216
+ services,
2217
+ options,
2218
+ defaultSchema: datasource.defaultSchema,
2219
+ oldModel: model,
2220
+ provider
2221
+ });
2222
+ const resolvedRelations = [];
2223
+ for (const table of tables) {
2224
+ const relations = syncTable({
2225
+ table,
2226
+ model: newModel,
2227
+ provider,
2228
+ services,
2229
+ options,
2230
+ defaultSchema: datasource.defaultSchema,
2231
+ oldModel: model
2232
+ });
2233
+ resolvedRelations.push(...relations);
2234
+ }
2235
+ for (const relation of resolvedRelations) {
2236
+ const similarRelations = resolvedRelations.filter((rr) => {
2237
+ return rr !== relation && (rr.schema === relation.schema && rr.table === relation.table && rr.references.schema === relation.references.schema && rr.references.table === relation.references.table || rr.schema === relation.references.schema && rr.columns[0] === relation.references.columns[0] && rr.references.schema === relation.schema && rr.references.table === relation.table);
2238
+ }).length;
2239
+ syncRelation({
2240
+ model: newModel,
2241
+ relation,
2242
+ services,
2243
+ options,
2244
+ selfRelation: relation.references.schema === relation.schema && relation.references.table === relation.table,
2245
+ similarRelations
2246
+ });
2247
+ }
2248
+ consolidateEnums({
2249
+ newModel,
2250
+ oldModel: model
2251
+ });
2252
+ console.log(colors.blue("Schema synced"));
2253
+ const baseDir = path.dirname(path.resolve(schemaFile));
2254
+ const baseDirUrlPath = new URL(`file://${baseDir}`).pathname;
2255
+ const docs = services.shared.workspace.LangiumDocuments.all.filter(({ uri }) => uri.path.toLowerCase().startsWith(baseDirUrlPath.toLowerCase())).toArray();
2256
+ const docsSet = new Set(docs.map((d) => d.uri.toString()));
2257
+ console.log(colors.bold("\nApplying changes to ZModel..."));
2258
+ const deletedModels = [];
2259
+ const deletedEnums = [];
2260
+ const addedModels = [];
2261
+ const addedEnums = [];
2262
+ const modelChanges = /* @__PURE__ */ new Map();
2263
+ const getModelChanges = (modelName) => {
2264
+ if (!modelChanges.has(modelName)) modelChanges.set(modelName, {
2265
+ addedFields: [],
2266
+ deletedFields: [],
2267
+ updatedFields: [],
2268
+ addedAttributes: [],
2269
+ deletedAttributes: [],
2270
+ updatedAttributes: []
2271
+ });
2272
+ return modelChanges.get(modelName);
2273
+ };
2274
+ services.shared.workspace.IndexManager.allElements("DataModel", docsSet).filter((declaration) => !newModel.declarations.find((d) => getDbName(d) === getDbName(declaration.node))).forEach((decl) => {
2275
+ const model = decl.node.$container;
2276
+ const index = model.declarations.findIndex((d) => d === decl.node);
2277
+ model.declarations.splice(index, 1);
2278
+ deletedModels.push(colors.red(`- Model ${decl.name} deleted`));
2279
+ });
2280
+ if (provider.isSupportedFeature("NativeEnum")) services.shared.workspace.IndexManager.allElements("Enum", docsSet).filter((declaration) => !newModel.declarations.find((d) => getDbName(d) === getDbName(declaration.node))).forEach((decl) => {
2281
+ const model = decl.node.$container;
2282
+ const index = model.declarations.findIndex((d) => d === decl.node);
2283
+ model.declarations.splice(index, 1);
2284
+ deletedEnums.push(colors.red(`- Enum ${decl.name} deleted`));
2285
+ });
2286
+ newModel.declarations.filter((d) => [DataModel, Enum].includes(d.$type)).forEach((_declaration) => {
2287
+ const newDataModel = _declaration;
2288
+ const declarations = services.shared.workspace.IndexManager.allElements(newDataModel.$type, docsSet).toArray();
2289
+ const originalDataModel = declarations.find((d) => getDbName(d.node) === getDbName(newDataModel))?.node;
2290
+ if (!originalDataModel) {
2291
+ if (newDataModel.$type === "DataModel") addedModels.push(colors.green(`+ Model ${newDataModel.name} added`));
2292
+ else if (newDataModel.$type === "Enum") addedEnums.push(colors.green(`+ Enum ${newDataModel.name} added`));
2293
+ model.declarations.push(newDataModel);
2294
+ newDataModel.$container = model;
2295
+ newDataModel.fields.forEach((f) => {
2296
+ if (f.$type === "DataField" && f.type.reference?.ref) {
2297
+ const ref = declarations.find((d) => getDbName(d.node) === getDbName(f.type.reference.ref))?.node;
2298
+ if (ref && f.type.reference) f.type.reference = {
2299
+ ref,
2300
+ $refText: ref.name ?? f.type.reference.$refText
2301
+ };
2302
+ }
2303
+ });
2304
+ return;
2305
+ }
2306
+ newDataModel.fields.forEach((f) => {
2307
+ let originalFields = originalDataModel.fields.filter((d) => getDbName(d) === getDbName(f));
2308
+ const isRelationField = f.$type === "DataField" && !!f.attributes?.some((a) => a?.decl?.ref?.name === "@relation");
2309
+ if (originalFields.length === 0 && isRelationField && !getRelationFieldsKey(f)) return;
2310
+ if (originalFields.length === 0) {
2311
+ const newFieldsKey = getRelationFieldsKey(f);
2312
+ if (newFieldsKey) originalFields = originalDataModel.fields.filter((d) => getRelationFieldsKey(d) === newFieldsKey);
2313
+ }
2314
+ if (originalFields.length === 0) originalFields = originalDataModel.fields.filter((d) => getRelationFkName(d) === getRelationFkName(f) && !!getRelationFkName(d) && !!getRelationFkName(f));
2315
+ if (originalFields.length === 0) originalFields = originalDataModel.fields.filter((d) => f.$type === "DataField" && d.$type === "DataField" && f.type.reference?.ref && d.type.reference?.ref && getDbName(f.type.reference.ref) === getDbName(d.type.reference.ref));
2316
+ if (originalFields.length > 1) {
2317
+ if (!!getRelationFieldsKey(f)) console.warn(colors.yellow(`Found more original fields, need to tweak the search algorithm. ${originalDataModel.name}->[${originalFields.map((of) => of.name).join(", ")}](${f.name})`));
2318
+ return;
2319
+ }
2320
+ const originalField = originalFields.at(0);
2321
+ if (originalField && f.$type === "DataField" && originalField.$type === "DataField") {
2322
+ const newType = f.type;
2323
+ const oldType = originalField.type;
2324
+ const fieldUpdates = [];
2325
+ const isOldTypeEnumWithoutNativeSupport = oldType.reference?.ref?.$type === "Enum" && !provider.isSupportedFeature("NativeEnum");
2326
+ if (newType.type && oldType.type !== newType.type && !isOldTypeEnumWithoutNativeSupport) {
2327
+ fieldUpdates.push(`type: ${oldType.type} -> ${newType.type}`);
2328
+ oldType.type = newType.type;
2329
+ }
2330
+ if (newType.reference?.ref && oldType.reference?.ref) {
2331
+ if (getDbName(newType.reference.ref) !== getDbName(oldType.reference.ref)) {
2332
+ fieldUpdates.push(`reference: ${oldType.reference.$refText} -> ${newType.reference.$refText}`);
2333
+ oldType.reference = {
2334
+ ref: newType.reference.ref,
2335
+ $refText: newType.reference.$refText
2336
+ };
2337
+ }
2338
+ } else if (newType.reference?.ref && !oldType.reference) {
2339
+ fieldUpdates.push(`type: ${oldType.type} -> ${newType.reference.$refText}`);
2340
+ oldType.reference = newType.reference;
2341
+ oldType.type = void 0;
2342
+ } else if (!newType.reference && oldType.reference?.ref && newType.type) {
2343
+ if (!(oldType.reference.ref.$type === "Enum" && !provider.isSupportedFeature("NativeEnum"))) {
2344
+ fieldUpdates.push(`type: ${oldType.reference.$refText} -> ${newType.type}`);
2345
+ oldType.type = newType.type;
2346
+ oldType.reference = void 0;
2347
+ }
2348
+ }
2349
+ if (!!newType.optional !== !!oldType.optional) {
2350
+ fieldUpdates.push(`optional: ${!!oldType.optional} -> ${!!newType.optional}`);
2351
+ oldType.optional = newType.optional;
2352
+ }
2353
+ if (!!newType.array !== !!oldType.array) {
2354
+ fieldUpdates.push(`array: ${!!oldType.array} -> ${!!newType.array}`);
2355
+ oldType.array = newType.array;
2356
+ }
2357
+ if (fieldUpdates.length > 0) getModelChanges(originalDataModel.name).updatedFields.push(colors.yellow(`~ ${originalField.name} (${fieldUpdates.join(", ")})`));
2358
+ const newDefaultAttr = f.attributes.find((a) => a.decl.$refText === "@default");
2359
+ const oldDefaultAttr = originalField.attributes.find((a) => a.decl.$refText === "@default");
2360
+ if (newDefaultAttr && oldDefaultAttr) {
2361
+ const serializeArgs = (args) => args.map((arg) => {
2362
+ if (arg.value?.$type === "StringLiteral") return `"${arg.value.value}"`;
2363
+ if (arg.value?.$type === "NumberLiteral") return String(arg.value.value);
2364
+ if (arg.value?.$type === "BooleanLiteral") return String(arg.value.value);
2365
+ if (arg.value?.$type === "InvocationExpr") return arg.value.function?.$refText ?? "";
2366
+ if (arg.value?.$type === "ReferenceExpr") return arg.value.target?.$refText ?? "";
2367
+ if (arg.value?.$type === "ArrayExpr") return `[${(arg.value.items ?? []).map((item) => {
2368
+ if (item.$type === "ReferenceExpr") return item.target?.$refText ?? "";
2369
+ return item.$type ?? "unknown";
2370
+ }).join(",")}]`;
2371
+ return arg.value?.$type ?? "unknown";
2372
+ }).join(",");
2373
+ if (serializeArgs(newDefaultAttr.args ?? []) !== serializeArgs(oldDefaultAttr.args ?? [])) {
2374
+ oldDefaultAttr.args = newDefaultAttr.args.map((arg) => ({
2375
+ ...arg,
2376
+ $container: oldDefaultAttr
2377
+ }));
2378
+ getModelChanges(originalDataModel.name).updatedAttributes.push(colors.yellow(`~ @default on ${originalDataModel.name}.${originalField.name}`));
2379
+ }
2380
+ }
2381
+ }
2382
+ if (!originalField) {
2383
+ getModelChanges(originalDataModel.name).addedFields.push(colors.green(`+ ${f.name}`));
2384
+ f.$container = originalDataModel;
2385
+ originalDataModel.fields.push(f);
2386
+ if (f.$type === "DataField" && f.type.reference?.ref) {
2387
+ const ref = declarations.find((d) => getDbName(d.node) === getDbName(f.type.reference.ref))?.node;
2388
+ if (ref) f.type.reference = {
2389
+ ref,
2390
+ $refText: ref.name ?? f.type.reference.$refText
2391
+ };
2392
+ }
2393
+ return;
2394
+ }
2395
+ originalField.attributes.filter((attr) => !f.attributes.find((d) => d.decl.$refText === attr.decl.$refText) && isDatabaseManagedAttribute(attr.decl.$refText)).forEach((attr) => {
2396
+ const field = attr.$container;
2397
+ const index = field.attributes.findIndex((d) => d === attr);
2398
+ field.attributes.splice(index, 1);
2399
+ getModelChanges(originalDataModel.name).deletedAttributes.push(colors.yellow(`- ${attr.decl.$refText} from field: ${originalDataModel.name}.${field.name}`));
2400
+ });
2401
+ f.attributes.filter((attr) => !originalField.attributes.find((d) => d.decl.$refText === attr.decl.$refText) && isDatabaseManagedAttribute(attr.decl.$refText)).forEach((attr) => {
2402
+ const cloned = {
2403
+ ...attr,
2404
+ $container: originalField
2405
+ };
2406
+ originalField.attributes.push(cloned);
2407
+ getModelChanges(originalDataModel.name).addedAttributes.push(colors.green(`+ ${attr.decl.$refText} to field: ${originalDataModel.name}.${f.name}`));
2408
+ });
2409
+ });
2410
+ originalDataModel.fields.filter((f) => {
2411
+ if (newDataModel.fields.find((d) => getDbName(d) === getDbName(f))) return false;
2412
+ const originalFieldsKey = getRelationFieldsKey(f);
2413
+ if (originalFieldsKey) {
2414
+ if (newDataModel.fields.find((d) => getRelationFieldsKey(d) === originalFieldsKey)) return false;
2415
+ }
2416
+ if (newDataModel.fields.find((d) => getRelationFkName(d) === getRelationFkName(f) && !!getRelationFkName(d) && !!getRelationFkName(f))) return false;
2417
+ return !newDataModel.fields.find((d) => f.$type === "DataField" && d.$type === "DataField" && f.type.reference?.ref && d.type.reference?.ref && getDbName(f.type.reference.ref) === getDbName(d.type.reference.ref));
2418
+ }).forEach((f) => {
2419
+ const _model = f.$container;
2420
+ const index = _model.fields.findIndex((d) => d === f);
2421
+ _model.fields.splice(index, 1);
2422
+ getModelChanges(_model.name).deletedFields.push(colors.red(`- ${f.name}`));
2423
+ });
2424
+ });
2425
+ if (deletedModels.length > 0) {
2426
+ console.log(colors.bold("\nDeleted Models:"));
2427
+ deletedModels.forEach((msg) => {
2428
+ console.log(msg);
2429
+ });
2430
+ }
2431
+ if (deletedEnums.length > 0) {
2432
+ console.log(colors.bold("\nDeleted Enums:"));
2433
+ deletedEnums.forEach((msg) => {
2434
+ console.log(msg);
2435
+ });
2436
+ }
2437
+ if (addedModels.length > 0) {
2438
+ console.log(colors.bold("\nAdded Models:"));
2439
+ addedModels.forEach((msg) => {
2440
+ console.log(msg);
2441
+ });
2442
+ }
2443
+ if (addedEnums.length > 0) {
2444
+ console.log(colors.bold("\nAdded Enums:"));
2445
+ addedEnums.forEach((msg) => {
2446
+ console.log(msg);
2447
+ });
2448
+ }
2449
+ if (modelChanges.size > 0) {
2450
+ console.log(colors.bold("\nModel Changes:"));
2451
+ modelChanges.forEach((changes, modelName) => {
2452
+ if (changes.addedFields.length > 0 || changes.deletedFields.length > 0 || changes.updatedFields.length > 0 || changes.addedAttributes.length > 0 || changes.deletedAttributes.length > 0 || changes.updatedAttributes.length > 0) {
2453
+ console.log(colors.cyan(` ${modelName}:`));
2454
+ if (changes.addedFields.length > 0) {
2455
+ console.log(colors.gray(" Added Fields:"));
2456
+ changes.addedFields.forEach((msg) => {
2457
+ console.log(` ${msg}`);
2458
+ });
2459
+ }
2460
+ if (changes.deletedFields.length > 0) {
2461
+ console.log(colors.gray(" Deleted Fields:"));
2462
+ changes.deletedFields.forEach((msg) => {
2463
+ console.log(` ${msg}`);
2464
+ });
2465
+ }
2466
+ if (changes.updatedFields.length > 0) {
2467
+ console.log(colors.gray(" Updated Fields:"));
2468
+ changes.updatedFields.forEach((msg) => {
2469
+ console.log(` ${msg}`);
2470
+ });
2471
+ }
2472
+ if (changes.addedAttributes.length > 0) {
2473
+ console.log(colors.gray(" Added Attributes:"));
2474
+ changes.addedAttributes.forEach((msg) => {
2475
+ console.log(` ${msg}`);
2476
+ });
2477
+ }
2478
+ if (changes.deletedAttributes.length > 0) {
2479
+ console.log(colors.gray(" Deleted Attributes:"));
2480
+ changes.deletedAttributes.forEach((msg) => {
2481
+ console.log(` ${msg}`);
2482
+ });
2483
+ }
2484
+ if (changes.updatedAttributes.length > 0) {
2485
+ console.log(colors.gray(" Updated Attributes:"));
2486
+ changes.updatedAttributes.forEach((msg) => {
2487
+ console.log(` ${msg}`);
2488
+ });
2489
+ }
2490
+ }
2491
+ });
2492
+ }
2493
+ const generator = new ZModelCodeGenerator({
2494
+ quote: options.quote ?? "single",
2495
+ indent: options.indent ?? 4
2496
+ });
2497
+ if (options.output) if (treatAsFile) {
2498
+ const zmodelSchema = await formatDocument(generator.generate(newModel));
2499
+ console.log(colors.blue(`Writing to ${outPath}`));
2500
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
2501
+ fs.writeFileSync(outPath, zmodelSchema);
2502
+ } else {
2503
+ fs.mkdirSync(outPath, { recursive: true });
2504
+ const baseDir = path.dirname(path.resolve(schemaFile));
2505
+ for (const { uri, parseResult: { value: documentModel } } of docs) {
2506
+ const zmodelSchema = await formatDocument(generator.generate(documentModel));
2507
+ const relPath = path.relative(baseDir, uri.fsPath);
2508
+ const targetFile = path.join(outPath, relPath);
2509
+ fs.mkdirSync(path.dirname(targetFile), { recursive: true });
2510
+ console.log(colors.blue(`Writing to ${targetFile}`));
2511
+ fs.writeFileSync(targetFile, zmodelSchema);
2512
+ }
2513
+ }
2514
+ else for (const { uri, parseResult: { value: documentModel } } of docs) {
2515
+ const zmodelSchema = await formatDocument(generator.generate(documentModel));
2516
+ console.log(colors.blue(`Writing to ${path.relative(process.cwd(), uri.fsPath).replace(/\\/g, "/")}`));
2517
+ fs.writeFileSync(uri.fsPath, zmodelSchema);
2518
+ }
2519
+ console.log(colors.green.bold("\nPull completed successfully!"));
2520
+ } catch (error) {
2521
+ spinner.fail("Pull failed");
2522
+ console.error(error);
2523
+ throw error;
2524
+ }
2525
+ }
2526
+ //#endregion
2527
+ //#region src/actions/format.ts
2528
+ /**
2529
+ * CLI action for formatting a ZModel schema file.
2530
+ */
2531
+ async function run$6(options) {
2532
+ const schemaFile = getSchemaFile(options.schema);
2533
+ let formattedContent;
2534
+ try {
2535
+ formattedContent = await formatDocument(fs.readFileSync(schemaFile, "utf-8"));
2536
+ } catch (error) {
2537
+ console.error(colors.red("✗ Schema formatting failed."));
2538
+ throw error;
2539
+ }
2540
+ fs.writeFileSync(schemaFile, formattedContent, "utf-8");
2541
+ console.log(colors.green("✓ Schema formatting completed successfully."));
2542
+ }
2543
+ //#endregion
2544
+ //#region src/plugins/prisma.ts
2545
+ const plugin$1 = {
2546
+ name: "Prisma Schema Generator",
2547
+ statusText: "Generating Prisma schema",
2548
+ async generate({ model, defaultOutputPath, pluginOptions }) {
2549
+ let outFile = path.join(defaultOutputPath, "schema.prisma");
2550
+ if (typeof pluginOptions["output"] === "string") {
2551
+ outFile = path.resolve(defaultOutputPath, pluginOptions["output"]);
2552
+ if (!fs.existsSync(path.dirname(outFile))) fs.mkdirSync(path.dirname(outFile), { recursive: true });
2553
+ }
2554
+ const prismaSchema = await new PrismaSchemaGenerator(model).generate();
2555
+ fs.writeFileSync(outFile, prismaSchema);
2556
+ }
2557
+ };
2558
+ //#endregion
2559
+ //#region src/plugins/typescript.ts
2560
+ const plugin = {
2561
+ name: "TypeScript Schema Generator",
2562
+ statusText: "Generating TypeScript schema",
2563
+ async generate({ model, defaultOutputPath, pluginOptions }) {
2564
+ let outDir = defaultOutputPath;
2565
+ if (typeof pluginOptions["output"] === "string") {
2566
+ outDir = path.resolve(defaultOutputPath, pluginOptions["output"]);
2567
+ if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
2568
+ }
2569
+ const lite = pluginOptions["lite"] === true;
2570
+ const liteOnly = pluginOptions["liteOnly"] === true;
2571
+ const importWithFileExtension = pluginOptions["importWithFileExtension"];
2572
+ if (importWithFileExtension && typeof importWithFileExtension !== "string") throw new Error("The \"importWithFileExtension\" option must be a string if specified.");
2573
+ const generateModelTypes = pluginOptions["generateModels"] !== false;
2574
+ const generateInputTypes = pluginOptions["generateInput"] !== false;
2575
+ await new TsSchemaGenerator().generate(model, {
2576
+ outDir,
2577
+ lite,
2578
+ liteOnly,
2579
+ importWithFileExtension,
2580
+ generateModelTypes,
2581
+ generateInputTypes
2582
+ });
2583
+ }
2584
+ };
2585
+ //#endregion
2586
+ //#region src/plugins/index.ts
2587
+ var plugins_exports = /* @__PURE__ */ __exportAll({
2588
+ prisma: () => plugin$1,
2589
+ typescript: () => plugin
2590
+ });
2591
+ //#endregion
2592
+ //#region src/actions/generate.ts
2593
+ /**
2594
+ * CLI action for generating code from schema
2595
+ */
2596
+ async function run$5(options) {
2597
+ try {
2598
+ await checkForMismatchedPackages(process.cwd());
2599
+ } catch (err) {
2600
+ console.warn(colors.yellow(`Failed to check for mismatched ZenStack packages: ${err}`));
2601
+ }
2602
+ const maybeShowUsageTips = options.tips && !options.silent && !options.watch ? startUsageTipsFetch() : void 0;
2603
+ const model = await pureGenerate(options, false);
2604
+ await maybeShowUsageTips?.();
2605
+ if (options.watch) {
2606
+ const logsEnabled = !options.silent;
2607
+ if (logsEnabled) console.log(colors.green(`\nEnabled watch mode!`));
2608
+ const schemaExtensions = ZModelLanguageMetaData.fileExtensions;
2609
+ const getRootModelWatchPaths = (model) => new Set(model.declarations.filter((v) => v.$cstNode?.parent?.element.$type === "Model" && !!v.$cstNode.parent.element.$document?.uri?.fsPath).map((v) => v.$cstNode.parent.element.$document.uri.fsPath));
2610
+ const watchedPaths = getRootModelWatchPaths(model);
2611
+ if (logsEnabled) {
2612
+ const logPaths = [...watchedPaths].map((at) => `- ${at}`).join("\n");
2613
+ console.log(`Watched file paths:\n${logPaths}`);
2614
+ }
2615
+ const watcher = watch([...watchedPaths], {
2616
+ alwaysStat: false,
2617
+ ignoreInitial: true,
2618
+ ignorePermissionErrors: true,
2619
+ ignored: (at) => !schemaExtensions.some((ext) => at.endsWith(ext))
2620
+ });
2621
+ const reGenerateSchema = singleDebounce(async () => {
2622
+ if (logsEnabled) console.log("Got changes, run generation!");
2623
+ try {
2624
+ const allModelsPaths = getRootModelWatchPaths(await pureGenerate(options, true));
2625
+ const newModelPaths = [...allModelsPaths].filter((at) => !watchedPaths.has(at));
2626
+ const removeModelPaths = [...watchedPaths].filter((at) => !allModelsPaths.has(at));
2627
+ if (newModelPaths.length) {
2628
+ if (logsEnabled) {
2629
+ const logPaths = newModelPaths.map((at) => `- ${at}`).join("\n");
2630
+ console.log(`Added file(s) to watch:\n${logPaths}`);
2631
+ }
2632
+ newModelPaths.forEach((at) => watchedPaths.add(at));
2633
+ watcher.add(newModelPaths);
2634
+ }
2635
+ if (removeModelPaths.length) {
2636
+ if (logsEnabled) {
2637
+ const logPaths = removeModelPaths.map((at) => `- ${at}`).join("\n");
2638
+ console.log(`Removed file(s) from watch:\n${logPaths}`);
2639
+ }
2640
+ removeModelPaths.forEach((at) => watchedPaths.delete(at));
2641
+ watcher.unwatch(removeModelPaths);
2642
+ }
2643
+ } catch (e) {
2644
+ console.error(e);
2645
+ }
2646
+ }, 500, true);
2647
+ watcher.on("unlink", (pathAt) => {
2648
+ if (logsEnabled) console.log(`Removed file from watch: ${pathAt}`);
2649
+ watchedPaths.delete(pathAt);
2650
+ watcher.unwatch(pathAt);
2651
+ reGenerateSchema();
2652
+ });
2653
+ watcher.on("change", () => {
2654
+ reGenerateSchema();
2655
+ });
2656
+ }
2657
+ }
2658
+ async function pureGenerate(options, fromWatch) {
2659
+ const start = Date.now();
2660
+ const schemaFile = getSchemaFile(options.schema);
2661
+ const model = await loadSchemaDocument(schemaFile);
2662
+ const outputPath = getOutputPath(options, schemaFile);
2663
+ await runPlugins(schemaFile, model, outputPath, options);
2664
+ if (!options.silent) {
2665
+ console.log(colors.green(`Generation completed successfully in ${Date.now() - start}ms.\n`));
2666
+ if (!fromWatch) console.log(`You can now create a ZenStack client with it.
2667
+
2668
+ \`\`\`ts
2669
+ import { ZenStackClient } from '@zenstackhq/orm';
2670
+ import { schema } from '${path.relative(".", outputPath)}/schema';
2671
+
2672
+ const client = new ZenStackClient(schema, {
2673
+ dialect: { ... }
2674
+ });
2675
+ \`\`\`
2676
+
2677
+ Check documentation: https://zenstack.dev/docs/`);
2678
+ }
2679
+ return model;
2680
+ }
2681
+ async function runPlugins(schemaFile, model, outputPath, options) {
2682
+ const plugins = model.declarations.filter(isPlugin);
2683
+ const processedPlugins = [];
2684
+ for (const plugin of plugins) {
2685
+ const provider = getPluginProvider(plugin);
2686
+ let cliPlugin;
2687
+ if (provider.startsWith("@core/")) {
2688
+ cliPlugin = plugins_exports[provider.slice(6)];
2689
+ if (!cliPlugin) throw new CliError(`Unknown core plugin: ${provider}`);
2690
+ } else {
2691
+ const pluginSourcePath = plugin.$cstNode?.parent?.element.$document?.uri?.fsPath ?? schemaFile;
2692
+ cliPlugin = await loadPluginModule(provider, path.dirname(pluginSourcePath));
2693
+ }
2694
+ if (cliPlugin) {
2695
+ const pluginOptions = getPluginOptions(plugin);
2696
+ if (provider === "@core/typescript") {
2697
+ if (options.lite !== void 0) pluginOptions["lite"] = options.lite;
2698
+ if (options.liteOnly !== void 0) pluginOptions["liteOnly"] = options.liteOnly;
2699
+ if (options.generateModels !== void 0) pluginOptions["generateModels"] = options.generateModels;
2700
+ if (options.generateInput !== void 0) pluginOptions["generateInput"] = options.generateInput;
2701
+ }
2702
+ processedPlugins.push({
2703
+ cliPlugin,
2704
+ pluginOptions
2705
+ });
2706
+ }
2707
+ }
2708
+ [{
2709
+ plugin,
2710
+ options: {
2711
+ lite: options.lite,
2712
+ liteOnly: options.liteOnly,
2713
+ generateModels: options.generateModels,
2714
+ generateInput: options.generateInput
2715
+ }
2716
+ }].forEach(({ plugin, options }) => {
2717
+ if (!processedPlugins.some((p) => p.cliPlugin === plugin)) processedPlugins.unshift({
2718
+ cliPlugin: plugin,
2719
+ pluginOptions: options
2720
+ });
2721
+ });
2722
+ for (const { cliPlugin, pluginOptions } of processedPlugins) {
2723
+ invariant(typeof cliPlugin.generate === "function", `Plugin ${cliPlugin.name} does not have a generate function`);
2724
+ let spinner;
2725
+ if (!options.silent) spinner = ora(cliPlugin.statusText ?? `Running plugin ${cliPlugin.name}`).start();
2726
+ try {
2727
+ await cliPlugin.generate({
2728
+ schemaFile,
2729
+ model,
2730
+ defaultOutputPath: outputPath,
2731
+ pluginOptions
2732
+ });
2733
+ spinner?.succeed();
2734
+ } catch (err) {
2735
+ spinner?.fail();
2736
+ throw err;
2737
+ }
2738
+ }
2739
+ }
2740
+ function getPluginOptions(plugin) {
2741
+ const result = {};
2742
+ for (const field of plugin.fields) {
2743
+ if (field.name === "provider") continue;
2744
+ const value = getLiteral(field.value) ?? getLiteralArray(field.value);
2745
+ if (value === void 0) {
2746
+ console.warn(`Plugin "${plugin.name}" option "${field.name}" has unsupported value, skipping`);
2747
+ continue;
2748
+ }
2749
+ result[field.name] = value;
2750
+ }
2751
+ return result;
2752
+ }
2753
+ async function checkForMismatchedPackages(projectPath) {
2754
+ const packages = await getZenStackPackages(projectPath);
2755
+ if (!packages.length) return false;
2756
+ const versions = /* @__PURE__ */ new Set();
2757
+ for (const { version } of packages) if (version) versions.add(version);
2758
+ if (versions.size > 1) {
2759
+ const message = "WARNING: Multiple versions of ZenStack packages detected.\n This will probably cause issues and break your types.";
2760
+ const slashes = "/".repeat(73);
2761
+ const latestVersion = semver.sort(Array.from(versions)).reverse()[0];
2762
+ console.warn(colors.yellow(`${slashes}\n\n\t${message}\n`));
2763
+ for (const { pkg, version } of packages) {
2764
+ if (!version) continue;
2765
+ if (version === latestVersion) console.log(`\t${pkg.padEnd(32)}\t${colors.green(version)}`);
2766
+ else console.log(`\t${pkg.padEnd(32)}\t${colors.yellow(version)}`);
2767
+ }
2768
+ console.warn(`\n${colors.yellow(slashes)}`);
2769
+ return true;
2770
+ }
2771
+ return false;
2772
+ }
2773
+ //#endregion
2774
+ //#region src/actions/info.ts
2775
+ /**
2776
+ * CLI action for getting information about installed ZenStack packages
2777
+ */
2778
+ async function run$4(projectPath) {
2779
+ const packages = await getZenStackPackages(projectPath);
2780
+ if (!packages.length) {
2781
+ console.error("Unable to locate package.json. Are you in a valid project directory?");
2782
+ return;
2783
+ }
2784
+ console.log("Installed ZenStack Packages:");
2785
+ const versions = /* @__PURE__ */ new Set();
2786
+ for (const { pkg, version } of packages) {
2787
+ if (version) versions.add(version);
2788
+ console.log(` ${colors.green(pkg.padEnd(20))}\t${version}`);
2789
+ }
2790
+ if (versions.size > 1) console.warn(colors.yellow("WARNING: Multiple versions of Zenstack packages detected. This may cause issues."));
2791
+ }
2792
+ //#endregion
2793
+ //#region src/actions/templates.ts
2794
+ const STARTER_ZMODEL = `// This is a sample model to get you started.
2795
+
2796
+ /// A sample data source using local sqlite db.
2797
+ datasource db {
2798
+ provider = 'sqlite'
2799
+ url = 'file:./dev.db'
2800
+ }
2801
+
2802
+ /// User model
2803
+ model User {
2804
+ id String @id @default(cuid())
2805
+ email String @unique @email @length(6, 32)
2806
+ posts Post[]
2807
+ }
2808
+
2809
+ /// Post model
2810
+ model Post {
2811
+ id String @id @default(cuid())
2812
+ createdAt DateTime @default(now())
2813
+ updatedAt DateTime @updatedAt
2814
+ title String @length(1, 256)
2815
+ content String
2816
+ published Boolean @default(false)
2817
+ author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
2818
+ authorId String
2819
+ }
2820
+ `;
2821
+ //#endregion
2822
+ //#region src/actions/init.ts
2823
+ /**
2824
+ * CLI action for getting information about installed ZenStack packages
2825
+ */
2826
+ async function run$3(projectPath) {
2827
+ const packages = [
2828
+ {
2829
+ name: "@zenstackhq/cli@latest",
2830
+ dev: true
2831
+ },
2832
+ {
2833
+ name: "@zenstackhq/schema@latest",
2834
+ dev: false
2835
+ },
2836
+ {
2837
+ name: "@zenstackhq/orm@latest",
2838
+ dev: false
2839
+ }
2840
+ ];
2841
+ let pm = await detect();
2842
+ if (!pm) pm = {
2843
+ agent: "npm",
2844
+ name: "npm"
2845
+ };
2846
+ console.log(colors.gray(`Using package manager: ${pm.agent}`));
2847
+ for (const pkg of packages) {
2848
+ const resolved = resolveCommand(pm.agent, "add", [pkg.name, ...pkg.dev ? [pm.agent.startsWith("yarn") || pm.agent === "bun" ? "--dev" : "--save-dev"] : []]);
2849
+ if (!resolved) throw new CliError(`Unable to determine how to install package "${pkg.name}". Please install it manually.`);
2850
+ const spinner = ora(`Installing "${pkg.name}"`).start();
2851
+ try {
2852
+ execSync$1(`${resolved.command} ${resolved.args.join(" ")}`, { cwd: projectPath });
2853
+ spinner.succeed();
2854
+ } catch (e) {
2855
+ spinner.fail();
2856
+ throw e;
2857
+ }
2858
+ }
2859
+ const generationFolder = "zenstack";
2860
+ if (!fs.existsSync(path.join(projectPath, generationFolder))) fs.mkdirSync(path.join(projectPath, generationFolder));
2861
+ if (!fs.existsSync(path.join(projectPath, generationFolder, "schema.zmodel"))) fs.writeFileSync(path.join(projectPath, generationFolder, "schema.zmodel"), STARTER_ZMODEL);
2862
+ else console.log(colors.yellow("Schema file already exists. Skipping generation of sample."));
2863
+ console.log(colors.green("ZenStack project initialized successfully!"));
2864
+ console.log(colors.gray(`See "${generationFolder}/schema.zmodel" for your database schema.`));
2865
+ console.log(colors.gray("Run `zenstack generate` to compile the the schema into a TypeScript file."));
2866
+ }
2867
+ //#endregion
2868
+ //#region src/actions/seed.ts
2869
+ /**
2870
+ * CLI action for seeding the database.
2871
+ */
2872
+ async function run$2(options, args) {
2873
+ const pkgJsonConfig = getPkgJsonConfig(process.cwd());
2874
+ if (!pkgJsonConfig.seed) {
2875
+ if (!options.noWarnings) console.warn(colors.yellow("No seed script defined in package.json. Skipping seeding."));
2876
+ return;
2877
+ }
2878
+ const command = `${pkgJsonConfig.seed}${args.length > 0 ? " " + args.join(" ") : ""}`;
2879
+ if (options.printStatus) console.log(colors.gray(`Running seed script "${command}"...`));
2880
+ try {
2881
+ await execaCommand(command, {
2882
+ stdout: "inherit",
2883
+ stderr: "inherit"
2884
+ });
2885
+ } catch (err) {
2886
+ console.error(colors.red(err instanceof Error ? err.message : String(err)));
2887
+ throw new CliError("Failed to seed the database. Please check the error message above for details.");
2888
+ }
2889
+ }
2890
+ //#endregion
2891
+ //#region src/actions/migrate.ts
2892
+ /**
2893
+ * CLI action for migration-related commands
2894
+ */
2895
+ async function run$1(command, options) {
2896
+ const schemaFile = getSchemaFile(options.schema);
2897
+ await requireDataSourceUrl(schemaFile);
2898
+ const prismaSchemaFile = await generateTempPrismaSchema(schemaFile, {
2899
+ folder: options.migrations ? path.dirname(options.migrations) : void 0,
2900
+ randomName: options.randomPrismaSchemaName
2901
+ });
2902
+ try {
2903
+ switch (command) {
2904
+ case "dev":
2905
+ await runDev(prismaSchemaFile, options);
2906
+ break;
2907
+ case "reset":
2908
+ await runReset(prismaSchemaFile, options);
2909
+ break;
2910
+ case "deploy":
2911
+ await runDeploy(prismaSchemaFile, options);
2912
+ break;
2913
+ case "status":
2914
+ await runStatus(prismaSchemaFile, options);
2915
+ break;
2916
+ case "resolve":
2917
+ await runResolve(prismaSchemaFile, options);
2918
+ break;
2919
+ }
2920
+ } finally {
2921
+ if (fs.existsSync(prismaSchemaFile)) fs.unlinkSync(prismaSchemaFile);
2922
+ }
2923
+ }
2924
+ function runDev(prismaSchemaFile, options) {
2925
+ try {
2926
+ execPrisma([
2927
+ "migrate dev",
2928
+ ` --schema "${prismaSchemaFile}"`,
2929
+ " --skip-generate",
2930
+ " --skip-seed",
2931
+ options.name ? ` --name "${options.name}"` : "",
2932
+ options.createOnly ? " --create-only" : ""
2933
+ ].join(""));
2934
+ } catch (err) {
2935
+ handleSubProcessError(err);
2936
+ }
2937
+ }
2938
+ async function runReset(prismaSchemaFile, options) {
2939
+ try {
2940
+ execPrisma([
2941
+ "migrate reset",
2942
+ ` --schema "${prismaSchemaFile}"`,
2943
+ " --skip-generate",
2944
+ " --skip-seed",
2945
+ options.force ? " --force" : ""
2946
+ ].join(""));
2947
+ } catch (err) {
2948
+ handleSubProcessError(err);
2949
+ }
2950
+ if (!options.skipSeed) await run$2({
2951
+ noWarnings: true,
2952
+ printStatus: true
2953
+ }, []);
2954
+ }
2955
+ function runDeploy(prismaSchemaFile, _options) {
2956
+ try {
2957
+ execPrisma(["migrate deploy", ` --schema "${prismaSchemaFile}"`].join(""));
2958
+ } catch (err) {
2959
+ handleSubProcessError(err);
2960
+ }
2961
+ }
2962
+ function runStatus(prismaSchemaFile, _options) {
2963
+ try {
2964
+ execPrisma(`migrate status --schema "${prismaSchemaFile}"`);
2965
+ } catch (err) {
2966
+ handleSubProcessError(err);
2967
+ }
2968
+ }
2969
+ function runResolve(prismaSchemaFile, options) {
2970
+ if (!options.applied && !options.rolledBack) throw new CliError("Either --applied or --rolled-back option must be provided");
2971
+ try {
2972
+ execPrisma([
2973
+ "migrate resolve",
2974
+ ` --schema "${prismaSchemaFile}"`,
2975
+ options.applied ? ` --applied "${options.applied}"` : "",
2976
+ options.rolledBack ? ` --rolled-back "${options.rolledBack}"` : ""
2977
+ ].join(""));
2978
+ } catch (err) {
2979
+ handleSubProcessError(err);
2980
+ }
2981
+ }
2982
+ function handleSubProcessError(err) {
2983
+ if (err instanceof Error && "status" in err && typeof err.status === "number") process.exit(err.status);
2984
+ else process.exit(1);
2985
+ }
2986
+ //#endregion
2987
+ //#region src/utils/version-utils.ts
2988
+ const CHECK_VERSION_TIMEOUT = 2e3;
2989
+ const VERSION_CHECK_TAG = "latest";
2990
+ function getVersion() {
2991
+ try {
2992
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
2993
+ return JSON.parse(fs.readFileSync(path.join(_dirname, "../package.json"), "utf8")).version;
2994
+ } catch {
2995
+ return;
2996
+ }
2997
+ }
2998
+ async function checkNewVersion() {
2999
+ const currVersion = getVersion();
3000
+ let latestVersion;
3001
+ try {
3002
+ latestVersion = await getLatestVersion();
3003
+ } catch {
3004
+ return;
3005
+ }
3006
+ if (latestVersion && currVersion && semver.gt(latestVersion, currVersion)) console.log(`A newer version ${colors.cyan(latestVersion)} is available.`);
3007
+ }
3008
+ async function getLatestVersion() {
3009
+ const fetchResult = await fetch(`https://registry.npmjs.org/@zenstackhq/cli/${VERSION_CHECK_TAG}`, {
3010
+ headers: { accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*" },
3011
+ signal: AbortSignal.timeout(CHECK_VERSION_TIMEOUT)
3012
+ });
3013
+ if (fetchResult.ok) {
3014
+ const latestVersion = (await fetchResult.json())?.version;
3015
+ if (typeof latestVersion === "string" && semver.valid(latestVersion)) return latestVersion;
3016
+ }
3017
+ throw new Error("invalid npm registry response");
3018
+ }
3019
+ //#endregion
3020
+ //#region src/actions/proxy.ts
3021
+ async function run(options) {
3022
+ const allowedLogLevels = ["error", "query"];
3023
+ const log = options.logLevel?.filter((level) => allowedLogLevels.includes(level));
3024
+ const schemaFile = getSchemaFile(options.schema);
3025
+ console.log(colors.gray(`Loading ZModel schema from: ${schemaFile}`));
3026
+ let outputPath = getOutputPath(options, schemaFile);
3027
+ if (!path.isAbsolute(outputPath)) outputPath = path.resolve(process.cwd(), outputPath);
3028
+ const dataSource = (await loadSchemaDocument(schemaFile)).declarations.find(isDataSource);
3029
+ let databaseUrl = options.databaseUrl;
3030
+ if (!databaseUrl) {
3031
+ const schemaUrl = dataSource?.fields.find((f) => f.name === "url")?.value;
3032
+ if (!schemaUrl) throw new CliError(`The schema's "datasource" does not have a "url" field, please provide it with -d option.`);
3033
+ databaseUrl = evaluateUrl(schemaUrl);
3034
+ }
3035
+ const dialect = await createDialect(getStringLiteral(dataSource?.fields.find((f) => f.name === "provider")?.value), databaseUrl, outputPath);
3036
+ const schemaModule = await createJiti(typeof __filename !== "undefined" ? __filename : import.meta.url).import(path.join(outputPath, "schema"));
3037
+ const schema = schemaModule.schema;
3038
+ const omit = {};
3039
+ for (const [modelName, modelDef] of Object.entries(schema.models)) {
3040
+ const omitFields = {};
3041
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.computed === true || fieldDef.type === "Unsupported") omitFields[fieldName] = true;
3042
+ if (Object.keys(omitFields).length > 0) omit[modelName] = omitFields;
3043
+ }
3044
+ const db = new ZenStackClient(schema, {
3045
+ dialect,
3046
+ log: log && log.length > 0 ? log : void 0,
3047
+ omit: Object.keys(omit).length > 0 ? omit : void 0,
3048
+ skipValidationForComputedFields: true
3049
+ });
3050
+ try {
3051
+ await db.$connect();
3052
+ } catch (err) {
3053
+ throw new CliError(`Failed to connect to the database: ${err instanceof Error ? err.message : String(err)}`);
3054
+ }
3055
+ startServer(db, schemaModule.schema, options);
3056
+ }
3057
+ function evaluateUrl(schemaUrl) {
3058
+ if (isLiteralExpr(schemaUrl)) return getStringLiteral(schemaUrl);
3059
+ else if (isInvocationExpr(schemaUrl)) {
3060
+ const envName = getStringLiteral(schemaUrl.args[0]?.value);
3061
+ const envValue = process.env[envName];
3062
+ if (!envValue) throw new CliError(`Environment variable ${envName} is not set`);
3063
+ return envValue;
3064
+ } else throw new CliError(`Unable to resolve the "url" field value.`);
3065
+ }
3066
+ function redactDatabaseUrl(url) {
3067
+ try {
3068
+ const parsedUrl = new URL(url);
3069
+ if (parsedUrl.password) parsedUrl.password = "***";
3070
+ if (parsedUrl.username) parsedUrl.username = "***";
3071
+ return parsedUrl.toString();
3072
+ } catch {
3073
+ return url;
3074
+ }
3075
+ }
3076
+ async function createDialect(provider, databaseUrl, outputPath) {
3077
+ switch (provider) {
3078
+ case "sqlite": {
3079
+ let SQLite;
3080
+ try {
3081
+ SQLite = (await import("better-sqlite3")).default;
3082
+ } catch {
3083
+ throw new CliError(`Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`);
3084
+ }
3085
+ let resolvedUrl = databaseUrl.trim();
3086
+ if (resolvedUrl.startsWith("file:")) {
3087
+ const filePath = resolvedUrl.substring(5);
3088
+ if (!path.isAbsolute(filePath)) resolvedUrl = path.join(outputPath, filePath);
3089
+ }
3090
+ console.log(colors.gray(`Connecting to SQLite database at: ${resolvedUrl}`));
3091
+ return new SqliteDialect({ database: new SQLite(resolvedUrl) });
3092
+ }
3093
+ case "postgresql": {
3094
+ let PgPool;
3095
+ try {
3096
+ PgPool = (await import("pg")).Pool;
3097
+ } catch {
3098
+ throw new CliError(`Package "pg" is required for PostgreSQL support. Please install it with: npm install pg`);
3099
+ }
3100
+ console.log(colors.gray(`Connecting to PostgreSQL database at: ${redactDatabaseUrl(databaseUrl)}`));
3101
+ return new PostgresDialect({ pool: new PgPool({ connectionString: databaseUrl }) });
3102
+ }
3103
+ case "mysql": {
3104
+ let createMysqlPool;
3105
+ try {
3106
+ createMysqlPool = (await import("mysql2")).createPool;
3107
+ } catch {
3108
+ throw new CliError(`Package "mysql2" is required for MySQL support. Please install it with: npm install mysql2`);
3109
+ }
3110
+ console.log(colors.gray(`Connecting to MySQL database at: ${redactDatabaseUrl(databaseUrl)}`));
3111
+ return new MysqlDialect({ pool: createMysqlPool(databaseUrl) });
3112
+ }
3113
+ default: throw new CliError(`Unsupported database provider: ${provider}`);
3114
+ }
3115
+ }
3116
+ function createProxyApp(client, schema) {
3117
+ const app = express();
3118
+ app.use(cors());
3119
+ app.use(express.json({ limit: "5mb" }));
3120
+ app.use(express.urlencoded({
3121
+ extended: true,
3122
+ limit: "5mb"
3123
+ }));
3124
+ app.use("/api/model", ZenStackMiddleware({
3125
+ apiHandler: new RPCApiHandler({ schema }),
3126
+ getClient: () => client
3127
+ }));
3128
+ app.get("/api/schema", (_req, res) => {
3129
+ res.json({
3130
+ ...schema,
3131
+ zenstackVersion: getVersion()
3132
+ });
3133
+ });
3134
+ return app;
3135
+ }
3136
+ function startServer(client, schema, options) {
3137
+ const server = createProxyApp(client, schema).listen(options.port, () => {
3138
+ console.log(`ZenStack proxy server is running on port: ${options.port}`);
3139
+ console.log(`You can visit ZenStack Studio at: ${colors.blue("https://studio.zenstack.dev")}`);
3140
+ });
3141
+ server.on("error", (err) => {
3142
+ if (err.code === "EADDRINUSE") console.error(colors.red(`Port ${options.port} is already in use. Please choose a different port using -p option.`));
3143
+ else throw new CliError(`Failed to start the server: ${err.message}`);
3144
+ process.exit(1);
3145
+ });
3146
+ process.on("SIGTERM", async () => {
3147
+ server.close(() => {
3148
+ console.log("\nZenStack proxy server closed");
3149
+ });
3150
+ await client.$disconnect();
3151
+ process.exit(0);
3152
+ });
3153
+ process.on("SIGINT", async () => {
3154
+ server.close(() => {
3155
+ console.log("\nZenStack proxy server closed");
3156
+ });
3157
+ await client.$disconnect();
3158
+ process.exit(0);
3159
+ });
3160
+ }
3161
+ //#endregion
3162
+ //#region src/constants.ts
3163
+ const TELEMETRY_TRACKING_TOKEN = "74944eb779d7d3b4ce185be843fde9fc";
3164
+ //#endregion
3165
+ //#region src/utils/is-ci.ts
3166
+ const isInCi = env["CI"] !== "0" && env["CI"] !== "false" && ("CI" in env || "CONTINUOUS_INTEGRATION" in env || Object.keys(env).some((key) => key.startsWith("CI_")));
3167
+ //#endregion
3168
+ //#region src/utils/is-docker.ts
3169
+ let isDockerCached;
3170
+ function hasDockerEnv() {
3171
+ try {
3172
+ fs.statSync("/.dockerenv");
3173
+ return true;
3174
+ } catch {
3175
+ return false;
3176
+ }
3177
+ }
3178
+ function hasDockerCGroup() {
3179
+ try {
3180
+ return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
3181
+ } catch {
3182
+ return false;
3183
+ }
3184
+ }
3185
+ function isDocker() {
3186
+ if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
3187
+ return isDockerCached;
3188
+ }
3189
+ //#endregion
3190
+ //#region src/utils/is-container.ts
3191
+ let cachedResult;
3192
+ const hasContainerEnv = () => {
3193
+ try {
3194
+ fs.statSync("/run/.containerenv");
3195
+ return true;
3196
+ } catch {
3197
+ return false;
3198
+ }
3199
+ };
3200
+ function isInContainer() {
3201
+ if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
3202
+ return cachedResult;
3203
+ }
3204
+ //#endregion
3205
+ //#region src/utils/is-wsl.ts
3206
+ const isWsl = () => {
3207
+ if (process$1.platform !== "linux") return false;
3208
+ if (os.release().toLowerCase().includes("microsoft")) return true;
3209
+ try {
3210
+ return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft");
3211
+ } catch {
3212
+ return false;
3213
+ }
3214
+ };
3215
+ //#endregion
3216
+ //#region src/utils/machine-id-utils.ts
3217
+ const { platform } = process;
3218
+ const guid = {
3219
+ darwin: "ioreg -rd1 -c IOPlatformExpertDevice",
3220
+ win32: `${{
3221
+ native: "%windir%\\System32",
3222
+ mixed: "%windir%\\sysnative\\cmd.exe /c %windir%\\System32"
3223
+ }[isWindowsProcessMixedOrNativeArchitecture()]}\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`,
3224
+ linux: "( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname 2> /dev/null) | head -n 1 || :",
3225
+ freebsd: "kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"
3226
+ };
3227
+ function isWindowsProcessMixedOrNativeArchitecture() {
3228
+ if (process.arch === "ia32" && process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")) return "mixed";
3229
+ return "native";
3230
+ }
3231
+ function hash(guid) {
3232
+ return createHash("sha256").update(guid).digest("hex");
3233
+ }
3234
+ function expose(result) {
3235
+ switch (platform) {
3236
+ case "darwin": return result.split("IOPlatformUUID")[1]?.split("\n")[0]?.replace(/=|\s+|"/gi, "").toLowerCase();
3237
+ case "win32": return result.toString().split("REG_SZ")[1]?.replace(/\r+|\n+|\s+/gi, "").toLowerCase();
3238
+ case "linux": return result.toString().replace(/\r+|\n+|\s+/gi, "").toLowerCase();
3239
+ case "freebsd": return result.toString().replace(/\r+|\n+|\s+/gi, "").toLowerCase();
3240
+ default: throw new Error(`Unsupported platform: ${process.platform}`);
3241
+ }
3242
+ }
3243
+ function getMachineId() {
3244
+ if (!(platform in guid)) return randomUUID();
3245
+ try {
3246
+ const id = expose(execSync(guid[platform]).toString());
3247
+ if (!id) return randomUUID();
3248
+ return hash(id);
3249
+ } catch {
3250
+ return randomUUID();
3251
+ }
3252
+ }
3253
+ //#endregion
3254
+ //#region src/telemetry.ts
3255
+ /**
3256
+ * Utility class for sending telemetry
3257
+ */
3258
+ var Telemetry = class {
3259
+ mixpanel;
3260
+ hostId = getMachineId();
3261
+ sessionid = randomUUID();
3262
+ _os_type = os$1.type();
3263
+ _os_release = os$1.release();
3264
+ _os_arch = os$1.arch();
3265
+ _os_version = os$1.version();
3266
+ _os_platform = os$1.platform();
3267
+ version = getVersion();
3268
+ prismaVersion = this.getPrismaVersion();
3269
+ isDocker = isDocker();
3270
+ isWsl = isWsl();
3271
+ isContainer = isInContainer();
3272
+ isCi = isInCi;
3273
+ constructor() {
3274
+ if (process.env["DO_NOT_TRACK"] !== "1" && "<TELEMETRY_TRACKING_TOKEN>") this.mixpanel = init(TELEMETRY_TRACKING_TOKEN, { geolocate: true });
3275
+ }
3276
+ get isTracking() {
3277
+ return !!this.mixpanel;
3278
+ }
3279
+ track(event, properties = {}) {
3280
+ if (this.mixpanel) {
3281
+ const payload = {
3282
+ distinct_id: this.hostId,
3283
+ session: this.sessionid,
3284
+ time: /* @__PURE__ */ new Date(),
3285
+ $os: this._os_type,
3286
+ osType: this._os_type,
3287
+ osRelease: this._os_release,
3288
+ osPlatform: this._os_platform,
3289
+ osArch: this._os_arch,
3290
+ osVersion: this._os_version,
3291
+ nodeVersion: process.version,
3292
+ version: this.version,
3293
+ prismaVersion: this.prismaVersion,
3294
+ isDocker: this.isDocker,
3295
+ isWsl: this.isWsl,
3296
+ isContainer: this.isContainer,
3297
+ isCi: this.isCi,
3298
+ ...properties
3299
+ };
3300
+ this.mixpanel.track(event, payload);
3301
+ }
3302
+ }
3303
+ trackError(err) {
3304
+ this.track("cli:error", {
3305
+ message: err.message,
3306
+ stack: err.stack
3307
+ });
3308
+ }
3309
+ async trackSpan(startEvent, completeEvent, errorEvent, properties, action) {
3310
+ this.track(startEvent, properties);
3311
+ const start = Date.now();
3312
+ let success = true;
3313
+ try {
3314
+ return await action();
3315
+ } catch (err) {
3316
+ this.track(errorEvent, {
3317
+ message: err.message,
3318
+ stack: err.stack,
3319
+ ...properties
3320
+ });
3321
+ success = false;
3322
+ throw err;
3323
+ } finally {
3324
+ this.track(completeEvent, {
3325
+ duration: Date.now() - start,
3326
+ success,
3327
+ ...properties
3328
+ });
3329
+ }
3330
+ }
3331
+ async trackCommand(command, action) {
3332
+ await this.trackSpan("cli:command:start", "cli:command:complete", "cli:command:error", { command }, action);
3333
+ }
3334
+ async trackCli(action) {
3335
+ await this.trackSpan("cli:start", "cli:complete", "cli:error", {}, action);
3336
+ }
3337
+ getPrismaVersion() {
3338
+ try {
3339
+ const packageJsonPath = import.meta.resolve("prisma/package.json");
3340
+ const packageJsonUrl = new URL(packageJsonPath);
3341
+ return JSON.parse(fs.readFileSync(packageJsonUrl, "utf8")).version;
3342
+ } catch {
3343
+ return;
3344
+ }
3345
+ }
3346
+ };
3347
+ const telemetry = new Telemetry();
3348
+ //#endregion
3349
+ //#region src/index.ts
3350
+ const generateAction = async (options) => {
3351
+ await telemetry.trackCommand("generate", () => run$5(options));
3352
+ };
3353
+ const migrateAction = async (subCommand, options) => {
3354
+ await telemetry.trackCommand(`migrate ${subCommand}`, () => run$1(subCommand, options));
3355
+ };
3356
+ const dbAction = async (subCommand, options) => {
3357
+ await telemetry.trackCommand(`db ${subCommand}`, () => run$7(subCommand, options));
3358
+ };
3359
+ const infoAction = async (projectPath) => {
3360
+ await telemetry.trackCommand("info", () => run$4(projectPath));
3361
+ };
3362
+ const initAction = async (projectPath) => {
3363
+ await telemetry.trackCommand("init", () => run$3(projectPath));
3364
+ };
3365
+ const checkAction = async (options) => {
3366
+ await telemetry.trackCommand("check", () => run$8(options));
3367
+ };
3368
+ const formatAction = async (options) => {
3369
+ await telemetry.trackCommand("format", () => run$6(options));
3370
+ };
3371
+ const seedAction = async (options, args) => {
3372
+ await telemetry.trackCommand("db seed", () => run$2(options, args));
3373
+ };
3374
+ const proxyAction = async (options) => {
3375
+ await telemetry.trackCommand("proxy", () => run(options));
3376
+ };
3377
+ function triStateBooleanOption(flag, description) {
3378
+ return new Option(flag, description).choices(["true", "false"]).argParser((value) => {
3379
+ if (value === void 0 || value === "true") return true;
3380
+ if (value === "false") return false;
3381
+ throw new CliError(`Invalid value for ${flag}: ${value}`);
3382
+ });
3383
+ }
3384
+ function createProgram() {
3385
+ const program = new Command("zen").alias("zenstack").helpOption("-h, --help", "Show this help message").version(getVersion(), "-v --version", "Show CLI version");
3386
+ const schemaExtensions = ZModelLanguageMetaData.fileExtensions.join(", ");
3387
+ program.description(`${colors.bold.blue("ζ")} ZenStack is the modern data layer for TypeScript apps.\n\nDocumentation: https://zenstack.dev/docs`).showHelpAfterError().showSuggestionAfterError();
3388
+ const schemaOption = new Option("--schema <file>", `schema file (with extension ${schemaExtensions}). Defaults to "zenstack/schema.zmodel" unless specified in package.json.`);
3389
+ const noVersionCheckOption = new Option("--no-version-check", "do not check for new version");
3390
+ const noTipsOption = new Option("--no-tips", "do not show usage tips");
3391
+ const randomPrismaSchemaNameOption = new Option("--random-prisma-schema-name", "append a random UUID to the temporary Prisma schema filename (e.g., ~schema.<uuid>.prisma) to avoid collisions between concurrent runs sharing a working directory").default(false);
3392
+ program.command("generate").description("Run code generation plugins").addOption(schemaOption).addOption(noVersionCheckOption).addOption(noTipsOption).addOption(new Option("-o, --output <path>", "default output directory for code generation")).addOption(new Option("-w, --watch", "enable watch mode").default(false)).addOption(triStateBooleanOption("--lite [boolean]", "also generate a lite version of schema without attributes, defaults to false")).addOption(triStateBooleanOption("--lite-only [boolean]", "only generate lite version of schema without attributes, defaults to false")).addOption(triStateBooleanOption("--generate-models [boolean]", "generate models.ts file, defaults to true")).addOption(triStateBooleanOption("--generate-input [boolean]", "generate input.ts file, defaults to true")).addOption(new Option("--silent", "suppress all output except errors").default(false)).action(generateAction);
3393
+ const migrateCommand = program.command("migrate").description("Run database schema migration related tasks.");
3394
+ const migrationsOption = new Option("--migrations <path>", "path that contains the \"migrations\" directory");
3395
+ migrateCommand.command("dev").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("-n, --name <name>", "migration name")).addOption(new Option("--create-only", "only create migration, do not apply")).addOption(migrationsOption).addOption(randomPrismaSchemaNameOption).description("Create a migration from changes in schema and apply it to the database").action((options) => migrateAction("dev", options));
3396
+ migrateCommand.command("reset").addOption(schemaOption).addOption(new Option("--force", "skip the confirmation prompt")).addOption(migrationsOption).addOption(new Option("--skip-seed", "skip seeding the database after reset")).addOption(noVersionCheckOption).addOption(randomPrismaSchemaNameOption).description("Reset your database and apply all migrations, all data will be lost").addHelpText("after", "\nIf there is a seed script defined in package.json, it will be run after the reset. Use --skip-seed to skip it.").action((options) => migrateAction("reset", options));
3397
+ migrateCommand.command("deploy").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).addOption(randomPrismaSchemaNameOption).description("Deploy your pending migrations to your production/staging database").action((options) => migrateAction("deploy", options));
3398
+ migrateCommand.command("status").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).addOption(randomPrismaSchemaNameOption).description("Check the status of your database migrations").action((options) => migrateAction("status", options));
3399
+ migrateCommand.command("resolve").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).addOption(randomPrismaSchemaNameOption).addOption(new Option("--applied <migration>", "record a specific migration as applied")).addOption(new Option("--rolled-back <migration>", "record a specific migration as rolled back")).description("Resolve issues with database migrations in deployment databases").action((options) => migrateAction("resolve", options));
3400
+ const dbCommand = program.command("db").description("Manage your database schema during development");
3401
+ dbCommand.command("push").description("Push the state from your schema to your database").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("--accept-data-loss", "ignore data loss warnings")).addOption(new Option("--force-reset", "force a reset of the database before push")).addOption(randomPrismaSchemaNameOption).action((options) => dbAction("push", options));
3402
+ dbCommand.command("pull").description("Introspect your database.").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("-o, --output <path>", "set custom output path for the introspected schema. If a file path is provided, all schemas are merged into that single file. If a directory path is provided, files are written to the directory and imports are kept.")).addOption(new Option("--model-casing <pascal|camel|snake|none>", "set the casing of generated models").default("pascal")).addOption(new Option("--field-casing <pascal|camel|snake|none>", "set the casing of generated fields").default("camel")).addOption(new Option("--always-map", "always add @map and @@map attributes to models and fields").default(false)).addOption(new Option("--quote <double|single>", "set the quote style of generated schema files").default("single")).addOption(new Option("--indent <number>", "set the indentation of the generated schema files").default(4)).action((options) => dbAction("pull", options));
3403
+ dbCommand.command("seed").description("Seed the database").allowExcessArguments(true).addHelpText("after", `
3404
+ Seed script is configured under the "zenstack.seed" field in package.json.
3405
+ E.g.:
3406
+ {
3407
+ "zenstack": {
3408
+ "seed": "ts-node ./zenstack/seed.ts"
3409
+ }
3410
+ }
3411
+
3412
+ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --users 10"`).addOption(noVersionCheckOption).action((options, command) => seedAction(options, command.args));
3413
+ program.command("info").description("Get information of installed ZenStack packages").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(infoAction);
3414
+ program.command("init").description("Initialize an existing project for ZenStack").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(initAction);
3415
+ program.command("check").description("Check a ZModel schema for syntax or semantic errors").addOption(schemaOption).addOption(noVersionCheckOption).action(checkAction);
3416
+ program.command("format").description("Format a ZModel schema file").addOption(schemaOption).addOption(noVersionCheckOption).action(formatAction);
3417
+ program.command("proxy").alias("studio").description("Start the ZenStack proxy server").addOption(schemaOption).addOption(new Option("-p, --port <port>", "port to run the proxy server on").default(2311)).addOption(new Option("-o, --output <path>", "output directory for `zen generate` command")).addOption(new Option("-d, --databaseUrl <url>", "database connection URL")).addOption(new Option("-l, --logLevel <level...>", "Query log levels (e.g., query, error)")).addOption(noVersionCheckOption).action(proxyAction);
3418
+ program.addHelpCommand("help [command]", "Display help for a command");
3419
+ program.hook("preAction", async (_thisCommand, actionCommand) => {
3420
+ if (actionCommand.getOptionValue("versionCheck") !== false) await checkNewVersion();
3421
+ });
3422
+ return program;
3423
+ }
3424
+ async function main() {
3425
+ let exitCode = 0;
3426
+ const program = createProgram();
3427
+ program.exitOverride();
3428
+ try {
3429
+ await telemetry.trackCli(async () => {
3430
+ await program.parseAsync();
3431
+ });
3432
+ } catch (e) {
3433
+ if (e instanceof CommanderError) exitCode = e.exitCode;
3434
+ else if (e instanceof CliError) {
3435
+ console.error(colors.red(e.message));
3436
+ exitCode = 1;
3437
+ } else {
3438
+ console.error(colors.red(`Unhandled error: ${e}`));
3439
+ exitCode = 1;
3440
+ }
3441
+ }
3442
+ if (program.args.includes("generate") && (program.args.includes("-w") || program.args.includes("--watch")) || ["proxy", "studio"].some((cmd) => program.args.includes(cmd))) return;
3443
+ if (telemetry.isTracking) setTimeout(() => {
3444
+ process.exit(exitCode);
3445
+ }, 200);
3446
+ else process.exit(exitCode);
3447
+ }
3448
+ main();
3449
+ //#endregion
3450
+ export {};
3451
+
3452
+ //# sourceMappingURL=index.mjs.map