@absolutejs/dbml 0.1.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 +20 -0
- package/README.md +45 -7
- package/changelog.json +59 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +1313 -129
- package/dist/drizzle/index.js +96 -8
- package/dist/drizzle/relations.d.ts +1 -0
- package/dist/index.js +105 -10
- package/dist/model.d.ts +16 -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 +8 -0
- package/dist/postgres/index.js +413 -34
- 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/cli.js
CHANGED
|
@@ -8,6 +8,7 @@ import process from "process";
|
|
|
8
8
|
import { pathToFileURL } from "url";
|
|
9
9
|
import { parseArgs } from "util";
|
|
10
10
|
var {SQL: SQL3 } = globalThis.Bun;
|
|
11
|
+
import { Database } from "bun:sqlite";
|
|
11
12
|
|
|
12
13
|
// src/drizzle/index.ts
|
|
13
14
|
import { is as is4 } from "drizzle-orm";
|
|
@@ -25,6 +26,70 @@ var emptyModel = (project) => ({
|
|
|
25
26
|
tableGroups: [],
|
|
26
27
|
tables: []
|
|
27
28
|
});
|
|
29
|
+
var unqualified = (place, schema) => {
|
|
30
|
+
if (place.schema !== schema)
|
|
31
|
+
return place;
|
|
32
|
+
const { schema: dropped, ...rest } = place;
|
|
33
|
+
return rest;
|
|
34
|
+
};
|
|
35
|
+
var withDefaultSchema = (model, schema) => {
|
|
36
|
+
const result = {
|
|
37
|
+
...model,
|
|
38
|
+
deps: model.deps.map((dep) => ({
|
|
39
|
+
...dep,
|
|
40
|
+
downstream: unqualified(dep.downstream, schema),
|
|
41
|
+
upstream: unqualified(dep.upstream, schema)
|
|
42
|
+
})),
|
|
43
|
+
enums: model.enums.map((entry) => unqualified(entry, schema)),
|
|
44
|
+
records: model.records.map((records) => unqualified(records, schema)),
|
|
45
|
+
refs: model.refs.map((ref) => ({
|
|
46
|
+
...ref,
|
|
47
|
+
from: unqualified(ref.from, schema),
|
|
48
|
+
to: unqualified(ref.to, schema)
|
|
49
|
+
})),
|
|
50
|
+
tableGroups: model.tableGroups.map((group) => ({
|
|
51
|
+
...group,
|
|
52
|
+
tables: group.tables.map((entry) => unqualified(entry, schema))
|
|
53
|
+
})),
|
|
54
|
+
tables: model.tables.map((table) => ({
|
|
55
|
+
...unqualified(table, schema),
|
|
56
|
+
columns: table.columns.map((column) => {
|
|
57
|
+
if (column.typeSchema !== schema)
|
|
58
|
+
return column;
|
|
59
|
+
const { typeSchema: dropped, ...rest } = column;
|
|
60
|
+
return rest;
|
|
61
|
+
})
|
|
62
|
+
}))
|
|
63
|
+
};
|
|
64
|
+
return result;
|
|
65
|
+
};
|
|
66
|
+
var groupBySchema = (tables, defaultSchema = "public") => {
|
|
67
|
+
const byName = new Map;
|
|
68
|
+
tables.forEach((table) => {
|
|
69
|
+
const name = table.schema ?? defaultSchema;
|
|
70
|
+
byName.set(name, [
|
|
71
|
+
...byName.get(name) ?? [],
|
|
72
|
+
{
|
|
73
|
+
...table.schema ? { schema: table.schema } : {},
|
|
74
|
+
table: table.name
|
|
75
|
+
}
|
|
76
|
+
]);
|
|
77
|
+
});
|
|
78
|
+
return [...byName].map(([name, members]) => {
|
|
79
|
+
const group = { name, tables: members };
|
|
80
|
+
return group;
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
var sortedColumns = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
|
|
84
|
+
var coversAll = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
|
|
85
|
+
var isUniqueSet = (table, columns) => {
|
|
86
|
+
const [only] = columns;
|
|
87
|
+
const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
|
|
88
|
+
if (single?.pk === true || single?.unique === true)
|
|
89
|
+
return true;
|
|
90
|
+
const wanted = [...columns].sort().join("\x00");
|
|
91
|
+
return table.indexes.some((index) => coversAll(index) && index.parts.every((part) => part.kind === "column") && sortedColumns(index) === wanted);
|
|
92
|
+
};
|
|
28
93
|
|
|
29
94
|
// src/drizzle/dialects.ts
|
|
30
95
|
import { is, SQL, sql } from "drizzle-orm";
|
|
@@ -112,6 +177,20 @@ var isRecord = (value) => typeof value === "object" && value !== null;
|
|
|
112
177
|
var isTableRelations = (entry) => isRecord(entry) && isRecord(entry.relations) && ("table" in entry);
|
|
113
178
|
var isRelationsV2 = (value) => isRecord(value) && !is2(value, Relations) && Object.keys(value).length > 0 && Object.values(value).every(isTableRelations);
|
|
114
179
|
var throughOf = (relation) => ("throughTable" in relation) && isRecord(relation.throughTable) ? relation.throughTable : undefined;
|
|
180
|
+
var filterOf = (relation) => ("where" in relation) && relation.where !== undefined ? { where: relation.where } : {};
|
|
181
|
+
var declaredMany = (field, relation) => {
|
|
182
|
+
if ("isReversed" in relation && relation.isReversed === true)
|
|
183
|
+
return;
|
|
184
|
+
const link = {
|
|
185
|
+
field,
|
|
186
|
+
from: relation.targetColumns,
|
|
187
|
+
kind: "one",
|
|
188
|
+
owner: relation.sourceTable,
|
|
189
|
+
target: relation.sourceColumns,
|
|
190
|
+
...filterOf(relation)
|
|
191
|
+
};
|
|
192
|
+
return link;
|
|
193
|
+
};
|
|
115
194
|
var v2Link = (field, relation) => {
|
|
116
195
|
const from = relation.sourceColumns;
|
|
117
196
|
const target = relation.targetColumns;
|
|
@@ -119,10 +198,19 @@ var v2Link = (field, relation) => {
|
|
|
119
198
|
return;
|
|
120
199
|
const owner = relation.sourceTable;
|
|
121
200
|
if (is2(relation, One)) {
|
|
122
|
-
const link = {
|
|
201
|
+
const link = {
|
|
202
|
+
field,
|
|
203
|
+
from,
|
|
204
|
+
kind: "one",
|
|
205
|
+
owner,
|
|
206
|
+
target,
|
|
207
|
+
...filterOf(relation)
|
|
208
|
+
};
|
|
123
209
|
return link;
|
|
124
210
|
}
|
|
125
211
|
const through = throughOf(relation);
|
|
212
|
+
if (is2(relation, Many) && !through)
|
|
213
|
+
return declaredMany(field, relation);
|
|
126
214
|
if (!is2(relation, Many) || !through)
|
|
127
215
|
return;
|
|
128
216
|
const link = {
|
|
@@ -195,7 +283,8 @@ var applyRelations = (options) => {
|
|
|
195
283
|
const target = endpointOf(options.lookup, link.target);
|
|
196
284
|
if (!from || !target)
|
|
197
285
|
continue;
|
|
198
|
-
const
|
|
286
|
+
const filter = link.where === undefined ? "" : ` where ${JSON.stringify(link.where)}`;
|
|
287
|
+
const field = `${options.lookup(link.owner)?.table ?? from.table}.${link.field}${filter}`;
|
|
199
288
|
const key = refKey({ from, to: target });
|
|
200
289
|
const existing = byKey.get(key);
|
|
201
290
|
if (existing)
|
|
@@ -457,15 +546,15 @@ var tableOf = (config) => {
|
|
|
457
546
|
table
|
|
458
547
|
};
|
|
459
548
|
};
|
|
460
|
-
var
|
|
461
|
-
var
|
|
462
|
-
var
|
|
549
|
+
var sortedColumns2 = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
|
|
550
|
+
var coversAll2 = (index) => index.pk === true || index.unique === true && index.note?.startsWith("Where") !== true;
|
|
551
|
+
var isUniqueSet2 = (table, columns) => {
|
|
463
552
|
const [only] = columns;
|
|
464
553
|
const single = columns.length === 1 ? table.columns.find((entry) => entry.name === only) : undefined;
|
|
465
554
|
if (single?.pk === true || single?.unique === true)
|
|
466
555
|
return true;
|
|
467
556
|
const wanted = [...columns].sort().join("\x00");
|
|
468
|
-
return table.indexes.some((index) =>
|
|
557
|
+
return table.indexes.some((index) => coversAll2(index) && index.parts.every((part) => part.kind === "column") && sortedColumns2(index) === wanted);
|
|
469
558
|
};
|
|
470
559
|
|
|
471
560
|
// src/drizzle/views.ts
|
|
@@ -628,7 +717,7 @@ var foreignKeyRefs = (entry, lookup, tables) => entry.config.foreignKeys.flatMap
|
|
|
628
717
|
...reference.name ? { name: reference.name } : {},
|
|
629
718
|
...onDelete ? { onDelete } : {},
|
|
630
719
|
...onUpdate ? { onUpdate } : {},
|
|
631
|
-
relation: table &&
|
|
720
|
+
relation: table && isUniqueSet2(table, columns) ? "-" : ">",
|
|
632
721
|
to: {
|
|
633
722
|
...target,
|
|
634
723
|
columns: reference.foreignColumns.map((column) => column.name)
|
|
@@ -755,7 +844,7 @@ var fromDrizzle = (schema, options = {}) => {
|
|
|
755
844
|
refs: model.refs,
|
|
756
845
|
isUnique: (end) => {
|
|
757
846
|
const table = byPlace.get(keyOf({ name: end.table, schema: end.schema }));
|
|
758
|
-
return table ?
|
|
847
|
+
return table ? isUniqueSet2(table, end.columns) : false;
|
|
759
848
|
}
|
|
760
849
|
});
|
|
761
850
|
addViews(model, found, lookup, (table) => byObject.get(table)?.columns.map((column) => column.name) ?? []);
|
|
@@ -765,9 +854,476 @@ var fromDrizzle = (schema, options = {}) => {
|
|
|
765
854
|
return model;
|
|
766
855
|
};
|
|
767
856
|
|
|
857
|
+
// src/mysql/index.ts
|
|
858
|
+
var lowered = (row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key.toLowerCase(), value]));
|
|
859
|
+
var text = (value) => {
|
|
860
|
+
if (value === null || value === undefined)
|
|
861
|
+
return;
|
|
862
|
+
if (value instanceof Uint8Array)
|
|
863
|
+
return new TextDecoder().decode(value);
|
|
864
|
+
return typeof value === "string" ? value : `${value}`;
|
|
865
|
+
};
|
|
866
|
+
var integer = (value) => Number.parseInt(text(value) ?? "0", 10);
|
|
867
|
+
var VIEW_COLOR2 = "#64748b";
|
|
868
|
+
var ACTIONS2 = {
|
|
869
|
+
CASCADE: "cascade",
|
|
870
|
+
"NO ACTION": undefined,
|
|
871
|
+
RESTRICT: undefined,
|
|
872
|
+
"SET DEFAULT": "set default",
|
|
873
|
+
"SET NULL": "set null"
|
|
874
|
+
};
|
|
875
|
+
var NUMBER = /^-?\d+(\.\d+)?$/u;
|
|
876
|
+
var actionOf2 = (rule) => ACTIONS2[rule ?? ""];
|
|
877
|
+
var defaultOf2 = (raw, extra, mariadb) => {
|
|
878
|
+
if (raw === undefined)
|
|
879
|
+
return;
|
|
880
|
+
if (/^NULL$/iu.test(raw))
|
|
881
|
+
return mariadb || extra === "" ? { kind: "null" } : undefined;
|
|
882
|
+
if (/DEFAULT_GENERATED/iu.test(extra) || /^(CURRENT_TIMESTAMP|now\(\))/iu.test(raw))
|
|
883
|
+
return {
|
|
884
|
+
kind: "expression",
|
|
885
|
+
value: raw.replace(/^\((.*)\)$/su, "$1")
|
|
886
|
+
};
|
|
887
|
+
const unquoted = mariadb && /^'.*'$/su.test(raw) ? raw.slice(1, -1).replaceAll("''", "'") : raw;
|
|
888
|
+
if (NUMBER.test(unquoted) && Number.isSafeInteger(Math.trunc(Number.parseFloat(unquoted))))
|
|
889
|
+
return {
|
|
890
|
+
kind: "number",
|
|
891
|
+
value: Number.parseFloat(unquoted)
|
|
892
|
+
};
|
|
893
|
+
if (mariadb && !/^'.*'$/su.test(raw))
|
|
894
|
+
return { kind: "expression", value: raw };
|
|
895
|
+
return { kind: "string", value: unquoted };
|
|
896
|
+
};
|
|
897
|
+
var ENUMISH = /^(enum|set)\((.*)\)$/isu;
|
|
898
|
+
var valuesOf2 = (list) => [...list.matchAll(/'((?:[^']|'')*)'/gu)].map((match) => (match[1] ?? "").replaceAll("''", "'"));
|
|
899
|
+
var columnOf2 = (row, table, context) => {
|
|
900
|
+
const type = text(row.column_type) ?? "";
|
|
901
|
+
const extra = text(row.extra) ?? "";
|
|
902
|
+
const enumish = ENUMISH.exec(type);
|
|
903
|
+
const name = text(row.column_name) ?? "";
|
|
904
|
+
const generated = /\b(VIRTUAL|STORED|PERSISTENT) GENERATED\b/iu.exec(extra)?.[1]?.toLowerCase();
|
|
905
|
+
const fallback = generated ? undefined : defaultOf2(text(row.column_default), extra, context.mariadb);
|
|
906
|
+
const metadata = {
|
|
907
|
+
...text(row.collation_name) && text(row.collation_name) !== text(row.table_collation) ? { collation: text(row.collation_name) ?? "" } : {},
|
|
908
|
+
...text(row.srs_id) ? { srid: integer(row.srs_id) } : {}
|
|
909
|
+
};
|
|
910
|
+
const notes = [
|
|
911
|
+
text(row.column_comment) || undefined,
|
|
912
|
+
generated ? `Generated always as (${text(row.generation_expression) ?? ""}), ${generated}` : undefined,
|
|
913
|
+
/on update/iu.test(extra) ? `Set to ${/on update (.*)$/iu.exec(extra)?.[1] ?? "the current time"} on every update` : undefined,
|
|
914
|
+
/INVISIBLE/iu.test(extra) ? "Invisible: SELECT * leaves it out" : undefined,
|
|
915
|
+
enumish ? `Stored as ${type}` : undefined,
|
|
916
|
+
enumish?.[1]?.toLowerCase() === "set" ? "A set: any number of these values at once" : undefined
|
|
917
|
+
].filter((line) => line !== undefined);
|
|
918
|
+
const enumType = enumish ? {
|
|
919
|
+
name: `${table.name}_${name}`,
|
|
920
|
+
schema: table.schema,
|
|
921
|
+
values: valuesOf2(enumish[2] ?? "").map((value) => ({
|
|
922
|
+
name: value
|
|
923
|
+
}))
|
|
924
|
+
} : undefined;
|
|
925
|
+
const column = {
|
|
926
|
+
name,
|
|
927
|
+
type: enumType ? enumType.name : type,
|
|
928
|
+
...enumType ? { typeSchema: table.schema } : {},
|
|
929
|
+
.../auto_increment/iu.test(extra) ? { increment: true } : {},
|
|
930
|
+
...text(row.is_nullable) === "NO" ? { notNull: true } : {},
|
|
931
|
+
...fallback ? { default: fallback } : {},
|
|
932
|
+
...Object.keys(metadata).length > 0 ? { metadata } : {},
|
|
933
|
+
...notes.length > 0 ? { note: notes.join(`
|
|
934
|
+
`) } : {}
|
|
935
|
+
};
|
|
936
|
+
return { column, enumType };
|
|
937
|
+
};
|
|
938
|
+
var keyOf2 = (schema, table) => `${text(schema)}.${text(table)}`;
|
|
939
|
+
var group = (rows, keyFn) => {
|
|
940
|
+
const groups = new Map;
|
|
941
|
+
rows.forEach((row) => groups.set(keyFn(row), [...groups.get(keyFn(row)) ?? [], row]));
|
|
942
|
+
return groups;
|
|
943
|
+
};
|
|
944
|
+
var indexOf2 = (rows) => {
|
|
945
|
+
const [first] = rows;
|
|
946
|
+
const name = text(first?.index_name) ?? "";
|
|
947
|
+
const sorted = [...rows].sort((left, right) => integer(left.seq_in_index) - integer(right.seq_in_index));
|
|
948
|
+
const prefixes = sorted.filter((row) => text(row.sub_part)).map((row) => `${text(row.column_name)}(${text(row.sub_part)})`);
|
|
949
|
+
const method = text(first?.index_type)?.toLowerCase();
|
|
950
|
+
const notes = [
|
|
951
|
+
text(first?.index_comment) || undefined,
|
|
952
|
+
prefixes.length > 0 ? `Prefix: ${prefixes.join(", ")}` : undefined,
|
|
953
|
+
text(first?.is_visible) === "NO" || text(first?.ignored) === "YES" ? "Invisible: the optimizer ignores it" : undefined
|
|
954
|
+
].filter((line) => line !== undefined);
|
|
955
|
+
const index = {
|
|
956
|
+
parts: sorted.map((row) => {
|
|
957
|
+
const desc = text(row.collation) === "D" ? { desc: true } : {};
|
|
958
|
+
const column = text(row.column_name);
|
|
959
|
+
const part = column ? { column, kind: "column", ...desc } : {
|
|
960
|
+
expression: (text(row.expression) ?? "").replace(/^\((.*)\)$/su, "$1"),
|
|
961
|
+
kind: "expression",
|
|
962
|
+
...desc
|
|
963
|
+
};
|
|
964
|
+
return part;
|
|
965
|
+
}),
|
|
966
|
+
...name === "PRIMARY" ? { pk: true } : { name },
|
|
967
|
+
...integer(first?.non_unique) === 0 && name !== "PRIMARY" ? { unique: true } : {},
|
|
968
|
+
...method && method !== "btree" ? { type: method } : {},
|
|
969
|
+
...notes.length > 0 ? { note: notes.join(`
|
|
970
|
+
`) } : {}
|
|
971
|
+
};
|
|
972
|
+
return index;
|
|
973
|
+
};
|
|
974
|
+
var placeIndex = (table, index) => {
|
|
975
|
+
const [part] = index.parts;
|
|
976
|
+
const plain = index.parts.length === 1 && part?.kind === "column" && index.note === undefined;
|
|
977
|
+
const column = plain && part?.kind === "column" ? table.columns.find((entry) => entry.name === part.column) : undefined;
|
|
978
|
+
if (column && index.pk) {
|
|
979
|
+
column.pk = true;
|
|
980
|
+
delete column.notNull;
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
if (column && index.unique && index.name === column.name) {
|
|
984
|
+
column.unique = true;
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
table.indexes.push(index);
|
|
988
|
+
};
|
|
989
|
+
var tableMetadata = (row, context, grants) => {
|
|
990
|
+
const metadata = {
|
|
991
|
+
...text(row.engine) ? { engine: text(row.engine) ?? "" } : {},
|
|
992
|
+
...text(row.table_collation) ? { collation: text(row.table_collation) ?? "" } : {},
|
|
993
|
+
...text(row.row_format) ? { row_format: text(row.row_format) ?? "" } : {},
|
|
994
|
+
...text(row.create_options) ? { options: text(row.create_options) ?? "" } : {},
|
|
995
|
+
...grants ? { grants } : {},
|
|
996
|
+
...context.statistics && text(row.table_rows) ? { rows: integer(row.table_rows) } : {},
|
|
997
|
+
...context.statistics && text(row.data_length) ? {
|
|
998
|
+
size_bytes: integer(row.data_length) + integer(row.index_length)
|
|
999
|
+
} : {},
|
|
1000
|
+
...context.statistics && text(row.auto_increment) ? { next_id: integer(row.auto_increment) } : {}
|
|
1001
|
+
};
|
|
1002
|
+
return metadata;
|
|
1003
|
+
};
|
|
1004
|
+
var VIEWS = [
|
|
1005
|
+
"tables",
|
|
1006
|
+
"columns",
|
|
1007
|
+
"statistics",
|
|
1008
|
+
"table_constraints",
|
|
1009
|
+
"key_column_usage",
|
|
1010
|
+
"referential_constraints",
|
|
1011
|
+
"check_constraints",
|
|
1012
|
+
"views",
|
|
1013
|
+
"triggers",
|
|
1014
|
+
"routines",
|
|
1015
|
+
"parameters",
|
|
1016
|
+
"partitions",
|
|
1017
|
+
"events",
|
|
1018
|
+
"table_privileges",
|
|
1019
|
+
"view_table_usage"
|
|
1020
|
+
];
|
|
1021
|
+
var SCHEMA_COLUMN = {
|
|
1022
|
+
check_constraints: "constraint_schema",
|
|
1023
|
+
events: "event_schema",
|
|
1024
|
+
parameters: "specific_schema",
|
|
1025
|
+
referential_constraints: "constraint_schema",
|
|
1026
|
+
routines: "routine_schema",
|
|
1027
|
+
table_constraints: "constraint_schema",
|
|
1028
|
+
table_privileges: "table_schema",
|
|
1029
|
+
triggers: "trigger_schema",
|
|
1030
|
+
view_table_usage: "view_schema"
|
|
1031
|
+
};
|
|
1032
|
+
var readCatalog = async (query, schemas) => {
|
|
1033
|
+
const marks = schemas.map(() => "?").join(", ");
|
|
1034
|
+
const entries = await Promise.all(VIEWS.map(async (view) => {
|
|
1035
|
+
const column = SCHEMA_COLUMN[view] ?? "table_schema";
|
|
1036
|
+
const rows = await query(`select * from information_schema.${view} where ${column} in (${marks})`, schemas).catch(() => []);
|
|
1037
|
+
const entry = [view, rows.map(lowered)];
|
|
1038
|
+
return entry;
|
|
1039
|
+
}));
|
|
1040
|
+
const catalog = Object.fromEntries(entries);
|
|
1041
|
+
return catalog;
|
|
1042
|
+
};
|
|
1043
|
+
var triggerLine = (row) => `Trigger ${text(row.trigger_name)} ${text(row.action_timing)} ${text(row.event_manipulation)}: ${(text(row.action_statement) ?? "").replace(/\s+/gu, " ")}`;
|
|
1044
|
+
var partitionLines = (rows) => {
|
|
1045
|
+
const named = rows.filter((row) => text(row.partition_name));
|
|
1046
|
+
const [first] = named;
|
|
1047
|
+
if (!first)
|
|
1048
|
+
return [];
|
|
1049
|
+
return [
|
|
1050
|
+
`Partitioned by ${text(first.partition_method)} (${text(first.partition_expression)})`,
|
|
1051
|
+
...named.map((row) => `Partition ${text(row.partition_name)}${text(row.partition_description) ? `: ${text(row.partition_description)}` : ""}`)
|
|
1052
|
+
];
|
|
1053
|
+
};
|
|
1054
|
+
var routineNote = (catalog) => {
|
|
1055
|
+
const routines = catalog.routines ?? [];
|
|
1056
|
+
if (routines.length === 0)
|
|
1057
|
+
return [];
|
|
1058
|
+
const parameters = group(catalog.parameters ?? [], (row) => keyOf2(row.specific_schema, row.specific_name));
|
|
1059
|
+
const lines = routines.map((row) => {
|
|
1060
|
+
const args = (parameters.get(keyOf2(row.routine_schema, row.specific_name)) ?? []).filter((parameter) => text(parameter.parameter_name)).sort((left, right) => integer(left.ordinal_position) - integer(right.ordinal_position)).map((parameter) => `${text(parameter.parameter_mode) ?? ""} ${text(parameter.parameter_name)} ${text(parameter.dtd_identifier)}`.trim()).join(", ");
|
|
1061
|
+
const kind = text(row.routine_type)?.toLowerCase() ?? "function";
|
|
1062
|
+
const result = kind === "function" ? ` \u2192 ${text(row.dtd_identifier)}` : "";
|
|
1063
|
+
return `${text(row.routine_name)}(${args})${result}, ${kind}`;
|
|
1064
|
+
});
|
|
1065
|
+
const note = {
|
|
1066
|
+
content: `Functions and procedures
|
|
1067
|
+
${lines.join(`
|
|
1068
|
+
`)}`,
|
|
1069
|
+
name: "functions"
|
|
1070
|
+
};
|
|
1071
|
+
return [note];
|
|
1072
|
+
};
|
|
1073
|
+
var eventNote = (catalog) => {
|
|
1074
|
+
const events = catalog.events ?? [];
|
|
1075
|
+
if (events.length === 0)
|
|
1076
|
+
return [];
|
|
1077
|
+
const note = {
|
|
1078
|
+
content: `Scheduled events
|
|
1079
|
+
${events.map((row) => `${text(row.event_name)}: ${text(row.interval_value) ? `every ${text(row.interval_value)} ${text(row.interval_field)}` : `at ${text(row.execute_at)}`}, ${text(row.status)?.toLowerCase()}`).join(`
|
|
1080
|
+
`)}`,
|
|
1081
|
+
name: "events"
|
|
1082
|
+
};
|
|
1083
|
+
return [note];
|
|
1084
|
+
};
|
|
1085
|
+
var grantsOf = (catalog) => group(catalog.table_privileges ?? [], (row) => keyOf2(row.table_schema, row.table_name));
|
|
1086
|
+
var checksOf = (catalog) => {
|
|
1087
|
+
const tableOfCheck = new Map((catalog.table_constraints ?? []).filter((row) => text(row.constraint_type) === "CHECK").map((row) => [
|
|
1088
|
+
keyOf2(row.constraint_schema, row.constraint_name),
|
|
1089
|
+
keyOf2(row.table_schema, row.table_name)
|
|
1090
|
+
]));
|
|
1091
|
+
return group(catalog.check_constraints ?? [], (row) => text(row.table_name) ? keyOf2(row.constraint_schema, row.table_name) : tableOfCheck.get(keyOf2(row.constraint_schema, row.constraint_name)) ?? "");
|
|
1092
|
+
};
|
|
1093
|
+
var isOwnCheck = (row) => !/^`?\w+`? IS NOT NULL$/iu.test(text(row.check_clause) ?? "") || text(row.level) !== "Column";
|
|
1094
|
+
var foreignKeys = (catalog, tables) => {
|
|
1095
|
+
const rules = new Map((catalog.referential_constraints ?? []).map((row) => [
|
|
1096
|
+
keyOf2(row.constraint_schema, row.constraint_name),
|
|
1097
|
+
row
|
|
1098
|
+
]));
|
|
1099
|
+
const usage = group((catalog.key_column_usage ?? []).filter((row) => text(row.referenced_table_name)), (row) => `${keyOf2(row.constraint_schema, row.table_name)}.${text(row.constraint_name)}`);
|
|
1100
|
+
return [...usage.values()].flatMap((rows) => {
|
|
1101
|
+
const sorted = [...rows].sort((left, right) => integer(left.ordinal_position) - integer(right.ordinal_position));
|
|
1102
|
+
const [first] = sorted;
|
|
1103
|
+
if (!first)
|
|
1104
|
+
return [];
|
|
1105
|
+
const table = tables.get(keyOf2(first.table_schema, first.table_name));
|
|
1106
|
+
const rule = rules.get(keyOf2(first.constraint_schema, first.constraint_name));
|
|
1107
|
+
const columns = sorted.map((row) => text(row.column_name) ?? "");
|
|
1108
|
+
const onDelete = actionOf2(text(rule?.delete_rule));
|
|
1109
|
+
const onUpdate = actionOf2(text(rule?.update_rule));
|
|
1110
|
+
const name = text(first.constraint_name) ?? "";
|
|
1111
|
+
const ref = {
|
|
1112
|
+
from: {
|
|
1113
|
+
columns,
|
|
1114
|
+
schema: text(first.table_schema) ?? "",
|
|
1115
|
+
table: text(first.table_name) ?? ""
|
|
1116
|
+
},
|
|
1117
|
+
.../_ibfk_\d+$/u.test(name) ? {} : { name },
|
|
1118
|
+
...onDelete ? { onDelete } : {},
|
|
1119
|
+
...onUpdate ? { onUpdate } : {},
|
|
1120
|
+
relation: table && isUniqueSet(table, columns) ? "-" : ">",
|
|
1121
|
+
to: {
|
|
1122
|
+
columns: sorted.map((row) => text(row.referenced_column_name) ?? ""),
|
|
1123
|
+
schema: text(first.referenced_table_schema) ?? "",
|
|
1124
|
+
table: text(first.referenced_table_name) ?? ""
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
return [ref];
|
|
1128
|
+
});
|
|
1129
|
+
};
|
|
1130
|
+
var viewDeps = (catalog, views, tables) => {
|
|
1131
|
+
const usage = catalog.view_table_usage ?? [];
|
|
1132
|
+
if (usage.length > 0)
|
|
1133
|
+
return usage.map((row) => ({
|
|
1134
|
+
downstream: {
|
|
1135
|
+
schema: text(row.view_schema) ?? "",
|
|
1136
|
+
table: text(row.view_name) ?? ""
|
|
1137
|
+
},
|
|
1138
|
+
upstream: {
|
|
1139
|
+
schema: text(row.table_schema) ?? "",
|
|
1140
|
+
table: text(row.table_name) ?? ""
|
|
1141
|
+
}
|
|
1142
|
+
}));
|
|
1143
|
+
const definitions = new Map((catalog.views ?? []).map((row) => [
|
|
1144
|
+
keyOf2(row.table_schema, row.table_name),
|
|
1145
|
+
text(row.view_definition) ?? ""
|
|
1146
|
+
]));
|
|
1147
|
+
return views.flatMap((view) => {
|
|
1148
|
+
const sql = definitions.get(keyOf2(view.schema, view.name)) ?? "";
|
|
1149
|
+
return tables.filter((table) => sql.includes(`\`${table.name}\``)).map((table) => ({
|
|
1150
|
+
downstream: { schema: view.schema ?? "", table: view.name },
|
|
1151
|
+
upstream: { schema: table.schema ?? "", table: table.name }
|
|
1152
|
+
}));
|
|
1153
|
+
});
|
|
1154
|
+
};
|
|
1155
|
+
var fromMysql = async (query, options = {}) => {
|
|
1156
|
+
const [version] = await query("select version() as version", []);
|
|
1157
|
+
const mariadb = /mariadb/iu.test(text(version?.version) ?? "");
|
|
1158
|
+
const schemas = options.schemas ?? [
|
|
1159
|
+
text((await query("select database() as name", []))[0]?.name) ?? ""
|
|
1160
|
+
];
|
|
1161
|
+
const catalog = await readCatalog(query, schemas);
|
|
1162
|
+
const context = {
|
|
1163
|
+
mariadb,
|
|
1164
|
+
statistics: options.statistics === true
|
|
1165
|
+
};
|
|
1166
|
+
const model = emptyModel({
|
|
1167
|
+
databaseType: mariadb ? "MariaDB" : "MySQL",
|
|
1168
|
+
...options.project
|
|
1169
|
+
});
|
|
1170
|
+
const columns = group(catalog.columns ?? [], (row) => keyOf2(row.table_schema, row.table_name));
|
|
1171
|
+
const indexes = group(catalog.statistics ?? [], (row) => `${keyOf2(row.table_schema, row.table_name)}.${text(row.index_name)}`);
|
|
1172
|
+
const checks = checksOf(catalog);
|
|
1173
|
+
const grants = grantsOf(catalog);
|
|
1174
|
+
const triggers = group(catalog.triggers ?? [], (row) => keyOf2(row.event_object_schema, row.event_object_table));
|
|
1175
|
+
const partitions = group(catalog.partitions ?? [], (row) => keyOf2(row.table_schema, row.table_name));
|
|
1176
|
+
const views = new Map((catalog.views ?? []).map((row) => [
|
|
1177
|
+
keyOf2(row.table_schema, row.table_name),
|
|
1178
|
+
row
|
|
1179
|
+
]));
|
|
1180
|
+
const tables = new Map;
|
|
1181
|
+
const enums = [];
|
|
1182
|
+
(catalog.tables ?? []).forEach((row) => {
|
|
1183
|
+
const schema = text(row.table_schema) ?? "";
|
|
1184
|
+
const name = text(row.table_name) ?? "";
|
|
1185
|
+
const key = keyOf2(schema, name);
|
|
1186
|
+
const view = views.get(key);
|
|
1187
|
+
const built = (columns.get(key) ?? []).sort((left, right) => integer(left.ordinal_position) - integer(right.ordinal_position)).map((column) => columnOf2({ ...column, table_collation: row.table_collation }, { name, schema }, context));
|
|
1188
|
+
enums.push(...built.flatMap((entry) => entry.enumType ? [entry.enumType] : []));
|
|
1189
|
+
const grantLine = (grants.get(key) ?? []).map((grant) => `${text(grant.privilege_type)} to ${text(grant.grantee)}`).join(", ");
|
|
1190
|
+
const metadata = view ? {
|
|
1191
|
+
...text(view.check_option) && text(view.check_option) !== "NONE" ? { check_option: text(view.check_option) ?? "" } : {},
|
|
1192
|
+
...text(view.security_type) ? { security: text(view.security_type) ?? "" } : {}
|
|
1193
|
+
} : tableMetadata(row, context, grantLine || undefined);
|
|
1194
|
+
const notes = [
|
|
1195
|
+
text(row.table_comment) && text(row.table_comment) !== "VIEW" ? text(row.table_comment) : undefined,
|
|
1196
|
+
view ? `View:
|
|
1197
|
+
${text(view.view_definition) ?? ""}` : undefined,
|
|
1198
|
+
...partitionLines(partitions.get(key) ?? []),
|
|
1199
|
+
...(triggers.get(key) ?? []).map(triggerLine)
|
|
1200
|
+
].filter((line) => line !== undefined && line !== "");
|
|
1201
|
+
const table = {
|
|
1202
|
+
checks: (checks.get(key) ?? []).filter(isOwnCheck).map((check) => ({
|
|
1203
|
+
expression: (text(check.check_clause) ?? "").replace(/^\((.*)\)$/su, "$1"),
|
|
1204
|
+
name: text(check.constraint_name) ?? ""
|
|
1205
|
+
})),
|
|
1206
|
+
columns: built.map((entry) => entry.column),
|
|
1207
|
+
...view ? { headerColor: VIEW_COLOR2 } : {},
|
|
1208
|
+
indexes: [],
|
|
1209
|
+
...Object.keys(metadata).length > 0 ? { metadata } : {},
|
|
1210
|
+
name,
|
|
1211
|
+
...notes.length > 0 ? { note: notes.join(`
|
|
1212
|
+
`) } : {},
|
|
1213
|
+
schema
|
|
1214
|
+
};
|
|
1215
|
+
[...indexes.entries()].filter(([indexKey]) => indexKey.startsWith(`${key}.`)).forEach(([, rows]) => placeIndex(table, indexOf2(rows)));
|
|
1216
|
+
tables.set(key, table);
|
|
1217
|
+
});
|
|
1218
|
+
model.enums.push(...enums);
|
|
1219
|
+
model.tables.push(...tables.values());
|
|
1220
|
+
model.refs.push(...foreignKeys(catalog, tables));
|
|
1221
|
+
model.deps.push(...viewDeps(catalog, model.tables.filter((table) => table.headerColor), model.tables.filter((table) => !table.headerColor)));
|
|
1222
|
+
model.notes.push(...routineNote(catalog), ...eventNote(catalog));
|
|
1223
|
+
const defaultSchema = options.defaultSchema ?? schemas[0] ?? "";
|
|
1224
|
+
const result = withDefaultSchema(model, defaultSchema);
|
|
1225
|
+
if (options.groups === "schema")
|
|
1226
|
+
result.tableGroups.push(...groupBySchema(result.tables, defaultSchema));
|
|
1227
|
+
return result;
|
|
1228
|
+
};
|
|
1229
|
+
|
|
768
1230
|
// src/postgres/index.ts
|
|
769
1231
|
import { Buffer } from "buffer";
|
|
770
1232
|
|
|
1233
|
+
// src/postgres/details.ts
|
|
1234
|
+
var present2 = (lines) => lines.filter((line) => line !== undefined && line !== "");
|
|
1235
|
+
var withMetadata = (metadata) => Object.keys(metadata).length > 0 ? { metadata } : {};
|
|
1236
|
+
var DEFAULT_IDENTITY = "1 1";
|
|
1237
|
+
var columnMetadata = (row) => {
|
|
1238
|
+
const [start, increment] = (row.identitySequence ?? "").split(" ");
|
|
1239
|
+
const identity = row.identitySequence && row.identitySequence !== DEFAULT_IDENTITY ? {
|
|
1240
|
+
identity_increment: Number.parseInt(increment ?? "1", 10),
|
|
1241
|
+
identity_start: Number.parseInt(start ?? "1", 10)
|
|
1242
|
+
} : {};
|
|
1243
|
+
const metadata = {
|
|
1244
|
+
...row.collation ? { collation: row.collation } : {},
|
|
1245
|
+
...row.compression ? { compression: row.compression } : {},
|
|
1246
|
+
...row.domainBase ? { domain_of: row.domainBase } : {},
|
|
1247
|
+
...identity
|
|
1248
|
+
};
|
|
1249
|
+
return withMetadata(metadata);
|
|
1250
|
+
};
|
|
1251
|
+
var nullsOrdering = (row, part, name) => {
|
|
1252
|
+
const descending = row.descending[part] === true;
|
|
1253
|
+
const nullsFirst = row.nullsFirst[part] === true;
|
|
1254
|
+
if (descending === nullsFirst)
|
|
1255
|
+
return;
|
|
1256
|
+
return `${name} nulls ${nullsFirst ? "first" : "last"}`;
|
|
1257
|
+
};
|
|
1258
|
+
var indexNotes2 = (row, partName) => {
|
|
1259
|
+
const parts = Array.from({ length: row.keyCount }, (_, part) => part);
|
|
1260
|
+
const nulls = present2(parts.map((part) => nullsOrdering(row, part, partName(part))));
|
|
1261
|
+
const classes = present2(parts.map((part) => row.opclasses[part] ? `${partName(part)} ${row.opclasses[part]}` : undefined));
|
|
1262
|
+
const collations = present2(parts.map((part) => row.collations[part] ? `${partName(part)} ${row.collations[part]}` : undefined));
|
|
1263
|
+
return present2([
|
|
1264
|
+
nulls.length > 0 ? `Sorted with ${nulls.join(", ")}` : undefined,
|
|
1265
|
+
classes.length > 0 ? `Operator class: ${classes.join(", ")}` : undefined,
|
|
1266
|
+
collations.length > 0 ? `Collation: ${collations.join(", ")}` : undefined,
|
|
1267
|
+
row.nullsNotDistinct ? "Nulls not distinct" : undefined
|
|
1268
|
+
]);
|
|
1269
|
+
};
|
|
1270
|
+
var tableMetadata2 = (relation, statistics) => {
|
|
1271
|
+
const metadata = {
|
|
1272
|
+
...relation.owner ? { owner: relation.owner } : {},
|
|
1273
|
+
...relation.grants ? { grants: relation.grants } : {},
|
|
1274
|
+
...relation.persistence === "u" ? { unlogged: true } : {},
|
|
1275
|
+
...relation.options ? { options: relation.options } : {},
|
|
1276
|
+
...relation.foreignServer ? { foreign_server: relation.foreignServer } : {},
|
|
1277
|
+
...relation.foreignOptions ? { foreign_options: relation.foreignOptions } : {},
|
|
1278
|
+
...relation.inherits ? { inherits: relation.inherits } : {},
|
|
1279
|
+
...statistics && relation.rowEstimate ? { rows: Number.parseInt(relation.rowEstimate, 10) } : {},
|
|
1280
|
+
...statistics && relation.sizeBytes ? { size_bytes: Number.parseInt(relation.sizeBytes, 10) } : {}
|
|
1281
|
+
};
|
|
1282
|
+
return withMetadata(metadata);
|
|
1283
|
+
};
|
|
1284
|
+
var DISABLED = "D";
|
|
1285
|
+
var definitionLine = (kind, entry) => {
|
|
1286
|
+
const body = entry.definition.replace(/^CREATE (OR REPLACE )?(CONSTRAINT )?(TRIGGER|RULE) /u, "");
|
|
1287
|
+
return `${kind} ${body}${entry.enabled === DISABLED ? " (disabled)" : ""}`;
|
|
1288
|
+
};
|
|
1289
|
+
var tableNoteLines = (input) => present2([
|
|
1290
|
+
input.inherits ? `Inherits from ${input.inherits}` : undefined,
|
|
1291
|
+
...input.partitions.map((partition) => `Partition ${partition.name}: ${partition.bound}`),
|
|
1292
|
+
...input.triggers.map((trigger) => definitionLine("Trigger", trigger)),
|
|
1293
|
+
...input.rules.map((rule) => definitionLine("Rule", rule))
|
|
1294
|
+
]);
|
|
1295
|
+
var KINDS = {
|
|
1296
|
+
a: "aggregate",
|
|
1297
|
+
f: "function",
|
|
1298
|
+
p: "procedure",
|
|
1299
|
+
w: "window function"
|
|
1300
|
+
};
|
|
1301
|
+
var qualified = (schema, name, defaultSchema) => schema === defaultSchema ? name : `${schema}.${name}`;
|
|
1302
|
+
var sticky = (name, title, lines) => {
|
|
1303
|
+
if (lines.length === 0)
|
|
1304
|
+
return [];
|
|
1305
|
+
const note = {
|
|
1306
|
+
content: `${title}
|
|
1307
|
+
${lines.join(`
|
|
1308
|
+
`)}`,
|
|
1309
|
+
name
|
|
1310
|
+
};
|
|
1311
|
+
return [note];
|
|
1312
|
+
};
|
|
1313
|
+
var domainLine = (domain, defaultSchema) => [
|
|
1314
|
+
`${qualified(domain.schema, domain.name, defaultSchema)}: ${domain.base}`,
|
|
1315
|
+
domain.notNull ? "not null" : undefined,
|
|
1316
|
+
domain.default ? `default ${domain.default}` : undefined,
|
|
1317
|
+
domain.constraints
|
|
1318
|
+
].filter((part) => part !== undefined).join(", ");
|
|
1319
|
+
var extraNotes = (extras, defaultSchema) => [
|
|
1320
|
+
...sticky("functions", "Functions and procedures", extras.functions.map((entry) => `${qualified(entry.schema, entry.name, defaultSchema)}(${entry.arguments})${entry.kind === "p" ? "" : ` \u2192 ${entry.result}`}, ${KINDS[entry.kind] ?? "function"} in ${entry.language}`)),
|
|
1321
|
+
...sticky("domains", "Domains", extras.domains.map((domain) => domainLine(domain, defaultSchema))),
|
|
1322
|
+
...sticky("composite_types", "Composite types", extras.composites.map((entry) => `${qualified(entry.schema, entry.name, defaultSchema)}: ${entry.fields}`)),
|
|
1323
|
+
...sticky("extensions", "Extensions", extras.extensions.map((entry) => `${entry.name} ${entry.version}, in ${entry.schema}`)),
|
|
1324
|
+
...sticky("event_triggers", "Event triggers", extras.eventTriggers.map((entry) => `${entry.name}: on ${entry.event}, runs ${entry.function}${entry.enabled === DISABLED ? " (disabled)" : ""}`))
|
|
1325
|
+
];
|
|
1326
|
+
|
|
771
1327
|
// src/postgres/queries.ts
|
|
772
1328
|
var SCHEMAS = `
|
|
773
1329
|
select nspname as name
|
|
@@ -782,6 +1338,7 @@ from pg_type t
|
|
|
782
1338
|
join pg_namespace n on n.oid = t.typnamespace
|
|
783
1339
|
join pg_enum e on e.enumtypid = t.oid
|
|
784
1340
|
where n.nspname = any($1)
|
|
1341
|
+
and not exists (select 1 from pg_depend x where x.classid = 'pg_type'::regclass and x.objid = t.oid and x.deptype = 'e')
|
|
785
1342
|
group by n.nspname, t.typname
|
|
786
1343
|
order by n.nspname, t.typname`;
|
|
787
1344
|
var RELATIONS = `
|
|
@@ -790,10 +1347,23 @@ select c.oid::int as id, n.nspname as schema, c.relname as name, c.relkind as ki
|
|
|
790
1347
|
c.relrowsecurity as rls, c.relforcerowsecurity as force_rls,
|
|
791
1348
|
case when c.relkind = 'p' then pg_get_partkeydef(c.oid) end as partition_key,
|
|
792
1349
|
case when c.relkind in ('v', 'm') then pg_get_viewdef(c.oid, true) end as definition,
|
|
793
|
-
(select count(*)::int from pg_inherits i where i.inhparent = c.oid) as partitions
|
|
1350
|
+
(select count(*)::int from pg_inherits i where i.inhparent = c.oid) as partitions,
|
|
1351
|
+
pg_get_userbyid(c.relowner) as owner,
|
|
1352
|
+
c.relpersistence as persistence,
|
|
1353
|
+
array_to_string(c.reloptions, ', ') as options,
|
|
1354
|
+
case when c.reltuples >= 0 then c.reltuples::bigint::text end as row_estimate,
|
|
1355
|
+
case when c.relkind in ('r', 'p', 'm') then pg_total_relation_size(c.oid)::text end as size_bytes,
|
|
1356
|
+
(select string_agg(g.privilege_type || ' to ' || case when g.grantee = 0 then 'public' else pg_get_userbyid(g.grantee) end, ', ' order by g.grantee, g.privilege_type)
|
|
1357
|
+
from aclexplode(c.relacl) as g where g.grantee <> c.relowner) as grants,
|
|
1358
|
+
(select s.srvname from pg_foreign_table ft join pg_foreign_server s on s.oid = ft.ftserver where ft.ftrelid = c.oid) as foreign_server,
|
|
1359
|
+
(select array_to_string(ft.ftoptions, ', ') from pg_foreign_table ft where ft.ftrelid = c.oid) as foreign_options,
|
|
1360
|
+
(select string_agg(quote_ident(pn.nspname) || '.' || quote_ident(p.relname), ', ')
|
|
1361
|
+
from pg_inherits i join pg_class p on p.oid = i.inhparent join pg_namespace pn on pn.oid = p.relnamespace
|
|
1362
|
+
where i.inhrelid = c.oid and p.relkind <> 'p') as inherits
|
|
794
1363
|
from pg_class c
|
|
795
1364
|
join pg_namespace n on n.oid = c.relnamespace
|
|
796
1365
|
where n.nspname = any($1) and c.relkind in ('r', 'p', 'v', 'm', 'f') and not c.relispartition
|
|
1366
|
+
and not exists (select 1 from pg_depend e where e.classid = 'pg_class'::regclass and e.objid = c.oid and e.deptype = 'e')
|
|
797
1367
|
order by n.nspname, c.relname`;
|
|
798
1368
|
var COLUMNS = `
|
|
799
1369
|
select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name,
|
|
@@ -805,7 +1375,12 @@ select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name
|
|
|
805
1375
|
when et.typtype = 'e' then etn.nspname end as enum_schema,
|
|
806
1376
|
coalesce(case when t.typtype = 'e' then t.typname end,
|
|
807
1377
|
case when et.typtype = 'e' then et.typname || '[]' end) as enum_type,
|
|
808
|
-
pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname) as serial_sequence
|
|
1378
|
+
pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname) as serial_sequence,
|
|
1379
|
+
case when a.attcollation <> 0 and a.attcollation <> t.typcollation then (select collname from pg_collation where oid = a.attcollation) end as collation,
|
|
1380
|
+
case to_jsonb(a) ->> 'attcompression' when 'p' then 'pglz' when 'l' then 'lz4' end as compression,
|
|
1381
|
+
case when a.attidentity <> '' then (select s.seqstart::text || ' ' || s.seqincrement::text from pg_sequence s
|
|
1382
|
+
where s.seqrelid = pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname)::regclass) end as identity_sequence,
|
|
1383
|
+
case when t.typtype = 'd' then format_type(t.typbasetype, t.typtypmod) end as domain_base
|
|
809
1384
|
from pg_attribute a
|
|
810
1385
|
join pg_class c on c.oid = a.attrelid
|
|
811
1386
|
join pg_namespace n on n.oid = c.relnamespace
|
|
@@ -843,6 +1418,17 @@ select i.indrelid::int as table_id, ic.relname as name, am.amname as method,
|
|
|
843
1418
|
from generate_series(1, i.indnatts) as k) as attnums,
|
|
844
1419
|
(select array_agg((i.indoption[k - 1] & 1) = 1 order by k)
|
|
845
1420
|
from generate_series(1, i.indnkeyatts) as k) as descending,
|
|
1421
|
+
(select array_agg((i.indoption[k - 1] & 2) = 2 order by k)
|
|
1422
|
+
from generate_series(1, i.indnkeyatts) as k) as nulls_first,
|
|
1423
|
+
/* An operator class or collation that isn't the column's own, per key
|
|
1424
|
+
* part, empty where it is. */
|
|
1425
|
+
(select array_agg(case when opc.opcdefault then '' else opc.opcname end order by k)
|
|
1426
|
+
from generate_series(1, i.indnkeyatts) as k join pg_opclass opc on opc.oid = i.indclass[k - 1]) as opclasses,
|
|
1427
|
+
(select array_agg(coalesce((select co.collname from pg_collation co where co.oid = i.indcollation[k - 1]
|
|
1428
|
+
and i.indcollation[k - 1] <> coalesce((select a.attcollation from pg_attribute a where a.attrelid = i.indrelid and a.attnum = i.indkey[k - 1]), 0)
|
|
1429
|
+
and co.collname <> 'default'), '') order by k)
|
|
1430
|
+
from generate_series(1, i.indnkeyatts) as k) as collations,
|
|
1431
|
+
(to_jsonb(i) ->> 'indnullsnotdistinct')::boolean as nulls_not_distinct,
|
|
846
1432
|
pg_get_expr(i.indpred, i.indrelid, true) as predicate,
|
|
847
1433
|
obj_description(i.indexrelid, 'pg_class') as comment
|
|
848
1434
|
from pg_index i
|
|
@@ -884,6 +1470,81 @@ order by n.nspname, c.relname`;
|
|
|
884
1470
|
var SCHEMA_COMMENTS = `
|
|
885
1471
|
select nspname as name, obj_description(oid, 'pg_namespace') as comment
|
|
886
1472
|
from pg_namespace where nspname = any($1)`;
|
|
1473
|
+
var TRIGGERS = `
|
|
1474
|
+
select t.tgrelid::int as table_id, t.tgname as name, pg_get_triggerdef(t.oid, true) as definition,
|
|
1475
|
+
t.tgenabled as enabled
|
|
1476
|
+
from pg_trigger t
|
|
1477
|
+
join pg_class c on c.oid = t.tgrelid
|
|
1478
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
1479
|
+
where n.nspname = any($1) and not t.tgisinternal
|
|
1480
|
+
order by t.tgrelid, t.tgname`;
|
|
1481
|
+
var RULES = `
|
|
1482
|
+
select r.ev_class::int as table_id, r.rulename as name, pg_get_ruledef(r.oid, true) as definition
|
|
1483
|
+
from pg_rewrite r
|
|
1484
|
+
join pg_class c on c.oid = r.ev_class
|
|
1485
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
1486
|
+
where n.nspname = any($1) and r.rulename <> '_RETURN'
|
|
1487
|
+
order by r.ev_class, r.rulename`;
|
|
1488
|
+
var FUNCTIONS = `
|
|
1489
|
+
select n.nspname as schema, p.proname as name, p.prokind as kind,
|
|
1490
|
+
pg_get_function_identity_arguments(p.oid) as arguments,
|
|
1491
|
+
pg_get_function_result(p.oid) as result, l.lanname as language
|
|
1492
|
+
from pg_proc p
|
|
1493
|
+
join pg_namespace n on n.oid = p.pronamespace
|
|
1494
|
+
join pg_language l on l.oid = p.prolang
|
|
1495
|
+
where n.nspname = any($1)
|
|
1496
|
+
and not exists (select 1 from pg_depend e where e.classid = 'pg_proc'::regclass and e.objid = p.oid and e.deptype = 'e')
|
|
1497
|
+
order by n.nspname, p.proname, arguments`;
|
|
1498
|
+
var DOMAINS = `
|
|
1499
|
+
select n.nspname as schema, t.typname as name, format_type(t.typbasetype, t.typtypmod) as base,
|
|
1500
|
+
t.typnotnull as not_null, t.typdefault as "default",
|
|
1501
|
+
(select string_agg(pg_get_constraintdef(con.oid, true), ' and ' order by con.conname)
|
|
1502
|
+
/* Postgres 17 also keeps NOT NULL as a constraint; typnotnull says it. */
|
|
1503
|
+
from pg_constraint con where con.contypid = t.oid and con.contype <> 'n') as constraints
|
|
1504
|
+
from pg_type t
|
|
1505
|
+
join pg_namespace n on n.oid = t.typnamespace
|
|
1506
|
+
where n.nspname = any($1) and t.typtype = 'd'
|
|
1507
|
+
and not exists (select 1 from pg_depend e where e.classid = 'pg_type'::regclass and e.objid = t.oid and e.deptype = 'e')
|
|
1508
|
+
order by n.nspname, t.typname`;
|
|
1509
|
+
var COMPOSITES = `
|
|
1510
|
+
select n.nspname as schema, t.typname as name,
|
|
1511
|
+
string_agg(a.attname || ' ' || format_type(a.atttypid, a.atttypmod), ', ' order by a.attnum) as fields
|
|
1512
|
+
from pg_type t
|
|
1513
|
+
join pg_namespace n on n.oid = t.typnamespace
|
|
1514
|
+
join pg_class c on c.oid = t.typrelid and c.relkind = 'c'
|
|
1515
|
+
join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
|
|
1516
|
+
where n.nspname = any($1)
|
|
1517
|
+
and not exists (select 1 from pg_depend e where e.classid = 'pg_type'::regclass and e.objid = t.oid and e.deptype = 'e')
|
|
1518
|
+
group by n.nspname, t.typname
|
|
1519
|
+
order by n.nspname, t.typname`;
|
|
1520
|
+
var EXTENSIONS = `
|
|
1521
|
+
select e.extname as name, e.extversion as version, n.nspname as schema
|
|
1522
|
+
from pg_extension e
|
|
1523
|
+
join pg_namespace n on n.oid = e.extnamespace
|
|
1524
|
+
where e.extname <> 'plpgsql'
|
|
1525
|
+
order by e.extname`;
|
|
1526
|
+
var EVENT_TRIGGERS = `
|
|
1527
|
+
select evtname as name, evtevent as event, evtfoid::regproc::text as function, evtenabled as enabled
|
|
1528
|
+
from pg_event_trigger
|
|
1529
|
+
order by evtname`;
|
|
1530
|
+
var PARTITIONS = `
|
|
1531
|
+
select i.inhparent::int as table_id, c.relname as name, pg_get_expr(c.relpartbound, c.oid, true) as bound
|
|
1532
|
+
from pg_inherits i
|
|
1533
|
+
join pg_class c on c.oid = i.inhrelid
|
|
1534
|
+
join pg_class p on p.oid = i.inhparent
|
|
1535
|
+
join pg_namespace n on n.oid = p.relnamespace
|
|
1536
|
+
where n.nspname = any($1) and p.relkind = 'p'
|
|
1537
|
+
order by i.inhparent, c.relname`;
|
|
1538
|
+
var VIEW_COLUMNS = `
|
|
1539
|
+
select distinct v.oid::int as view_id, d.refobjid::int as source_id, a.attname as name
|
|
1540
|
+
from pg_class v
|
|
1541
|
+
join pg_namespace n on n.oid = v.relnamespace
|
|
1542
|
+
join pg_rewrite r on r.ev_class = v.oid
|
|
1543
|
+
join pg_depend d on d.objid = r.oid and d.classid = 'pg_rewrite'::regclass
|
|
1544
|
+
and d.refclassid = 'pg_class'::regclass and d.refobjid <> v.oid and d.refobjsubid > 0
|
|
1545
|
+
join pg_attribute a on a.attrelid = d.refobjid and a.attnum = d.refobjsubid
|
|
1546
|
+
where n.nspname = any($1) and v.relkind in ('v', 'm')
|
|
1547
|
+
order by view_id, source_id, name`;
|
|
887
1548
|
|
|
888
1549
|
// src/postgres/rows.ts
|
|
889
1550
|
var optional = (key, value) => {
|
|
@@ -892,62 +1553,75 @@ var optional = (key, value) => {
|
|
|
892
1553
|
entry[key] = value;
|
|
893
1554
|
return entry;
|
|
894
1555
|
};
|
|
895
|
-
var
|
|
1556
|
+
var text2 = (value) => {
|
|
896
1557
|
if (value === null || value === undefined)
|
|
897
1558
|
return;
|
|
898
1559
|
return typeof value === "string" ? value : `${value}`;
|
|
899
1560
|
};
|
|
900
|
-
var
|
|
1561
|
+
var integer2 = (value) => {
|
|
901
1562
|
if (typeof value === "number")
|
|
902
1563
|
return value;
|
|
903
|
-
const parsed = Number.parseInt(
|
|
1564
|
+
const parsed = Number.parseInt(text2(value) ?? "", 10);
|
|
904
1565
|
return Number.isNaN(parsed) ? 0 : parsed;
|
|
905
1566
|
};
|
|
906
1567
|
var flag = (value) => value === true || value === "t" || value === "true";
|
|
907
1568
|
var ARRAY_ITEM = /"((?:[^"\\]|\\.)*)"|([^,{}]+)/gu;
|
|
908
1569
|
var list = (value) => {
|
|
909
1570
|
if (Array.isArray(value))
|
|
910
|
-
return value.map((entry) =>
|
|
911
|
-
const raw =
|
|
1571
|
+
return value.map((entry) => text2(entry) ?? "");
|
|
1572
|
+
const raw = text2(value);
|
|
912
1573
|
if (raw === undefined)
|
|
913
1574
|
return [];
|
|
914
1575
|
return [...raw.matchAll(ARRAY_ITEM)].map((match) => match[1] === undefined ? match[2] ?? "" : match[1].replace(/\\(.)/gu, "$1"));
|
|
915
1576
|
};
|
|
916
|
-
var integers = (value) => list(value).map(
|
|
1577
|
+
var integers = (value) => list(value).map(integer2);
|
|
917
1578
|
var flags = (value) => list(value).map(flag);
|
|
918
1579
|
var relationRow = (row) => {
|
|
919
1580
|
const result = {
|
|
920
1581
|
forceRls: flag(row.force_rls),
|
|
921
|
-
id:
|
|
922
|
-
kind:
|
|
923
|
-
name:
|
|
924
|
-
partitions:
|
|
1582
|
+
id: integer2(row.id),
|
|
1583
|
+
kind: text2(row.kind) ?? "",
|
|
1584
|
+
name: text2(row.name) ?? "",
|
|
1585
|
+
partitions: integer2(row.partitions),
|
|
1586
|
+
persistence: text2(row.persistence) ?? "p",
|
|
925
1587
|
rls: flag(row.rls),
|
|
926
|
-
schema:
|
|
927
|
-
...optional("comment",
|
|
928
|
-
...optional("definition",
|
|
929
|
-
...optional("
|
|
1588
|
+
schema: text2(row.schema) ?? "",
|
|
1589
|
+
...optional("comment", text2(row.comment)),
|
|
1590
|
+
...optional("definition", text2(row.definition)),
|
|
1591
|
+
...optional("foreignOptions", setting(row.foreign_options)),
|
|
1592
|
+
...optional("foreignServer", text2(row.foreign_server)),
|
|
1593
|
+
...optional("grants", text2(row.grants)),
|
|
1594
|
+
...optional("inherits", text2(row.inherits)),
|
|
1595
|
+
...optional("options", setting(row.options)),
|
|
1596
|
+
...optional("owner", text2(row.owner)),
|
|
1597
|
+
...optional("partitionKey", text2(row.partition_key)),
|
|
1598
|
+
...optional("rowEstimate", text2(row.row_estimate)),
|
|
1599
|
+
...optional("sizeBytes", text2(row.size_bytes))
|
|
930
1600
|
};
|
|
931
1601
|
return result;
|
|
932
1602
|
};
|
|
933
1603
|
var setting = (value) => {
|
|
934
|
-
const raw =
|
|
1604
|
+
const raw = text2(value);
|
|
935
1605
|
return raw === "" ? undefined : raw;
|
|
936
1606
|
};
|
|
937
1607
|
var columnRow = (row) => {
|
|
938
1608
|
const result = {
|
|
939
|
-
name:
|
|
1609
|
+
name: text2(row.name) ?? "",
|
|
940
1610
|
notNull: flag(row.not_null),
|
|
941
|
-
position:
|
|
942
|
-
tableId:
|
|
943
|
-
type:
|
|
944
|
-
...optional("
|
|
945
|
-
...optional("
|
|
946
|
-
...optional("
|
|
947
|
-
...optional("
|
|
1611
|
+
position: integer2(row.position),
|
|
1612
|
+
tableId: integer2(row.table_id),
|
|
1613
|
+
type: text2(row.type) ?? "",
|
|
1614
|
+
...optional("collation", text2(row.collation)),
|
|
1615
|
+
...optional("comment", text2(row.comment)),
|
|
1616
|
+
...optional("compression", text2(row.compression)),
|
|
1617
|
+
...optional("default", text2(row.default)),
|
|
1618
|
+
...optional("domainBase", text2(row.domain_base)),
|
|
1619
|
+
...optional("enumSchema", text2(row.enum_schema)),
|
|
1620
|
+
...optional("enumType", text2(row.enum_type)),
|
|
948
1621
|
...optional("generated", setting(row.generated)),
|
|
949
1622
|
...optional("identity", setting(row.identity)),
|
|
950
|
-
...optional("
|
|
1623
|
+
...optional("identitySequence", text2(row.identity_sequence)),
|
|
1624
|
+
...optional("serialSequence", text2(row.serial_sequence))
|
|
951
1625
|
};
|
|
952
1626
|
return result;
|
|
953
1627
|
};
|
|
@@ -956,75 +1630,127 @@ var constraintRow = (row) => {
|
|
|
956
1630
|
columns: integers(row.columns),
|
|
957
1631
|
deferrable: flag(row.deferrable),
|
|
958
1632
|
deferred: flag(row.deferred),
|
|
959
|
-
definition:
|
|
1633
|
+
definition: text2(row.definition) ?? "",
|
|
960
1634
|
foreignColumns: integers(row.foreign_columns),
|
|
961
|
-
foreignTableId:
|
|
962
|
-
kind:
|
|
963
|
-
name:
|
|
1635
|
+
foreignTableId: integer2(row.foreign_table_id),
|
|
1636
|
+
kind: text2(row.kind) ?? "",
|
|
1637
|
+
name: text2(row.name) ?? "",
|
|
964
1638
|
nullsNotDistinct: flag(row.nulls_not_distinct),
|
|
965
|
-
onDelete:
|
|
966
|
-
onUpdate:
|
|
967
|
-
tableId:
|
|
968
|
-
...optional("checkExpression",
|
|
969
|
-
...optional("comment",
|
|
1639
|
+
onDelete: text2(row.on_delete) ?? "a",
|
|
1640
|
+
onUpdate: text2(row.on_update) ?? "a",
|
|
1641
|
+
tableId: integer2(row.table_id),
|
|
1642
|
+
...optional("checkExpression", text2(row.check_expression)),
|
|
1643
|
+
...optional("comment", text2(row.comment))
|
|
970
1644
|
};
|
|
971
1645
|
return result;
|
|
972
1646
|
};
|
|
973
1647
|
var indexRow = (row) => {
|
|
974
1648
|
const result = {
|
|
975
1649
|
attnums: integers(row.attnums),
|
|
1650
|
+
collations: list(row.collations),
|
|
976
1651
|
descending: flags(row.descending),
|
|
977
|
-
keyCount:
|
|
978
|
-
method:
|
|
979
|
-
name:
|
|
1652
|
+
keyCount: integer2(row.key_count),
|
|
1653
|
+
method: text2(row.method) ?? "btree",
|
|
1654
|
+
name: text2(row.name) ?? "",
|
|
1655
|
+
nullsFirst: flags(row.nulls_first),
|
|
1656
|
+
nullsNotDistinct: flag(row.nulls_not_distinct),
|
|
1657
|
+
opclasses: list(row.opclasses),
|
|
980
1658
|
parts: list(row.parts),
|
|
981
|
-
tableId:
|
|
1659
|
+
tableId: integer2(row.table_id),
|
|
982
1660
|
unique: flag(row.is_unique),
|
|
983
|
-
...optional("comment",
|
|
984
|
-
...optional("predicate",
|
|
1661
|
+
...optional("comment", text2(row.comment)),
|
|
1662
|
+
...optional("predicate", text2(row.predicate))
|
|
985
1663
|
};
|
|
986
1664
|
return result;
|
|
987
1665
|
};
|
|
988
1666
|
var policyRow = (row) => {
|
|
989
1667
|
const result = {
|
|
990
|
-
command:
|
|
991
|
-
name:
|
|
1668
|
+
command: text2(row.command) ?? "*",
|
|
1669
|
+
name: text2(row.name) ?? "",
|
|
992
1670
|
permissive: flag(row.permissive),
|
|
993
1671
|
roles: list(row.roles),
|
|
994
|
-
tableId:
|
|
995
|
-
...optional("using",
|
|
996
|
-
...optional("withCheck",
|
|
1672
|
+
tableId: integer2(row.table_id),
|
|
1673
|
+
...optional("using", text2(row.using)),
|
|
1674
|
+
...optional("withCheck", text2(row.with_check))
|
|
997
1675
|
};
|
|
998
1676
|
return result;
|
|
999
1677
|
};
|
|
1000
1678
|
var namedRow = (row) => {
|
|
1001
1679
|
const result = {
|
|
1002
|
-
name:
|
|
1003
|
-
schema:
|
|
1004
|
-
...optional("comment",
|
|
1680
|
+
name: text2(row.name) ?? "",
|
|
1681
|
+
schema: text2(row.schema) ?? "",
|
|
1682
|
+
...optional("comment", text2(row.comment))
|
|
1005
1683
|
};
|
|
1006
1684
|
return result;
|
|
1007
1685
|
};
|
|
1008
1686
|
var enumRow = (row) => ({
|
|
1009
|
-
name:
|
|
1010
|
-
schema:
|
|
1687
|
+
name: text2(row.name) ?? "",
|
|
1688
|
+
schema: text2(row.schema) ?? "",
|
|
1011
1689
|
values: list(row.values)
|
|
1012
1690
|
});
|
|
1013
1691
|
var sequenceRow = (row) => ({
|
|
1014
|
-
increment:
|
|
1015
|
-
name:
|
|
1016
|
-
schema:
|
|
1017
|
-
start:
|
|
1692
|
+
increment: text2(row.increment) ?? "1",
|
|
1693
|
+
name: text2(row.name) ?? "",
|
|
1694
|
+
schema: text2(row.schema) ?? "",
|
|
1695
|
+
start: text2(row.start) ?? "1"
|
|
1018
1696
|
});
|
|
1019
1697
|
var viewSourceRow = (row) => ({
|
|
1020
|
-
sourceId:
|
|
1021
|
-
viewId:
|
|
1698
|
+
sourceId: integer2(row.source_id),
|
|
1699
|
+
viewId: integer2(row.view_id)
|
|
1700
|
+
});
|
|
1701
|
+
var definitionRow = (row) => ({
|
|
1702
|
+
definition: text2(row.definition) ?? "",
|
|
1703
|
+
enabled: text2(row.enabled) ?? "O",
|
|
1704
|
+
name: text2(row.name) ?? "",
|
|
1705
|
+
tableId: integer2(row.table_id)
|
|
1706
|
+
});
|
|
1707
|
+
var functionRow = (row) => ({
|
|
1708
|
+
arguments: text2(row.arguments) ?? "",
|
|
1709
|
+
kind: text2(row.kind) ?? "f",
|
|
1710
|
+
language: text2(row.language) ?? "",
|
|
1711
|
+
name: text2(row.name) ?? "",
|
|
1712
|
+
result: text2(row.result) ?? "",
|
|
1713
|
+
schema: text2(row.schema) ?? ""
|
|
1714
|
+
});
|
|
1715
|
+
var domainRow = (row) => ({
|
|
1716
|
+
base: text2(row.base) ?? "",
|
|
1717
|
+
constraints: text2(row.constraints),
|
|
1718
|
+
default: text2(row.default),
|
|
1719
|
+
name: text2(row.name) ?? "",
|
|
1720
|
+
notNull: flag(row.not_null),
|
|
1721
|
+
schema: text2(row.schema) ?? ""
|
|
1722
|
+
});
|
|
1723
|
+
var compositeRow = (row) => ({
|
|
1724
|
+
fields: text2(row.fields) ?? "",
|
|
1725
|
+
name: text2(row.name) ?? "",
|
|
1726
|
+
schema: text2(row.schema) ?? ""
|
|
1727
|
+
});
|
|
1728
|
+
var extensionRow = (row) => ({
|
|
1729
|
+
name: text2(row.name) ?? "",
|
|
1730
|
+
schema: text2(row.schema) ?? "",
|
|
1731
|
+
version: text2(row.version) ?? ""
|
|
1732
|
+
});
|
|
1733
|
+
var eventTriggerRow = (row) => ({
|
|
1734
|
+
enabled: text2(row.enabled) ?? "O",
|
|
1735
|
+
event: text2(row.event) ?? "",
|
|
1736
|
+
function: text2(row.function) ?? "",
|
|
1737
|
+
name: text2(row.name) ?? ""
|
|
1738
|
+
});
|
|
1739
|
+
var partitionRow = (row) => ({
|
|
1740
|
+
bound: text2(row.bound) ?? "",
|
|
1741
|
+
name: text2(row.name) ?? "",
|
|
1742
|
+
tableId: integer2(row.table_id)
|
|
1743
|
+
});
|
|
1744
|
+
var viewColumnRow = (row) => ({
|
|
1745
|
+
name: text2(row.name) ?? "",
|
|
1746
|
+
sourceId: integer2(row.source_id),
|
|
1747
|
+
viewId: integer2(row.view_id)
|
|
1022
1748
|
});
|
|
1023
1749
|
|
|
1024
1750
|
// src/postgres/index.ts
|
|
1025
1751
|
var DEFAULT_SCHEMA = "public";
|
|
1026
|
-
var inSchema2 = (schema) =>
|
|
1027
|
-
var
|
|
1752
|
+
var inSchema2 = (schema) => ({ schema });
|
|
1753
|
+
var ACTIONS3 = {
|
|
1028
1754
|
a: undefined,
|
|
1029
1755
|
c: "cascade",
|
|
1030
1756
|
d: "set default",
|
|
@@ -1032,7 +1758,7 @@ var ACTIONS2 = {
|
|
|
1032
1758
|
r: "restrict"
|
|
1033
1759
|
};
|
|
1034
1760
|
var QUOTED = /^'((?:[^']|'')*)'(?:::([\w\s."[\]()]+))?$/u;
|
|
1035
|
-
var
|
|
1761
|
+
var NUMBER2 = /^-?\d+(\.\d+)?$/u;
|
|
1036
1762
|
var NUMBER_CAST = /^\(?(-?\d+(?:\.\d+)?)\)?::[\w\s."]+$/u;
|
|
1037
1763
|
var NULL = /^NULL(::[\w\s."[\]()]+)?$/u;
|
|
1038
1764
|
var NUMERIC_TYPE = /^(smallint|integer|bigint|int[248]?|numeric(\(.*\))?|decimal(\(.*\))?|real|double precision|float[48]?)$/u;
|
|
@@ -1047,7 +1773,7 @@ var numberDefault = (digits, expression) => {
|
|
|
1047
1773
|
return result;
|
|
1048
1774
|
};
|
|
1049
1775
|
var quotedDefault = (inner, type, expression) => {
|
|
1050
|
-
if (NUMERIC_TYPE.test(type) &&
|
|
1776
|
+
if (NUMERIC_TYPE.test(type) && NUMBER2.test(inner))
|
|
1051
1777
|
return numberDefault(inner, expression);
|
|
1052
1778
|
const result = {
|
|
1053
1779
|
kind: "string",
|
|
@@ -1063,7 +1789,7 @@ var parseDefault = (expression) => {
|
|
|
1063
1789
|
kind: "boolean",
|
|
1064
1790
|
value: expression === "true"
|
|
1065
1791
|
};
|
|
1066
|
-
if (
|
|
1792
|
+
if (NUMBER2.test(expression))
|
|
1067
1793
|
return numberDefault(expression, expression);
|
|
1068
1794
|
const [, castDigits] = NUMBER_CAST.exec(expression) ?? [];
|
|
1069
1795
|
if (castDigits !== undefined)
|
|
@@ -1073,13 +1799,13 @@ var parseDefault = (expression) => {
|
|
|
1073
1799
|
return quotedDefault(inner, type ?? "", expression);
|
|
1074
1800
|
return { kind: "expression", value: expression };
|
|
1075
1801
|
};
|
|
1076
|
-
var
|
|
1802
|
+
var KINDS2 = {
|
|
1077
1803
|
f: "Foreign table",
|
|
1078
1804
|
m: "Materialized view",
|
|
1079
1805
|
p: "Partitioned table",
|
|
1080
1806
|
v: "View"
|
|
1081
1807
|
};
|
|
1082
|
-
var
|
|
1808
|
+
var VIEW_COLOR3 = "#64748b";
|
|
1083
1809
|
var POLICY_COMMANDS = {
|
|
1084
1810
|
"*": "all",
|
|
1085
1811
|
a: "insert",
|
|
@@ -1107,8 +1833,8 @@ var generatedNote2 = (row) => {
|
|
|
1107
1833
|
return `Generated always as (${row.default}), ${mode}`;
|
|
1108
1834
|
};
|
|
1109
1835
|
var isSerial = (row) => row.serialSequence !== undefined && row.default?.startsWith("nextval(") === true;
|
|
1110
|
-
var enumSchema = (row) => row.enumType && row.enumSchema
|
|
1111
|
-
var
|
|
1836
|
+
var enumSchema = (row) => row.enumType && row.enumSchema ? { typeSchema: row.enumSchema } : {};
|
|
1837
|
+
var columnOf3 = (row) => {
|
|
1112
1838
|
const serial = isSerial(row);
|
|
1113
1839
|
const fallback = row.default !== undefined && !serial && !row.generated ? parseDefault(row.default) : undefined;
|
|
1114
1840
|
const column = {
|
|
@@ -1118,6 +1844,7 @@ var columnOf2 = (row) => {
|
|
|
1118
1844
|
...serial || row.identity ? { increment: true } : {},
|
|
1119
1845
|
...row.notNull ? { notNull: true } : {},
|
|
1120
1846
|
...fallback ? { default: fallback } : {},
|
|
1847
|
+
...columnMetadata(row),
|
|
1121
1848
|
...withNote(joinNotes([
|
|
1122
1849
|
row.comment,
|
|
1123
1850
|
identityNote2(row.identity),
|
|
@@ -1165,15 +1892,15 @@ var applyKey = (table, row, columns) => {
|
|
|
1165
1892
|
};
|
|
1166
1893
|
table.indexes.push(index);
|
|
1167
1894
|
};
|
|
1168
|
-
var
|
|
1169
|
-
var
|
|
1170
|
-
var
|
|
1895
|
+
var sortedColumns3 = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
|
|
1896
|
+
var coversAll3 = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
|
|
1897
|
+
var isUniqueSet3 = (table, columns) => {
|
|
1171
1898
|
const [only] = columns;
|
|
1172
1899
|
const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
|
|
1173
1900
|
if (single?.pk === true || single?.unique === true)
|
|
1174
1901
|
return true;
|
|
1175
1902
|
const wanted = [...columns].sort().join("\x00");
|
|
1176
|
-
return table.indexes.some((index) =>
|
|
1903
|
+
return table.indexes.some((index) => coversAll3(index) && index.parts.every((part) => part.kind === "column") && sortedColumns3(index) === wanted);
|
|
1177
1904
|
};
|
|
1178
1905
|
var refOf = (row, context) => {
|
|
1179
1906
|
const source = context.relations.get(row.tableId);
|
|
@@ -1182,14 +1909,14 @@ var refOf = (row, context) => {
|
|
|
1182
1909
|
if (!source || !target || !table)
|
|
1183
1910
|
return;
|
|
1184
1911
|
const columns = row.columns.map((position) => context.columnName(source.id, position));
|
|
1185
|
-
const onDelete =
|
|
1186
|
-
const onUpdate =
|
|
1912
|
+
const onDelete = ACTIONS3[row.onDelete];
|
|
1913
|
+
const onUpdate = ACTIONS3[row.onUpdate];
|
|
1187
1914
|
const ref = {
|
|
1188
1915
|
from: { columns, ...inSchema2(source.schema), table: source.name },
|
|
1189
1916
|
...row.name === defaultName(row, source.name, columns) ? {} : { name: row.name },
|
|
1190
1917
|
...onDelete ? { onDelete } : {},
|
|
1191
1918
|
...onUpdate ? { onUpdate } : {},
|
|
1192
|
-
relation:
|
|
1919
|
+
relation: isUniqueSet3(table, columns) ? "-" : ">",
|
|
1193
1920
|
to: {
|
|
1194
1921
|
columns: row.foreignColumns.map((position) => context.columnName(target.id, position)),
|
|
1195
1922
|
...inSchema2(target.schema),
|
|
@@ -1214,7 +1941,7 @@ var partOf2 = (row, index, context) => {
|
|
|
1214
1941
|
...desc
|
|
1215
1942
|
};
|
|
1216
1943
|
};
|
|
1217
|
-
var
|
|
1944
|
+
var indexOf3 = (row, context) => {
|
|
1218
1945
|
const included = row.parts.slice(row.keyCount);
|
|
1219
1946
|
const index = {
|
|
1220
1947
|
name: row.name,
|
|
@@ -1224,7 +1951,11 @@ var indexOf2 = (row, context) => {
|
|
|
1224
1951
|
...withNote(joinNotes([
|
|
1225
1952
|
row.comment,
|
|
1226
1953
|
row.predicate ? `Where ${row.predicate}` : undefined,
|
|
1227
|
-
included.length > 0 ? `Includes ${included.join(", ")}` : undefined
|
|
1954
|
+
included.length > 0 ? `Includes ${included.join(", ")}` : undefined,
|
|
1955
|
+
...indexNotes2(row, (part) => {
|
|
1956
|
+
const position = row.attnums[part] ?? 0;
|
|
1957
|
+
return position > 0 ? context.columnName(row.tableId, position) : row.parts[part] ?? "";
|
|
1958
|
+
})
|
|
1228
1959
|
]))
|
|
1229
1960
|
};
|
|
1230
1961
|
return index;
|
|
@@ -1239,7 +1970,7 @@ var policyLine2 = (row) => [
|
|
|
1239
1970
|
].filter((part) => part !== undefined).join(" ");
|
|
1240
1971
|
var MAX_DEFINITION = 600;
|
|
1241
1972
|
var kindLine = (relation) => {
|
|
1242
|
-
const kind =
|
|
1973
|
+
const kind = KINDS2[relation.kind];
|
|
1243
1974
|
const definition = relation.definition?.trim();
|
|
1244
1975
|
if (!kind || !definition)
|
|
1245
1976
|
return kind;
|
|
@@ -1247,10 +1978,11 @@ var kindLine = (relation) => {
|
|
|
1247
1978
|
return `${kind}:
|
|
1248
1979
|
${shown}`;
|
|
1249
1980
|
};
|
|
1250
|
-
var tableNote2 = (relation, policies) => joinNotes([
|
|
1981
|
+
var tableNote2 = (relation, policies, extra) => joinNotes([
|
|
1251
1982
|
relation.comment,
|
|
1252
1983
|
kindLine(relation),
|
|
1253
|
-
relation.partitionKey ? `Partitioned by ${relation.partitionKey}
|
|
1984
|
+
relation.partitionKey ? `Partitioned by ${relation.partitionKey}` : undefined,
|
|
1985
|
+
...extra,
|
|
1254
1986
|
relation.rls ? `Row-level security is on${relation.forceRls ? ", for the owner too" : ""}` : undefined,
|
|
1255
1987
|
...policies.map(policyLine2)
|
|
1256
1988
|
]);
|
|
@@ -1282,16 +2014,23 @@ var readRecords = (query, tables, limit) => Promise.all(tables.map(async (table)
|
|
|
1282
2014
|
};
|
|
1283
2015
|
return records;
|
|
1284
2016
|
}));
|
|
1285
|
-
var tableOf2 = (relation,
|
|
2017
|
+
var tableOf2 = (relation, catalogs, statistics) => {
|
|
2018
|
+
const own = (rows) => rows.filter((row) => row.tableId === relation.id);
|
|
1286
2019
|
const view = relation.kind === "v" || relation.kind === "m";
|
|
1287
2020
|
const table = {
|
|
1288
2021
|
checks: [],
|
|
1289
|
-
columns:
|
|
1290
|
-
...view ? { headerColor:
|
|
2022
|
+
columns: own(catalogs.columns).map(columnOf3),
|
|
2023
|
+
...view ? { headerColor: VIEW_COLOR3 } : {},
|
|
1291
2024
|
indexes: [],
|
|
1292
2025
|
name: relation.name,
|
|
1293
2026
|
...inSchema2(relation.schema),
|
|
1294
|
-
...
|
|
2027
|
+
...tableMetadata2(relation, statistics),
|
|
2028
|
+
...withNote(tableNote2(relation, own(catalogs.policies), tableNoteLines({
|
|
2029
|
+
...relation.inherits ? { inherits: relation.inherits } : {},
|
|
2030
|
+
partitions: own(catalogs.partitions),
|
|
2031
|
+
rules: own(catalogs.rules),
|
|
2032
|
+
triggers: own(catalogs.triggers)
|
|
2033
|
+
})))
|
|
1295
2034
|
};
|
|
1296
2035
|
return table;
|
|
1297
2036
|
};
|
|
@@ -1315,9 +2054,9 @@ var applyConstraints = (rows, context) => rows.filter((row) => {
|
|
|
1315
2054
|
});
|
|
1316
2055
|
return false;
|
|
1317
2056
|
});
|
|
1318
|
-
var sequenceNote = (rows) => ({
|
|
2057
|
+
var sequenceNote = (rows, defaultSchema) => ({
|
|
1319
2058
|
content: `Sequences
|
|
1320
|
-
${rows.map((row) => `${row.schema ===
|
|
2059
|
+
${rows.map((row) => `${row.schema === defaultSchema ? "" : `${row.schema}.`}${row.name}: start ${row.start}, increment ${row.increment}`).join(`
|
|
1321
2060
|
`)}`,
|
|
1322
2061
|
name: "sequences"
|
|
1323
2062
|
});
|
|
@@ -1332,7 +2071,16 @@ var readCatalogs = async (query, schemas) => {
|
|
|
1332
2071
|
sources,
|
|
1333
2072
|
policies,
|
|
1334
2073
|
sequences,
|
|
1335
|
-
comments
|
|
2074
|
+
comments,
|
|
2075
|
+
triggers,
|
|
2076
|
+
rules,
|
|
2077
|
+
functions,
|
|
2078
|
+
domains,
|
|
2079
|
+
composites,
|
|
2080
|
+
partitions,
|
|
2081
|
+
viewColumns,
|
|
2082
|
+
extensions,
|
|
2083
|
+
eventTriggers
|
|
1336
2084
|
] = await Promise.all([
|
|
1337
2085
|
read(ENUMS),
|
|
1338
2086
|
read(RELATIONS),
|
|
@@ -1342,34 +2090,59 @@ var readCatalogs = async (query, schemas) => {
|
|
|
1342
2090
|
read(VIEW_SOURCES),
|
|
1343
2091
|
read(POLICIES),
|
|
1344
2092
|
read(SEQUENCES),
|
|
1345
|
-
read(SCHEMA_COMMENTS)
|
|
2093
|
+
read(SCHEMA_COMMENTS),
|
|
2094
|
+
read(TRIGGERS),
|
|
2095
|
+
read(RULES),
|
|
2096
|
+
read(FUNCTIONS),
|
|
2097
|
+
read(DOMAINS),
|
|
2098
|
+
read(COMPOSITES),
|
|
2099
|
+
read(PARTITIONS),
|
|
2100
|
+
read(VIEW_COLUMNS),
|
|
2101
|
+
query(EXTENSIONS, []),
|
|
2102
|
+
query(EVENT_TRIGGERS, [])
|
|
1346
2103
|
]);
|
|
1347
2104
|
return {
|
|
1348
2105
|
columns: columns.map(columnRow),
|
|
1349
2106
|
comments: comments.map(namedRow),
|
|
2107
|
+
composites: composites.map(compositeRow),
|
|
1350
2108
|
constraints: constraints.map(constraintRow),
|
|
2109
|
+
domains: domains.map(domainRow),
|
|
1351
2110
|
enums: enums.map(enumRow),
|
|
2111
|
+
eventTriggers: eventTriggers.map(eventTriggerRow),
|
|
2112
|
+
extensions: extensions.map(extensionRow),
|
|
2113
|
+
functions: functions.map(functionRow),
|
|
1352
2114
|
indexes: indexes.map(indexRow),
|
|
2115
|
+
partitions: partitions.map(partitionRow),
|
|
1353
2116
|
policies: policies.map(policyRow),
|
|
1354
2117
|
relations: relations.map(relationRow),
|
|
2118
|
+
rules: rules.map(definitionRow),
|
|
1355
2119
|
sequences: sequences.map(sequenceRow),
|
|
1356
|
-
sources: sources.map(viewSourceRow)
|
|
2120
|
+
sources: sources.map(viewSourceRow),
|
|
2121
|
+
triggers: triggers.map(definitionRow),
|
|
2122
|
+
viewColumns: viewColumns.map(viewColumnRow)
|
|
1357
2123
|
};
|
|
1358
2124
|
};
|
|
1359
2125
|
var schemasToRead = async (query, schemas) => schemas ?? (await query(SCHEMAS, [])).map((row) => namedRow(row).name);
|
|
1360
2126
|
var addDeps = (model, catalogs, relations) => catalogs.sources.forEach((row) => {
|
|
1361
2127
|
const view = relations.get(row.viewId);
|
|
1362
2128
|
const source = relations.get(row.sourceId);
|
|
1363
|
-
if (view
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
}
|
|
2129
|
+
if (!view || !source)
|
|
2130
|
+
return;
|
|
2131
|
+
const columns = catalogs.viewColumns.filter((entry) => entry.viewId === row.viewId && entry.sourceId === row.sourceId).map((entry) => entry.name);
|
|
2132
|
+
model.deps.push({
|
|
2133
|
+
downstream: { ...inSchema2(view.schema), table: view.name },
|
|
2134
|
+
upstream: {
|
|
2135
|
+
...columns.length > 0 ? { columns } : {},
|
|
2136
|
+
...inSchema2(source.schema),
|
|
2137
|
+
table: source.name
|
|
2138
|
+
}
|
|
2139
|
+
});
|
|
1368
2140
|
});
|
|
1369
|
-
var addNotes2 = (model, catalogs) => {
|
|
2141
|
+
var addNotes2 = (model, catalogs, defaultSchema) => {
|
|
1370
2142
|
if (catalogs.sequences.length > 0)
|
|
1371
|
-
model.notes.push(sequenceNote(catalogs.sequences));
|
|
1372
|
-
|
|
2143
|
+
model.notes.push(sequenceNote(catalogs.sequences, defaultSchema));
|
|
2144
|
+
model.notes.push(...extraNotes(catalogs, defaultSchema));
|
|
2145
|
+
const described = catalogs.comments.filter((row) => row.comment !== undefined && row.name !== defaultSchema);
|
|
1373
2146
|
if (described.length > 0)
|
|
1374
2147
|
model.notes.push({
|
|
1375
2148
|
content: `Schemas
|
|
@@ -1396,7 +2169,7 @@ var fromPostgres = async (query, options = {}) => {
|
|
|
1396
2169
|
]));
|
|
1397
2170
|
const tables = new Map(catalogs.relations.map((row) => [
|
|
1398
2171
|
row.id,
|
|
1399
|
-
tableOf2(row, catalogs
|
|
2172
|
+
tableOf2(row, catalogs, options.statistics === true)
|
|
1400
2173
|
]));
|
|
1401
2174
|
const context = {
|
|
1402
2175
|
relations,
|
|
@@ -1404,21 +2177,25 @@ var fromPostgres = async (query, options = {}) => {
|
|
|
1404
2177
|
columnName: (tableId, position) => names.get(`${tableId}:${position}`) ?? `${position}`
|
|
1405
2178
|
};
|
|
1406
2179
|
const foreign = applyConstraints(catalogs.constraints, context);
|
|
1407
|
-
catalogs.indexes.forEach((row) => tables.get(row.tableId)?.indexes.push(
|
|
2180
|
+
catalogs.indexes.forEach((row) => tables.get(row.tableId)?.indexes.push(indexOf3(row, context)));
|
|
1408
2181
|
model.tables.push(...tables.values());
|
|
1409
2182
|
model.refs.push(...foreign.map((row) => refOf(row, context)).filter((ref) => ref !== undefined));
|
|
1410
2183
|
addDeps(model, catalogs, relations);
|
|
1411
|
-
|
|
2184
|
+
const defaultSchema = options.defaultSchema ?? DEFAULT_SCHEMA;
|
|
2185
|
+
addNotes2(model, catalogs, defaultSchema);
|
|
1412
2186
|
const limit = options.records?.limit ?? 0;
|
|
1413
2187
|
if (limit > 0)
|
|
1414
2188
|
model.records.push(...await readRecords(query, model.tables.filter((table) => !table.headerColor), limit));
|
|
1415
|
-
|
|
2189
|
+
const result = withDefaultSchema(model, defaultSchema);
|
|
2190
|
+
if (options.groups === "schema")
|
|
2191
|
+
result.tableGroups.push(...groupBySchema(result.tables, defaultSchema));
|
|
2192
|
+
return result;
|
|
1416
2193
|
};
|
|
1417
2194
|
|
|
1418
2195
|
// src/print.ts
|
|
1419
2196
|
var INDENT = " ";
|
|
1420
2197
|
var quoteName = (name) => `"${name.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
|
|
1421
|
-
var
|
|
2198
|
+
var qualified2 = (schema, name) => schema ? `${quoteName(schema)}.${quoteName(name)}` : quoteName(name);
|
|
1422
2199
|
var quoteText = (text) => {
|
|
1423
2200
|
const escaped = text.replaceAll("\\", "\\\\").replaceAll(`\r
|
|
1424
2201
|
`, `
|
|
@@ -1483,7 +2260,7 @@ ${lines.map((line) => `${pad}${line}`).join(`
|
|
|
1483
2260
|
${INDENT.repeat(depth - 1)}}`;
|
|
1484
2261
|
};
|
|
1485
2262
|
var printTable = (table) => {
|
|
1486
|
-
const head = `Table ${
|
|
2263
|
+
const head = `Table ${qualified2(table.schema, table.name)}${table.alias ? ` as ${quoteName(table.alias)}` : ""}${settings([
|
|
1487
2264
|
table.headerColor !== undefined && `headerColor: ${table.headerColor}`
|
|
1488
2265
|
])}`;
|
|
1489
2266
|
const body = table.columns.map(printColumn);
|
|
@@ -1502,12 +2279,12 @@ ${[lines.join(`
|
|
|
1502
2279
|
`)}
|
|
1503
2280
|
}`;
|
|
1504
2281
|
};
|
|
1505
|
-
var printEnum = (entry) => block(`Enum ${
|
|
2282
|
+
var printEnum = (entry) => block(`Enum ${qualified2(entry.schema, entry.name)}`, entry.values.map((value) => `${quoteName(value.name)}${settings([
|
|
1506
2283
|
value.note !== undefined && `note: ${quoteText(value.note)}`
|
|
1507
2284
|
])}`));
|
|
1508
2285
|
var printEndpoint = (endpoint) => {
|
|
1509
2286
|
const columns = endpoint.columns.length === 1 ? quoteName(endpoint.columns[0] ?? "") : `(${endpoint.columns.map(quoteName).join(", ")})`;
|
|
1510
|
-
return `${
|
|
2287
|
+
return `${qualified2(endpoint.schema, endpoint.table)}.${columns}`;
|
|
1511
2288
|
};
|
|
1512
2289
|
var printRef = (ref) => `Ref${ref.name === undefined ? "" : ` ${quoteName(ref.name)}`}: ${printEndpoint(ref.from)} ${ref.relation} ${printEndpoint(ref.to)}${settings([
|
|
1513
2290
|
ref.onDelete !== undefined && `delete: ${ref.onDelete}`,
|
|
@@ -1516,22 +2293,32 @@ var printRef = (ref) => `Ref${ref.name === undefined ? "" : ` ${quoteName(ref.na
|
|
|
1516
2293
|
ref.inactive && "inactive",
|
|
1517
2294
|
ref.note !== undefined && `note: ${quoteText(ref.note)}`
|
|
1518
2295
|
])}`;
|
|
1519
|
-
var printDepEnd = (end) => {
|
|
1520
|
-
const table =
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
2296
|
+
var printDepEnd = (end, column) => {
|
|
2297
|
+
const table = qualified2(end.schema, end.table);
|
|
2298
|
+
return column === undefined ? table : `${table}.${quoteName(column)}`;
|
|
2299
|
+
};
|
|
2300
|
+
var depEdges = (dep) => {
|
|
2301
|
+
const upstream = dep.upstream.columns ?? [];
|
|
2302
|
+
const downstream = dep.downstream.columns ?? [];
|
|
2303
|
+
if (upstream.length <= 1 && downstream.length <= 1)
|
|
2304
|
+
return [
|
|
2305
|
+
`${printDepEnd(dep.upstream, upstream[0])} -> ${printDepEnd(dep.downstream, downstream[0])}`
|
|
2306
|
+
];
|
|
2307
|
+
return upstream.map((column, index) => `${printDepEnd(dep.upstream, column)} -> ${printDepEnd(dep.downstream, downstream[index])}`);
|
|
1524
2308
|
};
|
|
1525
2309
|
var printDep = (dep) => {
|
|
1526
|
-
const
|
|
1527
|
-
if (dep.note === undefined)
|
|
1528
|
-
return `Dep: ${
|
|
1529
|
-
return block("Dep", [
|
|
2310
|
+
const edges = depEdges(dep);
|
|
2311
|
+
if (dep.note === undefined && edges.length === 1)
|
|
2312
|
+
return `Dep: ${edges[0] ?? ""}`;
|
|
2313
|
+
return block("Dep", [
|
|
2314
|
+
...edges,
|
|
2315
|
+
...dep.note === undefined ? [] : ["", `note: ${quoteText(dep.note)}`]
|
|
2316
|
+
]);
|
|
1530
2317
|
};
|
|
1531
2318
|
var printGroup = (group) => block(`TableGroup ${quoteName(group.name)}${settings([
|
|
1532
2319
|
group.color !== undefined && `color: ${group.color}`
|
|
1533
2320
|
])}`, [
|
|
1534
|
-
...group.tables.map((entry) =>
|
|
2321
|
+
...group.tables.map((entry) => qualified2(entry.schema, entry.table)),
|
|
1535
2322
|
...group.note === undefined ? [] : [`Note: ${quoteText(group.note)}`]
|
|
1536
2323
|
]);
|
|
1537
2324
|
var printNote = (note) => block(`Note ${quoteName(note.name)}${settings([
|
|
@@ -1544,11 +2331,28 @@ var printValue = (value) => {
|
|
|
1544
2331
|
return `${value}`;
|
|
1545
2332
|
return quoteText(value);
|
|
1546
2333
|
};
|
|
1547
|
-
var printRecords = (records) => block(`Records ${
|
|
2334
|
+
var printRecords = (records) => block(`Records ${qualified2(records.schema, records.table)}(${records.columns.map(quoteName).join(", ")})`, records.rows.map((row) => row.map(printValue).join(", ")));
|
|
1548
2335
|
var printProject = (project) => block(`Project${project.name ? ` ${quoteName(project.name)}` : ""}`, [
|
|
1549
2336
|
...project.databaseType === undefined ? [] : [`database_type: ${quoteText(project.databaseType)}`],
|
|
1550
2337
|
...project.note === undefined ? [] : [`Note: ${quoteText(project.note)}`]
|
|
1551
2338
|
]);
|
|
2339
|
+
var printMetadataValue = (value) => typeof value === "string" ? quoteText(value) : `${value}`;
|
|
2340
|
+
var metadataKey = (key) => key.replace(/[^A-Za-z0-9_]/gu, "_");
|
|
2341
|
+
var metadataBlock = (title, metadata) => {
|
|
2342
|
+
const entries = Object.entries(metadata ?? {});
|
|
2343
|
+
if (entries.length === 0)
|
|
2344
|
+
return [];
|
|
2345
|
+
return [
|
|
2346
|
+
block(`Metadata ${title}`, entries.map(([key, value]) => `${metadataKey(key)}: ${printMetadataValue(value)}`))
|
|
2347
|
+
];
|
|
2348
|
+
};
|
|
2349
|
+
var printMetadata = (tables) => tables.flatMap((table) => {
|
|
2350
|
+
const name = qualified2(table.schema, table.name);
|
|
2351
|
+
return [
|
|
2352
|
+
...metadataBlock(`Table ${name}`, table.metadata),
|
|
2353
|
+
...table.columns.flatMap((column) => metadataBlock(`Column ${name}.${quoteName(column.name)}`, column.metadata))
|
|
2354
|
+
];
|
|
2355
|
+
});
|
|
1552
2356
|
var printDbml = (model) => {
|
|
1553
2357
|
const { project } = model;
|
|
1554
2358
|
const hasProject = project !== undefined && (project.name !== undefined || project.databaseType !== undefined || project.note !== undefined);
|
|
@@ -1562,7 +2366,8 @@ var printDbml = (model) => {
|
|
|
1562
2366
|
...model.deps.length > 0 ? [model.deps.map(printDep).join(`
|
|
1563
2367
|
`)] : [],
|
|
1564
2368
|
...model.notes.map(printNote),
|
|
1565
|
-
...model.records.filter((records) => records.rows.length > 0).map(printRecords)
|
|
2369
|
+
...model.records.filter((records) => records.rows.length > 0).map(printRecords),
|
|
2370
|
+
...printMetadata(model.tables)
|
|
1566
2371
|
];
|
|
1567
2372
|
return `${sections.join(`
|
|
1568
2373
|
|
|
@@ -1570,10 +2375,353 @@ var printDbml = (model) => {
|
|
|
1570
2375
|
`;
|
|
1571
2376
|
};
|
|
1572
2377
|
|
|
2378
|
+
// src/sqlite/text.ts
|
|
2379
|
+
var CLOSERS = {
|
|
2380
|
+
"'": "'",
|
|
2381
|
+
'"': '"',
|
|
2382
|
+
"[": "]",
|
|
2383
|
+
"`": "`"
|
|
2384
|
+
};
|
|
2385
|
+
var pastQuote = (text, start) => {
|
|
2386
|
+
const close = CLOSERS[text[start] ?? ""] ?? "";
|
|
2387
|
+
let index = start + 1;
|
|
2388
|
+
while (index < text.length) {
|
|
2389
|
+
if (text[index] === close && text[index + 1] === close && close !== "]")
|
|
2390
|
+
index += 2;
|
|
2391
|
+
else if (text[index] === close)
|
|
2392
|
+
return index + 1;
|
|
2393
|
+
else
|
|
2394
|
+
index += 1;
|
|
2395
|
+
}
|
|
2396
|
+
return text.length;
|
|
2397
|
+
};
|
|
2398
|
+
var DEPTH = { "(": 1, ")": -1 };
|
|
2399
|
+
var unquoted = (text, from) => {
|
|
2400
|
+
const marks = [];
|
|
2401
|
+
let depth = 0;
|
|
2402
|
+
let index = from;
|
|
2403
|
+
while (index < text.length) {
|
|
2404
|
+
const character = text[index] ?? "";
|
|
2405
|
+
const quoted = character in CLOSERS;
|
|
2406
|
+
depth += quoted ? 0 : DEPTH[character] ?? 0;
|
|
2407
|
+
if (!quoted)
|
|
2408
|
+
marks.push({ character, depth, index });
|
|
2409
|
+
index = quoted ? pastQuote(text, index) : index + 1;
|
|
2410
|
+
}
|
|
2411
|
+
return marks;
|
|
2412
|
+
};
|
|
2413
|
+
var bracketed = (text, open) => {
|
|
2414
|
+
const end = unquoted(text, open).find((mark) => mark.character === ")" && mark.depth === 0);
|
|
2415
|
+
return end ? { close: end.index, inner: text.slice(open + 1, end.index) } : undefined;
|
|
2416
|
+
};
|
|
2417
|
+
var topLevel = (text) => {
|
|
2418
|
+
const commas = unquoted(text, 0).filter((mark) => mark.character === "," && mark.depth === 0).map((mark) => mark.index);
|
|
2419
|
+
const bounds = [-1, ...commas, text.length];
|
|
2420
|
+
return bounds.slice(1).map((bound, position) => text.slice((bounds[position] ?? -1) + 1, bound).trim()).filter((part) => part !== "");
|
|
2421
|
+
};
|
|
2422
|
+
var unquote = (name) => {
|
|
2423
|
+
const trimmed = name.trim();
|
|
2424
|
+
const first = trimmed[0] ?? "";
|
|
2425
|
+
if (!(first in CLOSERS))
|
|
2426
|
+
return trimmed;
|
|
2427
|
+
const close = CLOSERS[first] ?? "";
|
|
2428
|
+
return trimmed.slice(1, -1).replaceAll(close + close, close);
|
|
2429
|
+
};
|
|
2430
|
+
var leadingName = (definition) => {
|
|
2431
|
+
const first = definition[0] ?? "";
|
|
2432
|
+
if (first in CLOSERS)
|
|
2433
|
+
return definition.slice(0, pastQuote(definition, 0));
|
|
2434
|
+
return /^[^\s(]+/u.exec(definition)?.[0] ?? "";
|
|
2435
|
+
};
|
|
2436
|
+
var afterKeyword = (text, keyword) => {
|
|
2437
|
+
const match = keyword.exec(text);
|
|
2438
|
+
if (!match)
|
|
2439
|
+
return;
|
|
2440
|
+
const open = text.indexOf("(", match.index + match[0].length - 1);
|
|
2441
|
+
return open === -1 ? undefined : bracketed(text, open);
|
|
2442
|
+
};
|
|
2443
|
+
var checksIn = (definition) => {
|
|
2444
|
+
const checks = [];
|
|
2445
|
+
const pattern = /(?:\bCONSTRAINT\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\S+)\s+)?\bCHECK\s*\(/giu;
|
|
2446
|
+
let match = pattern.exec(definition);
|
|
2447
|
+
while (match) {
|
|
2448
|
+
const open = match.index + match[0].length - 1;
|
|
2449
|
+
const found = bracketed(definition, open);
|
|
2450
|
+
if (found)
|
|
2451
|
+
checks.push({
|
|
2452
|
+
expression: found.inner.trim(),
|
|
2453
|
+
...match[1] ? { name: unquote(match[1]) } : {}
|
|
2454
|
+
});
|
|
2455
|
+
pattern.lastIndex = (found?.close ?? open) + 1;
|
|
2456
|
+
match = pattern.exec(definition);
|
|
2457
|
+
}
|
|
2458
|
+
return checks;
|
|
2459
|
+
};
|
|
2460
|
+
|
|
2461
|
+
// src/sqlite/index.ts
|
|
2462
|
+
var text3 = (value) => {
|
|
2463
|
+
if (value === null || value === undefined)
|
|
2464
|
+
return;
|
|
2465
|
+
return typeof value === "string" ? value : `${value}`;
|
|
2466
|
+
};
|
|
2467
|
+
var integer3 = (value) => typeof value === "number" ? value : Number.parseInt(text3(value) ?? "0", 10);
|
|
2468
|
+
var VIEW_COLOR4 = "#64748b";
|
|
2469
|
+
var ACTIONS4 = {
|
|
2470
|
+
CASCADE: "cascade",
|
|
2471
|
+
"NO ACTION": undefined,
|
|
2472
|
+
RESTRICT: "restrict",
|
|
2473
|
+
"SET DEFAULT": "set default",
|
|
2474
|
+
"SET NULL": "set null"
|
|
2475
|
+
};
|
|
2476
|
+
var NUMBER3 = /^-?\d+(\.\d+)?$/u;
|
|
2477
|
+
var QUOTED2 = /^'((?:[^']|'')*)'$/u;
|
|
2478
|
+
var defaultOf3 = (raw) => {
|
|
2479
|
+
if (/^null$/iu.test(raw))
|
|
2480
|
+
return { kind: "null" };
|
|
2481
|
+
if (/^(true|false)$/iu.test(raw))
|
|
2482
|
+
return {
|
|
2483
|
+
kind: "boolean",
|
|
2484
|
+
value: raw.toLowerCase() === "true"
|
|
2485
|
+
};
|
|
2486
|
+
if (NUMBER3.test(raw) && Number.isSafeInteger(Math.trunc(Number.parseFloat(raw))))
|
|
2487
|
+
return {
|
|
2488
|
+
kind: "number",
|
|
2489
|
+
value: Number.parseFloat(raw)
|
|
2490
|
+
};
|
|
2491
|
+
const [, quoted] = QUOTED2.exec(raw) ?? [];
|
|
2492
|
+
if (quoted !== undefined)
|
|
2493
|
+
return {
|
|
2494
|
+
kind: "string",
|
|
2495
|
+
value: quoted.replaceAll("''", "'")
|
|
2496
|
+
};
|
|
2497
|
+
const inner = raw.startsWith("(") && raw.endsWith(")") ? raw.slice(1, -1) : raw;
|
|
2498
|
+
return { kind: "expression", value: inner };
|
|
2499
|
+
};
|
|
2500
|
+
var definitionsOf = (sql) => {
|
|
2501
|
+
const open = sql.indexOf("(");
|
|
2502
|
+
const body = open === -1 ? undefined : bracketed(sql, open);
|
|
2503
|
+
const parts = body ? topLevel(body.inner) : [];
|
|
2504
|
+
const constraint = /^(CONSTRAINT|PRIMARY|UNIQUE|CHECK|FOREIGN)\b/iu;
|
|
2505
|
+
return {
|
|
2506
|
+
body: body?.inner ?? "",
|
|
2507
|
+
columns: new Map(parts.filter((part) => !constraint.test(part)).map((part) => [unquote(leadingName(part)).toLowerCase(), part])),
|
|
2508
|
+
suffix: body ? sql.slice(body.close + 1) : ""
|
|
2509
|
+
};
|
|
2510
|
+
};
|
|
2511
|
+
var collationOf = (definition) => {
|
|
2512
|
+
const name = /\bCOLLATE\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/iu.exec(definition)?.[1];
|
|
2513
|
+
return name && name.toUpperCase() !== "BINARY" ? unquote(name) : undefined;
|
|
2514
|
+
};
|
|
2515
|
+
var columnInfo = (row) => {
|
|
2516
|
+
const info = {
|
|
2517
|
+
cid: integer3(row.cid),
|
|
2518
|
+
...text3(row.dflt_value) === undefined ? {} : { default: text3(row.dflt_value) ?? "" },
|
|
2519
|
+
hidden: integer3(row.hidden),
|
|
2520
|
+
name: text3(row.name) ?? "",
|
|
2521
|
+
notNull: integer3(row.notnull) === 1,
|
|
2522
|
+
pk: integer3(row.pk),
|
|
2523
|
+
type: text3(row.type) ?? ""
|
|
2524
|
+
};
|
|
2525
|
+
return info;
|
|
2526
|
+
};
|
|
2527
|
+
var GENERATED = { 2: "virtual", 3: "stored" };
|
|
2528
|
+
var columnOf4 = (info, definition, rowidKey) => {
|
|
2529
|
+
const generated = GENERATED[info.hidden];
|
|
2530
|
+
const expression = generated ? afterKeyword(definition, /\bAS\s*\(/iu)?.inner.trim() : undefined;
|
|
2531
|
+
const collation = collationOf(definition);
|
|
2532
|
+
const metadata = collation ? { collation } : {};
|
|
2533
|
+
const notes = [
|
|
2534
|
+
generated ? `Generated always as (${expression ?? "\u2026"}), ${generated}` : undefined,
|
|
2535
|
+
/\bAUTOINCREMENT\b/iu.test(definition) ? "AUTOINCREMENT: ids are never reused" : undefined
|
|
2536
|
+
].filter((line) => line !== undefined);
|
|
2537
|
+
const column = {
|
|
2538
|
+
name: info.name,
|
|
2539
|
+
type: info.type === "" ? "any" : info.type.toLowerCase(),
|
|
2540
|
+
...info.pk > 0 && rowidKey ? { increment: true, pk: true } : {},
|
|
2541
|
+
...info.pk > 0 && !rowidKey && !generated ? {} : {},
|
|
2542
|
+
...info.notNull && info.pk === 0 ? { notNull: true } : {},
|
|
2543
|
+
...info.default !== undefined && !generated ? { default: defaultOf3(info.default) } : {},
|
|
2544
|
+
...Object.keys(metadata).length > 0 ? { metadata } : {},
|
|
2545
|
+
...notes.length > 0 ? { note: notes.join(`
|
|
2546
|
+
`) } : {}
|
|
2547
|
+
};
|
|
2548
|
+
return column;
|
|
2549
|
+
};
|
|
2550
|
+
var NO_PARTS = { parts: [] };
|
|
2551
|
+
var indexPartsText = (sql) => {
|
|
2552
|
+
if (!sql)
|
|
2553
|
+
return NO_PARTS;
|
|
2554
|
+
const target = /\bON\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\S+?)\s*\(/iu.exec(sql);
|
|
2555
|
+
if (!target)
|
|
2556
|
+
return NO_PARTS;
|
|
2557
|
+
const found = bracketed(sql, target.index + target[0].length - 1);
|
|
2558
|
+
const where = found ? /\bWHERE\s+([\s\S]+)$/iu.exec(sql.slice(found.close + 1))?.[1]?.trim() : undefined;
|
|
2559
|
+
return { parts: found ? topLevel(found.inner) : [], where };
|
|
2560
|
+
};
|
|
2561
|
+
var indexesOf = async (read, table, sqlOf, columnCollation) => {
|
|
2562
|
+
const list = await read("select * from pragma_index_list(?)", [table]);
|
|
2563
|
+
const indexes = await Promise.all(list.filter((row) => text3(row.origin) !== "pk").map(async (row) => {
|
|
2564
|
+
const name = text3(row.name) ?? "";
|
|
2565
|
+
const parts = (await read("select * from pragma_index_xinfo(?)", [name])).filter((part) => integer3(part.key) === 1);
|
|
2566
|
+
const written = indexPartsText(sqlOf(name));
|
|
2567
|
+
const collations = parts.filter((part) => {
|
|
2568
|
+
const column = text3(part.name);
|
|
2569
|
+
const collation = text3(part.coll)?.toUpperCase();
|
|
2570
|
+
return column !== undefined && collation !== undefined && collation !== columnCollation(column);
|
|
2571
|
+
}).map((part) => `${text3(part.name)} ${text3(part.coll)}`);
|
|
2572
|
+
const index = {
|
|
2573
|
+
parts: parts.map((part, position) => {
|
|
2574
|
+
const desc = integer3(part.desc) === 1 ? { desc: true } : {};
|
|
2575
|
+
const column = text3(part.name);
|
|
2576
|
+
const entry = integer3(part.cid) >= 0 && column ? { column, kind: "column", ...desc } : {
|
|
2577
|
+
expression: (written.parts[position] ?? "").replace(/\s+(ASC|DESC)$/iu, ""),
|
|
2578
|
+
kind: "expression",
|
|
2579
|
+
...desc
|
|
2580
|
+
};
|
|
2581
|
+
return entry;
|
|
2582
|
+
}),
|
|
2583
|
+
...integer3(row.unique) === 1 ? { unique: true } : {},
|
|
2584
|
+
...name.startsWith("sqlite_autoindex_") ? {} : { name },
|
|
2585
|
+
...(() => {
|
|
2586
|
+
const lines = [
|
|
2587
|
+
written.where && integer3(row.partial) === 1 ? `Where ${written.where}` : undefined,
|
|
2588
|
+
collations.length > 0 ? `Collation: ${collations.join(", ")}` : undefined
|
|
2589
|
+
].filter((line) => line !== undefined);
|
|
2590
|
+
return lines.length > 0 ? { note: lines.join(`
|
|
2591
|
+
`) } : {};
|
|
2592
|
+
})()
|
|
2593
|
+
};
|
|
2594
|
+
return { index, origin: text3(row.origin) ?? "c" };
|
|
2595
|
+
}));
|
|
2596
|
+
return indexes;
|
|
2597
|
+
};
|
|
2598
|
+
var foreignKeysOf = async (read, table) => {
|
|
2599
|
+
const rows = await read("select * from pragma_foreign_key_list(?)", [
|
|
2600
|
+
table.name
|
|
2601
|
+
]);
|
|
2602
|
+
const groups = new Map;
|
|
2603
|
+
rows.forEach((row) => groups.set(integer3(row.id), [
|
|
2604
|
+
...groups.get(integer3(row.id)) ?? [],
|
|
2605
|
+
row
|
|
2606
|
+
]));
|
|
2607
|
+
return [...groups.values()].map((group) => {
|
|
2608
|
+
const [first] = group;
|
|
2609
|
+
const columns = group.map((row) => text3(row.from) ?? "");
|
|
2610
|
+
const onDelete = ACTIONS4[text3(first?.on_delete) ?? ""];
|
|
2611
|
+
const onUpdate = ACTIONS4[text3(first?.on_update) ?? ""];
|
|
2612
|
+
const ref = {
|
|
2613
|
+
from: { columns, table: table.name },
|
|
2614
|
+
...onDelete ? { onDelete } : {},
|
|
2615
|
+
...onUpdate ? { onUpdate } : {},
|
|
2616
|
+
relation: isUniqueSet(table, columns) ? "-" : ">",
|
|
2617
|
+
to: {
|
|
2618
|
+
columns: group.map((row) => text3(row.to) ?? ""),
|
|
2619
|
+
table: text3(first?.table) ?? ""
|
|
2620
|
+
}
|
|
2621
|
+
};
|
|
2622
|
+
return ref;
|
|
2623
|
+
});
|
|
2624
|
+
};
|
|
2625
|
+
var quoteIdent2 = (name) => `"${name.replaceAll('"', '""')}"`;
|
|
2626
|
+
var placeIndex2 = (table, index, origin) => {
|
|
2627
|
+
const [part] = index.parts;
|
|
2628
|
+
const single = index.parts.length === 1 && part?.kind === "column" && origin === "u";
|
|
2629
|
+
const column = single ? table.columns.find((own) => own.name === part.column) : undefined;
|
|
2630
|
+
if (column)
|
|
2631
|
+
column.unique = true;
|
|
2632
|
+
else
|
|
2633
|
+
table.indexes.push(index);
|
|
2634
|
+
};
|
|
2635
|
+
var tableOf3 = async (read, entry, context) => {
|
|
2636
|
+
const name = text3(entry.name) ?? "";
|
|
2637
|
+
const view = text3(entry.type) === "view";
|
|
2638
|
+
const sql = text3(entry.sql) ?? "";
|
|
2639
|
+
const definitions = definitionsOf(sql);
|
|
2640
|
+
const info = (await read("select * from pragma_table_xinfo(?)", [name])).map(columnInfo);
|
|
2641
|
+
const keyed = info.filter((column) => column.pk > 0).sort((left, right) => left.pk - right.pk);
|
|
2642
|
+
const [onlyKey] = keyed;
|
|
2643
|
+
const rowidKey = keyed.length === 1 && onlyKey?.type.toUpperCase() === "INTEGER";
|
|
2644
|
+
const tableEntry = context.listed.find((row) => row.name === name);
|
|
2645
|
+
const rows = context.statistics && !view ? integer3((await read(`select count(*) as total from ${quoteIdent2(name)}`))[0]?.total) : undefined;
|
|
2646
|
+
const metadata = {
|
|
2647
|
+
...integer3(tableEntry?.strict) === 1 ? { strict: true } : {},
|
|
2648
|
+
...integer3(tableEntry?.wr) === 1 ? { without_rowid: true } : {},
|
|
2649
|
+
...rows === undefined ? {} : { rows }
|
|
2650
|
+
};
|
|
2651
|
+
const own = context.triggers.filter((row) => row.tbl_name === name);
|
|
2652
|
+
const noteLines = [
|
|
2653
|
+
view ? `View:
|
|
2654
|
+
${sql.replace(/^CREATE\s+(TEMP\s+|TEMPORARY\s+)?VIEW\s+\S+\s+AS\s+/iu, "")}` : undefined,
|
|
2655
|
+
...own.map((row) => `Trigger ${(text3(row.sql) ?? "").replace(/^CREATE\s+(TEMP\s+|TEMPORARY\s+)?TRIGGER\s+(IF NOT EXISTS\s+)?/iu, "")}`)
|
|
2656
|
+
].filter((line) => line !== undefined);
|
|
2657
|
+
const table = {
|
|
2658
|
+
checks: view ? [] : checksIn(definitions.body),
|
|
2659
|
+
columns: info.map((column) => columnOf4(column, definitions.columns.get(column.name.toLowerCase()) ?? "", rowidKey && column.pk > 0)),
|
|
2660
|
+
...view ? { headerColor: VIEW_COLOR4 } : {},
|
|
2661
|
+
indexes: [],
|
|
2662
|
+
...Object.keys(metadata).length > 0 ? { metadata } : {},
|
|
2663
|
+
name,
|
|
2664
|
+
...noteLines.length > 0 ? { note: noteLines.join(`
|
|
2665
|
+
`) } : {}
|
|
2666
|
+
};
|
|
2667
|
+
if (keyed.length === 1 && !rowidKey)
|
|
2668
|
+
table.columns.forEach((column) => {
|
|
2669
|
+
if (column.name === onlyKey?.name)
|
|
2670
|
+
column.pk = true;
|
|
2671
|
+
});
|
|
2672
|
+
if (keyed.length > 1)
|
|
2673
|
+
table.indexes.push({
|
|
2674
|
+
parts: keyed.map((column) => ({
|
|
2675
|
+
column: column.name,
|
|
2676
|
+
kind: "column"
|
|
2677
|
+
})),
|
|
2678
|
+
pk: true
|
|
2679
|
+
});
|
|
2680
|
+
if (view)
|
|
2681
|
+
return table;
|
|
2682
|
+
const indexes = await indexesOf(read, name, context.sqlOf, (column) => {
|
|
2683
|
+
const collation = table.columns.find((candidate) => candidate.name === column)?.metadata?.collation;
|
|
2684
|
+
return typeof collation === "string" ? collation.toUpperCase() : "BINARY";
|
|
2685
|
+
});
|
|
2686
|
+
indexes.forEach(({ index, origin }) => placeIndex2(table, index, origin));
|
|
2687
|
+
return table;
|
|
2688
|
+
};
|
|
2689
|
+
var fromSqlite = async (query, options = {}) => {
|
|
2690
|
+
const read = async (statement, params = []) => query(statement, params);
|
|
2691
|
+
const schema = await read(`select type, name, tbl_name, sql from sqlite_schema where name not like 'sqlite_%' order by rowid`);
|
|
2692
|
+
const sqlOf = (name) => text3(schema.find((row) => row.name === name)?.sql);
|
|
2693
|
+
const listed = (await read("select * from pragma_table_list")).filter((row) => text3(row.schema) === "main" && !(text3(row.name) ?? "").startsWith("sqlite_"));
|
|
2694
|
+
const model = emptyModel({
|
|
2695
|
+
databaseType: "SQLite",
|
|
2696
|
+
...options.project
|
|
2697
|
+
});
|
|
2698
|
+
const ordered = schema.filter((row) => text3(row.type) === "table" || text3(row.type) === "view");
|
|
2699
|
+
const context = {
|
|
2700
|
+
listed,
|
|
2701
|
+
sqlOf,
|
|
2702
|
+
statistics: options.statistics === true,
|
|
2703
|
+
triggers: schema.filter((row) => text3(row.type) === "trigger")
|
|
2704
|
+
};
|
|
2705
|
+
model.tables.push(...await Promise.all(ordered.map((entry) => tableOf3(read, entry, context))));
|
|
2706
|
+
const tables = model.tables.filter((table) => !table.headerColor);
|
|
2707
|
+
const refs = await Promise.all(tables.map((table) => foreignKeysOf(read, table)));
|
|
2708
|
+
model.refs.push(...refs.flat());
|
|
2709
|
+
model.tables.filter((table) => table.headerColor).forEach((view) => {
|
|
2710
|
+
const sql = sqlOf(view.name) ?? "";
|
|
2711
|
+
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({
|
|
2712
|
+
downstream: { table: view.name },
|
|
2713
|
+
upstream: { table: table.name }
|
|
2714
|
+
}));
|
|
2715
|
+
});
|
|
2716
|
+
return model;
|
|
2717
|
+
};
|
|
2718
|
+
|
|
1573
2719
|
// src/cli.ts
|
|
1574
2720
|
var USAGE = `Usage:
|
|
1575
2721
|
absolute-dbml <schema.ts> [options] a Drizzle schema module
|
|
1576
2722
|
absolute-dbml --postgres <url> [options] a live Postgres database
|
|
2723
|
+
absolute-dbml --mysql <url> [options] a live MySQL or MariaDB database
|
|
2724
|
+
absolute-dbml --sqlite <file> [options] a SQLite database file
|
|
1577
2725
|
|
|
1578
2726
|
Options:
|
|
1579
2727
|
-o, --output <file> write to a file instead of standard output
|
|
@@ -1581,8 +2729,9 @@ Options:
|
|
|
1581
2729
|
--name <name> the project's name
|
|
1582
2730
|
--groups schema group tables by schema
|
|
1583
2731
|
--relations <name> the schema module's defineRelations export
|
|
1584
|
-
--schema <name> a schema to read (repeatable
|
|
2732
|
+
--schema <name> a schema (or MySQL database) to read (repeatable)
|
|
1585
2733
|
--records <n> each table's first n rows as Records (Postgres only)
|
|
2734
|
+
--statistics each table's row count and size, as metadata
|
|
1586
2735
|
-h, --help show this help
|
|
1587
2736
|
`;
|
|
1588
2737
|
var fail = (message) => {
|
|
@@ -1597,12 +2746,15 @@ var { positionals, values } = parseArgs({
|
|
|
1597
2746
|
groups: { type: "string" },
|
|
1598
2747
|
help: { short: "h", type: "boolean" },
|
|
1599
2748
|
json: { type: "boolean" },
|
|
2749
|
+
mysql: { type: "string" },
|
|
1600
2750
|
name: { type: "string" },
|
|
1601
2751
|
output: { short: "o", type: "string" },
|
|
1602
2752
|
postgres: { type: "string" },
|
|
1603
2753
|
records: { type: "string" },
|
|
1604
2754
|
relations: { type: "string" },
|
|
1605
|
-
schema: { multiple: true, type: "string" }
|
|
2755
|
+
schema: { multiple: true, type: "string" },
|
|
2756
|
+
sqlite: { type: "string" },
|
|
2757
|
+
statistics: { type: "boolean" }
|
|
1606
2758
|
}
|
|
1607
2759
|
});
|
|
1608
2760
|
if (values.help) {
|
|
@@ -1611,6 +2763,35 @@ if (values.help) {
|
|
|
1611
2763
|
}
|
|
1612
2764
|
var project = values.name ? { name: values.name } : undefined;
|
|
1613
2765
|
var STATEMENT_TIMEOUT = "15s";
|
|
2766
|
+
var TIMEOUT_MS = 15000;
|
|
2767
|
+
var shared = {
|
|
2768
|
+
...project ? { project } : {},
|
|
2769
|
+
...values.groups === "schema" ? { groups: "schema" } : {},
|
|
2770
|
+
...values.schema ? { schemas: values.schema } : {},
|
|
2771
|
+
...values.statistics ? { statistics: true } : {}
|
|
2772
|
+
};
|
|
2773
|
+
var readMysql = async (url) => {
|
|
2774
|
+
const client = new SQL3({ max: 1, url });
|
|
2775
|
+
try {
|
|
2776
|
+
const connection = await client.reserve();
|
|
2777
|
+
await connection.unsafe("SET SESSION TRANSACTION READ ONLY");
|
|
2778
|
+
await connection.unsafe(`SET SESSION max_execution_time = ${TIMEOUT_MS}`).catch(() => connection.unsafe(`SET SESSION max_statement_time = ${TIMEOUT_MS / 1000}`));
|
|
2779
|
+
return await fromMysql(async (text, params) => {
|
|
2780
|
+
const rows = await connection.unsafe(text, params);
|
|
2781
|
+
return [...rows];
|
|
2782
|
+
}, shared);
|
|
2783
|
+
} finally {
|
|
2784
|
+
await client.close();
|
|
2785
|
+
}
|
|
2786
|
+
};
|
|
2787
|
+
var readSqlite = async (file) => {
|
|
2788
|
+
const database = new Database(resolve(file), { readonly: true });
|
|
2789
|
+
try {
|
|
2790
|
+
return await fromSqlite((text, params) => database.query(text).all(...params.map((param) => typeof param === "number" ? param : `${param}`)), shared);
|
|
2791
|
+
} finally {
|
|
2792
|
+
database.close();
|
|
2793
|
+
}
|
|
2794
|
+
};
|
|
1614
2795
|
var readDatabase = async (url) => {
|
|
1615
2796
|
const client = new SQL3({ max: 1, url });
|
|
1616
2797
|
try {
|
|
@@ -1622,9 +2803,8 @@ var readDatabase = async (url) => {
|
|
|
1622
2803
|
const rows = await transaction.unsafe(text, params);
|
|
1623
2804
|
return rows;
|
|
1624
2805
|
}, {
|
|
1625
|
-
...
|
|
1626
|
-
...limit > 0 ? { records: { limit } } : {}
|
|
1627
|
-
...values.schema ? { schemas: values.schema } : {}
|
|
2806
|
+
...shared,
|
|
2807
|
+
...limit > 0 ? { records: { limit } } : {}
|
|
1628
2808
|
});
|
|
1629
2809
|
});
|
|
1630
2810
|
} finally {
|
|
@@ -1644,9 +2824,13 @@ var [source] = positionals;
|
|
|
1644
2824
|
var readModel = () => {
|
|
1645
2825
|
if (values.postgres)
|
|
1646
2826
|
return readDatabase(values.postgres);
|
|
2827
|
+
if (values.mysql)
|
|
2828
|
+
return readMysql(values.mysql);
|
|
2829
|
+
if (values.sqlite)
|
|
2830
|
+
return readSqlite(values.sqlite);
|
|
1647
2831
|
if (source)
|
|
1648
2832
|
return readSchema(source);
|
|
1649
|
-
return fail("Give a schema file or --
|
|
2833
|
+
return fail("Give a schema file, --postgres <url>, --mysql <url> or --sqlite <file>.");
|
|
1650
2834
|
};
|
|
1651
2835
|
var model = await readModel();
|
|
1652
2836
|
var output = values.json ? `${JSON.stringify(model, null, "\t")}
|