@absolutejs/dbml 0.2.0 → 0.3.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.
- package/CHANGELOG.md +13 -0
- package/README.md +45 -7
- package/changelog.json +44 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +1267 -121
- package/dist/drizzle/index.js +59 -8
- package/dist/drizzle/relations.d.ts +1 -0
- package/dist/index.js +66 -9
- package/dist/model.d.ts +10 -0
- package/dist/mysql/index.d.ts +20 -0
- package/dist/mysql/index.js +452 -0
- package/dist/postgres/details.d.ts +40 -0
- package/dist/postgres/index.d.ts +5 -0
- package/dist/postgres/index.js +367 -26
- package/dist/postgres/queries.d.ts +13 -4
- package/dist/postgres/rows.d.ts +66 -0
- package/dist/sqlite/index.d.ts +14 -0
- package/dist/sqlite/index.js +420 -0
- package/dist/sqlite/text.d.ts +22 -0
- package/package.json +16 -3
package/dist/postgres/rows.d.ts
CHANGED
|
@@ -2,23 +2,36 @@ type Raw = Record<string, unknown>;
|
|
|
2
2
|
export type RelationRow = {
|
|
3
3
|
comment?: string;
|
|
4
4
|
definition?: string;
|
|
5
|
+
foreignOptions?: string;
|
|
6
|
+
foreignServer?: string;
|
|
5
7
|
forceRls: boolean;
|
|
8
|
+
grants?: string;
|
|
9
|
+
inherits?: string;
|
|
6
10
|
id: number;
|
|
7
11
|
kind: string;
|
|
8
12
|
name: string;
|
|
13
|
+
options?: string;
|
|
14
|
+
owner?: string;
|
|
9
15
|
partitionKey?: string;
|
|
10
16
|
partitions: number;
|
|
17
|
+
persistence: string;
|
|
11
18
|
rls: boolean;
|
|
19
|
+
rowEstimate?: string;
|
|
12
20
|
schema: string;
|
|
21
|
+
sizeBytes?: string;
|
|
13
22
|
};
|
|
14
23
|
export declare const relationRow: (row: Raw) => RelationRow;
|
|
15
24
|
export type ColumnRow = {
|
|
25
|
+
collation?: string;
|
|
16
26
|
comment?: string;
|
|
27
|
+
compression?: string;
|
|
17
28
|
default?: string;
|
|
29
|
+
domainBase?: string;
|
|
18
30
|
enumSchema?: string;
|
|
19
31
|
enumType?: string;
|
|
20
32
|
generated?: string;
|
|
21
33
|
identity?: string;
|
|
34
|
+
identitySequence?: string;
|
|
22
35
|
name: string;
|
|
23
36
|
notNull: boolean;
|
|
24
37
|
position: number;
|
|
@@ -46,11 +59,15 @@ export type ConstraintRow = {
|
|
|
46
59
|
export declare const constraintRow: (row: Raw) => ConstraintRow;
|
|
47
60
|
export type IndexRow = {
|
|
48
61
|
attnums: number[];
|
|
62
|
+
collations: string[];
|
|
49
63
|
comment?: string;
|
|
50
64
|
descending: boolean[];
|
|
51
65
|
keyCount: number;
|
|
52
66
|
method: string;
|
|
53
67
|
name: string;
|
|
68
|
+
nullsFirst: boolean[];
|
|
69
|
+
nullsNotDistinct: boolean;
|
|
70
|
+
opclasses: string[];
|
|
54
71
|
parts: string[];
|
|
55
72
|
predicate?: string;
|
|
56
73
|
tableId: number;
|
|
@@ -88,4 +105,53 @@ export declare const viewSourceRow: (row: Raw) => {
|
|
|
88
105
|
sourceId: number;
|
|
89
106
|
viewId: number;
|
|
90
107
|
};
|
|
108
|
+
/** A row of a table-scoped definition (a trigger, a rule). */
|
|
109
|
+
export declare const definitionRow: (row: Raw) => {
|
|
110
|
+
definition: string;
|
|
111
|
+
enabled: string;
|
|
112
|
+
name: string;
|
|
113
|
+
tableId: number;
|
|
114
|
+
};
|
|
115
|
+
export declare const functionRow: (row: Raw) => {
|
|
116
|
+
arguments: string;
|
|
117
|
+
kind: string;
|
|
118
|
+
language: string;
|
|
119
|
+
name: string;
|
|
120
|
+
result: string;
|
|
121
|
+
schema: string;
|
|
122
|
+
};
|
|
123
|
+
export declare const domainRow: (row: Raw) => {
|
|
124
|
+
base: string;
|
|
125
|
+
constraints: string | undefined;
|
|
126
|
+
default: string | undefined;
|
|
127
|
+
name: string;
|
|
128
|
+
notNull: boolean;
|
|
129
|
+
schema: string;
|
|
130
|
+
};
|
|
131
|
+
export declare const compositeRow: (row: Raw) => {
|
|
132
|
+
fields: string;
|
|
133
|
+
name: string;
|
|
134
|
+
schema: string;
|
|
135
|
+
};
|
|
136
|
+
export declare const extensionRow: (row: Raw) => {
|
|
137
|
+
name: string;
|
|
138
|
+
schema: string;
|
|
139
|
+
version: string;
|
|
140
|
+
};
|
|
141
|
+
export declare const eventTriggerRow: (row: Raw) => {
|
|
142
|
+
enabled: string;
|
|
143
|
+
event: string;
|
|
144
|
+
function: string;
|
|
145
|
+
name: string;
|
|
146
|
+
};
|
|
147
|
+
export declare const partitionRow: (row: Raw) => {
|
|
148
|
+
bound: string;
|
|
149
|
+
name: string;
|
|
150
|
+
tableId: number;
|
|
151
|
+
};
|
|
152
|
+
export declare const viewColumnRow: (row: Raw) => {
|
|
153
|
+
name: string;
|
|
154
|
+
sourceId: number;
|
|
155
|
+
viewId: number;
|
|
156
|
+
};
|
|
91
157
|
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type DbmlModel } from '../model';
|
|
2
|
+
/** Runs one statement with positional parameters and returns its rows. */
|
|
3
|
+
export type SqliteQuery = (text: string, params: unknown[]) => Promise<Record<string, unknown>[]> | Record<string, unknown>[];
|
|
4
|
+
export type FromSqliteOptions = {
|
|
5
|
+
project?: {
|
|
6
|
+
name?: string;
|
|
7
|
+
note?: string;
|
|
8
|
+
};
|
|
9
|
+
/** Each table's row count, as metadata. Counting reads every row, so
|
|
10
|
+
* it's left out unless asked for. */
|
|
11
|
+
statistics?: boolean;
|
|
12
|
+
};
|
|
13
|
+
/** The database's structure as a DBML model. */
|
|
14
|
+
export declare const fromSqlite: (query: SqliteQuery, options?: FromSqliteOptions) => Promise<DbmlModel>;
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/model.ts
|
|
3
|
+
var emptyModel = (project) => ({
|
|
4
|
+
deps: [],
|
|
5
|
+
enums: [],
|
|
6
|
+
notes: [],
|
|
7
|
+
...project ? { project } : {},
|
|
8
|
+
records: [],
|
|
9
|
+
refs: [],
|
|
10
|
+
tableGroups: [],
|
|
11
|
+
tables: []
|
|
12
|
+
});
|
|
13
|
+
var unqualified = (place, schema) => {
|
|
14
|
+
if (place.schema !== schema)
|
|
15
|
+
return place;
|
|
16
|
+
const { schema: dropped, ...rest } = place;
|
|
17
|
+
return rest;
|
|
18
|
+
};
|
|
19
|
+
var withDefaultSchema = (model, schema) => {
|
|
20
|
+
const result = {
|
|
21
|
+
...model,
|
|
22
|
+
deps: model.deps.map((dep) => ({
|
|
23
|
+
...dep,
|
|
24
|
+
downstream: unqualified(dep.downstream, schema),
|
|
25
|
+
upstream: unqualified(dep.upstream, schema)
|
|
26
|
+
})),
|
|
27
|
+
enums: model.enums.map((entry) => unqualified(entry, schema)),
|
|
28
|
+
records: model.records.map((records) => unqualified(records, schema)),
|
|
29
|
+
refs: model.refs.map((ref) => ({
|
|
30
|
+
...ref,
|
|
31
|
+
from: unqualified(ref.from, schema),
|
|
32
|
+
to: unqualified(ref.to, schema)
|
|
33
|
+
})),
|
|
34
|
+
tableGroups: model.tableGroups.map((group) => ({
|
|
35
|
+
...group,
|
|
36
|
+
tables: group.tables.map((entry) => unqualified(entry, schema))
|
|
37
|
+
})),
|
|
38
|
+
tables: model.tables.map((table) => ({
|
|
39
|
+
...unqualified(table, schema),
|
|
40
|
+
columns: table.columns.map((column) => {
|
|
41
|
+
if (column.typeSchema !== schema)
|
|
42
|
+
return column;
|
|
43
|
+
const { typeSchema: dropped, ...rest } = column;
|
|
44
|
+
return rest;
|
|
45
|
+
})
|
|
46
|
+
}))
|
|
47
|
+
};
|
|
48
|
+
return result;
|
|
49
|
+
};
|
|
50
|
+
var groupBySchema = (tables, defaultSchema = "public") => {
|
|
51
|
+
const byName = new Map;
|
|
52
|
+
tables.forEach((table) => {
|
|
53
|
+
const name = table.schema ?? defaultSchema;
|
|
54
|
+
byName.set(name, [
|
|
55
|
+
...byName.get(name) ?? [],
|
|
56
|
+
{
|
|
57
|
+
...table.schema ? { schema: table.schema } : {},
|
|
58
|
+
table: table.name
|
|
59
|
+
}
|
|
60
|
+
]);
|
|
61
|
+
});
|
|
62
|
+
return [...byName].map(([name, members]) => {
|
|
63
|
+
const group = { name, tables: members };
|
|
64
|
+
return group;
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
var sortedColumns = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
|
|
68
|
+
var coversAll = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
|
|
69
|
+
var isUniqueSet = (table, columns) => {
|
|
70
|
+
const [only] = columns;
|
|
71
|
+
const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
|
|
72
|
+
if (single?.pk === true || single?.unique === true)
|
|
73
|
+
return true;
|
|
74
|
+
const wanted = [...columns].sort().join("\x00");
|
|
75
|
+
return table.indexes.some((index) => coversAll(index) && index.parts.every((part) => part.kind === "column") && sortedColumns(index) === wanted);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// src/sqlite/text.ts
|
|
79
|
+
var CLOSERS = {
|
|
80
|
+
"'": "'",
|
|
81
|
+
'"': '"',
|
|
82
|
+
"[": "]",
|
|
83
|
+
"`": "`"
|
|
84
|
+
};
|
|
85
|
+
var pastQuote = (text, start) => {
|
|
86
|
+
const close = CLOSERS[text[start] ?? ""] ?? "";
|
|
87
|
+
let index = start + 1;
|
|
88
|
+
while (index < text.length) {
|
|
89
|
+
if (text[index] === close && text[index + 1] === close && close !== "]")
|
|
90
|
+
index += 2;
|
|
91
|
+
else if (text[index] === close)
|
|
92
|
+
return index + 1;
|
|
93
|
+
else
|
|
94
|
+
index += 1;
|
|
95
|
+
}
|
|
96
|
+
return text.length;
|
|
97
|
+
};
|
|
98
|
+
var DEPTH = { "(": 1, ")": -1 };
|
|
99
|
+
var unquoted = (text, from) => {
|
|
100
|
+
const marks = [];
|
|
101
|
+
let depth = 0;
|
|
102
|
+
let index = from;
|
|
103
|
+
while (index < text.length) {
|
|
104
|
+
const character = text[index] ?? "";
|
|
105
|
+
const quoted = character in CLOSERS;
|
|
106
|
+
depth += quoted ? 0 : DEPTH[character] ?? 0;
|
|
107
|
+
if (!quoted)
|
|
108
|
+
marks.push({ character, depth, index });
|
|
109
|
+
index = quoted ? pastQuote(text, index) : index + 1;
|
|
110
|
+
}
|
|
111
|
+
return marks;
|
|
112
|
+
};
|
|
113
|
+
var bracketed = (text, open) => {
|
|
114
|
+
const end = unquoted(text, open).find((mark) => mark.character === ")" && mark.depth === 0);
|
|
115
|
+
return end ? { close: end.index, inner: text.slice(open + 1, end.index) } : undefined;
|
|
116
|
+
};
|
|
117
|
+
var topLevel = (text) => {
|
|
118
|
+
const commas = unquoted(text, 0).filter((mark) => mark.character === "," && mark.depth === 0).map((mark) => mark.index);
|
|
119
|
+
const bounds = [-1, ...commas, text.length];
|
|
120
|
+
return bounds.slice(1).map((bound, position) => text.slice((bounds[position] ?? -1) + 1, bound).trim()).filter((part) => part !== "");
|
|
121
|
+
};
|
|
122
|
+
var unquote = (name) => {
|
|
123
|
+
const trimmed = name.trim();
|
|
124
|
+
const first = trimmed[0] ?? "";
|
|
125
|
+
if (!(first in CLOSERS))
|
|
126
|
+
return trimmed;
|
|
127
|
+
const close = CLOSERS[first] ?? "";
|
|
128
|
+
return trimmed.slice(1, -1).replaceAll(close + close, close);
|
|
129
|
+
};
|
|
130
|
+
var leadingName = (definition) => {
|
|
131
|
+
const first = definition[0] ?? "";
|
|
132
|
+
if (first in CLOSERS)
|
|
133
|
+
return definition.slice(0, pastQuote(definition, 0));
|
|
134
|
+
return /^[^\s(]+/u.exec(definition)?.[0] ?? "";
|
|
135
|
+
};
|
|
136
|
+
var afterKeyword = (text, keyword) => {
|
|
137
|
+
const match = keyword.exec(text);
|
|
138
|
+
if (!match)
|
|
139
|
+
return;
|
|
140
|
+
const open = text.indexOf("(", match.index + match[0].length - 1);
|
|
141
|
+
return open === -1 ? undefined : bracketed(text, open);
|
|
142
|
+
};
|
|
143
|
+
var checksIn = (definition) => {
|
|
144
|
+
const checks = [];
|
|
145
|
+
const pattern = /(?:\bCONSTRAINT\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\S+)\s+)?\bCHECK\s*\(/giu;
|
|
146
|
+
let match = pattern.exec(definition);
|
|
147
|
+
while (match) {
|
|
148
|
+
const open = match.index + match[0].length - 1;
|
|
149
|
+
const found = bracketed(definition, open);
|
|
150
|
+
if (found)
|
|
151
|
+
checks.push({
|
|
152
|
+
expression: found.inner.trim(),
|
|
153
|
+
...match[1] ? { name: unquote(match[1]) } : {}
|
|
154
|
+
});
|
|
155
|
+
pattern.lastIndex = (found?.close ?? open) + 1;
|
|
156
|
+
match = pattern.exec(definition);
|
|
157
|
+
}
|
|
158
|
+
return checks;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// src/sqlite/index.ts
|
|
162
|
+
var text = (value) => {
|
|
163
|
+
if (value === null || value === undefined)
|
|
164
|
+
return;
|
|
165
|
+
return typeof value === "string" ? value : `${value}`;
|
|
166
|
+
};
|
|
167
|
+
var integer = (value) => typeof value === "number" ? value : Number.parseInt(text(value) ?? "0", 10);
|
|
168
|
+
var VIEW_COLOR = "#64748b";
|
|
169
|
+
var ACTIONS = {
|
|
170
|
+
CASCADE: "cascade",
|
|
171
|
+
"NO ACTION": undefined,
|
|
172
|
+
RESTRICT: "restrict",
|
|
173
|
+
"SET DEFAULT": "set default",
|
|
174
|
+
"SET NULL": "set null"
|
|
175
|
+
};
|
|
176
|
+
var NUMBER = /^-?\d+(\.\d+)?$/u;
|
|
177
|
+
var QUOTED = /^'((?:[^']|'')*)'$/u;
|
|
178
|
+
var defaultOf = (raw) => {
|
|
179
|
+
if (/^null$/iu.test(raw))
|
|
180
|
+
return { kind: "null" };
|
|
181
|
+
if (/^(true|false)$/iu.test(raw))
|
|
182
|
+
return {
|
|
183
|
+
kind: "boolean",
|
|
184
|
+
value: raw.toLowerCase() === "true"
|
|
185
|
+
};
|
|
186
|
+
if (NUMBER.test(raw) && Number.isSafeInteger(Math.trunc(Number.parseFloat(raw))))
|
|
187
|
+
return {
|
|
188
|
+
kind: "number",
|
|
189
|
+
value: Number.parseFloat(raw)
|
|
190
|
+
};
|
|
191
|
+
const [, quoted] = QUOTED.exec(raw) ?? [];
|
|
192
|
+
if (quoted !== undefined)
|
|
193
|
+
return {
|
|
194
|
+
kind: "string",
|
|
195
|
+
value: quoted.replaceAll("''", "'")
|
|
196
|
+
};
|
|
197
|
+
const inner = raw.startsWith("(") && raw.endsWith(")") ? raw.slice(1, -1) : raw;
|
|
198
|
+
return { kind: "expression", value: inner };
|
|
199
|
+
};
|
|
200
|
+
var definitionsOf = (sql) => {
|
|
201
|
+
const open = sql.indexOf("(");
|
|
202
|
+
const body = open === -1 ? undefined : bracketed(sql, open);
|
|
203
|
+
const parts = body ? topLevel(body.inner) : [];
|
|
204
|
+
const constraint = /^(CONSTRAINT|PRIMARY|UNIQUE|CHECK|FOREIGN)\b/iu;
|
|
205
|
+
return {
|
|
206
|
+
body: body?.inner ?? "",
|
|
207
|
+
columns: new Map(parts.filter((part) => !constraint.test(part)).map((part) => [unquote(leadingName(part)).toLowerCase(), part])),
|
|
208
|
+
suffix: body ? sql.slice(body.close + 1) : ""
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
var collationOf = (definition) => {
|
|
212
|
+
const name = /\bCOLLATE\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/iu.exec(definition)?.[1];
|
|
213
|
+
return name && name.toUpperCase() !== "BINARY" ? unquote(name) : undefined;
|
|
214
|
+
};
|
|
215
|
+
var columnInfo = (row) => {
|
|
216
|
+
const info = {
|
|
217
|
+
cid: integer(row.cid),
|
|
218
|
+
...text(row.dflt_value) === undefined ? {} : { default: text(row.dflt_value) ?? "" },
|
|
219
|
+
hidden: integer(row.hidden),
|
|
220
|
+
name: text(row.name) ?? "",
|
|
221
|
+
notNull: integer(row.notnull) === 1,
|
|
222
|
+
pk: integer(row.pk),
|
|
223
|
+
type: text(row.type) ?? ""
|
|
224
|
+
};
|
|
225
|
+
return info;
|
|
226
|
+
};
|
|
227
|
+
var GENERATED = { 2: "virtual", 3: "stored" };
|
|
228
|
+
var columnOf = (info, definition, rowidKey) => {
|
|
229
|
+
const generated = GENERATED[info.hidden];
|
|
230
|
+
const expression = generated ? afterKeyword(definition, /\bAS\s*\(/iu)?.inner.trim() : undefined;
|
|
231
|
+
const collation = collationOf(definition);
|
|
232
|
+
const metadata = collation ? { collation } : {};
|
|
233
|
+
const notes = [
|
|
234
|
+
generated ? `Generated always as (${expression ?? "\u2026"}), ${generated}` : undefined,
|
|
235
|
+
/\bAUTOINCREMENT\b/iu.test(definition) ? "AUTOINCREMENT: ids are never reused" : undefined
|
|
236
|
+
].filter((line) => line !== undefined);
|
|
237
|
+
const column = {
|
|
238
|
+
name: info.name,
|
|
239
|
+
type: info.type === "" ? "any" : info.type.toLowerCase(),
|
|
240
|
+
...info.pk > 0 && rowidKey ? { increment: true, pk: true } : {},
|
|
241
|
+
...info.pk > 0 && !rowidKey && !generated ? {} : {},
|
|
242
|
+
...info.notNull && info.pk === 0 ? { notNull: true } : {},
|
|
243
|
+
...info.default !== undefined && !generated ? { default: defaultOf(info.default) } : {},
|
|
244
|
+
...Object.keys(metadata).length > 0 ? { metadata } : {},
|
|
245
|
+
...notes.length > 0 ? { note: notes.join(`
|
|
246
|
+
`) } : {}
|
|
247
|
+
};
|
|
248
|
+
return column;
|
|
249
|
+
};
|
|
250
|
+
var NO_PARTS = { parts: [] };
|
|
251
|
+
var indexPartsText = (sql) => {
|
|
252
|
+
if (!sql)
|
|
253
|
+
return NO_PARTS;
|
|
254
|
+
const target = /\bON\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\S+?)\s*\(/iu.exec(sql);
|
|
255
|
+
if (!target)
|
|
256
|
+
return NO_PARTS;
|
|
257
|
+
const found = bracketed(sql, target.index + target[0].length - 1);
|
|
258
|
+
const where = found ? /\bWHERE\s+([\s\S]+)$/iu.exec(sql.slice(found.close + 1))?.[1]?.trim() : undefined;
|
|
259
|
+
return { parts: found ? topLevel(found.inner) : [], where };
|
|
260
|
+
};
|
|
261
|
+
var indexesOf = async (read, table, sqlOf, columnCollation) => {
|
|
262
|
+
const list = await read("select * from pragma_index_list(?)", [table]);
|
|
263
|
+
const indexes = await Promise.all(list.filter((row) => text(row.origin) !== "pk").map(async (row) => {
|
|
264
|
+
const name = text(row.name) ?? "";
|
|
265
|
+
const parts = (await read("select * from pragma_index_xinfo(?)", [name])).filter((part) => integer(part.key) === 1);
|
|
266
|
+
const written = indexPartsText(sqlOf(name));
|
|
267
|
+
const collations = parts.filter((part) => {
|
|
268
|
+
const column = text(part.name);
|
|
269
|
+
const collation = text(part.coll)?.toUpperCase();
|
|
270
|
+
return column !== undefined && collation !== undefined && collation !== columnCollation(column);
|
|
271
|
+
}).map((part) => `${text(part.name)} ${text(part.coll)}`);
|
|
272
|
+
const index = {
|
|
273
|
+
parts: parts.map((part, position) => {
|
|
274
|
+
const desc = integer(part.desc) === 1 ? { desc: true } : {};
|
|
275
|
+
const column = text(part.name);
|
|
276
|
+
const entry = integer(part.cid) >= 0 && column ? { column, kind: "column", ...desc } : {
|
|
277
|
+
expression: (written.parts[position] ?? "").replace(/\s+(ASC|DESC)$/iu, ""),
|
|
278
|
+
kind: "expression",
|
|
279
|
+
...desc
|
|
280
|
+
};
|
|
281
|
+
return entry;
|
|
282
|
+
}),
|
|
283
|
+
...integer(row.unique) === 1 ? { unique: true } : {},
|
|
284
|
+
...name.startsWith("sqlite_autoindex_") ? {} : { name },
|
|
285
|
+
...(() => {
|
|
286
|
+
const lines = [
|
|
287
|
+
written.where && integer(row.partial) === 1 ? `Where ${written.where}` : undefined,
|
|
288
|
+
collations.length > 0 ? `Collation: ${collations.join(", ")}` : undefined
|
|
289
|
+
].filter((line) => line !== undefined);
|
|
290
|
+
return lines.length > 0 ? { note: lines.join(`
|
|
291
|
+
`) } : {};
|
|
292
|
+
})()
|
|
293
|
+
};
|
|
294
|
+
return { index, origin: text(row.origin) ?? "c" };
|
|
295
|
+
}));
|
|
296
|
+
return indexes;
|
|
297
|
+
};
|
|
298
|
+
var foreignKeysOf = async (read, table) => {
|
|
299
|
+
const rows = await read("select * from pragma_foreign_key_list(?)", [
|
|
300
|
+
table.name
|
|
301
|
+
]);
|
|
302
|
+
const groups = new Map;
|
|
303
|
+
rows.forEach((row) => groups.set(integer(row.id), [
|
|
304
|
+
...groups.get(integer(row.id)) ?? [],
|
|
305
|
+
row
|
|
306
|
+
]));
|
|
307
|
+
return [...groups.values()].map((group) => {
|
|
308
|
+
const [first] = group;
|
|
309
|
+
const columns = group.map((row) => text(row.from) ?? "");
|
|
310
|
+
const onDelete = ACTIONS[text(first?.on_delete) ?? ""];
|
|
311
|
+
const onUpdate = ACTIONS[text(first?.on_update) ?? ""];
|
|
312
|
+
const ref = {
|
|
313
|
+
from: { columns, table: table.name },
|
|
314
|
+
...onDelete ? { onDelete } : {},
|
|
315
|
+
...onUpdate ? { onUpdate } : {},
|
|
316
|
+
relation: isUniqueSet(table, columns) ? "-" : ">",
|
|
317
|
+
to: {
|
|
318
|
+
columns: group.map((row) => text(row.to) ?? ""),
|
|
319
|
+
table: text(first?.table) ?? ""
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
return ref;
|
|
323
|
+
});
|
|
324
|
+
};
|
|
325
|
+
var quoteIdent = (name) => `"${name.replaceAll('"', '""')}"`;
|
|
326
|
+
var placeIndex = (table, index, origin) => {
|
|
327
|
+
const [part] = index.parts;
|
|
328
|
+
const single = index.parts.length === 1 && part?.kind === "column" && origin === "u";
|
|
329
|
+
const column = single ? table.columns.find((own) => own.name === part.column) : undefined;
|
|
330
|
+
if (column)
|
|
331
|
+
column.unique = true;
|
|
332
|
+
else
|
|
333
|
+
table.indexes.push(index);
|
|
334
|
+
};
|
|
335
|
+
var tableOf = async (read, entry, context) => {
|
|
336
|
+
const name = text(entry.name) ?? "";
|
|
337
|
+
const view = text(entry.type) === "view";
|
|
338
|
+
const sql = text(entry.sql) ?? "";
|
|
339
|
+
const definitions = definitionsOf(sql);
|
|
340
|
+
const info = (await read("select * from pragma_table_xinfo(?)", [name])).map(columnInfo);
|
|
341
|
+
const keyed = info.filter((column) => column.pk > 0).sort((left, right) => left.pk - right.pk);
|
|
342
|
+
const [onlyKey] = keyed;
|
|
343
|
+
const rowidKey = keyed.length === 1 && onlyKey?.type.toUpperCase() === "INTEGER";
|
|
344
|
+
const tableEntry = context.listed.find((row) => row.name === name);
|
|
345
|
+
const rows = context.statistics && !view ? integer((await read(`select count(*) as total from ${quoteIdent(name)}`))[0]?.total) : undefined;
|
|
346
|
+
const metadata = {
|
|
347
|
+
...integer(tableEntry?.strict) === 1 ? { strict: true } : {},
|
|
348
|
+
...integer(tableEntry?.wr) === 1 ? { without_rowid: true } : {},
|
|
349
|
+
...rows === undefined ? {} : { rows }
|
|
350
|
+
};
|
|
351
|
+
const own = context.triggers.filter((row) => row.tbl_name === name);
|
|
352
|
+
const noteLines = [
|
|
353
|
+
view ? `View:
|
|
354
|
+
${sql.replace(/^CREATE\s+(TEMP\s+|TEMPORARY\s+)?VIEW\s+\S+\s+AS\s+/iu, "")}` : undefined,
|
|
355
|
+
...own.map((row) => `Trigger ${(text(row.sql) ?? "").replace(/^CREATE\s+(TEMP\s+|TEMPORARY\s+)?TRIGGER\s+(IF NOT EXISTS\s+)?/iu, "")}`)
|
|
356
|
+
].filter((line) => line !== undefined);
|
|
357
|
+
const table = {
|
|
358
|
+
checks: view ? [] : checksIn(definitions.body),
|
|
359
|
+
columns: info.map((column) => columnOf(column, definitions.columns.get(column.name.toLowerCase()) ?? "", rowidKey && column.pk > 0)),
|
|
360
|
+
...view ? { headerColor: VIEW_COLOR } : {},
|
|
361
|
+
indexes: [],
|
|
362
|
+
...Object.keys(metadata).length > 0 ? { metadata } : {},
|
|
363
|
+
name,
|
|
364
|
+
...noteLines.length > 0 ? { note: noteLines.join(`
|
|
365
|
+
`) } : {}
|
|
366
|
+
};
|
|
367
|
+
if (keyed.length === 1 && !rowidKey)
|
|
368
|
+
table.columns.forEach((column) => {
|
|
369
|
+
if (column.name === onlyKey?.name)
|
|
370
|
+
column.pk = true;
|
|
371
|
+
});
|
|
372
|
+
if (keyed.length > 1)
|
|
373
|
+
table.indexes.push({
|
|
374
|
+
parts: keyed.map((column) => ({
|
|
375
|
+
column: column.name,
|
|
376
|
+
kind: "column"
|
|
377
|
+
})),
|
|
378
|
+
pk: true
|
|
379
|
+
});
|
|
380
|
+
if (view)
|
|
381
|
+
return table;
|
|
382
|
+
const indexes = await indexesOf(read, name, context.sqlOf, (column) => {
|
|
383
|
+
const collation = table.columns.find((candidate) => candidate.name === column)?.metadata?.collation;
|
|
384
|
+
return typeof collation === "string" ? collation.toUpperCase() : "BINARY";
|
|
385
|
+
});
|
|
386
|
+
indexes.forEach(({ index, origin }) => placeIndex(table, index, origin));
|
|
387
|
+
return table;
|
|
388
|
+
};
|
|
389
|
+
var fromSqlite = async (query, options = {}) => {
|
|
390
|
+
const read = async (statement, params = []) => query(statement, params);
|
|
391
|
+
const schema = await read(`select type, name, tbl_name, sql from sqlite_schema where name not like 'sqlite_%' order by rowid`);
|
|
392
|
+
const sqlOf = (name) => text(schema.find((row) => row.name === name)?.sql);
|
|
393
|
+
const listed = (await read("select * from pragma_table_list")).filter((row) => text(row.schema) === "main" && !(text(row.name) ?? "").startsWith("sqlite_"));
|
|
394
|
+
const model = emptyModel({
|
|
395
|
+
databaseType: "SQLite",
|
|
396
|
+
...options.project
|
|
397
|
+
});
|
|
398
|
+
const ordered = schema.filter((row) => text(row.type) === "table" || text(row.type) === "view");
|
|
399
|
+
const context = {
|
|
400
|
+
listed,
|
|
401
|
+
sqlOf,
|
|
402
|
+
statistics: options.statistics === true,
|
|
403
|
+
triggers: schema.filter((row) => text(row.type) === "trigger")
|
|
404
|
+
};
|
|
405
|
+
model.tables.push(...await Promise.all(ordered.map((entry) => tableOf(read, entry, context))));
|
|
406
|
+
const tables = model.tables.filter((table) => !table.headerColor);
|
|
407
|
+
const refs = await Promise.all(tables.map((table) => foreignKeysOf(read, table)));
|
|
408
|
+
model.refs.push(...refs.flat());
|
|
409
|
+
model.tables.filter((table) => table.headerColor).forEach((view) => {
|
|
410
|
+
const sql = sqlOf(view.name) ?? "";
|
|
411
|
+
tables.filter((table) => new RegExp(`(^|[^\\w"\`])["\`[]?${table.name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}["\`\\]]?($|[^\\w"\`])`, "iu").test(sql.replace(/^CREATE\s+\S+\s+\S+/iu, ""))).forEach((table) => model.deps.push({
|
|
412
|
+
downstream: { table: view.name },
|
|
413
|
+
upstream: { table: table.name }
|
|
414
|
+
}));
|
|
415
|
+
});
|
|
416
|
+
return model;
|
|
417
|
+
};
|
|
418
|
+
export {
|
|
419
|
+
fromSqlite
|
|
420
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The text inside the bracket opening at `open`, and where it closes. */
|
|
2
|
+
export declare const bracketed: (text: string, open: number) => {
|
|
3
|
+
close: number;
|
|
4
|
+
inner: string;
|
|
5
|
+
} | undefined;
|
|
6
|
+
/** Splits at commas that aren't inside brackets or quotes. */
|
|
7
|
+
export declare const topLevel: (text: string) => string[];
|
|
8
|
+
/** An identifier as written, its quotes taken off. */
|
|
9
|
+
export declare const unquote: (name: string) => string;
|
|
10
|
+
/** The first word of a definition (a column's name), quotes and all. */
|
|
11
|
+
export declare const leadingName: (definition: string) => string;
|
|
12
|
+
/** The expression in brackets that follows a keyword (CHECK, AS), or
|
|
13
|
+
* undefined when the keyword isn't there. */
|
|
14
|
+
export declare const afterKeyword: (text: string, keyword: RegExp) => {
|
|
15
|
+
close: number;
|
|
16
|
+
inner: string;
|
|
17
|
+
} | undefined;
|
|
18
|
+
/** Every CHECK in a definition list, with the constraint name before it. */
|
|
19
|
+
export declare const checksIn: (definition: string) => {
|
|
20
|
+
expression: string;
|
|
21
|
+
name?: string;
|
|
22
|
+
}[];
|
package/package.json
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
"bugs": {
|
|
7
7
|
"url": "https://github.com/absolutejs/dbml/issues"
|
|
8
8
|
},
|
|
9
|
-
"description": "Turn any Drizzle schema, or a live Postgres database, into DBML: tables, enums, keys, indexes, checks, relations and notes, with one model behind both.",
|
|
9
|
+
"description": "Turn any Drizzle schema, or a live Postgres, MySQL, MariaDB or SQLite database, into DBML: tables, enums, keys, indexes, checks, relations and notes, with one model behind both.",
|
|
10
10
|
"devDependencies": {
|
|
11
11
|
"@absolutejs/changelog": "^0.6.0",
|
|
12
12
|
"@dbml/core": "12.1.0",
|
|
@@ -34,10 +34,20 @@
|
|
|
34
34
|
"import": "./dist/drizzle/index.js",
|
|
35
35
|
"types": "./dist/drizzle/index.d.ts"
|
|
36
36
|
},
|
|
37
|
+
"./mysql": {
|
|
38
|
+
"default": "./dist/mysql/index.js",
|
|
39
|
+
"import": "./dist/mysql/index.js",
|
|
40
|
+
"types": "./dist/mysql/index.d.ts"
|
|
41
|
+
},
|
|
37
42
|
"./postgres": {
|
|
38
43
|
"default": "./dist/postgres/index.js",
|
|
39
44
|
"import": "./dist/postgres/index.js",
|
|
40
45
|
"types": "./dist/postgres/index.d.ts"
|
|
46
|
+
},
|
|
47
|
+
"./sqlite": {
|
|
48
|
+
"default": "./dist/sqlite/index.js",
|
|
49
|
+
"import": "./dist/sqlite/index.js",
|
|
50
|
+
"types": "./dist/sqlite/index.d.ts"
|
|
41
51
|
}
|
|
42
52
|
},
|
|
43
53
|
"files": [
|
|
@@ -53,6 +63,9 @@
|
|
|
53
63
|
"drizzle",
|
|
54
64
|
"drizzle-orm",
|
|
55
65
|
"postgres",
|
|
66
|
+
"mysql",
|
|
67
|
+
"mariadb",
|
|
68
|
+
"sqlite",
|
|
56
69
|
"schema",
|
|
57
70
|
"erd",
|
|
58
71
|
"diagram"
|
|
@@ -76,7 +89,7 @@
|
|
|
76
89
|
"url": "https://github.com/absolutejs/dbml.git"
|
|
77
90
|
},
|
|
78
91
|
"scripts": {
|
|
79
|
-
"build": "rm -rf dist && bun build src/index.ts src/drizzle/index.ts src/postgres/index.ts src/cli.ts --outdir dist --root ./src --target=bun --external drizzle-orm && tsc --emitDeclarationOnly --project tsconfig.build.json",
|
|
92
|
+
"build": "rm -rf dist && bun build src/index.ts src/drizzle/index.ts src/postgres/index.ts src/mysql/index.ts src/sqlite/index.ts src/cli.ts --outdir dist --root ./src --target=bun --external drizzle-orm && tsc --emitDeclarationOnly --project tsconfig.build.json",
|
|
80
93
|
"check:package": "bun run typecheck && bun run lint && bun run build && bun run test && absolute-changelog check",
|
|
81
94
|
"format": "prettier --write \"./**/*.{ts,json,mjs,md}\"",
|
|
82
95
|
"lint": "eslint ./",
|
|
@@ -86,5 +99,5 @@
|
|
|
86
99
|
},
|
|
87
100
|
"type": "module",
|
|
88
101
|
"types": "./dist/index.d.ts",
|
|
89
|
-
"version": "0.
|
|
102
|
+
"version": "0.3.0"
|
|
90
103
|
}
|