@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.cjs CHANGED
@@ -3344,6 +3344,180 @@ async function resolveSchemaSource(cfg, cwd = process.cwd()) {
3344
3344
  };
3345
3345
  }
3346
3346
 
3347
+ // src/constraint-drift.ts
3348
+ var import_validation_core5 = require("@drzl/validation-core");
3349
+ var import_chalk4 = require("chalk");
3350
+ var PLAIN3 = new import_chalk4.Chalk({ level: 0 });
3351
+ var PLAIN_TEXT_TYPES = /* @__PURE__ */ new Set([
3352
+ "text",
3353
+ "varchar",
3354
+ "character varying",
3355
+ "char",
3356
+ "character",
3357
+ "bpchar",
3358
+ "citext",
3359
+ "tinytext",
3360
+ "mediumtext",
3361
+ "longtext",
3362
+ "nvarchar",
3363
+ "nchar"
3364
+ ]);
3365
+ function typeStem(sqlType) {
3366
+ return sqlType.replace(/\(.*$/, "").replace(/\[\]$/, "").trim().toLowerCase();
3367
+ }
3368
+ function isSchemaOnlyEnum(column) {
3369
+ if (!column.enumValues || column.enumValues.length === 0) return false;
3370
+ if (!column.sqlType) return false;
3371
+ return PLAIN_TEXT_TYPES.has(typeStem(column.sqlType));
3372
+ }
3373
+ function sqlLiterals(values) {
3374
+ return values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ");
3375
+ }
3376
+ function derivedName(table, column) {
3377
+ return `${table}_${column}_check`;
3378
+ }
3379
+ function buildConstraintDriftReport(analysis, schemaPath) {
3380
+ const entries = [];
3381
+ for (const table of analysis.tables) {
3382
+ for (const c of (0, import_validation_core5.tableConstraints)(table).constraints) {
3383
+ if (c.enforced) {
3384
+ for (const part of c.unenforced ?? []) {
3385
+ entries.push({
3386
+ side: "database-only",
3387
+ table: table.name,
3388
+ columns: [...c.columns],
3389
+ rule: part.part,
3390
+ reason: part.reason,
3391
+ ...c.name ? { constraint: c.name } : {}
3392
+ });
3393
+ }
3394
+ continue;
3395
+ }
3396
+ entries.push({
3397
+ side: "database-only",
3398
+ table: table.name,
3399
+ columns: [...c.columns],
3400
+ rule: c.rule,
3401
+ reason: reasonFor(c.kind, c.unenforced),
3402
+ ...c.name ? { constraint: c.name } : {}
3403
+ });
3404
+ }
3405
+ for (const column of table.columns) {
3406
+ if (!isSchemaOnlyEnum(column)) continue;
3407
+ const values = column.enumValues;
3408
+ entries.push({
3409
+ side: "schema-only",
3410
+ table: table.name,
3411
+ columns: [column.name],
3412
+ rule: `${column.name} IN (${sqlLiterals(values)})`,
3413
+ reason: `the column is declared ${column.sqlType}, which holds any text; the set exists only in the generated schemas`,
3414
+ fix: `ALTER TABLE ${table.name} ADD CONSTRAINT ${derivedName(table.name, column.name)} CHECK (${column.name} IN (${sqlLiterals(values)}));`
3415
+ });
3416
+ }
3417
+ }
3418
+ const databaseOnly = entries.filter((e) => e.side === "database-only").length;
3419
+ const schemaOnly = entries.filter((e) => e.side === "schema-only").length;
3420
+ return {
3421
+ schema: schemaPath,
3422
+ dialect: analysis.dialect,
3423
+ ok: entries.length === 0,
3424
+ counts: { tables: analysis.tables.length, databaseOnly, schemaOnly },
3425
+ entries
3426
+ };
3427
+ }
3428
+ function reasonFor(kind, unenforced) {
3429
+ if (unenforced && unenforced.length) return unenforced.map((u) => u.reason).join("; ");
3430
+ switch (kind) {
3431
+ case "primaryKey":
3432
+ case "unique":
3433
+ return "whether a value is already taken is a fact about the table, not about one row";
3434
+ case "foreignKey":
3435
+ return "whether the referenced row exists is a question only the database can answer";
3436
+ default:
3437
+ return "no generated schema states it";
3438
+ }
3439
+ }
3440
+ function wrap3(text, indent, first = indent, width = 96) {
3441
+ const words = text.split(/\s+/).filter(Boolean);
3442
+ const lines = [];
3443
+ let line = first;
3444
+ let started = false;
3445
+ for (const w of words) {
3446
+ if (started && line.length + 1 + w.length > width) {
3447
+ lines.push(line);
3448
+ line = indent + w;
3449
+ } else {
3450
+ line = started ? `${line} ${w}` : line + w;
3451
+ started = true;
3452
+ }
3453
+ }
3454
+ if (started) lines.push(line);
3455
+ return lines.join("\n");
3456
+ }
3457
+ function renderConstraintDriftReport(report, style = PLAIN3) {
3458
+ const chalk = style;
3459
+ const out = [];
3460
+ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
3461
+ out.push(chalk.bold(`DRZL constraint drift ${report.schema}`));
3462
+ out.push(chalk.dim(`${report.dialect}, ${plural(report.counts.tables, "table")}`));
3463
+ out.push("");
3464
+ if (report.ok) {
3465
+ out.push(chalk.green("No drift."));
3466
+ out.push(chalk.dim(" Every constraint the database declares is one the generated schemas state."));
3467
+ out.push(chalk.dim(" Every set the generated schemas restrict is one the database enforces."));
3468
+ return out.join("\n");
3469
+ }
3470
+ const schemaOnly = report.entries.filter((e) => e.side === "schema-only");
3471
+ if (schemaOnly.length) {
3472
+ out.push(chalk.yellow("Your schemas enforce this and the database does not"));
3473
+ out.push(
3474
+ chalk.dim(
3475
+ wrap3(
3476
+ "Any other client writes past these. A migration, a psql session or an admin tool is not running your validators.",
3477
+ " "
3478
+ )
3479
+ )
3480
+ );
3481
+ out.push("");
3482
+ for (const e of schemaOnly) {
3483
+ out.push(` ${chalk.dim("-")} ${chalk.bold(e.table)}.${e.columns.join(", ")}`);
3484
+ out.push(wrap3(e.rule, " "));
3485
+ out.push(chalk.dim(wrap3(e.reason, " ")));
3486
+ if (e.fix) {
3487
+ out.push(chalk.dim(" Close it with:"));
3488
+ out.push(` ${e.fix}`);
3489
+ }
3490
+ out.push("");
3491
+ }
3492
+ }
3493
+ const databaseOnly = report.entries.filter((e) => e.side === "database-only");
3494
+ if (databaseOnly.length) {
3495
+ out.push(chalk.cyan("The database enforces this and your schemas do not"));
3496
+ out.push(
3497
+ chalk.dim(
3498
+ wrap3(
3499
+ "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.",
3500
+ " "
3501
+ )
3502
+ )
3503
+ );
3504
+ out.push("");
3505
+ for (const e of databaseOnly) {
3506
+ const name = e.constraint ? ` ${chalk.dim(`(${e.constraint})`)}` : "";
3507
+ out.push(` ${chalk.dim("-")} ${chalk.bold(e.table)}${name}`);
3508
+ out.push(wrap3(e.rule, " "));
3509
+ out.push(chalk.dim(wrap3(e.reason, " ")));
3510
+ out.push("");
3511
+ }
3512
+ }
3513
+ out.push(
3514
+ chalk.dim(
3515
+ `${plural(report.counts.schemaOnly, "gap")} your schemas alone enforce, ${plural(report.counts.databaseOnly, "constraint")} only the database does.`
3516
+ )
3517
+ );
3518
+ return out.join("\n");
3519
+ }
3520
+
3347
3521
  // src/drift.ts
3348
3522
  var import_node_fs = require("fs");
3349
3523
  var import_node_path = __toESM(require("path"), 1);
@@ -4266,7 +4440,10 @@ withOutputFlags(
4266
4440
  }
4267
4441
  });
