@absolutejs/dbml 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,1660 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import { writeFileSync } from "fs";
6
+ import { resolve } from "path";
7
+ import process from "process";
8
+ import { pathToFileURL } from "url";
9
+ import { parseArgs } from "util";
10
+ var {SQL: SQL3 } = globalThis.Bun;
11
+
12
+ // src/drizzle/index.ts
13
+ import { is as is4 } from "drizzle-orm";
14
+ import * as cockroach2 from "drizzle-orm/cockroach-core";
15
+ import * as pg2 from "drizzle-orm/pg-core";
16
+
17
+ // src/model.ts
18
+ var emptyModel = (project) => ({
19
+ deps: [],
20
+ enums: [],
21
+ notes: [],
22
+ ...project ? { project } : {},
23
+ records: [],
24
+ refs: [],
25
+ tableGroups: [],
26
+ tables: []
27
+ });
28
+
29
+ // src/drizzle/dialects.ts
30
+ import { is, SQL, sql } from "drizzle-orm";
31
+ import * as cockroach from "drizzle-orm/cockroach-core";
32
+ import * as mssql from "drizzle-orm/mssql-core";
33
+ import * as mysql from "drizzle-orm/mysql-core";
34
+ import * as pg from "drizzle-orm/pg-core";
35
+ import * as singlestore from "drizzle-orm/singlestore-core";
36
+ import * as sqlite from "drizzle-orm/sqlite-core";
37
+ var none = () => {
38
+ return;
39
+ };
40
+ var DIALECTS = [
41
+ {
42
+ databaseType: "PostgreSQL",
43
+ enumOf: (value) => pg.isPgEnum(value) ? value : undefined,
44
+ materializedViewOf: (value) => pg.isPgMaterializedView(value) ? pg.getMaterializedViewConfig(value) : undefined,
45
+ sequenceOf: (value) => pg.isPgSequence(value) ? value : undefined,
46
+ tableOf: (value) => is(value, pg.PgTable) ? pg.getTableConfig(value) : undefined,
47
+ viewOf: (value) => pg.isPgView(value) ? pg.getViewConfig(value) : undefined
48
+ },
49
+ {
50
+ databaseType: "CockroachDB",
51
+ enumOf: (value) => cockroach.isCockroachEnum(value) ? value : undefined,
52
+ materializedViewOf: (value) => cockroach.isCockroachMaterializedView(value) ? cockroach.getMaterializedViewConfig(value) : undefined,
53
+ sequenceOf: (value) => cockroach.isCockroachSequence(value) ? value : undefined,
54
+ tableOf: (value) => is(value, cockroach.CockroachTable) ? cockroach.getTableConfig(value) : undefined,
55
+ viewOf: (value) => cockroach.isCockroachView(value) ? cockroach.getViewConfig(value) : undefined
56
+ },
57
+ {
58
+ databaseType: "MySQL",
59
+ enumOf: none,
60
+ materializedViewOf: none,
61
+ sequenceOf: none,
62
+ tableOf: (value) => is(value, mysql.MySqlTable) ? mysql.getTableConfig(value) : undefined,
63
+ viewOf: (value) => is(value, mysql.MySqlView) ? mysql.getViewConfig(value) : undefined
64
+ },
65
+ {
66
+ databaseType: "SingleStore",
67
+ enumOf: none,
68
+ materializedViewOf: none,
69
+ sequenceOf: none,
70
+ viewOf: none,
71
+ tableOf: (value) => is(value, singlestore.SingleStoreTable) ? {
72
+ checks: [],
73
+ foreignKeys: [],
74
+ ...singlestore.getTableConfig(value)
75
+ } : undefined
76
+ },
77
+ {
78
+ databaseType: "SQLite",
79
+ enumOf: none,
80
+ materializedViewOf: none,
81
+ sequenceOf: none,
82
+ tableOf: (value) => is(value, sqlite.SQLiteTable) ? sqlite.getTableConfig(value) : undefined,
83
+ viewOf: (value) => is(value, sqlite.SQLiteView) ? sqlite.getViewConfig(value) : undefined
84
+ },
85
+ {
86
+ databaseType: "SQL Server",
87
+ enumOf: none,
88
+ materializedViewOf: none,
89
+ sequenceOf: none,
90
+ tableOf: (value) => is(value, mssql.MsSqlTable) ? mssql.getTableConfig(value) : undefined,
91
+ viewOf: (value) => is(value, mssql.MsSqlView) ? mssql.getViewConfig(value) : undefined
92
+ }
93
+ ];
94
+ var writer = new pg.PgDialect;
95
+ var sqlText = (fragment) => writer.sqlToQuery(sql`${fragment}`.inlineParams(), "indexes").sql;
96
+ var sqlTextQualified = (fragment) => writer.sqlToQuery(sql`${fragment}`.inlineParams()).sql;
97
+ var isSql = (value) => is(value, SQL);
98
+
99
+ // src/drizzle/relations.ts
100
+ import {
101
+ getColumnTable,
102
+ is as is2,
103
+ Many,
104
+ One
105
+ } from "drizzle-orm";
106
+ import {
107
+ createTableRelationsHelpers,
108
+ One as OneV1,
109
+ Relations
110
+ } from "drizzle-orm/_relations";
111
+ var isRecord = (value) => typeof value === "object" && value !== null;
112
+ var isTableRelations = (entry) => isRecord(entry) && isRecord(entry.relations) && ("table" in entry);
113
+ var isRelationsV2 = (value) => isRecord(value) && !is2(value, Relations) && Object.keys(value).length > 0 && Object.values(value).every(isTableRelations);
114
+ var throughOf = (relation) => ("throughTable" in relation) && isRecord(relation.throughTable) ? relation.throughTable : undefined;
115
+ var v2Link = (field, relation) => {
116
+ const from = relation.sourceColumns;
117
+ const target = relation.targetColumns;
118
+ if (from.length === 0 || target.length === 0)
119
+ return;
120
+ const owner = relation.sourceTable;
121
+ if (is2(relation, One)) {
122
+ const link = { field, from, kind: "one", owner, target };
123
+ return link;
124
+ }
125
+ const through = throughOf(relation);
126
+ if (!is2(relation, Many) || !through)
127
+ return;
128
+ const link = {
129
+ field,
130
+ from,
131
+ kind: "many-through",
132
+ owner,
133
+ target,
134
+ through
135
+ };
136
+ return link;
137
+ };
138
+ var linksFromV2 = (relations) => Object.values(relations).flatMap((config) => Object.entries(config.relations).map(([field, relation]) => v2Link(field, relation)).filter((link) => link !== undefined));
139
+ var isRelationsV1 = (value) => is2(value, Relations);
140
+ var linksFromV1 = (relations) => Object.entries(relations.config(createTableRelationsHelpers(relations.table))).map(([field, relation]) => {
141
+ if (!is2(relation, OneV1))
142
+ return;
143
+ const from = relation.config?.fields ?? [];
144
+ const target = relation.config?.references ?? [];
145
+ if (from.length === 0 || target.length === 0)
146
+ return;
147
+ const link = {
148
+ field,
149
+ from,
150
+ kind: "one",
151
+ owner: relations.table,
152
+ target
153
+ };
154
+ return link;
155
+ }).filter((link) => link !== undefined);
156
+ var endpointOf = (lookup, columns) => {
157
+ const [first] = columns;
158
+ if (!first)
159
+ return;
160
+ const place = lookup(getColumnTable(first));
161
+ if (!place)
162
+ return;
163
+ const endpoint = {
164
+ ...place,
165
+ columns: columns.map((column) => column.name)
166
+ };
167
+ return endpoint;
168
+ };
169
+ var side = (end) => `${end.schema ?? ""}.${end.table}(${end.columns.join(",")})`;
170
+ var refKey = (ref) => [side(ref.from), side(ref.to)].sort().join("|");
171
+ var newRef = (link, ends, field, options) => {
172
+ if (link.kind === "many-through") {
173
+ const through = link.through ? options.lookup(link.through) : undefined;
174
+ const ref = {
175
+ ...ends,
176
+ inactive: true,
177
+ note: `Many-to-many through ${through?.table ?? "a junction table"}, read as ${field}`,
178
+ relation: "<>"
179
+ };
180
+ return ref;
181
+ }
182
+ const ref = {
183
+ ...ends,
184
+ inactive: true,
185
+ note: `Not a foreign key: the app's relation ${field}`,
186
+ relation: options.isUnique(ends.from) ? "-" : ">"
187
+ };
188
+ return ref;
189
+ };
190
+ var applyRelations = (options) => {
191
+ const byKey = new Map(options.refs.map((ref) => [refKey(ref), ref]));
192
+ const named = new Map;
193
+ for (const link of options.links) {
194
+ const from = endpointOf(options.lookup, link.from);
195
+ const target = endpointOf(options.lookup, link.target);
196
+ if (!from || !target)
197
+ continue;
198
+ const field = `${options.lookup(link.owner)?.table ?? from.table}.${link.field}`;
199
+ const key = refKey({ from, to: target });
200
+ const existing = byKey.get(key);
201
+ if (existing)
202
+ named.set(existing, [...named.get(existing) ?? [], field]);
203
+ if (existing)
204
+ continue;
205
+ const ref = newRef(link, { from, to: target }, field, options);
206
+ byKey.set(key, ref);
207
+ options.refs.push(ref);
208
+ }
209
+ named.forEach((fields, ref) => {
210
+ const line = `Read in the app as ${[...new Set(fields)].join(", ")}`;
211
+ ref.note = ref.note ? `${ref.note}
212
+ ${line}` : line;
213
+ });
214
+ };
215
+
216
+ // src/drizzle/tables.ts
217
+ var SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
218
+ var SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
219
+ var bigintDefault = (value) => {
220
+ const safe = value <= SAFE_MAX && value >= SAFE_MIN;
221
+ const result = safe ? { kind: "number", value: `${value}` } : { kind: "expression", value: `${value}` };
222
+ return result;
223
+ };
224
+ var literalDefault = (value) => {
225
+ if (value === null)
226
+ return { kind: "null" };
227
+ if (typeof value === "boolean")
228
+ return { kind: "boolean", value };
229
+ if (typeof value === "number")
230
+ return { kind: "number", value };
231
+ if (typeof value === "bigint")
232
+ return bigintDefault(value);
233
+ if (typeof value === "string")
234
+ return { kind: "string", value };
235
+ if (value instanceof Date)
236
+ return {
237
+ kind: "string",
238
+ value: value.toISOString()
239
+ };
240
+ return {
241
+ kind: "string",
242
+ value: JSON.stringify(value)
243
+ };
244
+ };
245
+ var defaultOf = (column) => {
246
+ if (column.default === undefined)
247
+ return;
248
+ if (isSql(column.default))
249
+ return {
250
+ kind: "expression",
251
+ value: sqlText(column.default)
252
+ };
253
+ return literalDefault(column.default);
254
+ };
255
+ var SERIAL = /Serial/u;
256
+ var identityNote = (column) => {
257
+ const type = column.generatedIdentity?.type;
258
+ if (type === "always")
259
+ return "Identity, generated always";
260
+ if (type !== undefined)
261
+ return "Identity, generated by default";
262
+ if (column.identity !== undefined)
263
+ return "Identity";
264
+ return;
265
+ };
266
+ var isIncrement = (column) => column.generatedIdentity !== undefined || column.identity !== undefined || column.autoIncrement === true || SERIAL.test(column.columnType);
267
+ var generatedText = (value) => {
268
+ if (isSql(value))
269
+ return sqlText(value);
270
+ if (typeof value === "function")
271
+ return "a value the app computes";
272
+ return `${value}`;
273
+ };
274
+ var generatedNote = (column) => {
275
+ const { generated } = column;
276
+ if (!generated)
277
+ return;
278
+ const mode = generated.mode ? `, ${generated.mode}` : "";
279
+ return `Generated always as (${generatedText(generated.as)})${mode}`;
280
+ };
281
+ var present = (lines) => lines.filter((line) => line !== undefined);
282
+ var columnNotes = (column, storedAs) => present([
283
+ identityNote(column),
284
+ generatedNote(column),
285
+ column.default === undefined && column.defaultFn ? "The app sets it when a row is inserted" : undefined,
286
+ column.onUpdateFn ? "The app sets it whenever the row is updated" : undefined,
287
+ column.hasOnUpdateNow === true ? "Set to the current time on every update" : undefined,
288
+ column.uniqueType === "not distinct" ? "Unique, nulls not distinct" : undefined,
289
+ storedAs ? `Stored as ${storedAs}` : undefined
290
+ ]);
291
+ var inSchema = (schema) => schema ? { schema } : {};
292
+ var arraySuffix = (dimensions) => {
293
+ if (dimensions === undefined || dimensions === 0)
294
+ return "";
295
+ return "[]".repeat(Number.isFinite(dimensions) ? dimensions : 1);
296
+ };
297
+ var valuesOf = (values) => (values ?? []).map((value) => ({ name: value }));
298
+ var typeOf = (column, table) => {
299
+ const sqlType = column.getSQLType();
300
+ const arrays = arraySuffix(column.dimensions);
301
+ if (column.enum?.enumName) {
302
+ const named = {
303
+ enum: {
304
+ name: column.enum.enumName,
305
+ ...inSchema(column.enum.schema),
306
+ values: valuesOf(column.enumValues)
307
+ },
308
+ type: `${column.enum.enumName}${arrays}`,
309
+ ...column.enum.schema ? { typeSchema: column.enum.schema } : {}
310
+ };
311
+ return named;
312
+ }
313
+ if (!column.enumValues || column.enumValues.length === 0) {
314
+ const plain = { type: `${sqlType}${arrays}` };
315
+ return plain;
316
+ }
317
+ const name = `${table.name}_${column.name}`;
318
+ const inline = {
319
+ enum: {
320
+ name,
321
+ ...inSchema(table.schema),
322
+ values: valuesOf(column.enumValues)
323
+ },
324
+ storedAs: sqlType,
325
+ type: name,
326
+ ...table.schema ? { typeSchema: table.schema } : {}
327
+ };
328
+ return inline;
329
+ };
330
+ var columnOf = (column, table) => {
331
+ const type = typeOf(column, table);
332
+ const notes = columnNotes(column, type.storedAs);
333
+ const fallback = defaultOf(column);
334
+ const result = {
335
+ name: column.name,
336
+ type: type.type,
337
+ ...type.typeSchema ? { typeSchema: type.typeSchema } : {},
338
+ ...column.primary ? { pk: true } : {},
339
+ ...isIncrement(column) ? { increment: true } : {},
340
+ ...column.isUnique && !column.primary ? { unique: true } : {},
341
+ ...column.notNull && !column.primary ? { notNull: true } : {},
342
+ ...fallback ? { default: fallback } : {},
343
+ ...notes.length > 0 ? { note: notes.join(`
344
+ `) } : {}
345
+ };
346
+ return { column: result, enum: type.enum };
347
+ };
348
+ var isIndexedColumn = (value) => typeof value === "object" && value !== null && ("name" in value) && typeof value.name === "string";
349
+ var partOf = (value) => {
350
+ if (isSql(value))
351
+ return {
352
+ expression: sqlText(value),
353
+ kind: "expression"
354
+ };
355
+ if (!isIndexedColumn(value))
356
+ return {
357
+ expression: `${value}`,
358
+ kind: "expression"
359
+ };
360
+ return {
361
+ column: value.name,
362
+ kind: "column",
363
+ ...value.indexConfig?.order === "desc" ? { desc: true } : {}
364
+ };
365
+ };
366
+ var indexNotes = (config) => {
367
+ const nulls = config.columns.filter(isIndexedColumn).filter((column) => column.indexConfig?.nulls === "first").map((column) => `${column.name} nulls first`);
368
+ const options = Object.entries(config.with ?? {}).map(([key, value]) => `${key} = ${value}`);
369
+ return present([
370
+ config.where ? `Where ${sqlText(config.where)}` : undefined,
371
+ nulls.length > 0 ? `Sorted with ${nulls.join(", ")}` : undefined,
372
+ options.length > 0 ? `With ${options.join(", ")}` : undefined,
373
+ config.concurrently === true ? "Built concurrently" : undefined,
374
+ config.algorithm ? `Algorithm ${config.algorithm}` : undefined,
375
+ config.lock ? `Lock ${config.lock}` : undefined
376
+ ]);
377
+ };
378
+ var methodOf = (config) => {
379
+ if (config.method !== undefined)
380
+ return config.method === "btree" ? undefined : config.method;
381
+ if (config.using === undefined)
382
+ return;
383
+ return isSql(config.using) ? sqlText(config.using) : config.using;
384
+ };
385
+ var indexOf = (config) => {
386
+ const notes = indexNotes(config);
387
+ const method = methodOf(config);
388
+ const index = {
389
+ parts: config.columns.map(partOf),
390
+ ...config.unique === true ? { unique: true } : {},
391
+ ...method ? { type: method } : {},
392
+ ...config.name ? { name: config.name } : {},
393
+ ...notes.length > 0 ? { note: notes.join(`
394
+ `) } : {}
395
+ };
396
+ return index;
397
+ };
398
+ var roleName = (role) => typeof role === "object" && role !== null && ("name" in role) ? `${role.name}` : `${role}`;
399
+ var roleText = (roles) => (Array.isArray(roles) ? roles : [roles]).filter((role) => role !== undefined).map(roleName).join(", ");
400
+ var policyLine = (policy) => present([
401
+ `Policy ${policy.name}`,
402
+ policy.as && policy.as !== "permissive" ? policy.as : undefined,
403
+ `for ${policy.for ?? "all"}`,
404
+ policy.to === undefined ? undefined : `to ${roleText(policy.to)}`,
405
+ policy.using ? `using (${sqlText(policy.using)})` : undefined,
406
+ policy.withCheck ? `with check (${sqlText(policy.withCheck)})` : undefined
407
+ ]).join(" ");
408
+ var tableNote = (config) => {
409
+ const policies = config.policies ?? [];
410
+ const secured = config.enableRLS === true || policies.length > 0;
411
+ const lines = present([
412
+ secured ? "Row-level security is on" : undefined,
413
+ ...policies.map(policyLine)
414
+ ]);
415
+ return lines.length > 0 ? lines.join(`
416
+ `) : undefined;
417
+ };
418
+ var columnParts = (columns) => columns.map((column) => ({ column: column.name, kind: "column" }));
419
+ var keyIndexes = (config) => [
420
+ ...config.primaryKeys.map((key) => {
421
+ const index = {
422
+ parts: columnParts(key.columns),
423
+ pk: true,
424
+ ...key.name ? { name: key.name } : {}
425
+ };
426
+ return index;
427
+ }),
428
+ ...config.uniqueConstraints.map((constraint) => {
429
+ const index = {
430
+ parts: columnParts(constraint.columns),
431
+ unique: true,
432
+ ...constraint.name ? { name: constraint.name } : {},
433
+ ...constraint.nullsNotDistinct === true ? { note: "Nulls not distinct" } : {}
434
+ };
435
+ return index;
436
+ })
437
+ ];
438
+ var tableOf = (config) => {
439
+ const columns = config.columns.map((column) => columnOf(column, config));
440
+ const note = tableNote(config);
441
+ const table = {
442
+ checks: config.checks.map((check) => ({
443
+ expression: sqlText(check.value),
444
+ name: check.name
445
+ })),
446
+ columns: columns.map((entry) => entry.column),
447
+ indexes: [
448
+ ...keyIndexes(config),
449
+ ...config.indexes.map((index) => indexOf(index.config))
450
+ ],
451
+ name: config.name,
452
+ ...inSchema(config.schema),
453
+ ...note ? { note } : {}
454
+ };
455
+ return {
456
+ enums: columns.map((entry) => entry.enum).filter((entry) => entry !== undefined),
457
+ table
458
+ };
459
+ };
460
+ var sortedColumns = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
461
+ var coversAll = (index) => index.pk === true || index.unique === true && index.note?.startsWith("Where") !== true;
462
+ var isUniqueSet = (table, columns) => {
463
+ const [only] = columns;
464
+ const single = columns.length === 1 ? table.columns.find((entry) => entry.name === only) : undefined;
465
+ if (single?.pk === true || single?.unique === true)
466
+ return true;
467
+ const wanted = [...columns].sort().join("\x00");
468
+ return table.indexes.some((index) => coversAll(index) && index.parts.every((part) => part.kind === "column") && sortedColumns(index) === wanted);
469
+ };
470
+
471
+ // src/drizzle/views.ts
472
+ import {
473
+ Column,
474
+ getColumnTable as getColumnTable2,
475
+ is as is3,
476
+ SQL as SQL2,
477
+ Subquery,
478
+ Table,
479
+ View
480
+ } from "drizzle-orm";
481
+ var VIEW_COLOR = "#64748b";
482
+ var isAliased = (value) => typeof value === "object" && value !== null && ("fieldAlias" in value) && ("sql" in value) && is3(value.sql, SQL2);
483
+ var childrenOf = (chunk) => {
484
+ if (Array.isArray(chunk))
485
+ return chunk;
486
+ if (isAliased(chunk))
487
+ return [chunk.sql];
488
+ if (is3(chunk, SQL2))
489
+ return chunk.queryChunks;
490
+ if (is3(chunk, Subquery))
491
+ return [chunk._.sql];
492
+ return [];
493
+ };
494
+ var sourceOf = (chunk) => {
495
+ if (is3(chunk, Table) || is3(chunk, View))
496
+ return chunk;
497
+ if (is3(chunk, Column))
498
+ return getColumnTable2(chunk);
499
+ return;
500
+ };
501
+ var sourcesOf = (fragment) => {
502
+ const found = new Set;
503
+ const pending = [fragment];
504
+ while (pending.length > 0) {
505
+ const chunk = pending.pop();
506
+ const source = sourceOf(chunk);
507
+ if (source)
508
+ found.add(source);
509
+ else
510
+ pending.push(...childrenOf(chunk));
511
+ }
512
+ return found;
513
+ };
514
+ var SERIALS = {
515
+ bigserial: "bigint",
516
+ serial: "integer",
517
+ smallserial: "smallint"
518
+ };
519
+ var readType = (type) => SERIALS[type] ?? type;
520
+ var originOf = (column, sources) => {
521
+ const owners = sources.filter((source) => source.columns.includes(column));
522
+ const [owner] = owners;
523
+ return owners.length === 1 && owner ? `${owner.table}.${column}` : column;
524
+ };
525
+ var columnOfField = (name, field, sources) => {
526
+ if (is3(field, Column)) {
527
+ const origin = originOf(field.name, sources);
528
+ const picked = {
529
+ name,
530
+ ...origin === name ? {} : { note: `From ${origin}` },
531
+ type: readType(field.getSQLType())
532
+ };
533
+ return picked;
534
+ }
535
+ const expression = isAliased(field) ? field.sql : field;
536
+ const computed = {
537
+ name,
538
+ ...is3(expression, SQL2) ? { note: `Computed: ${sqlText(expression)}` } : {},
539
+ type: "unknown"
540
+ };
541
+ return computed;
542
+ };
543
+ var MAX_QUERY = 600;
544
+ var shortened = (query) => query.length > MAX_QUERY ? `${query.slice(0, MAX_QUERY)}\u2026` : query;
545
+ var viewNote = (config, kind) => {
546
+ if (config.isExisting)
547
+ return `${kind} that already exists in the database; its query lives there`;
548
+ if (!config.query)
549
+ return kind;
550
+ return `${kind}:
551
+ ${shortened(sqlTextQualified(config.query))}`;
552
+ };
553
+ var viewOf = (config, materialized, sources) => {
554
+ const view = {
555
+ checks: [],
556
+ columns: Object.entries(config.selectedFields).map(([name, field]) => columnOfField(name, field, sources)),
557
+ headerColor: VIEW_COLOR,
558
+ indexes: [],
559
+ name: config.name,
560
+ note: viewNote(config, materialized ? "Materialized view" : "View"),
561
+ ...config.schema ? { schema: config.schema } : {}
562
+ };
563
+ return view;
564
+ };
565
+
566
+ // src/drizzle/index.ts
567
+ var isRole = (value) => is4(value, pg2.PgRole) || is4(value, cockroach2.CockroachRole);
568
+ var isObject = (value) => typeof value === "object" && value !== null;
569
+ var classifyInDialects = (value, found) => DIALECTS.some((dialect) => {
570
+ const table = dialect.tableOf(value);
571
+ if (table && isObject(value))
572
+ found.tables.push({
573
+ config: table,
574
+ databaseType: dialect.databaseType,
575
+ object: value
576
+ });
577
+ const enumConfig = dialect.enumOf(value);
578
+ if (enumConfig)
579
+ found.enums.push(enumConfig);
580
+ const materialized = dialect.materializedViewOf(value);
581
+ const view = materialized ?? dialect.viewOf(value);
582
+ if (view && isObject(value))
583
+ found.views.push({
584
+ config: view,
585
+ materialized: materialized !== undefined,
586
+ object: value
587
+ });
588
+ const sequence = dialect.sequenceOf(value);
589
+ if (sequence)
590
+ found.sequences.push(sequence);
591
+ return (table ?? enumConfig ?? view ?? sequence) !== undefined;
592
+ });
593
+ var classify = (value, found) => {
594
+ if (isRelationsV2(value))
595
+ found.links.push(...linksFromV2(value));
596
+ else if (isRelationsV1(value))
597
+ found.links.push(...linksFromV1(value));
598
+ else if (isRole(value))
599
+ found.roles.push(value.name);
600
+ else
601
+ classifyInDialects(value, found);
602
+ };
603
+ var placeOf = (schema, table) => {
604
+ const place = { ...schema ? { schema } : {}, table };
605
+ return place;
606
+ };
607
+ var keyOf = (entry) => `${entry.schema ?? ""}.${entry.name}`;
608
+ var ACTIONS = {
609
+ cascade: "cascade",
610
+ "no action": undefined,
611
+ restrict: "restrict",
612
+ "set default": "set default",
613
+ "set null": "set null"
614
+ };
615
+ var actionOf = (action) => action === undefined ? undefined : ACTIONS[action.toLowerCase()];
616
+ var foreignKeyRefs = (entry, lookup, tables) => entry.config.foreignKeys.flatMap((key) => {
617
+ const reference = key.reference();
618
+ const target = lookup(reference.foreignTable);
619
+ if (!target)
620
+ return [];
621
+ const from = placeOf(entry.config.schema, entry.config.name);
622
+ const columns = reference.columns.map((column) => column.name);
623
+ const table = tables.get(keyOf({ name: from.table, schema: from.schema }));
624
+ const onDelete = actionOf(key.onDelete);
625
+ const onUpdate = actionOf(key.onUpdate);
626
+ const ref = {
627
+ from: { ...from, columns },
628
+ ...reference.name ? { name: reference.name } : {},
629
+ ...onDelete ? { onDelete } : {},
630
+ ...onUpdate ? { onUpdate } : {},
631
+ relation: table && isUniqueSet(table, columns) ? "-" : ">",
632
+ to: {
633
+ ...target,
634
+ columns: reference.foreignColumns.map((column) => column.name)
635
+ }
636
+ };
637
+ return [ref];
638
+ });
639
+ var sequenceLine = (sequence) => {
640
+ const options = Object.entries(sequence.seqOptions ?? {}).filter(([, value]) => value !== undefined).map(([key, value]) => `${key} ${value}`);
641
+ const name = `${sequence.schema ? `${sequence.schema}.` : ""}${sequence.seqName ?? "sequence"}`;
642
+ return options.length > 0 ? `${name}: ${options.join(", ")}` : name;
643
+ };
644
+ var groupNamer = (groups) => {
645
+ if (groups === "schema")
646
+ return (table) => table.schema ?? "public";
647
+ return (table) => groups({
648
+ name: table.name,
649
+ ...table.schema ? { schema: table.schema } : {}
650
+ });
651
+ };
652
+ var groupsOf = (tables, groups) => {
653
+ const nameOf = groupNamer(groups);
654
+ const byName = new Map;
655
+ tables.forEach((table) => {
656
+ const name = nameOf(table);
657
+ if (name !== undefined)
658
+ byName.set(name, [
659
+ ...byName.get(name) ?? [],
660
+ placeOf(table.schema, table.name)
661
+ ]);
662
+ });
663
+ return [...byName].map(([name, members]) => {
664
+ const group = { name, tables: members };
665
+ return group;
666
+ });
667
+ };
668
+ var enumOf = (config) => {
669
+ const entry = {
670
+ name: config.enumName,
671
+ ...config.schema ? { schema: config.schema } : {},
672
+ values: config.enumValues.map((name) => ({ name }))
673
+ };
674
+ return entry;
675
+ };
676
+ var viewSources = (view, lookup) => [
677
+ ...sourcesOf([
678
+ view.config.query,
679
+ Object.values(view.config.selectedFields)
680
+ ])
681
+ ].filter((source) => source !== view.object && lookup(source) !== undefined);
682
+ var addViews = (model, found, lookup, columnsOf) => found.views.forEach((view) => {
683
+ const downstream = placeOf(view.config.schema, view.config.name);
684
+ const sources = viewSources(view, lookup);
685
+ model.tables.push(viewOf(view.config, view.materialized, sources.map((source) => ({
686
+ columns: columnsOf(source),
687
+ table: lookup(source)?.table ?? ""
688
+ }))));
689
+ sources.forEach((source) => {
690
+ const upstream = lookup(source);
691
+ if (upstream)
692
+ model.deps.push({ downstream, upstream });
693
+ });
694
+ });
695
+ var addNotes = (model, found) => {
696
+ if (found.sequences.length > 0)
697
+ model.notes.push({
698
+ content: `Sequences
699
+ ${found.sequences.map(sequenceLine).join(`
700
+ `)}`,
701
+ name: "sequences"
702
+ });
703
+ if (found.roles.length > 0)
704
+ model.notes.push({
705
+ content: `Roles
706
+ ${found.roles.join(`
707
+ `)}`,
708
+ name: "roles"
709
+ });
710
+ };
711
+ var collect = (schema, relations) => {
712
+ const found = {
713
+ enums: [],
714
+ links: [],
715
+ roles: [],
716
+ sequences: [],
717
+ tables: [],
718
+ views: []
719
+ };
720
+ const values = new Set(Array.isArray(schema) ? schema : Object.values(schema));
721
+ if (relations !== undefined)
722
+ values.add(relations);
723
+ values.forEach((value) => classify(value, found));
724
+ return found;
725
+ };
726
+ var fromDrizzle = (schema, options = {}) => {
727
+ const found = collect(schema, options.relations);
728
+ const places = new Map;
729
+ [...found.tables, ...found.views].forEach((entry) => places.set(entry.object, placeOf(entry.config.schema, entry.config.name)));
730
+ const lookup = (table) => places.get(table);
731
+ const enums = new Map(found.enums.map((entry) => [
732
+ keyOf({ name: entry.enumName, schema: entry.schema }),
733
+ enumOf(entry)
734
+ ]));
735
+ const built = found.tables.map((entry) => tableOf(entry.config));
736
+ built.flatMap((result) => result.enums).forEach((entry) => {
737
+ if (!enums.has(keyOf(entry)))
738
+ enums.set(keyOf(entry), entry);
739
+ });
740
+ const tables = built.map((result) => result.table);
741
+ const byPlace = new Map(tables.map((table) => [keyOf(table), table]));
742
+ const byObject = new Map(found.tables.map((entry, index) => [entry.object, tables[index]]));
743
+ const types = new Set(found.tables.map((entry) => entry.databaseType));
744
+ const [databaseType] = types;
745
+ const model = emptyModel({
746
+ ...options.project,
747
+ ...types.size === 1 && databaseType ? { databaseType } : {}
748
+ });
749
+ model.enums.push(...enums.values());
750
+ model.tables.push(...tables);
751
+ model.refs.push(...found.tables.flatMap((entry) => foreignKeyRefs(entry, lookup, byPlace)));
752
+ applyRelations({
753
+ links: found.links,
754
+ lookup,
755
+ refs: model.refs,
756
+ isUnique: (end) => {
757
+ const table = byPlace.get(keyOf({ name: end.table, schema: end.schema }));
758
+ return table ? isUniqueSet(table, end.columns) : false;
759
+ }
760
+ });
761
+ addViews(model, found, lookup, (table) => byObject.get(table)?.columns.map((column) => column.name) ?? []);
762
+ addNotes(model, found);
763
+ if (options.groups)
764
+ model.tableGroups.push(...groupsOf(model.tables, options.groups));
765
+ return model;
766
+ };
767
+
768
+ // src/postgres/index.ts
769
+ import { Buffer } from "buffer";
770
+
771
+ // src/postgres/queries.ts
772
+ var SCHEMAS = `
773
+ select nspname as name
774
+ from pg_namespace
775
+ where nspname not in ('pg_catalog', 'information_schema', 'pg_toast')
776
+ and nspname not like 'pg_temp_%' and nspname not like 'pg_toast_temp_%'
777
+ order by nspname`;
778
+ var ENUMS = `
779
+ select n.nspname as schema, t.typname as name,
780
+ array_agg(e.enumlabel order by e.enumsortorder) as "values"
781
+ from pg_type t
782
+ join pg_namespace n on n.oid = t.typnamespace
783
+ join pg_enum e on e.enumtypid = t.oid
784
+ where n.nspname = any($1)
785
+ group by n.nspname, t.typname
786
+ order by n.nspname, t.typname`;
787
+ var RELATIONS = `
788
+ select c.oid::int as id, n.nspname as schema, c.relname as name, c.relkind as kind,
789
+ obj_description(c.oid, 'pg_class') as comment,
790
+ c.relrowsecurity as rls, c.relforcerowsecurity as force_rls,
791
+ case when c.relkind = 'p' then pg_get_partkeydef(c.oid) end as partition_key,
792
+ case when c.relkind in ('v', 'm') then pg_get_viewdef(c.oid, true) end as definition,
793
+ (select count(*)::int from pg_inherits i where i.inhparent = c.oid) as partitions
794
+ from pg_class c
795
+ join pg_namespace n on n.oid = c.relnamespace
796
+ where n.nspname = any($1) and c.relkind in ('r', 'p', 'v', 'm', 'f') and not c.relispartition
797
+ order by n.nspname, c.relname`;
798
+ var COLUMNS = `
799
+ select a.attrelid::int as table_id, a.attnum::int as position, a.attname as name,
800
+ format_type(a.atttypid, a.atttypmod) as type,
801
+ a.attnotnull as not_null, a.attidentity as identity, a.attgenerated as generated,
802
+ pg_get_expr(d.adbin, d.adrelid) as "default",
803
+ col_description(a.attrelid, a.attnum) as comment,
804
+ case when t.typtype = 'e' then tn.nspname
805
+ when et.typtype = 'e' then etn.nspname end as enum_schema,
806
+ coalesce(case when t.typtype = 'e' then t.typname end,
807
+ case when et.typtype = 'e' then et.typname || '[]' end) as enum_type,
808
+ pg_get_serial_sequence(quote_ident(n.nspname) || '.' || quote_ident(c.relname), a.attname) as serial_sequence
809
+ from pg_attribute a
810
+ join pg_class c on c.oid = a.attrelid
811
+ join pg_namespace n on n.oid = c.relnamespace
812
+ join pg_type t on t.oid = a.atttypid
813
+ join pg_namespace tn on tn.oid = t.typnamespace
814
+ left join pg_type et on et.oid = t.typelem and t.typcategory = 'A'
815
+ left join pg_namespace etn on etn.oid = et.typnamespace
816
+ left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum
817
+ where n.nspname = any($1) and c.relkind in ('r', 'p', 'v', 'm', 'f') and not c.relispartition
818
+ and a.attnum > 0 and not a.attisdropped
819
+ order by a.attrelid, a.attnum`;
820
+ var CONSTRAINTS = `
821
+ select con.conrelid::int as table_id, con.conname as name, con.contype as kind,
822
+ (select array_agg(k::int order by o) from unnest(con.conkey) with ordinality as u(k, o)) as columns,
823
+ con.confrelid::int as foreign_table_id,
824
+ (select array_agg(k::int order by o) from unnest(con.confkey) with ordinality as u(k, o)) as foreign_columns,
825
+ con.confdeltype as on_delete, con.confupdtype as on_update,
826
+ pg_get_constraintdef(con.oid, true) as definition,
827
+ case when con.contype = 'c' then pg_get_expr(con.conbin, con.conrelid, true) end as check_expression,
828
+ obj_description(con.oid, 'pg_constraint') as comment,
829
+ con.condeferrable as deferrable, con.condeferred as deferred,
830
+ /* Read through jsonb so a Postgres older than 15, without the column,
831
+ * reads null instead of failing. */
832
+ (to_jsonb(con) ->> 'connullsnotdistinct')::boolean as nulls_not_distinct
833
+ from pg_constraint con
834
+ join pg_namespace n on n.oid = con.connamespace
835
+ where n.nspname = any($1) and con.contype in ('p', 'u', 'f', 'c', 'x') and con.conrelid <> 0
836
+ order by con.conrelid, con.contype, con.conname`;
837
+ var INDEXES = `
838
+ select i.indrelid::int as table_id, ic.relname as name, am.amname as method,
839
+ i.indisunique as is_unique, i.indnkeyatts::int as key_count, i.indnatts::int as count,
840
+ (select array_agg(pg_get_indexdef(i.indexrelid, k, true) order by k)
841
+ from generate_series(1, i.indnatts) as k) as parts,
842
+ (select array_agg(i.indkey[k - 1]::int order by k)
843
+ from generate_series(1, i.indnatts) as k) as attnums,
844
+ (select array_agg((i.indoption[k - 1] & 1) = 1 order by k)
845
+ from generate_series(1, i.indnkeyatts) as k) as descending,
846
+ pg_get_expr(i.indpred, i.indrelid, true) as predicate,
847
+ obj_description(i.indexrelid, 'pg_class') as comment
848
+ from pg_index i
849
+ join pg_class ic on ic.oid = i.indexrelid
850
+ join pg_class tc on tc.oid = i.indrelid
851
+ join pg_namespace n on n.oid = tc.relnamespace
852
+ join pg_am am on am.oid = ic.relam
853
+ where n.nspname = any($1)
854
+ and not exists (select 1 from pg_constraint con where con.conindid = i.indexrelid and con.contype in ('p', 'u', 'x'))
855
+ order by i.indrelid, ic.relname`;
856
+ var VIEW_SOURCES = `
857
+ select distinct v.oid::int as view_id, d.refobjid::int as source_id
858
+ from pg_class v
859
+ join pg_namespace n on n.oid = v.relnamespace
860
+ join pg_rewrite r on r.ev_class = v.oid
861
+ join pg_depend d on d.objid = r.oid and d.classid = 'pg_rewrite'::regclass
862
+ and d.refclassid = 'pg_class'::regclass and d.refobjid <> v.oid
863
+ where n.nspname = any($1) and v.relkind in ('v', 'm')`;
864
+ var POLICIES = `
865
+ select p.polrelid::int as table_id, p.polname as name, p.polpermissive as permissive,
866
+ p.polcmd as command,
867
+ (select array_agg(case when r = 0 then 'public' else pg_get_userbyid(r) end) from unnest(p.polroles) as r) as roles,
868
+ pg_get_expr(p.polqual, p.polrelid, true) as "using",
869
+ pg_get_expr(p.polwithcheck, p.polrelid, true) as with_check
870
+ from pg_policy p
871
+ join pg_class c on c.oid = p.polrelid
872
+ join pg_namespace n on n.oid = c.relnamespace
873
+ where n.nspname = any($1)
874
+ order by p.polrelid, p.polname`;
875
+ var SEQUENCES = `
876
+ select n.nspname as schema, c.relname as name, s.seqstart::text as start,
877
+ s.seqincrement::text as increment
878
+ from pg_sequence s
879
+ join pg_class c on c.oid = s.seqrelid
880
+ join pg_namespace n on n.oid = c.relnamespace
881
+ where n.nspname = any($1)
882
+ and not exists (select 1 from pg_depend d where d.objid = c.oid and d.deptype in ('a', 'i'))
883
+ order by n.nspname, c.relname`;
884
+ var SCHEMA_COMMENTS = `
885
+ select nspname as name, obj_description(oid, 'pg_namespace') as comment
886
+ from pg_namespace where nspname = any($1)`;
887
+
888
+ // src/postgres/rows.ts
889
+ var optional = (key, value) => {
890
+ const entry = {};
891
+ if (value !== undefined)
892
+ entry[key] = value;
893
+ return entry;
894
+ };
895
+ var text = (value) => {
896
+ if (value === null || value === undefined)
897
+ return;
898
+ return typeof value === "string" ? value : `${value}`;
899
+ };
900
+ var integer = (value) => {
901
+ if (typeof value === "number")
902
+ return value;
903
+ const parsed = Number.parseInt(text(value) ?? "", 10);
904
+ return Number.isNaN(parsed) ? 0 : parsed;
905
+ };
906
+ var flag = (value) => value === true || value === "t" || value === "true";
907
+ var ARRAY_ITEM = /"((?:[^"\\]|\\.)*)"|([^,{}]+)/gu;
908
+ var list = (value) => {
909
+ if (Array.isArray(value))
910
+ return value.map((entry) => text(entry) ?? "");
911
+ const raw = text(value);
912
+ if (raw === undefined)
913
+ return [];
914
+ return [...raw.matchAll(ARRAY_ITEM)].map((match) => match[1] === undefined ? match[2] ?? "" : match[1].replace(/\\(.)/gu, "$1"));
915
+ };
916
+ var integers = (value) => list(value).map(integer);
917
+ var flags = (value) => list(value).map(flag);
918
+ var relationRow = (row) => {
919
+ const result = {
920
+ forceRls: flag(row.force_rls),
921
+ id: integer(row.id),
922
+ kind: text(row.kind) ?? "",
923
+ name: text(row.name) ?? "",
924
+ partitions: integer(row.partitions),
925
+ rls: flag(row.rls),
926
+ schema: text(row.schema) ?? "",
927
+ ...optional("comment", text(row.comment)),
928
+ ...optional("definition", text(row.definition)),
929
+ ...optional("partitionKey", text(row.partition_key))
930
+ };
931
+ return result;
932
+ };
933
+ var setting = (value) => {
934
+ const raw = text(value);
935
+ return raw === "" ? undefined : raw;
936
+ };
937
+ var columnRow = (row) => {
938
+ const result = {
939
+ name: text(row.name) ?? "",
940
+ notNull: flag(row.not_null),
941
+ position: integer(row.position),
942
+ tableId: integer(row.table_id),
943
+ type: text(row.type) ?? "",
944
+ ...optional("comment", text(row.comment)),
945
+ ...optional("default", text(row.default)),
946
+ ...optional("enumSchema", text(row.enum_schema)),
947
+ ...optional("enumType", text(row.enum_type)),
948
+ ...optional("generated", setting(row.generated)),
949
+ ...optional("identity", setting(row.identity)),
950
+ ...optional("serialSequence", text(row.serial_sequence))
951
+ };
952
+ return result;
953
+ };
954
+ var constraintRow = (row) => {
955
+ const result = {
956
+ columns: integers(row.columns),
957
+ deferrable: flag(row.deferrable),
958
+ deferred: flag(row.deferred),
959
+ definition: text(row.definition) ?? "",
960
+ foreignColumns: integers(row.foreign_columns),
961
+ foreignTableId: integer(row.foreign_table_id),
962
+ kind: text(row.kind) ?? "",
963
+ name: text(row.name) ?? "",
964
+ nullsNotDistinct: flag(row.nulls_not_distinct),
965
+ onDelete: text(row.on_delete) ?? "a",
966
+ onUpdate: text(row.on_update) ?? "a",
967
+ tableId: integer(row.table_id),
968
+ ...optional("checkExpression", text(row.check_expression)),
969
+ ...optional("comment", text(row.comment))
970
+ };
971
+ return result;
972
+ };
973
+ var indexRow = (row) => {
974
+ const result = {
975
+ attnums: integers(row.attnums),
976
+ descending: flags(row.descending),
977
+ keyCount: integer(row.key_count),
978
+ method: text(row.method) ?? "btree",
979
+ name: text(row.name) ?? "",
980
+ parts: list(row.parts),
981
+ tableId: integer(row.table_id),
982
+ unique: flag(row.is_unique),
983
+ ...optional("comment", text(row.comment)),
984
+ ...optional("predicate", text(row.predicate))
985
+ };
986
+ return result;
987
+ };
988
+ var policyRow = (row) => {
989
+ const result = {
990
+ command: text(row.command) ?? "*",
991
+ name: text(row.name) ?? "",
992
+ permissive: flag(row.permissive),
993
+ roles: list(row.roles),
994
+ tableId: integer(row.table_id),
995
+ ...optional("using", text(row.using)),
996
+ ...optional("withCheck", text(row.with_check))
997
+ };
998
+ return result;
999
+ };
1000
+ var namedRow = (row) => {
1001
+ const result = {
1002
+ name: text(row.name) ?? "",
1003
+ schema: text(row.schema) ?? "",
1004
+ ...optional("comment", text(row.comment))
1005
+ };
1006
+ return result;
1007
+ };
1008
+ var enumRow = (row) => ({
1009
+ name: text(row.name) ?? "",
1010
+ schema: text(row.schema) ?? "",
1011
+ values: list(row.values)
1012
+ });
1013
+ var sequenceRow = (row) => ({
1014
+ increment: text(row.increment) ?? "1",
1015
+ name: text(row.name) ?? "",
1016
+ schema: text(row.schema) ?? "",
1017
+ start: text(row.start) ?? "1"
1018
+ });
1019
+ var viewSourceRow = (row) => ({
1020
+ sourceId: integer(row.source_id),
1021
+ viewId: integer(row.view_id)
1022
+ });
1023
+
1024
+ // src/postgres/index.ts
1025
+ var DEFAULT_SCHEMA = "public";
1026
+ var inSchema2 = (schema) => schema === DEFAULT_SCHEMA ? {} : { schema };
1027
+ var ACTIONS2 = {
1028
+ a: undefined,
1029
+ c: "cascade",
1030
+ d: "set default",
1031
+ n: "set null",
1032
+ r: "restrict"
1033
+ };
1034
+ var QUOTED = /^'((?:[^']|'')*)'(?:::([\w\s."[\]()]+))?$/u;
1035
+ var NUMBER = /^-?\d+(\.\d+)?$/u;
1036
+ var NUMBER_CAST = /^\(?(-?\d+(?:\.\d+)?)\)?::[\w\s."]+$/u;
1037
+ var NULL = /^NULL(::[\w\s."[\]()]+)?$/u;
1038
+ var NUMERIC_TYPE = /^(smallint|integer|bigint|int[248]?|numeric(\(.*\))?|decimal(\(.*\))?|real|double precision|float[48]?)$/u;
1039
+ var exactNumber = (digits) => {
1040
+ const value = Number.parseFloat(digits);
1041
+ const exact = digits.includes(".") || Number.isSafeInteger(value);
1042
+ return exact ? value : undefined;
1043
+ };
1044
+ var numberDefault = (digits, expression) => {
1045
+ const value = exactNumber(digits);
1046
+ const result = value === undefined ? { kind: "expression", value: expression } : { kind: "number", value };
1047
+ return result;
1048
+ };
1049
+ var quotedDefault = (inner, type, expression) => {
1050
+ if (NUMERIC_TYPE.test(type) && NUMBER.test(inner))
1051
+ return numberDefault(inner, expression);
1052
+ const result = {
1053
+ kind: "string",
1054
+ value: inner.replaceAll("''", "'")
1055
+ };
1056
+ return result;
1057
+ };
1058
+ var parseDefault = (expression) => {
1059
+ if (NULL.test(expression))
1060
+ return { kind: "null" };
1061
+ if (expression === "true" || expression === "false")
1062
+ return {
1063
+ kind: "boolean",
1064
+ value: expression === "true"
1065
+ };
1066
+ if (NUMBER.test(expression))
1067
+ return numberDefault(expression, expression);
1068
+ const [, castDigits] = NUMBER_CAST.exec(expression) ?? [];
1069
+ if (castDigits !== undefined)
1070
+ return numberDefault(castDigits, expression);
1071
+ const [, inner, type] = QUOTED.exec(expression) ?? [];
1072
+ if (inner !== undefined)
1073
+ return quotedDefault(inner, type ?? "", expression);
1074
+ return { kind: "expression", value: expression };
1075
+ };
1076
+ var KINDS = {
1077
+ f: "Foreign table",
1078
+ m: "Materialized view",
1079
+ p: "Partitioned table",
1080
+ v: "View"
1081
+ };
1082
+ var VIEW_COLOR2 = "#64748b";
1083
+ var POLICY_COMMANDS = {
1084
+ "*": "all",
1085
+ a: "insert",
1086
+ d: "delete",
1087
+ r: "select",
1088
+ w: "update"
1089
+ };
1090
+ var joinNotes = (lines) => {
1091
+ const present = lines.filter((line) => line !== undefined && line !== "");
1092
+ return present.length > 0 ? present.join(`
1093
+ `) : undefined;
1094
+ };
1095
+ var withNote = (note) => note === undefined ? {} : { note };
1096
+ var identityNote2 = (identity) => {
1097
+ if (identity === "a")
1098
+ return "Identity, generated always";
1099
+ if (identity === "d")
1100
+ return "Identity, generated by default";
1101
+ return;
1102
+ };
1103
+ var generatedNote2 = (row) => {
1104
+ if (!row.generated || !row.default)
1105
+ return;
1106
+ const mode = row.generated === "v" ? "virtual" : "stored";
1107
+ return `Generated always as (${row.default}), ${mode}`;
1108
+ };
1109
+ var isSerial = (row) => row.serialSequence !== undefined && row.default?.startsWith("nextval(") === true;
1110
+ var enumSchema = (row) => row.enumType && row.enumSchema && row.enumSchema !== DEFAULT_SCHEMA ? { typeSchema: row.enumSchema } : {};
1111
+ var columnOf2 = (row) => {
1112
+ const serial = isSerial(row);
1113
+ const fallback = row.default !== undefined && !serial && !row.generated ? parseDefault(row.default) : undefined;
1114
+ const column = {
1115
+ name: row.name,
1116
+ type: row.enumType ?? row.type,
1117
+ ...enumSchema(row),
1118
+ ...serial || row.identity ? { increment: true } : {},
1119
+ ...row.notNull ? { notNull: true } : {},
1120
+ ...fallback ? { default: fallback } : {},
1121
+ ...withNote(joinNotes([
1122
+ row.comment,
1123
+ identityNote2(row.identity),
1124
+ generatedNote2(row)
1125
+ ]))
1126
+ };
1127
+ return column;
1128
+ };
1129
+ var constraintNote = (row) => joinNotes([
1130
+ row.comment,
1131
+ row.deferrable ? `Deferrable${row.deferred ? ", initially deferred" : ""}` : undefined,
1132
+ row.nullsNotDistinct ? "Nulls not distinct" : undefined
1133
+ ]);
1134
+ var defaultName = (row, table, columns) => {
1135
+ if (row.kind === "p")
1136
+ return `${table}_pkey`;
1137
+ if (row.kind === "f")
1138
+ return `${table}_${columns.join("_")}_fkey`;
1139
+ return `${table}_${columns.join("_")}_key`;
1140
+ };
1141
+ var columnParts2 = (columns) => columns.map((column) => ({ column, kind: "column" }));
1142
+ var markColumn = (column, primary) => {
1143
+ if (!primary) {
1144
+ column.unique = true;
1145
+ return;
1146
+ }
1147
+ column.pk = true;
1148
+ delete column.notNull;
1149
+ };
1150
+ var applyKey = (table, row, columns) => {
1151
+ const primary = row.kind === "p";
1152
+ const plain = row.name === defaultName(row, table.name, columns);
1153
+ const note = constraintNote(row);
1154
+ const [only] = columns;
1155
+ const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
1156
+ if (single && plain && note === undefined) {
1157
+ markColumn(single, primary);
1158
+ return;
1159
+ }
1160
+ const index = {
1161
+ parts: columnParts2(columns),
1162
+ ...primary ? { pk: true } : { unique: true },
1163
+ ...plain ? {} : { name: row.name },
1164
+ ...withNote(note)
1165
+ };
1166
+ table.indexes.push(index);
1167
+ };
1168
+ var sortedColumns2 = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
1169
+ var coversAll2 = (index) => index.pk === true || index.unique === true && index.note?.includes("Where ") !== true;
1170
+ var isUniqueSet2 = (table, columns) => {
1171
+ const [only] = columns;
1172
+ const single = columns.length === 1 ? table.columns.find((column) => column.name === only) : undefined;
1173
+ if (single?.pk === true || single?.unique === true)
1174
+ return true;
1175
+ const wanted = [...columns].sort().join("\x00");
1176
+ return table.indexes.some((index) => coversAll2(index) && index.parts.every((part) => part.kind === "column") && sortedColumns2(index) === wanted);
1177
+ };
1178
+ var refOf = (row, context) => {
1179
+ const source = context.relations.get(row.tableId);
1180
+ const target = context.relations.get(row.foreignTableId);
1181
+ const table = context.tables.get(row.tableId);
1182
+ if (!source || !target || !table)
1183
+ return;
1184
+ const columns = row.columns.map((position) => context.columnName(source.id, position));
1185
+ const onDelete = ACTIONS2[row.onDelete];
1186
+ const onUpdate = ACTIONS2[row.onUpdate];
1187
+ const ref = {
1188
+ from: { columns, ...inSchema2(source.schema), table: source.name },
1189
+ ...row.name === defaultName(row, source.name, columns) ? {} : { name: row.name },
1190
+ ...onDelete ? { onDelete } : {},
1191
+ ...onUpdate ? { onUpdate } : {},
1192
+ relation: isUniqueSet2(table, columns) ? "-" : ">",
1193
+ to: {
1194
+ columns: row.foreignColumns.map((position) => context.columnName(target.id, position)),
1195
+ ...inSchema2(target.schema),
1196
+ table: target.name
1197
+ },
1198
+ ...withNote(constraintNote(row))
1199
+ };
1200
+ return ref;
1201
+ };
1202
+ var partOf2 = (row, index, context) => {
1203
+ const desc = row.descending[index] === true ? { desc: true } : {};
1204
+ const position = row.attnums[index] ?? 0;
1205
+ if (position > 0)
1206
+ return {
1207
+ column: context.columnName(row.tableId, position),
1208
+ kind: "column",
1209
+ ...desc
1210
+ };
1211
+ return {
1212
+ expression: row.parts[index] ?? "",
1213
+ kind: "expression",
1214
+ ...desc
1215
+ };
1216
+ };
1217
+ var indexOf2 = (row, context) => {
1218
+ const included = row.parts.slice(row.keyCount);
1219
+ const index = {
1220
+ name: row.name,
1221
+ parts: row.parts.slice(0, row.keyCount).map((_, position) => partOf2(row, position, context)),
1222
+ ...row.method === "btree" ? {} : { type: row.method },
1223
+ ...row.unique ? { unique: true } : {},
1224
+ ...withNote(joinNotes([
1225
+ row.comment,
1226
+ row.predicate ? `Where ${row.predicate}` : undefined,
1227
+ included.length > 0 ? `Includes ${included.join(", ")}` : undefined
1228
+ ]))
1229
+ };
1230
+ return index;
1231
+ };
1232
+ var policyLine2 = (row) => [
1233
+ `Policy ${row.name}`,
1234
+ row.permissive ? undefined : "restrictive",
1235
+ `for ${POLICY_COMMANDS[row.command] ?? "all"}`,
1236
+ `to ${row.roles.join(", ")}`,
1237
+ row.using ? `using (${row.using})` : undefined,
1238
+ row.withCheck ? `with check (${row.withCheck})` : undefined
1239
+ ].filter((part) => part !== undefined).join(" ");
1240
+ var MAX_DEFINITION = 600;
1241
+ var kindLine = (relation) => {
1242
+ const kind = KINDS[relation.kind];
1243
+ const definition = relation.definition?.trim();
1244
+ if (!kind || !definition)
1245
+ return kind;
1246
+ const shown = definition.length > MAX_DEFINITION ? `${definition.slice(0, MAX_DEFINITION)}\u2026` : definition;
1247
+ return `${kind}:
1248
+ ${shown}`;
1249
+ };
1250
+ var tableNote2 = (relation, policies) => joinNotes([
1251
+ relation.comment,
1252
+ kindLine(relation),
1253
+ relation.partitionKey ? `Partitioned by ${relation.partitionKey}, ${relation.partitions} partitions` : undefined,
1254
+ relation.rls ? `Row-level security is on${relation.forceRls ? ", for the owner too" : ""}` : undefined,
1255
+ ...policies.map(policyLine2)
1256
+ ]);
1257
+ var recordValue = (value) => {
1258
+ if (value === null || value === undefined)
1259
+ return null;
1260
+ if (typeof value === "boolean" || typeof value === "string")
1261
+ return value;
1262
+ if (typeof value === "number")
1263
+ return Number.isFinite(value) ? value : `${value}`;
1264
+ if (typeof value === "bigint")
1265
+ return `${value}`;
1266
+ if (value instanceof Date)
1267
+ return value.toISOString();
1268
+ if (value instanceof Uint8Array)
1269
+ return `\\x${Buffer.from(value).toString("hex")}`;
1270
+ return JSON.stringify(value);
1271
+ };
1272
+ var quoteIdent = (name) => `"${name.replaceAll('"', '""')}"`;
1273
+ var readRecords = (query, tables, limit) => Promise.all(tables.map(async (table) => {
1274
+ const columns = table.columns.map((column) => column.name);
1275
+ const from = `${quoteIdent(table.schema ?? DEFAULT_SCHEMA)}.${quoteIdent(table.name)}`;
1276
+ const rows = await query(`select ${columns.map(quoteIdent).join(", ")} from ${from} limit ${Math.max(0, Math.floor(limit))}`, []);
1277
+ const records = {
1278
+ columns,
1279
+ rows: rows.map((row) => columns.map((column) => recordValue(row[column]))),
1280
+ ...table.schema ? { schema: table.schema } : {},
1281
+ table: table.name
1282
+ };
1283
+ return records;
1284
+ }));
1285
+ var tableOf2 = (relation, columns, policies) => {
1286
+ const view = relation.kind === "v" || relation.kind === "m";
1287
+ const table = {
1288
+ checks: [],
1289
+ columns: columns.filter((row) => row.tableId === relation.id).map(columnOf2),
1290
+ ...view ? { headerColor: VIEW_COLOR2 } : {},
1291
+ indexes: [],
1292
+ name: relation.name,
1293
+ ...inSchema2(relation.schema),
1294
+ ...withNote(tableNote2(relation, policies.filter((row) => row.tableId === relation.id)))
1295
+ };
1296
+ return table;
1297
+ };
1298
+ var applyConstraints = (rows, context) => rows.filter((row) => {
1299
+ const table = context.tables.get(row.tableId);
1300
+ if (!table || row.kind === "f")
1301
+ return table !== undefined;
1302
+ const columns = row.columns.map((position) => context.columnName(row.tableId, position));
1303
+ if (row.kind === "p" || row.kind === "u")
1304
+ applyKey(table, row, columns);
1305
+ if (row.kind === "c")
1306
+ table.checks.push({
1307
+ expression: (row.checkExpression ?? row.definition).replace(/^\((.*)\)$/su, "$1"),
1308
+ name: row.name
1309
+ });
1310
+ if (row.kind === "x")
1311
+ table.indexes.push({
1312
+ name: row.name,
1313
+ note: `Exclusion constraint: ${row.definition}`,
1314
+ parts: columnParts2(columns)
1315
+ });
1316
+ return false;
1317
+ });
1318
+ var sequenceNote = (rows) => ({
1319
+ content: `Sequences
1320
+ ${rows.map((row) => `${row.schema === DEFAULT_SCHEMA ? "" : `${row.schema}.`}${row.name}: start ${row.start}, increment ${row.increment}`).join(`
1321
+ `)}`,
1322
+ name: "sequences"
1323
+ });
1324
+ var readCatalogs = async (query, schemas) => {
1325
+ const read = (sql) => query(sql, [schemas]);
1326
+ const [
1327
+ enums,
1328
+ relations,
1329
+ columns,
1330
+ constraints,
1331
+ indexes,
1332
+ sources,
1333
+ policies,
1334
+ sequences,
1335
+ comments
1336
+ ] = await Promise.all([
1337
+ read(ENUMS),
1338
+ read(RELATIONS),
1339
+ read(COLUMNS),
1340
+ read(CONSTRAINTS),
1341
+ read(INDEXES),
1342
+ read(VIEW_SOURCES),
1343
+ read(POLICIES),
1344
+ read(SEQUENCES),
1345
+ read(SCHEMA_COMMENTS)
1346
+ ]);
1347
+ return {
1348
+ columns: columns.map(columnRow),
1349
+ comments: comments.map(namedRow),
1350
+ constraints: constraints.map(constraintRow),
1351
+ enums: enums.map(enumRow),
1352
+ indexes: indexes.map(indexRow),
1353
+ policies: policies.map(policyRow),
1354
+ relations: relations.map(relationRow),
1355
+ sequences: sequences.map(sequenceRow),
1356
+ sources: sources.map(viewSourceRow)
1357
+ };
1358
+ };
1359
+ var schemasToRead = async (query, schemas) => schemas ?? (await query(SCHEMAS, [])).map((row) => namedRow(row).name);
1360
+ var addDeps = (model, catalogs, relations) => catalogs.sources.forEach((row) => {
1361
+ const view = relations.get(row.viewId);
1362
+ const source = relations.get(row.sourceId);
1363
+ if (view && source)
1364
+ model.deps.push({
1365
+ downstream: { ...inSchema2(view.schema), table: view.name },
1366
+ upstream: { ...inSchema2(source.schema), table: source.name }
1367
+ });
1368
+ });
1369
+ var addNotes2 = (model, catalogs) => {
1370
+ if (catalogs.sequences.length > 0)
1371
+ model.notes.push(sequenceNote(catalogs.sequences));
1372
+ const described = catalogs.comments.filter((row) => row.comment !== undefined && row.name !== DEFAULT_SCHEMA);
1373
+ if (described.length > 0)
1374
+ model.notes.push({
1375
+ content: `Schemas
1376
+ ${described.map((row) => `${row.name}: ${row.comment}`).join(`
1377
+ `)}`,
1378
+ name: "schemas"
1379
+ });
1380
+ };
1381
+ var fromPostgres = async (query, options = {}) => {
1382
+ const catalogs = await readCatalogs(query, await schemasToRead(query, options.schemas));
1383
+ const model = emptyModel({
1384
+ databaseType: "PostgreSQL",
1385
+ ...options.project
1386
+ });
1387
+ model.enums.push(...catalogs.enums.map((row) => ({
1388
+ name: row.name,
1389
+ ...inSchema2(row.schema),
1390
+ values: row.values.map((name) => ({ name }))
1391
+ })));
1392
+ const relations = new Map(catalogs.relations.map((row) => [row.id, row]));
1393
+ const names = new Map(catalogs.columns.map((row) => [
1394
+ `${row.tableId}:${row.position}`,
1395
+ row.name
1396
+ ]));
1397
+ const tables = new Map(catalogs.relations.map((row) => [
1398
+ row.id,
1399
+ tableOf2(row, catalogs.columns, catalogs.policies)
1400
+ ]));
1401
+ const context = {
1402
+ relations,
1403
+ tables,
1404
+ columnName: (tableId, position) => names.get(`${tableId}:${position}`) ?? `${position}`
1405
+ };
1406
+ const foreign = applyConstraints(catalogs.constraints, context);
1407
+ catalogs.indexes.forEach((row) => tables.get(row.tableId)?.indexes.push(indexOf2(row, context)));
1408
+ model.tables.push(...tables.values());
1409
+ model.refs.push(...foreign.map((row) => refOf(row, context)).filter((ref) => ref !== undefined));
1410
+ addDeps(model, catalogs, relations);
1411
+ addNotes2(model, catalogs);
1412
+ const limit = options.records?.limit ?? 0;
1413
+ if (limit > 0)
1414
+ model.records.push(...await readRecords(query, model.tables.filter((table) => !table.headerColor), limit));
1415
+ return model;
1416
+ };
1417
+
1418
+ // src/print.ts
1419
+ var INDENT = " ";
1420
+ var quoteName = (name) => `"${name.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
1421
+ var qualified = (schema, name) => schema ? `${quoteName(schema)}.${quoteName(name)}` : quoteName(name);
1422
+ var quoteText = (text) => {
1423
+ const escaped = text.replaceAll("\\", "\\\\").replaceAll(`\r
1424
+ `, `
1425
+ `);
1426
+ if (/[\n']/u.test(escaped))
1427
+ return `'''${escaped.replaceAll("'''", "\\'''")}'''`;
1428
+ return `'${escaped}'`;
1429
+ };
1430
+ var quoteExpression = (expression) => `\`${expression.replaceAll("`", '"')}\``;
1431
+ var BARE_TYPE = /^[A-Za-z_][\w]*(\([\w,]*\))?$/u;
1432
+ var printType = (column) => {
1433
+ const type = BARE_TYPE.test(column.type) ? column.type : quoteName(column.type);
1434
+ return column.typeSchema ? `${quoteName(column.typeSchema)}.${type}` : type;
1435
+ };
1436
+ var printDefault = (value) => {
1437
+ if (value.kind === "null")
1438
+ return "null";
1439
+ if (value.kind === "boolean")
1440
+ return `${value.value}`;
1441
+ if (value.kind === "number")
1442
+ return `${value.value}`;
1443
+ if (value.kind === "string")
1444
+ return quoteText(value.value);
1445
+ return quoteExpression(value.value);
1446
+ };
1447
+ var settings = (entries) => {
1448
+ const present = entries.filter((entry) => typeof entry === "string");
1449
+ return present.length > 0 ? ` [${present.join(", ")}]` : "";
1450
+ };
1451
+ var printColumn = (column) => `${quoteName(column.name)} ${printType(column)}${settings([
1452
+ column.pk && "pk",
1453
+ column.increment && "increment",
1454
+ column.unique && "unique",
1455
+ column.notNull && "not null",
1456
+ column.default && `default: ${printDefault(column.default)}`,
1457
+ ...(column.checks ?? []).map((check) => `check: ${quoteExpression(check)}`),
1458
+ column.note !== undefined && `note: ${quoteText(column.note)}`
1459
+ ])}`;
1460
+ var printIndexPart = (part) => {
1461
+ const target = part.kind === "column" ? quoteName(part.column) : quoteExpression(part.expression);
1462
+ return part.desc ? `${target} [desc]` : target;
1463
+ };
1464
+ var printIndex = (index) => {
1465
+ const parts = index.parts.map(printIndexPart);
1466
+ const grouped = parts.length === 1 && !index.parts[0]?.desc ? parts[0] ?? "" : `(${parts.join(", ")})`;
1467
+ return `${grouped}${settings([
1468
+ index.pk && "pk",
1469
+ index.unique && "unique",
1470
+ index.type !== undefined && `type: ${index.type}`,
1471
+ index.name !== undefined && `name: ${quoteName(index.name)}`,
1472
+ index.note !== undefined && `note: ${quoteText(index.note)}`
1473
+ ])}`;
1474
+ };
1475
+ var printCheck = (check) => `${quoteExpression(check.expression)}${settings([
1476
+ check.name !== undefined && `name: ${quoteText(check.name)}`
1477
+ ])}`;
1478
+ var block = (title, lines, depth = 1) => {
1479
+ const pad = INDENT.repeat(depth);
1480
+ return `${INDENT.repeat(depth - 1)}${title} {
1481
+ ${lines.map((line) => `${pad}${line}`).join(`
1482
+ `)}
1483
+ ${INDENT.repeat(depth - 1)}}`;
1484
+ };
1485
+ var printTable = (table) => {
1486
+ const head = `Table ${qualified(table.schema, table.name)}${table.alias ? ` as ${quoteName(table.alias)}` : ""}${settings([
1487
+ table.headerColor !== undefined && `headerColor: ${table.headerColor}`
1488
+ ])}`;
1489
+ const body = table.columns.map(printColumn);
1490
+ const sections = [];
1491
+ if (table.checks.length > 0)
1492
+ sections.push(block("Checks", table.checks.map(printCheck), 2));
1493
+ if (table.indexes.length > 0)
1494
+ sections.push(block("Indexes", table.indexes.map(printIndex), 2));
1495
+ if (table.note !== undefined)
1496
+ sections.push(`${INDENT}Note: ${quoteText(table.note)}`);
1497
+ const lines = body.map((line) => `${INDENT}${line}`);
1498
+ return `${head} {
1499
+ ${[lines.join(`
1500
+ `), ...sections].join(`
1501
+
1502
+ `)}
1503
+ }`;
1504
+ };
1505
+ var printEnum = (entry) => block(`Enum ${qualified(entry.schema, entry.name)}`, entry.values.map((value) => `${quoteName(value.name)}${settings([
1506
+ value.note !== undefined && `note: ${quoteText(value.note)}`
1507
+ ])}`));
1508
+ var printEndpoint = (endpoint) => {
1509
+ const columns = endpoint.columns.length === 1 ? quoteName(endpoint.columns[0] ?? "") : `(${endpoint.columns.map(quoteName).join(", ")})`;
1510
+ return `${qualified(endpoint.schema, endpoint.table)}.${columns}`;
1511
+ };
1512
+ var printRef = (ref) => `Ref${ref.name === undefined ? "" : ` ${quoteName(ref.name)}`}: ${printEndpoint(ref.from)} ${ref.relation} ${printEndpoint(ref.to)}${settings([
1513
+ ref.onDelete !== undefined && `delete: ${ref.onDelete}`,
1514
+ ref.onUpdate !== undefined && `update: ${ref.onUpdate}`,
1515
+ ref.color !== undefined && `color: ${ref.color}`,
1516
+ ref.inactive && "inactive",
1517
+ ref.note !== undefined && `note: ${quoteText(ref.note)}`
1518
+ ])}`;
1519
+ var printDepEnd = (end) => {
1520
+ const table = qualified(end.schema, end.table);
1521
+ if (!end.columns || end.columns.length === 0)
1522
+ return table;
1523
+ return `${table}.${end.columns.length === 1 ? quoteName(end.columns[0] ?? "") : `(${end.columns.map(quoteName).join(", ")})`}`;
1524
+ };
1525
+ var printDep = (dep) => {
1526
+ const edge = `${printDepEnd(dep.upstream)} -> ${printDepEnd(dep.downstream)}`;
1527
+ if (dep.note === undefined)
1528
+ return `Dep: ${edge}`;
1529
+ return block("Dep", [edge, "", `note: ${quoteText(dep.note)}`]);
1530
+ };
1531
+ var printGroup = (group) => block(`TableGroup ${quoteName(group.name)}${settings([
1532
+ group.color !== undefined && `color: ${group.color}`
1533
+ ])}`, [
1534
+ ...group.tables.map((entry) => qualified(entry.schema, entry.table)),
1535
+ ...group.note === undefined ? [] : [`Note: ${quoteText(group.note)}`]
1536
+ ]);
1537
+ var printNote = (note) => block(`Note ${quoteName(note.name)}${settings([
1538
+ note.color !== undefined && `color: ${note.color}`
1539
+ ])}`, [quoteText(note.content)]);
1540
+ var printValue = (value) => {
1541
+ if (value === null)
1542
+ return "null";
1543
+ if (typeof value === "boolean" || typeof value === "number")
1544
+ return `${value}`;
1545
+ return quoteText(value);
1546
+ };
1547
+ var printRecords = (records) => block(`Records ${qualified(records.schema, records.table)}(${records.columns.map(quoteName).join(", ")})`, records.rows.map((row) => row.map(printValue).join(", ")));
1548
+ var printProject = (project) => block(`Project${project.name ? ` ${quoteName(project.name)}` : ""}`, [
1549
+ ...project.databaseType === undefined ? [] : [`database_type: ${quoteText(project.databaseType)}`],
1550
+ ...project.note === undefined ? [] : [`Note: ${quoteText(project.note)}`]
1551
+ ]);
1552
+ var printDbml = (model) => {
1553
+ const { project } = model;
1554
+ const hasProject = project !== undefined && (project.name !== undefined || project.databaseType !== undefined || project.note !== undefined);
1555
+ const sections = [
1556
+ ...hasProject && project ? [printProject(project)] : [],
1557
+ ...model.enums.map(printEnum),
1558
+ ...model.tables.map(printTable),
1559
+ ...model.tableGroups.map(printGroup),
1560
+ ...model.refs.length > 0 ? [model.refs.map(printRef).join(`
1561
+ `)] : [],
1562
+ ...model.deps.length > 0 ? [model.deps.map(printDep).join(`
1563
+ `)] : [],
1564
+ ...model.notes.map(printNote),
1565
+ ...model.records.filter((records) => records.rows.length > 0).map(printRecords)
1566
+ ];
1567
+ return `${sections.join(`
1568
+
1569
+ `)}
1570
+ `;
1571
+ };
1572
+
1573
+ // src/cli.ts
1574
+ var USAGE = `Usage:
1575
+ absolute-dbml <schema.ts> [options] a Drizzle schema module
1576
+ absolute-dbml --postgres <url> [options] a live Postgres database
1577
+
1578
+ Options:
1579
+ -o, --output <file> write to a file instead of standard output
1580
+ --json print the model as JSON instead of DBML
1581
+ --name <name> the project's name
1582
+ --groups schema group tables by schema
1583
+ --relations <name> the schema module's defineRelations export
1584
+ --schema <name> a schema to read (repeatable; Postgres only)
1585
+ --records <n> each table's first n rows as Records (Postgres only)
1586
+ -h, --help show this help
1587
+ `;
1588
+ var fail = (message) => {
1589
+ process.stderr.write(`${message}
1590
+
1591
+ ${USAGE}`);
1592
+ process.exit(1);
1593
+ };
1594
+ var { positionals, values } = parseArgs({
1595
+ allowPositionals: true,
1596
+ options: {
1597
+ groups: { type: "string" },
1598
+ help: { short: "h", type: "boolean" },
1599
+ json: { type: "boolean" },
1600
+ name: { type: "string" },
1601
+ output: { short: "o", type: "string" },
1602
+ postgres: { type: "string" },
1603
+ records: { type: "string" },
1604
+ relations: { type: "string" },
1605
+ schema: { multiple: true, type: "string" }
1606
+ }
1607
+ });
1608
+ if (values.help) {
1609
+ process.stdout.write(USAGE);
1610
+ process.exit(0);
1611
+ }
1612
+ var project = values.name ? { name: values.name } : undefined;
1613
+ var STATEMENT_TIMEOUT = "15s";
1614
+ var readDatabase = async (url) => {
1615
+ const client = new SQL3({ max: 1, url });
1616
+ try {
1617
+ return await client.begin(async (transaction) => {
1618
+ await transaction`SET TRANSACTION READ ONLY`;
1619
+ await transaction.unsafe(`SET LOCAL statement_timeout = '${STATEMENT_TIMEOUT}'`);
1620
+ const limit = Number.parseInt(values.records ?? "0", 10);
1621
+ return fromPostgres(async (text, params) => {
1622
+ const rows = await transaction.unsafe(text, params);
1623
+ return rows;
1624
+ }, {
1625
+ ...project ? { project } : {},
1626
+ ...limit > 0 ? { records: { limit } } : {},
1627
+ ...values.schema ? { schemas: values.schema } : {}
1628
+ });
1629
+ });
1630
+ } finally {
1631
+ await client.close();
1632
+ }
1633
+ };
1634
+ var readSchema = async (file) => {
1635
+ const module = await import(pathToFileURL(resolve(file)).href);
1636
+ const options = {
1637
+ ...project ? { project } : {},
1638
+ ...values.groups === "schema" ? { groups: "schema" } : {},
1639
+ ...values.relations ? { relations: module[values.relations] } : {}
1640
+ };
1641
+ return fromDrizzle(module, options);
1642
+ };
1643
+ var [source] = positionals;
1644
+ var readModel = () => {
1645
+ if (values.postgres)
1646
+ return readDatabase(values.postgres);
1647
+ if (source)
1648
+ return readSchema(source);
1649
+ return fail("Give a schema file or --postgres <url>.");
1650
+ };
1651
+ var model = await readModel();
1652
+ var output = values.json ? `${JSON.stringify(model, null, "\t")}
1653
+ ` : printDbml(model);
1654
+ if (values.output)
1655
+ writeFileSync(resolve(values.output), output);
1656
+ else
1657
+ process.stdout.write(output);
1658
+ export {
1659
+ USAGE
1660
+ };