@drzl/cli 4.34.0 → 4.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2150,6 +2150,180 @@ async function resolveSchemaSource(cfg, cwd = process.cwd()) {
2150
2150
  };
2151
2151
  }
2152
2152
 
2153
+ // src/constraint-drift.ts
2154
+ import { tableConstraints as tableConstraints2 } from "@drzl/validation-core";
2155
+ import { Chalk as Chalk4 } from "chalk";
2156
+ var PLAIN3 = new Chalk4({ level: 0 });
2157
+ var PLAIN_TEXT_TYPES = /* @__PURE__ */ new Set([
2158
+ "text",
2159
+ "varchar",
2160
+ "character varying",
2161
+ "char",
2162
+ "character",
2163
+ "bpchar",
2164
+ "citext",
2165
+ "tinytext",
2166
+ "mediumtext",
2167
+ "longtext",
2168
+ "nvarchar",
2169
+ "nchar"
2170
+ ]);
2171
+ function typeStem(sqlType) {
2172
+ return sqlType.replace(/\(.*$/, "").replace(/\[\]$/, "").trim().toLowerCase();
2173
+ }
2174
+ function isSchemaOnlyEnum(column) {
2175
+ if (!column.enumValues || column.enumValues.length === 0) return false;
2176
+ if (!column.sqlType) return false;
2177
+ return PLAIN_TEXT_TYPES.has(typeStem(column.sqlType));
2178
+ }
2179
+ function sqlLiterals(values) {
2180
+ return values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ");
2181
+ }
2182
+ function derivedName(table, column) {
2183
+ return `${table}_${column}_check`;
2184
+ }
2185
+ function buildConstraintDriftReport(analysis, schemaPath) {
2186
+ const entries = [];
2187
+ for (const table of analysis.tables) {
2188
+ for (const c of tableConstraints2(table).constraints) {
2189
+ if (c.enforced) {
2190
+ for (const part of c.unenforced ?? []) {
2191
+ entries.push({
2192
+ side: "database-only",
2193
+ table: table.name,
2194
+ columns: [...c.columns],
2195
+ rule: part.part,
2196
+ reason: part.reason,
2197
+ ...c.name ? { constraint: c.name } : {}
2198
+ });
2199
+ }
2200
+ continue;
2201
+ }
2202
+ entries.push({
2203
+ side: "database-only",
2204
+ table: table.name,
2205
+ columns: [...c.columns],
2206
+ rule: c.rule,
2207
+ reason: reasonFor(c.kind, c.unenforced),
2208
+ ...c.name ? { constraint: c.name } : {}
2209
+ });
2210
+ }
2211
+ for (const column of table.columns) {
2212
+ if (!isSchemaOnlyEnum(column)) continue;
2213
+ const values = column.enumValues;
2214
+ entries.push({
2215
+ side: "schema-only",
2216
+ table: table.name,
2217
+ columns: [column.name],
2218
+ rule: `${column.name} IN (${sqlLiterals(values)})`,
2219
+ reason: `the column is declared ${column.sqlType}, which holds any text; the set exists only in the generated schemas`,
2220
+ fix: `ALTER TABLE ${table.name} ADD CONSTRAINT ${derivedName(table.name, column.name)} CHECK (${column.name} IN (${sqlLiterals(values)}));`
2221
+ });
2222
+ }
2223
+ }
2224
+ const databaseOnly = entries.filter((e) => e.side === "database-only").length;
2225
+ const schemaOnly = entries.filter((e) => e.side === "schema-only").length;
2226
+ return {
2227
+ schema: schemaPath,
2228
+ dialect: analysis.dialect,
2229
+ ok: entries.length === 0,
2230
+ counts: { tables: analysis.tables.length, databaseOnly, schemaOnly },
2231
+ entries
2232
+ };
2233
+ }
2234
+ function reasonFor(kind, unenforced) {
2235
+ if (unenforced && unenforced.length) return unenforced.map((u) => u.reason).join("; ");
2236
+ switch (kind) {
2237
+ case "primaryKey":
2238
+ case "unique":
2239
+ return "whether a value is already taken is a fact about the table, not about one row";
2240
+ case "foreignKey":
2241
+ return "whether the referenced row exists is a question only the database can answer";
2242
+ default:
2243
+ return "no generated schema states it";
2244
+ }
2245
+ }
2246
+ function wrap3(text, indent, first = indent, width = 96) {
2247
+ const words = text.split(/\s+/).filter(Boolean);
2248
+ const lines = [];
2249
+ let line = first;
2250
+ let started = false;
2251
+ for (const w of words) {
2252
+ if (started && line.length + 1 + w.length > width) {
2253
+ lines.push(line);
2254
+ line = indent + w;
2255
+ } else {
2256
+ line = started ? `${line} ${w}` : line + w;
2257
+ started = true;
2258
+ }
2259
+ }
2260
+ if (started) lines.push(line);
2261
+ return lines.join("\n");
2262
+ }
2263
+ function renderConstraintDriftReport(report, style = PLAIN3) {
2264
+ const chalk = style;
2265
+ const out = [];
2266
+ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
2267
+ out.push(chalk.bold(`DRZL constraint drift ${report.schema}`));
2268
+ out.push(chalk.dim(`${report.dialect}, ${plural(report.counts.tables, "table")}`));
2269
+ out.push("");
2270
+ if (report.ok) {
2271
+ out.push(chalk.green("No drift."));
2272
+ out.push(chalk.dim(" Every constraint the database declares is one the generated schemas state."));
2273
+ out.push(chalk.dim(" Every set the generated schemas restrict is one the database enforces."));
2274
+ return out.join("\n");
2275
+ }
2276
+ const schemaOnly = report.entries.filter((e) => e.side === "schema-only");
2277
+ if (schemaOnly.length) {
2278
+ out.push(chalk.yellow("Your schemas enforce this and the database does not"));
2279
+ out.push(
2280
+ chalk.dim(
2281
+ wrap3(
2282
+ "Any other client writes past these. A migration, a psql session or an admin tool is not running your validators.",
2283
+ " "
2284
+ )
2285
+ )
2286
+ );
2287
+ out.push("");
2288
+ for (const e of schemaOnly) {
2289
+ out.push(` ${chalk.dim("-")} ${chalk.bold(e.table)}.${e.columns.join(", ")}`);
2290
+ out.push(wrap3(e.rule, " "));
2291
+ out.push(chalk.dim(wrap3(e.reason, " ")));
2292
+ if (e.fix) {
2293
+ out.push(chalk.dim(" Close it with:"));
2294
+ out.push(` ${e.fix}`);
2295
+ }
2296
+ out.push("");
2297
+ }
2298
+ }
2299
+ const databaseOnly = report.entries.filter((e) => e.side === "database-only");
2300
+ if (databaseOnly.length) {
2301
+ out.push(chalk.cyan("The database enforces this and your schemas do not"));
2302
+ out.push(
2303
+ chalk.dim(
2304
+ wrap3(
2305
+ "Mostly not a defect: a key, a unique index and a foreign key are facts about the table rather than about one row, so no per-row validator can see them. Listed so nobody reads the generated schemas as the whole story.",
2306
+ " "
2307
+ )
2308
+ )
2309
+ );
2310
+ out.push("");
2311
+ for (const e of databaseOnly) {
2312
+ const name = e.constraint ? ` ${chalk.dim(`(${e.constraint})`)}` : "";
2313
+ out.push(` ${chalk.dim("-")} ${chalk.bold(e.table)}${name}`);
2314
+ out.push(wrap3(e.rule, " "));
2315
+ out.push(chalk.dim(wrap3(e.reason, " ")));
2316
+ out.push("");
2317
+ }
2318
+ }
2319
+ out.push(
2320
+ chalk.dim(
2321
+ `${plural(report.counts.schemaOnly, "gap")} your schemas alone enforce, ${plural(report.counts.databaseOnly, "constraint")} only the database does.`
2322
+ )
2323
+ );
2324
+ return out.join("\n");
2325
+ }
2326
+
2153
2327
  // src/drift.ts
2154
2328
  import { promises as fs2 } from "fs";
2155
2329
  import path2 from "path";
@@ -3072,7 +3246,10 @@ withOutputFlags(
3072
3246
  }
3073
3247
  });
