-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpgpm-module.ts
More file actions
331 lines (290 loc) · 10 KB
/
pgpm-module.ts
File metadata and controls
331 lines (290 loc) · 10 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/**
* PGPM Module Schema Source
*
* Loads GraphQL schema from a PGPM module by:
* 1. Creating an ephemeral database
* 2. Deploying the module to the database
* 3. Introspecting the database with PostGraphile
* 4. Cleaning up the ephemeral database (unless keepDb is true)
*/
import { PgpmPackage } from '@pgpmjs/core';
import { buildSchema, introspectionFromSchema } from 'graphql';
import { getPgPool, pgCache } from 'pg-cache';
import { createEphemeralDb, type EphemeralDbResult } from 'pgsql-client';
import { deployPgpm } from 'pgsql-seed';
import { buildSchemaSDL } from 'graphile-schema';
import type { IntrospectionQueryResponse } from '../../../types/introspection';
import { resolveApiSchemas, validateServicesSchemas } from './api-schemas';
import type { SchemaSource, SchemaSourceResult } from './types';
import { SchemaSourceError } from './types';
/**
* Options for PGPM module schema source using direct module path
*/
export interface PgpmModulePathOptions {
/**
* Path to the PGPM module directory
* The directory should contain a pgpm.plan file and .control file
*/
pgpmModulePath: string;
/**
* PostgreSQL schemas to include in introspection
* Mutually exclusive with apiNames
*/
schemas?: string[];
/**
* API names to resolve schemas from
* Queries services_public.api_schemas to get schema names
* Mutually exclusive with schemas
*/
apiNames?: string[];
/**
* If true, keeps the ephemeral database after introspection (useful for debugging)
* @default false
*/
keepDb?: boolean;
}
/**
* Options for PGPM module schema source using workspace + module name
*/
export interface PgpmWorkspaceOptions {
/**
* Path to the PGPM workspace directory
* The directory should contain a pgpm.config.yaml or similar workspace config
*/
pgpmWorkspacePath: string;
/**
* Name of the module within the workspace
*/
pgpmModuleName: string;
/**
* PostgreSQL schemas to include in introspection
* Mutually exclusive with apiNames
*/
schemas?: string[];
/**
* API names to resolve schemas from
* Queries services_public.api_schemas to get schema names
* Mutually exclusive with schemas
*/
apiNames?: string[];
/**
* If true, keeps the ephemeral database after introspection (useful for debugging)
* @default false
*/
keepDb?: boolean;
}
export type PgpmModuleSchemaSourceOptions =
| PgpmModulePathOptions
| PgpmWorkspaceOptions;
/**
* Type guard to check if options use direct module path
*/
export function isPgpmModulePathOptions(
options: PgpmModuleSchemaSourceOptions,
): options is PgpmModulePathOptions {
return 'pgpmModulePath' in options;
}
/**
* Type guard to check if options use workspace + module name
*/
export function isPgpmWorkspaceOptions(
options: PgpmModuleSchemaSourceOptions,
): options is PgpmWorkspaceOptions {
return 'pgpmWorkspacePath' in options && 'pgpmModuleName' in options;
}
/**
* Schema source that loads from a PGPM module
*
* Creates an ephemeral database, deploys the module, introspects the schema,
* and cleans up. Supports both direct module path and workspace + module name modes.
*/
export class PgpmModuleSchemaSource implements SchemaSource {
private readonly options: PgpmModuleSchemaSourceOptions;
private ephemeralDb: EphemeralDbResult | null = null;
constructor(options: PgpmModuleSchemaSourceOptions) {
this.options = options;
}
async fetch(): Promise<SchemaSourceResult> {
const keepDb = this.getKeepDb();
const apiNames = this.getApiNames();
// Resolve the module path
let modulePath: string;
try {
modulePath = this.resolveModulePath();
} catch (err) {
throw new SchemaSourceError(
`Failed to resolve module path: ${err instanceof Error ? err.message : 'Unknown error'}`,
this.describe(),
err instanceof Error ? err : undefined,
);
}
// Validate the module exists
const pkg = new PgpmPackage(modulePath);
if (!pkg.isInModule()) {
throw new SchemaSourceError(
`Not a valid PGPM module: ${modulePath}. Directory must contain pgpm.plan and .control files.`,
this.describe(),
);
}
// Create ephemeral database
try {
this.ephemeralDb = createEphemeralDb({
prefix: 'codegen_pgpm_',
verbose: false,
});
} catch (err) {
throw new SchemaSourceError(
`Failed to create ephemeral database: ${err instanceof Error ? err.message : 'Unknown error'}`,
this.describe(),
err instanceof Error ? err : undefined,
);
}
const { config: dbConfig, teardown } = this.ephemeralDb;
try {
// Deploy the module to the ephemeral database
try {
await deployPgpm(dbConfig, modulePath, false);
} catch (err) {
throw new SchemaSourceError(
`Failed to deploy PGPM module: ${err instanceof Error ? err.message : 'Unknown error'}`,
this.describe(),
err instanceof Error ? err : undefined,
);
}
// Resolve schemas - either from explicit schemas option or from apiNames (after deployment)
let schemas: string[];
if (apiNames && apiNames.length > 0) {
// For PGPM mode, validate services schemas AFTER migration
const pool = getPgPool(dbConfig);
try {
const validation = await validateServicesSchemas(pool);
if (!validation.valid) {
throw new SchemaSourceError(validation.error!, this.describe());
}
schemas = await resolveApiSchemas(pool, apiNames);
} catch (err) {
if (err instanceof SchemaSourceError) throw err;
throw new SchemaSourceError(
`Failed to resolve API schemas: ${err instanceof Error ? err.message : 'Unknown error'}`,
this.describe(),
err instanceof Error ? err : undefined,
);
}
} else {
schemas = this.getSchemas();
}
// Build SDL from the deployed database
let sdl: string;
try {
sdl = await buildSchemaSDL({
database: dbConfig.database,
schemas,
});
} catch (err) {
throw new SchemaSourceError(
`Failed to introspect database: ${err instanceof Error ? err.message : 'Unknown error'}`,
this.describe(),
err instanceof Error ? err : undefined,
);
}
// Validate non-empty
if (!sdl.trim()) {
throw new SchemaSourceError(
'Database introspection returned empty schema',
this.describe(),
);
}
// Parse SDL to GraphQL schema
let schema;
try {
schema = buildSchema(sdl);
} catch (err) {
throw new SchemaSourceError(
`Invalid GraphQL SDL from database: ${err instanceof Error ? err.message : 'Unknown error'}`,
this.describe(),
err instanceof Error ? err : undefined,
);
}
// Convert to introspection format
let introspectionResult;
try {
introspectionResult = introspectionFromSchema(schema);
} catch (err) {
throw new SchemaSourceError(
`Failed to generate introspection: ${err instanceof Error ? err.message : 'Unknown error'}`,
this.describe(),
err instanceof Error ? err : undefined,
);
}
// Convert graphql-js introspection result to our mutable type
const introspection: IntrospectionQueryResponse = JSON.parse(
JSON.stringify(introspectionResult),
) as IntrospectionQueryResponse;
return { introspection };
} finally {
// Release pg-cache pool for this ephemeral database before dropping
// deployPgpm() and getPgPool() cache connections that must be closed first
pgCache.delete(dbConfig.database);
await pgCache.waitForDisposals();
// Clean up the ephemeral database
teardown({ keepDb });
if (keepDb) {
console.log(
`[pgpm-module] Kept ephemeral database: ${dbConfig.database}`,
);
}
}
}
describe(): string {
const apiNames = this.getApiNames();
if (isPgpmModulePathOptions(this.options)) {
if (apiNames && apiNames.length > 0) {
return `pgpm module: ${this.options.pgpmModulePath} (apiNames: ${apiNames.join(', ')})`;
}
const schemas = this.options.schemas ?? ['public'];
return `pgpm module: ${this.options.pgpmModulePath} (schemas: ${schemas.join(', ')})`;
} else {
if (apiNames && apiNames.length > 0) {
return `pgpm workspace: ${this.options.pgpmWorkspacePath}, module: ${this.options.pgpmModuleName} (apiNames: ${apiNames.join(', ')})`;
}
const schemas = this.options.schemas ?? ['public'];
return `pgpm workspace: ${this.options.pgpmWorkspacePath}, module: ${this.options.pgpmModuleName} (schemas: ${schemas.join(', ')})`;
}
}
private resolveModulePath(): string {
if (isPgpmModulePathOptions(this.options)) {
return this.options.pgpmModulePath;
}
// Workspace + module name mode
const { pgpmWorkspacePath, pgpmModuleName } = this.options;
const workspace = new PgpmPackage(pgpmWorkspacePath);
if (!workspace.workspacePath) {
throw new Error(`Not a valid PGPM workspace: ${pgpmWorkspacePath}`);
}
// Get the module from the workspace
const moduleProject = workspace.getModuleProject(pgpmModuleName);
const modulePath = moduleProject.getModulePath();
if (!modulePath) {
throw new Error(`Module "${pgpmModuleName}" not found in workspace`);
}
return modulePath;
}
private getSchemas(): string[] {
if (isPgpmModulePathOptions(this.options)) {
return this.options.schemas ?? ['public'];
}
return this.options.schemas ?? ['public'];
}
private getApiNames(): string[] | undefined {
if (isPgpmModulePathOptions(this.options)) {
return this.options.apiNames;
}
return this.options.apiNames;
}
private getKeepDb(): boolean {
if (isPgpmModulePathOptions(this.options)) {
return this.options.keepDb ?? false;
}
return this.options.keepDb ?? false;
}
}