@apso/cli 0.29.1 → 0.31.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.
@@ -0,0 +1,327 @@
1
+ "use strict";
2
+ /**
3
+ * Database Import — introspection layer
4
+ *
5
+ * Reads the schema of a live Postgres/Supabase database. This layer is
6
+ * deliberately thin and side-effect-light: it only issues read-only SELECTs
7
+ * against information_schema/pg_catalog and returns an `IntrospectedSchema`.
8
+ * All interpretation lives in the conversion layer (pg-to-apsorc.ts).
9
+ *
10
+ * `pg` is loaded lazily so importing this module (e.g. from the command) does
11
+ * not pull the driver until an actual connection is made.
12
+ */
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.buildSchema = exports.PgIntrospector = exports.redactConnectionString = exports.SYSTEM_SCHEMAS = void 0;
38
+ /** Supabase- and Postgres-managed schemas we never import from. */
39
+ exports.SYSTEM_SCHEMAS = new Set([
40
+ "auth",
41
+ "storage",
42
+ "realtime",
43
+ "_realtime",
44
+ "vault",
45
+ "extensions",
46
+ "graphql",
47
+ "graphql_public",
48
+ "pgsodium",
49
+ "pgsodium_masks",
50
+ "pgbouncer",
51
+ "cron",
52
+ "net",
53
+ "supabase_functions",
54
+ "supabase_migrations",
55
+ "_analytics",
56
+ "information_schema",
57
+ "pg_catalog",
58
+ "pg_toast",
59
+ ]);
60
+ const CONFDELTYPE_TO_ACTION = {
61
+ a: "NO ACTION",
62
+ r: "RESTRICT",
63
+ c: "CASCADE",
64
+ n: "SET NULL",
65
+ d: "SET DEFAULT",
66
+ };
67
+ /** Strip credentials from a connection string for safe display in errors. */
68
+ function redactConnectionString(input) {
69
+ return input.replace(/(\/\/[^/:@]+:)[^@]*(@)/, "$1****$2");
70
+ }
71
+ exports.redactConnectionString = redactConnectionString;
72
+ /**
73
+ * Reads schema metadata from a Postgres database via a connection string.
74
+ * SSL is enabled by default (Supabase requires it).
75
+ */
76
+ class PgIntrospector {
77
+ constructor(connectionString) {
78
+ this.connectionString = connectionString;
79
+ }
80
+ async connect() {
81
+ var _a, _b;
82
+ // Lazy import keeps `pg` out of the module graph until we actually connect.
83
+ const pg = await Promise.resolve().then(() => __importStar(require("pg")));
84
+ const Client = (_a = pg.Client) !== null && _a !== void 0 ? _a : (_b = pg.default) === null || _b === void 0 ? void 0 : _b.Client;
85
+ const client = new Client({
86
+ connectionString: this.connectionString,
87
+ ssl: { rejectUnauthorized: false },
88
+ });
89
+ await client.connect();
90
+ return client;
91
+ }
92
+ async introspect(schema) {
93
+ let client;
94
+ try {
95
+ client = await this.connect();
96
+ const [tableRows, columnRows, pkRows, fkRows, uniqueRows, indexRows, enumRows, schemaRows,] = [
97
+ await client.query(TABLES_SQL, [schema]),
98
+ await client.query(COLUMNS_SQL, [schema]),
99
+ await client.query(PRIMARY_KEYS_SQL, [schema]),
100
+ await client.query(FOREIGN_KEYS_SQL, [schema]),
101
+ await client.query(UNIQUE_SQL, [schema]),
102
+ await client.query(INDEXES_SQL, [schema]),
103
+ await client.query(ENUMS_SQL, [schema]),
104
+ await client.query(SCHEMAS_SQL),
105
+ ];
106
+ return buildSchema(schema, {
107
+ tableRows: tableRows.rows,
108
+ columnRows: columnRows.rows,
109
+ pkRows: pkRows.rows,
110
+ fkRows: fkRows.rows,
111
+ uniqueRows: uniqueRows.rows,
112
+ indexRows: indexRows.rows,
113
+ enumRows: enumRows.rows,
114
+ schemaRows: schemaRows.rows,
115
+ });
116
+ }
117
+ catch (error) {
118
+ const message = error instanceof Error ? error.message : String(error);
119
+ throw new Error(`Failed to introspect database: ${redactConnectionString(message)}`);
120
+ }
121
+ finally {
122
+ if (client)
123
+ await client.end();
124
+ }
125
+ }
126
+ }
127
+ exports.PgIntrospector = PgIntrospector;
128
+ const TABLES_SQL = `
129
+ SELECT table_name, table_type
130
+ FROM information_schema.tables
131
+ WHERE table_schema = $1 AND table_type IN ('BASE TABLE', 'VIEW')
132
+ ORDER BY table_name`;
133
+ const COLUMNS_SQL = `
134
+ SELECT table_name, column_name, udt_name, data_type, is_nullable,
135
+ column_default, character_maximum_length, numeric_precision,
136
+ numeric_scale, ordinal_position
137
+ FROM information_schema.columns
138
+ WHERE table_schema = $1
139
+ ORDER BY table_name, ordinal_position`;
140
+ const PRIMARY_KEYS_SQL = `
141
+ SELECT cl.relname AS table_name, att.attname AS column_name, ord.n AS key_index
142
+ FROM pg_constraint con
143
+ JOIN pg_class cl ON cl.oid = con.conrelid
144
+ JOIN pg_namespace ns ON ns.oid = cl.relnamespace
145
+ JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS ord(attnum, n) ON true
146
+ JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ord.attnum
147
+ WHERE con.contype = 'p' AND ns.nspname = $1
148
+ ORDER BY cl.relname, ord.n`;
149
+ const FOREIGN_KEYS_SQL = `
150
+ SELECT con.conname, cl.relname AS table_name, att.attname AS column_name,
151
+ clf.relname AS referenced_table, attf.attname AS referenced_column,
152
+ con.confdeltype, ord.n AS key_index
153
+ FROM pg_constraint con
154
+ JOIN pg_class cl ON cl.oid = con.conrelid
155
+ JOIN pg_namespace ns ON ns.oid = cl.relnamespace
156
+ JOIN pg_class clf ON clf.oid = con.confrelid
157
+ JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS ord(attnum, n) ON true
158
+ JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ord.attnum
159
+ JOIN pg_attribute attf ON attf.attrelid = con.confrelid AND attf.attnum = con.confkey[ord.n]
160
+ WHERE con.contype = 'f' AND ns.nspname = $1
161
+ ORDER BY con.conname, ord.n`;
162
+ const UNIQUE_SQL = `
163
+ SELECT con.conname, cl.relname AS table_name, att.attname AS column_name, ord.n AS key_index
164
+ FROM pg_constraint con
165
+ JOIN pg_class cl ON cl.oid = con.conrelid
166
+ JOIN pg_namespace ns ON ns.oid = cl.relnamespace
167
+ JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS ord(attnum, n) ON true
168
+ JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ord.attnum
169
+ WHERE con.contype = 'u' AND ns.nspname = $1
170
+ ORDER BY con.conname, ord.n`;
171
+ const INDEXES_SQL = `
172
+ SELECT tc.relname AS table_name, ic.relname AS index_name,
173
+ a.attname AS column_name, ix.indisunique, k.n AS ord
174
+ FROM pg_index ix
175
+ JOIN pg_class ic ON ic.oid = ix.indexrelid
176
+ JOIN pg_class tc ON tc.oid = ix.indrelid
177
+ JOIN pg_namespace ns ON ns.oid = tc.relnamespace
178
+ JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, n) ON true
179
+ JOIN pg_attribute a ON a.attrelid = tc.oid AND a.attnum = k.attnum
180
+ WHERE ns.nspname = $1 AND ix.indisprimary = false
181
+ ORDER BY tc.relname, ic.relname, k.n`;
182
+ const ENUMS_SQL = `
183
+ SELECT t.typname AS enum_name, e.enumlabel AS label
184
+ FROM pg_type t
185
+ JOIN pg_enum e ON e.enumtypid = t.oid
186
+ JOIN pg_namespace n ON n.oid = t.typnamespace
187
+ WHERE n.nspname = $1
188
+ ORDER BY t.typname, e.enumsortorder`;
189
+ const SCHEMAS_SQL = `SELECT schema_name FROM information_schema.schemata`;
190
+ /**
191
+ * Assemble raw query rows into an IntrospectedSchema. Exported (separate from
192
+ * the DB connection) so it can be unit-tested with fixture rows.
193
+ */
194
+ function buildSchema(schema, raw) {
195
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
196
+ // Enums
197
+ const enumMap = new Map();
198
+ for (const row of raw.enumRows) {
199
+ const list = (_a = enumMap.get(row.enum_name)) !== null && _a !== void 0 ? _a : [];
200
+ list.push(row.label);
201
+ enumMap.set(row.enum_name, list);
202
+ }
203
+ const enums = [...enumMap.entries()].map(([name, labels]) => ({ name, labels }));
204
+ // Tables / views
205
+ const baseTables = raw.tableRows
206
+ .filter((r) => r.table_type === "BASE TABLE")
207
+ .map((r) => r.table_name);
208
+ const views = raw.tableRows
209
+ .filter((r) => r.table_type === "VIEW")
210
+ .map((r) => r.table_name);
211
+ // Columns grouped by table
212
+ const columnsByTable = new Map();
213
+ for (const row of raw.columnRows) {
214
+ const isEnum = row.data_type === "USER-DEFINED" && enumMap.has(row.udt_name);
215
+ const col = {
216
+ name: row.column_name,
217
+ udtName: row.udt_name,
218
+ dataType: row.data_type,
219
+ nullable: row.is_nullable === "YES",
220
+ default: (_b = row.column_default) !== null && _b !== void 0 ? _b : null,
221
+ charMaxLength: (_c = row.character_maximum_length) !== null && _c !== void 0 ? _c : null,
222
+ numericPrecision: (_d = row.numeric_precision) !== null && _d !== void 0 ? _d : null,
223
+ numericScale: (_e = row.numeric_scale) !== null && _e !== void 0 ? _e : null,
224
+ ordinal: row.ordinal_position,
225
+ isEnum,
226
+ enumTypeName: isEnum ? row.udt_name : undefined,
227
+ };
228
+ const list = (_f = columnsByTable.get(row.table_name)) !== null && _f !== void 0 ? _f : [];
229
+ list.push(col);
230
+ columnsByTable.set(row.table_name, list);
231
+ }
232
+ // Primary keys
233
+ const pkByTable = new Map();
234
+ for (const row of raw.pkRows) {
235
+ const list = (_g = pkByTable.get(row.table_name)) !== null && _g !== void 0 ? _g : [];
236
+ list.push(row.column_name);
237
+ pkByTable.set(row.table_name, list);
238
+ }
239
+ // Foreign keys (grouped by constraint name to handle composite keys)
240
+ const fkByConstraint = new Map();
241
+ for (const row of raw.fkRows) {
242
+ const existing = fkByConstraint.get(row.conname);
243
+ if (existing) {
244
+ existing.columns.push(row.column_name);
245
+ existing.refColumns.push(row.referenced_column);
246
+ }
247
+ else {
248
+ fkByConstraint.set(row.conname, {
249
+ table: row.table_name,
250
+ columns: [row.column_name],
251
+ refTable: row.referenced_table,
252
+ refColumns: [row.referenced_column],
253
+ confdeltype: row.confdeltype,
254
+ });
255
+ }
256
+ }
257
+ const fksByTable = new Map();
258
+ for (const fk of fkByConstraint.values()) {
259
+ const list = (_h = fksByTable.get(fk.table)) !== null && _h !== void 0 ? _h : [];
260
+ list.push({
261
+ columns: fk.columns,
262
+ referencedTable: fk.refTable,
263
+ referencedColumns: fk.refColumns,
264
+ onDelete: (_j = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _j !== void 0 ? _j : "NO ACTION",
265
+ });
266
+ fksByTable.set(fk.table, list);
267
+ }
268
+ // Unique constraints (grouped by constraint name)
269
+ const uniqueByConstraint = new Map();
270
+ for (const row of raw.uniqueRows) {
271
+ const existing = uniqueByConstraint.get(row.conname);
272
+ if (existing)
273
+ existing.columns.push(row.column_name);
274
+ else
275
+ uniqueByConstraint.set(row.conname, {
276
+ table: row.table_name,
277
+ columns: [row.column_name],
278
+ });
279
+ }
280
+ const uniquesByTable = new Map();
281
+ for (const [name, uc] of uniqueByConstraint.entries()) {
282
+ const list = (_k = uniquesByTable.get(uc.table)) !== null && _k !== void 0 ? _k : [];
283
+ list.push({ name, columns: uc.columns });
284
+ uniquesByTable.set(uc.table, list);
285
+ }
286
+ // Indexes (grouped by index name)
287
+ const indexByName = new Map();
288
+ for (const row of raw.indexRows) {
289
+ const existing = indexByName.get(row.index_name);
290
+ if (existing)
291
+ existing.columns.push(row.column_name);
292
+ else
293
+ indexByName.set(row.index_name, {
294
+ table: row.table_name,
295
+ columns: [row.column_name],
296
+ unique: row.indisunique,
297
+ });
298
+ }
299
+ const indexesByTable = new Map();
300
+ for (const [name, idx] of indexByName.entries()) {
301
+ const list = (_l = indexesByTable.get(idx.table)) !== null && _l !== void 0 ? _l : [];
302
+ list.push({ name, columns: idx.columns, unique: idx.unique });
303
+ indexesByTable.set(idx.table, list);
304
+ }
305
+ const tables = baseTables.map((name) => {
306
+ var _a, _b, _c, _d, _e;
307
+ return ({
308
+ name,
309
+ columns: (_a = columnsByTable.get(name)) !== null && _a !== void 0 ? _a : [],
310
+ primaryKey: (_b = pkByTable.get(name)) !== null && _b !== void 0 ? _b : [],
311
+ foreignKeys: (_c = fksByTable.get(name)) !== null && _c !== void 0 ? _c : [],
312
+ uniqueConstraints: (_d = uniquesByTable.get(name)) !== null && _d !== void 0 ? _d : [],
313
+ indexes: (_e = indexesByTable.get(name)) !== null && _e !== void 0 ? _e : [],
314
+ });
315
+ });
316
+ const systemSchemas = raw.schemaRows
317
+ .map((r) => r.schema_name)
318
+ .filter((s) => exports.SYSTEM_SCHEMAS.has(s) && s !== schema)
319
+ .sort();
320
+ return {
321
+ schema,
322
+ tables,
323
+ enums,
324
+ skipped: { views, systemSchemas },
325
+ };
326
+ }
327
+ exports.buildSchema = buildSchema;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Database Import — conversion layer
3
+ *
4
+ * Turns an `IntrospectedSchema` (read from a live Postgres/Supabase database)
5
+ * into a `.apsorc`-shaped object. This is a pure function: same input always
6
+ * yields the same output and report, with no I/O — which keeps it exhaustively
7
+ * unit-testable.
8
+ *
9
+ * The reverse type map here is the inverse of `fieldTypeToColumnType`
10
+ * (src/lib/utils/field.ts). The FK-to-relationship logic mirrors how the
11
+ * platform derives FK column names in `getRelationshipIdField`
12
+ * (src/lib/utils/relationships/parse.ts) so imported relationships round-trip.
13
+ */
14
+ import { ImportReport, IntrospectedColumn, IntrospectedSchema } from "./types";
15
+ export interface ApsorcImportFieldOutput {
16
+ name: string;
17
+ type: string;
18
+ nullable?: boolean;
19
+ unique?: boolean;
20
+ default?: unknown;
21
+ index?: boolean;
22
+ values?: string[];
23
+ length?: number;
24
+ precision?: number;
25
+ scale?: number;
26
+ primary?: boolean;
27
+ }
28
+ export interface ApsorcImportEntityOutput {
29
+ name: string;
30
+ primaryKeyType?: "serial" | "uuid" | "text";
31
+ created_at?: boolean;
32
+ updated_at?: boolean;
33
+ fields?: ApsorcImportFieldOutput[];
34
+ uniques?: Array<{
35
+ fields: string[];
36
+ name?: string;
37
+ }>;
38
+ indexes?: Array<{
39
+ fields: string[];
40
+ unique?: boolean;
41
+ }>;
42
+ }
43
+ export interface ApsorcImportRelationshipOutput {
44
+ from: string;
45
+ to: string;
46
+ type: "OneToMany" | "ManyToOne" | "ManyToMany" | "OneToOne";
47
+ to_name?: string;
48
+ nullable?: boolean;
49
+ bi_directional?: boolean;
50
+ cascadeDelete?: boolean;
51
+ }
52
+ export interface ApsorcImportOutput {
53
+ version: number;
54
+ rootFolder: string;
55
+ apiType: string;
56
+ entities: ApsorcImportEntityOutput[];
57
+ relationships: ApsorcImportRelationshipOutput[];
58
+ }
59
+ interface TypeResolution {
60
+ type: string;
61
+ /** True when the mapping loses information (arrays, unknown types). */
62
+ lossy?: "array" | "defaulted";
63
+ }
64
+ /**
65
+ * Resolve a column's `.apsorc` field type from its Postgres type. Postgres
66
+ * arrays (udt_name starting with "_") collapse to `array`; user enums become
67
+ * `enum`; unknown types fall back to `text`.
68
+ */
69
+ export declare function pgTypeToApsorcType(col: IntrospectedColumn): TypeResolution;
70
+ /**
71
+ * Translate a raw Postgres default expression into an `.apsorc` default value.
72
+ * Returns `{ drop: true }` when the default cannot be represented (function
73
+ * calls, sequence/uuid generators). Auto-timestamp and sequence defaults are
74
+ * dropped silently by callers that handle them structurally.
75
+ */
76
+ export declare function parseDefault(raw: string | null, apsorcType: string): {
77
+ value?: unknown;
78
+ drop?: boolean;
79
+ };
80
+ /**
81
+ * Derive the relationship `to_name` so the platform regenerates a FK column
82
+ * matching the source column. Returns `undefined` when the default naming
83
+ * (`${camelCase(target)}Id`) already produces the source column. Sets
84
+ * `unmapped: true` when no name round-trips to the source column.
85
+ */
86
+ export declare function deriveToName(sourceColumn: string, targetTable: string): {
87
+ toName?: string;
88
+ unmapped?: boolean;
89
+ };
90
+ /**
91
+ * Convert an introspected Postgres schema into a `.apsorc`-shaped object plus a
92
+ * report of everything that could not be represented losslessly.
93
+ */
94
+ export declare function pgToApsorc(schema: IntrospectedSchema): {
95
+ apsorc: ApsorcImportOutput;
96
+ report: ImportReport;
97
+ };
98
+ /**
99
+ * Invariant guard: every emitted field type must be a recognized `.apsorc`
100
+ * column type, so code generation never silently falls back to varchar.
101
+ * Returns the list of any offending types (empty when valid).
102
+ */
103
+ export declare function findUnknownEmittedTypes(output: ApsorcImportOutput): string[];
104
+ export {};