@absolutejs/dbml 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,164 @@ var emptyModel = (project) => ({
13
13
  tableGroups: [],
14
14
  tables: []
15
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
+ var groupBySchema = (tables, defaultSchema = "public") => {
54
+ const byName = new Map;
55
+ tables.forEach((table) => {
56
+ const name = table.schema ?? defaultSchema;
57
+ byName.set(name, [
58
+ ...byName.get(name) ?? [],
59
+ {
60
+ ...table.schema ? { schema: table.schema } : {},
61
+ table: table.name
62
+ }
63
+ ]);
64
+ });
65
+ return [...byName].map(([name, members]) => {
66
+ const group = { name, tables: members };
67
+ return group;
68
+ });
69
+ };
70
+ var sortedColumns = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
71
+ var coversAll = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
72
+ var isUniqueSet = (table, columns) => {
73
+ const [only] = columns;
74
+ const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
75
+ if (single?.pk === true || single?.unique === true)
76
+ return true;
77
+ const wanted = [...columns].sort().join("\x00");
78
+ return table.indexes.some((index) => coversAll(index) && index.parts.every((part) => part.kind === "column") && sortedColumns(index) === wanted);
79
+ };
80
+
81
+ // src/postgres/details.ts
82
+ var present = (lines) => lines.filter((line) => line !== undefined && line !== "");
83
+ var withMetadata = (metadata) => Object.keys(metadata).length > 0 ? { metadata } : {};
84
+ var DEFAULT_IDENTITY = "1 1";
85
+ var columnMetadata = (row) => {
86
+ const [start, increment] = (row.identitySequence ?? "").split(" ");
87
+ const identity = row.identitySequence && row.identitySequence !== DEFAULT_IDENTITY ? {
88
+ identity_increment: Number.parseInt(increment ?? "1", 10),
89
+ identity_start: Number.parseInt(start ?? "1", 10)
90
+ } : {};
91
+ const metadata = {
92
+ ...row.collation ? { collation: row.collation } : {},
93
+ ...row.compression ? { compression: row.compression } : {},
94
+ ...row.domainBase ? { domain_of: row.domainBase } : {},
95
+ ...identity
96
+ };
97
+ return withMetadata(metadata);
98
+ };
99
+ var nullsOrdering = (row, part, name) => {
100
+ const descending = row.descending[part] === true;
101
+ const nullsFirst = row.nullsFirst[part] === true;
102
+ if (descending === nullsFirst)
103
+ return;
104
+ return `${name} nulls ${nullsFirst ? "first" : "last"}`;
105
+ };
106
+ var indexNotes = (row, partName) => {
107
+ const parts = Array.from({ length: row.keyCount }, (_, part) => part);
108
+ const nulls = present(parts.map((part) => nullsOrdering(row, part, partName(part))));
109
+ const classes = present(parts.map((part) => row.opclasses[part] ? `${partName(part)} ${row.opclasses[part]}` : undefined));
110
+ const collations = present(parts.map((part) => row.collations[part] ? `${partName(part)} ${row.collations[part]}` : undefined));
111
+ return present([
112
+ nulls.length > 0 ? `Sorted with ${nulls.join(", ")}` : undefined,
113
+ classes.length > 0 ? `Operator class: ${classes.join(", ")}` : undefined,
114
+ collations.length > 0 ? `Collation: ${collations.join(", ")}` : undefined,
115
+ row.nullsNotDistinct ? "Nulls not distinct" : undefined
116
+ ]);
117
+ };
118
+ var tableMetadata = (relation, statistics) => {
119
+ const metadata = {
120
+ ...relation.owner ? { owner: relation.owner } : {},
121
+ ...relation.grants ? { grants: relation.grants } : {},
122
+ ...relation.persistence === "u" ? { unlogged: true } : {},
123
+ ...relation.options ? { options: relation.options } : {},
124
+ ...relation.foreignServer ? { foreign_server: relation.foreignServer } : {},
125
+ ...relation.foreignOptions ? { foreign_options: relation.foreignOptions } : {},
126
+ ...relation.inherits ? { inherits: relation.inherits } : {},
127
+ ...statistics && relation.rowEstimate ? { rows: Number.parseInt(relation.rowEstimate, 10) } : {},
128
+ ...statistics && relation.sizeBytes ? { size_bytes: Number.parseInt(relation.sizeBytes, 10) } : {}
129
+ };
130
+ return withMetadata(metadata);
131
+ };
132
+ var DISABLED = "D";
133
+ var definitionLine = (kind, entry) => {
134
+ const body = entry.definition.replace(/^CREATE (OR REPLACE )?(CONSTRAINT )?(TRIGGER|RULE) /u, "");
135
+ return `${kind} ${body}${entry.enabled === DISABLED ? " (disabled)" : ""}`;
136
+ };
137
+ var tableNoteLines = (input) => present([
138
+ input.inherits ? `Inherits from ${input.inherits}` : undefined,
139
+ ...input.partitions.map((partition) => `Partition ${partition.name}: ${partition.bound}`),
140
+ ...input.triggers.map((trigger) => definitionLine("Trigger", trigger)),
141
+ ...input.rules.map((rule) => definitionLine("Rule", rule))
142
+ ]);
143
+ var KINDS = {
144
+ a: "aggregate",
145
+ f: "function",
146
+ p: "procedure",
147
+ w: "window function"
148
+ };
149
+ var qualified = (schema, name, defaultSchema) => schema === defaultSchema ? name : `${schema}.${name}`;
150
+ var sticky = (name, title, lines) => {
151
+ if (lines.length === 0)
152
+ return [];
153
+ const note = {
154
+ content: `${title}
155
+ ${lines.join(`
156
+ `)}`,
157
+ name
158
+ };
159
+ return [note];
160
+ };
161
+ var domainLine = (domain, defaultSchema) => [
162
+ `${qualified(domain.schema, domain.name, defaultSchema)}: ${domain.base}`,
163
+ domain.notNull ? "not null" : undefined,
164
+ domain.default ? `default ${domain.default}` : undefined,
165
+ domain.constraints
166
+ ].filter((part) => part !== undefined).join(", ");
167
+ var extraNotes = (extras, defaultSchema) => [
168
+ ...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}`)),
169
+ ...sticky("domains", "Domains", extras.domains.map((domain) => domainLine(domain, defaultSchema))),
170
+ ...sticky("composite_types", "Composite types", extras.composites.map((entry) => `${qualified(entry.schema, entry.name, defaultSchema)}: ${entry.fields}`)),
171
+ ...sticky("extensions", "Extensions", extras.extensions.map((entry) => `${entry.name} ${entry.version}, in ${entry.schema}`)),
172
+ ...sticky("event_triggers", "Event triggers", extras.eventTriggers.map((entry) => `${entry.name}: on ${entry.event}, runs ${entry.function}${entry.enabled === DISABLED ? " (disabled)" : ""}`))
173
+ ];
16
174
 
17
175
  // src/postgres/queries.ts
18
176
  var SCHEMAS = `
@@ -28,6 +186,7 @@ from pg_type t
28
186
  join pg_namespace n on n.oid = t.typnamespace
29
187
  join pg_enum e on e.enumtypid = t.oid
30
188
  where n.nspname = any($1)
189
+ and not exists (select 1 from pg_depend x where x.classid = 'pg_type'::regclass and x.objid = t.oid and x.deptype = 'e')
31
190
  group by n.nspname, t.typname
32
191
  order by n.nspname, t.typname`;
33
192
  var RELATIONS = `
@@ -36,10 +195,23 @@ select c.oid::int as id, n.nspname as schema, c.relname as name, c.relkind as ki
36
195
  c.relrowsecurity as rls, c.relforcerowsecurity as force_rls,
37
196
  case when c.relkind = 'p' then pg_get_partkeydef(c.oid) end as partition_key,
38
197
  case when c.relkind in ('v', 'm') then pg_get_viewdef(c.oid, true) end as definition,
39
- (select count(*)::int from pg_inherits i where i.inhparent = c.oid) as partitions
198
+ (select count(*)::int from pg_inherits i where i.inhparent = c.oid) as partitions,
199
+ pg_get_userbyid(c.relowner) as owner,
200
+ c.relpersistence as persistence,
201
+ array_to_string(c.reloptions, ', ') as options,
202
+ case when c.reltuples >= 0 then c.reltuples::bigint::text end as row_estimate,
203
+ case when c.relkind in ('r', 'p', 'm') then pg_total_relation_size(c.oid)::text end as size_bytes,
204
+ (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)
205
+ from aclexplode(c.relacl) as g where g.grantee <> c.relowner) as grants,
206
+ (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,
207
+ (select array_to_string(ft.ftoptions, ', ') from pg_foreign_table ft where ft.ftrelid = c.oid) as foreign_options,
208
+ (select string_agg(quote_ident(pn.nspname) || '.' || quote_ident(p.relname), ', ')
209
+ from pg_inherits i join pg_class p on p.oid = i.inhparent join pg_namespace pn on pn.oid = p.relnamespace
210
+ where i.inhrelid = c.oid and p.relkind <> 'p') as inherits
40
211
  from pg_class c
41
212
  join pg_namespace n on n.oid = c.relnamespace
42
213
  where n.nspname = any($1) and c.relkind in ('r', 'p', 'v', 'm', 'f') and not c.relispartition
214
+ and not exists (select 1 from pg_depend e where e.classid = 'pg_class'::regclass and e.objid = c.oid and e.deptype = 'e')
43
215
  order by n.nspname, c.relname`;
44
216
  var COLUMNS = `
45
217
  select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name,
@@ -51,7 +223,12 @@ select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name
51
223
  when et.typtype = 'e' then etn.nspname end as enum_schema,
52
224
  coalesce(case when t.typtype = 'e' then t.typname end,
53
225
  case when et.typtype = 'e' then et.typname || '[]' end) as enum_type,
54
- pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname) as serial_sequence
226
+ pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname) as serial_sequence,
227
+ case when a.attcollation <> 0 and a.attcollation <> t.typcollation then (select collname from pg_collation where oid = a.attcollation) end as collation,
228
+ case to_jsonb(a) ->> 'attcompression' when 'p' then 'pglz' when 'l' then 'lz4' end as compression,
229
+ case when a.attidentity <> '' then (select s.seqstart::text || ' ' || s.seqincrement::text from pg_sequence s
230
+ where s.seqrelid = pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname)::regclass) end as identity_sequence,
231
+ case when t.typtype = 'd' then format_type(t.typbasetype, t.typtypmod) end as domain_base
55
232
  from pg_attribute a
