@casekit/orm2-cli 0.0.0-20250331202540 → 0.0.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.
Files changed (65) hide show
  1. package/build/cli.js +1 -2
  2. package/build/commands/db-drop/handler.js +0 -3
  3. package/build/commands/db-drop.test.js +1 -0
  4. package/build/commands/db-pull/handler.js +21 -8
  5. package/build/commands/db-pull/options.d.ts +5 -0
  6. package/build/commands/db-pull/options.js +5 -0
  7. package/build/commands/db-pull/util/relationNames.d.ts +3 -0
  8. package/build/commands/db-pull/util/relationNames.js +14 -0
  9. package/build/commands/db-pull/util/relationNames.test.js +61 -0
  10. package/build/commands/db-pull/util/renderDefault.d.ts +3 -0
  11. package/build/commands/db-pull/util/renderDefault.js +46 -0
  12. package/build/commands/db-pull/util/renderDefault.test.d.ts +1 -0
  13. package/build/commands/db-pull/util/renderDefault.test.js +67 -0
  14. package/build/commands/db-pull/util/renderFieldDefinition.d.ts +2 -0
  15. package/build/commands/db-pull/util/renderFieldDefinition.js +50 -0
  16. package/build/commands/db-pull/util/renderFieldDefinition.test.d.ts +1 -0
  17. package/build/commands/db-pull/util/renderFieldDefinition.test.js +182 -0
  18. package/build/commands/db-pull/util/renderModel.basic.test.d.ts +1 -0
  19. package/build/commands/db-pull/util/renderModel.basic.test.js +169 -0
  20. package/build/commands/db-pull/util/renderModel.constraints.test.d.ts +1 -0
  21. package/build/commands/db-pull/util/renderModel.constraints.test.js +677 -0
  22. package/build/commands/db-pull/util/renderModel.d.ts +2 -0
  23. package/build/commands/db-pull/util/renderModel.defaultValues.test.d.ts +1 -0
  24. package/build/commands/db-pull/util/renderModel.defaultValues.test.js +518 -0
  25. package/build/commands/db-pull/util/renderModel.js +88 -0
  26. package/build/commands/db-pull/util/renderModel.relations.test.d.ts +1 -0
  27. package/build/commands/db-pull/util/renderModel.relations.test.js +880 -0
  28. package/build/commands/db-pull/util/renderModel.types.test.d.ts +1 -0
  29. package/build/commands/db-pull/util/renderModel.types.test.js +703 -0
  30. package/build/commands/db-pull/util/renderRelations.d.ts +2 -0
  31. package/build/commands/db-pull/util/renderRelations.js +55 -0
  32. package/build/commands/db-pull/util/renderRelations.test.d.ts +1 -0
  33. package/build/commands/db-pull/util/renderRelations.test.js +165 -0
  34. package/build/commands/db-pull/util/renderType.d.ts +6 -0
  35. package/build/commands/db-pull/util/renderType.js +55 -0
  36. package/build/commands/db-pull/util/renderType.test.d.ts +1 -0
  37. package/build/commands/db-pull/util/renderType.test.js +46 -0
  38. package/build/commands/db-pull.d.ts +10 -0
  39. package/build/commands/db-pull.test.js +625 -0
  40. package/build/commands/db-push/handler.js +0 -3
  41. package/build/commands/init/handler.js +16 -3
  42. package/build/commands/init/util/generateConfigFile.js +2 -3
  43. package/build/commands/init/util/generateDbFile.js +13 -24
  44. package/build/commands/init/util/generateModelsFile.d.ts +1 -1
  45. package/build/commands/init/util/generateModelsFile.js +6 -2
  46. package/build/commands/init.test.js +19 -31
  47. package/build/types.d.ts +2 -2
  48. package/build/util/createOrOverwriteFile.d.ts +1 -1
  49. package/build/util/createOrOverwriteFile.js +1 -1
  50. package/build/util/loadConfig.js +5 -1
  51. package/package.json +26 -25
  52. package/build/commands/generate-model/handler.d.ts +0 -3
  53. package/build/commands/generate-model/handler.js +0 -10
  54. package/build/commands/generate-model/options.d.ts +0 -18
  55. package/build/commands/generate-model/options.js +0 -18
  56. package/build/commands/generate-model/util/generateModelFile.d.ts +0 -3
  57. package/build/commands/generate-model/util/generateModelFile.js +0 -59
  58. package/build/commands/generate-model/util/generateModelFile.test.js +0 -67
  59. package/build/commands/generate-model/util/regenerateModelsFile.d.ts +0 -2
  60. package/build/commands/generate-model/util/regenerateModelsFile.js +0 -50
  61. package/build/commands/generate-model.d.ts +0 -40
  62. package/build/commands/generate-model.js +0 -8
  63. package/build/commands/generate-model.test.js +0 -55
  64. /package/build/commands/{generate-model/util/generateModelFile.test.d.ts → db-pull/util/relationNames.test.d.ts} +0 -0
  65. /package/build/commands/{generate-model.test.d.ts → db-pull.test.d.ts} +0 -0
