@turingcode/cli 0.2.0 → 0.2.3

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.
@@ -1,10 +1,9 @@
1
1
  import { basename, dirname, join, resolve } from "node:path";
2
- import { Fraction } from "../../core/exact/fraction.js";
3
2
  import { readJsonFile } from "../../core/files.js";
4
3
  import { checkShape, show } from "../../core/json-shape.js";
5
4
  import { diag } from "./diagnostics.js";
6
- import { CONTRACT_SHAPE, keyColumns, RULE_BASE, whenColumns } from "./model.js";
7
- import { RULE_KINDS } from "./rules.js";
5
+ import { CONTRACT_SHAPE, keyColumns } from "./model.js";
6
+ import { checkQuery } from "./rules.js";
8
7
  /**
9
8
  * Parses a column reference.
10
9
  *
@@ -18,6 +17,16 @@ export function parseRef(ref) {
18
17
  const dot = rest.indexOf(".");
19
18
  return dot > 0 ? { alias, table: rest.slice(0, dot), column: rest.slice(dot + 1) } : { alias, table: null, column: rest };
20
19
  }
20
+ /**
21
+ * Parses a table reference (a rule's `on`).
22
+ *
23
+ * @param {string} ref - `Table` or `alias:Table`.
24
+ * @returns {{alias: string|null, table: string}} Its parts.
25
+ */
26
+ export function parseTableRef(ref) {
27
+ const colon = ref.indexOf(":");
28
+ return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
29
+ }
21
30
  /** A shape message without its leading JSON path, which the diagnostic already shows as its column. */
22
31
  const stripPath = (message, path) => message.replace(/^[^:]*: /, "") || path;
23
32
  /** Pushes CONTRACT.DUPLICATE for repeated names. */
@@ -29,42 +38,6 @@ function checkUnique(names, what, out, table) {
29
38
  seen.add(n);
30
39
  }
31
40
  }
32
- /**
33
- * Checks one column's constraints fit its type and each other.
34
- *
35
- * @param {Column} col - The column.
36
- * @param {Table} t - Its table.
37
- * @param {Diagnostic[]} out - Receives diagnostics.
38
- */
39
- function checkColumn(col, t, out) {
40
- const type = col.type ?? "string";
41
- const at = { table: t.name, column: col.name };
42
- const conflict = (message, found, expected) => out.push(diag("CONTRACT.CONFLICT", message, at, found, expected));
43
- const bounds = {};
44
- for (const key of ["minimum", "maximum"]) {
45
- if (col[key] === undefined)
46
- continue;
47
- if (type !== "integer" && type !== "number")
48
- conflict(`${key} needs an integer or number column`, type, "integer or number");
49
- bounds[key] = Fraction.parseDecimal(String(col[key]));
50
- if (!bounds[key])
51
- out.push(diag("CONTRACT.BAD_FIELD", `${key} is not a number`, at, String(col[key]), "a number"));
52
- }
53
- if (bounds.minimum && bounds.maximum && bounds.minimum.cmp(bounds.maximum) > 0) {
54
- conflict("minimum is greater than maximum", `${col.minimum} > ${col.maximum}`, "minimum <= maximum");
55
- }
56
- for (const key of ["min_length", "max_length"]) {
57
- if (col[key] !== undefined && type !== "string" && type !== "list")
58
- conflict(`${key} needs a string or list column`, type, "string or list");
59
- }
60
- if (col.min_length !== undefined && col.max_length !== undefined && col.min_length > col.max_length) {
61
- conflict("min_length is greater than max_length", `${col.min_length} > ${col.max_length}`, "min_length <= max_length");
62
- }
63
- if (col.separator !== undefined && type !== "list")
64
- conflict("separator needs a list column", type, "list");
65
- if (col.enum && (type === "boolean" || type === "date"))
66
- conflict(`enum does not apply to ${type} columns`, type, "string, integer, number or list");
67
- }
68
41
  /**
69
42
  * Validates one contract whose dependencies are already loaded.
70
43
  *
@@ -88,80 +61,95 @@ export function validateContract(data, deps) {
88
61
  }
89
62
  checkUnique(c.tables.map(t => t.name), "table", out);
90
63
  /** Resolves a column reference against this contract or a dependency. */
