@absolutejs/dbml 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +45 -7
- package/changelog.json +44 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +1267 -121
- package/dist/drizzle/index.js +59 -8
- package/dist/drizzle/relations.d.ts +1 -0
- package/dist/index.js +66 -9
- package/dist/model.d.ts +10 -0
- package/dist/mysql/index.d.ts +20 -0
- package/dist/mysql/index.js +452 -0
- package/dist/postgres/details.d.ts +40 -0
- package/dist/postgres/index.d.ts +5 -0
- package/dist/postgres/index.js +367 -26
- package/dist/postgres/queries.d.ts +13 -4
- package/dist/postgres/rows.d.ts +66 -0
- package/dist/sqlite/index.d.ts +14 -0
- package/dist/sqlite/index.js +420 -0
- package/dist/sqlite/text.d.ts +22 -0
- package/package.json +16 -3
package/dist/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";
|
|
@@ -62,6 +63,33 @@ var withDefaultSchema = (model, schema) => {
|
|
|
62
63
|
};
|
|
63
64
|
return result;
|
|
64
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
|
+
};
|
|
65
93
|
|
|
66
94
|
// src/drizzle/dialects.ts
|
|
67
95
|
import { is, SQL, sql } from "drizzle-orm";
|
|
@@ -149,6 +177,20 @@ var isRecord = (value) => typeof value === "object" && value !== null;
|
|
|
149
177
|
var isTableRelations = (entry) => isRecord(entry) && isRecord(entry.relations) && ("table" in entry);
|
|
150
178
|
var isRelationsV2 = (value) => isRecord(value) && !is2(value, Relations) && Object.keys(value).length > 0 && Object.values(value).every(isTableRelations);
|
|
151
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
|
+
};
|
|
152
194
|
var v2Link = (field, relation) => {
|
|
153
195
|
const from = relation.sourceColumns;
|
|
154
196
|
const target = relation.targetColumns;
|
|
@@ -156,10 +198,19 @@ var v2Link = (field, relation) => {
|
|
|
156
198
|
return;
|
|
157
199
|
const owner = relation.sourceTable;
|
|
158
200
|
if (is2(relation, One)) {
|
|
159
|
-
const link = {
|
|
201
|
+
const link = {
|
|
202
|
+
field,
|
|
203
|
+
from,
|
|
204
|
+
kind: "one",
|
|
205
|
+
owner,
|
|
206
|
+
target,
|
|
207
|
+
...filterOf(relation)
|
|
208
|
+
};
|
|
160
209
|
return link;
|
|
161
210
|
}
|
|
162
211
|
const through = throughOf(relation);
|
|
212
|
+
if (is2(relation, Many) && !through)
|
|
213
|
+
return declaredMany(field, relation);
|
|
163
214
|
if (!is2(relation, Many) || !through)
|
|
164
215
|
return;
|
|
165
216
|
const link = {
|
|
@@ -232,7 +283,8 @@ var applyRelations = (options) => {
|
|
|
232
283
|
const target = endpointOf(options.lookup, link.target);
|
|
233
284
|
if (!from || !target)
|
|
234
285
|
continue;
|
|
235
|
-
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}`;
|
|
236
288
|
const key = refKey({ from, to: target });
|
|
237
289
|
const existing = byKey.get(key);
|
|
238
290
|
if (existing)
|
|
@@ -494,15 +546,15 @@ var tableOf = (config) => {
|
|
|
494
546
|
table
|
|
495
547
|
};
|
|
496
548
|
};
|
|
497
|
-
var
|
|
498
|
-
var
|
|
499
|
-
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) => {
|
|
500
552
|
const [only] = columns;
|
|
501
553
|
const single = columns.length === 1 ? table.columns.find((entry) => entry.name === only) : undefined;
|
|
502
554
|
if (single?.pk === true || single?.unique === true)
|
|
503
555
|
return true;
|
|
504
556
|
const wanted = [...columns].sort().join("\x00");
|
|
505
|
-
return table.indexes.some((index) =>
|
|
557
|
+
return table.indexes.some((index) => coversAll2(index) && index.parts.every((part) => part.kind === "column") && sortedColumns2(index) === wanted);
|
|
506
558
|
};
|
|
507
559
|
|
|
508
560
|
// src/drizzle/views.ts
|
|
@@ -665,7 +717,7 @@ var foreignKeyRefs = (entry, lookup, tables) => entry.config.foreignKeys.flatMap
|
|
|
665
717
|
...reference.name ? { name: reference.name } : {},
|
|
666
718
|
...onDelete ? { onDelete } : {},
|
|
667
719
|
...onUpdate ? { onUpdate } : {},
|
|
668
|
-
relation: table &&
|
|
720
|
+
relation: table && isUniqueSet2(table, columns) ? "-" : ">",
|
|
669
721
|
to: {
|
|
670
722
|
...target,
|
|
671
723
|
columns: reference.foreignColumns.map((column) => column.name)
|
|
@@ -792,7 +844,7 @@ var fromDrizzle = (schema, options = {}) => {
|
|
|
792
844
|
refs: model.refs,
|
|
793
845
|
isUnique: (end) => {
|
|
794
846
|
const table = byPlace.get(keyOf({ name: end.table, schema: end.schema }));
|
|
795
|
-
return table ?
|
|
847
|
+
return table ? isUniqueSet2(table, end.columns) : false;
|
|
796
848
|
}
|
|
797
849
|
});
|
|
798
850
|
addViews(model, found, lookup, (table) => byObject.get(table)?.columns.map((column) => column.name) ?? []);
|
|
@@ -802,9 +854,476 @@ var fromDrizzle = (schema, options = {}) => {
|
|
|
802
854
|
return model;
|
|
803
855
|
};
|
|
804
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
|
+
|
|
805
1230
|
// src/postgres/index.ts
|
|
806
1231
|
import { Buffer } from "buffer";
|
|
807
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
|
+
|
|
808
1327
|
// src/postgres/queries.ts
|
|
809
1328
|
var SCHEMAS = `
|
|
810
1329
|
select nspname as name
|
|
@@ -819,6 +1338,7 @@ from pg_type t
|
|
|
819
1338
|
join pg_namespace n on n.oid = t.typnamespace
|
|
820
1339
|
join pg_enum e on e.enumtypid = t.oid
|
|
821
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')
|
|
822
1342
|
group by n.nspname, t.typname
|
|
823
1343
|
order by n.nspname, t.typname`;
|
|
824
1344
|
var RELATIONS = `
|
|
@@ -827,10 +1347,23 @@ select c.oid::int as id, n.nspname as schema, c.relname as name, c.relkind as ki
|
|
|
827
1347
|
c.relrowsecurity as rls, c.relforcerowsecurity as force_rls,
|
|
828
1348
|
case when c.relkind = 'p' then pg_get_partkeydef(c.oid) end as partition_key,
|
|
829
1349
|
case when c.relkind in ('v', 'm') then pg_get_viewdef(c.oid, true) end as definition,
|
|
830
|
-
(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
|
|
831
1363
|
from pg_class c
|
|
832
1364
|
join pg_namespace n on n.oid = c.relnamespace
|
|
833
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')
|
|
834
1367
|
order by n.nspname, c.relname`;
|
|
835
1368
|
var COLUMNS = `
|
|
836
1369
|
select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name,
|
|
@@ -842,7 +1375,12 @@ select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name
|
|
|
842
1375
|
when et.typtype = 'e' then etn.nspname end as enum_schema,
|
|
843
1376
|
coalesce(case when t.typtype = 'e' then t.typname end,
|
|
844
1377
|
case when et.typtype = 'e' then et.typname || '[]' end) as enum_type,
|
|
845
|
-
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
|
|
846
1384
|
from pg_attribute a
|
|
847
1385
|
join pg_class c on c.oid = a.attrelid
|
|
848
1386
|
join pg_namespace n on n.oid = c.relnamespace
|
|
@@ -880,6 +1418,17 @@ select i.indrelid::int as table_id, ic.relname as name, am.amname as method,
|
|
|
880
1418
|
from generate_series(1, i.indnatts) as k) as attnums,
|
|
881
1419
|
(select array_agg((i.indoption[k - 1] & 1) = 1 order by k)
|
|
882
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,
|
|
883
1432
|
pg_get_expr(i.indpred, i.indrelid, true) as predicate,
|
|
884
1433
|
obj_description(i.indexrelid, 'pg_class') as comment
|
|
885
1434
|
from pg_index i
|
|
@@ -921,6 +1470,81 @@ order by n.nspname, c.relname`;
|
|
|
921
1470
|
var SCHEMA_COMMENTS = `
|
|
922
1471
|
select nspname as name, obj_description(oid, 'pg_namespace') as comment
|
|
923
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`;
|
|
924
1548
|
|
|
925
1549
|
// src/postgres/rows.ts
|
|
926
1550
|
var optional = (key, value) => {
|
|
@@ -929,62 +1553,75 @@ var optional = (key, value) => {
|
|
|
929
1553
|
entry[key] = value;
|
|
930
1554
|
return entry;
|
|
931
1555
|
};
|
|
932
|
-
var
|
|
1556
|
+
var text2 = (value) => {
|
|
933
1557
|
if (value === null || value === undefined)
|
|
934
1558
|
return;
|
|
935
1559
|
return typeof value === "string" ? value : `${value}`;
|
|
936
1560
|
};
|
|
937
|
-
var
|
|
1561
|
+
var integer2 = (value) => {
|
|
938
1562
|
if (typeof value === "number")
|
|
939
1563
|
return value;
|
|
940
|
-
const parsed = Number.parseInt(
|
|
1564
|
+
const parsed = Number.parseInt(text2(value) ?? "", 10);
|
|
941
1565
|
return Number.isNaN(parsed) ? 0 : parsed;
|
|
942
1566
|
};
|
|
943
1567
|
var flag = (value) => value === true || value === "t" || value === "true";
|
|
944
1568
|
var ARRAY_ITEM = /"((?:[^"\\]|\\.)*)"|([^,{}]+)/gu;
|
|
945
1569
|
var list = (value) => {
|
|
946
1570
|
if (Array.isArray(value))
|
|
947
|
-
return value.map((entry) =>
|
|
948
|
-
const raw =
|
|
1571
|
+
return value.map((entry) => text2(entry) ?? "");
|
|
1572
|
+
const raw = text2(value);
|
|
949
1573
|
if (raw === undefined)
|
|
950
1574
|
return [];
|
|
951
1575
|
return [...raw.matchAll(ARRAY_ITEM)].map((match) => match[1] === undefined ? match[2] ?? "" : match[1].replace(/\\(.)/gu, "$1"));
|
|
952
1576
|
};
|
|
953
|
-
var integers = (value) => list(value).map(
|
|
1577
|
+
var integers = (value) => list(value).map(integer2);
|
|
954
1578
|
var flags = (value) => list(value).map(flag);
|
|
955
1579
|
var relationRow = (row) => {
|
|
956
1580
|
const result = {
|
|
957
1581
|
forceRls: flag(row.force_rls),
|
|
958
|
-
id:
|
|
959
|
-
kind:
|
|
960
|
-
name:
|
|
961
|
-
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",
|
|
962
1587
|
rls: flag(row.rls),
|
|
963
|
-
schema:
|
|
964
|
-
...optional("comment",
|
|
965
|
-
...optional("definition",
|
|
966
|
-
...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))
|
|
967
1600
|
};
|
|
968
1601
|
return result;
|
|
969
1602
|
};
|
|
970
1603
|
var setting = (value) => {
|
|
971
|
-
const raw =
|
|
1604
|
+
const raw = text2(value);
|
|
972
1605
|
return raw === "" ? undefined : raw;
|
|
973
1606
|
};
|
|
974
1607
|
var columnRow = (row) => {
|
|
975
1608
|
const result = {
|
|
976
|
-
name:
|
|
1609
|
+
name: text2(row.name) ?? "",
|
|
977
1610
|
notNull: flag(row.not_null),
|
|
978
|
-
position:
|
|
979
|
-
tableId:
|
|
980
|
-
type:
|
|
981
|
-
...optional("
|
|
982
|
-
...optional("
|
|
983
|
-
...optional("
|
|
984
|
-
...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)),
|
|
985
1621
|
...optional("generated", setting(row.generated)),
|
|
986
1622
|
...optional("identity", setting(row.identity)),
|
|
987
|
-
...optional("
|
|
1623
|
+
...optional("identitySequence", text2(row.identity_sequence)),
|
|
1624
|
+
...optional("serialSequence", text2(row.serial_sequence))
|
|
988
1625
|
};
|
|
989
1626
|
return result;
|
|
990
1627
|
};
|
|
@@ -993,75 +1630,127 @@ var constraintRow = (row) => {
|
|
|
993
1630
|
columns: integers(row.columns),
|
|
994
1631
|
deferrable: flag(row.deferrable),
|
|
995
1632
|
deferred: flag(row.deferred),
|
|
996
|
-
definition:
|
|
1633
|
+
definition: text2(row.definition) ?? "",
|
|
997
1634
|
foreignColumns: integers(row.foreign_columns),
|
|
998
|
-
foreignTableId:
|
|
999
|
-
kind:
|
|
1000
|
-
name:
|
|
1635
|
+
foreignTableId: integer2(row.foreign_table_id),
|
|
1636
|
+
kind: text2(row.kind) ?? "",
|
|
1637
|
+
name: text2(row.name) ?? "",
|
|
1001
1638
|
nullsNotDistinct: flag(row.nulls_not_distinct),
|
|
1002
|
-
onDelete:
|
|
1003
|
-
onUpdate:
|
|
1004
|
-
tableId:
|
|
1005
|
-
...optional("checkExpression",
|
|
1006
|
-
...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))
|
|
1007
1644
|
};
|
|
1008
1645
|
return result;
|
|
1009
1646
|
};
|
|
1010
1647
|
var indexRow = (row) => {
|
|
1011
1648
|
const result = {
|
|
1012
1649
|
attnums: integers(row.attnums),
|
|
1650
|
+
collations: list(row.collations),
|
|
1013
1651
|
descending: flags(row.descending),
|
|
1014
|
-
keyCount:
|
|
1015
|
-
method:
|
|
1016
|
-
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),
|
|
1017
1658
|
parts: list(row.parts),
|
|
1018
|
-
tableId:
|
|
1659
|
+
tableId: integer2(row.table_id),
|
|
1019
1660
|
unique: flag(row.is_unique),
|
|
1020
|
-
...optional("comment",
|
|
1021
|
-
...optional("predicate",
|
|
1661
|
+
...optional("comment", text2(row.comment)),
|
|
1662
|
+
...optional("predicate", text2(row.predicate))
|
|
1022
1663
|
};
|
|
1023
1664
|
return result;
|
|
1024
1665
|
};
|
|
1025
1666
|
var policyRow = (row) => {
|
|
1026
1667
|
const result = {
|
|
1027
|
-
command:
|
|
1028
|
-
name:
|
|
1668
|
+
command: text2(row.command) ?? "*",
|
|
1669
|
+
name: text2(row.name) ?? "",
|
|
1029
1670
|
permissive: flag(row.permissive),
|
|
1030
1671
|
roles: list(row.roles),
|
|
1031
|
-
tableId:
|
|
1032
|
-
...optional("using",
|
|
1033
|
-
...optional("withCheck",
|
|
1672
|
+
tableId: integer2(row.table_id),
|
|
1673
|
+
...optional("using", text2(row.using)),
|
|
1674
|
+
...optional("withCheck", text2(row.with_check))
|
|
1034
1675
|
};
|
|
1035
1676
|
return result;
|
|
1036
1677
|
};
|
|
1037
1678
|
var namedRow = (row) => {
|
|
1038
1679
|
const result = {
|
|
1039
|
-
name:
|
|
1040
|
-
schema:
|
|
1041
|
-
...optional("comment",
|
|
1680
|
+
name: text2(row.name) ?? "",
|
|
1681
|
+
schema: text2(row.schema) ?? "",
|
|
1682
|
+
...optional("comment", text2(row.comment))
|
|
1042
1683
|
};
|
|
1043
1684
|
return result;
|
|
1044
1685
|
};
|
|
1045
1686
|
var enumRow = (row) => ({
|
|
1046
|
-
name:
|
|
1047
|
-
schema:
|
|
1687
|
+
name: text2(row.name) ?? "",
|
|
1688
|
+
schema: text2(row.schema) ?? "",
|
|
1048
1689
|
values: list(row.values)
|
|
1049
1690
|
});
|
|
1050
1691
|
var sequenceRow = (row) => ({
|
|
1051
|
-
increment:
|
|
1052
|
-
name:
|
|
1053
|
-
schema:
|
|
1054
|
-
start:
|
|
1692
|
+
increment: text2(row.increment) ?? "1",
|
|
1693
|
+
name: text2(row.name) ?? "",
|
|
1694
|
+
schema: text2(row.schema) ?? "",
|
|
1695
|
+
start: text2(row.start) ?? "1"
|
|
1055
1696
|
});
|
|
1056
1697
|
var viewSourceRow = (row) => ({
|
|
1057
|
-
sourceId:
|
|
1058
|
-
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)
|
|
1059
1748
|
});
|
|
1060
1749
|
|
|
1061
1750
|
// src/postgres/index.ts
|
|
1062
1751
|
var DEFAULT_SCHEMA = "public";
|
|
1063
1752
|
var inSchema2 = (schema) => ({ schema });
|
|
1064
|
-
var
|
|
1753
|
+
var ACTIONS3 = {
|
|
1065
1754
|
a: undefined,
|
|
1066
1755
|
c: "cascade",
|
|
1067
1756
|
d: "set default",
|
|
@@ -1069,7 +1758,7 @@ var ACTIONS2 = {
|
|
|
1069
1758
|
r: "restrict"
|
|
1070
1759
|
};
|
|
1071
1760
|
var QUOTED = /^'((?:[^']|'')*)'(?:::([\w\s."[\]()]+))?$/u;
|
|
1072
|
-
var
|
|
1761
|
+
var NUMBER2 = /^-?\d+(\.\d+)?$/u;
|
|
1073
1762
|
var NUMBER_CAST = /^\(?(-?\d+(?:\.\d+)?)\)?::[\w\s."]+$/u;
|
|
1074
1763
|
var NULL = /^NULL(::[\w\s."[\]()]+)?$/u;
|
|
1075
1764
|
var NUMERIC_TYPE = /^(smallint|integer|bigint|int[248]?|numeric(\(.*\))?|decimal(\(.*\))?|real|double precision|float[48]?)$/u;
|
|
@@ -1084,7 +1773,7 @@ var numberDefault = (digits, expression) => {
|
|
|
1084
1773
|
return result;
|
|
1085
1774
|
};
|
|
1086
1775
|
var quotedDefault = (inner, type, expression) => {
|
|
1087
|
-
if (NUMERIC_TYPE.test(type) &&
|
|
1776
|
+
if (NUMERIC_TYPE.test(type) && NUMBER2.test(inner))
|
|
1088
1777
|
return numberDefault(inner, expression);
|
|
1089
1778
|
const result = {
|
|
1090
1779
|
kind: "string",
|
|
@@ -1100,7 +1789,7 @@ var parseDefault = (expression) => {
|
|
|
1100
1789
|
kind: "boolean",
|
|
1101
1790
|
value: expression === "true"
|
|
1102
1791
|
};
|
|
1103
|
-
if (
|
|
1792
|
+
if (NUMBER2.test(expression))
|
|
1104
1793
|
return numberDefault(expression, expression);
|
|
1105
1794
|
const [, castDigits] = NUMBER_CAST.exec(expression) ?? [];
|
|
1106
1795
|
if (castDigits !== undefined)
|
|
@@ -1110,13 +1799,13 @@ var parseDefault = (expression) => {
|
|
|
1110
1799
|
return quotedDefault(inner, type ?? "", expression);
|
|
1111
1800
|
return { kind: "expression", value: expression };
|
|
1112
1801
|
};
|
|
1113
|
-
var
|
|
1802
|
+
var KINDS2 = {
|
|
1114
1803
|
f: "Foreign table",
|
|
1115
1804
|
m: "Materialized view",
|
|
1116
1805
|
p: "Partitioned table",
|
|
1117
1806
|
v: "View"
|
|
1118
1807
|
};
|
|
1119
|
-
var
|
|
1808
|
+
var VIEW_COLOR3 = "#64748b";
|
|
1120
1809
|
var POLICY_COMMANDS = {
|
|
1121
1810
|
"*": "all",
|
|
1122
1811
|
a: "insert",
|
|
@@ -1145,7 +1834,7 @@ var generatedNote2 = (row) => {
|
|
|
1145
1834
|
};
|
|
1146
1835
|
var isSerial = (row) => row.serialSequence !== undefined && row.default?.startsWith("nextval(") === true;
|
|
1147
1836
|
var enumSchema = (row) => row.enumType && row.enumSchema ? { typeSchema: row.enumSchema } : {};
|
|
1148
|
-
var
|
|
1837
|
+
var columnOf3 = (row) => {
|
|
1149
1838
|
const serial = isSerial(row);
|
|
1150
1839
|
const fallback = row.default !== undefined && !serial && !row.generated ? parseDefault(row.default) : undefined;
|
|
1151
1840
|
const column = {
|
|
@@ -1155,6 +1844,7 @@ var columnOf2 = (row) => {
|
|
|
1155
1844
|
...serial || row.identity ? { increment: true } : {},
|
|
1156
1845
|
...row.notNull ? { notNull: true } : {},
|
|
1157
1846
|
...fallback ? { default: fallback } : {},
|
|
1847
|
+
...columnMetadata(row),
|
|
1158
1848
|
...withNote(joinNotes([
|
|
1159
1849
|
row.comment,
|
|
1160
1850
|
identityNote2(row.identity),
|
|
@@ -1202,15 +1892,15 @@ var applyKey = (table, row, columns) => {
|
|
|
1202
1892
|
};
|
|
1203
1893
|
table.indexes.push(index);
|
|
1204
1894
|
};
|
|
1205
|
-
var
|
|
1206
|
-
var
|
|
1207
|
-
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) => {
|
|
1208
1898
|
const [only] = columns;
|
|
1209
1899
|
const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
|
|
1210
1900
|
if (single?.pk === true || single?.unique === true)
|
|
1211
1901
|
return true;
|
|
1212
1902
|
const wanted = [...columns].sort().join("\x00");
|
|
1213
|
-
return table.indexes.some((index) =>
|
|
1903
|
+
return table.indexes.some((index) => coversAll3(index) && index.parts.every((part) => part.kind === "column") && sortedColumns3(index) === wanted);
|
|
1214
1904
|
};
|
|
1215
1905
|
var refOf = (row, context) => {
|
|
1216
1906
|
const source = context.relations.get(row.tableId);
|
|
@@ -1219,14 +1909,14 @@ var refOf = (row, context) => {
|
|
|
1219
1909
|
if (!source || !target || !table)
|
|
1220
1910
|
return;
|
|
1221
1911
|
const columns = row.columns.map((position) => context.columnName(source.id, position));
|
|
1222
|
-
const onDelete =
|
|
1223
|
-
const onUpdate =
|
|
1912
|
+
const onDelete = ACTIONS3[row.onDelete];
|
|
1913
|
+
const onUpdate = ACTIONS3[row.onUpdate];
|
|
1224
1914
|
const ref = {
|
|
1225
1915
|
from: { columns, ...inSchema2(source.schema), table: source.name },
|
|
1226
1916
|
...row.name === defaultName(row, source.name, columns) ? {} : { name: row.name },
|
|
1227
1917
|
...onDelete ? { onDelete } : {},
|
|
1228
1918
|
...onUpdate ? { onUpdate } : {},
|
|
1229
|
-
relation:
|
|
1919
|
+
relation: isUniqueSet3(table, columns) ? "-" : ">",
|
|
1230
1920
|
to: {
|
|
1231
1921
|
columns: row.foreignColumns.map((position) => context.columnName(target.id, position)),
|
|
1232
1922
|
...inSchema2(target.schema),
|
|
@@ -1251,7 +1941,7 @@ var partOf2 = (row, index, context) => {
|
|
|
1251
1941
|
...desc
|
|
1252
1942
|
};
|
|
1253
1943
|
};
|
|
1254
|
-
var
|
|
1944
|
+
var indexOf3 = (row, context) => {
|
|
1255
1945
|
const included = row.parts.slice(row.keyCount);
|
|
1256
1946
|
const index = {
|
|
1257
1947
|
name: row.name,
|
|
@@ -1261,7 +1951,11 @@ var indexOf2 = (row, context) => {
|
|
|
1261
1951
|
...withNote(joinNotes([
|
|
1262
1952
|
row.comment,
|
|
1263
1953
|
row.predicate ? `Where ${row.predicate}` : undefined,
|
|
1264
|
-
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
|
+
})
|
|
1265
1959
|
]))
|
|
1266
1960
|
};
|
|
1267
1961
|
return index;
|
|
@@ -1276,7 +1970,7 @@ var policyLine2 = (row) => [
|
|
|
1276
1970
|
].filter((part) => part !== undefined).join(" ");
|
|
1277
1971
|
var MAX_DEFINITION = 600;
|
|
1278
1972
|
var kindLine = (relation) => {
|
|
1279
|
-
const kind =
|
|
1973
|
+
const kind = KINDS2[relation.kind];
|
|
1280
1974
|
const definition = relation.definition?.trim();
|
|
1281
1975
|
if (!kind || !definition)
|
|
1282
1976
|
return kind;
|
|
@@ -1284,10 +1978,11 @@ var kindLine = (relation) => {
|
|
|
1284
1978
|
return `${kind}:
|
|
1285
1979
|
${shown}`;
|
|
1286
1980
|
};
|
|
1287
|
-
var tableNote2 = (relation, policies) => joinNotes([
|
|
1981
|
+
var tableNote2 = (relation, policies, extra) => joinNotes([
|
|
1288
1982
|
relation.comment,
|
|
1289
1983
|
kindLine(relation),
|
|
1290
|
-
relation.partitionKey ? `Partitioned by ${relation.partitionKey}
|
|
1984
|
+
relation.partitionKey ? `Partitioned by ${relation.partitionKey}` : undefined,
|
|
1985
|
+
...extra,
|
|
1291
1986
|
relation.rls ? `Row-level security is on${relation.forceRls ? ", for the owner too" : ""}` : undefined,
|
|
1292
1987
|
...policies.map(policyLine2)
|
|
1293
1988
|
]);
|
|
@@ -1319,16 +2014,23 @@ var readRecords = (query, tables, limit) => Promise.all(tables.map(async (table)
|
|
|
1319
2014
|
};
|
|
1320
2015
|
return records;
|
|
1321
2016
|
}));
|
|
1322
|
-
var tableOf2 = (relation,
|
|
2017
|
+
var tableOf2 = (relation, catalogs, statistics) => {
|
|
2018
|
+
const own = (rows) => rows.filter((row) => row.tableId === relation.id);
|
|
1323
2019
|
const view = relation.kind === "v" || relation.kind === "m";
|
|
1324
2020
|
const table = {
|
|
1325
2021
|
checks: [],
|
|
1326
|
-
columns:
|
|
1327
|
-
...view ? { headerColor:
|
|
2022
|
+
columns: own(catalogs.columns).map(columnOf3),
|
|
2023
|
+
...view ? { headerColor: VIEW_COLOR3 } : {},
|
|
1328
2024
|
indexes: [],
|
|
1329
2025
|
name: relation.name,
|
|
1330
2026
|
...inSchema2(relation.schema),
|
|
1331
|
-
...
|
|
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
|
+
})))
|
|
1332
2034
|
};
|
|
1333
2035
|
return table;
|
|
1334
2036
|
};
|
|
@@ -1369,7 +2071,16 @@ var readCatalogs = async (query, schemas) => {
|
|
|
1369
2071
|
sources,
|
|
1370
2072
|
policies,
|
|
1371
2073
|
sequences,
|
|
1372
|
-
comments
|
|
2074
|
+
comments,
|
|
2075
|
+
triggers,
|
|
2076
|
+
rules,
|
|
2077
|
+
functions,
|
|
2078
|
+
domains,
|
|
2079
|
+
composites,
|
|
2080
|
+
partitions,
|
|
2081
|
+
viewColumns,
|
|
2082
|
+
extensions,
|
|
2083
|
+
eventTriggers
|
|
1373
2084
|
] = await Promise.all([
|
|
1374
2085
|
read(ENUMS),
|
|
1375
2086
|
read(RELATIONS),
|
|
@@ -1379,33 +2090,58 @@ var readCatalogs = async (query, schemas) => {
|
|
|
1379
2090
|
read(VIEW_SOURCES),
|
|
1380
2091
|
read(POLICIES),
|
|
1381
2092
|
read(SEQUENCES),
|
|
1382
|
-
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, [])
|
|
1383
2103
|
]);
|
|
1384
2104
|
return {
|
|
1385
2105
|
columns: columns.map(columnRow),
|
|
1386
2106
|
comments: comments.map(namedRow),
|
|
2107
|
+
composites: composites.map(compositeRow),
|
|
1387
2108
|
constraints: constraints.map(constraintRow),
|
|
2109
|
+
domains: domains.map(domainRow),
|
|
1388
2110
|
enums: enums.map(enumRow),
|
|
2111
|
+
eventTriggers: eventTriggers.map(eventTriggerRow),
|
|
2112
|
+
extensions: extensions.map(extensionRow),
|
|
2113
|
+
functions: functions.map(functionRow),
|
|
1389
2114
|
indexes: indexes.map(indexRow),
|
|
2115
|
+
partitions: partitions.map(partitionRow),
|
|
1390
2116
|
policies: policies.map(policyRow),
|
|
1391
2117
|
relations: relations.map(relationRow),
|
|
2118
|
+
rules: rules.map(definitionRow),
|
|
1392
2119
|
sequences: sequences.map(sequenceRow),
|
|
1393
|
-
sources: sources.map(viewSourceRow)
|
|
2120
|
+
sources: sources.map(viewSourceRow),
|
|
2121
|
+
triggers: triggers.map(definitionRow),
|
|
2122
|
+
viewColumns: viewColumns.map(viewColumnRow)
|
|
1394
2123
|
};
|
|
1395
2124
|
};
|
|
1396
2125
|
var schemasToRead = async (query, schemas) => schemas ?? (await query(SCHEMAS, [])).map((row) => namedRow(row).name);
|
|
1397
2126
|
var addDeps = (model, catalogs, relations) => catalogs.sources.forEach((row) => {
|
|
1398
2127
|
const view = relations.get(row.viewId);
|
|
1399
2128
|
const source = relations.get(row.sourceId);
|
|
1400
|
-
if (view
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
}
|
|
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
|
+
});
|
|
1405
2140
|
});
|
|
1406
2141
|
var addNotes2 = (model, catalogs, defaultSchema) => {
|
|
1407
2142
|
if (catalogs.sequences.length > 0)
|
|
1408
2143
|
model.notes.push(sequenceNote(catalogs.sequences, defaultSchema));
|
|
2144
|
+
model.notes.push(...extraNotes(catalogs, defaultSchema));
|
|
1409
2145
|
const described = catalogs.comments.filter((row) => row.comment !== undefined && row.name !== defaultSchema);
|
|
1410
2146
|
if (described.length > 0)
|
|
1411
2147
|
model.notes.push({
|
|
@@ -1433,7 +2169,7 @@ var fromPostgres = async (query, options = {}) => {
|
|
|
1433
2169
|
]));
|
|
1434
2170
|
const tables = new Map(catalogs.relations.map((row) => [
|
|
1435
2171
|
row.id,
|
|
1436
|
-
tableOf2(row, catalogs
|
|
2172
|
+
tableOf2(row, catalogs, options.statistics === true)
|
|
1437
2173
|
]));
|
|
1438
2174
|
const context = {
|
|
1439
2175
|
relations,
|
|
@@ -1441,7 +2177,7 @@ var fromPostgres = async (query, options = {}) => {
|
|
|
1441
2177
|
columnName: (tableId, position) => names.get(`${tableId}:${position}`) ?? `${position}`
|
|
1442
2178
|
};
|
|
1443
2179
|
const foreign = applyConstraints(catalogs.constraints, context);
|
|
1444
|
-
catalogs.indexes.forEach((row) => tables.get(row.tableId)?.indexes.push(
|
|
2180
|
+
catalogs.indexes.forEach((row) => tables.get(row.tableId)?.indexes.push(indexOf3(row, context)));
|
|
1445
2181
|
model.tables.push(...tables.values());
|
|
1446
2182
|
model.refs.push(...foreign.map((row) => refOf(row, context)).filter((ref) => ref !== undefined));
|
|
1447
2183
|
addDeps(model, catalogs, relations);
|
|
@@ -1450,13 +2186,16 @@ var fromPostgres = async (query, options = {}) => {
|
|
|
1450
2186
|
const limit = options.records?.limit ?? 0;
|
|
1451
2187
|
if (limit > 0)
|
|
1452
2188
|
model.records.push(...await readRecords(query, model.tables.filter((table) => !table.headerColor), limit));
|
|
1453
|
-
|
|
2189
|
+
const result = withDefaultSchema(model, defaultSchema);
|
|
2190
|
+
if (options.groups === "schema")
|
|
2191
|
+
result.tableGroups.push(...groupBySchema(result.tables, defaultSchema));
|
|
2192
|
+
return result;
|
|
1454
2193
|
};
|
|
1455
2194
|
|
|
1456
2195
|
// src/print.ts
|
|
1457
2196
|
var INDENT = " ";
|
|
1458
2197
|
var quoteName = (name) => `"${name.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
|
|
1459
|
-
var
|
|
2198
|
+
var qualified2 = (schema, name) => schema ? `${quoteName(schema)}.${quoteName(name)}` : quoteName(name);
|
|
1460
2199
|
var quoteText = (text) => {
|
|
1461
2200
|
const escaped = text.replaceAll("\\", "\\\\").replaceAll(`\r
|
|
1462
2201
|
`, `
|
|
@@ -1521,7 +2260,7 @@ ${lines.map((line) => `${pad}${line}`).join(`
|
|
|
1521
2260
|
${INDENT.repeat(depth - 1)}}`;
|
|
1522
2261
|
};
|
|
1523
2262
|
var printTable = (table) => {
|
|
1524
|
-
const head = `Table ${
|
|
2263
|
+
const head = `Table ${qualified2(table.schema, table.name)}${table.alias ? ` as ${quoteName(table.alias)}` : ""}${settings([
|
|
1525
2264
|
table.headerColor !== undefined && `headerColor: ${table.headerColor}`
|
|
1526
2265
|
])}`;
|
|
1527
2266
|
const body = table.columns.map(printColumn);
|
|
@@ -1540,12 +2279,12 @@ ${[lines.join(`
|
|
|
1540
2279
|
`)}
|
|
1541
2280
|
}`;
|
|
1542
2281
|
};
|
|
1543
|
-
var printEnum = (entry) => block(`Enum ${
|
|
2282
|
+
var printEnum = (entry) => block(`Enum ${qualified2(entry.schema, entry.name)}`, entry.values.map((value) => `${quoteName(value.name)}${settings([
|
|
1544
2283
|
value.note !== undefined && `note: ${quoteText(value.note)}`
|
|
1545
2284
|
])}`));
|
|
1546
2285
|
var printEndpoint = (endpoint) => {
|
|
1547
2286
|
const columns = endpoint.columns.length === 1 ? quoteName(endpoint.columns[0] ?? "") : `(${endpoint.columns.map(quoteName).join(", ")})`;
|
|
1548
|
-
return `${
|
|
2287
|
+
return `${qualified2(endpoint.schema, endpoint.table)}.${columns}`;
|
|
1549
2288
|
};
|
|
1550
2289
|
var printRef = (ref) => `Ref${ref.name === undefined ? "" : ` ${quoteName(ref.name)}`}: ${printEndpoint(ref.from)} ${ref.relation} ${printEndpoint(ref.to)}${settings([
|
|
1551
2290
|
ref.onDelete !== undefined && `delete: ${ref.onDelete}`,
|
|
@@ -1554,22 +2293,32 @@ var printRef = (ref) => `Ref${ref.name === undefined ? "" : ` ${quoteName(ref.na
|
|
|
1554
2293
|
ref.inactive && "inactive",
|
|
1555
2294
|
ref.note !== undefined && `note: ${quoteText(ref.note)}`
|
|
1556
2295
|
])}`;
|
|
1557
|
-
var printDepEnd = (end) => {
|
|
1558
|
-
const table =
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
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])}`);
|
|
1562
2308
|
};
|
|
1563
2309
|
var printDep = (dep) => {
|
|
1564
|
-
const
|
|
1565
|
-
if (dep.note === undefined)
|
|
1566
|
-
return `Dep: ${
|
|
1567
|
-
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
|
+
]);
|
|
1568
2317
|
};
|
|
1569
2318
|
var printGroup = (group) => block(`TableGroup ${quoteName(group.name)}${settings([
|
|
1570
2319
|
group.color !== undefined && `color: ${group.color}`
|
|
1571
2320
|
])}`, [
|
|
1572
|
-
...group.tables.map((entry) =>
|
|
2321
|
+
...group.tables.map((entry) => qualified2(entry.schema, entry.table)),
|
|
1573
2322
|
...group.note === undefined ? [] : [`Note: ${quoteText(group.note)}`]
|
|
1574
2323
|
]);
|
|
1575
2324
|
var printNote = (note) => block(`Note ${quoteName(note.name)}${settings([
|
|
@@ -1582,11 +2331,28 @@ var printValue = (value) => {
|
|
|
1582
2331
|
return `${value}`;
|
|
1583
2332
|
return quoteText(value);
|
|
1584
2333
|
};
|
|
1585
|
-
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(", ")));
|
|
1586
2335
|
var printProject = (project) => block(`Project${project.name ? ` ${quoteName(project.name)}` : ""}`, [
|
|
1587
2336
|
...project.databaseType === undefined ? [] : [`database_type: ${quoteText(project.databaseType)}`],
|
|
1588
2337
|
...project.note === undefined ? [] : [`Note: ${quoteText(project.note)}`]
|
|
1589
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
|
+
});
|
|
1590
2356
|
var printDbml = (model) => {
|
|
1591
2357
|
const { project } = model;
|
|
1592
2358
|
const hasProject = project !== undefined && (project.name !== undefined || project.databaseType !== undefined || project.note !== undefined);
|
|
@@ -1600,7 +2366,8 @@ var printDbml = (model) => {
|
|
|
1600
2366
|
...model.deps.length > 0 ? [model.deps.map(printDep).join(`
|
|
1601
2367
|
`)] : [],
|
|
1602
2368
|
...model.notes.map(printNote),
|
|
1603
|
-
...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)
|
|
1604
2371
|
];
|
|
1605
2372
|
return `${sections.join(`
|
|
1606
2373
|
|
|
@@ -1608,10 +2375,353 @@ var printDbml = (model) => {
|
|
|
1608
2375
|
`;
|
|
1609
2376
|
};
|
|
1610
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
|
+
|
|
1611
2719
|
// src/cli.ts
|
|
1612
2720
|
var USAGE = `Usage:
|
|
1613
2721
|
absolute-dbml <schema.ts> [options] a Drizzle schema module
|
|
1614
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
|
|
1615
2725
|
|
|
1616
2726
|
Options:
|
|
1617
2727
|
-o, --output <file> write to a file instead of standard output
|
|
@@ -1619,8 +2729,9 @@ Options:
|
|
|
1619
2729
|
--name <name> the project's name
|
|
1620
2730
|
--groups schema group tables by schema
|
|
1621
2731
|
--relations <name> the schema module's defineRelations export
|
|
1622
|
-
--schema <name> a schema to read (repeatable
|
|
2732
|
+
--schema <name> a schema (or MySQL database) to read (repeatable)
|
|
1623
2733
|
--records <n> each table's first n rows as Records (Postgres only)
|
|
2734
|
+
--statistics each table's row count and size, as metadata
|
|
1624
2735
|
-h, --help show this help
|
|
1625
2736
|
`;
|
|
1626
2737
|
var fail = (message) => {
|
|
@@ -1635,12 +2746,15 @@ var { positionals, values } = parseArgs({
|
|
|
1635
2746
|
groups: { type: "string" },
|
|
1636
2747
|
help: { short: "h", type: "boolean" },
|
|
1637
2748
|
json: { type: "boolean" },
|
|
2749
|
+
mysql: { type: "string" },
|
|
1638
2750
|
name: { type: "string" },
|
|
1639
2751
|
output: { short: "o", type: "string" },
|
|
1640
2752
|
postgres: { type: "string" },
|
|
1641
2753
|
records: { type: "string" },
|
|
1642
2754
|
relations: { type: "string" },
|
|
1643
|
-
schema: { multiple: true, type: "string" }
|
|
2755
|
+
schema: { multiple: true, type: "string" },
|
|
2756
|
+
sqlite: { type: "string" },
|
|
2757
|
+
statistics: { type: "boolean" }
|
|
1644
2758
|
}
|
|
1645
2759
|
});
|
|
1646
2760
|
if (values.help) {
|
|
@@ -1649,6 +2763,35 @@ if (values.help) {
|
|
|
1649
2763
|
}
|
|
1650
2764
|
var project = values.name ? { name: values.name } : undefined;
|
|
1651
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
|
+
};
|
|
1652
2795
|
var readDatabase = async (url) => {
|
|
1653
2796
|
const client = new SQL3({ max: 1, url });
|
|
1654
2797
|
try {
|
|
@@ -1660,9 +2803,8 @@ var readDatabase = async (url) => {
|
|
|
1660
2803
|
const rows = await transaction.unsafe(text, params);
|
|
1661
2804
|
return rows;
|
|
1662
2805
|
}, {
|
|
1663
|
-
...
|
|
1664
|
-
...limit > 0 ? { records: { limit } } : {}
|
|
1665
|
-
...values.schema ? { schemas: values.schema } : {}
|
|
2806
|
+
...shared,
|
|
2807
|
+
...limit > 0 ? { records: { limit } } : {}
|
|
1666
2808
|
});
|
|
1667
2809
|
});
|
|
1668
2810
|
} finally {
|
|
@@ -1682,9 +2824,13 @@ var [source] = positionals;
|
|
|
1682
2824
|
var readModel = () => {
|
|
1683
2825
|
if (values.postgres)
|
|
1684
2826
|
return readDatabase(values.postgres);
|
|
2827
|
+
if (values.mysql)
|
|
2828
|
+
return readMysql(values.mysql);
|
|
2829
|
+
if (values.sqlite)
|
|
2830
|
+
return readSqlite(values.sqlite);
|
|
1685
2831
|
if (source)
|
|
1686
2832
|
return readSchema(source);
|
|
1687
|
-
return fail("Give a schema file or --
|
|
2833
|
+
return fail("Give a schema file, --postgres <url>, --mysql <url> or --sqlite <file>.");
|
|
1688
2834
|
};
|
|
1689
2835
|
var model = await readModel();
|
|
1690
2836
|
var output = values.json ? `${JSON.stringify(model, null, "\t")}
|