@@ -0,0 +1,2 @@
1
+ import type { ForeignKey, Table } from "@casekit/orm2-migrate";
2
+ export declare const renderRelations: (table: Table, allForeignKeys: ForeignKey[]) => string;
@@ -0,0 +1,55 @@
1
+ import { camelCase } from "es-toolkit/string";
2
+ import { guessManyToOneRelationName, guessOneToManyRelationName, } from "./relationNames.js";
3
+ export const renderRelations = (table, allForeignKeys) => {
4
+ const relations = [];
5
+ // N:1 relations (this table references others)
6
+ table.foreignKeys.forEach((fk) => {
7
+ const relationName = guessManyToOneRelationName(fk);
8
+ const parts = [`type: "N:1"`, `model: "${camelCase(fk.tableTo)}"`];
9
+ if (fk.columnsFrom.length === 1 &&
10
+ fk.columnsTo.length === 1 &&
11
+ fk.columnsFrom[0] &&
12
+ fk.columnsTo[0]) {
13
+ const fromField = camelCase(fk.columnsFrom[0]);
14
+ const toField = camelCase(fk.columnsTo[0]);
15
+ parts.push(`fromField: "${fromField}"`);
16
+ parts.push(`toField: "${toField}"`);
17
+ }
18
+ else {
19
+ parts.push(`fromField: [${fk.columnsFrom.map((f) => `"${camelCase(f)}"`).join(", ")}]`);
20
+ parts.push(`toField: [${fk.columnsTo.map((f) => `"${camelCase(f)}"`).join(", ")}]`);
21
+ }
22
+ // Check if the foreign key column is nullable
23
+ const isNullable = fk.columnsFrom.length === 1 &&
24
+ table.columns.find((c) => c.column === fk.columnsFrom[0])?.nullable;
25
+ if (isNullable) {
26
+ parts.push("optional: true");
27
+ }
28
+ relations.push(`${relationName}: { ${parts.join(", ")} }`);
29
+ });
30
+ // 1:N relations (other tables reference this one)
31
+ allForeignKeys
32
+ .filter((fk) => fk.tableTo === table.name && fk.schema === table.schema)
33
+ .forEach((fk) => {
34
+ const relationName = guessOneToManyRelationName(fk);
35
+ const parts = [
36
+ `type: "1:N"`,
37
+ `model: "${camelCase(fk.tableFrom)}"`,
38
+ ];
39
+ if (fk.columnsFrom.length === 1 &&
40
+ fk.columnsTo.length === 1 &&
41
+ fk.columnsFrom[0] &&
42
+ fk.columnsTo[0]) {
43
+ const fromField = camelCase(fk.columnsTo[0]);
44
+ const toField = camelCase(fk.columnsFrom[0]);
45
+ parts.push(`fromField: "${fromField}"`);
46
+ parts.push(`toField: "${toField}"`);
47
+ }
48
+ else {
49
+ parts.push(`fromField: [${fk.columnsTo.map((f) => `"${camelCase(f)}"`).join(", ")}]`);
50
+ parts.push(`toField: [${fk.columnsFrom.map((f) => `"${camelCase(f)}"`).join(", ")}]`);
51
+ }
52
+ relations.push(`${relationName}: { ${parts.join(", ")} }`);
53
+ });
54
+ return relations.length > 0 ? relations.join(",\n ") : "";
55
+ };
@@ -0,0 +1,165 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { renderRelations } from "./renderRelations.js";
3
+ describe("renderRelations", () => {
4
+ const createColumn = (column, nullable = false) => ({
5
+ schema: "public",
6
+ table: "test",
7
+ column,
8
+ ordinalPosition: 1,
9
+ type: "integer",
10
+ default: null,
11
+ nullable,
12
+ udtSchema: "pg_catalog",
13
+ udt: "int4",
14
+ elementType: null,
15
+ elementTypeSchema: null,
16
+ cardinality: 0,
17
+ size: null,
18
+ isSerial: false,
19
+ });
20
+ const createForeignKey = (overrides) => ({
21
+ constraintName: "test_fk",
22
+ schema: "public",
23
+ tableFrom: "posts",
24
+ tableTo: "users",
25
+ columnsFrom: ["user_id"],
26
+ columnsTo: ["id"],
27
+ ...overrides,
28
+ });
29
+ const createTable = (overrides = {}) => ({
30
+ schema: "public",
31
+ name: "posts",
32
+ columns: [createColumn("id"), createColumn("user_id")],
33
+ primaryKey: null,
34
+ uniqueConstraints: [],
35
+ foreignKeys: [],
36
+ ...overrides,
37
+ });
38
+ it("renders empty string when no relations exist", () => {
39
+ const table = createTable();
40
+ const allForeignKeys = [];
41
+ expect(renderRelations(table, allForeignKeys)).toBe("");
42
+ });
43
+ it("renders N:1 relation for single column foreign key", () => {
44
+ const fk = createForeignKey({});
45
+ const table = createTable({ foreignKeys: [fk] });
46
+ expect(renderRelations(table, [])).toBe('user: { type: "N:1", model: "users", fromField: "userId", toField: "id" }');
47
+ });
48
+ it("renders N:1 relation with non-id target field", () => {
49
+ const fk = createForeignKey({
50
+ columnsFrom: ["email"],
51
+ columnsTo: ["email"],
52
+ });
53
+ const table = createTable({
54
+ columns: [createColumn("id"), createColumn("email")],
55
+ foreignKeys: [fk],
56
+ });
57
+ expect(renderRelations(table, [])).toBe('email: { type: "N:1", model: "users", fromField: "email", toField: "email" }');
58
+ });
59
+ it("renders N:1 relation with optional flag for nullable columns", () => {
60
+ const fk = createForeignKey({});
61
+ const table = createTable({
62
+ columns: [createColumn("id"), createColumn("user_id", true)],
63
+ foreignKeys: [fk],
64
+ });
65
+ expect(renderRelations(table, [])).toBe('user: { type: "N:1", model: "users", fromField: "userId", toField: "id", optional: true }');
66
+ });
67
+ it("renders N:1 relation for multi-column foreign key", () => {
68
+ const fk = createForeignKey({
69
+ columnsFrom: ["tenant_id", "user_id"],
70
+ columnsTo: ["tenant_id", "id"],
71
+ });
72
+ const table = createTable({
73
+ columns: [
74
+ createColumn("id"),
75
+ createColumn("tenant_id"),
76
+ createColumn("user_id"),
77
+ ],
78
+ foreignKeys: [fk],
79
+ });
80
+ expect(renderRelations(table, [])).toBe('tenantUser: { type: "N:1", model: "users", fromField: ["tenantId", "userId"], toField: ["tenantId", "id"] }');
81
+ });
82
+ it("renders 1:N relation for incoming foreign key", () => {
83
+ const table = createTable({ name: "users", foreignKeys: [] });
84
+ const allForeignKeys = [createForeignKey({})];
85
+ expect(renderRelations(table, allForeignKeys)).toBe('posts: { type: "1:N", model: "posts", fromField: "id", toField: "userId" }');
86
+ });
87
+ it("renders 1:N relation with non-id source field", () => {
88
+ const table = createTable({
89
+ name: "users",
90
+ columns: [createColumn("id"), createColumn("email")],
91
+ foreignKeys: [],
92
+ });
93
+ const allForeignKeys = [
94
+ createForeignKey({
95
+ tableTo: "users",
96
+ columnsFrom: ["author_email"],
97
+ columnsTo: ["email"],
98
+ }),
99
+ ];
100
+ expect(renderRelations(table, allForeignKeys)).toBe('authorEmailPosts: { type: "1:N", model: "posts", fromField: "email", toField: "authorEmail" }');
101
+ });
102
+ it("renders 1:N relation for multi-column foreign key", () => {
103
+ const table = createTable({
104
+ name: "users",
105
+ columns: [createColumn("tenant_id"), createColumn("id")],
106
+ foreignKeys: [],
107
+ });
108
+ const allForeignKeys = [
109
+ createForeignKey({
110
+ tableTo: "users",
111
+ columnsFrom: ["tenant_id", "user_id"],
112
+ columnsTo: ["tenant_id", "id"],
113
+ }),
114
+ ];
115
+ expect(renderRelations(table, allForeignKeys)).toBe('tenantUserPosts: { type: "1:N", model: "posts", fromField: ["tenantId", "id"], toField: ["tenantId", "userId"] }');
116
+ });
117
+ it("renders both N:1 and 1:N relations", () => {
118
+ const outgoingFk = createForeignKey({
119
+ tableFrom: "posts",
120
+ tableTo: "users",
121
+ });
122
+ const incomingFk = createForeignKey({
123
+ tableFrom: "comments",
124
+ tableTo: "posts",
125
+ columnsFrom: ["post_id"],
126
+ });
127
+ const table = createTable({
128
+ foreignKeys: [outgoingFk],
129
+ });
130
+ const allForeignKeys = [outgoingFk, incomingFk];
131
+ const result = renderRelations(table, allForeignKeys);
132
+ expect(result).toBe('user: { type: "N:1", model: "users", fromField: "userId", toField: "id" },\n' +
133
+ ' comments: { type: "1:N", model: "comments", fromField: "id", toField: "postId" }');
134
+ });
135
+ it("filters 1:N relations by schema", () => {
136
+ const table = createTable({
137
+ schema: "public",
138
+ name: "users",
139
+ foreignKeys: [],
140
+ });
141
+ const allForeignKeys = [
142
+ createForeignKey({ schema: "public", tableTo: "users" }),
143
+ createForeignKey({ schema: "other", tableTo: "users" }),
144
+ ];
145
+ const result = renderRelations(table, allForeignKeys);
146
+ // Should only include the foreign key from the same schema
147
+ expect(result).toBe('posts: { type: "1:N", model: "posts", fromField: "id", toField: "userId" }');
148
+ });
149
+ it("handles self-referential relations", () => {
150
+ const fk = createForeignKey({
151
+ tableFrom: "categories",
152
+ tableTo: "categories",
153
+ columnsFrom: ["parent_id"],
154
+ });
155
+ const table = createTable({
156
+ name: "categories",
157
+ columns: [createColumn("id"), createColumn("parent_id", true)],
158
+ foreignKeys: [fk],
159
+ });
160
+ const allForeignKeys = [fk];
161
+ const result = renderRelations(table, allForeignKeys);
162
+ expect(result).toBe('parent: { type: "N:1", model: "categories", fromField: "parentId", toField: "id", optional: true },\n' +
163
+ ' parentCategories: { type: "1:N", model: "categories", fromField: "id", toField: "parentId" }');
164
+ });
165
+ });
@@ -0,0 +1,6 @@
1
+ import type { Column } from "@casekit/orm2-migrate";
2
+ /**
3
+ * Renders PostgreSQL column types for code generation
4
+ * Handles array types, SERIAL types, and passes through all other types unchanged
5
+ */
6
+ export declare const renderType: (column: Column) => string;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Renders PostgreSQL column types for code generation
3
+ * Handles array types, SERIAL types, and passes through all other types unchanged
4
+ */
5
+ export const renderType = (column) => {
6
+ // Handle SERIAL columns first
7
+ if (column.isSerial) {
8
+ if (column.type === "smallint") {
9
+ return "smallserial";
10
+ }
11
+ else if (column.type === "integer") {
12
+ return "serial";
13
+ }
14
+ else if (column.type === "bigint") {
15
+ return "bigserial";
16
+ }
17
+ }
18
+ // Handle array types
19
+ if (column.type === "ARRAY" && column.elementType) {
20
+ return `${column.elementType}${"[]".repeat(column.cardinality ?? 1)}`;
21
+ }
22
+ // Handle PostgreSQL array shortcuts (e.g., _text, _int4)
23
+ // These are internal representations for array types
24
+ const arrayShortcuts = {
25
+ _text: "text[]",
26
+ _varchar: "varchar[]",
27
+ _int4: "integer[]",
28
+ _int8: "bigint[]",
29
+ _int2: "smallint[]",
30
+ _float4: "real[]",
31
+ _float8: "double precision[]",
32
+ _bool: "boolean[]",
33
+ _uuid: "uuid[]",
34
+ _json: "json[]",
35
+ _jsonb: "jsonb[]",
36
+ _bytea: "bytea[]",
37
+ _date: "date[]",
38
+ _timestamp: "timestamp[]",
39
+ _timestamptz: "timestamptz[]",
40
+ _time: "time[]",
41
+ _timetz: "timetz[]",
42
+ _numeric: "numeric[]",
43
+ _money: "money[]",
44
+ _inet: "inet[]",
45
+ _cidr: "cidr[]",
46
+ _macaddr: "macaddr[]",
47
+ _macaddr8: "macaddr8[]",
48
+ };
49
+ const shortcut = arrayShortcuts[column.type];
50
+ if (shortcut) {
51
+ return shortcut;
52
+ }
53
+ // Pass through all other types unchanged
54
+ return column.type;
55
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,46 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { renderType } from "./renderType.js";
3
+ describe("renderType", () => {
4
+ const createColumn = (type, elementType, cardinality) => ({
5
+ schema: "public",
6
+ table: "test",
7
+ column: "test_column",
8
+ ordinalPosition: 1,
9
+ type,
10
+ default: null,
11
+ nullable: false,
12
+ udtSchema: "pg_catalog",
13
+ udt: "test",
14
+ elementType: elementType ?? null,
15
+ elementTypeSchema: null,
16
+ cardinality: cardinality ?? 0,
17
+ size: null,
18
+ isSerial: false,
19
+ });
20
+ describe("Array types", () => {
21
+ test("renders ARRAY types with element types", () => {
22
+ expect(renderType(createColumn("ARRAY", "integer", 1))).toBe("integer[]");
23
+ expect(renderType(createColumn("ARRAY", "text", 1))).toBe("text[]");
24
+ expect(renderType(createColumn("ARRAY", "varchar", 2))).toBe("varchar[][]");
25
+ expect(renderType(createColumn("ARRAY", "boolean", 3))).toBe("boolean[][][]");
26
+ });
27
+ test("handles array type shortcuts", () => {
28
+ expect(renderType(createColumn("_text"))).toBe("text[]");
29
+ expect(renderType(createColumn("_int4"))).toBe("integer[]");
30
+ expect(renderType(createColumn("_varchar"))).toBe("varchar[]");
31
+ expect(renderType(createColumn("_bool"))).toBe("boolean[]");
32
+ });
33
+ test("handles ARRAY type without elementType", () => {
34
+ expect(renderType(createColumn("ARRAY", null))).toBe("ARRAY");
35
+ });
36
+ });
37
+ describe("Pass-through types", () => {
38
+ test("passes through all non-array types unchanged", () => {
39
+ expect(renderType(createColumn("integer"))).toBe("integer");
40
+ expect(renderType(createColumn("character varying"))).toBe("character varying");
41
+ expect(renderType(createColumn("timestamp with time zone"))).toBe("timestamp with time zone");
42
+ expect(renderType(createColumn("numeric(10,2)"))).toBe("numeric(10,2)");
43
+ expect(renderType(createColumn("custom_enum_type"))).toBe("custom_enum_type");
44
+ });
45
+ });
46
+ });
@@ -8,6 +8,11 @@ export declare const dbPull: {
8
8
  array: true;
9
9
  default: never[];
10
10
  };
11
+ force: {
12
+ type: "boolean";
13
+ desc: string;
14
+ default: boolean;
15
+ };
11
16
  };
12
17
  handler: import("../types.js").Handler<{
13
18
  schema: {
@@ -16,5 +21,10 @@ export declare const dbPull: {
16
21
  array: true;
17
22
  default: never[];
18
23
  };
24
+ force: {
25
+ type: "boolean";
26
+ desc: string;
27
+ default: boolean;
28
+ };
19
29
  }>;
20
30
  };