91
- const resolveRef = (ref, owner, allowOwnColumn, report) => {
64
+ const resolveRef = (ref, report) => {
92
65
  const p = parseRef(ref);
93
- if (p.table === null && !allowOwnColumn) {
66
+ if (p.table === null) {
94
67
  report("CONTRACT.BAD_FIELD", `'${ref}' must name a table: Table.Column or alias:Table.Column`, ref, "Table.Column");
95
68
  return null;
96
69
  }
70
+ const target = resolveTable(p.alias, p.table, ref, report);
71
+ if (!target)
72
+ return null;
73
+ const column = target.columns.find(col => col.name === p.column);
74
+ if (!column) {
75
+ report("CONTRACT.UNKNOWN_COLUMN", `column '${p.column}' is not in table ${target.name}`, ref, target.columns.map(col => col.name).join(", "));
76
+ return null;
77
+ }
78
+ return { alias: p.alias, table: target, column };
79
+ };
80
+ /** Resolves `Table` or `alias:Table`; null (reported) when unknown, or when the dependency itself is invalid. */
81
+ const resolveTable = (alias, name, text, report) => {
97
82
  let target = c;
98
- if (p.alias) {
99
- if (!c.depends_on?.[p.alias]) {
100
- report("CONTRACT.UNKNOWN_DEPENDENCY", `'${p.alias}' is not in depends_on`, p.alias, Object.keys(c.depends_on ?? {}).join(", ") || "(no depends_on)");
83
+ if (alias) {
84
+ if (!c.depends_on?.[alias]) {
85
+ report("CONTRACT.UNKNOWN_DEPENDENCY", `'${alias}' is not in depends_on`, alias, Object.keys(c.depends_on ?? {}).join(", ") || "(no depends_on)");
101
86
  return null;
102
87
  }
103
- target = deps.get(p.alias)?.contract ?? null;
88
+ target = deps.get(alias)?.contract ?? null;
104
89
  if (!target)
105
90
  return null; // the dependency's own problems are reported with it
106
91
  }
107
- const table = p.table === null ? owner : target.tables.find(t => t.name === p.table);
108
- if (!table) {
109
- report("CONTRACT.UNKNOWN_TABLE", `table '${p.table}' does not exist`, ref, target.tables.map(t => t.name).join(", "));
110
- return null;
111
- }
112
- const column = table.columns.find(col => col.name === p.column);
113
- if (!column) {
114
- report("CONTRACT.UNKNOWN_COLUMN", `column '${p.column}' is not in table ${table.name}`, ref, table.columns.map(col => col.name).join(", "));
115
- return null;
116
- }
117
- return { alias: p.alias, table, column };
92
+ const table = target.tables.find(t => t.name === name);
93
+ if (!table)
94
+ report("CONTRACT.UNKNOWN_TABLE", `table '${name}' does not exist`, text, target.tables.map(t => t.name).join(", "));
95
+ return table ?? null;
96
+ };
97
+ /** A validation context for queries on `scope`'s rows; findings are placed at `at`, the field prefixed to messages when given. */
98
+ const context = (scope, at, prefix = "") => {
99
+ const names = scope.columns.map(col => col.name);
100
+ const column = (field) => (at.column ?? field);
101
+ return {
102
+ contract: c, table: scope,
103
+ problem: (code, message, field, found, expected) => out.push(diag(code, prefix + message, { ...at, column: column(field) }, found, expected)),
104
+ requireColumns: (cols, field) => {
105
+ const unknown = cols.filter(n => !names.includes(n));
106
+ for (const n of unknown) {
107
+ out.push(diag("CONTRACT.UNKNOWN_COLUMN", `${prefix}column '${n}' is not in table ${scope.name}`, { ...at, column: column(field) }, n, names.join(", ")));
108
+ }
109
+ return unknown.length === 0;
110
+ },
111
+ resolve: (ref, field) => resolveRef(ref, (code, message, found, expected) => out.push(diag(code, prefix + message, { ...at, column: column(field) }, found, expected))),
112
+ };
118
113
  };
119
114
  const ruleIds = [];
120
- c.tables.forEach((t, ti) => {
115
+ for (const t of c.tables) {
121
116
  const names = t.columns.map(col => col.name);
122
117
  checkUnique(names, "column", out, t.name);
123
118
  for (const col of t.columns) {
124
- checkColumn(col, t, out);
125
- if (col.references !== undefined) {
126
- resolveRef(col.references, t, false, (code, message, found, expected) => out.push(diag(code, `references: ${message}`, { table: t.name, column: col.name }, found, expected)));
119
+ if (col.separator !== undefined && col.type !== "list") {
120
+ out.push(diag("CONTRACT.CONFLICT", "separator needs a list column", { table: t.name, column: col.name }, col.type ?? "string", "list"));
127
121
  }
122
+ if (col.match !== undefined)
123
+ checkQuery({ [col.name]: col.match }, "match", context(t, { table: t.name, column: col.name }, "match: "));
128
124
  }
129
125
  for (const k of keyColumns(t).filter(k => !names.includes(k))) {
130
126
  out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${k}' is not declared`, { table: t.name, column: "primary_key" }, k, names.join(", ")));
131
127
  }
132
128
  (t.rules ?? []).forEach((rule, ri) => {
133
- const label = rule.id ?? `${t.name}.rules[${ri}]`;
129
+ const at = { table: t.name, rule: rule.id ?? `${t.name}.rules[${ri}]` };
134
130
  if (rule.id)
135
131
  ruleIds.push(rule.id);
136
- const at = { table: t.name, rule: label };
137
- const kind = typeof rule.kind === "string" ? RULE_KINDS[rule.kind] : undefined;
138
- if (!kind) {
139
- out.push(diag("CONTRACT.BAD_FIELD", `rule kind '${String(rule.kind)}' does not exist`, { ...at, column: "kind" }, show(rule.kind), Object.keys(RULE_KINDS).join(", ")));
132
+ const report = (code, message, found, expected) => out.push(diag(code, message, { ...at, column: "on" }, found, expected));
133
+ const onRef = rule.on === undefined ? null : parseTableRef(rule.on);
134
+ const on = onRef ? resolveTable(onRef.alias, onRef.table, rule.on, report) : t;
135
+ if (!on)
140
136
  return;
137
+ if ((rule.require === undefined) === (rule.count === undefined)) {
138
+ out.push(diag("CONTRACT.BAD_FIELD", "a rule needs exactly one of require and count", { ...at, column: "require" }, rule.require && rule.count ? "both" : "(absent)", "require or count"));
141
139
  }
142
- const issues = checkShape(rule, { obj: { ...RULE_BASE, ...kind.params } }, `$.tables[${ti}].rules[${ri}]`);
143
- for (const i of issues)
144
- out.push(diag("CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { ...at, column: i.path }, i.found, i.expected));
145
- if (issues.length)
146
- return;
147
- for (const col of whenColumns(rule.when).filter(n => !names.includes(n))) {
148
- out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${col}' is not in table ${t.name}`, { ...at, column: "when" }, col, names.join(", ")));
140
+ const v = context(on, at);
141
+ if (rule.when !== undefined)
142
+ checkQuery(rule.when, "when", v);
143
+ if (rule.require !== undefined) {
144
+ if (!Object.keys(rule.require).length)
145
+ v.problem("CONTRACT.BAD_FIELD", "require is empty", "require", "{}", "a row query");
146
+ else
147
+ checkQuery(rule.require, "require", v);
149
148
  }
150
- const v = {
151
- contract: c, table: t,
152
- problem: (code, message, field, found, expected) => out.push(diag(code, message, { ...at, column: field }, found, expected)),
153
- requireColumns: (cols, field) => {
154
- const unknown = cols.filter(n => !names.includes(n));
155
- for (const n of unknown) {
156
- out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${n}' is not in table ${t.name}`, { ...at, column: field }, n, names.join(", ")));
157
- }
158
- return unknown.length === 0;
159
- },
160
- resolve: (ref, field, allowOwn) => resolveRef(ref, t, allowOwn, (code, message, found, expected) => out.push(diag(code, message, { ...at, column: field }, found, expected))),
161
- };
162
- kind.validate(rule, v);
149
+ if (rule.count !== undefined)
150
+ checkQuery({ _: rule.count }, "count", v);
163
151
  });
164
- });
152
+ }
165
153
  checkUnique(ruleIds, "rule", out);
166
154
  return out;
167
155
  }
@@ -1,16 +1,16 @@
1
1
  export const COLUMN_TYPES = ["string", "integer", "number", "boolean", "date", "list"];
2
2
  const S = "string";
3
- const SL = { list: "string", min: 1 };
4
3
  export const COLUMN_SHAPE = {
5
4
  obj: {
6
- name: S, "type?": { enum: COLUMN_TYPES }, "description?": S, "required?": "bool", "unique?": "bool",
7
- "pattern?": "regex", "enum?": SL, "minimum?": "number_or_string", "maximum?": "number_or_string",
8
- "min_length?": "int", "max_length?": "int", "separator?": S, "references?": S,
5
+ name: S, "type?": { enum: COLUMN_TYPES }, "description?": S, "required?": "bool", "separator?": S, "match?": { map: "any" },
9
6
  },
10
7
  };
11
- /** Fields every rule may have, besides its kind's own parameters. */
12
- export const RULE_BASE = {
13
- kind: S, "id?": S, "description?": S, "when?": { map: "string_or_list" }, "severity?": { enum: ["error", "warning"] },
8
+ /** A rule. */
9
+ export const RULE_SHAPE = {
10
+ obj: {
11
+ "id?": S, "description?": S, "on?": S, "when?": { map: "any" }, "require?": { map: "any" }, "count?": { map: "any" },
12
+ "severity?": { enum: ["error", "warning"] },
13
+ },
14
14
  };
15
15
  export const CONTRACT_SHAPE = {
16
16
  obj: {
@@ -20,7 +20,7 @@ export const CONTRACT_SHAPE = {
20
20
  list: {
21
21
  obj: {
22
22
  name: S, "description?": S, "required?": "bool", "ordered?": "bool", "allow_extra_columns?": "bool",
23
- "primary_key?": "string_or_list", columns: { list: COLUMN_SHAPE, min: 1 }, "rules?": { list: { map: "any" } },
23
+ "primary_key?": "string_or_list", columns: { list: COLUMN_SHAPE, min: 1 }, "rules?": { list: RULE_SHAPE },
24
24
  },
25
25
  },
26
26
  min: 1,
@@ -29,5 +29,3 @@ export const CONTRACT_SHAPE = {
29
29
  };
30
30
  /** The primary key columns of a table (empty when none). */
31
31
  export const keyColumns = (t) => (t.primary_key === undefined ? [] : Array.isArray(t.primary_key) ? t.primary_key : [t.primary_key]);
32
- /** The rows filter's column names. */
33
- export const whenColumns = (w) => Object.keys(w ?? {});