56
233
  join pg_class c on c.oid = a.attrelid
57
234
  join pg_namespace n on n.oid = c.relnamespace
@@ -89,6 +266,17 @@ select i.indrelid::int as table_id, ic.relname as name, am.amname as method,
89
266
  from generate_series(1, i.indnatts) as k) as attnums,
90
267
  (select array_agg((i.indoption[k - 1] & 1) = 1 order by k)
91
268
  from generate_series(1, i.indnkeyatts) as k) as descending,
269
+ (select array_agg((i.indoption[k - 1] & 2) = 2 order by k)
270
+ from generate_series(1, i.indnkeyatts) as k) as nulls_first,
271
+ /* An operator class or collation that isn't the column's own, per key
272
+ * part, empty where it is. */
273
+ (select array_agg(case when opc.opcdefault then '' else opc.opcname end order by k)
274
+ from generate_series(1, i.indnkeyatts) as k join pg_opclass opc on opc.oid = i.indclass[k - 1]) as opclasses,
275
+ (select array_agg(coalesce((select co.collname from pg_collation co where co.oid = i.indcollation[k - 1]
276
+ 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)
277
+ and co.collname <> 'default'), '') order by k)
278
+ from generate_series(1, i.indnkeyatts) as k) as collations,
279
+ (to_jsonb(i) ->> 'indnullsnotdistinct')::boolean as nulls_not_distinct,
92
280
  pg_get_expr(i.indpred, i.indrelid, true) as predicate,