3074
3248
  withOutputFlags(
3075
- program.command("doctor").description("Report what DRZL cannot type or enforce in your schema, and why").argument("[schema]", "path to drizzle schema (TS); defaults to the schema in drzl.config").option("-c, --config <path>", "path to drzl.config, read when no schema argument is given").option("--strict", "exit 2 when anything is reported", false)
3249
+ program.command("doctor").description("Report what DRZL cannot type or enforce in your schema, and why").argument("[schema]", "path to drizzle schema (TS); defaults to the schema in drzl.config").option("-c, --config <path>", "path to drzl.config, read when no schema argument is given").option("--strict", "exit 2 when anything is reported", false).option(
3250
+ "--constraints",
3251
+ "report what each side enforces that the other does not, instead of the usual findings"
3252
+ )
3076
3253
  ).action(async (schema, opts) => {
3077
3254
  const out = outputFor(opts);
3078
3255
  {
@@ -3094,10 +3271,34 @@ withOutputFlags(
3094
3271
  includeRelations: true,
3095
3272
  validateConstraints: true
3096
3273
  });
3097
- const report = buildDoctorReport(
3098
- analysis,
3099
- Array.isArray(target) ? target.join(", ") : target
3100
- );
3274
+ const schemaLabel = Array.isArray(target) ? target.join(", ") : target;
3275
+ if (opts.constraints) {
3276
+ const preflight = buildDoctorReport(analysis, schemaLabel);
3277
+ const fatal = preflight.findings.filter((f) => f.level === "error");
3278
+ if (fatal.length) {
3279
+ if (opts.json)
3280
+ out.data(
3281
+ JSON.stringify(
3282
+ { command: "doctor", exitCode: EXIT_FAILED, ...preflight },
3283
+ null,
3284
+ 2
3285
+ )
3286
+ );
3287
+ else out.data(renderDoctorReport(preflight, out.outStyle));
3288
+ process.exit(EXIT_FAILED);
3289
+ return;
3290
+ }
3291
+ const drift = buildConstraintDriftReport(analysis, schemaLabel);
3292
+ const driftCode = opts.strict && drift.counts.schemaOnly ? EXIT_FINDINGS : EXIT_OK;
3293
+ if (opts.json)
3294
+ out.data(
3295
+ JSON.stringify({ command: "doctor", exitCode: driftCode, ...drift }, null, 2)
3296
+ );
3297
+ else out.data(renderConstraintDriftReport(drift, out.outStyle));
3298
+ process.exit(driftCode);
3299
+ return;
3300
+ }
3301
+ const report = buildDoctorReport(analysis, schemaLabel);
3101
3302
  const unreadable = report.findings.some((f) => f.level === "error");
3102
3303
  const code = unreadable ? EXIT_FAILED : opts.strict && report.findings.length ? EXIT_FINDINGS : EXIT_OK;
3103
3304
  if (opts.json)