4268
4442
  withOutputFlags(
4269
- 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)
4443
+ 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(
4444
+ "--constraints",
4445
+ "report what each side enforces that the other does not, instead of the usual findings"
4446
+ )
4270
4447
  ).action(async (schema, opts) => {
4271
4448
  const out = outputFor(opts);
4272
4449
  {
@@ -4288,10 +4465,34 @@ withOutputFlags(
4288
4465
  includeRelations: true,
4289
4466
  validateConstraints: true
4290
4467
  });
4291
- const report = buildDoctorReport(
4292
- analysis,
4293
- Array.isArray(target) ? target.join(", ") : target
4294
- );
4468
+ const schemaLabel = Array.isArray(target) ? target.join(", ") : target;
4469
+ if (opts.constraints) {
4470
+ const preflight = buildDoctorReport(analysis, schemaLabel);
4471
+ const fatal = preflight.findings.filter((f) => f.level === "error");
4472
+ if (fatal.length) {
4473
+ if (opts.json)
4474
+ out.data(
4475
+ JSON.stringify(
4476
+ { command: "doctor", exitCode: EXIT_FAILED, ...preflight },
4477
+ null,
4478
+ 2
4479
+ )
4480
+ );
4481
+ else out.data(renderDoctorReport(preflight, out.outStyle));
4482
+ process.exit(EXIT_FAILED);
4483
+ return;
4484
+ }
4485
+ const drift = buildConstraintDriftReport(analysis, schemaLabel);
4486
+ const driftCode = opts.strict && drift.counts.schemaOnly ? EXIT_FINDINGS : EXIT_OK;
4487
+ if (opts.json)
4488
+ out.data(
4489
+ JSON.stringify({ command: "doctor", exitCode: driftCode, ...drift }, null, 2)
4490
+ );
4491
+ else out.data(renderConstraintDriftReport(drift, out.outStyle));
4492
+ process.exit(driftCode);
4493
+ return;
4494
+ }
4495
+ const report = buildDoctorReport(analysis, schemaLabel);
4295
4496
  const unreadable = report.findings.some((f) => f.level === "error");
4296
4497
  const code = unreadable ? EXIT_FAILED : opts.strict && report.findings.length ? EXIT_FINDINGS : EXIT_OK;
4297
4498
  if (opts.json)