-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.mjs
executable file
·1653 lines (1580 loc) · 56.1 KB
/
index.mjs
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// @ts-check
import path from "path";
import _debug from "debug";
import fs from "fs/promises";
import { transform } from "inflection";
import {
entityPermissions,
makeIntrospectionQuery,
parseIntrospectionResults,
} from "pg-introspection";
import recast from "recast";
import { cosmiconfig } from "cosmiconfig";
import { z } from "zod";
main();
const debug = _debug("pg-sourcerer");
const inflectionsSchema = z
.record(
z.array(
z.union([
z.literal("pluralize"),
z.literal("singularize"),
z.literal("camelize"),
z.literal("underscore"),
z.literal("humanize"),
z.literal("capitalize"),
z.literal("dasherize"),
z.literal("titleize"),
z.literal("demodulize"),
z.literal("tableize"),
z.literal("classify"),
z.literal("foreignKey"),
z.literal("ordinalize"),
]),
),
)
.optional();
export const userConfig = z.object({
connectionString: z.string(),
adapter: z.union([z.literal("pg"), z.literal("postgres")]),
outputDir: z.string(),
outputExtension: z.string(),
typeMap: z
.record(
z.union([
z.literal("string"),
z.literal("boolean"),
z.literal("number"),
z.literal("Date"),
z.literal("unknown"),
]),
)
.optional(),
role: z.string().optional(),
inflections: inflectionsSchema,
plugins: z.array(
z.object({
name: z.string(),
inflections: inflectionsSchema,
// TODO: other possible phases?
render: z
.function()
.args(z.any())
.returns(
z.array(
z
.object({
content: z.any(), // ast builder can take care of itself
path: z.string(),
exports: z
.array(
z.object({
identifier: z.string(),
kind: z.union([
z.literal("type"),
z.literal("zodSchema"),
z.record(
// z.union([
z.function(z.tuple([]), z.any()),
// ]),
),
]),
}),
)
.refine(
entries => {
const [values, types] = partition([e => e.kind === "type"], entries);
const typeIdentifiers = new Set(types.map(e => e.identifier));
const valueIdentifiers = new Set(values.map(e => e.identifier));
return (
typeIdentifiers.size === types.length &&
valueIdentifiers.size === values.length
);
},
{ message: "export identifiers must be unique" },
),
imports: z
.array(
z
.object({
typeImport: z.boolean().optional(),
identifier: z.string(),
default: z.boolean().optional(),
path: z.string(),
})
.strict(),
)
.optional(),
})
.optional(),
),
),
}),
),
});
/** @typedef {z.infer<typeof userConfig>} Config */
/** @typedef {z.infer<typeof inflectionsSchema>} Inflections */
/** @returns {Promise<Config>} */
export async function parseConfig() {
let configSearch = await cosmiconfig("pgsourcerer").search();
if (!configSearch) {
// TODO: what if we codegen a config from prompts?
console.error("a pgsourcerer config is required");
process.exit(1);
}
let config;
try {
config = userConfig.parse(configSearch.config);
} catch (e) {
console.log(e instanceof z.ZodError ? e.flatten() : e);
process.exit(1);
}
return config;
}
/** @typedef {{ typeImport?: boolean, identifier: string, default?: boolean, path: string}} ImportSpec */
/** @typedef {ReturnType<Config['plugins'][number]['render']>[number]} Output */
const utils = {
getTypeName,
getTSTypeNameFromPgType,
getASTTypeFromTypeName,
getOperatorsFrom,
getPermissions,
getDescription,
findExports,
builders: recast.types.builders,
};
/** @typedef {{
name: string,
inflections?: Inflections;
render(info: {
introspection: { schemas: Record<string, DbSchema> };
output: Array<Output> | null;
config: Config;
utils: typeof utils;
}): Array<Output>
}} Plugin */
/** @returns {Promise<void>} */
async function main() {
const config = await parseConfig();
const introspectionResult = await (async () => {
const query = makeIntrospectionQuery();
switch (config.adapter) {
case "pg": {
const { default: pg } = await import("pg");
const pool = new pg.Pool({ connectionString: config.connectionString });
const client = await pool.connect();
await client.query("begin");
if (config.role) {
await client.query("select set_config('role', $1, false)", [config.role]);
}
const { rows } = await client.query(query);
await client.query("rollback");
client.release();
pool.end();
return rows[0].introspection;
}
case "postgres": {
const { default: postgres } = await import("postgres");
const sql = postgres(config.connectionString);
const result = await sql.begin(async sql => {
if (config.role) {
await sql`select set_config('role', ${config.role}, false)`;
}
const rows = await sql.unsafe(query);
sql.unsafe("rollback");
return rows[0].introspection;
});
sql.end();
return result;
}
default:
console.error(`invalid adapter in config: ${config.adapter}`);
process.exit(1);
}
})();
if (!("plugins" in config)) {
console.error("no plugins defined, nothing to do");
return process.exit(0);
}
const introspection = processIntrospection(parseIntrospectionResults(introspectionResult, true));
/** @type {null | Array<Output>} */
const output = pluginRunner(config, introspection);
if (!output || !output.length) {
console.error("no output from plugins");
return process.exit(1);
}
Object.entries(groupBy(o => o.path, output)).forEach(async ([strPath, files]) => {
const parsedFile = path.parse(path.join(config.outputDir ?? "./", strPath));
const filepath = parsedFile.dir;
const newPath = path.join(parsedFile.dir, parsedFile.base);
const result = recast.print(
recast.types.builders.program([
...parseDependencies(files.flatMap(f => f.imports ?? [])),
...files.flatMap(f => f.content),
]),
{ tabWidth: 2 },
);
await fs.mkdir(filepath, { recursive: true });
await fs.writeFile(newPath, result.code, "utf8");
console.log('wrote file "%s"', newPath.replace(import.meta.dirname, "."));
});
}
/**
* @param {Config} config
* @param {Introspection} introspection
*/
function pluginRunner(config, introspection) {
// @workspace compose plugin.inflections
const inflections = config.plugins.reduce(
(o, plugin) => {
if (plugin.inflections) {
for (const key in plugin.inflections) {
const inflections = (config.inflections?.[key] ?? []).concat(
plugin.inflections[key] ?? [],
);
o[key] = str => transform(str, inflections);
}
}
return o;
},
{ columns: s => s },
);
config.inflections = inflections;
return config.plugins.reduce((prevOutput, plugin) => {
const newOutput = plugin.render({
introspection,
output: prevOutput,
config,
utils,
});
return prevOutput ? prevOutput.concat(newOutput) : newOutput;
}, /** @type {null | Array<Output>} */ (null));
}
/** @param {import("pg-introspection").PgType} type */
function getTypeName(type) {
return [type.getNamespace()?.nspname, type.typname].join(".");
}
/**
* might implement a custom metadata parser later
* @param {{ getDescription(): string | undefined }} entity
*/
function getDescription(entity) {
return entity.getDescription();
}
/** @typedef {{ name: string, schemas: Record<string, DbSchema> }} Introspection */
/**
* @param {import("pg-introspection").Introspection} introspection
* @returns {Introspection}
*/
function processIntrospection(introspection) {
const role = introspection.getCurrentUser();
if (!role) throw new Error("who am i???");
return {
name: introspection.database.datname,
schemas: Object.fromEntries(
introspection.namespaces.map(schema => [
schema.nspname,
processSchema(schema, { introspection, role }),
]),
),
};
}
/**
* @param {Parameters<typeof entityPermissions>[1]} entity
* @param {{
introspection: import("pg-introspection").Introspection,
role: import("pg-introspection").PgRoles,
}}
* @returns {{canSelect?: boolean, canInsert?: boolean, canUpdate?: boolean, canDelete?: boolean, canExecute?: boolean}}
*/
function getPermissions(entity, { introspection, role }) {
// licensed under MIT from Benjie Gillam
// https://github.com/graphile/crystal/blob/9d1c54a28e29a2da710ba093541b4a03bab6b5c6/graphile-build/graphile-build-pg/src/plugins/PgRBACPlugin.ts
switch (entity._type) {
case "PgAttribute": {
const table = entity.getClass();
if (!table) throw new Error(`couldn't find table for attribute ${entity.attname}`);
const attributePermissions = entityPermissions(introspection, entity, role, true);
const tablePermissions = entityPermissions(introspection, table, role, true);
const canSelect = attributePermissions.select || Boolean(tablePermissions.select);
const canInsert = attributePermissions.insert || Boolean(tablePermissions.insert);
const canUpdate = attributePermissions.update || Boolean(tablePermissions.update);
return { canSelect, canInsert, canUpdate };
}
case "PgClass": {
const perms = entityPermissions(introspection, entity, role, true);
let canSelect = perms.select ?? false;
let canInsert = perms.insert ?? false;
let canUpdate = perms.update ?? false;
const canDelete = perms.delete ?? false;
if (!canInsert || !canUpdate || !canSelect) {
const attributePermissions = entity
.getAttributes()
.filter(att => att.attnum > 0)
.map(att => entityPermissions(introspection, att, role, true));
for (const attributePermission of attributePermissions) {
canSelect ||= Boolean(attributePermission.select);
canInsert ||= Boolean(attributePermission.insert);
canUpdate ||= Boolean(attributePermission.update);
}
}
return { canSelect, canInsert, canUpdate, canDelete };
}
case "PgProc": {
const { execute } = entityPermissions(introspection, entity, role, true);
return { canExecute: execute };
}
default:
throw new Error(`unknown entity type "${entity._type}"`);
}
}
/** @typedef {ReturnType<typeof getPermissions>} Permissions */
/** @typedef {{
name: string;
views: Record<string, DbView>;
tables: Record<string, DbTable>;
functions: Record<string, DbFunction>;
types: Record<string, DbType>;
}} DbSchema */
/**
* @param {import("pg-introspection").PgNamespace} schema
* @param {{
introspection: import("pg-introspection").Introspection;
role: import("pg-introspection").PgRoles,
}}
* @returns {DbSchema}
*/
function processSchema(schema, { introspection, role }) {
return {
name: schema.nspname,
views: processViews(schema.oid, { introspection, role }),
tables: processTables(schema.oid, { introspection, role }),
functions: processFunctions(schema.oid, { introspection, role }),
types: processTypes(schema.oid, { introspection, role }),
// permissions: getPermissions(schema, { introspection, role }),
};
}
/**
* @param {string} schemaId
* @param {{
introspection: import("pg-introspection").Introspection,
role: import("pg-introspection").PgRoles,
}}
* @returns {Array<
* | { kind: "domain", name: string, type: "text" }
* | { kind: "enum", name: string, values: Array<string> }
* | { composite: "enum", name: string, type: Array<{ name: string, type: string }> }
* >}
*/
function processTypes(schemaId, { introspection, role }) {
void fs.writeFile("types.json", stringify(introspection.types), "utf8");
const domains = introspection.types
.filter(t => t.typtype === "d" && t.typnamespace === schemaId)
.map(t => ({ name: t.typname, kind: "domain", type: t.typoutput }));
const enums = introspection.types
.filter(t => t.typtype === "e" && t.typnamespace === schemaId)
.map(t => {
const values = t.getEnumValues();
if (!values) throw new Error("could not find enum values for ${t.typname}");
return {
name: t.typname,
kind: "enum",
values: values.map(x => x.enumlabel),
};
});
const composites = introspection.classes
.filter(cls => cls.relnamespace === schemaId && cls.relkind === "c")
.map(t => ({
name: t.relname,
kind: "composite",
values: t.getAttributes().map(a => {
const type = a.getType();
if (!type) throw new Error(`could not find type for composite attribute ${t.relname}`);
return { name: a.attname, type: getTypeName(type) };
}),
}));
const types = groupWith(
(a, b) => {
if (a) throw new Error(`existing type with name ${a.name}`);
return b;
},
t => t.name,
[...domains, ...enums, ...composites],
);
return types;
}
/** @typedef {{
name: string;
columns: Record<string, DbColumn>;
constraints: Record<string, DbReference>;
description: string | undefined;
permissions: Permissions;
}} DbView */
/**
* @param {string} schemaId
* @param {{
introspection: import("pg-introspection").Introspection,
role: import("pg-introspection").PgRoles,
}}
* @returns {Record<string, DbView>}
*/
function processViews(schemaId, { introspection, role }) {
const views = Object.fromEntries(
introspection.classes
.filter(cls => cls.relnamespace === schemaId && cls.relkind === "v")
.map(view => [
view.relname,
{
name: view.relname,
// TODO: any other attributes specific to views? references? pseudo-FKs?
columns: processColumns(view.oid, { introspection, role }),
constraints: processReferences(view.oid, { introspection }),
description: getDescription(view),
permissions: getPermissions(view, { introspection, role }),
},
]),
);
// console.log(...Object.values(views))
return views;
}
/** @typedef {{
name: string;
columns: Record<string, DbColumn>;
indexes: Record<string, DbIndex>;
references: Record<string, DbReference>;
permissions: Permissions;
description: string | undefined;
}} DbTable */
/**
* @param {string} schemaId
* @param {{
introspection: import("pg-introspection").Introspection,
role: import("pg-introspection").PgRoles,
}}
* @returns {Record<string, DbTable>}
*/
function processTables(schemaId, { introspection, role }) {
return Object.fromEntries(
introspection.classes
.filter(cls => cls.relnamespace === schemaId && cls.relkind === "r")
.map(table => {
const name = table.relname;
const permissions = getPermissions(table, { introspection, role });
const description = getDescription(table);
const references = processReferences(table.oid, { introspection });
const indexes = processIndexes(table.oid, { introspection });
const columns = processColumns(table.oid, { introspection, role });
return [name, { name, columns, indexes, references, permissions, description }];
}),
);
}
/** @typedef {{
name: string;
identity: string | null;
type: string;
nullable: boolean;
generated: string | boolean;
isArray: boolean;
description: string | undefined;
permissions: Permissions;
}} DbColumn */
/**
* @param {string} tableId
* @param {{
* introspection: import("pg-introspection").Introspection,
* role: import("pg-introspection").PgRoles,
* }}
* @returns {Record<string, DbColumn>}
*/
function processColumns(tableId, { introspection, role }) {
return Object.fromEntries(
introspection.attributes
.filter(attr => attr.attrelid === tableId)
.map(column => {
const type = column.getType();
if (!type) throw new Error(`couldn't find type for column ${column.attname}`);
const isArray = column.attndims && column.attndims > 0;
const typeName = isArray ? getTypeName(type.getElemType()) : getTypeName(type);
return [
column.attname,
{
name: column.attname,
identity: column.attidentity,
type: typeName,
nullable: !column.attnotnull,
generated: column.attgenerated ? "STORED" : false,
isArray,
description: getDescription(column),
// original: column,
permissions: getPermissions(column, { introspection, role }),
},
];
}),
);
}
/** @typedef {{
name: string;
colnames: Array<string>;
isUnique: boolean | null;
isPrimary: boolean | null;
option: Readonly<Array<number>> | null;
type: string
}} DbIndex */
/**
* @param {string} tableId
* @param {{
* introspection: import("pg-introspection").Introspection,
* }}
* @returns {Record<string, DbIndex>}
*/
function processIndexes(tableId, { introspection }) {
return Object.fromEntries(
introspection.indexes
.filter(index => index.indrelid === tableId)
.map(index => {
const cls = index.getIndexClass();
if (!cls) throw new Error(`failed to find index class for index ${index.indrelid}`);
const am = cls.getAccessMethod();
if (!am) throw new Error(`failed to find access method for index ${cls.relname}`);
const keys = index.getKeys();
if (!keys) throw new Error(`failed to find keys for index ${cls.relname}`);
const colnames = keys.filter(Boolean).map(a => a.attname);
const name = cls.relname;
// TODO: process index-specific options?
const option = index.indoption;
return [
name,
/** @type DbIndex */ ({
name,
isUnique: index.indisunique,
isPrimary: index.indisprimary,
option,
type: am.amname,
colnames,
}),
];
}),
);
}
/** @typedef {{
refPath: {
schema: string;
table: string;
column: string;
};
}} DbReference */
/**
* @param {string} tableId
* @param {{introspection: import("pg-introspection").Introspection}}
* @returns {Record<string, DbReference>}
*/
function processReferences(tableId, { introspection }) {
return Object.fromEntries(
introspection.constraints
.filter(c => c.conrelid === tableId && c.contype === "f")
.map(constraint => {
const fkeyAttr = constraint.getForeignAttributes();
if (!fkeyAttr) throw new Error();
const fkeyClass = constraint.getForeignClass();
if (!fkeyClass) throw new Error();
const fkeyNsp = fkeyClass?.getNamespace();
if (!fkeyNsp) throw new Error();
const refPath = {
schema: fkeyNsp?.nspname,
table: fkeyClass?.relname,
column: fkeyAttr?.[0].attname,
};
return [
constraint.conname,
{
name: constraint.conname,
refPath,
// original: constraint,
},
];
}),
);
}
/** @typedef {{
permissions: Permissions;
returnType: string | undefined;
args: Array<[string | number, { type: string; hasDefault?: boolean }]>;
volatility: "immutable" | "stable" | "volatile"
}} DbFunction */
/**
* @param {string} schemaId
* @param {{
introspection: import("pg-introspection").Introspection,
role: import("pg-introspection").PgRoles,
}} _
* @returns {Record<string, DbFunction>}
*/
function processFunctions(schemaId, { introspection, role }) {
return Object.fromEntries(
introspection.procs
.filter(proc => proc.pronamespace === schemaId)
.map(proc => {
const type = proc.getReturnType();
if (!type) throw new Error(`couldn't find type for proc ${proc.proname}`);
return [
proc.proname,
{
permissions: getPermissions(proc, { introspection, role }),
returnType: getTypeName(type),
volatility: { i: "immutable", s: "stable", v: "volatile" }[proc.provolatile],
// TODO: inflection?
args: !proc.proargnames
? []
: proc.getArguments().map((a, i) => {
/* not every argument is named! */
const argName = proc.proargnames?.[i] ?? i + 1;
return [
argName,
{
type: getTypeName(a.type),
hasDefault: a.hasDefault,
},
];
}),
},
];
}),
);
}
/******************************************************************************/
/** @type {(opts?: {
schemas?: Array<string>
tables?: Array<string>
inflections?: Inflections
path?: string | ((o: { schema: string, name: string }) => string),
}) => Plugin} pluginOpts */
export const makeTypesPlugin = pluginOpts => ({
name: "types",
inflections: {
types: ["classify"],
columns: [],
},
render({ introspection, config, utils }) {
const b = utils.builders;
return Object.values(introspection.schemas)
.filter(schema => pluginOpts?.schemas?.includes(schema.name) ?? true)
.flatMap(schema => {
const enums = Object.values(schema.types)
.filter(t => t.kind === "enum")
.map(t => {
return b.exportNamedDeclaration.from({
declaration: b.tsTypeAliasDeclaration.from({
id: t.name,
typeAnnotation: b.tsUnionType(t.values.map(v => b.literal(v))),
}),
});
});
const tables = Object.values(schema.tables)
.filter(table => pluginOpts?.tables?.includes(table.name) ?? true)
.map(table => {
const identifier = config.inflections.types(table.name);
const typeAlias = b.exportNamedDeclaration.from({
comments: table.description
? [
b.commentBlock.from({
leading: true,
value: `* ${table.description} `,
}),
]
: null,
declaration: b.tsTypeAliasDeclaration.from({
id: b.identifier(identifier),
typeAnnotation: b.tsTypeLiteral(
Object.values(table.columns).map(column => {
const type = utils.getASTTypeFromTypeName(
utils.getTSTypeNameFromPgType(column.type, config),
);
return b.tsPropertySignature.from({
comments: column.description
? [b.commentBlock(`* ${column.description} `)]
: null,
key: b.identifier(config.inflections.columns(column.name)),
typeAnnotation: b.tsTypeAnnotation(
column.nullable ? b.tsUnionType([type, b.tsNullKeyword()]) : type,
),
});
}),
),
}),
});
return { identifier, typeAlias };
});
return [...tables, ...enums].map(({ identifier, typeAlias }) => ({
path: makePathFromConfig({
config: { ...config, pluginOpts },
name: identifier,
schema: schema.name,
}),
content: typeAlias,
exports: [{ identifier, kind: "type" }],
}));
});
},
});
/** @type {(pluginOpts?: {
schemas?: Array<string>
tables?: Array<string>
path?: string | ((o: { schema: string, name: string }) => string),
exportType?: boolean
}) => Plugin} */
export const makeZodSchemasPlugin = pluginOpts => ({
name: "schemas",
inflections: {
types: ["camelize", "singularize"],
schemas: ["camelize", "singularize"],
},
render({ introspection, config, utils }) {
const b = utils.builders;
return Object.values(introspection.schemas)
.filter(s => pluginOpts?.schemas?.includes(s.name) ?? true)
.flatMap(schema => {
const tables = Object.values(schema.tables)
.filter(table => pluginOpts?.tables?.includes(table.name) ?? true)
.map(table => {
const identifier = config.inflections.schemas(table.name);
const exportType = b.exportNamedDeclaration(
b.tsTypeAliasDeclaration.from({
id: b.identifier(config.inflections.schemas(identifier)),
typeAnnotation: b.tsExpressionWithTypeArguments(
b.tsQualifiedName(b.identifier("z"), b.identifier("infer")),
b.tsTypeParameterInstantiation([
b.tsTypeQuery(b.identifier(config.inflections.schemas(identifier))),
]),
),
}),
);
const zodSchema = b.exportNamedDeclaration(
b.variableDeclaration("const", [
b.variableDeclarator(
b.identifier(config.inflections.schemas(identifier)),
b.callExpression(
b.memberExpression(
b.callExpression(
b.memberExpression(b.identifier("z"), b.identifier("object")),
[
b.objectExpression(
Object.values(table.columns).map(c => {
const tsType = utils.getTSTypeNameFromPgType(c.type, config);
if (!tsType) {
c.type.split(".").reduce((p, c) => p[c], introspection);
}
const value = b.callExpression(
b.memberExpression(b.identifier("z"), b.identifier(tsType)),
[],
);
const typeModifiers = [
...(c.nullable ? ["nullable"] : []),
...({ "pg_catalog.uuid": ["uuid"] }[c.type] ?? []),
].reduceRight(
(p, i) =>
b.callExpression(b.memberExpression(p, b.identifier(i)), []),
value,
);
return b.objectProperty.from({
key: b.literal(config.inflections.columns(c.name)),
value: typeModifiers,
});
}),
),
],
),
b.identifier("strict"),
),
[],
),
),
]),
);
return {
content: pluginOpts?.exportType ? [zodSchema, exportType] : [zodSchema],
identifier,
};
});
return [
...tables,
// TODO: ...views
].map(
({ identifier, content }) =>
/** @type {Output} */ ({
path: makePathFromConfig({
config: { ...config, pluginOpts },
name: config.inflections.schemas(identifier),
schema: schema.name,
}),
content,
imports: [{ identifier: "z", path: "zod" }],
exports: [
{ identifier, kind: "zodSchema" },
...(pluginOpts?.exportType ? [{ identifier, kind: "type" }] : []),
],
}),
);
});
},
});
/** @typedef {{
name: string;
operation: "select" | "insert" | "update" | "delete" | "function"
params: Record<string, { default?: any; type: string, Pick?: Array<string> }>;
where?: Array<[string, string, string]>;
join?: Array<string>;
order?: Array<string>;
returnType?: string;
returnsMany?: boolean;
schema: string;
identifier: string;
}} QueryData */
// TODO: typescript optional? jsdoc setting?
/** @type {(opts: {
schemas: Array<string>,
tables?: Array<string>,
path?: string | ((o: { schema: string, name: string }) => string),
}) => Plugin} pluginOpts */
export const makeQueriesPlugin = pluginOpts => ({
name: "queries",
inflections: {
identifiers: ["camelize"],
methods: ["camelize"],
},
render({ introspection, config, output, utils }) {
if (!output) {
throw new Error("makeQueriesPlugin must be placed after a plugin that exports a type");
}
return Object.values(introspection.schemas)
.filter(schema => pluginOpts.schemas?.includes(schema.name) ?? true)
.map(schema => {
const tableNames = Object.keys(schema.tables).map(t => `${schema.name}.${t}`);
const availableFunctions = Object.entries(schema.functions).filter(
([_, f]) => f.permissions.canExecute,
);
const [computed, procs] = partition(
[
([_, fn]) => {
if (fn.args.length !== 1) return false;
if (fn.volatility === "volatile") return false;
const firstArgType = fn.args[0]?.[1].type;
const idx = tableNames.findIndex(
tableName => firstArgType && firstArgType === tableName,
);
return idx > -1;
},
],
availableFunctions,
);
const computedByTables = groupBy(([_, fn]) => fn.args[0][1].type, computed);
const fnQueries = procs.map(
([name, fn]) =>
/** @type QueryData */ ({
name: config.inflections.methods(name),
operation: "select",
schema: schema.name,
identifier: name,
}),
);
/** @type QueryData[][] */
const tables = Object.values(schema.tables)
.filter(table => pluginOpts.tables?.includes(table.name) ?? true)
.map(table =>
Object.values(table.indexes).flatMap(index => {
if (index.colnames.length > 1) {
debug("queries plugin", `ignoring multi-column index ${index.name}`);
return [];
}
const columns = Object.values(table.columns);
const idxColumns = index.colnames.map(n => table.columns[n]);
const identifier = table.name;
const schemaName = schema.name;
const returnType = config.inflections.types(table.name);
const pgTypeName = utils.getTSTypeNameFromPgType(idxColumns.type, config);
if (idxColumns.length > 1) {
console.log(idxColumns);
} else {
const column = idxColumns[0];
const columnName = config.inflections.columns(column.name);
switch (true) {
case index.isPrimary:
return [
...(!table.permissions.canSelect
? []
: [
{
name: config.inflections.methods(`by_${idxColumns.name}`),
operation: "select",
where: [[column.name, "=", "?"]],
params: {
patch: {
Pick: [columnName],
type: config.inflections.types(table.name),
},
},
returnType,
returnsMany: false,
schema: schemaName,
identifier,
},
]),
...(!table.permissions.canInsert
? []
: [
{
name: config.inflections.methods("create"),
operation: "insert",
params: {
patch: {
type: config.inflections.types(table.name),
Pick: columns
.filter(c => c.permissions.canInsert)
.map(c => config.inflections.columns(c.name)),
},
},
returnType,
returnsMany: false,
schema: schemaName,
identifier,
},
]),
...(!table.permissions.canUpdate
? []
: [
{
name: config.inflections.methods("update"),
operation: "update",
where: [[columnName, "=", "?"]],