@absolutejs/dbml 0.0.0-stage → 0.2.0

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