-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
nameCasing.ts
69 lines (67 loc) · 2.5 KB
/
nameCasing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { detectCasing, recase } from "@kristiandupont/recase";
import type {
TableColumn,
TableDetails,
ViewColumn,
ViewDetails,
} from "extract-pg-schema";
import type Rule from "../Rule";
export const nameCasing: Rule = {
name: "name-casing",
docs: {
description: "Enforce casing style of names",
url: "https://github.com/kristiandupont/schemalint/tree/master/src/rules#name-casing",
},
process({ options, schemaObject, report }) {
const expectedCasing = (options.length > 0 && options[0]) || "snake";
const validator =
(entityType: "table" | "view") =>
({ name: entityName }: TableDetails | ViewDetails) => {
const casing = detectCasing(entityName);
const matches = casing === null || casing === expectedCasing;
if (!matches) {
report({
rule: this.name,
identifier: `${schemaObject.name}.${entityName}`,
message: `The ${entityType} ${entityName} seems to be ${casing}-cased rather than ${expectedCasing}-cased.`,
suggestedMigration: `ALTER ${entityType.toUpperCase()} "${entityName}" RENAME TO "${recase(
casing,
expectedCasing,
entityName,
)}";`,
});
}
};
const columnValidator =
(entityType: "table" | "view") =>
({ name: entityName }: TableDetails | ViewDetails) =>
({ name: columnName }: TableColumn | ViewColumn) => {
const casing = detectCasing(columnName);
const matches = casing === null || casing === expectedCasing;
if (!matches) {
report({
rule: this.name,
identifier: `${schemaObject.name}.${entityName}.${columnName}`,
message: `The column ${columnName} on the ${entityType} ${entityName} seems to be ${casing}-cased rather than ${expectedCasing}-cased.`,
suggestedMigration: `ALTER ${entityType.toUpperCase()} "${entityName}" RENAME COLUMN "${columnName}" TO "${recase(
casing,
expectedCasing,
columnName,
)}";`,
});
}
};
if (Array.isArray(schemaObject.tables)) {
schemaObject.tables.forEach((entity) => {
validator("table")(entity);
entity.columns.forEach(columnValidator("table")(entity));
});
}
if (Array.isArray(schemaObject.views)) {
schemaObject.views.forEach((entity) => {
validator("view")(entity);
entity.columns.forEach(columnValidator("view")(entity));
});
}
},
};