-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
119 lines (104 loc) · 2.25 KB
/
index.js
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
#!/usr/bin/env node
import Fs from "node:fs";
import meow from "meow";
import Process from "node:process";
import Path from "node:path";
import { tsImport } from "tsx/esm/api";
import {
pgGenerate,
mysqlGenerate,
sqliteGenerate,
} from "drizzle-dbml-generator";
const cli = meow(
`
Usage
$ drizzle-dbml-cli <input>
Options
--type, -t Explicit type: one of sqlite, mysql, or pg
If not provided, it'll be auto-detected
-o Save output to the given output file
instead of writing to stdout
--verbose, -v Verbose output
--format, -f Format, one of dbml, svg, or dot.
Examples
$ drizzle-dbml-cli db/schema.ts
`,
{
importMeta: import.meta, // This is required
flags: {
type: {
type: "string",
shortFlag: "t",
choices: ["sqlite", "mysql", "pg"],
},
format: {
type: "string",
shortFlag: "f",
choices: ["dbml", "svg", "dot"],
},
o: {
type: "string",
},
verbose: {
type: "boolean",
shortFlag: "v",
},
},
},
);
if (!cli.input.length) {
cli.showHelp();
}
const relational = false;
const schema = await tsImport(
Path.resolve(Process.cwd(), process.argv[2]),
import.meta.url,
);
let method = null;
function log(...input) {
if (cli.flags.v) {
console.error(...input);
}
}
if (cli.flags.type) {
method = {
pg: pgGenerate,
mysql: mysqlGenerate,
sqlite: sqliteGenerate,
}[cli.flags.type];
} else {
for (const e of Object.values(schema)) {
const name = e?.constructor?.name;
if (typeof name !== "string") continue;
if (name.startsWith("Pg")) {
log("Detected Postgres");
method = pgGenerate;
break;
}
if (name.startsWith("My")) {
log("Detected MySQL");
method = mysqlGenerate;
break;
}
if (name.startsWith("SQ")) {
log("Detected SQLite");
method = sqliteGenerate;
break;
}
}
}
if (!method) {
console.error("Detecting database type failed");
process.exit(1);
}
let output = method({ schema, relational });
const format = cli.flags.format || "dbml";
if (format === "svg" || format === "dot") {
const { run } = await import("@softwaretechnik/dbml-renderer");
output = run(output, format);
}
if (cli.flags.o) {
Fs.writeFileSync(cli.flags.o, output);
} else {
process.stdout.write(output);
}