93
281
  obj_description(i.indexrelid, 'pg_class') as comment
94
282
  from pg_index i
@@ -130,6 +318,81 @@ order by n.nspname, c.relname`;
130
318
  var SCHEMA_COMMENTS = `
131
319
  select nspname as name, obj_description(oid, 'pg_namespace') as comment
132
320
  from pg_namespace where nspname = any($1)`;
321
+ var TRIGGERS = `
322
+ select t.tgrelid::int as table_id, t.tgname as name, pg_get_triggerdef(t.oid, true) as definition,
323
+ t.tgenabled as enabled
324
+ from pg_trigger t
325
+ join pg_class c on c.oid = t.tgrelid
326
+ join pg_namespace n on n.oid = c.relnamespace
327
+ where n.nspname = any($1) and not t.tgisinternal
328
+ order by t.tgrelid, t.tgname`;
329
+ var RULES = `
330
+ select r.ev_class::int as table_id, r.rulename as name, pg_get_ruledef(r.oid, true) as definition
331
+ from pg_rewrite r
332
+ join pg_class c on c.oid = r.ev_class
333
+ join pg_namespace n on n.oid = c.relnamespace
334
+ where n.nspname = any($1) and r.rulename <> '_RETURN'
335
+ order by r.ev_class, r.rulename`;
336
+ var FUNCTIONS = `
337
+ select n.nspname as schema, p.proname as name, p.prokind as kind,
338
+ pg_get_function_identity_arguments(p.oid) as arguments,
339
+ pg_get_function_result(p.oid) as result, l.lanname as language
340
+ from pg_proc p
341
+ join pg_namespace n on n.oid = p.pronamespace
342
+ join pg_language l on l.oid = p.prolang
343
+ where n.nspname = any($1)
344
+ and not exists (select 1 from pg_depend e where e.classid = 'pg_proc'::regclass and e.objid = p.oid and e.deptype = 'e')
345
+ order by n.nspname, p.proname, arguments`;
346
+ var DOMAINS = `
347
+ select n.nspname as schema, t.typname as name, format_type(t.typbasetype, t.typtypmod) as base,
348
+ t.typnotnull as not_null, t.typdefault as "default",
349
+ (select string_agg(pg_get_constraintdef(con.oid, true), ' and ' order by con.conname)
350
+ /* Postgres 17 also keeps NOT NULL as a constraint; typnotnull says it. */
351
+ from pg_constraint con where con.contypid = t.oid and con.contype <> 'n') as constraints
352
+ from pg_type t
353
+ join pg_namespace n on n.oid = t.typnamespace
354
+ where n.nspname = any($1) and t.typtype = 'd'
355
+ and not exists (select 1 from pg_depend e where e.classid = 'pg_type'::regclass and e.objid = t.oid and e.deptype = 'e')
356
+ order by n.nspname, t.typname`;
357
+ var COMPOSITES = `
358
+ select n.nspname as schema, t.typname as name,
359
+ string_agg(a.attname || ' ' || format_type(a.atttypid, a.atttypmod), ', ' order by a.attnum) as fields
360
+ from pg_type t
361
+ join pg_namespace n on n.oid = t.typnamespace
362
+ join pg_class c on c.oid = t.typrelid and c.relkind = 'c'
363
+ join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
364
+ where n.nspname = any($1)
365
+ and not exists (select 1 from pg_depend e where e.classid = 'pg_type'::regclass and e.objid = t.oid and e.deptype = 'e')
366
+ group by n.nspname, t.typname
367
+ order by n.nspname, t.typname`;
368
+ var EXTENSIONS = `
369
+ select e.extname as name, e.extversion as version, n.nspname as schema
370
+ from pg_extension e
371
+ join pg_namespace n on n.oid = e.extnamespace
372
+ where e.extname <> 'plpgsql'
373
+ order by e.extname`;
374
+ var EVENT_TRIGGERS = `
375
+ select evtname as name, evtevent as event, evtfoid::regproc::text as function, evtenabled as enabled
376
+ from pg_event_trigger
377
+ order by evtname`;
378
+ var PARTITIONS = `
379
+ select i.inhparent::int as table_id, c.relname as name, pg_get_expr(c.relpartbound, c.oid, true) as bound
380
+ from pg_inherits i
381
+ join pg_class c on c.oid = i.inhrelid
382
+ join pg_class p on p.oid = i.inhparent
383
+ join pg_namespace n on n.oid = p.relnamespace
384
+ where n.nspname = any($1) and p.relkind = 'p'
385
+ order by i.inhparent, c.relname`;
386
+ var VIEW_COLUMNS = `
387
+ select distinct v.oid::int as view_id, d.refobjid::int as source_id, a.attname as name
388
+ from pg_class v
389
+ join pg_namespace n on n.oid = v.relnamespace
390
+ join pg_rewrite r on r.ev_class = v.oid
391
+ join pg_depend d on d.objid = r.oid and d.classid = 'pg_rewrite'::regclass
392
+ and d.refclassid = 'pg_class'::regclass and d.refobjid <> v.oid and d.refobjsubid > 0
393
+ join pg_attribute a on a.attrelid = d.refobjid and a.attnum = d.refobjsubid
394
+ where n.nspname = any($1) and v.relkind in ('v', 'm')
395
+ order by view_id, source_id, name`;
133
396
 
134
397
  // src/postgres/rows.ts
135
398
  var optional = (key, value) => {
@@ -168,11 +431,20 @@ var relationRow = (row) => {
168
431
  kind: text(row.kind) ?? "",
169
432
  name: text(row.name) ?? "",
170
433
  partitions: integer(row.partitions),
434
+ persistence: text(row.persistence) ?? "p",
171
435
  rls: flag(row.rls),
172
436
  schema: text(row.schema) ?? "",
173
437
  ...optional("comment", text(row.comment)),
174
438
  ...optional("definition", text(row.definition)),
175
- ...optional("partitionKey", text(row.partition_key))
439
+ ...optional("foreignOptions", setting(row.foreign_options)),
440
+ ...optional("foreignServer", text(row.foreign_server)),
441
+ ...optional("grants", text(row.grants)),
442
+ ...optional("inherits", text(row.inherits)),
443
+ ...optional("options", setting(row.options)),
444
+ ...optional("owner", text(row.owner)),
445
+ ...optional("partitionKey", text(row.partition_key)),
446
+ ...optional("rowEstimate", text(row.row_estimate)),
447
+ ...optional("sizeBytes", text(row.size_bytes))
176
448
  };
177
449
  return result;
178
450
  };
@@ -187,12 +459,16 @@ var columnRow = (row) => {
187
459
  position: integer(row.position),
188
460
  tableId: integer(row.table_id),
189
461
  type: text(row.type) ?? "",
462
+ ...optional("collation", text(row.collation)),
190
463
  ...optional("comment", text(row.comment)),
464
+ ...optional("compression", text(row.compression)),
191
465
  ...optional("default", text(row.default)),
466
+ ...optional("domainBase", text(row.domain_base)),
192
467
  ...optional("enumSchema", text(row.enum_schema)),
193
468
  ...optional("enumType", text(row.enum_type)),
194
469
  ...optional("generated", setting(row.generated)),
195
470
  ...optional("identity", setting(row.identity)),
471
+ ...optional("identitySequence", text(row.identity_sequence)),
196
472
  ...optional("serialSequence", text(row.serial_sequence))
197
473
  };
198
474
  return result;
@@ -219,10 +495,14 @@ var constraintRow = (row) => {
219
495
  var indexRow = (row) => {
220
496
  const result = {
221
497
  attnums: integers(row.attnums),
498
+ collations: list(row.collations),
222
499
  descending: flags(row.descending),
223
500
  keyCount: integer(row.key_count),
224
501
  method: text(row.method) ?? "btree",
225
502
  name: text(row.name) ?? "",
503
+ nullsFirst: flags(row.nulls_first),
504
+ nullsNotDistinct: flag(row.nulls_not_distinct),
505
+ opclasses: list(row.opclasses),
226
506
  parts: list(row.parts),
227
507
  tableId: integer(row.table_id),
228
508
  unique: flag(row.is_unique),
@@ -266,10 +546,58 @@ var viewSourceRow = (row) => ({
266
546
  sourceId: integer(row.source_id),
267
547
  viewId: integer(row.view_id)
268
548
  });
549
+ var definitionRow = (row) => ({
550
+ definition: text(row.definition) ?? "",
551
+ enabled: text(row.enabled) ?? "O",
552
+ name: text(row.name) ?? "",
553
+ tableId: integer(row.table_id)
554
+ });
555
+ var functionRow = (row) => ({
556
+ arguments: text(row.arguments) ?? "",
557
+ kind: text(row.kind) ?? "f",
558
+ language: text(row.language) ?? "",
559
+ name: text(row.name) ?? "",
560
+ result: text(row.result) ?? "",
561
+ schema: text(row.schema) ?? ""
562
+ });
563
+ var domainRow = (row) => ({
564
+ base: text(row.base) ?? "",
565
+ constraints: text(row.constraints),
566
+ default: text(row.default),
567
+ name: text(row.name) ?? "",
568
+ notNull: flag(row.not_null),
569
+ schema: text(row.schema) ?? ""
570
+ });
571
+ var compositeRow = (row) => ({
572
+ fields: text(row.fields) ?? "",
573
+ name: text(row.name) ?? "",
574
+ schema: text(row.schema) ?? ""
575
+ });
576
+ var extensionRow = (row) => ({
577
+ name: text(row.name) ?? "",
578
+ schema: text(row.schema) ?? "",
579
+ version: text(row.version) ?? ""
580
+ });
581
+ var eventTriggerRow = (row) => ({
582
+ enabled: text(row.enabled) ?? "O",
583
+ event: text(row.event) ?? "",
584
+ function: text(row.function) ?? "",
585
+ name: text(row.name) ?? ""
586
+ });
587
+ var partitionRow = (row) => ({
588
+ bound: text(row.bound) ?? "",
589
+ name: text(row.name) ?? "",
590
+ tableId: integer(row.table_id)
591
+ });
592
+ var viewColumnRow = (row) => ({
593
+ name: text(row.name) ?? "",
594
+ sourceId: integer(row.source_id),
595
+ viewId: integer(row.view_id)
596
+ });
269
597
 
270
598
  // src/postgres/index.ts
271
599
  var DEFAULT_SCHEMA = "public";
272
- var inSchema = (schema) => schema === DEFAULT_SCHEMA ? {} : { schema };
600
+ var inSchema = (schema) => ({ schema });
273
601
  var ACTIONS = {
274
602
  a: undefined,
275
603
  c: "cascade",
@@ -319,7 +647,7 @@ var parseDefault = (expression) => {
319
647
  return quotedDefault(inner, type ?? "", expression);
320
648
  return { kind: "expression", value: expression };
321
649
  };
322
- var KINDS = {
650
+ var KINDS2 = {
323
651
  f: "Foreign table",
324
652
  m: "Materialized view",
325
653
  p: "Partitioned table",
@@ -353,7 +681,7 @@ var generatedNote = (row) => {
353
681
  return `Generated always as (${row.default}), ${mode}`;
354
682
  };
355
683
  var isSerial = (row) => row.serialSequence !== undefined && row.default?.startsWith("nextval(") === true;
356
- var enumSchema = (row) => row.enumType && row.enumSchema && row.enumSchema !== DEFAULT_SCHEMA ? { typeSchema: row.enumSchema } : {};
684
+ var enumSchema = (row) => row.enumType && row.enumSchema ? { typeSchema: row.enumSchema } : {};
357
685
  var columnOf = (row) => {
358
686
  const serial = isSerial(row);
359
687
  const fallback = row.default !== undefined && !serial && !row.generated ? parseDefault(row.default) : undefined;
@@ -364,6 +692,7 @@ var columnOf = (row) => {
364
692
  ...serial || row.identity ? { increment: true } : {},
365
693
  ...row.notNull ? { notNull: true } : {},
366
694
  ...fallback ? { default: fallback } : {},
695
+ ...columnMetadata(row),
367
696
  ...withNote(joinNotes([
368
697
  row.comment,
369
698
  identityNote(row.identity),
@@ -411,15 +740,15 @@ var applyKey = (table, row, columns) => {
411
740
  };
412
741
  table.indexes.push(index);
413
742
  };
414
- var sortedColumns = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
415
- var coversAll = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
416
- var isUniqueSet = (table, columns) => {
743
+ var sortedColumns2 = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
744
+ var coversAll2 = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
745
+ var isUniqueSet2 = (table, columns) => {
417
746
  const [only] = columns;
418
747
  const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
419
748
  if (single?.pk === true || single?.unique === true)
420
749
  return true;
421
750
  const wanted = [...columns].sort().join("\x00");
422
- return table.indexes.some((index) => coversAll(index) && index.parts.every((part) => part.kind === "column") && sortedColumns(index) === wanted);
751
+ return table.indexes.some((index) => coversAll2(index) && index.parts.every((part) => part.kind === "column") && sortedColumns2(index) === wanted);
423
752
  };
424
753
  var refOf = (row, context) => {
425
754
  const source = context.relations.get(row.tableId);
@@ -435,7 +764,7 @@ var refOf = (row, context) => {
435
764
  ...row.name === defaultName(row, source.name, columns) ? {} : { name: row.name },
436
765
  ...onDelete ? { onDelete } : {},
437
766
  ...onUpdate ? { onUpdate } : {},
438
- relation: isUniqueSet(table, columns) ? "-" : ">",
767
+ relation: isUniqueSet2(table, columns) ? "-" : ">",
439
768
  to: {
440
769
  columns: row.foreignColumns.map((position) => context.columnName(target.id, position)),
441
770
  ...inSchema(target.schema),
@@ -470,7 +799,11 @@ var indexOf = (row, context) => {
470
799
  ...withNote(joinNotes([
471
800
  row.comment,
472
801
  row.predicate ? `Where ${row.predicate}` : undefined,
473
- included.length > 0 ? `Includes ${included.join(", ")}` : undefined
802
+ included.length > 0 ? `Includes ${included.join(", ")}` : undefined,
803
+ ...indexNotes(row, (part) => {
804
+ const position = row.attnums[part] ?? 0;
805
+ return position > 0 ? context.columnName(row.tableId, position) : row.parts[part] ?? "";
806
+ })
474
807
  ]))
475
808
  };
476
809
  return index;
@@ -485,7 +818,7 @@ var policyLine = (row) => [
485
818
  ].filter((part) => part !== undefined).join(" ");
486
819
  var MAX_DEFINITION = 600;
487
820
  var kindLine = (relation) => {
488
- const kind = KINDS[relation.kind];
821
+ const kind = KINDS2[relation.kind];
489
822
  const definition = relation.definition?.trim();
490
823
  if (!kind || !definition)
491
824
  return kind;
@@ -493,10 +826,11 @@ var kindLine = (relation) => {
493
826
  return `${kind}:
494
827
  ${shown}`;
495
828
  };
496
- var tableNote = (relation, policies) => joinNotes([
829
+ var tableNote = (relation, policies, extra) => joinNotes([
497
830
  relation.comment,
498
831
  kindLine(relation),
499
- relation.partitionKey ? `Partitioned by ${relation.partitionKey}, ${relation.partitions} partitions` : undefined,
832
+ relation.partitionKey ? `Partitioned by ${relation.partitionKey}` : undefined,
833
+ ...extra,
500
834
  relation.rls ? `Row-level security is on${relation.forceRls ? ", for the owner too" : ""}` : undefined,
501
835
  ...policies.map(policyLine)
502
836
  ]);
@@ -528,16 +862,23 @@ var readRecords = (query, tables, limit) => Promise.all(tables.map(async (table)
528
862
  };
529
863
  return records;
530
864
  }));
531
- var tableOf = (relation, columns, policies) => {
865
+ var tableOf = (relation, catalogs, statistics) => {
866
+ const own = (rows) => rows.filter((row) => row.tableId === relation.id);
532
867
  const view = relation.kind === "v" || relation.kind === "m";
533
868
  const table = {
534
869
  checks: [],
535
- columns: columns.filter((row) => row.tableId === relation.id).map(columnOf),
870
+ columns: own(catalogs.columns).map(columnOf),
536
871
  ...view ? { headerColor: VIEW_COLOR } : {},
537
872
  indexes: [],
538
873
  name: relation.name,
539
874
  ...inSchema(relation.schema),
540
- ...withNote(tableNote(relation, policies.filter((row) => row.tableId === relation.id)))
875
+ ...tableMetadata(relation, statistics),
876
+ ...withNote(tableNote(relation, own(catalogs.policies), tableNoteLines({
877
+ ...relation.inherits ? { inherits: relation.inherits } : {},
878
+ partitions: own(catalogs.partitions),
879
+ rules: own(catalogs.rules),
880
+ triggers: own(catalogs.triggers)
881
+ })))
541
882
  };
542
883
  return table;
543
884
  };
@@ -561,9 +902,9 @@ var applyConstraints = (rows, context) => rows.filter((row) => {
561
902
  });
562
903
  return false;
563
904
  });
564
- var sequenceNote = (rows) => ({
905
+ var sequenceNote = (rows, defaultSchema) => ({
565
906
  content: `Sequences
