@drzl/cli 4.34.0 → 4.36.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,240 @@ 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
+ var ADD_CONSTRAINT_DIALECTS = /* @__PURE__ */ new Set([
3380
+ "postgres",
3381
+ "cockroach",
3382
+ "gel",
3383
+ "mysql",
3384
+ "singlestore",
3385
+ "mssql"
3386
+ ]);
3387
+ function fixFor(dialect, table, column, values) {
3388
+ if (!ADD_CONSTRAINT_DIALECTS.has(dialect)) return void 0;
3389
+ return `ALTER TABLE ${table} ADD CONSTRAINT ${derivedName(table, column)} CHECK (${column} IN (${sqlLiterals(values)}));`;
3390
+ }
3391
+ function noFixReason(dialect) {
3392
+ if (dialect === "sqlite") {
3393
+ return "SQLite cannot add a CHECK to an existing column: ALTER TABLE ... ADD CONSTRAINT is a syntax error there. Closing this means rebuilding the table, which is the twelve-step procedure SQLite documents: create the new table with the constraint, copy the rows, drop the old one, rename.";
3394
+ }
3395
+ return `no statement is emitted for the "${dialect}" dialect, which this report cannot name a fix for`;
3396
+ }
3397
+ function buildConstraintDriftReport(analysis, schemaPath) {
3398
+ const entries = [];
3399
+ for (const table of analysis.tables) {
3400
+ for (const c of (0, import_validation_core5.tableConstraints)(table).constraints) {
3401
+ if (c.enforced) {
3402
+ for (const part of c.unenforced ?? []) {
3403
+ entries.push({
3404
+ side: "database-only",
3405
+ table: table.name,
3406
+ columns: [...c.columns],
3407
+ rule: part.part,
3408
+ reason: part.reason,
3409
+ ...c.name ? { constraint: c.name } : {}
3410
+ });
3411
+ }
3412
+ continue;
3413
+ }
3414
+ entries.push({
3415
+ side: "database-only",
3416
+ table: table.name,
3417
+ columns: [...c.columns],
3418
+ rule: c.rule,
3419
+ reason: reasonFor(c.kind, c.unenforced),
3420
+ ...c.name ? { constraint: c.name } : {}
3421
+ });
3422
+ }
3423
+ for (const column of table.columns) {
3424
+ if (!isSchemaOnlyEnum(column)) continue;
3425
+ const values = column.enumValues;
3426
+ entries.push({
3427
+ side: "schema-only",
3428
+ table: table.name,
3429
+ columns: [column.name],
3430
+ rule: `${column.name} IN (${sqlLiterals(values)})`,
3431
+ reason: `the column is declared ${column.sqlType}, which holds any text; the set exists only in the generated schemas`,
3432
+ ...(() => {
3433
+ const fix = fixFor(analysis.dialect, table.name, column.name, values);
3434
+ return fix ? { fix } : { noFix: noFixReason(analysis.dialect) };
3435
+ })()
3436
+ });
3437
+ }
3438
+ }
3439
+ const databaseOnly = entries.filter((e) => e.side === "database-only").length;
3440
+ const schemaOnly = entries.filter((e) => e.side === "schema-only").length;
3441
+ return {
3442
+ schema: schemaPath,
3443
+ dialect: analysis.dialect,
3444
+ ok: entries.length === 0,
3445
+ counts: { tables: analysis.tables.length, databaseOnly, schemaOnly },
3446
+ entries
3447
+ };
3448
+ }
3449
+ function reasonFor(kind, unenforced) {
3450
+ if (unenforced && unenforced.length) return unenforced.map((u) => u.reason).join("; ");
3451
+ switch (kind) {
3452
+ case "primaryKey":
3453
+ case "unique":
3454
+ return "whether a value is already taken is a fact about the table, not about one row";
3455
+ case "foreignKey":
3456
+ return "whether the referenced row exists is a question only the database can answer";
3457
+ default:
3458
+ return "no generated schema states it";
3459
+ }
3460
+ }
3461
+ function wrap3(text, indent, first = indent, width = 96) {
3462
+ const words = text.split(/\s+/).filter(Boolean);
3463
+ const lines = [];
3464
+ let line = first;
3465
+ let started = false;
3466
+ for (const w of words) {
3467
+ if (started && line.length + 1 + w.length > width) {
3468
+ lines.push(line);
3469
+ line = indent + w;
3470
+ } else {
3471
+ line = started ? `${line} ${w}` : line + w;
3472
+ started = true;
3473
+ }
3474
+ }
3475
+ if (started) lines.push(line);
3476
+ return lines.join("\n");
3477
+ }
3478
+ function renderConstraintDriftReport(report, style = PLAIN3) {
3479
+ const chalk = style;
3480
+ const out = [];
3481
+ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
3482
+ out.push(chalk.bold(`DRZL constraint drift ${report.schema}`));
3483
+ out.push(chalk.dim(`${report.dialect}, ${plural(report.counts.tables, "table")}`));
3484
+ out.push("");
3485
+ if (report.ok) {
3486
+ out.push(chalk.green("No drift."));
3487
+ out.push(chalk.dim(" Every constraint the database declares is one the generated schemas state."));
3488
+ out.push(chalk.dim(" Every set the generated schemas restrict is one the database enforces."));
3489
+ return out.join("\n");
3490
+ }
3491
+ const schemaOnly = report.entries.filter((e) => e.side === "schema-only");
3492
+ if (schemaOnly.length) {
3493
+ out.push(chalk.yellow("Your schemas enforce this and the database does not"));
3494
+ out.push(
3495
+ chalk.dim(
3496
+ wrap3(
3497
+ "Any other client writes past these. A migration, a psql session or an admin tool is not running your validators.",
3498
+ " "
3499
+ )
3500
+ )
3501
+ );
3502
+ out.push("");
3503
+ for (const e of schemaOnly) {
3504
+ out.push(` ${chalk.dim("-")} ${chalk.bold(e.table)}.${e.columns.join(", ")}`);
3505
+ out.push(wrap3(e.rule, " "));
3506
+ out.push(chalk.dim(wrap3(e.reason, " ")));
3507
+ if (e.fix) {
3508
+ out.push(chalk.dim(" Close it with:"));
3509
+ out.push(` ${e.fix}`);
3510
+ } else if (e.noFix) {
3511
+ out.push(chalk.dim(wrap3(e.noFix, " ", " Not one statement here: ")));
3512
+ }
3513
+ out.push("");
3514
+ }
3515
+ }
3516
+ const databaseOnly = report.entries.filter((e) => e.side === "database-only");
3517
+ if (databaseOnly.length) {
3518
+ out.push(chalk.cyan("The database enforces this and your schemas do not"));
3519
+ out.push(
3520
+ chalk.dim(
3521
+ wrap3(
3522
+ "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.",
3523
+ " "
3524
+ )
3525
+ )
3526
+ );
3527
+ out.push("");
3528
+ for (const e of databaseOnly) {
3529
+ const name = e.constraint ? ` ${chalk.dim(`(${e.constraint})`)}` : "";
3530
+ out.push(` ${chalk.dim("-")} ${chalk.bold(e.table)}${name}`);
3531
+ out.push(wrap3(e.rule, " "));
3532
+ out.push(chalk.dim(wrap3(e.reason, " ")));
3533
+ out.push("");
3534
+ }
3535
+ }
3536
+ out.push(
3537
+ chalk.dim(
3538
+ `${plural(report.counts.schemaOnly, "gap")} your schemas alone enforce, ${plural(report.counts.databaseOnly, "constraint")} only the database does.`
3539
+ )
3540
+ );
3541
+ return out.join("\n");
3542
+ }
3543
+ function renderConstraintDriftSql(report) {
3544
+ const gaps = report.entries.filter((e) => e.side === "schema-only");
3545
+ if (!gaps.length) return "";
3546
+ const out = [];
3547
+ const runnable = gaps.filter((g) => g.fix);
3548
+ const unrunnable = gaps.filter((g) => !g.fix);
3549
+ out.push(`-- Generated by drzl doctor --constraints --sql`);
3550
+ out.push(`-- ${report.schema}, ${report.dialect}`);
3551
+ out.push(
3552
+ `-- ${runnable.length} constraint(s) your schemas enforce and the database does not.`
3553
+ );
3554
+ if (unrunnable.length) {
3555
+ out.push(
3556
+ `-- ${unrunnable.length} more cannot be closed by one statement on this dialect; see below.`
3557
+ );
3558
+ }
3559
+ out.push("");
3560
+ const byPlace = (a, b) => a.table.localeCompare(b.table) || a.columns.join().localeCompare(b.columns.join());
3561
+ for (const g of [...runnable].sort(byPlace)) {
3562
+ out.push(`-- ${g.table}.${g.columns.join(", ")}: ${g.reason}`);
3563
+ out.push(g.fix);
3564
+ out.push("");
3565
+ }
3566
+ if (unrunnable.length) {
3567
+ out.push("-- The rest, which this dialect cannot do in one statement:");
3568
+ for (const g of [...unrunnable].sort(byPlace)) {
3569
+ out.push(`--`);
3570
+ out.push(`-- ${g.table}.${g.columns.join(", ")}`);
3571
+ out.push(`-- ${g.rule}`);
3572
+ for (const line of (g.noFix ?? "").match(/.{1,88}(\s|$)/g) ?? []) {
3573
+ out.push(`-- ${line.trim()}`);
3574
+ }
3575
+ }
3576
+ out.push("");
3577
+ }
3578
+ return out.join("\n");
3579
+ }
3580
+
3347
3581
  // src/drift.ts
