Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: a new required column must ship a default value
aashu046ef594896d
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex b7f11b76ae..48026172f8 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -428,8 +428,6 @@"no-raw-rounding::apps/erp/app/routes/x+/resources+/_index.tsx::{percentageChange.toFixed(0)}%","no-raw-rounding::apps/erp/app/routes/x+/sales+/_index.tsx::<Badge variant=\"green\">+{percentageChange.toFixed(0)}%</Badge>","no-raw-rounding::apps/erp/app/routes/x+/sales+/_index.tsx::<Badge variant=\"red\">{percentageChange.toFixed(0)}%</Badge>",- "no-raw-rounding::apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx::const now = Math.floor(Date.now() / 1000);",- "no-raw-rounding::apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx::return Math.floor(","no-raw-rounding::apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx::size: Math.round(file.byteLength / 1024),","no-raw-rounding::apps/erp/app/routes/x+/settings+/backups.tsx::{convertKbToString(Math.round(file.sizeBytes / 1024))}","no-raw-rounding::apps/erp/app/routes/x+/settings+/printing.tsx::const heightDots = Math.round(height * dpi);",@@ -507,8 +505,6 @@"no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts::const cents = Math.round(","no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts::const cents = Math.round(amount * 100);","no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts::const cents = Math.round(line.amount * 100);",- "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.ts::: Math.floor(Date.now() / 1000) - 60 * 60 * 24 * 7; // 7 days max",- "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.ts::? Math.floor(new Date(target.updatedAt).getTime() / 1000)","no-raw-rounding::packages/jobs/src/inngest/functions/scheduled/cleanup.ts::await step.sleep(\"jitter\", `${Math.floor(Math.random() * 3600)}s`);","no-raw-rounding::packages/react/src/BarProgress.tsx::<span className=\"sr-only\">{Math.round(percentage)}%</span>","no-raw-rounding::packages/react/src/BarProgress.tsx::const activeBars = Math.round((clampedProgress / max) * barCount);",@@ -530,5 +526,15 @@"no-raw-rounding::packages/utils/src/file.ts::return `${gb.toFixed(2)} GB`;","no-raw-rounding::packages/utils/src/file.ts::return `${mb.toFixed(2)} MB`;","no-raw-rounding::packages/utils/src/labels.ts::const heightMm = Math.round(size.height * 25.4);",- "no-raw-rounding::packages/utils/src/labels.ts::const widthMm = Math.round(size.width * 25.4);"+ "no-raw-rounding::packages/utils/src/labels.ts::const widthMm = Math.round(size.width * 25.4);",+ "no-required-column-without-default::20240621114604_method-rls.sql::ADD COLUMN \"description\" TEXT NOT NULL",+ "no-required-column-without-default::20240621114604_method-rls.sql::ADD COLUMN \"itemReadableId\" TEXT NOT NULL",+ "no-required-column-without-default::20240715024405_quotes.sql::ADD COLUMN \"quoteMakeMethodId\" TEXT NOT NULL",+ "no-required-column-without-default::20240811231527_convert-rfq.sql::ADD COLUMN \"customerPartId\" TEXT NOT NULL",+ "no-required-column-without-default::20240819115702_work-centers.sql::ADD COLUMN \"processId\" TEXT NOT NULL",+ "no-required-column-without-default::20240913162203_item-inventory.sql::ADD COLUMN IF NOT EXISTS \"name\" TEXT NOT NULL",+ "no-required-column-without-default::20240915192542_job-methods.sql::ADD COLUMN \"jobMakeMethodId\" TEXT NOT NULL",+ "no-required-column-without-default::20241210214820_purchasing-redux.sql::ADD COLUMN \"supplierInteractionId\" TEXT NOT NULL",+ "no-required-column-without-default::20241210214820_purchasing-redux.sql::ADD COLUMN IF NOT EXISTS \"supplierInteractionId\" TEXT NOT NULL",+ "no-required-column-without-default::20260402000000_journal-entries.sql::ADD COLUMN \"journalEntryId\" TEXT NOT NULL"]diff --git a/packages/checks/src/conformance/no-required-column-without-default.test.ts b/packages/checks/src/conformance/no-required-column-without-default.test.tsnew file mode 100644index 0000000000..4a5bc0094a--- /dev/null+++ b/packages/checks/src/conformance/no-required-column-without-default.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from "vitest";+import { noRequiredColumnWithoutDefault } from "./no-required-column-without-default";++const scan = (sql: string) => noRequiredColumnWithoutDefault.scan("m.sql", sql);++describe("no-required-column-without-default", () => {+ it("allows a new NOT NULL column that ships a DEFAULT", () => {+ expect(+ scan(+ `ALTER TABLE "item" ADD COLUMN "unitOfMeasure" TEXT NOT NULL DEFAULT 'EA';`+ )+ ).toEqual([]);+ });++ it("flags a new NOT NULL column with no DEFAULT, on the right line", () => {+ const sql = [+ `-- widen the item table`,+ ``,+ `ALTER TABLE "item" ADD COLUMN "unitOfMeasure" TEXT NOT NULL;`+ ].join("\n");++ const violations = scan(sql);+ expect(violations).toHaveLength(1);+ expect(violations[0]?.line).toBe(3);+ expect(violations[0]?.snippet).toContain("ADD COLUMN");+ expect(violations[0]?.message).toContain("unrestorable");+ });++ it("allows a nullable new column", () => {+ expect(scan(`ALTER TABLE "item" ADD COLUMN "notes" TEXT;`)).toEqual([]);+ });++ it("does not let a LATER column's DEFAULT excuse an earlier one", () => {+ // The bounded span is what makes this work: without it, the DEFAULT on+ // "b" would satisfy the lookahead for "a" and the real violation would+ // pass silently.+ const violations = scan(+ `ALTER TABLE "item" ADD COLUMN "a" TEXT NOT NULL, ADD COLUMN "b" TEXT NOT NULL DEFAULT '';`+ );+ expect(violations).toHaveLength(1);+ expect(violations[0]?.snippet).toContain(`"a"`);+ });++ it("ignores NOT NULL appearing outside an ADD COLUMN", () => {+ const sql = [+ `CREATE TABLE "thing" ("id" TEXT NOT NULL, "companyId" TEXT NOT NULL);`,+ `ALTER TABLE "thing" ADD CONSTRAINT "thing_check" CHECK ("id" IS NOT NULL);`+ ].join("\n");+ expect(scan(sql)).toEqual([]);+ });++ it("ignores IS NOT NULL inside a generated column's expression", () => {+ // Real false positive from 20250115041610_backfill-release-date.sql: the+ // `IS NOT NULL` here is a predicate, not a column constraint, and a backup+ // can never supply a generated column anyway.+ expect(+ scan(+ `ALTER TABLE "job" ADD COLUMN "secondsToComplete" DECIMAL GENERATED ALWAYS AS ( CASE WHEN "releasedDate" IS NOT NULL THEN 1 ELSE 0 END ) STORED;`+ )+ ).toEqual([]);+ });++ it("ignores IS NOT NULL in a plain added column's expression", () => {+ expect(+ scan(+ `ALTER TABLE "job" ADD COLUMN "flag" BOOLEAN DEFAULT ("releasedDate" IS NOT NULL);`+ )+ ).toEqual([]);+ });++ it("handles ADD COLUMN IF NOT EXISTS", () => {+ expect(+ scan(`ALTER TABLE "item" ADD COLUMN IF NOT EXISTS "x" TEXT NOT NULL;`)+ ).toHaveLength(1);+ expect(+ scan(+ `ALTER TABLE "item" ADD COLUMN IF NOT EXISTS "x" TEXT NOT NULL DEFAULT '';`+ )+ ).toEqual([]);+ });+});diff --git a/packages/checks/src/conformance/no-required-column-without-default.ts b/packages/checks/src/conformance/no-required-column-without-default.tsnew file mode 100644index 0000000000..91353e537e--- /dev/null+++ b/packages/checks/src/conformance/no-required-column-without-default.ts@@ -0,0 +1,55 @@+import type { ConformanceCheck, Violation } from "../check";++/**+ * Matches `ADD COLUMN … NOT NULL` where the same column definition carries no+ * `DEFAULT`.+ *+ * `[^,;]*?` cannot cross a comma or a semicolon, so the match is confined to the+ * ONE column definition being added — a `DEFAULT` belonging to a later column in+ * the same `ALTER TABLE` cannot satisfy an earlier one, and a `NOT NULL` in a+ * following statement cannot be attributed to this column.+ *+ * The negative lookahead is applied over that same bounded span, which is what+ * makes "has no DEFAULT" mean "this column has no DEFAULT" rather than "the file+ * has no DEFAULT anywhere".+ *+ * `(?<!\bIS\s+)` excludes `IS NOT NULL`, which is a predicate and not a column+ * constraint. Without it, a generated column whose expression contains+ * `CASE WHEN "x" IS NOT NULL` is reported as a required column — that is a real+ * false positive this check produced on+ * `20250115041610_backfill-release-date.sql`.+ *+ * `GENERATED` columns are skipped outright: a backup can never supply one, and+ * `reportBackupCompatibility` already excludes them for the same reason.+ *+ * Only the `ADD COLUMN` form is checked. A `NOT NULL` column in a `CREATE TABLE`+ * is not a backup-compatibility problem: the table is simply absent from older+ * manifests, which `reportBackupCompatibility` already handles as a separate+ * finding. Detecting "CREATE TABLE for a table that already existed" is not+ * something a regex over one file can do honestly.+ */+const REQUIRED_COLUMN_NO_DEFAULT =+ /ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?(?!(?:[^,;]*?\b(?:DEFAULT|GENERATED)\b))[^,;]*?(?<!\bIS\s+)\bNOT\s+NULL\b/gi;++export const noRequiredColumnWithoutDefault: ConformanceCheck = {+ id: "no-required-column-without-default",+ description:+ "A new NOT NULL column must ship a DEFAULT, so existing backups stay restorable.",+ provenance: {+ deprecates: 'ADD COLUMN "x" TEXT NOT NULL',+ replacedBy: "ADD COLUMN \"x\" TEXT NOT NULL DEFAULT ''"+ },+ scan(file, contents) {+ const violations: Violation[] = [];+ for (const m of contents.matchAll(REQUIRED_COLUMN_NO_DEFAULT)) {+ violations.push({+ file,+ line: contents.slice(0, m.index).split("\n").length,+ snippet: m[0].replace(/\s+/g, " "),+ message:+ "A NOT NULL column with no DEFAULT makes every existing backup unrestorable — the backup has no value to supply for it, so the compatibility gate refuses the whole restore. Add a DEFAULT, or make the column nullable and backfill."+ });+ }+ return violations;+ }+};diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsindex f7c5988ea2..69a24524a1 100644--- a/packages/checks/src/index.ts+++ b/packages/checks/src/index.ts@@ -13,6 +13,7 @@ export { noLegacyRls } from "./conformance/no-legacy-rls";export { noLocalTimezone } from "./conformance/no-local-timezone";export { noNumericPrecision } from "./conformance/no-numeric-precision";export { noRawRounding } from "./conformance/no-raw-rounding";+export { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";export { noZeroConcurrency } from "./conformance/no-zero-concurrency";export {type Invariant,diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex bbc839ee17..990c030d9e 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -13,6 +13,7 @@ import { noLegacyRls } from "./conformance/no-legacy-rls";import { noLocalTimezone } from "./conformance/no-local-timezone";import { noNumericPrecision } from "./conformance/no-numeric-precision";import { noRawRounding } from "./conformance/no-raw-rounding";+import { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";import { noZeroConcurrency } from "./conformance/no-zero-concurrency";import { loadSqlFiles, migrationsDir, repoRoot } from "./sources/migrations";import { loadModules, modulesDir } from "./sources/modules";@@ -22,7 +23,8 @@ import { loadTypescriptFiles } from "./sources/typescript";export const CONFORMANCE_CHECKS: ConformanceCheck[] = [noNumericPrecision,noLegacyRls,- noDerivedPercentColumn+ noDerivedPercentColumn,+ noRequiredColumnWithoutDefault];/** Checks that run over server-side TS, not SQL migrations. */