566
- ${rows.map((row) => `${row.schema === DEFAULT_SCHEMA ? "" : `${row.schema}.`}${row.name}: start ${row.start}, increment ${row.increment}`).join(`
907
+ ${rows.map((row) => `${row.schema === defaultSchema ? "" : `${row.schema}.`}${row.name}: start ${row.start}, increment ${row.increment}`).join(`
567
908
  `)}`,
568
909
  name: "sequences"
569
910
  });
@@ -578,7 +919,16 @@ var readCatalogs = async (query, schemas) => {
578
919
  sources,
579
920
  policies,
580
921
  sequences,
581
- comments
922
+ comments,
923
+ triggers,
924
+ rules,
925
+ functions,
926
+ domains,
927
+ composites,
928
+ partitions,
929
+ viewColumns,
930
+ extensions,
931
+ eventTriggers
582
932
  ] = await Promise.all([
583
933
  read(ENUMS),
584
934
  read(RELATIONS),
@@ -588,34 +938,59 @@ var readCatalogs = async (query, schemas) => {
588
938
  read(VIEW_SOURCES),
589
939
  read(POLICIES),
590
940
  read(SEQUENCES),
591
- read(SCHEMA_COMMENTS)
941
+ read(SCHEMA_COMMENTS),
942
+ read(TRIGGERS),
943
+ read(RULES),
944
+ read(FUNCTIONS),
945
+ read(DOMAINS),
946
+ read(COMPOSITES),
947
+ read(PARTITIONS),
948
+ read(VIEW_COLUMNS),
949
+ query(EXTENSIONS, []),
950
+ query(EVENT_TRIGGERS, [])
592
951
  ]);
593
952
  return {
594
953
  columns: columns.map(columnRow),
595
954
  comments: comments.map(namedRow),
955
+ composites: composites.map(compositeRow),
596
956
  constraints: constraints.map(constraintRow),
957
+ domains: domains.map(domainRow),
597
958
  enums: enums.map(enumRow),
959
+ eventTriggers: eventTriggers.map(eventTriggerRow),
960
+ extensions: extensions.map(extensionRow),
961
+ functions: functions.map(functionRow),
598
962
  indexes: indexes.map(indexRow),
963
+ partitions: partitions.map(partitionRow),
599
964
  policies: policies.map(policyRow),
600
965
  relations: relations.map(relationRow),
966
+ rules: rules.map(definitionRow),
601
967
  sequences: sequences.map(sequenceRow),
602
- sources: sources.map(viewSourceRow)
968
+ sources: sources.map(viewSourceRow),
969
+ triggers: triggers.map(definitionRow),
970
+ viewColumns: viewColumns.map(viewColumnRow)
603
971
  };
604
972
  };
