@rebasepro/server-postgresql 0.0.1-canary.ca2cb6e → 0.0.1-canary.dbf160a
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/server-postgresql/src/schema/introspect-db-logic.d.ts +82 -0
- package/dist/server-postgresql/src/schema/introspect-db.d.ts +1 -0
- package/package.json +6 -5
- package/src/cli.ts +59 -1
- package/src/schema/introspect-db-logic.ts +592 -0
- package/src/schema/introspect-db.ts +211 -0
- package/test/introspect-db-generation.test.ts +436 -0
- package/test/introspect-db-utils.test.ts +392 -0
- package/test/unmapped-tables-safety.test.ts +345 -0
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import pg from "pg";
|
|
5
|
+
import arg from "arg";
|
|
6
|
+
import * as dotenv from "dotenv";
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
TableRow,
|
|
10
|
+
TableColumn,
|
|
11
|
+
EnumValue,
|
|
12
|
+
PrimaryKeyRow,
|
|
13
|
+
ForeignKeyRow,
|
|
14
|
+
buildTablesMap,
|
|
15
|
+
buildEnumMap,
|
|
16
|
+
identifyJoinTables,
|
|
17
|
+
generateCollectionFile,
|
|
18
|
+
generateIndexContent,
|
|
19
|
+
mergeIndexContent,
|
|
20
|
+
safeHostFromUrl,
|
|
21
|
+
} from "./introspect-db-logic";
|
|
22
|
+
|
|
23
|
+
async function main() {
|
|
24
|
+
const args = arg(
|
|
25
|
+
{
|
|
26
|
+
"--output": String,
|
|
27
|
+
"--force": Boolean,
|
|
28
|
+
"--schema": String,
|
|
29
|
+
"-o": "--output",
|
|
30
|
+
"-f": "--force",
|
|
31
|
+
},
|
|
32
|
+
{ permissive: true }
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
const outDir = args["--output"] || path.resolve(process.cwd(), "config", "collections");
|
|
36
|
+
const force = args["--force"] || false;
|
|
37
|
+
const pgSchema = args["--schema"] || "public";
|
|
38
|
+
|
|
39
|
+
if (!fs.existsSync(outDir)) {
|
|
40
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Load env
|
|
44
|
+
const envPaths = [
|
|
45
|
+
process.env.DOTENV_CONFIG_PATH,
|
|
46
|
+
path.resolve(process.cwd(), ".env"),
|
|
47
|
+
path.resolve(process.cwd(), "../.env"),
|
|
48
|
+
path.resolve(process.cwd(), "../../.env")
|
|
49
|
+
].filter(Boolean) as string[];
|
|
50
|
+
|
|
51
|
+
for (const p of envPaths) {
|
|
52
|
+
if (fs.existsSync(p)) {
|
|
53
|
+
dotenv.config({ path: p });
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
|
|
59
|
+
if (!databaseUrl) {
|
|
60
|
+
console.error(chalk.red("✗ DATABASE_URL is not set. Make sure your .env file is configured."));
|
|
61
|
+
process.exit(1);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const client = new pg.Client({ connectionString: databaseUrl });
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
await client.connect();
|
|
68
|
+
} catch (err) {
|
|
69
|
+
console.error(chalk.red(`✗ Failed to connect to database: ${err instanceof Error ? err.message : String(err)}`));
|
|
70
|
+
console.error(chalk.gray(" Check your DATABASE_URL and ensure the database is reachable."));
|
|
71
|
+
process.exit(1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Log the host portion safely — handle URLs without "@"
|
|
75
|
+
const hostPart = safeHostFromUrl(databaseUrl);
|
|
76
|
+
console.log(chalk.gray(`Connected to database: ${hostPart}`));
|
|
77
|
+
console.log(chalk.gray(`Introspecting schema '${pgSchema}'...`));
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
// 1. Get Tables
|
|
81
|
+
const { rows: tables } = await client.query<TableRow>(`
|
|
82
|
+
SELECT table_name
|
|
83
|
+
FROM information_schema.tables
|
|
84
|
+
WHERE table_schema = $1 AND table_type = 'BASE TABLE'
|
|
85
|
+
AND table_name NOT LIKE 'drizzle_%'
|
|
86
|
+
AND table_name NOT LIKE 'rebase_%'
|
|
87
|
+
ORDER BY table_name
|
|
88
|
+
`, [pgSchema]);
|
|
89
|
+
|
|
90
|
+
// 2. Get Columns
|
|
91
|
+
const { rows: columns } = await client.query<TableColumn>(`
|
|
92
|
+
SELECT table_name, column_name, data_type, udt_name, is_nullable, column_default
|
|
93
|
+
FROM information_schema.columns
|
|
94
|
+
WHERE table_schema = $1
|
|
95
|
+
`, [pgSchema]);
|
|
96
|
+
|
|
97
|
+
// 2b. Get Enum Types and their values
|
|
98
|
+
const { rows: enumValues } = await client.query<EnumValue>(`
|
|
99
|
+
SELECT t.typname AS enum_name,
|
|
100
|
+
e.enumlabel AS enum_value,
|
|
101
|
+
e.enumsortorder AS sort_order
|
|
102
|
+
FROM pg_type t
|
|
103
|
+
JOIN pg_enum e ON t.oid = e.enumtypid
|
|
104
|
+
JOIN pg_namespace n ON t.typnamespace = n.oid
|
|
105
|
+
WHERE n.nspname = $1
|
|
106
|
+
ORDER BY t.typname, e.enumsortorder
|
|
107
|
+
`, [pgSchema]);
|
|
108
|
+
|
|
109
|
+
// Build a map: enum_name -> ordered list of values
|
|
110
|
+
const enumMap = buildEnumMap(enumValues);
|
|
111
|
+
|
|
112
|
+
// 3. Get Primary Keys
|
|
113
|
+
const { rows: pks } = await client.query<PrimaryKeyRow>(`
|
|
114
|
+
SELECT t.relname as table_name, a.attname as column_name
|
|
115
|
+
FROM pg_index i
|
|
116
|
+
JOIN pg_attribute a ON a.attrelid = i.indrelid
|
|
117
|
+
AND a.attnum = ANY(i.indkey)
|
|
118
|
+
JOIN pg_class t ON t.oid = i.indrelid
|
|
119
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
120
|
+
WHERE i.indisprimary AND n.nspname = $1
|
|
121
|
+
`, [pgSchema]);
|
|
122
|
+
|
|
123
|
+
// 4. Get Foreign Keys
|
|
124
|
+
const { rows: fks } = await client.query<ForeignKeyRow>(`
|
|
125
|
+
SELECT
|
|
126
|
+
tc.table_name,
|
|
127
|
+
kcu.column_name,
|
|
128
|
+
ccu.table_name AS foreign_table_name,
|
|
129
|
+
ccu.column_name AS foreign_column_name
|
|
130
|
+
FROM
|
|
131
|
+
information_schema.table_constraints AS tc
|
|
132
|
+
JOIN information_schema.key_column_usage AS kcu
|
|
133
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
134
|
+
AND tc.table_schema = kcu.table_schema
|
|
135
|
+
JOIN information_schema.constraint_column_usage AS ccu
|
|
136
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
137
|
+
AND ccu.table_schema = tc.table_schema
|
|
138
|
+
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = $1
|
|
139
|
+
`, [pgSchema]);
|
|
140
|
+
|
|
141
|
+
const tablesMap = buildTablesMap(tables, columns, pks, fks);
|
|
142
|
+
const joinTables = identifyJoinTables(tablesMap);
|
|
143
|
+
|
|
144
|
+
console.log(chalk.blue(`Found ${tablesMap.size} tables (including ${joinTables.size} detected join tables).`));
|
|
145
|
+
|
|
146
|
+
// Generate Collections
|
|
147
|
+
const generatedFiles: string[] = [];
|
|
148
|
+
const skippedFiles: string[] = [];
|
|
149
|
+
|
|
150
|
+
for (const [tableName, meta] of tablesMap.entries()) {
|
|
151
|
+
if (joinTables.has(tableName)) continue; // We don't generate base collections for pure join tables
|
|
152
|
+
|
|
153
|
+
// ── File overwrite protection ──────────────────────────────
|
|
154
|
+
const filePath = path.join(outDir, `${tableName}.ts`);
|
|
155
|
+
if (fs.existsSync(filePath) && !force) {
|
|
156
|
+
skippedFiles.push(tableName);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const fileContent = generateCollectionFile(
|
|
161
|
+
tableName,
|
|
162
|
+
meta,
|
|
163
|
+
fks,
|
|
164
|
+
joinTables,
|
|
165
|
+
tablesMap,
|
|
166
|
+
enumMap,
|
|
167
|
+
);
|
|
168
|
+
|
|
169
|
+
fs.writeFileSync(filePath, fileContent, "utf-8");
|
|
170
|
+
generatedFiles.push(tableName);
|
|
171
|
+
console.log(chalk.green(` ✓ ${filePath}`));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Generate index.ts (sorted alphabetically for deterministic output)
|
|
175
|
+
if (generatedFiles.length > 0) {
|
|
176
|
+
const indexPath = path.join(outDir, "index.ts");
|
|
177
|
+
|
|
178
|
+
if (fs.existsSync(indexPath) && !force) {
|
|
179
|
+
// Merge: read existing index, add new exports that don't already exist
|
|
180
|
+
const existing = fs.readFileSync(indexPath, "utf-8");
|
|
181
|
+
const merged = mergeIndexContent(existing, generatedFiles);
|
|
182
|
+
fs.writeFileSync(indexPath, merged, "utf-8");
|
|
183
|
+
} else {
|
|
184
|
+
const indexContent = generateIndexContent(generatedFiles);
|
|
185
|
+
fs.writeFileSync(indexPath, indexContent, "utf-8");
|
|
186
|
+
}
|
|
187
|
+
console.log(chalk.green(` ✓ ${indexPath}`));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
console.log("");
|
|
191
|
+
if (skippedFiles.length > 0) {
|
|
192
|
+
console.log(chalk.yellow(`⚠ Skipped ${skippedFiles.length} existing file(s): ${skippedFiles.join(", ")}`));
|
|
193
|
+
console.log(chalk.gray(` Use --force to overwrite existing files.`));
|
|
194
|
+
console.log("");
|
|
195
|
+
}
|
|
196
|
+
console.log(chalk.bold.green(`✓ Introspected ${tablesMap.size} tables — generated ${generatedFiles.length} collection(s).`));
|
|
197
|
+
console.log(chalk.gray(` Review the generated files in ${outDir} and customize properties as needed.`));
|
|
198
|
+
console.log("");
|
|
199
|
+
|
|
200
|
+
} catch (e) {
|
|
201
|
+
console.error(chalk.red(`✗ Error introspecting database: ${e instanceof Error ? e.message : String(e)}`));
|
|
202
|
+
process.exit(1);
|
|
203
|
+
} finally {
|
|
204
|
+
await client.end();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
main().catch((err) => {
|
|
209
|
+
console.error(err);
|
|
210
|
+
process.exit(1);
|
|
211
|
+
});
|
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
import {
|
|
2
|
+
generateCollectionFile, buildTablesMap, buildEnumMap,
|
|
3
|
+
identifyJoinTables, TableRow, TableColumn, PrimaryKeyRow,
|
|
4
|
+
ForeignKeyRow, EnumValue, TableMeta,
|
|
5
|
+
} from "../src/schema/introspect-db-logic";
|
|
6
|
+
|
|
7
|
+
// ── Helpers ───────────────────────────────────────────────────────────
|
|
8
|
+
|
|
9
|
+
const mkCol = (table: string, col: string, opts: Partial<TableColumn> = {}): TableColumn => ({
|
|
10
|
+
table_name: table, column_name: col, data_type: "character varying",
|
|
11
|
+
udt_name: "varchar", is_nullable: "YES", column_default: null, ...opts,
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const mkFk = (table: string, col: string, fTable: string, fCol = "id"): ForeignKeyRow => ({
|
|
15
|
+
table_name: table, column_name: col, foreign_table_name: fTable, foreign_column_name: fCol,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
function makeSimpleTable(name: string, columns: TableColumn[], pks: string[] = ["id"], fks: ForeignKeyRow[] = []): TableMeta {
|
|
19
|
+
return { name, columns, pks, fks };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
23
|
+
// generateCollectionFile() — property generation
|
|
24
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
25
|
+
describe("generateCollectionFile", () => {
|
|
26
|
+
describe("basic property generation", () => {
|
|
27
|
+
it("generates a simple collection with slug, name, singularName and table", () => {
|
|
28
|
+
const meta = makeSimpleTable("products", [
|
|
29
|
+
mkCol("products", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
30
|
+
mkCol("products", "name", { is_nullable: "NO" }),
|
|
31
|
+
]);
|
|
32
|
+
const result = generateCollectionFile("products", meta, [], new Set(), new Map([["products", meta]]), new Map());
|
|
33
|
+
expect(result).toContain('slug: "products"');
|
|
34
|
+
expect(result).toContain('name: "Products"');
|
|
35
|
+
expect(result).toContain('singularName: "Product"');
|
|
36
|
+
expect(result).toContain('table: "products"');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("generates correct property types from columns", () => {
|
|
40
|
+
const meta = makeSimpleTable("items", [
|
|
41
|
+
mkCol("items", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
42
|
+
mkCol("items", "count", { data_type: "integer", udt_name: "int4" }),
|
|
43
|
+
mkCol("items", "active", { data_type: "boolean", udt_name: "bool" }),
|
|
44
|
+
mkCol("items", "created_at", { data_type: "timestamp", udt_name: "timestamp" }),
|
|
45
|
+
mkCol("items", "metadata", { data_type: "jsonb", udt_name: "jsonb" }),
|
|
46
|
+
]);
|
|
47
|
+
const result = generateCollectionFile("items", meta, [], new Set(), new Map([["items", meta]]), new Map());
|
|
48
|
+
expect(result).toContain('type: "string"'); // id
|
|
49
|
+
expect(result).toContain('type: "number"');
|
|
50
|
+
expect(result).toContain('type: "boolean"');
|
|
51
|
+
expect(result).toContain('type: "date"');
|
|
52
|
+
expect(result).toContain('type: "map"');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("skips FK columns from properties (they become relations)", () => {
|
|
56
|
+
const fks = [mkFk("posts", "author_id", "users")];
|
|
57
|
+
const meta = makeSimpleTable("posts", [
|
|
58
|
+
mkCol("posts", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
59
|
+
mkCol("posts", "title", { is_nullable: "NO" }),
|
|
60
|
+
mkCol("posts", "author_id", { is_nullable: "NO" }),
|
|
61
|
+
], ["id"], fks);
|
|
62
|
+
const result = generateCollectionFile("posts", meta, fks, new Set(), new Map([["posts", meta]]), new Map());
|
|
63
|
+
// author_id should NOT appear as a regular property
|
|
64
|
+
expect(result).not.toMatch(/author_id:\s*\{[^}]*type:\s*"string"/);
|
|
65
|
+
// but author should appear as a relation
|
|
66
|
+
expect(result).toContain('type: "relation"');
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe("propertiesOrder correctness", () => {
|
|
71
|
+
it("includes relation property key, not FK column name", () => {
|
|
72
|
+
const fks = [mkFk("posts", "author_id", "users")];
|
|
73
|
+
const meta = makeSimpleTable("posts", [
|
|
74
|
+
mkCol("posts", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
75
|
+
mkCol("posts", "title"),
|
|
76
|
+
mkCol("posts", "author_id"),
|
|
77
|
+
], ["id"], fks);
|
|
78
|
+
const result = generateCollectionFile("posts", meta, fks, new Set(), new Map([["posts", meta]]), new Map());
|
|
79
|
+
// propertiesOrder should contain "author" (the relation key), not "author_id" (the FK column)
|
|
80
|
+
const orderMatch = result.match(/propertiesOrder:\s*(\[[\s\S]*?\])/);
|
|
81
|
+
expect(orderMatch).toBeTruthy();
|
|
82
|
+
const orderBlock = orderMatch![1];
|
|
83
|
+
expect(orderBlock).toContain('"author"');
|
|
84
|
+
// author_id should NOT appear in propertiesOrder (it may appear in localKey elsewhere)
|
|
85
|
+
expect(orderBlock).not.toContain('"author_id"');
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe("ID detection", () => {
|
|
90
|
+
it("marks uuid PK as isId uuid", () => {
|
|
91
|
+
const meta = makeSimpleTable("users", [
|
|
92
|
+
mkCol("users", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
93
|
+
]);
|
|
94
|
+
const result = generateCollectionFile("users", meta, [], new Set(), new Map([["users", meta]]), new Map());
|
|
95
|
+
expect(result).toContain('isId: "uuid"');
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("marks integer PK as isId increment", () => {
|
|
99
|
+
const meta = makeSimpleTable("counters", [
|
|
100
|
+
mkCol("counters", "id", { data_type: "integer", udt_name: "int4", is_nullable: "NO", column_default: "nextval" }),
|
|
101
|
+
]);
|
|
102
|
+
const result = generateCollectionFile("counters", meta, [], new Set(), new Map([["counters", meta]]), new Map());
|
|
103
|
+
expect(result).toContain('isId: "increment"');
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("flags composite primary keys with a comment", () => {
|
|
107
|
+
const meta = makeSimpleTable("scores", [
|
|
108
|
+
mkCol("scores", "user_id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
109
|
+
mkCol("scores", "game_id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
110
|
+
mkCol("scores", "score", { data_type: "integer", udt_name: "int4" }),
|
|
111
|
+
], ["user_id", "game_id"]);
|
|
112
|
+
const result = generateCollectionFile("scores", meta, [], new Set(), new Map([["scores", meta]]), new Map());
|
|
113
|
+
expect(result).toContain("composite primary key");
|
|
114
|
+
expect(result).toContain("user_id, game_id");
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
describe("validation.required", () => {
|
|
119
|
+
it("adds required when is_nullable is NO, not a PK, and no default", () => {
|
|
120
|
+
const meta = makeSimpleTable("items", [
|
|
121
|
+
mkCol("items", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
122
|
+
mkCol("items", "name", { is_nullable: "NO" }),
|
|
123
|
+
]);
|
|
124
|
+
const result = generateCollectionFile("items", meta, [], new Set(), new Map([["items", meta]]), new Map());
|
|
125
|
+
// name should have required
|
|
126
|
+
expect(result).toContain("required: true");
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("does NOT add required for nullable columns", () => {
|
|
130
|
+
const meta = makeSimpleTable("items", [
|
|
131
|
+
mkCol("items", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
132
|
+
mkCol("items", "bio", { is_nullable: "YES" }),
|
|
133
|
+
]);
|
|
134
|
+
const result = generateCollectionFile("items", meta, [], new Set(), new Map([["items", meta]]), new Map());
|
|
135
|
+
const bioSection = result.split("bio:")[1].split("},")[0];
|
|
136
|
+
expect(bioSection).not.toContain("required");
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("does NOT add required for columns with defaults", () => {
|
|
140
|
+
const meta = makeSimpleTable("items", [
|
|
141
|
+
mkCol("items", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
142
|
+
mkCol("items", "role", { is_nullable: "NO", column_default: "'user'" }),
|
|
143
|
+
]);
|
|
144
|
+
const result = generateCollectionFile("items", meta, [], new Set(), new Map([["items", meta]]), new Map());
|
|
145
|
+
const roleSection = result.split("role:")[1].split("},")[0];
|
|
146
|
+
expect(roleSection).not.toContain("required");
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
describe("enum support", () => {
|
|
151
|
+
it("generates enumValues for USER-DEFINED columns with matching enum", () => {
|
|
152
|
+
const enumMap = new Map([["order_status", ["pending", "shipped", "delivered"]]]);
|
|
153
|
+
const meta = makeSimpleTable("orders", [
|
|
154
|
+
mkCol("orders", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
155
|
+
mkCol("orders", "status", { data_type: "USER-DEFINED", udt_name: "order_status" }),
|
|
156
|
+
]);
|
|
157
|
+
const result = generateCollectionFile("orders", meta, [], new Set(), new Map([["orders", meta]]), enumMap);
|
|
158
|
+
expect(result).toContain('enumValues:');
|
|
159
|
+
expect(result).toContain('{ id: "pending", label: "Pending" }');
|
|
160
|
+
expect(result).toContain('{ id: "shipped", label: "Shipped" }');
|
|
161
|
+
expect(result).toContain('{ id: "delivered", label: "Delivered" }');
|
|
162
|
+
expect(result).toContain('type: "string"');
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("does NOT add enumValues for USER-DEFINED without matching enum", () => {
|
|
166
|
+
const meta = makeSimpleTable("things", [
|
|
167
|
+
mkCol("things", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
168
|
+
mkCol("things", "geom", { data_type: "USER-DEFINED", udt_name: "geometry" }),
|
|
169
|
+
]);
|
|
170
|
+
const result = generateCollectionFile("things", meta, [], new Set(), new Map([["things", meta]]), new Map());
|
|
171
|
+
expect(result).not.toContain("enumValues");
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("humanizes enum value labels with underscores", () => {
|
|
175
|
+
const enumMap = new Map([["my_enum", ["in_progress", "on_hold"]]]);
|
|
176
|
+
const meta = makeSimpleTable("tasks", [
|
|
177
|
+
mkCol("tasks", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
178
|
+
mkCol("tasks", "state", { data_type: "USER-DEFINED", udt_name: "my_enum" }),
|
|
179
|
+
]);
|
|
180
|
+
const result = generateCollectionFile("tasks", meta, [], new Set(), new Map([["tasks", meta]]), enumMap);
|
|
181
|
+
expect(result).toContain('label: "In Progress"');
|
|
182
|
+
expect(result).toContain('label: "On Hold"');
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
describe("date auto-value heuristics", () => {
|
|
187
|
+
it("sets autoValue on_create for created_at", () => {
|
|
188
|
+
const meta = makeSimpleTable("items", [
|
|
189
|
+
mkCol("items", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
190
|
+
mkCol("items", "created_at", { data_type: "timestamp", udt_name: "timestamp" }),
|
|
191
|
+
]);
|
|
192
|
+
const result = generateCollectionFile("items", meta, [], new Set(), new Map([["items", meta]]), new Map());
|
|
193
|
+
expect(result).toContain('autoValue: "on_create"');
|
|
194
|
+
expect(result).toContain("hideFromCollection: true");
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("sets autoValue on_update for updated_at", () => {
|
|
198
|
+
const meta = makeSimpleTable("items", [
|
|
199
|
+
mkCol("items", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
200
|
+
mkCol("items", "updated_at", { data_type: "timestamp", udt_name: "timestamp" }),
|
|
201
|
+
]);
|
|
202
|
+
const result = generateCollectionFile("items", meta, [], new Set(), new Map([["items", meta]]), new Map());
|
|
203
|
+
expect(result).toContain('autoValue: "on_update"');
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("sets autoValue on_create for columns with now() default", () => {
|
|
207
|
+
const meta = makeSimpleTable("items", [
|
|
208
|
+
mkCol("items", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
209
|
+
mkCol("items", "published_at", { data_type: "timestamp", udt_name: "timestamp", column_default: "now()" }),
|
|
210
|
+
]);
|
|
211
|
+
const result = generateCollectionFile("items", meta, [], new Set(), new Map([["items", meta]]), new Map());
|
|
212
|
+
expect(result).toContain('autoValue: "on_create"');
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
describe("string sub-type heuristics", () => {
|
|
217
|
+
it("adds storage config for image-like column names", () => {
|
|
218
|
+
for (const name of ["profile_image", "avatar", "photo_url", "logo", "cover_image"]) {
|
|
219
|
+
const meta = makeSimpleTable("t", [
|
|
220
|
+
mkCol("t", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
221
|
+
mkCol("t", name),
|
|
222
|
+
]);
|
|
223
|
+
const result = generateCollectionFile("t", meta, [], new Set(), new Map([["t", meta]]), new Map());
|
|
224
|
+
expect(result).toContain("storagePath:");
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("adds multiline for description/summary/excerpt", () => {
|
|
229
|
+
for (const name of ["description", "summary", "excerpt"]) {
|
|
230
|
+
const meta = makeSimpleTable("t", [
|
|
231
|
+
mkCol("t", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
232
|
+
mkCol("t", name),
|
|
233
|
+
]);
|
|
234
|
+
const result = generateCollectionFile("t", meta, [], new Set(), new Map([["t", meta]]), new Map());
|
|
235
|
+
expect(result).toContain("multiline: true");
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("adds markdown for content/body", () => {
|
|
240
|
+
for (const name of ["content", "body"]) {
|
|
241
|
+
const meta = makeSimpleTable("t", [
|
|
242
|
+
mkCol("t", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
243
|
+
mkCol("t", name),
|
|
244
|
+
]);
|
|
245
|
+
const result = generateCollectionFile("t", meta, [], new Set(), new Map([["t", meta]]), new Map());
|
|
246
|
+
expect(result).toContain("markdown: true");
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it("adds multiline for text data_type columns", () => {
|
|
251
|
+
const meta = makeSimpleTable("t", [
|
|
252
|
+
mkCol("t", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
253
|
+
mkCol("t", "notes", { data_type: "text", udt_name: "text" }),
|
|
254
|
+
]);
|
|
255
|
+
const result = generateCollectionFile("t", meta, [], new Set(), new Map([["t", meta]]), new Map());
|
|
256
|
+
expect(result).toContain("multiline: true");
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it("does NOT apply string heuristics to enum columns", () => {
|
|
260
|
+
const enumMap = new Map([["img_type", ["png", "jpg"]]]);
|
|
261
|
+
const meta = makeSimpleTable("t", [
|
|
262
|
+
mkCol("t", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
263
|
+
mkCol("t", "image_type", { data_type: "USER-DEFINED", udt_name: "img_type" }),
|
|
264
|
+
]);
|
|
265
|
+
const result = generateCollectionFile("t", meta, [], new Set(), new Map([["t", meta]]), enumMap);
|
|
266
|
+
expect(result).not.toContain("storagePath");
|
|
267
|
+
expect(result).toContain("enumValues");
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
describe("owning relation (FK -> other table)", () => {
|
|
272
|
+
it("generates a one-to-one owning relation with correct import", () => {
|
|
273
|
+
const fks = [mkFk("posts", "author_id", "users")];
|
|
274
|
+
const meta = makeSimpleTable("posts", [
|
|
275
|
+
mkCol("posts", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
276
|
+
mkCol("posts", "author_id"),
|
|
277
|
+
], ["id"], fks);
|
|
278
|
+
const result = generateCollectionFile("posts", meta, fks, new Set(), new Map([["posts", meta]]), new Map());
|
|
279
|
+
expect(result).toContain('import usersCollection from "./users"');
|
|
280
|
+
expect(result).toContain('author: {');
|
|
281
|
+
expect(result).toContain('cardinality: "one"');
|
|
282
|
+
expect(result).toContain('direction: "owning"');
|
|
283
|
+
expect(result).toContain('localKey: "author_id"');
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
describe("inverse relation (other table -> this table)", () => {
|
|
288
|
+
it("generates a one-to-many inverse relation", () => {
|
|
289
|
+
const allFks: ForeignKeyRow[] = [mkFk("comments", "post_id", "posts")];
|
|
290
|
+
const meta = makeSimpleTable("posts", [
|
|
291
|
+
mkCol("posts", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
292
|
+
]);
|
|
293
|
+
const result = generateCollectionFile("posts", meta, allFks, new Set(), new Map([["posts", meta]]), new Map());
|
|
294
|
+
expect(result).toContain('import commentsCollection from "./comments"');
|
|
295
|
+
expect(result).toContain('cardinality: "many"');
|
|
296
|
+
expect(result).toContain('direction: "inverse"');
|
|
297
|
+
expect(result).toContain('inverseRelationName: "post"');
|
|
298
|
+
expect(result).toContain('foreignKeyOnTarget: "post_id"');
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
describe("many-to-many relations", () => {
|
|
303
|
+
it("generates owning M2M with through config for alphabetically-first table", () => {
|
|
304
|
+
const jtFks: ForeignKeyRow[] = [
|
|
305
|
+
mkFk("articles_tags", "article_id", "articles"),
|
|
306
|
+
mkFk("articles_tags", "tag_id", "tags"),
|
|
307
|
+
];
|
|
308
|
+
const jtMeta: TableMeta = {
|
|
309
|
+
name: "articles_tags", pks: [],
|
|
310
|
+
columns: [mkCol("articles_tags", "article_id"), mkCol("articles_tags", "tag_id")],
|
|
311
|
+
fks: jtFks,
|
|
312
|
+
};
|
|
313
|
+
const articlesMeta = makeSimpleTable("articles", [
|
|
314
|
+
mkCol("articles", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
315
|
+
]);
|
|
316
|
+
const tablesMap = new Map([["articles", articlesMeta], ["articles_tags", jtMeta]]);
|
|
317
|
+
const joinTables = new Set(["articles_tags"]);
|
|
318
|
+
|
|
319
|
+
const result = generateCollectionFile("articles", articlesMeta, [], joinTables, tablesMap, new Map());
|
|
320
|
+
expect(result).toContain('direction: "owning"');
|
|
321
|
+
expect(result).toContain('table: "articles_tags"');
|
|
322
|
+
expect(result).toContain('sourceColumn: "article_id"');
|
|
323
|
+
expect(result).toContain('targetColumn: "tag_id"');
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it("generates inverse M2M for alphabetically-second table", () => {
|
|
327
|
+
const jtFks: ForeignKeyRow[] = [
|
|
328
|
+
mkFk("articles_tags", "article_id", "articles"),
|
|
329
|
+
mkFk("articles_tags", "tag_id", "tags"),
|
|
330
|
+
];
|
|
331
|
+
const jtMeta: TableMeta = {
|
|
332
|
+
name: "articles_tags", pks: [],
|
|
333
|
+
columns: [mkCol("articles_tags", "article_id"), mkCol("articles_tags", "tag_id")],
|
|
334
|
+
fks: jtFks,
|
|
335
|
+
};
|
|
336
|
+
const tagsMeta = makeSimpleTable("tags", [
|
|
337
|
+
mkCol("tags", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
338
|
+
]);
|
|
339
|
+
const tablesMap = new Map([["tags", tagsMeta], ["articles_tags", jtMeta]]);
|
|
340
|
+
const joinTables = new Set(["articles_tags"]);
|
|
341
|
+
|
|
342
|
+
const result = generateCollectionFile("tags", tagsMeta, [], joinTables, tablesMap, new Map());
|
|
343
|
+
expect(result).toContain('direction: "inverse"');
|
|
344
|
+
});
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
describe("self-referencing M2M", () => {
|
|
348
|
+
it("generates self-ref M2M with _via_ property name", () => {
|
|
349
|
+
const jtFks: ForeignKeyRow[] = [
|
|
350
|
+
mkFk("user_friends", "user_id", "users"),
|
|
351
|
+
mkFk("user_friends", "friend_id", "users"),
|
|
352
|
+
];
|
|
353
|
+
const jtMeta: TableMeta = {
|
|
354
|
+
name: "user_friends", pks: [],
|
|
355
|
+
columns: [mkCol("user_friends", "user_id"), mkCol("user_friends", "friend_id")],
|
|
356
|
+
fks: jtFks,
|
|
357
|
+
};
|
|
358
|
+
const usersMeta = makeSimpleTable("users", [
|
|
359
|
+
mkCol("users", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
360
|
+
]);
|
|
361
|
+
const tablesMap = new Map([["users", usersMeta], ["user_friends", jtMeta]]);
|
|
362
|
+
const joinTables = new Set(["user_friends"]);
|
|
363
|
+
|
|
364
|
+
const result = generateCollectionFile("users", usersMeta, [], joinTables, tablesMap, new Map());
|
|
365
|
+
expect(result).toContain("users_via_friend");
|
|
366
|
+
expect(result).toContain('table: "user_friends"');
|
|
367
|
+
expect(result).toContain('sourceColumn: "user_id"');
|
|
368
|
+
expect(result).toContain('targetColumn: "friend_id"');
|
|
369
|
+
// Self-ref should reference its own collection variable
|
|
370
|
+
expect(result).toContain("usersCollection");
|
|
371
|
+
});
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
describe("icon mapping", () => {
|
|
375
|
+
it("assigns correct icons based on table name", () => {
|
|
376
|
+
const make = (name: string) => {
|
|
377
|
+
const meta = makeSimpleTable(name, [mkCol(name, "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" })]);
|
|
378
|
+
return generateCollectionFile(name, meta, [], new Set(), new Map([[name, meta]]), new Map());
|
|
379
|
+
};
|
|
380
|
+
expect(make("users")).toContain('icon: "Users"');
|
|
381
|
+
expect(make("blog_posts")).toContain('icon: "FileText"');
|
|
382
|
+
expect(make("products")).toContain('icon: "Package"');
|
|
383
|
+
expect(make("orders")).toContain('icon: "ShoppingCart"');
|
|
384
|
+
expect(make("app_settings")).toContain('icon: "Settings"');
|
|
385
|
+
expect(make("random_xyz")).toContain('icon: "Database"');
|
|
386
|
+
});
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
describe("humanized names", () => {
|
|
390
|
+
it("uses Title Case for collection name from snake_case table", () => {
|
|
391
|
+
const meta = makeSimpleTable("user_profiles", [
|
|
392
|
+
mkCol("user_profiles", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
393
|
+
]);
|
|
394
|
+
const result = generateCollectionFile("user_profiles", meta, [], new Set(), new Map([["user_profiles", meta]]), new Map());
|
|
395
|
+
expect(result).toContain('name: "User Profiles"');
|
|
396
|
+
expect(result).toContain('singularName: "User Profile"');
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
it("humanizes property names", () => {
|
|
400
|
+
const meta = makeSimpleTable("t", [
|
|
401
|
+
mkCol("t", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
402
|
+
mkCol("t", "first_name"),
|
|
403
|
+
]);
|
|
404
|
+
const result = generateCollectionFile("t", meta, [], new Set(), new Map([["t", meta]]), new Map());
|
|
405
|
+
expect(result).toContain('name: "First Name"');
|
|
406
|
+
});
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
describe("import generation", () => {
|
|
410
|
+
it("always imports PostgresCollection", () => {
|
|
411
|
+
const meta = makeSimpleTable("t", [mkCol("t", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" })]);
|
|
412
|
+
const result = generateCollectionFile("t", meta, [], new Set(), new Map([["t", meta]]), new Map());
|
|
413
|
+
expect(result).toContain('import { PostgresCollection } from "@rebasepro/types"');
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
it("does not duplicate imports for multiple relations to same table", () => {
|
|
417
|
+
const fks = [mkFk("posts", "author_id", "users"), mkFk("posts", "reviewer_id", "users")];
|
|
418
|
+
const meta = makeSimpleTable("posts", [
|
|
419
|
+
mkCol("posts", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" }),
|
|
420
|
+
mkCol("posts", "author_id"),
|
|
421
|
+
mkCol("posts", "reviewer_id"),
|
|
422
|
+
], ["id"], fks);
|
|
423
|
+
const result = generateCollectionFile("posts", meta, fks, new Set(), new Map([["posts", meta]]), new Map());
|
|
424
|
+
const importMatches = result.match(/import usersCollection/g);
|
|
425
|
+
expect(importMatches).toHaveLength(1);
|
|
426
|
+
});
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
describe("export default", () => {
|
|
430
|
+
it("exports the collection variable as default", () => {
|
|
431
|
+
const meta = makeSimpleTable("orders", [mkCol("orders", "id", { data_type: "uuid", udt_name: "uuid", is_nullable: "NO" })]);
|
|
432
|
+
const result = generateCollectionFile("orders", meta, [], new Set(), new Map([["orders", meta]]), new Map());
|
|
433
|
+
expect(result).toContain("export default ordersCollection;");
|
|
434
|
+
});
|
|
435
|
+
});
|
|
436
|
+
});
|