3348
3582
  var import_node_fs = require("fs");
3349
3583
  var import_node_path = __toESM(require("path"), 1);
@@ -4266,7 +4500,10 @@ withOutputFlags(
4266
4500
  }
4267
4501
  });
4268
4502
  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)
4503
+ 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(
4504
+ "--constraints",
4505
+ "report what each side enforces that the other does not, instead of the usual findings"
4506
+ ).option("--sql", "with --constraints, emit the statements alone, for redirecting to a migration")
4270
4507
  ).action(async (schema, opts) => {
4271
4508
  const out = outputFor(opts);
4272
4509
  {
@@ -4288,10 +4525,46 @@ withOutputFlags(
4288
4525
  includeRelations: true,
4289
4526
  validateConstraints: true
4290
4527
  });
4291
- const report = buildDoctorReport(
4292
- analysis,
4293
- Array.isArray(target) ? target.join(", ") : target
4294
- );
4528
+ const schemaLabel = Array.isArray(target) ? target.join(", ") : target;
4529
+ if (opts.sql && !opts.constraints) {
4530
+ const msg = "--sql reports the constraint drift as statements, so it needs --constraints.";
4531
+ if (opts.json) out.jsonData(jsonFailure("doctor", "DRZL_CLI_DOCTOR", msg));
4532
+ else out.error("Doctor failed (DRZL_CLI_DOCTOR):", msg);
4533
+ process.exit(EXIT_FAILED);
4534
+ return;
4535
+ }
4536
+ if (opts.constraints) {
4537
+ const preflight = buildDoctorReport(analysis, schemaLabel);
4538
+ const fatal = preflight.findings.filter((f) => f.level === "error");
4539
+ if (fatal.length) {
4540
+ if (opts.json)
4541
+ out.data(
4542
+ JSON.stringify(
4543
+ { command: "doctor", exitCode: EXIT_FAILED, ...preflight },
4544
+ null,
4545
+ 2
4546
+ )
4547
+ );
4548
+ else out.data(renderDoctorReport(preflight, out.outStyle));
4549
+ process.exit(EXIT_FAILED);
4550
+ return;
4551
+ }
4552
+ const drift = buildConstraintDriftReport(analysis, schemaLabel);
4553
+ const driftCode = opts.strict && drift.counts.schemaOnly ? EXIT_FINDINGS : EXIT_OK;
4554
+ if (opts.sql) {
4555
+ out.data(renderConstraintDriftSql(drift));
4556
+ process.exit(driftCode);
4557
+ return;
4558
+ }
4559
+ if (opts.json)
4560
+ out.data(
4561
+ JSON.stringify({ command: "doctor", exitCode: driftCode, ...drift }, null, 2)
4562
+ );
4563
+ else out.data(renderConstraintDriftReport(drift, out.outStyle));
4564
+ process.exit(driftCode);
4565
+ return;
4566
+ }
4567
+ const report = buildDoctorReport(analysis, schemaLabel);
4295
4568
  const unreadable = report.findings.some((f) => f.level === "error");
4296
4569
  const code = unreadable ? EXIT_FAILED : opts.strict && report.findings.length ? EXIT_FINDINGS : EXIT_OK;
4297
4570
  if (opts.json)