605
973
  var schemasToRead = async (query, schemas) => schemas ?? (await query(SCHEMAS, [])).map((row) => namedRow(row).name);
606
974
  var addDeps = (model, catalogs, relations) => catalogs.sources.forEach((row) => {
607
975
  const view = relations.get(row.viewId);
608
976
  const source = relations.get(row.sourceId);
609
- if (view && source)
610
- model.deps.push({
611
- downstream: { ...inSchema(view.schema), table: view.name },
612
- upstream: { ...inSchema(source.schema), table: source.name }
613
- });
977
+ if (!view || !source)
978
+ return;
979
+ const columns = catalogs.viewColumns.filter((entry) => entry.viewId === row.viewId && entry.sourceId === row.sourceId).map((entry) => entry.name);
980
+ model.deps.push({
981
+ downstream: { ...inSchema(view.schema), table: view.name },
982
+ upstream: {
983
+ ...columns.length > 0 ? { columns } : {},
984
+ ...inSchema(source.schema),
985
+ table: source.name
986
+ }
987
+ });
614
988
  });
615
- var addNotes = (model, catalogs) => {
989
+ var addNotes = (model, catalogs, defaultSchema) => {
616
990
  if (catalogs.sequences.length > 0)
617
- model.notes.push(sequenceNote(catalogs.sequences));
618
- const described = catalogs.comments.filter((row) => row.comment !== undefined && row.name !== DEFAULT_SCHEMA);
991
+ model.notes.push(sequenceNote(catalogs.sequences, defaultSchema));
992
+ model.notes.push(...extraNotes(catalogs, defaultSchema));
993
+ const described = catalogs.comments.filter((row) => row.comment !== undefined && row.name !== defaultSchema);
619
994
  if (described.length > 0)
620
995
  model.notes.push({
621
996
  content: `Schemas
@@ -642,7 +1017,7 @@ var fromPostgres = async (query, options = {}) => {
642
1017
  ]));
643
1018
  const tables = new Map(catalogs.relations.map((row) => [
644
1019
  row.id,
645
- tableOf(row, catalogs.columns, catalogs.policies)
1020
+ tableOf(row, catalogs, options.statistics === true)
646
1021
  ]));
647
1022
  const context = {
648
1023
  relations,
@@ -654,11 +1029,15 @@ var fromPostgres = async (query, options = {}) => {
654
1029
  model.tables.push(...tables.values());
655
1030
  model.refs.push(...foreign.map((row) => refOf(row, context)).filter((ref) => ref !== undefined));
656
1031
  addDeps(model, catalogs, relations);
657
- addNotes(model, catalogs);
1032
+ const defaultSchema = options.defaultSchema ?? DEFAULT_SCHEMA;
1033
+ addNotes(model, catalogs, defaultSchema);
658
1034
  const limit = options.records?.limit ?? 0;
659
1035
  if (limit > 0)
660
1036
  model.records.push(...await readRecords(query, model.tables.filter((table) => !table.headerColor), limit));
661
- return model;
1037
+ const result = withDefaultSchema(model, defaultSchema);
1038
+ if (options.groups === "schema")
1039
+ result.tableGroups.push(...groupBySchema(result.tables, defaultSchema));
1040
+ return result;
662
1041
  };
663
1042
  export {
664
1043
  fromPostgres,