@absolutejs/dbml 0.0.0-stage → 0.2.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 +21 -0
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/changelog.json +32 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1698 -0
- package/dist/drizzle/dialects.d.ts +121 -0
- package/dist/drizzle/index.d.ts +21 -0
- package/dist/drizzle/index.js +796 -0
- package/dist/drizzle/relations.d.ts +40 -0
- package/dist/drizzle/tables.d.ts +10 -0
- package/dist/drizzle/views.d.ts +13 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +211 -0
- package/dist/model.d.ts +164 -0
- package/dist/postgres/index.d.ts +38 -0
- package/dist/postgres/index.js +704 -0
- package/dist/postgres/queries.d.ts +10 -0
- package/dist/postgres/rows.d.ts +91 -0
- package/dist/print.d.ts +11 -0
- package/package.json +89 -5
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/postgres/index.ts
|
|
3
|
+
import { Buffer } from "buffer";
|
|
4
|
+
|
|
5
|
+
// src/model.ts
|
|
6
|
+
var emptyModel = (project) => ({
|
|
7
|
+
deps: [],
|
|
8
|
+
enums: [],
|
|
9
|
+
notes: [],
|
|
10
|
+
...project ? { project } : {},
|
|
11
|
+
records: [],
|
|
12
|
+
refs: [],
|
|
13
|
+
tableGroups: [],
|
|
14
|
+
tables: []
|
|
15
|
+
});
|
|
16
|
+
var unqualified = (place, schema) => {
|
|
17
|
+
if (place.schema !== schema)
|
|
18
|
+
return place;
|
|
19
|
+
const { schema: dropped, ...rest } = place;
|
|
20
|
+
return rest;
|
|
21
|
+
};
|
|
22
|
+
var withDefaultSchema = (model, schema) => {
|
|
23
|
+
const result = {
|
|
24
|
+
...model,
|
|
25
|
+
deps: model.deps.map((dep) => ({
|
|
26
|
+
...dep,
|
|
27
|
+
downstream: unqualified(dep.downstream, schema),
|
|
28
|
+
upstream: unqualified(dep.upstream, schema)
|
|
29
|
+
})),
|
|
30
|
+
enums: model.enums.map((entry) => unqualified(entry, schema)),
|
|
31
|
+
records: model.records.map((records) => unqualified(records, schema)),
|
|
32
|
+
refs: model.refs.map((ref) => ({
|
|
33
|
+
...ref,
|
|
34
|
+
from: unqualified(ref.from, schema),
|
|
35
|
+
to: unqualified(ref.to, schema)
|
|
36
|
+
})),
|
|
37
|
+
tableGroups: model.tableGroups.map((group) => ({
|
|
38
|
+
...group,
|
|
39
|
+
tables: group.tables.map((entry) => unqualified(entry, schema))
|
|
40
|
+
})),
|
|
41
|
+
tables: model.tables.map((table) => ({
|
|
42
|
+
...unqualified(table, schema),
|
|
43
|
+
columns: table.columns.map((column) => {
|
|
44
|
+
if (column.typeSchema !== schema)
|
|
45
|
+
return column;
|
|
46
|
+
const { typeSchema: dropped, ...rest } = column;
|
|
47
|
+
return rest;
|
|
48
|
+
})
|
|
49
|
+
}))
|
|
50
|
+
};
|
|
51
|
+
return result;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// src/postgres/queries.ts
|
|
55
|
+
var SCHEMAS = `
|
|
56
|
+
select nspname as name
|
|
57
|
+
from pg_namespace
|
|
58
|
+
where nspname not in ('pg_catalog', 'information_schema', 'pg_toast')
|
|
59
|
+
and nspname not like 'pg_temp_%' and nspname not like 'pg_toast_temp_%'
|
|
60
|
+
order by nspname`;
|
|
61
|
+
var ENUMS = `
|
|
62
|
+
select n.nspname as schema, t.typname as name,
|
|
63
|
+
array_agg(e.enumlabel order by e.enumsortorder) as "values"
|
|
64
|
+
from pg_type t
|
|
65
|
+
join pg_namespace n on n.oid = t.typnamespace
|
|
66
|
+
join pg_enum e on e.enumtypid = t.oid
|
|
67
|
+
where n.nspname = any($1)
|
|
68
|
+
group by n.nspname, t.typname
|
|
69
|
+
order by n.nspname, t.typname`;
|
|
70
|
+
var RELATIONS = `
|
|
71
|
+
select c.oid::int as id, n.nspname as schema, c.relname as name, c.relkind as kind,
|
|
72
|
+
obj_description(c.oid, 'pg_class') as comment,
|
|
73
|
+
c.relrowsecurity as rls, c.relforcerowsecurity as force_rls,
|
|
74
|
+
case when c.relkind = 'p' then pg_get_partkeydef(c.oid) end as partition_key,
|
|
75
|
+
case when c.relkind in ('v', 'm') then pg_get_viewdef(c.oid, true) end as definition,
|
|
76
|
+
(select count(*)::int from pg_inherits i where i.inhparent = c.oid) as partitions
|
|
77
|
+
from pg_class c
|
|
78
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
79
|
+
where n.nspname = any($1) and c.relkind in ('r', 'p', 'v', 'm', 'f') and not c.relispartition
|
|
80
|
+
order by n.nspname, c.relname`;
|
|
81
|
+
var COLUMNS = `
|
|
82
|
+
select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name,
|
|
83
|
+
format_type(a.atttypid, a.atttypmod) as type,
|
|
84
|
+
a.attnotnull as not_null, a.attidentity as identity, a.attgenerated as generated,
|
|
85
|
+
pg_get_expr(d.adbin, d.adrelid) as "default",
|
|
86
|
+
col_description(a.attrelid, a.attnum) as comment,
|
|
87
|
+
case when t.typtype = 'e' then tn.nspname
|
|
88
|
+
when et.typtype = 'e' then etn.nspname end as enum_schema,
|
|
89
|
+
coalesce(case when t.typtype = 'e' then t.typname end,
|
|
90
|
+
case when et.typtype = 'e' then et.typname || '[]' end) as enum_type,
|
|
91
|
+
pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname) as serial_sequence
|
|
92
|
+
from pg_attribute a
|
|
93
|
+
join pg_class c on c.oid = a.attrelid
|
|
94
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
95
|
+
join pg_type t on t.oid = a.atttypid
|
|
96
|
+
join pg_namespace tn on tn.oid = t.typnamespace
|
|
97
|
+
left join pg_type et on et.oid = t.typelem and t.typcategory = 'A'
|
|
98
|
+
left join pg_namespace etn on etn.oid = et.typnamespace
|
|
99
|
+
left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum
|
|
100
|
+
where n.nspname = any($1) and c.relkind in ('r', 'p', 'v', 'm', 'f') and not c.relispartition
|
|
101
|
+
and a.attnum > 0 and not a.attisdropped
|
|
102
|
+
order by a.attrelid, a.attnum`;
|
|
103
|
+
var CONSTRAINTS = `
|
|
104
|
+
select con.conrelid::int as table_id, con.conname as name, con.contype as kind,
|
|
105
|
+
(select array_agg(k::int order by o) from unnest(con.conkey) with ordinality as u(k, o)) as columns,
|
|
106
|
+
con.confrelid::int as foreign_table_id,
|
|
107
|
+
(select array_agg(k::int order by o) from unnest(con.confkey) with ordinality as u(k, o)) as foreign_columns,
|
|
108
|
+
con.confdeltype as on_delete, con.confupdtype as on_update,
|
|
109
|
+
pg_get_constraintdef(con.oid, true) as definition,
|
|
110
|
+
case when con.contype = 'c' then pg_get_expr(con.conbin, con.conrelid, true) end as check_expression,
|
|
111
|
+
obj_description(con.oid, 'pg_constraint') as comment,
|
|
112
|
+
con.condeferrable as deferrable, con.condeferred as deferred,
|
|
113
|
+
/* Read through jsonb so a Postgres older than 15, without the column,
|
|
114
|
+
* reads null instead of failing. */
|
|
115
|
+
(to_jsonb(con) ->> 'connullsnotdistinct')::boolean as nulls_not_distinct
|
|
116
|
+
from pg_constraint con
|
|
117
|
+
join pg_namespace n on n.oid = con.connamespace
|
|
118
|
+
where n.nspname = any($1) and con.contype in ('p', 'u', 'f', 'c', 'x') and con.conrelid <> 0
|
|
119
|
+
order by con.conrelid, con.contype, con.conname`;
|
|
120
|
+
var INDEXES = `
|
|
121
|
+
select i.indrelid::int as table_id, ic.relname as name, am.amname as method,
|
|
122
|
+
i.indisunique as is_unique, i.indnkeyatts::int as key_count, i.indnatts::int as count,
|
|
123
|
+
(select array_agg(pg_get_indexdef(i.indexrelid, k, true) order by k)
|
|
124
|
+
from generate_series(1, i.indnatts) as k) as parts,
|
|
125
|
+
(select array_agg(i.indkey[k - 1]::int order by k)
|
|
126
|
+
from generate_series(1, i.indnatts) as k) as attnums,
|
|
127
|
+
(select array_agg((i.indoption[k - 1] & 1) = 1 order by k)
|
|
128
|
+
from generate_series(1, i.indnkeyatts) as k) as descending,
|
|
129
|
+
pg_get_expr(i.indpred, i.indrelid, true) as predicate,
|
|
130
|
+
obj_description(i.indexrelid, 'pg_class') as comment
|
|
131
|
+
from pg_index i
|
|
132
|
+
join pg_class ic on ic.oid = i.indexrelid
|
|
133
|
+
join pg_class tc on tc.oid = i.indrelid
|
|
134
|
+
join pg_namespace n on n.oid = tc.relnamespace
|
|
135
|
+
join pg_am am on am.oid = ic.relam
|
|
136
|
+
where n.nspname = any($1)
|
|
137
|
+
and not exists (select 1 from pg_constraint con where con.conindid = i.indexrelid and con.contype in ('p', 'u', 'x'))
|
|
138
|
+
order by i.indrelid, ic.relname`;
|
|
139
|
+
var VIEW_SOURCES = `
|
|
140
|
+
select distinct v.oid::int as view_id, d.refobjid::int as source_id
|
|
141
|
+
from pg_class v
|
|
142
|
+
join pg_namespace n on n.oid = v.relnamespace
|
|
143
|
+
join pg_rewrite r on r.ev_class = v.oid
|
|
144
|
+
join pg_depend d on d.objid = r.oid and d.classid = 'pg_rewrite'::regclass
|
|
145
|
+
and d.refclassid = 'pg_class'::regclass and d.refobjid <> v.oid
|
|
146
|
+
where n.nspname = any($1) and v.relkind in ('v', 'm')`;
|
|
147
|
+
var POLICIES = `
|
|
148
|
+
select p.polrelid::int as table_id, p.polname as name, p.polpermissive as permissive,
|
|
149
|
+
p.polcmd as command,
|
|
150
|
+
(select array_agg(case when r = 0 then 'public' else pg_get_userbyid(r) end) from unnest(p.polroles) as r) as roles,
|
|
151
|
+
pg_get_expr(p.polqual, p.polrelid, true) as "using",
|
|
152
|
+
pg_get_expr(p.polwithcheck, p.polrelid, true) as with_check
|
|
153
|
+
from pg_policy p
|
|
154
|
+
join pg_class c on c.oid = p.polrelid
|
|
155
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
156
|
+
where n.nspname = any($1)
|
|
157
|
+
order by p.polrelid, p.polname`;
|
|
158
|
+
var SEQUENCES = `
|
|
159
|
+
select n.nspname as schema, c.relname as name, s.seqstart::text as start,
|
|
160
|
+
s.seqincrement::text as increment
|
|
161
|
+
from pg_sequence s
|
|
162
|
+
join pg_class c on c.oid = s.seqrelid
|
|
163
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
164
|
+
where n.nspname = any($1)
|
|
165
|
+
and not exists (select 1 from pg_depend d where d.objid = c.oid and d.deptype in ('a', 'i'))
|
|
166
|
+
order by n.nspname, c.relname`;
|
|
167
|
+
var SCHEMA_COMMENTS = `
|
|
168
|
+
select nspname as name, obj_description(oid, 'pg_namespace') as comment
|
|
169
|
+
from pg_namespace where nspname = any($1)`;
|
|
170
|
+
|
|
171
|
+
// src/postgres/rows.ts
|
|
172
|
+
var optional = (key, value) => {
|
|
173
|
+
const entry = {};
|
|
174
|
+
if (value !== undefined)
|
|
175
|
+
entry[key] = value;
|
|
176
|
+
return entry;
|
|
177
|
+
};
|
|
178
|
+
var text = (value) => {
|
|
179
|
+
if (value === null || value === undefined)
|
|
180
|
+
return;
|
|
181
|
+
return typeof value === "string" ? value : `${value}`;
|
|
182
|
+
};
|
|
183
|
+
var integer = (value) => {
|
|
184
|
+
if (typeof value === "number")
|
|
185
|
+
return value;
|
|
186
|
+
const parsed = Number.parseInt(text(value) ?? "", 10);
|
|
187
|
+
return Number.isNaN(parsed) ? 0 : parsed;
|
|
188
|
+
};
|
|
189
|
+
var flag = (value) => value === true || value === "t" || value === "true";
|
|
190
|
+
var ARRAY_ITEM = /"((?:[^"\\]|\\.)*)"|([^,{}]+)/gu;
|
|
191
|
+
var list = (value) => {
|
|
192
|
+
if (Array.isArray(value))
|
|
193
|
+
return value.map((entry) => text(entry) ?? "");
|
|
194
|
+
const raw = text(value);
|
|
195
|
+
if (raw === undefined)
|
|
196
|
+
return [];
|
|
197
|
+
return [...raw.matchAll(ARRAY_ITEM)].map((match) => match[1] === undefined ? match[2] ?? "" : match[1].replace(/\\(.)/gu, "$1"));
|
|
198
|
+
};
|
|
199
|
+
var integers = (value) => list(value).map(integer);
|
|
200
|
+
var flags = (value) => list(value).map(flag);
|
|
201
|
+
var relationRow = (row) => {
|
|
202
|
+
const result = {
|
|
203
|
+
forceRls: flag(row.force_rls),
|
|
204
|
+
id: integer(row.id),
|
|
205
|
+
kind: text(row.kind) ?? "",
|
|
206
|
+
name: text(row.name) ?? "",
|
|
207
|
+
partitions: integer(row.partitions),
|
|
208
|
+
rls: flag(row.rls),
|
|
209
|
+
schema: text(row.schema) ?? "",
|
|
210
|
+
...optional("comment", text(row.comment)),
|
|
211
|
+
...optional("definition", text(row.definition)),
|
|
212
|
+
...optional("partitionKey", text(row.partition_key))
|
|
213
|
+
};
|
|
214
|
+
return result;
|
|
215
|
+
};
|
|
216
|
+
var setting = (value) => {
|
|
217
|
+
const raw = text(value);
|
|
218
|
+
return raw === "" ? undefined : raw;
|
|
219
|
+
};
|
|
220
|
+
var columnRow = (row) => {
|
|
221
|
+
const result = {
|
|
222
|
+
name: text(row.name) ?? "",
|
|
223
|
+
notNull: flag(row.not_null),
|
|
224
|
+
position: integer(row.position),
|
|
225
|
+
tableId: integer(row.table_id),
|
|
226
|
+
type: text(row.type) ?? "",
|
|
227
|
+
...optional("comment", text(row.comment)),
|
|
228
|
+
...optional("default", text(row.default)),
|
|
229
|
+
...optional("enumSchema", text(row.enum_schema)),
|
|
230
|
+
...optional("enumType", text(row.enum_type)),
|
|
231
|
+
...optional("generated", setting(row.generated)),
|
|
232
|
+
...optional("identity", setting(row.identity)),
|
|
233
|
+
...optional("serialSequence", text(row.serial_sequence))
|
|
234
|
+
};
|
|
235
|
+
return result;
|
|
236
|
+
};
|
|
237
|
+
var constraintRow = (row) => {
|
|
238
|
+
const result = {
|
|
239
|
+
columns: integers(row.columns),
|
|
240
|
+
deferrable: flag(row.deferrable),
|
|
241
|
+
deferred: flag(row.deferred),
|
|
242
|
+
definition: text(row.definition) ?? "",
|
|
243
|
+
foreignColumns: integers(row.foreign_columns),
|
|
244
|
+
foreignTableId: integer(row.foreign_table_id),
|
|
245
|
+
kind: text(row.kind) ?? "",
|
|
246
|
+
name: text(row.name) ?? "",
|
|
247
|
+
nullsNotDistinct: flag(row.nulls_not_distinct),
|
|
248
|
+
onDelete: text(row.on_delete) ?? "a",
|
|
249
|
+
onUpdate: text(row.on_update) ?? "a",
|
|
250
|
+
tableId: integer(row.table_id),
|
|
251
|
+
...optional("checkExpression", text(row.check_expression)),
|
|
252
|
+
...optional("comment", text(row.comment))
|
|
253
|
+
};
|
|
254
|
+
return result;
|
|
255
|
+
};
|
|
256
|
+
var indexRow = (row) => {
|
|
257
|
+
const result = {
|
|
258
|
+
attnums: integers(row.attnums),
|
|
259
|
+
descending: flags(row.descending),
|
|
260
|
+
keyCount: integer(row.key_count),
|
|
261
|
+
method: text(row.method) ?? "btree",
|
|
262
|
+
name: text(row.name) ?? "",
|
|
263
|
+
parts: list(row.parts),
|
|
264
|
+
tableId: integer(row.table_id),
|
|
265
|
+
unique: flag(row.is_unique),
|
|
266
|
+
...optional("comment", text(row.comment)),
|
|
267
|
+
...optional("predicate", text(row.predicate))
|
|
268
|
+
};
|
|
269
|
+
return result;
|
|
270
|
+
};
|
|
271
|
+
var policyRow = (row) => {
|
|
272
|
+
const result = {
|
|
273
|
+
command: text(row.command) ?? "*",
|
|
274
|
+
name: text(row.name) ?? "",
|
|
275
|
+
permissive: flag(row.permissive),
|
|
276
|
+
roles: list(row.roles),
|
|
277
|
+
tableId: integer(row.table_id),
|
|
278
|
+
...optional("using", text(row.using)),
|
|
279
|
+
...optional("withCheck", text(row.with_check))
|
|
280
|
+
};
|
|
281
|
+
return result;
|
|
282
|
+
};
|
|
283
|
+
var namedRow = (row) => {
|
|
284
|
+
const result = {
|
|
285
|
+
name: text(row.name) ?? "",
|
|
286
|
+
schema: text(row.schema) ?? "",
|
|
287
|
+
...optional("comment", text(row.comment))
|
|
288
|
+
};
|
|
289
|
+
return result;
|
|
290
|
+
};
|
|
291
|
+
var enumRow = (row) => ({
|
|
292
|
+
name: text(row.name) ?? "",
|
|
293
|
+
schema: text(row.schema) ?? "",
|
|
294
|
+
values: list(row.values)
|
|
295
|
+
});
|
|
296
|
+
var sequenceRow = (row) => ({
|
|
297
|
+
increment: text(row.increment) ?? "1",
|
|
298
|
+
name: text(row.name) ?? "",
|
|
299
|
+
schema: text(row.schema) ?? "",
|
|
300
|
+
start: text(row.start) ?? "1"
|
|
301
|
+
});
|
|
302
|
+
var viewSourceRow = (row) => ({
|
|
303
|
+
sourceId: integer(row.source_id),
|
|
304
|
+
viewId: integer(row.view_id)
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
// src/postgres/index.ts
|
|
308
|
+
var DEFAULT_SCHEMA = "public";
|
|
309
|
+
var inSchema = (schema) => ({ schema });
|
|
310
|
+
var ACTIONS = {
|
|
311
|
+
a: undefined,
|
|
312
|
+
c: "cascade",
|
|
313
|
+
d: "set default",
|
|
314
|
+
n: "set null",
|
|
315
|
+
r: "restrict"
|
|
316
|
+
};
|
|
317
|
+
var QUOTED = /^'((?:[^']|'')*)'(?:::([\w\s."[\]()]+))?$/u;
|
|
318
|
+
var NUMBER = /^-?\d+(\.\d+)?$/u;
|
|
319
|
+
var NUMBER_CAST = /^\(?(-?\d+(?:\.\d+)?)\)?::[\w\s."]+$/u;
|
|
320
|
+
var NULL = /^NULL(::[\w\s."[\]()]+)?$/u;
|
|
321
|
+
var NUMERIC_TYPE = /^(smallint|integer|bigint|int[248]?|numeric(\(.*\))?|decimal(\(.*\))?|real|double precision|float[48]?)$/u;
|
|
322
|
+
var exactNumber = (digits) => {
|
|
323
|
+
const value = Number.parseFloat(digits);
|
|
324
|
+
const exact = digits.includes(".") || Number.isSafeInteger(value);
|
|
325
|
+
return exact ? value : undefined;
|
|
326
|
+
};
|
|
327
|
+
var numberDefault = (digits, expression) => {
|
|
328
|
+
const value = exactNumber(digits);
|
|
329
|
+
const result = value === undefined ? { kind: "expression", value: expression } : { kind: "number", value };
|
|
330
|
+
return result;
|
|
331
|
+
};
|
|
332
|
+
var quotedDefault = (inner, type, expression) => {
|
|
333
|
+
if (NUMERIC_TYPE.test(type) && NUMBER.test(inner))
|
|
334
|
+
return numberDefault(inner, expression);
|
|
335
|
+
const result = {
|
|
336
|
+
kind: "string",
|
|
337
|
+
value: inner.replaceAll("''", "'")
|
|
338
|
+
};
|
|
339
|
+
return result;
|
|
340
|
+
};
|
|
341
|
+
var parseDefault = (expression) => {
|
|
342
|
+
if (NULL.test(expression))
|
|
343
|
+
return { kind: "null" };
|
|
344
|
+
if (expression === "true" || expression === "false")
|
|
345
|
+
return {
|
|
346
|
+
kind: "boolean",
|
|
347
|
+
value: expression === "true"
|
|
348
|
+
};
|
|
349
|
+
if (NUMBER.test(expression))
|
|
350
|
+
return numberDefault(expression, expression);
|
|
351
|
+
const [, castDigits] = NUMBER_CAST.exec(expression) ?? [];
|
|
352
|
+
if (castDigits !== undefined)
|
|
353
|
+
return numberDefault(castDigits, expression);
|
|
354
|
+
const [, inner, type] = QUOTED.exec(expression) ?? [];
|
|
355
|
+
if (inner !== undefined)
|
|
356
|
+
return quotedDefault(inner, type ?? "", expression);
|
|
357
|
+
return { kind: "expression", value: expression };
|
|
358
|
+
};
|
|
359
|
+
var KINDS = {
|
|
360
|
+
f: "Foreign table",
|
|
361
|
+
m: "Materialized view",
|
|
362
|
+
p: "Partitioned table",
|
|
363
|
+
v: "View"
|
|
364
|
+
};
|
|
365
|
+
var VIEW_COLOR = "#64748b";
|
|
366
|
+
var POLICY_COMMANDS = {
|
|
367
|
+
"*": "all",
|
|
368
|
+
a: "insert",
|
|
369
|
+
d: "delete",
|
|
370
|
+
r: "select",
|
|
371
|
+
w: "update"
|
|
372
|
+
};
|
|
373
|
+
var joinNotes = (lines) => {
|
|
374
|
+
const present = lines.filter((line) => line !== undefined && line !== "");
|
|
375
|
+
return present.length > 0 ? present.join(`
|
|
376
|
+
`) : undefined;
|
|
377
|
+
};
|
|
378
|
+
var withNote = (note) => note === undefined ? {} : { note };
|
|
379
|
+
var identityNote = (identity) => {
|
|
380
|
+
if (identity === "a")
|
|
381
|
+
return "Identity, generated always";
|
|
382
|
+
if (identity === "d")
|
|
383
|
+
return "Identity, generated by default";
|
|
384
|
+
return;
|
|
385
|
+
};
|
|
386
|
+
var generatedNote = (row) => {
|
|
387
|
+
if (!row.generated || !row.default)
|
|
388
|
+
return;
|
|
389
|
+
const mode = row.generated === "v" ? "virtual" : "stored";
|
|
390
|
+
return `Generated always as (${row.default}), ${mode}`;
|
|
391
|
+
};
|
|
392
|
+
var isSerial = (row) => row.serialSequence !== undefined && row.default?.startsWith("nextval(") === true;
|
|
393
|
+
var enumSchema = (row) => row.enumType && row.enumSchema ? { typeSchema: row.enumSchema } : {};
|
|
394
|
+
var columnOf = (row) => {
|
|
395
|
+
const serial = isSerial(row);
|
|
396
|
+
const fallback = row.default !== undefined && !serial && !row.generated ? parseDefault(row.default) : undefined;
|
|
397
|
+
const column = {
|
|
398
|
+
name: row.name,
|
|
399
|
+
type: row.enumType ?? row.type,
|
|
400
|
+
...enumSchema(row),
|
|
401
|
+
...serial || row.identity ? { increment: true } : {},
|
|
402
|
+
...row.notNull ? { notNull: true } : {},
|
|
403
|
+
...fallback ? { default: fallback } : {},
|
|
404
|
+
...withNote(joinNotes([
|
|
405
|
+
row.comment,
|
|
406
|
+
identityNote(row.identity),
|
|
407
|
+
generatedNote(row)
|
|
408
|
+
]))
|
|
409
|
+
};
|
|
410
|
+
return column;
|
|
411
|
+
};
|
|
412
|
+
var constraintNote = (row) => joinNotes([
|
|
413
|
+
row.comment,
|
|
414
|
+
row.deferrable ? `Deferrable${row.deferred ? ", initially deferred" : ""}` : undefined,
|
|
415
|
+
row.nullsNotDistinct ? "Nulls not distinct" : undefined
|
|
416
|
+
]);
|
|
417
|
+
var defaultName = (row, table, columns) => {
|
|
418
|
+
if (row.kind === "p")
|
|
419
|
+
return `${table}_pkey`;
|
|
420
|
+
if (row.kind === "f")
|
|
421
|
+
return `${table}_${columns.join("_")}_fkey`;
|
|
422
|
+
return `${table}_${columns.join("_")}_key`;
|
|
423
|
+
};
|
|
424
|
+
var columnParts = (columns) => columns.map((column) => ({ column, kind: "column" }));
|
|
425
|
+
var markColumn = (column, primary) => {
|
|
426
|
+
if (!primary) {
|
|
427
|
+
column.unique = true;
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
column.pk = true;
|
|
431
|
+
delete column.notNull;
|
|
432
|
+
};
|
|
433
|
+
var applyKey = (table, row, columns) => {
|
|
434
|
+
const primary = row.kind === "p";
|
|
435
|
+
const plain = row.name === defaultName(row, table.name, columns);
|
|
436
|
+
const note = constraintNote(row);
|
|
437
|
+
const [only] = columns;
|
|
438
|
+
const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
|
|
439
|
+
if (single && plain && note === undefined) {
|
|
440
|
+
markColumn(single, primary);
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
const index = {
|
|
444
|
+
parts: columnParts(columns),
|
|
445
|
+
...primary ? { pk: true } : { unique: true },
|
|
446
|
+
...plain ? {} : { name: row.name },
|
|
447
|
+
...withNote(note)
|
|
448
|
+
};
|
|
449
|
+
table.indexes.push(index);
|
|
450
|
+
};
|
|
451
|
+
var sortedColumns = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
|
|
452
|
+
var coversAll = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
|
|
453
|
+
var isUniqueSet = (table, columns) => {
|
|
454
|
+
const [only] = columns;
|
|
455
|
+
const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
|
|
456
|
+
if (single?.pk === true || single?.unique === true)
|
|
457
|
+
return true;
|
|
458
|
+
const wanted = [...columns].sort().join("\x00");
|
|
459
|
+
return table.indexes.some((index) => coversAll(index) && index.parts.every((part) => part.kind === "column") && sortedColumns(index) === wanted);
|
|
460
|
+
};
|
|
461
|
+
var refOf = (row, context) => {
|
|
462
|
+
const source = context.relations.get(row.tableId);
|
|
463
|
+
const target = context.relations.get(row.foreignTableId);
|
|
464
|
+
const table = context.tables.get(row.tableId);
|
|
465
|
+
if (!source || !target || !table)
|
|
466
|
+
return;
|
|
467
|
+
const columns = row.columns.map((position) => context.columnName(source.id, position));
|
|
468
|
+
const onDelete = ACTIONS[row.onDelete];
|
|
469
|
+
const onUpdate = ACTIONS[row.onUpdate];
|
|
470
|
+
const ref = {
|
|
471
|
+
from: { columns, ...inSchema(source.schema), table: source.name },
|
|
472
|
+
...row.name === defaultName(row, source.name, columns) ? {} : { name: row.name },
|
|
473
|
+
...onDelete ? { onDelete } : {},
|
|
474
|
+
...onUpdate ? { onUpdate } : {},
|
|
475
|
+
relation: isUniqueSet(table, columns) ? "-" : ">",
|
|
476
|
+
to: {
|
|
477
|
+
columns: row.foreignColumns.map((position) => context.columnName(target.id, position)),
|
|
478
|
+
...inSchema(target.schema),
|
|
479
|
+
table: target.name
|
|
480
|
+
},
|
|
481
|
+
...withNote(constraintNote(row))
|
|
482
|
+
};
|
|
483
|
+
return ref;
|
|
484
|
+
};
|
|
485
|
+
var partOf = (row, index, context) => {
|
|
486
|
+
const desc = row.descending[index] === true ? { desc: true } : {};
|
|
487
|
+
const position = row.attnums[index] ?? 0;
|
|
488
|
+
if (position > 0)
|
|
489
|
+
return {
|
|
490
|
+
column: context.columnName(row.tableId, position),
|
|
491
|
+
kind: "column",
|
|
492
|
+
...desc
|
|
493
|
+
};
|
|
494
|
+
return {
|
|
495
|
+
expression: row.parts[index] ?? "",
|
|
496
|
+
kind: "expression",
|
|
497
|
+
...desc
|
|
498
|
+
};
|
|
499
|
+
};
|
|
500
|
+
var indexOf = (row, context) => {
|
|
501
|
+
const included = row.parts.slice(row.keyCount);
|
|
502
|
+
const index = {
|
|
503
|
+
name: row.name,
|
|
504
|
+
parts: row.parts.slice(0, row.keyCount).map((_, position) => partOf(row, position, context)),
|
|
505
|
+
...row.method === "btree" ? {} : { type: row.method },
|
|
506
|
+
...row.unique ? { unique: true } : {},
|
|
507
|
+
...withNote(joinNotes([
|
|
508
|
+
row.comment,
|
|
509
|
+
row.predicate ? `Where ${row.predicate}` : undefined,
|
|
510
|
+
included.length > 0 ? `Includes ${included.join(", ")}` : undefined
|
|
511
|
+
]))
|
|
512
|
+
};
|
|
513
|
+
return index;
|
|
514
|
+
};
|
|
515
|
+
var policyLine = (row) => [
|
|
516
|
+
`Policy ${row.name}`,
|
|
517
|
+
row.permissive ? undefined : "restrictive",
|
|
518
|
+
`for ${POLICY_COMMANDS[row.command] ?? "all"}`,
|
|
519
|
+
`to ${row.roles.join(", ")}`,
|
|
520
|
+
row.using ? `using (${row.using})` : undefined,
|
|
521
|
+
row.withCheck ? `with check (${row.withCheck})` : undefined
|
|
522
|
+
].filter((part) => part !== undefined).join(" ");
|
|
523
|
+
var MAX_DEFINITION = 600;
|
|
524
|
+
var kindLine = (relation) => {
|
|
525
|
+
const kind = KINDS[relation.kind];
|
|
526
|
+
const definition = relation.definition?.trim();
|
|
527
|
+
if (!kind || !definition)
|
|
528
|
+
return kind;
|
|
529
|
+
const shown = definition.length > MAX_DEFINITION ? `${definition.slice(0, MAX_DEFINITION)}\u2026` : definition;
|
|
530
|
+
return `${kind}:
|
|
531
|
+
${shown}`;
|
|
532
|
+
};
|
|
533
|
+
var tableNote = (relation, policies) => joinNotes([
|
|
534
|
+
relation.comment,
|
|
535
|
+
kindLine(relation),
|
|
536
|
+
relation.partitionKey ? `Partitioned by ${relation.partitionKey}, ${relation.partitions} partitions` : undefined,
|
|
537
|
+
relation.rls ? `Row-level security is on${relation.forceRls ? ", for the owner too" : ""}` : undefined,
|
|
538
|
+
...policies.map(policyLine)
|
|
539
|
+
]);
|
|
540
|
+
var recordValue = (value) => {
|
|
541
|
+
if (value === null || value === undefined)
|
|
542
|
+
return null;
|
|
543
|
+
if (typeof value === "boolean" || typeof value === "string")
|
|
544
|
+
return value;
|
|
545
|
+
if (typeof value === "number")
|
|
546
|
+
return Number.isFinite(value) ? value : `${value}`;
|
|
547
|
+
if (typeof value === "bigint")
|
|
548
|
+
return `${value}`;
|
|
549
|
+
if (value instanceof Date)
|
|
550
|
+
return value.toISOString();
|
|
551
|
+
if (value instanceof Uint8Array)
|
|
552
|
+
return `\\x${Buffer.from(value).toString("hex")}`;
|
|
553
|
+
return JSON.stringify(value);
|
|
554
|
+
};
|
|
555
|
+
var quoteIdent = (name) => `"${name.replaceAll('"', '""')}"`;
|
|
556
|
+
var readRecords = (query, tables, limit) => Promise.all(tables.map(async (table) => {
|
|
557
|
+
const columns = table.columns.map((column) => column.name);
|
|
558
|
+
const from = `${quoteIdent(table.schema ?? DEFAULT_SCHEMA)}.${quoteIdent(table.name)}`;
|
|
559
|
+
const rows = await query(`select ${columns.map(quoteIdent).join(", ")} from ${from} limit ${Math.max(0, Math.floor(limit))}`, []);
|
|
560
|
+
const records = {
|
|
561
|
+
columns,
|
|
562
|
+
rows: rows.map((row) => columns.map((column) => recordValue(row[column]))),
|
|
563
|
+
...table.schema ? { schema: table.schema } : {},
|
|
564
|
+
table: table.name
|
|
565
|
+
};
|
|
566
|
+
return records;
|
|
567
|
+
}));
|
|
568
|
+
var tableOf = (relation, columns, policies) => {
|
|
569
|
+
const view = relation.kind === "v" || relation.kind === "m";
|
|
570
|
+
const table = {
|
|
571
|
+
checks: [],
|
|
572
|
+
columns: columns.filter((row) => row.tableId === relation.id).map(columnOf),
|
|
573
|
+
...view ? { headerColor: VIEW_COLOR } : {},
|
|
574
|
+
indexes: [],
|
|
575
|
+
name: relation.name,
|
|
576
|
+
...inSchema(relation.schema),
|
|
577
|
+
...withNote(tableNote(relation, policies.filter((row) => row.tableId === relation.id)))
|
|
578
|
+
};
|
|
579
|
+
return table;
|
|
580
|
+
};
|
|
581
|
+
var applyConstraints = (rows, context) => rows.filter((row) => {
|
|
582
|
+
const table = context.tables.get(row.tableId);
|
|
583
|
+
if (!table || row.kind === "f")
|
|
584
|
+
return table !== undefined;
|
|
585
|
+
const columns = row.columns.map((position) => context.columnName(row.tableId, position));
|
|
586
|
+
if (row.kind === "p" || row.kind === "u")
|
|
587
|
+
applyKey(table, row, columns);
|
|
588
|
+
if (row.kind === "c")
|
|
589
|
+
table.checks.push({
|
|
590
|
+
expression: (row.checkExpression ?? row.definition).replace(/^\((.*)\)$/su, "$1"),
|
|
591
|
+
name: row.name
|
|
592
|
+
});
|
|
593
|
+
if (row.kind === "x")
|
|
594
|
+
table.indexes.push({
|
|
595
|
+
name: row.name,
|
|
596
|
+
note: `Exclusion constraint: ${row.definition}`,
|
|
597
|
+
parts: columnParts(columns)
|
|
598
|
+
});
|
|
599
|
+
return false;
|
|
600
|
+
});
|
|
601
|
+
var sequenceNote = (rows, defaultSchema) => ({
|
|
602
|
+
content: `Sequences
|
|
603
|
+
${rows.map((row) => `${row.schema === defaultSchema ? "" : `${row.schema}.`}${row.name}: start ${row.start}, increment ${row.increment}`).join(`
|
|
604
|
+
`)}`,
|
|
605
|
+
name: "sequences"
|
|
606
|
+
});
|
|
607
|
+
var readCatalogs = async (query, schemas) => {
|
|
608
|
+
const read = (sql) => query(sql, [schemas]);
|
|
609
|
+
const [
|
|
610
|
+
enums,
|
|
611
|
+
relations,
|
|
612
|
+
columns,
|
|
613
|
+
constraints,
|
|
614
|
+
indexes,
|
|
615
|
+
sources,
|
|
616
|
+
policies,
|
|
617
|
+
sequences,
|
|
618
|
+
comments
|
|
619
|
+
] = await Promise.all([
|
|
620
|
+
read(ENUMS),
|
|
621
|
+
read(RELATIONS),
|
|
622
|
+
read(COLUMNS),
|
|
623
|
+
read(CONSTRAINTS),
|
|
624
|
+
read(INDEXES),
|
|
625
|
+
read(VIEW_SOURCES),
|
|
626
|
+
read(POLICIES),
|
|
627
|
+
read(SEQUENCES),
|
|
628
|
+
read(SCHEMA_COMMENTS)
|
|
629
|
+
]);
|
|
630
|
+
return {
|
|
631
|
+
columns: columns.map(columnRow),
|
|
632
|
+
comments: comments.map(namedRow),
|
|
633
|
+
constraints: constraints.map(constraintRow),
|
|
634
|
+
enums: enums.map(enumRow),
|
|
635
|
+
indexes: indexes.map(indexRow),
|
|
636
|
+
policies: policies.map(policyRow),
|
|
637
|
+
relations: relations.map(relationRow),
|
|
638
|
+
sequences: sequences.map(sequenceRow),
|
|
639
|
+
sources: sources.map(viewSourceRow)
|
|
640
|
+
};
|
|
641
|
+
};
|
|
642
|
+
var schemasToRead = async (query, schemas) => schemas ?? (await query(SCHEMAS, [])).map((row) => namedRow(row).name);
|
|
643
|
+
var addDeps = (model, catalogs, relations) => catalogs.sources.forEach((row) => {
|
|
644
|
+
const view = relations.get(row.viewId);
|
|
645
|
+
const source = relations.get(row.sourceId);
|
|
646
|
+
if (view && source)
|
|
647
|
+
model.deps.push({
|
|
648
|
+
downstream: { ...inSchema(view.schema), table: view.name },
|
|
649
|
+
upstream: { ...inSchema(source.schema), table: source.name }
|
|
650
|
+
});
|
|
651
|
+
});
|
|
652
|
+
var addNotes = (model, catalogs, defaultSchema) => {
|
|
653
|
+
if (catalogs.sequences.length > 0)
|
|
654
|
+
model.notes.push(sequenceNote(catalogs.sequences, defaultSchema));
|
|
655
|
+
const described = catalogs.comments.filter((row) => row.comment !== undefined && row.name !== defaultSchema);
|
|
656
|
+
if (described.length > 0)
|
|
657
|
+
model.notes.push({
|
|
658
|
+
content: `Schemas
|
|
659
|
+
${described.map((row) => `${row.name}: ${row.comment}`).join(`
|
|
660
|
+
`)}`,
|
|
661
|
+
name: "schemas"
|
|
662
|
+
});
|
|
663
|
+
};
|
|
664
|
+
var fromPostgres = async (query, options = {}) => {
|
|
665
|
+
const catalogs = await readCatalogs(query, await schemasToRead(query, options.schemas));
|
|
666
|
+
const model = emptyModel({
|
|
667
|
+
databaseType: "PostgreSQL",
|
|
668
|
+
...options.project
|
|
669
|
+
});
|
|
670
|
+
model.enums.push(...catalogs.enums.map((row) => ({
|
|
671
|
+
name: row.name,
|
|
672
|
+
...inSchema(row.schema),
|
|
673
|
+
values: row.values.map((name) => ({ name }))
|
|
674
|
+
})));
|
|
675
|
+
const relations = new Map(catalogs.relations.map((row) => [row.id, row]));
|
|
676
|
+
const names = new Map(catalogs.columns.map((row) => [
|
|
677
|
+
`${row.tableId}:${row.position}`,
|
|
678
|
+
row.name
|
|
679
|
+
]));
|
|
680
|
+
const tables = new Map(catalogs.relations.map((row) => [
|
|
681
|
+
row.id,
|
|
682
|
+
tableOf(row, catalogs.columns, catalogs.policies)
|
|
683
|
+
]));
|
|
684
|
+
const context = {
|
|
685
|
+
relations,
|
|
686
|
+
tables,
|
|
687
|
+
columnName: (tableId, position) => names.get(`${tableId}:${position}`) ?? `${position}`
|
|
688
|
+
};
|
|
689
|
+
const foreign = applyConstraints(catalogs.constraints, context);
|
|
690
|
+
catalogs.indexes.forEach((row) => tables.get(row.tableId)?.indexes.push(indexOf(row, context)));
|
|
691
|
+
model.tables.push(...tables.values());
|
|
692
|
+
model.refs.push(...foreign.map((row) => refOf(row, context)).filter((ref) => ref !== undefined));
|
|
693
|
+
addDeps(model, catalogs, relations);
|
|
694
|
+
const defaultSchema = options.defaultSchema ?? DEFAULT_SCHEMA;
|
|
695
|
+
addNotes(model, catalogs, defaultSchema);
|
|
696
|
+
const limit = options.records?.limit ?? 0;
|
|
697
|
+
if (limit > 0)
|
|
698
|
+
model.records.push(...await readRecords(query, model.tables.filter((table) => !table.headerColor), limit));
|
|
699
|
+
return withDefaultSchema(model, defaultSchema);
|
|
700
|
+
};
|
|
701
|
+
export {
|
|
702
|
+
fromPostgres,
|
|
703
|
+
parseDefault
|
|
704
|
+
};
|