@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.
@@ -0,0 +1,796 @@
1
+ // @bun
2
+ // src/drizzle/index.ts
3
+ import { is as is4 } from "drizzle-orm";
4
+ import * as cockroach2 from "drizzle-orm/cockroach-core";
5
+ import * as pg2 from "drizzle-orm/pg-core";
6
+
7
+ // src/model.ts
8
+ var emptyModel = (project) => ({
9
+ deps: [],
10
+ enums: [],
11
+ notes: [],
12
+ ...project ? { project } : {},
13
+ records: [],
14
+ refs: [],
15
+ tableGroups: [],
16
+ tables: []
17
+ });
18
+ var unqualified = (place, schema) => {
19
+ if (place.schema !== schema)
20
+ return place;
21
+ const { schema: dropped, ...rest } = place;
22
+ return rest;
23
+ };
24
+ var withDefaultSchema = (model, schema) => {
25
+ const result = {
26
+ ...model,
27
+ deps: model.deps.map((dep) => ({
28
+ ...dep,
29
+ downstream: unqualified(dep.downstream, schema),
30
+ upstream: unqualified(dep.upstream, schema)
31
+ })),
32
+ enums: model.enums.map((entry) => unqualified(entry, schema)),
33
+ records: model.records.map((records) => unqualified(records, schema)),
34
+ refs: model.refs.map((ref) => ({
35
+ ...ref,
36
+ from: unqualified(ref.from, schema),
37
+ to: unqualified(ref.to, schema)
38
+ })),
39
+ tableGroups: model.tableGroups.map((group) => ({
40
+ ...group,
41
+ tables: group.tables.map((entry) => unqualified(entry, schema))
42
+ })),
43
+ tables: model.tables.map((table) => ({
44
+ ...unqualified(table, schema),
45
+ columns: table.columns.map((column) => {
46
+ if (column.typeSchema !== schema)
47
+ return column;
48
+ const { typeSchema: dropped, ...rest } = column;
49
+ return rest;
50
+ })
51
+ }))
52
+ };
53
+ return result;
54
+ };
55
+
56
+ // src/drizzle/dialects.ts
57
+ import { is, SQL, sql } from "drizzle-orm";
58
+ import * as cockroach from "drizzle-orm/cockroach-core";
59
+ import * as mssql from "drizzle-orm/mssql-core";
60
+ import * as mysql from "drizzle-orm/mysql-core";
61
+ import * as pg from "drizzle-orm/pg-core";
62
+ import * as singlestore from "drizzle-orm/singlestore-core";
63
+ import * as sqlite from "drizzle-orm/sqlite-core";
64
+ var none = () => {
65
+ return;
66
+ };
67
+ var DIALECTS = [
68
+ {
69
+ databaseType: "PostgreSQL",
70
+ enumOf: (value) => pg.isPgEnum(value) ? value : undefined,
71
+ materializedViewOf: (value) => pg.isPgMaterializedView(value) ? pg.getMaterializedViewConfig(value) : undefined,
72
+ sequenceOf: (value) => pg.isPgSequence(value) ? value : undefined,
73
+ tableOf: (value) => is(value, pg.PgTable) ? pg.getTableConfig(value) : undefined,
74
+ viewOf: (value) => pg.isPgView(value) ? pg.getViewConfig(value) : undefined
75
+ },
76
+ {
77
+ databaseType: "CockroachDB",
78
+ enumOf: (value) => cockroach.isCockroachEnum(value) ? value : undefined,
79
+ materializedViewOf: (value) => cockroach.isCockroachMaterializedView(value) ? cockroach.getMaterializedViewConfig(value) : undefined,
80
+ sequenceOf: (value) => cockroach.isCockroachSequence(value) ? value : undefined,
81
+ tableOf: (value) => is(value, cockroach.CockroachTable) ? cockroach.getTableConfig(value) : undefined,
82
+ viewOf: (value) => cockroach.isCockroachView(value) ? cockroach.getViewConfig(value) : undefined
83
+ },
84
+ {
85
+ databaseType: "MySQL",
86
+ enumOf: none,
87
+ materializedViewOf: none,
88
+ sequenceOf: none,
89
+ tableOf: (value) => is(value, mysql.MySqlTable) ? mysql.getTableConfig(value) : undefined,
90
+ viewOf: (value) => is(value, mysql.MySqlView) ? mysql.getViewConfig(value) : undefined
91
+ },
92
+ {
93
+ databaseType: "SingleStore",
94
+ enumOf: none,
95
+ materializedViewOf: none,
96
+ sequenceOf: none,
97
+ viewOf: none,
98
+ tableOf: (value) => is(value, singlestore.SingleStoreTable) ? {
99
+ checks: [],
100
+ foreignKeys: [],
101
+ ...singlestore.getTableConfig(value)
102
+ } : undefined
103
+ },
104
+ {
105
+ databaseType: "SQLite",
106
+ enumOf: none,
107
+ materializedViewOf: none,
108
+ sequenceOf: none,
109
+ tableOf: (value) => is(value, sqlite.SQLiteTable) ? sqlite.getTableConfig(value) : undefined,
110
+ viewOf: (value) => is(value, sqlite.SQLiteView) ? sqlite.getViewConfig(value) : undefined
111
+ },
112
+ {
113
+ databaseType: "SQL Server",
114
+ enumOf: none,
115
+ materializedViewOf: none,
116
+ sequenceOf: none,
117
+ tableOf: (value) => is(value, mssql.MsSqlTable) ? mssql.getTableConfig(value) : undefined,
118
+ viewOf: (value) => is(value, mssql.MsSqlView) ? mssql.getViewConfig(value) : undefined
119
+ }
120
+ ];
121
+ var writer = new pg.PgDialect;
122
+ var sqlText = (fragment) => writer.sqlToQuery(sql`${fragment}`.inlineParams(), "indexes").sql;
123
+ var sqlTextQualified = (fragment) => writer.sqlToQuery(sql`${fragment}`.inlineParams()).sql;
124
+ var isSql = (value) => is(value, SQL);
125
+
126
+ // src/drizzle/relations.ts
127
+ import {
128
+ getColumnTable,
129
+ is as is2,
130
+ Many,
131
+ One
132
+ } from "drizzle-orm";
133
+ import {
134
+ createTableRelationsHelpers,
135
+ One as OneV1,
136
+ Relations
137
+ } from "drizzle-orm/_relations";
138
+ var isRecord = (value) => typeof value === "object" && value !== null;
139
+ var isTableRelations = (entry) => isRecord(entry) && isRecord(entry.relations) && ("table" in entry);
140
+ var isRelationsV2 = (value) => isRecord(value) && !is2(value, Relations) && Object.keys(value).length > 0 && Object.values(value).every(isTableRelations);
141
+ var throughOf = (relation) => ("throughTable" in relation) && isRecord(relation.throughTable) ? relation.throughTable : undefined;
142
+ var v2Link = (field, relation) => {
143
+ const from = relation.sourceColumns;
144
+ const target = relation.targetColumns;
145
+ if (from.length === 0 || target.length === 0)
146
+ return;
147
+ const owner = relation.sourceTable;
148
+ if (is2(relation, One)) {
149
+ const link = { field, from, kind: "one", owner, target };
150
+ return link;
151
+ }
152
+ const through = throughOf(relation);
153
+ if (!is2(relation, Many) || !through)
154
+ return;
155
+ const link = {
156
+ field,
157
+ from,
158
+ kind: "many-through",
159
+ owner,
160
+ target,
161
+ through
162
+ };
163
+ return link;
164
+ };
165
+ var linksFromV2 = (relations) => Object.values(relations).flatMap((config) => Object.entries(config.relations).map(([field, relation]) => v2Link(field, relation)).filter((link) => link !== undefined));
166
+ var isRelationsV1 = (value) => is2(value, Relations);
167
+ var linksFromV1 = (relations) => Object.entries(relations.config(createTableRelationsHelpers(relations.table))).map(([field, relation]) => {
168
+ if (!is2(relation, OneV1))
169
+ return;
170
+ const from = relation.config?.fields ?? [];
171
+ const target = relation.config?.references ?? [];
172
+ if (from.length === 0 || target.length === 0)
173
+ return;
174
+ const link = {
175
+ field,
176
+ from,
177
+ kind: "one",
178
+ owner: relations.table,
179
+ target
180
+ };
181
+ return link;
182
+ }).filter((link) => link !== undefined);
183
+ var endpointOf = (lookup, columns) => {
184
+ const [first] = columns;
185
+ if (!first)
186
+ return;
187
+ const place = lookup(getColumnTable(first));
188
+ if (!place)
189
+ return;
190
+ const endpoint = {
191
+ ...place,
192
+ columns: columns.map((column) => column.name)
193
+ };
194
+ return endpoint;
195
+ };
196
+ var side = (end) => `${end.schema ?? ""}.${end.table}(${end.columns.join(",")})`;
197
+ var refKey = (ref) => [side(ref.from), side(ref.to)].sort().join("|");
198
+ var newRef = (link, ends, field, options) => {
199
+ if (link.kind === "many-through") {
200
+ const through = link.through ? options.lookup(link.through) : undefined;
201
+ const ref = {
202
+ ...ends,
203
+ inactive: true,
204
+ note: `Many-to-many through ${through?.table ?? "a junction table"}, read as ${field}`,
205
+ relation: "<>"
206
+ };
207
+ return ref;
208
+ }
209
+ const ref = {
210
+ ...ends,
211
+ inactive: true,
212
+ note: `Not a foreign key: the app's relation ${field}`,
213
+ relation: options.isUnique(ends.from) ? "-" : ">"
214
+ };
215
+ return ref;
216
+ };
217
+ var applyRelations = (options) => {
218
+ const byKey = new Map(options.refs.map((ref) => [refKey(ref), ref]));
219
+ const named = new Map;
220
+ for (const link of options.links) {
221
+ const from = endpointOf(options.lookup, link.from);
222
+ const target = endpointOf(options.lookup, link.target);
223
+ if (!from || !target)
224
+ continue;
225
+ const field = `${options.lookup(link.owner)?.table ?? from.table}.${link.field}`;
226
+ const key = refKey({ from, to: target });
227
+ const existing = byKey.get(key);
228
+ if (existing)
229
+ named.set(existing, [...named.get(existing) ?? [], field]);
230
+ if (existing)
231
+ continue;
232
+ const ref = newRef(link, { from, to: target }, field, options);
233
+ byKey.set(key, ref);
234
+ options.refs.push(ref);
235
+ }
236
+ named.forEach((fields, ref) => {
237
+ const line = `Read in the app as ${[...new Set(fields)].join(", ")}`;
238
+ ref.note = ref.note ? `${ref.note}
239
+ ${line}` : line;
240
+ });
241
+ };
242
+
243
+ // src/drizzle/tables.ts
244
+ var SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
245
+ var SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
246
+ var bigintDefault = (value) => {
247
+ const safe = value <= SAFE_MAX && value >= SAFE_MIN;
248
+ const result = safe ? { kind: "number", value: `${value}` } : { kind: "expression", value: `${value}` };
249
+ return result;
250
+ };
251
+ var literalDefault = (value) => {
252
+ if (value === null)
253
+ return { kind: "null" };
254
+ if (typeof value === "boolean")
255
+ return { kind: "boolean", value };
256
+ if (typeof value === "number")
257
+ return { kind: "number", value };
258
+ if (typeof value === "bigint")
259
+ return bigintDefault(value);
260
+ if (typeof value === "string")
261
+ return { kind: "string", value };
262
+ if (value instanceof Date)
263
+ return {
264
+ kind: "string",
265
+ value: value.toISOString()
266
+ };
267
+ return {
268
+ kind: "string",
269
+ value: JSON.stringify(value)
270
+ };
271
+ };
272
+ var defaultOf = (column) => {
273
+ if (column.default === undefined)
274
+ return;
275
+ if (isSql(column.default))
276
+ return {
277
+ kind: "expression",
278
+ value: sqlText(column.default)
279
+ };
280
+ return literalDefault(column.default);
281
+ };
282
+ var SERIAL = /Serial/u;
283
+ var identityNote = (column) => {
284
+ const type = column.generatedIdentity?.type;
285
+ if (type === "always")
286
+ return "Identity, generated always";
287
+ if (type !== undefined)
288
+ return "Identity, generated by default";
289
+ if (column.identity !== undefined)
290
+ return "Identity";
291
+ return;
292
+ };
293
+ var isIncrement = (column) => column.generatedIdentity !== undefined || column.identity !== undefined || column.autoIncrement === true || SERIAL.test(column.columnType);
294
+ var generatedText = (value) => {
295
+ if (isSql(value))
296
+ return sqlText(value);
297
+ if (typeof value === "function")
298
+ return "a value the app computes";
299
+ return `${value}`;
300
+ };
301
+ var generatedNote = (column) => {
302
+ const { generated } = column;
303
+ if (!generated)
304
+ return;
305
+ const mode = generated.mode ? `, ${generated.mode}` : "";
306
+ return `Generated always as (${generatedText(generated.as)})${mode}`;
307
+ };
308
+ var present = (lines) => lines.filter((line) => line !== undefined);
309
+ var columnNotes = (column, storedAs) => present([
310
+ identityNote(column),
311
+ generatedNote(column),
312
+ column.default === undefined && column.defaultFn ? "The app sets it when a row is inserted" : undefined,
313
+ column.onUpdateFn ? "The app sets it whenever the row is updated" : undefined,
314
+ column.hasOnUpdateNow === true ? "Set to the current time on every update" : undefined,
315
+ column.uniqueType === "not distinct" ? "Unique, nulls not distinct" : undefined,
316
+ storedAs ? `Stored as ${storedAs}` : undefined
317
+ ]);
318
+ var inSchema = (schema) => schema ? { schema } : {};
319
+ var arraySuffix = (dimensions) => {
320
+ if (dimensions === undefined || dimensions === 0)
321
+ return "";
322
+ return "[]".repeat(Number.isFinite(dimensions) ? dimensions : 1);
323
+ };
324
+ var valuesOf = (values) => (values ?? []).map((value) => ({ name: value }));
325
+ var typeOf = (column, table) => {
326
+ const sqlType = column.getSQLType();
327
+ const arrays = arraySuffix(column.dimensions);
328
+ if (column.enum?.enumName) {
329
+ const named = {
330
+ enum: {
331
+ name: column.enum.enumName,
332
+ ...inSchema(column.enum.schema),
333
+ values: valuesOf(column.enumValues)
334
+ },
335
+ type: `${column.enum.enumName}${arrays}`,
336
+ ...column.enum.schema ? { typeSchema: column.enum.schema } : {}
337
+ };
338
+ return named;
339
+ }
340
+ if (!column.enumValues || column.enumValues.length === 0) {
341
+ const plain = { type: `${sqlType}${arrays}` };
342
+ return plain;
343
+ }
344
+ const name = `${table.name}_${column.name}`;
345
+ const inline = {
346
+ enum: {
347
+ name,
348
+ ...inSchema(table.schema),
349
+ values: valuesOf(column.enumValues)
350
+ },
351
+ storedAs: sqlType,
352
+ type: name,
353
+ ...table.schema ? { typeSchema: table.schema } : {}
354
+ };
355
+ return inline;
356
+ };
357
+ var columnOf = (column, table) => {
358
+ const type = typeOf(column, table);
359
+ const notes = columnNotes(column, type.storedAs);
360
+ const fallback = defaultOf(column);
361
+ const result = {
362
+ name: column.name,
363
+ type: type.type,
364
+ ...type.typeSchema ? { typeSchema: type.typeSchema } : {},
365
+ ...column.primary ? { pk: true } : {},
366
+ ...isIncrement(column) ? { increment: true } : {},
367
+ ...column.isUnique && !column.primary ? { unique: true } : {},
368
+ ...column.notNull && !column.primary ? { notNull: true } : {},
369
+ ...fallback ? { default: fallback } : {},
370
+ ...notes.length > 0 ? { note: notes.join(`
371
+ `) } : {}
372
+ };
373
+ return { column: result, enum: type.enum };
374
+ };
375
+ var isIndexedColumn = (value) => typeof value === "object" && value !== null && ("name" in value) && typeof value.name === "string";
376
+ var partOf = (value) => {
377
+ if (isSql(value))
378
+ return {
379
+ expression: sqlText(value),
380
+ kind: "expression"
381
+ };
382
+ if (!isIndexedColumn(value))
383
+ return {
384
+ expression: `${value}`,
385
+ kind: "expression"
386
+ };
387
+ return {
388
+ column: value.name,
389
+ kind: "column",
390
+ ...value.indexConfig?.order === "desc" ? { desc: true } : {}
391
+ };
392
+ };
393
+ var indexNotes = (config) => {
394
+ const nulls = config.columns.filter(isIndexedColumn).filter((column) => column.indexConfig?.nulls === "first").map((column) => `${column.name} nulls first`);
395
+ const options = Object.entries(config.with ?? {}).map(([key, value]) => `${key} = ${value}`);
396
+ return present([
397
+ config.where ? `Where ${sqlText(config.where)}` : undefined,
398
+ nulls.length > 0 ? `Sorted with ${nulls.join(", ")}` : undefined,
399
+ options.length > 0 ? `With ${options.join(", ")}` : undefined,
400
+ config.concurrently === true ? "Built concurrently" : undefined,
401
+ config.algorithm ? `Algorithm ${config.algorithm}` : undefined,
402
+ config.lock ? `Lock ${config.lock}` : undefined
403
+ ]);
404
+ };
405
+ var methodOf = (config) => {
406
+ if (config.method !== undefined)
407
+ return config.method === "btree" ? undefined : config.method;
408
+ if (config.using === undefined)
409
+ return;
410
+ return isSql(config.using) ? sqlText(config.using) : config.using;
411
+ };
412
+ var indexOf = (config) => {
413
+ const notes = indexNotes(config);
414
+ const method = methodOf(config);
415
+ const index = {
416
+ parts: config.columns.map(partOf),
417
+ ...config.unique === true ? { unique: true } : {},
418
+ ...method ? { type: method } : {},
419
+ ...config.name ? { name: config.name } : {},
420
+ ...notes.length > 0 ? { note: notes.join(`
421
+ `) } : {}
422
+ };
423
+ return index;
424
+ };
425
+ var roleName = (role) => typeof role === "object" && role !== null && ("name" in role) ? `${role.name}` : `${role}`;
426
+ var roleText = (roles) => (Array.isArray(roles) ? roles : [roles]).filter((role) => role !== undefined).map(roleName).join(", ");
427
+ var policyLine = (policy) => present([
428
+ `Policy ${policy.name}`,
429
+ policy.as && policy.as !== "permissive" ? policy.as : undefined,
430
+ `for ${policy.for ?? "all"}`,
431
+ policy.to === undefined ? undefined : `to ${roleText(policy.to)}`,
432
+ policy.using ? `using (${sqlText(policy.using)})` : undefined,
433
+ policy.withCheck ? `with check (${sqlText(policy.withCheck)})` : undefined
434
+ ]).join(" ");
435
+ var tableNote = (config) => {
436
+ const policies = config.policies ?? [];
437
+ const secured = config.enableRLS === true || policies.length > 0;
438
+ const lines = present([
439
+ secured ? "Row-level security is on" : undefined,
440
+ ...policies.map(policyLine)
441
+ ]);
442
+ return lines.length > 0 ? lines.join(`
443
+ `) : undefined;
444
+ };
445
+ var columnParts = (columns) => columns.map((column) => ({ column: column.name, kind: "column" }));
446
+ var keyIndexes = (config) => [
447
+ ...config.primaryKeys.map((key) => {
448
+ const index = {
449
+ parts: columnParts(key.columns),
450
+ pk: true,
451
+ ...key.name ? { name: key.name } : {}
452
+ };
453
+ return index;
454
+ }),
455
+ ...config.uniqueConstraints.map((constraint) => {
456
+ const index = {
457
+ parts: columnParts(constraint.columns),
458
+ unique: true,
459
+ ...constraint.name ? { name: constraint.name } : {},
460
+ ...constraint.nullsNotDistinct === true ? { note: "Nulls not distinct" } : {}
461
+ };
462
+ return index;
463
+ })
464
+ ];
465
+ var tableOf = (config) => {
466
+ const columns = config.columns.map((column) => columnOf(column, config));
467
+ const note = tableNote(config);
468
+ const table = {
469
+ checks: config.checks.map((check) => ({
470
+ expression: sqlText(check.value),
471
+ name: check.name
472
+ })),
473
+ columns: columns.map((entry) => entry.column),
474
+ indexes: [
475
+ ...keyIndexes(config),
476
+ ...config.indexes.map((index) => indexOf(index.config))
477
+ ],
478
+ name: config.name,
479
+ ...inSchema(config.schema),
480
+ ...note ? { note } : {}
481
+ };
482
+ return {
483
+ enums: columns.map((entry) => entry.enum).filter((entry) => entry !== undefined),
484
+ table
485
+ };
486
+ };
487
+ var sortedColumns = (index) => index.parts.map((part) => part.kind === "column" ? part.column : "").sort().join("\x00");
488
+ var coversAll = (index) => index.pk === true || index.unique === true && index.note?.startsWith("Where") !== true;
489
+ var isUniqueSet = (table, columns) => {
490
+ const [only] = columns;
491
+ const single = columns.length === 1 ? table.columns.find((entry) => entry.name === only) : undefined;
492
+ if (single?.pk === true || single?.unique === true)
493
+ return true;
494
+ const wanted = [...columns].sort().join("\x00");
495
+ return table.indexes.some((index) => coversAll(index) && index.parts.every((part) => part.kind === "column") && sortedColumns(index) === wanted);
496
+ };
497
+
498
+ // src/drizzle/views.ts
499
+ import {
500
+ Column,
501
+ getColumnTable as getColumnTable2,
502
+ is as is3,
503
+ SQL as SQL2,
504
+ Subquery,
505
+ Table,
506
+ View
507
+ } from "drizzle-orm";
508
+ var VIEW_COLOR = "#64748b";
509
+ var isAliased = (value) => typeof value === "object" && value !== null && ("fieldAlias" in value) && ("sql" in value) && is3(value.sql, SQL2);
510
+ var childrenOf = (chunk) => {
511
+ if (Array.isArray(chunk))
512
+ return chunk;
513
+ if (isAliased(chunk))
514
+ return [chunk.sql];
515
+ if (is3(chunk, SQL2))
516
+ return chunk.queryChunks;
517
+ if (is3(chunk, Subquery))
518
+ return [chunk._.sql];
519
+ return [];
520
+ };
521
+ var sourceOf = (chunk) => {
522
+ if (is3(chunk, Table) || is3(chunk, View))
523
+ return chunk;
524
+ if (is3(chunk, Column))
525
+ return getColumnTable2(chunk);
526
+ return;
527
+ };
528
+ var sourcesOf = (fragment) => {
529
+ const found = new Set;
530
+ const pending = [fragment];
531
+ while (pending.length > 0) {
532
+ const chunk = pending.pop();
533
+ const source = sourceOf(chunk);
534
+ if (source)
535
+ found.add(source);
536
+ else
537
+ pending.push(...childrenOf(chunk));
538
+ }
539
+ return found;
540
+ };
541
+ var SERIALS = {
542
+ bigserial: "bigint",
543
+ serial: "integer",
544
+ smallserial: "smallint"
545
+ };
546
+ var readType = (type) => SERIALS[type] ?? type;
547
+ var originOf = (column, sources) => {
548
+ const owners = sources.filter((source) => source.columns.includes(column));
549
+ const [owner] = owners;
550
+ return owners.length === 1 && owner ? `${owner.table}.${column}` : column;
551
+ };
552
+ var columnOfField = (name, field, sources) => {
553
+ if (is3(field, Column)) {
554
+ const origin = originOf(field.name, sources);
555
+ const picked = {
556
+ name,
557
+ ...origin === name ? {} : { note: `From ${origin}` },
558
+ type: readType(field.getSQLType())
559
+ };
560
+ return picked;
561
+ }
562
+ const expression = isAliased(field) ? field.sql : field;
563
+ const computed = {
564
+ name,
565
+ ...is3(expression, SQL2) ? { note: `Computed: ${sqlText(expression)}` } : {},
566
+ type: "unknown"
567
+ };
568
+ return computed;
569
+ };
570
+ var MAX_QUERY = 600;
571
+ var shortened = (query) => query.length > MAX_QUERY ? `${query.slice(0, MAX_QUERY)}\u2026` : query;
572
+ var viewNote = (config, kind) => {
573
+ if (config.isExisting)
574
+ return `${kind} that already exists in the database; its query lives there`;
575
+ if (!config.query)
576
+ return kind;
577
+ return `${kind}:
578
+ ${shortened(sqlTextQualified(config.query))}`;
579
+ };
580
+ var viewOf = (config, materialized, sources) => {
581
+ const view = {
582
+ checks: [],
583
+ columns: Object.entries(config.selectedFields).map(([name, field]) => columnOfField(name, field, sources)),
584
+ headerColor: VIEW_COLOR,
585
+ indexes: [],
586
+ name: config.name,
587
+ note: viewNote(config, materialized ? "Materialized view" : "View"),
588
+ ...config.schema ? { schema: config.schema } : {}
589
+ };
590
+ return view;
591
+ };
592
+
593
+ // src/drizzle/index.ts
594
+ var isRole = (value) => is4(value, pg2.PgRole) || is4(value, cockroach2.CockroachRole);
595
+ var isObject = (value) => typeof value === "object" && value !== null;
596
+ var classifyInDialects = (value, found) => DIALECTS.some((dialect) => {
597
+ const table = dialect.tableOf(value);
598
+ if (table && isObject(value))
599
+ found.tables.push({
600
+ config: table,
601
+ databaseType: dialect.databaseType,
602
+ object: value
603
+ });
604
+ const enumConfig = dialect.enumOf(value);
605
+ if (enumConfig)
606
+ found.enums.push(enumConfig);
607
+ const materialized = dialect.materializedViewOf(value);
608
+ const view = materialized ?? dialect.viewOf(value);
609
+ if (view && isObject(value))
610
+ found.views.push({
611
+ config: view,
612
+ materialized: materialized !== undefined,
613
+ object: value
614
+ });
615
+ const sequence = dialect.sequenceOf(value);
616
+ if (sequence)
617
+ found.sequences.push(sequence);
618
+ return (table ?? enumConfig ?? view ?? sequence) !== undefined;
619
+ });
620
+ var classify = (value, found) => {
621
+ if (isRelationsV2(value))
622
+ found.links.push(...linksFromV2(value));
623
+ else if (isRelationsV1(value))
624
+ found.links.push(...linksFromV1(value));
625
+ else if (isRole(value))
626
+ found.roles.push(value.name);
627
+ else
628
+ classifyInDialects(value, found);
629
+ };
630
+ var placeOf = (schema, table) => {
631
+ const place = { ...schema ? { schema } : {}, table };
632
+ return place;
633
+ };
634
+ var keyOf = (entry) => `${entry.schema ?? ""}.${entry.name}`;
635
+ var ACTIONS = {
636
+ cascade: "cascade",
637
+ "no action": undefined,
638
+ restrict: "restrict",
639
+ "set default": "set default",
640
+ "set null": "set null"
641
+ };
642
+ var actionOf = (action) => action === undefined ? undefined : ACTIONS[action.toLowerCase()];
643
+ var foreignKeyRefs = (entry, lookup, tables) => entry.config.foreignKeys.flatMap((key) => {
644
+ const reference = key.reference();
645
+ const target = lookup(reference.foreignTable);
646
+ if (!target)
647
+ return [];
648
+ const from = placeOf(entry.config.schema, entry.config.name);
649
+ const columns = reference.columns.map((column) => column.name);
650
+ const table = tables.get(keyOf({ name: from.table, schema: from.schema }));
651
+ const onDelete = actionOf(key.onDelete);
652
+ const onUpdate = actionOf(key.onUpdate);
653
+ const ref = {
654
+ from: { ...from, columns },
655
+ ...reference.name ? { name: reference.name } : {},
656
+ ...onDelete ? { onDelete } : {},
657
+ ...onUpdate ? { onUpdate } : {},
658
+ relation: table && isUniqueSet(table, columns) ? "-" : ">",
659
+ to: {
660
+ ...target,
661
+ columns: reference.foreignColumns.map((column) => column.name)
662
+ }
663
+ };
664
+ return [ref];
665
+ });
666
+ var sequenceLine = (sequence) => {
667
+ const options = Object.entries(sequence.seqOptions ?? {}).filter(([, value]) => value !== undefined).map(([key, value]) => `${key} ${value}`);
668
+ const name = `${sequence.schema ? `${sequence.schema}.` : ""}${sequence.seqName ?? "sequence"}`;
669
+ return options.length > 0 ? `${name}: ${options.join(", ")}` : name;
670
+ };
671
+ var groupNamer = (groups) => {
672
+ if (groups === "schema")
673
+ return (table) => table.schema ?? "public";
674
+ return (table) => groups({
675
+ name: table.name,
676
+ ...table.schema ? { schema: table.schema } : {}
677
+ });
678
+ };
679
+ var groupsOf = (tables, groups) => {
680
+ const nameOf = groupNamer(groups);
681
+ const byName = new Map;
682
+ tables.forEach((table) => {
683
+ const name = nameOf(table);
684
+ if (name !== undefined)
685
+ byName.set(name, [
686
+ ...byName.get(name) ?? [],
687
+ placeOf(table.schema, table.name)
688
+ ]);
689
+ });
690
+ return [...byName].map(([name, members]) => {
691
+ const group = { name, tables: members };
692
+ return group;
693
+ });
694
+ };
695
+ var enumOf = (config) => {
696
+ const entry = {
697
+ name: config.enumName,
698
+ ...config.schema ? { schema: config.schema } : {},
699
+ values: config.enumValues.map((name) => ({ name }))
700
+ };
701
+ return entry;
702
+ };
703
+ var viewSources = (view, lookup) => [
704
+ ...sourcesOf([
705
+ view.config.query,
706
+ Object.values(view.config.selectedFields)
707
+ ])
708
+ ].filter((source) => source !== view.object && lookup(source) !== undefined);
709
+ var addViews = (model, found, lookup, columnsOf) => found.views.forEach((view) => {
710
+ const downstream = placeOf(view.config.schema, view.config.name);
711
+ const sources = viewSources(view, lookup);
712
+ model.tables.push(viewOf(view.config, view.materialized, sources.map((source) => ({
713
+ columns: columnsOf(source),
714
+ table: lookup(source)?.table ?? ""
715
+ }))));
716
+ sources.forEach((source) => {
717
+ const upstream = lookup(source);
718
+ if (upstream)
719
+ model.deps.push({ downstream, upstream });
720
+ });
721
+ });
722
+ var addNotes = (model, found) => {
723
+ if (found.sequences.length > 0)
724
+ model.notes.push({
725
+ content: `Sequences
726
+ ${found.sequences.map(sequenceLine).join(`
727
+ `)}`,
728
+ name: "sequences"
729
+ });
730
+ if (found.roles.length > 0)
731
+ model.notes.push({
732
+ content: `Roles
733
+ ${found.roles.join(`
734
+ `)}`,
735
+ name: "roles"
736
+ });
737
+ };
738
+ var collect = (schema, relations) => {
739
+ const found = {
740
+ enums: [],
741
+ links: [],
742
+ roles: [],
743
+ sequences: [],
744
+ tables: [],
745
+ views: []
746
+ };
747
+ const values = new Set(Array.isArray(schema) ? schema : Object.values(schema));
748
+ if (relations !== undefined)
749
+ values.add(relations);
750
+ values.forEach((value) => classify(value, found));
751
+ return found;
752
+ };
753
+ var fromDrizzle = (schema, options = {}) => {
754
+ const found = collect(schema, options.relations);
755
+ const places = new Map;
756
+ [...found.tables, ...found.views].forEach((entry) => places.set(entry.object, placeOf(entry.config.schema, entry.config.name)));
757
+ const lookup = (table) => places.get(table);
758
+ const enums = new Map(found.enums.map((entry) => [
759
+ keyOf({ name: entry.enumName, schema: entry.schema }),
760
+ enumOf(entry)
761
+ ]));
762
+ const built = found.tables.map((entry) => tableOf(entry.config));
763
+ built.flatMap((result) => result.enums).forEach((entry) => {
764
+ if (!enums.has(keyOf(entry)))
765
+ enums.set(keyOf(entry), entry);
766
+ });
767
+ const tables = built.map((result) => result.table);
768
+ const byPlace = new Map(tables.map((table) => [keyOf(table), table]));
769
+ const byObject = new Map(found.tables.map((entry, index) => [entry.object, tables[index]]));
770
+ const types = new Set(found.tables.map((entry) => entry.databaseType));
771
+ const [databaseType] = types;
772
+ const model = emptyModel({
773
+ ...options.project,
774
+ ...types.size === 1 && databaseType ? { databaseType } : {}
775
+ });
776
+ model.enums.push(...enums.values());
777
+ model.tables.push(...tables);
778
+ model.refs.push(...found.tables.flatMap((entry) => foreignKeyRefs(entry, lookup, byPlace)));
779
+ applyRelations({
780
+ links: found.links,
781
+ lookup,
782
+ refs: model.refs,
783
+ isUnique: (end) => {
784
+ const table = byPlace.get(keyOf({ name: end.table, schema: end.schema }));
785
+ return table ? isUniqueSet(table, end.columns) : false;
786
+ }
787
+ });
788
+ addViews(model, found, lookup, (table) => byObject.get(table)?.columns.map((column) => column.name) ?? []);
789
+ addNotes(model, found);
790
+ if (options.groups)
791
+ model.tableGroups.push(...groupsOf(model.tables, options.groups));
792
+ return model;
793
+ };
794
+ export {
795
+ fromDrizzle
796
+ };