@constructive-io/schema-builder 0.2.0 → 0.2.1

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/card-widths-CmIxkRfh.cjs +28 -0
  3. package/dist/card-widths-CmIxkRfh.cjs.map +1 -0
  4. package/dist/card-widths-pI4Kw4Xz.js +22 -0
  5. package/dist/card-widths-pI4Kw4Xz.js.map +1 -0
  6. package/dist/core-WwCS0CKu.cjs +66 -0
  7. package/dist/core-WwCS0CKu.cjs.map +1 -0
  8. package/dist/core-kx6KjxE5.js +49 -0
  9. package/dist/core-kx6KjxE5.js.map +1 -0
  10. package/dist/core.cjs +14 -212
  11. package/dist/core.d.cts +3 -54
  12. package/dist/core.d.ts +3 -54
  13. package/dist/core.js +3 -200
  14. package/dist/create-table-card-BzNKfpXO.cjs +7726 -0
  15. package/dist/create-table-card-BzNKfpXO.cjs.map +1 -0
  16. package/dist/create-table-card-pZ0Aq6rr.js +7685 -0
  17. package/dist/create-table-card-pZ0Aq6rr.js.map +1 -0
  18. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs +42 -0
  19. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs.map +1 -0
  20. package/dist/delete-confirm-dialog-K0AWE643.js +37 -0
  21. package/dist/delete-confirm-dialog-K0AWE643.js.map +1 -0
  22. package/dist/empty-state-card-DMn8ADRq.cjs +62 -0
  23. package/dist/empty-state-card-DMn8ADRq.cjs.map +1 -0
  24. package/dist/empty-state-card-Dnn36JVH.js +57 -0
  25. package/dist/empty-state-card-Dnn36JVH.js.map +1 -0
  26. package/dist/fields.cjs +8 -7763
  27. package/dist/fields.d.cts +39 -39
  28. package/dist/fields.d.ts +39 -39
  29. package/dist/fields.js +2 -7735
  30. package/dist/generated-types-DZMUyNBH.d.cts +27 -0
  31. package/dist/generated-types-DZMUyNBH.d.ts +27 -0
  32. package/dist/index-9h0EROdb.d.cts +56 -0
  33. package/dist/index-CwQ9QpxA.d.ts +7 -0
  34. package/dist/index-DOWB1UBK.d.cts +56 -0
  35. package/dist/index-DOWB1UBK.d.ts +56 -0
  36. package/dist/index-Dgb_e3AP.d.cts +7 -0
  37. package/dist/index-p_NegPQ5.d.ts +56 -0
  38. package/dist/index.cjs +736 -13712
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.cts +4 -10
  41. package/dist/index.d.ts +4 -10
  42. package/dist/index.js +725 -13680
  43. package/dist/index.js.map +1 -1
  44. package/dist/indexes-view-CJ1WQKdp.js +736 -0
  45. package/dist/indexes-view-CJ1WQKdp.js.map +1 -0
  46. package/dist/indexes-view-peIv6QUZ.cjs +759 -0
  47. package/dist/indexes-view-peIv6QUZ.cjs.map +1 -0
  48. package/dist/indexes.cjs +6 -1041
  49. package/dist/indexes.d.cts +27 -27
  50. package/dist/indexes.d.ts +27 -27
  51. package/dist/indexes.js +2 -1016
  52. package/dist/invalidate-database-entities-9DsT5NlP.cjs +2862 -0
  53. package/dist/invalidate-database-entities-9DsT5NlP.cjs.map +1 -0
  54. package/dist/invalidate-database-entities-CmmOT3S0.js +2559 -0
  55. package/dist/invalidate-database-entities-CmmOT3S0.js.map +1 -0
  56. package/dist/keyboard-activation-BQiV0scm.js +13 -0
  57. package/dist/keyboard-activation-BQiV0scm.js.map +1 -0
  58. package/dist/keyboard-activation-D-L0IU6Y.cjs +19 -0
  59. package/dist/keyboard-activation-D-L0IU6Y.cjs.map +1 -0
  60. package/dist/policies-view-BRbpbyB6.js +1018 -0
  61. package/dist/policies-view-BRbpbyB6.js.map +1 -0
  62. package/dist/policies-view-H1HTjpmv.cjs +1023 -0
  63. package/dist/policies-view-H1HTjpmv.cjs.map +1 -0
  64. package/dist/policies.cjs +10 -5939
  65. package/dist/policies.d.cts +55 -50
  66. package/dist/policies.d.ts +55 -50
  67. package/dist/policies.js +4 -5911
  68. package/dist/policy-config-form-BwyK7DGV.js +2502 -0
  69. package/dist/policy-config-form-BwyK7DGV.js.map +1 -0
  70. package/dist/policy-config-form-CefFo6Fw.cjs +2629 -0
  71. package/dist/policy-config-form-CefFo6Fw.cjs.map +1 -0
  72. package/dist/policy-types-D_sYWb-b.d.cts +81 -0
  73. package/dist/policy-types-D_sYWb-b.d.ts +81 -0
  74. package/dist/query-BmN_qO0W.js +171 -0
  75. package/dist/query-BmN_qO0W.js.map +1 -0
  76. package/dist/query-DU-KZleN.cjs +212 -0
  77. package/dist/query-DU-KZleN.cjs.map +1 -0
  78. package/dist/relationships-view-B5TAcPHU.cjs +2452 -0
  79. package/dist/relationships-view-B5TAcPHU.cjs.map +1 -0
  80. package/dist/relationships-view-DbwFh5r-.js +2417 -0
  81. package/dist/relationships-view-DbwFh5r-.js.map +1 -0
  82. package/dist/relationships.cjs +9 -4328
  83. package/dist/relationships.d.cts +93 -92
  84. package/dist/relationships.d.ts +93 -92
  85. package/dist/relationships.js +2 -4300
  86. package/dist/rolldown-runtime-D_qnwXdH.cjs +35 -0
  87. package/dist/schema-builder-sidebar-Ctu621Vw.cjs +604 -0
  88. package/dist/schema-builder-sidebar-Ctu621Vw.cjs.map +1 -0
  89. package/dist/schema-builder-sidebar-VR-Ctidc.js +593 -0
  90. package/dist/schema-builder-sidebar-VR-Ctidc.js.map +1 -0
  91. package/dist/table-editor-C-hHz3DJ.cjs +1935 -0
  92. package/dist/table-editor-C-hHz3DJ.cjs.map +1 -0
  93. package/dist/table-editor-IVp3B4nG.js +1906 -0
  94. package/dist/table-editor-IVp3B4nG.js.map +1 -0
  95. package/dist/tables.cjs +6 -5643
  96. package/dist/tables.d.cts +22 -21
  97. package/dist/tables.d.ts +22 -21
  98. package/dist/tables.js +3 -5618
  99. package/dist/testing.cjs +63 -62
  100. package/dist/testing.cjs.map +1 -1
  101. package/dist/testing.d.cts +4 -4
  102. package/dist/testing.d.ts +4 -4
  103. package/dist/testing.js +62 -61
  104. package/dist/testing.js.map +1 -1
  105. package/dist/types-GUrH1Qny.d.cts +200 -0
  106. package/dist/types-GUrH1Qny.d.ts +200 -0
  107. package/dist/use-update-table-C7v3gRyG.cjs +291 -0
  108. package/dist/use-update-table-C7v3gRyG.cjs.map +1 -0
  109. package/dist/use-update-table-Dz6knGoH.js +244 -0
  110. package/dist/use-update-table-Dz6knGoH.js.map +1 -0
  111. package/package.json +6 -6
  112. package/dist/core.cjs.map +0 -1
  113. package/dist/core.js.map +0 -1
  114. package/dist/fields.cjs.map +0 -1
  115. package/dist/fields.js.map +0 -1
  116. package/dist/generated-types-CnAlqHU_.d.cts +0 -25
  117. package/dist/generated-types-CnAlqHU_.d.ts +0 -25
  118. package/dist/indexes.cjs.map +0 -1
  119. package/dist/indexes.js.map +0 -1
  120. package/dist/policies.cjs.map +0 -1
  121. package/dist/policies.js.map +0 -1
  122. package/dist/policy-types-CEYAR5TN.d.cts +0 -79
  123. package/dist/policy-types-CEYAR5TN.d.ts +0 -79
  124. package/dist/relationships.cjs.map +0 -1
  125. package/dist/relationships.js.map +0 -1
  126. package/dist/tables.cjs.map +0 -1
  127. package/dist/tables.js.map +0 -1
  128. package/dist/types-Du86atZ8.d.cts +0 -199
  129. package/dist/types-Du86atZ8.d.ts +0 -199
  130. package/dist/types-bX2dCrdl.d.cts +0 -52
  131. package/dist/types-bX2dCrdl.d.ts +0 -52
@@ -0,0 +1,2559 @@
1
+ 'use client';
2
+ import { a as useSchemaBuilderStore, i as useSchemaBuilder, t as schemaBuilderQueryKey } from "./query-BmN_qO0W.js";
3
+ import { createElement, useCallback, useMemo } from "react";
4
+ import { clsx } from "clsx";
5
+ import { twMerge } from "tailwind-merge";
6
+ import * as FluentContextSelector from "@fluentui/react-context-selector";
7
+ import { RiBracesLine, RiBracketsFill, RiCalculatorLine, RiCalendarLine, RiCharacterRecognitionLine, RiCodeLine, RiFingerprintLine, RiFontSize, RiGlobalLine, RiHashtag, RiImageLine, RiLink, RiMailLine, RiMapLine, RiMapPin2Line, RiSearchLine, RiText, RiTimer2Line, RiTimerLine, RiToggleLine, RiUploadCloudLine, RiWifiLine } from "@remixicon/react";
8
+ import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query";
9
+ import { nodes } from "pg-ast";
10
+
11
+ //#region src/lib/utils.ts
12
+ function cn(...inputs) {
13
+ return twMerge(clsx(inputs));
14
+ }
15
+
16
+ //#endregion
17
+ //#region src/schema/schema-builder-core/lib/schema/types.ts
18
+ const RelationshipTypes = {
19
+ ONE_TO_ONE: "one-to-one",
20
+ BELONGS_TO: "belongs-to",
21
+ ONE_TO_MANY: "one-to-many",
22
+ MANY_TO_MANY: "many-to-many"
23
+ };
24
+ const ForeignKeyActions = {
25
+ CASCADE: "c",
26
+ RESTRICT: "r",
27
+ SET_NULL: "n",
28
+ SET_DEFAULT: "d",
29
+ NO_ACTION: "a"
30
+ };
31
+ const RelationshipTypeLabels = {
32
+ [RelationshipTypes.ONE_TO_ONE]: "One to one",
33
+ [RelationshipTypes.BELONGS_TO]: "Belongs to",
34
+ [RelationshipTypes.ONE_TO_MANY]: "One to many",
35
+ [RelationshipTypes.MANY_TO_MANY]: "Many to many"
36
+ };
37
+ const ForeignKeyActionLabels = {
38
+ [ForeignKeyActions.CASCADE]: "Cascade",
39
+ [ForeignKeyActions.RESTRICT]: "Restrict",
40
+ [ForeignKeyActions.SET_NULL]: "Set null",
41
+ [ForeignKeyActions.SET_DEFAULT]: "Set default",
42
+ [ForeignKeyActions.NO_ACTION]: "No action"
43
+ };
44
+ const INDEX_TYPE_LABELS = {
45
+ btree: "B-Tree",
46
+ hash: "Hash",
47
+ gin: "GIN",
48
+ gist: "GiST",
49
+ spgist: "SP-GiST",
50
+ brin: "BRIN"
51
+ };
52
+
53
+ //#endregion
54
+ //#region src/schema/schema-builder-core/lib/schema/schema-conversion.ts
55
+ /**
56
+ * Position cache to avoid recalculating positions on every render.
57
+ * Keyed by table ID - positions persist across schema updates.
58
+ */
59
+ const positionCache = /* @__PURE__ */ new Map();
60
+ /**
61
+ * Generates automatic positioning for tables in the visualizer
62
+ * Uses a simple grid layout algorithm
63
+ */
64
+ function generateTablePosition(index, totalTables) {
65
+ const GRID_SPACING = 350;
66
+ const COLS = Math.max(1, Math.ceil(Math.sqrt(totalTables)));
67
+ const col = index % COLS;
68
+ const row = Math.floor(index / COLS);
69
+ return {
70
+ x: col * GRID_SPACING + 100,
71
+ y: row * GRID_SPACING + 100
72
+ };
73
+ }
74
+ /**
75
+ * Get cached position or create new one for a table.
76
+ * Positions are cached by table ID to persist across re-renders.
77
+ */
78
+ function getOrCreatePosition(tableId, index, totalTables) {
79
+ const cached = positionCache.get(tableId);
80
+ if (cached) return cached;
81
+ const position = generateTablePosition(index, totalTables);
82
+ positionCache.set(tableId, position);
83
+ return position;
84
+ }
85
+ /**
86
+ * Converts a DbLightSchema (builder format) to SchemaData (visualizer format)
87
+ */
88
+ function dbLightToSchemaData(dbSchema, options) {
89
+ const { includeCategories } = options ?? {};
90
+ const filteredTables = includeCategories ? dbSchema.tables.filter((t) => !t.category || includeCategories.includes(t.category)) : dbSchema.tables;
91
+ const visibleTableIds = new Set(filteredTables.map((t) => t.id));
92
+ const nodes = filteredTables.map((table, index) => {
93
+ const position = getOrCreatePosition(table.id, index, filteredTables.length);
94
+ return {
95
+ id: table.id,
96
+ type: "tableNode",
97
+ position,
98
+ data: {
99
+ label: table.name,
100
+ fields: table.fields.map(fieldDefinitionToTableField),
101
+ selected: false
102
+ }
103
+ };
104
+ });
105
+ const edges = (dbSchema.relationships || []).filter((r) => visibleTableIds.has(r.sourceTable) && visibleTableIds.has(r.targetTable)).map((relationship) => ({
106
+ id: `${relationship.sourceTable}-${relationship.targetTable}-${relationship.sourceField}`,
107
+ source: relationship.sourceTable,
108
+ target: relationship.targetTable,
109
+ sourceHandle: relationship.sourceField,
110
+ targetHandle: relationship.targetField,
111
+ type: "custom",
112
+ animated: false,
113
+ data: {
114
+ sourceField: relationship.sourceField,
115
+ targetField: relationship.targetField,
116
+ relationType: relationship.type,
117
+ onDelete: relationship.onDelete,
118
+ onUpdate: relationship.onUpdate
119
+ }
120
+ }));
121
+ return {
122
+ name: dbSchema.name,
123
+ description: dbSchema.description || "",
124
+ category: dbSchema.metadata?.tags?.[0] || "Custom",
125
+ nodes,
126
+ edges
127
+ };
128
+ }
129
+ /**
130
+ * Converts a FieldDefinition (builder) to TableField (visualizer)
131
+ */
132
+ function fieldDefinitionToTableField(field) {
133
+ const isForeign = isFieldForeign(field);
134
+ return {
135
+ name: field.name,
136
+ type: cellTypeToSqlType(field.type),
137
+ isPrimary: field.constraints.primaryKey || false,
138
+ isForeign,
139
+ isUnique: field.constraints.unique || false,
140
+ isNullable: field.constraints.nullable ?? true,
141
+ foreignKey: isForeign && field.metadata?.targetTable ? {
142
+ targetTable: field.metadata.targetTable,
143
+ targetField: field.metadata.targetField || "id"
144
+ } : void 0
145
+ };
146
+ }
147
+ /**
148
+ * Maps CellType to SQL type string for visualizer display
149
+ */
150
+ function cellTypeToSqlType(cellType) {
151
+ return {
152
+ text: "varchar",
153
+ textarea: "text",
154
+ integer: "int",
155
+ number: "float",
156
+ boolean: "boolean",
157
+ toggle: "boolean",
158
+ decimal: "decimal",
159
+ smallint: "smallint",
160
+ email: "varchar",
161
+ url: "varchar",
162
+ phone: "varchar",
163
+ currency: "decimal",
164
+ percentage: "decimal",
165
+ color: "varchar",
166
+ rating: "int",
167
+ tags: "varchar",
168
+ date: "date",
169
+ datetime: "datetime",
170
+ timestamptz: "timestamp",
171
+ time: "time",
172
+ interval: "interval",
173
+ json: "json",
174
+ jsonb: "jsonb",
175
+ "text-array": "text[]",
176
+ "integer-array": "int[]",
177
+ "number-array": "float[]",
178
+ "uuid-array": "uuid[]",
179
+ "date-array": "date[]",
180
+ array: "array",
181
+ image: "varchar",
182
+ file: "varchar",
183
+ video: "varchar",
184
+ audio: "varchar",
185
+ upload: "varchar",
186
+ uuid: "uuid",
187
+ inet: "inet",
188
+ geometry: "geometry",
189
+ "geometry-point": "point",
190
+ "geometry-collection": "geometry",
191
+ tsvector: "tsvector",
192
+ origin: "varchar",
193
+ relation: "int",
194
+ citext: "citext",
195
+ bpchar: "char",
196
+ bit: "bit",
197
+ unknown: "varchar"
198
+ }[cellType] || "varchar";
199
+ }
200
+ /**
201
+ * Determines if a field is a foreign key based on its metadata
202
+ */
203
+ function isFieldForeign(field) {
204
+ return !!(field.metadata?.targetTable || field.name.endsWith("_id"));
205
+ }
206
+
207
+ //#endregion
208
+ //#region src/schema/schema-builder-core/lib/schema/field-type-registry.ts
209
+ const DEFAULT_TEXT_CONSTRAINTS = {
210
+ nullable: true,
211
+ maxLength: 255
212
+ };
213
+ const DEFAULT_NUMERIC_CONSTRAINTS = { nullable: true };
214
+ const DEFAULT_BOOLEAN_CONSTRAINTS = {
215
+ nullable: true,
216
+ defaultValue: false
217
+ };
218
+ const DEFAULT_DATE_CONSTRAINTS = { nullable: true };
219
+ const DEFAULT_JSON_CONSTRAINTS = { nullable: true };
220
+ const DEFAULT_ARRAY_CONSTRAINTS = { nullable: true };
221
+ const DEFAULT_MEDIA_CONSTRAINTS = { nullable: true };
222
+ const DEFAULT_SPECIAL_CONSTRAINTS = { nullable: true };
223
+ const FIELD_TYPES = [
224
+ {
225
+ type: "text",
226
+ label: "Text",
227
+ description: "Variable-length character string",
228
+ icon: RiText,
229
+ isBasic: true,
230
+ defaultConstraints: DEFAULT_TEXT_CONSTRAINTS,
231
+ configurable: {
232
+ length: true,
233
+ pattern: true
234
+ }
235
+ },
236
+ {
237
+ type: "integer",
238
+ label: "Integer",
239
+ description: "Whole number (32-bit)",
240
+ icon: RiHashtag,
241
+ badge: "32",
242
+ isBasic: true,
243
+ defaultConstraints: DEFAULT_NUMERIC_CONSTRAINTS,
244
+ configurable: { range: true }
245
+ },
246
+ {
247
+ type: "number",
248
+ label: "Number",
249
+ description: "Floating-point number",
250
+ icon: RiHashtag,
251
+ badge: "f",
252
+ isBasic: true,
253
+ defaultConstraints: DEFAULT_NUMERIC_CONSTRAINTS,
254
+ configurable: {
255
+ precision: true,
256
+ range: true
257
+ }
258
+ },
259
+ {
260
+ type: "boolean",
261
+ label: "Boolean",
262
+ description: "True or false value",
263
+ icon: RiToggleLine,
264
+ isBasic: true,
265
+ defaultConstraints: DEFAULT_BOOLEAN_CONSTRAINTS,
266
+ configurable: {}
267
+ },
268
+ {
269
+ type: "decimal",
270
+ label: "Decimal",
271
+ description: "Fixed-precision decimal number",
272
+ icon: RiCalculatorLine,
273
+ defaultConstraints: {
274
+ ...DEFAULT_NUMERIC_CONSTRAINTS,
275
+ precision: 10,
276
+ scale: 2
277
+ },
278
+ configurable: {
279
+ precision: true,
280
+ scale: true,
281
+ range: true
282
+ }
283
+ },
284
+ {
285
+ type: "smallint",
286
+ label: "Small Integer",
287
+ description: "Small whole number (16-bit)",
288
+ icon: RiHashtag,
289
+ badge: "16",
290
+ defaultConstraints: DEFAULT_NUMERIC_CONSTRAINTS,
291
+ configurable: { range: true }
292
+ },
293
+ {
294
+ type: "email",
295
+ label: "Email",
296
+ description: "Email address with validation",
297
+ icon: RiMailLine,
298
+ defaultConstraints: {
299
+ ...DEFAULT_TEXT_CONSTRAINTS,
300
+ pattern: "^[^@]+@[^@]+\\.[^@]+$"
301
+ },
302
+ configurable: { length: true }
303
+ },
304
+ {
305
+ type: "url",
306
+ label: "URL",
307
+ description: "Web address with validation",
308
+ icon: RiLink,
309
+ defaultConstraints: {
310
+ ...DEFAULT_TEXT_CONSTRAINTS,
311
+ pattern: "^https?://.+"
312
+ },
313
+ configurable: { length: true }
314
+ },
315
+ {
316
+ type: "date",
317
+ label: "Date",
318
+ description: "Date without time",
319
+ icon: RiCalendarLine,
320
+ isBasic: true,
321
+ defaultConstraints: DEFAULT_DATE_CONSTRAINTS,
322
+ configurable: {}
323
+ },
324
+ {
325
+ type: "timestamptz",
326
+ label: "Timestamp",
327
+ description: "Date and time with timezone",
328
+ icon: RiGlobalLine,
329
+ isBasic: true,
330
+ defaultConstraints: DEFAULT_DATE_CONSTRAINTS,
331
+ configurable: {}
332
+ },
333
+ {
334
+ type: "time",
335
+ label: "Time",
336
+ description: "Time without date",
337
+ icon: RiTimerLine,
338
+ defaultConstraints: DEFAULT_DATE_CONSTRAINTS,
339
+ configurable: {}
340
+ },
341
+ {
342
+ type: "interval",
343
+ label: "Interval",
344
+ description: "Time interval/duration",
345
+ icon: RiTimer2Line,
346
+ defaultConstraints: DEFAULT_DATE_CONSTRAINTS,
347
+ configurable: {}
348
+ },
349
+ {
350
+ type: "json",
351
+ label: "JSON",
352
+ description: "JSON data structure",
353
+ icon: RiBracesLine,
354
+ badge: "tx",
355
+ defaultConstraints: DEFAULT_JSON_CONSTRAINTS,
356
+ configurable: {}
357
+ },
358
+ {
359
+ type: "jsonb",
360
+ label: "JSONB",
361
+ description: "Binary JSON with indexing",
362
+ icon: RiBracesLine,
363
+ badge: "b",
364
+ isBasic: true,
365
+ defaultConstraints: DEFAULT_JSON_CONSTRAINTS,
366
+ configurable: {}
367
+ },
368
+ {
369
+ type: "text-array",
370
+ label: "Text Array",
371
+ description: "Array of text values",
372
+ icon: RiBracketsFill,
373
+ badge: "str",
374
+ defaultConstraints: DEFAULT_ARRAY_CONSTRAINTS,
375
+ configurable: { length: true }
376
+ },
377
+ {
378
+ type: "integer-array",
379
+ label: "Integer Array",
380
+ description: "Array of integer values",
381
+ icon: RiBracketsFill,
382
+ badge: "int",
383
+ defaultConstraints: DEFAULT_ARRAY_CONSTRAINTS,
384
+ configurable: {}
385
+ },
386
+ {
387
+ type: "number-array",
388
+ label: "Number Array",
389
+ description: "Array of numeric values",
390
+ icon: RiBracketsFill,
391
+ badge: "num",
392
+ defaultConstraints: DEFAULT_ARRAY_CONSTRAINTS,
393
+ configurable: {}
394
+ },
395
+ {
396
+ type: "uuid-array",
397
+ label: "UUID Array",
398
+ description: "Array of UUID values",
399
+ icon: RiBracketsFill,
400
+ badge: "uid",
401
+ defaultConstraints: DEFAULT_ARRAY_CONSTRAINTS,
402
+ configurable: {}
403
+ },
404
+ {
405
+ type: "date-array",
406
+ label: "Date Array",
407
+ description: "Array of date values",
408
+ icon: RiBracketsFill,
409
+ badge: "dt",
410
+ defaultConstraints: DEFAULT_ARRAY_CONSTRAINTS,
411
+ configurable: {}
412
+ },
413
+ {
414
+ type: "array",
415
+ label: "Generic Array",
416
+ description: "Generic array type",
417
+ icon: RiBracketsFill,
418
+ badge: "any",
419
+ defaultConstraints: DEFAULT_ARRAY_CONSTRAINTS,
420
+ configurable: {}
421
+ },
422
+ {
423
+ type: "image",
424
+ label: "Image",
425
+ description: "Image file reference",
426
+ icon: RiImageLine,
427
+ isBasic: true,
428
+ defaultConstraints: DEFAULT_MEDIA_CONSTRAINTS,
429
+ configurable: { length: true }
430
+ },
431
+ {
432
+ type: "upload",
433
+ label: "Upload",
434
+ description: "Generic file upload",
435
+ icon: RiUploadCloudLine,
436
+ isBasic: true,
437
+ defaultConstraints: DEFAULT_MEDIA_CONSTRAINTS,
438
+ configurable: { length: true }
439
+ },
440
+ {
441
+ type: "uuid",
442
+ label: "UUID",
443
+ description: "Universally unique identifier",
444
+ icon: RiFingerprintLine,
445
+ isBasic: true,
446
+ defaultConstraints: {
447
+ ...DEFAULT_SPECIAL_CONSTRAINTS,
448
+ nullable: false
449
+ },
450
+ configurable: {}
451
+ },
452
+ {
453
+ type: "inet",
454
+ label: "IP Address",
455
+ description: "IPv4 or IPv6 address",
456
+ icon: RiWifiLine,
457
+ defaultConstraints: DEFAULT_SPECIAL_CONSTRAINTS,
458
+ configurable: {}
459
+ },
460
+ {
461
+ type: "geometry",
462
+ label: "Geometry",
463
+ description: "Geometric shape data",
464
+ icon: RiMapLine,
465
+ badge: "geo",
466
+ defaultConstraints: DEFAULT_SPECIAL_CONSTRAINTS,
467
+ configurable: {}
468
+ },
469
+ {
470
+ type: "geometry-point",
471
+ label: "Point",
472
+ description: "Geographic point coordinates",
473
+ icon: RiMapPin2Line,
474
+ defaultConstraints: DEFAULT_SPECIAL_CONSTRAINTS,
475
+ configurable: {}
476
+ },
477
+ {
478
+ type: "geometry-collection",
479
+ label: "Geometry Collection",
480
+ description: "Collection of geometric shapes",
481
+ icon: RiMapLine,
482
+ badge: "col",
483
+ defaultConstraints: DEFAULT_SPECIAL_CONSTRAINTS,
484
+ configurable: {}
485
+ },
486
+ {
487
+ type: "tsvector",
488
+ label: "Text Search",
489
+ description: "Full-text search vector",
490
+ icon: RiSearchLine,
491
+ defaultConstraints: DEFAULT_SPECIAL_CONSTRAINTS,
492
+ configurable: {}
493
+ },
494
+ {
495
+ type: "citext",
496
+ label: "Citext",
497
+ description: "Text with case-insensitive comparison",
498
+ icon: RiFontSize,
499
+ defaultConstraints: DEFAULT_TEXT_CONSTRAINTS,
500
+ configurable: { length: true }
501
+ },
502
+ {
503
+ type: "bpchar",
504
+ label: "Fixed Char",
505
+ description: "Fixed-length character string",
506
+ icon: RiCharacterRecognitionLine,
507
+ defaultConstraints: {
508
+ ...DEFAULT_TEXT_CONSTRAINTS,
509
+ maxLength: 1
510
+ },
511
+ configurable: { length: true }
512
+ },
513
+ {
514
+ type: "bit",
515
+ label: "Bit String",
516
+ description: "Fixed-length bit string",
517
+ icon: RiCodeLine,
518
+ defaultConstraints: DEFAULT_SPECIAL_CONSTRAINTS,
519
+ configurable: { length: true }
520
+ }
521
+ ];
522
+ const FIELD_TYPE_CATEGORIES = [
523
+ {
524
+ name: "basic",
525
+ label: "Basic Types",
526
+ description: "Fundamental data types",
527
+ types: FIELD_TYPES.filter((type) => [
528
+ "text",
529
+ "integer",
530
+ "number",
531
+ "boolean",
532
+ "decimal",
533
+ "smallint",
534
+ "image",
535
+ "upload"
536
+ ].includes(type.type))
537
+ },
538
+ {
539
+ name: "enhanced",
540
+ label: "Enhanced Types",
541
+ description: "Types with built-in validation and formatting",
542
+ types: FIELD_TYPES.filter((type) => ["email", "url"].includes(type.type))
543
+ },
544
+ {
545
+ name: "datetime",
546
+ label: "Date & Time",
547
+ description: "Date and time related types",
548
+ types: FIELD_TYPES.filter((type) => [
549
+ "date",
550
+ "timestamptz",
551
+ "time",
552
+ "interval"
553
+ ].includes(type.type))
554
+ },
555
+ {
556
+ name: "json",
557
+ label: "JSON Types",
558
+ description: "Structured data storage",
559
+ types: FIELD_TYPES.filter((type) => ["json", "jsonb"].includes(type.type))
560
+ },
561
+ {
562
+ name: "arrays",
563
+ label: "Array Types",
564
+ description: "Arrays of values",
565
+ types: FIELD_TYPES.filter((type) => [
566
+ "text-array",
567
+ "integer-array",
568
+ "number-array",
569
+ "uuid-array",
570
+ "date-array",
571
+ "array"
572
+ ].includes(type.type))
573
+ },
574
+ {
575
+ name: "media",
576
+ label: "Media Types",
577
+ description: "File and media references",
578
+ types: []
579
+ },
580
+ {
581
+ name: "special",
582
+ label: "Special Types",
583
+ description: "Specialized data types",
584
+ types: FIELD_TYPES.filter((type) => [
585
+ "uuid",
586
+ "inet",
587
+ "geometry",
588
+ "geometry-point",
589
+ "geometry-collection",
590
+ "tsvector",
591
+ "citext",
592
+ "bpchar",
593
+ "bit"
594
+ ].includes(type.type))
595
+ }
596
+ ];
597
+ function getFieldTypeInfo(type) {
598
+ return FIELD_TYPES.find((fieldType) => fieldType.type === type);
599
+ }
600
+ function getAllFieldTypes() {
601
+ return FIELD_TYPES;
602
+ }
603
+ function searchFieldTypes(query) {
604
+ const lowercaseQuery = query.toLowerCase();
605
+ return FIELD_TYPES.filter((type) => type.label.toLowerCase().includes(lowercaseQuery) || type.description.toLowerCase().includes(lowercaseQuery) || type.type.toLowerCase().includes(lowercaseQuery));
606
+ }
607
+ function getDefaultConstraintsForType(type) {
608
+ return getFieldTypeInfo(type)?.defaultConstraints || DEFAULT_SPECIAL_CONSTRAINTS;
609
+ }
610
+ function getBasicFieldTypes() {
611
+ return FIELD_TYPES.filter((type) => type.isBasic === true).sort((a, b) => {
612
+ if (a.type === "uuid") return -1;
613
+ if (b.type === "uuid") return 1;
614
+ return 0;
615
+ });
616
+ }
617
+ function getAdvancedFieldTypes() {
618
+ return FIELD_TYPES.filter((type) => type.isBasic !== true);
619
+ }
620
+
621
+ //#endregion
622
+ //#region src/compat/auth-sdk.ts
623
+ function useAuthSdkClient() {
624
+ const { adapter, scope } = useSchemaBuilder();
625
+ return { fetchUsersQuery: (variables, signal) => adapter.core.users(variables, {
626
+ scope,
627
+ signal
628
+ }) };
629
+ }
630
+
631
+ //#endregion
632
+ //#region src/compat/schema-builder-sdk.ts
633
+ const featureByMutation = {
634
+ createField: "fields",
635
+ createForeignKeyConstraint: "relationships",
636
+ createIndex: "indexes",
637
+ createPrimaryKeyConstraint: "fields",
638
+ createTableGrant: "policies",
639
+ createTable: "policies",
640
+ createUniqueConstraint: "fields",
641
+ deleteField: "fields",
642
+ deleteForeignKeyConstraint: "relationships",
643
+ deleteIndex: "indexes",
644
+ deletePolicy: "policies",
645
+ deletePrimaryKeyConstraint: "fields",
646
+ deleteTable: "tables",
647
+ deleteUniqueConstraint: "fields",
648
+ updateField: "fields",
649
+ updateForeignKeyConstraint: "relationships",
650
+ updateIndex: "indexes",
651
+ updatePolicy: "policies",
652
+ updatePrimaryKeyConstraint: "fields",
653
+ updateTable: "tables"
654
+ };
655
+ function useGeneratedMutation(operation, options) {
656
+ const { adapter, scope, onInvalidate } = useSchemaBuilder();
657
+ const feature = featureByMutation[operation];
658
+ const operationFn = adapter[feature][operation];
659
+ const selection = options?.selection?.fields;
660
+ return useMutation({
661
+ mutationFn: (variables) => operationFn(variables, {
662
+ scope,
663
+ selection
664
+ }),
665
+ onSuccess: () => onInvalidate?.({
666
+ scope,
667
+ feature,
668
+ operation
669
+ })
670
+ });
671
+ }
672
+ function useSchemaBuilderSdkClient() {
673
+ const { adapter, scope } = useSchemaBuilder();
674
+ const bind = (operation) => (variables, signal) => adapter.core[operation](variables, {
675
+ scope,
676
+ signal
677
+ });
678
+ return {
679
+ fetchApiSchemasQuery: bind("apiSchemas"),
680
+ fetchApisQuery: bind("apis"),
681
+ fetchDatabasesQuery: bind("databases"),
682
+ fetchFieldsQuery: bind("fields"),
683
+ fetchForeignKeyConstraintsQuery: bind("foreignKeyConstraints"),
684
+ fetchIndicesQuery: bind("indices"),
685
+ fetchPoliciesQuery: bind("policies"),
686
+ fetchPrimaryKeyConstraintsQuery: bind("primaryKeyConstraints"),
687
+ fetchSchemasQuery: bind("schemas"),
688
+ fetchTableQuery: bind("table"),
689
+ fetchTablesQuery: bind("tables"),
690
+ fetchUniqueConstraintsQuery: bind("uniqueConstraints")
691
+ };
692
+ }
693
+ const apiKeys = { all: ["schema-builder", "apis"] };
694
+ const domainKeys = {
695
+ all: ["schema-builder", "domains"],
696
+ lists: () => [
697
+ "schema-builder",
698
+ "domains",
699
+ "list"
700
+ ]
701
+ };
702
+ const schemaKeys = { all: ["schema-builder", "schemas"] };
703
+ const siteKeys = { all: ["schema-builder", "sites"] };
704
+ const useCreateFieldMutation = (options) => useGeneratedMutation("createField", options);
705
+ const useCreateForeignKeyConstraintMutation = (options) => useGeneratedMutation("createForeignKeyConstraint", options);
706
+ const useCreateIndexMutation = (options) => useGeneratedMutation("createIndex", options);
707
+ const useCreatePrimaryKeyConstraintMutation = (options) => useGeneratedMutation("createPrimaryKeyConstraint", options);
708
+ const useCreateTableGrantMutation = (options) => useGeneratedMutation("createTableGrant", options);
709
+ const useCreateTableMutation = (options) => useGeneratedMutation("createTable", options);
710
+ const useCreateUniqueConstraintMutation = (options) => useGeneratedMutation("createUniqueConstraint", options);
711
+ const useDeleteFieldMutation = (options) => useGeneratedMutation("deleteField", options);
712
+ const useDeleteForeignKeyConstraintMutation = (options) => useGeneratedMutation("deleteForeignKeyConstraint", options);
713
+ const useDeleteIndexMutation = (options) => useGeneratedMutation("deleteIndex", options);
714
+ const useDeletePolicyMutation = (options) => useGeneratedMutation("deletePolicy", options);
715
+ const useDeletePrimaryKeyConstraintMutation = (options) => useGeneratedMutation("deletePrimaryKeyConstraint", options);
716
+ const useDeleteTableMutation = (options) => useGeneratedMutation("deleteTable", options);
717
+ const useDeleteUniqueConstraintMutation = (options) => useGeneratedMutation("deleteUniqueConstraint", options);
718
+ const useUpdateFieldMutation = (options) => useGeneratedMutation("updateField", options);
719
+ const useUpdateForeignKeyConstraintMutation = (options) => useGeneratedMutation("updateForeignKeyConstraint", options);
720
+ const useUpdateIndexMutation = (options) => useGeneratedMutation("updateIndex", options);
721
+ const useUpdatePolicyMutation = (options) => useGeneratedMutation("updatePolicy", options);
722
+ const useUpdatePrimaryKeyConstraintMutation = (options) => useGeneratedMutation("updatePrimaryKeyConstraint", options);
723
+ const useUpdateTableMutation = (options) => useGeneratedMutation("updateTable", options);
724
+
725
+ //#endregion
726
+ //#region src/compat/block-config.tsx
727
+ function useSchemaBuilderConfig() {
728
+ return useSchemaBuilder().scope;
729
+ }
730
+ function useSchemaBuilderRuntime() {
731
+ const runtime = useSchemaBuilder();
732
+ return {
733
+ ...runtime,
734
+ setCurrentDatabaseApi: (api) => runtime.store.getState().setCurrentDatabaseApi(api)
735
+ };
736
+ }
737
+ function useSchemaBuilderRuntimeStore(selector) {
738
+ return useSchemaBuilderStore(selector);
739
+ }
740
+
741
+ //#endregion
742
+ //#region src/schema/schema-builder-core/lib/gql/type-mapping.ts
743
+ /**
744
+ * Maps GraphQL field metadata to frontend cell types
745
+ * Uses priority: pgAlias > pgType > gqlType for type determination
746
+ * This is completely backend-agnostic and focuses only on frontend rendering needs
747
+ */
748
+ function mapToFrontendCellType(metadata) {
749
+ const { gqlType, isArray, pgAlias, pgType } = metadata;
750
+ if (pgAlias) {
751
+ const aliasType = mapAliasToCellType(pgAlias);
752
+ if (aliasType !== "unknown") return aliasType;
753
+ }
754
+ if (isArray) return mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);
755
+ if (pgType) {
756
+ const pgTypeMapped = mapBackendTypeToCellType(pgType);
757
+ if (pgTypeMapped !== "unknown") return pgTypeMapped;
758
+ }
759
+ return mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);
760
+ }
761
+ /**
762
+ * Maps PostgreSQL aliases to frontend cell types
763
+ */
764
+ function mapAliasToCellType(alias) {
765
+ return {
766
+ image: "image",
767
+ file: "file",
768
+ video: "video",
769
+ audio: "audio",
770
+ upload: "upload",
771
+ relation: "relation",
772
+ email: "email",
773
+ url: "url",
774
+ phone: "phone",
775
+ citext: "citext",
776
+ textarea: "textarea",
777
+ number: "number",
778
+ currency: "currency",
779
+ percentage: "percentage",
780
+ numeric: "decimal",
781
+ decimal: "decimal",
782
+ int: "integer",
783
+ integer: "integer",
784
+ smallint: "smallint",
785
+ boolean: "boolean",
786
+ toggle: "toggle",
787
+ date: "date",
788
+ datetime: "datetime",
789
+ time: "time",
790
+ timestamptz: "timestamptz",
791
+ interval: "interval",
792
+ json: "json",
793
+ jsonb: "jsonb",
794
+ inet: "inet",
795
+ geometry: "geometry",
796
+ "geometry-point": "geometry-point",
797
+ "geometry-collection": "geometry-collection",
798
+ color: "color",
799
+ rating: "rating",
800
+ tags: "tags",
801
+ uuid: "uuid",
802
+ tsvector: "tsvector",
803
+ origin: "origin",
804
+ char: "bpchar",
805
+ bpchar: "bpchar",
806
+ text: "text",
807
+ bit: "bit",
808
+ array: "array",
809
+ "text-array": "text-array",
810
+ "integer-array": "integer-array",
811
+ "number-array": "number-array",
812
+ "uuid-array": "uuid-array",
813
+ "date-array": "date-array"
814
+ }[alias.toLowerCase()] || "unknown";
815
+ }
816
+ /**
817
+ * Maps backend-specific types to frontend cell types
818
+ */
819
+ function mapBackendTypeToCellType(pgType) {
820
+ return {
821
+ text: "text",
822
+ varchar: "text",
823
+ character: "text",
824
+ char: "text",
825
+ "character varying": "text",
826
+ citext: "citext",
827
+ bpchar: "bpchar",
828
+ integer: "integer",
829
+ int4: "integer",
830
+ smallint: "smallint",
831
+ int2: "smallint",
832
+ bigint: "integer",
833
+ int8: "integer",
834
+ numeric: "decimal",
835
+ decimal: "decimal",
836
+ real: "number",
837
+ float4: "number",
838
+ "double precision": "number",
839
+ float8: "number",
840
+ money: "currency",
841
+ boolean: "boolean",
842
+ bool: "boolean",
843
+ bit: "bit",
844
+ "bit varying": "bit",
845
+ varbit: "bit",
846
+ date: "date",
847
+ timestamp: "datetime",
848
+ timestamptz: "timestamptz",
849
+ "timestamp with time zone": "timestamptz",
850
+ "timestamp without time zone": "datetime",
851
+ time: "time",
852
+ timetz: "time",
853
+ "time with time zone": "time",
854
+ "time without time zone": "time",
855
+ interval: "interval",
856
+ json: "json",
857
+ jsonb: "jsonb",
858
+ uuid: "uuid",
859
+ tsvector: "tsvector",
860
+ inet: "inet",
861
+ cidr: "inet",
862
+ macaddr: "text",
863
+ macaddr8: "text",
864
+ point: "geometry-point",
865
+ line: "geometry",
866
+ lseg: "geometry",
867
+ box: "geometry",
868
+ path: "geometry",
869
+ polygon: "geometry",
870
+ circle: "geometry",
871
+ geometry: "geometry",
872
+ geography: "geometry",
873
+ email: "email",
874
+ url: "url",
875
+ image: "image",
876
+ upload: "upload",
877
+ origin: "origin",
878
+ _text: "array",
879
+ _varchar: "array",
880
+ _integer: "array"
881
+ }[pgType.toLowerCase()] || "unknown";
882
+ }
883
+ /**
884
+ * Maps GraphQL types to frontend cell types based on actual _meta data structure
885
+ */
886
+ function mapGraphQLTypeToCellType(gqlType, isArray, subtype, _typmod) {
887
+ if (isArray) return {
888
+ String: "text-array",
889
+ UUID: "uuid-array",
890
+ BigFloat: "number-array",
891
+ Int: "integer-array",
892
+ Date: "date-array"
893
+ }[gqlType.replace(/[!\[\]]/g, "")] || "array";
894
+ const baseType = gqlType.replace(/[!\[\]]/g, "");
895
+ if (baseType === "Relation") return "relation";
896
+ if (baseType === "Interval") return "interval";
897
+ if (baseType === "GeometryGeometryCollection") return "geometry-collection";
898
+ if (baseType === "GeoJSON") {
899
+ if (subtype === "GeometryPoint") return "geometry-point";
900
+ if (subtype === "GeometryPolygon") return "geometry-collection";
901
+ return "geometry";
902
+ }
903
+ return {
904
+ String: "text",
905
+ Int: "integer",
906
+ Float: "number",
907
+ Boolean: "boolean",
908
+ ID: "uuid",
909
+ DateTime: "datetime",
910
+ Datetime: "datetime",
911
+ Date: "date",
912
+ Time: "time",
913
+ JSON: "json",
914
+ JSONObject: "json",
915
+ Upload: "file",
916
+ URL: "url",
917
+ EmailAddress: "email",
918
+ PhoneNumber: "phone",
919
+ UUID: "uuid",
920
+ BigFloat: "number",
921
+ BigInt: "integer"
922
+ }[baseType] || "text";
923
+ }
924
+
925
+ //#endregion
926
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/transformers/decimal-constraints.ts
927
+ /**
928
+ * Generate AST for decimal precision and scale constraints
929
+ * @param precision - Maximum total number of digits
930
+ * @param scale - Maximum number of decimal places
931
+ * @returns PostgreSQL AST for the precision/scale constraint
932
+ */
933
+ function generateDecimalPrecisionScaleAST(precision, scale) {
934
+ const constraints = [];
935
+ if (precision !== void 0 && precision > 0) constraints.push(nodes.aExpr({
936
+ kind: "AEXPR_OP",
937
+ name: [nodes.string({ sval: "<=" })],
938
+ lexpr: nodes.funcCall({
939
+ funcname: [nodes.string({ sval: "length" })],
940
+ args: [nodes.funcCall({
941
+ funcname: [nodes.string({ sval: "replace" })],
942
+ args: [
943
+ nodes.typeCast({
944
+ arg: nodes.columnRef({ fields: [nodes.string({ sval: "value" })] }),
945
+ typeName: { names: [nodes.string({ sval: "text" })] }
946
+ }),
947
+ nodes.aConst({ sval: { sval: "." } }),
948
+ nodes.aConst({ sval: { sval: "" } })
949
+ ]
950
+ })]
951
+ }),
952
+ rexpr: nodes.aConst({ ival: { ival: precision } })
953
+ }));
954
+ if (scale !== void 0 && scale > 0) constraints.push(nodes.aExpr({
955
+ kind: "AEXPR_OP",
956
+ name: [nodes.string({ sval: "<=" })],
957
+ lexpr: nodes.funcCall({
958
+ funcname: [nodes.string({ sval: "length" })],
959
+ args: [nodes.funcCall({
960
+ funcname: [nodes.string({ sval: "coalesce" })],
961
+ args: [nodes.funcCall({
962
+ funcname: [nodes.string({ sval: "split_part" })],
963
+ args: [
964
+ nodes.typeCast({
965
+ arg: nodes.columnRef({ fields: [nodes.string({ sval: "value" })] }),
966
+ typeName: { names: [nodes.string({ sval: "text" })] }
967
+ }),
968
+ nodes.aConst({ sval: { sval: "." } }),
969
+ nodes.aConst({ ival: { ival: 2 } })
970
+ ]
971
+ }), nodes.aConst({ sval: { sval: "" } })]
972
+ })]
973
+ }),
974
+ rexpr: nodes.aConst({ ival: { ival: scale } })
975
+ }));
976
+ if (constraints.length === 0) return null;
977
+ if (constraints.length === 1) return constraints[0];
978
+ return nodes.boolExpr({
979
+ boolop: "AND_EXPR",
980
+ args: constraints
981
+ });
982
+ }
983
+ /**
984
+ * Parse precision and scale from a check constraint AST
985
+ * Based on the actual generated AST structure from pg-ast
986
+ * @param chk - The check constraint AST from the database
987
+ * @returns Object with precision and scale if found, otherwise undefined values
988
+ */
989
+ function parseDecimalConstraintsFromAST(chk) {
990
+ if (!chk) return {};
991
+ const result = {};
992
+ try {
993
+ const boolExpr = chk.BoolExpr;
994
+ if (!boolExpr || boolExpr.boolop !== "AND_EXPR" || !Array.isArray(boolExpr.args)) {
995
+ parseConstraintExpression(chk, result);
996
+ return result;
997
+ }
998
+ for (const arg of boolExpr.args) parseConstraintExpression(arg, result);
999
+ } catch (error) {
1000
+ console.warn("Failed to parse decimal constraints from AST:", error);
1001
+ }
1002
+ return result;
1003
+ }
1004
+ /**
1005
+ * Parse a single constraint expression (A_Expr)
1006
+ */
1007
+ function parseConstraintExpression(node, result) {
1008
+ const aExpr = node.A_Expr;
1009
+ if (!aExpr) return;
1010
+ const funcCall = aExpr.lexpr?.FuncCall;
1011
+ const rexprConst = aExpr.rexpr?.A_Const;
1012
+ if (!funcCall || !rexprConst) return;
1013
+ if (funcCall.funcname?.[0]?.String?.sval !== "length") return;
1014
+ const innerFuncCall = funcCall.args?.[0]?.FuncCall;
1015
+ if (!innerFuncCall) return;
1016
+ const innerFuncName = innerFuncCall.funcname?.[0]?.String?.sval;
1017
+ const constraintValue = rexprConst.ival?.ival;
1018
+ if (typeof constraintValue !== "number") return;
1019
+ if (innerFuncName === "replace") result.precision = constraintValue;
1020
+ else if (innerFuncName === "coalesce") result.scale = constraintValue;
1021
+ }
1022
+
1023
+ //#endregion
1024
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/transformers/field-constraints-mapper.ts
1025
+ /**
1026
+ * Convert CellType to backend type string for GraphQL mutations
1027
+ */
1028
+ function cellTypeToBackendType(cellType) {
1029
+ return {
1030
+ text: "text",
1031
+ textarea: "text",
1032
+ integer: "integer",
1033
+ smallint: "smallint",
1034
+ number: "numeric",
1035
+ decimal: "numeric",
1036
+ boolean: "boolean",
1037
+ date: "date",
1038
+ datetime: "timestamp",
1039
+ timestamptz: "timestamptz",
1040
+ time: "time",
1041
+ interval: "interval",
1042
+ json: "json",
1043
+ jsonb: "jsonb",
1044
+ uuid: "uuid",
1045
+ inet: "inet",
1046
+ geometry: "geometry",
1047
+ "geometry-point": "point",
1048
+ "geometry-collection": "geometry",
1049
+ tsvector: "tsvector",
1050
+ citext: "citext",
1051
+ bpchar: "bpchar",
1052
+ bit: "bit",
1053
+ email: "email",
1054
+ url: "url",
1055
+ phone: "text",
1056
+ currency: "numeric",
1057
+ percentage: "numeric",
1058
+ color: "text",
1059
+ rating: "integer",
1060
+ tags: "text",
1061
+ image: "image",
1062
+ file: "text",
1063
+ video: "text",
1064
+ audio: "text",
1065
+ upload: "upload",
1066
+ "text-array": "text[]",
1067
+ "integer-array": "integer[]",
1068
+ "number-array": "numeric[]",
1069
+ "uuid-array": "uuid[]",
1070
+ "date-array": "date[]",
1071
+ array: "text[]",
1072
+ relation: "uuid",
1073
+ origin: "text",
1074
+ toggle: "boolean",
1075
+ unknown: "text"
1076
+ }[cellType] || "text";
1077
+ }
1078
+ /**
1079
+ * Determines if a field type needs a pgAlias smart tag
1080
+ * (when frontend type differs from backend type semantically)
1081
+ *
1082
+ * This is critical for preserving the original frontend type when:
1083
+ * - Enhanced types map to base types (e.g., 'phone' → 'text')
1084
+ * - Media types without DOMAINs map to text (e.g., 'file' → 'text', 'video' → 'text')
1085
+ * - Numeric variants map to numeric (e.g., 'number' → 'numeric', 'currency' → 'numeric')
1086
+ *
1087
+ * Types that use PostgreSQL DOMAINs do NOT need pgAlias because _meta returns the
1088
+ * domain name directly (e.g., 'upload', 'image', 'email', 'url').
1089
+ *
1090
+ * Without the pgAlias, the original type is lost after refetch from the server.
1091
+ */
1092
+ function needsPgAlias(cellType) {
1093
+ const backendType = cellTypeToBackendType(cellType);
1094
+ if ([
1095
+ "phone",
1096
+ "color",
1097
+ "tags",
1098
+ "file",
1099
+ "video",
1100
+ "audio",
1101
+ "number",
1102
+ "currency",
1103
+ "percentage",
1104
+ "geometry-collection",
1105
+ "array",
1106
+ "rating"
1107
+ ].includes(cellType)) return true;
1108
+ if (cellType !== backendType && cellType !== "unknown") {
1109
+ const legitimate = {
1110
+ decimal: ["numeric"],
1111
+ datetime: ["timestamp"],
1112
+ timestamptz: ["timestamptz"],
1113
+ "geometry-point": ["point"],
1114
+ toggle: ["boolean"],
1115
+ textarea: ["text"],
1116
+ relation: ["uuid"],
1117
+ origin: ["text"],
1118
+ "text-array": ["text[]"],
1119
+ "integer-array": ["integer[]"],
1120
+ "number-array": ["numeric[]"],
1121
+ "uuid-array": ["uuid[]"],
1122
+ "date-array": ["date[]"]
1123
+ }[cellType];
1124
+ if (!legitimate || !legitimate.includes(backendType)) console.warn(`Type '${cellType}' maps to '${backendType}' - consider adding to needsPgAlias if type is lost on refetch`);
1125
+ }
1126
+ return false;
1127
+ }
1128
+ /**
1129
+ * Maps field constraints to FieldPatch properties based on type configurability
1130
+ */
1131
+ function mapConstraintsToFieldPatch(field) {
1132
+ const typeInfo = getFieldTypeInfo(field.type);
1133
+ if (!typeInfo) return {};
1134
+ const result = {};
1135
+ const { constraints } = field;
1136
+ if (field.metadata?.smartTags && Object.keys(field.metadata.smartTags).length > 0) result.smartTags = { ...field.metadata.smartTags };
1137
+ if (typeInfo.configurable.length) {
1138
+ if (constraints.minLength != null) result.min = constraints.minLength;
1139
+ if (constraints.maxLength != null) result.max = constraints.maxLength;
1140
+ }
1141
+ if (typeInfo.configurable.range) {
1142
+ if (constraints.minValue != null) result.min = constraints.minValue;
1143
+ if (constraints.maxValue != null) result.max = constraints.maxValue;
1144
+ }
1145
+ if (typeInfo.configurable.pattern) {
1146
+ if (constraints.pattern != null) result.regexp = constraints.pattern;
1147
+ }
1148
+ if (typeInfo.configurable.precision || typeInfo.configurable.scale) result.chk = generateDecimalPrecisionScaleAST(constraints.precision, constraints.scale);
1149
+ if (constraints.checkExpression) result.chkExpr = constraints.checkExpression;
1150
+ if (needsPgAlias(field.type)) result.smartTags = {
1151
+ ...typeof result.smartTags === "object" && result.smartTags !== null && !Array.isArray(result.smartTags) ? result.smartTags : {},
1152
+ pgAlias: field.type
1153
+ };
1154
+ return result;
1155
+ }
1156
+ /**
1157
+ * Maps backend field constraints to frontend FieldConstraints based on type configurability
1158
+ * This is the inverse operation of mapConstraintsToFieldPatch
1159
+ */
1160
+ function mapDbFieldToConstraints(dbField, cellType) {
1161
+ const typeInfo = getFieldTypeInfo(cellType);
1162
+ if (!typeInfo) return {};
1163
+ const result = {};
1164
+ if (typeInfo.configurable.length) {
1165
+ result.minLength = dbField.min ?? void 0;
1166
+ result.maxLength = dbField.max ?? void 0;
1167
+ }
1168
+ if (typeInfo.configurable.range) {
1169
+ result.minValue = dbField.min ?? void 0;
1170
+ result.maxValue = dbField.max ?? void 0;
1171
+ }
1172
+ if (typeInfo.configurable.pattern) result.pattern = dbField.regexp ?? void 0;
1173
+ if ((typeInfo.configurable.precision || typeInfo.configurable.scale) && dbField.chk) {
1174
+ const { precision, scale } = parseDecimalConstraintsFromAST(dbField.chk);
1175
+ if (precision !== void 0) result.precision = precision;
1176
+ if (scale !== void 0) result.scale = scale;
1177
+ }
1178
+ if (dbField.chkExpr) result.checkExpression = String(dbField.chkExpr);
1179
+ return result;
1180
+ }
1181
+
1182
+ //#endregion
1183
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/transformers/transformers.ts
1184
+ const DEFAULT_TIMESTAMP = "1970-01-01T00:00:00.000Z";
1185
+ function normalizeTables(connection) {
1186
+ if (!connection) return [];
1187
+ return connection.edges?.map((edge) => edge.node).filter(Boolean) ?? [];
1188
+ }
1189
+ function normalizeFields(connection) {
1190
+ if (!connection) return [];
1191
+ return connection.nodes ?? [];
1192
+ }
1193
+ function extractSmartTagAlias(smartTags) {
1194
+ if (!smartTags || typeof smartTags !== "object") return null;
1195
+ for (const key of [
1196
+ "pgAlias",
1197
+ "type",
1198
+ "alias"
1199
+ ]) {
1200
+ const value = smartTags[key];
1201
+ if (typeof value === "string" && value.trim().length > 0) return value;
1202
+ }
1203
+ return null;
1204
+ }
1205
+ function mapPgTypeToGraphql(pgType) {
1206
+ if (!pgType) return "String";
1207
+ const normalized = pgType.toLowerCase();
1208
+ if (normalized.includes("int")) return "Int";
1209
+ if (normalized.includes("uuid")) return "UUID";
1210
+ if (normalized.includes("bool")) return "Boolean";
1211
+ if (normalized.includes("double") || normalized.includes("numeric") || normalized.includes("float") || normalized.includes("decimal")) return "Float";
1212
+ if (normalized.includes("timestamp") || normalized.includes("datetime")) return "Datetime";
1213
+ if (normalized.includes("date")) return "Date";
1214
+ if (normalized.includes("time")) return "Time";
1215
+ if (normalized.includes("jsonb")) return "JSON";
1216
+ if (normalized.includes("json")) return "JSON";
1217
+ if (normalized.includes("interval")) return "Interval";
1218
+ if (normalized.includes("point") || normalized.includes("geometry")) return "GeoJSON";
1219
+ return "String";
1220
+ }
1221
+ function inferCellType(field) {
1222
+ const typeName = field.type ?? "";
1223
+ const isArray = typeName.endsWith("[]");
1224
+ const baseType = isArray ? typeName.slice(0, -2) : typeName;
1225
+ const smartTagAlias = extractSmartTagAlias(field.smartTags ?? void 0);
1226
+ const cellType = mapToFrontendCellType({
1227
+ gqlType: mapPgTypeToGraphql(baseType),
1228
+ isArray,
1229
+ pgAlias: smartTagAlias ?? void 0,
1230
+ pgType: baseType || void 0,
1231
+ subtype: null
1232
+ });
1233
+ return cellType === "unknown" ? "text" : cellType;
1234
+ }
1235
+ function buildFieldConstraints(field, cellType, isPrimaryKey, isUnique) {
1236
+ const constraints = {
1237
+ nullable: !field.isRequired,
1238
+ defaultValue: field.defaultValue,
1239
+ primaryKey: isPrimaryKey,
1240
+ unique: isUnique
1241
+ };
1242
+ const dynamicConstraints = mapDbFieldToConstraints(field, cellType);
1243
+ return {
1244
+ ...constraints,
1245
+ ...dynamicConstraints
1246
+ };
1247
+ }
1248
+ function buildFieldDefinition(field, isPrimaryKey, isUnique, naturalOrder) {
1249
+ const cellType = inferCellType(field);
1250
+ return {
1251
+ id: field.id,
1252
+ name: field.name,
1253
+ type: cellType,
1254
+ label: field.label ?? field.name,
1255
+ description: field.description ?? void 0,
1256
+ constraints: buildFieldConstraints(field, cellType, isPrimaryKey, isUnique),
1257
+ fieldOrder: field.fieldOrder ?? naturalOrder,
1258
+ isRequired: field.isRequired ?? false,
1259
+ metadata: { smartTags: field.smartTags ?? null }
1260
+ };
1261
+ }
1262
+ function buildTableDefinition(table, primaryKeyConstraint, uniqueConstraints, foreignKeyConstraints, indices) {
1263
+ const fields = normalizeFields(table.fields).sort((a, b) => (a.fieldOrder ?? 0) - (b.fieldOrder ?? 0));
1264
+ const primaryKeyFieldIds = new Set(primaryKeyConstraint?.fieldIds ?? []);
1265
+ const uniqueFieldIds = /* @__PURE__ */ new Set();
1266
+ for (const constraint of uniqueConstraints) if (constraint.fieldIds.length === 1) uniqueFieldIds.add(constraint.fieldIds[0]);
1267
+ const fieldDefinitions = fields.map((field, index) => buildFieldDefinition(field, primaryKeyFieldIds.has(field.id), uniqueFieldIds.has(field.id), index));
1268
+ const constraints = [];
1269
+ if (primaryKeyConstraint) constraints.push({
1270
+ id: primaryKeyConstraint.id,
1271
+ name: primaryKeyConstraint.name ?? void 0,
1272
+ type: "primary_key",
1273
+ fields: primaryKeyConstraint.fieldIds
1274
+ });
1275
+ for (const constraint of uniqueConstraints) constraints.push({
1276
+ id: constraint.id,
1277
+ name: constraint.name ?? void 0,
1278
+ type: "unique",
1279
+ fields: constraint.fieldIds
1280
+ });
1281
+ for (const fk of foreignKeyConstraints) if (fk.fieldIds.length === 1 && fk.refFieldIds.length === 1) constraints.push({
1282
+ id: fk.id,
1283
+ name: fk.name ?? void 0,
1284
+ type: "foreign_key",
1285
+ fields: fk.fieldIds,
1286
+ referencedTable: fk.refTableId,
1287
+ referencedFields: fk.refFieldIds,
1288
+ onDelete: fk.deleteAction ?? ForeignKeyActions.NO_ACTION,
1289
+ onUpdate: fk.updateAction ?? ForeignKeyActions.NO_ACTION,
1290
+ smartTags: fk.smartTags ?? null,
1291
+ createdAt: fk.createdAt ?? void 0
1292
+ });
1293
+ const tableIndexes = indices.filter((index) => index.tableId === table.id).map((index) => ({
1294
+ id: index.id,
1295
+ name: index.name,
1296
+ fields: index.fieldIds ?? [],
1297
+ unique: Boolean(index.isUnique),
1298
+ type: index.accessMethod,
1299
+ createdAt: index.createdAt ?? void 0
1300
+ }));
1301
+ const category = table.category ? table.category.toUpperCase() : void 0;
1302
+ return {
1303
+ id: table.id,
1304
+ name: table.name,
1305
+ label: table.label ?? table.name,
1306
+ description: table.description ?? void 0,
1307
+ fields: fieldDefinitions,
1308
+ indexes: tableIndexes,
1309
+ constraints,
1310
+ category,
1311
+ smartTags: table.smartTags ?? void 0
1312
+ };
1313
+ }
1314
+ function buildDbLightSchema(database, primaryKeyConstraintsMap, uniqueConstraintsMap, foreignKeyConstraintsMap, indicesMap) {
1315
+ const tables = normalizeTables(database.tables).map((table) => buildTableDefinition(table, primaryKeyConstraintsMap.get(table.id), uniqueConstraintsMap.get(table.id) ?? [], foreignKeyConstraintsMap.get(table.id) ?? [], indicesMap.get(table.id) ?? []));
1316
+ const totalFields = tables.reduce((sum, table) => sum + table.fields.length, 0);
1317
+ const relationships = buildRelationships(foreignKeyConstraintsMap, tables);
1318
+ return {
1319
+ id: database.id,
1320
+ name: database.label ?? database.name ?? "Untitled Database",
1321
+ description: database.name ?? void 0,
1322
+ version: "remote-schema-1",
1323
+ tables,
1324
+ relationships,
1325
+ metadata: {
1326
+ createdAt: DEFAULT_TIMESTAMP,
1327
+ updatedAt: DEFAULT_TIMESTAMP,
1328
+ author: database.owner?.displayName ?? database.owner?.username ?? "",
1329
+ tags: ["Database", database.name ?? ""].filter(Boolean),
1330
+ databaseId: database.id,
1331
+ databaseName: database.name ?? void 0,
1332
+ databaseLabel: database.label ?? null,
1333
+ sourceType: "remote-database",
1334
+ ownerId: database.owner?.id ?? null,
1335
+ ownerName: database.owner?.displayName ?? database.owner?.username ?? null,
1336
+ tableCount: tables.length,
1337
+ fieldCount: totalFields
1338
+ }
1339
+ };
1340
+ }
1341
+ function createChecksum(dbSchema) {
1342
+ return JSON.stringify({
1343
+ id: dbSchema.id,
1344
+ name: dbSchema.name,
1345
+ tables: dbSchema.tables.map((table) => ({
1346
+ id: table.id,
1347
+ name: table.name,
1348
+ fields: table.fields.map((field) => ({
1349
+ id: field.id,
1350
+ name: field.name,
1351
+ type: field.type,
1352
+ constraints: field.constraints,
1353
+ fieldOrder: field.fieldOrder
1354
+ })),
1355
+ constraints: (table.constraints || []).map((constraint) => {
1356
+ if (constraint.type === "foreign_key") return {
1357
+ id: constraint.id,
1358
+ type: constraint.type,
1359
+ fields: constraint.fields,
1360
+ referencedTable: constraint.referencedTable,
1361
+ referencedFields: constraint.referencedFields,
1362
+ onDelete: constraint.onDelete,
1363
+ onUpdate: constraint.onUpdate
1364
+ };
1365
+ if (constraint.type === "primary_key" || constraint.type === "unique") return {
1366
+ id: constraint.id,
1367
+ type: constraint.type,
1368
+ fields: constraint.fields
1369
+ };
1370
+ return {
1371
+ id: constraint.id,
1372
+ type: constraint.type,
1373
+ fields: constraint.fields
1374
+ };
1375
+ }),
1376
+ indexes: (table.indexes || []).map((index) => ({
1377
+ id: index.id,
1378
+ name: index.name,
1379
+ fields: index.fields,
1380
+ unique: index.unique,
1381
+ type: index.type,
1382
+ createdAt: index.createdAt
1383
+ }))
1384
+ })),
1385
+ relationships: (dbSchema.relationships || []).map((relationship) => ({
1386
+ id: relationship.id,
1387
+ name: relationship.name,
1388
+ sourceTable: relationship.sourceTable,
1389
+ sourceField: relationship.sourceField,
1390
+ targetTable: relationship.targetTable,
1391
+ targetField: relationship.targetField,
1392
+ type: relationship.type,
1393
+ onDelete: relationship.onDelete,
1394
+ onUpdate: relationship.onUpdate
1395
+ }))
1396
+ });
1397
+ }
1398
+ function resolveSchemaId(database) {
1399
+ const schemaNodes = (database.schemas?.nodes ?? []).filter((schema) => Boolean(schema && schema.id));
1400
+ const appPublicSchema = schemaNodes.find((schema) => schema.name === "app_public");
1401
+ if (appPublicSchema) return appPublicSchema.id;
1402
+ return schemaNodes.find((schema) => schema.name === "public")?.id;
1403
+ }
1404
+ function buildRelationships(foreignKeyConstraintsMap, tables) {
1405
+ const relationships = [];
1406
+ const tableIdToNameMap = new Map(tables.map((t) => [t.id, t.name]));
1407
+ const fieldIdToNameMap = /* @__PURE__ */ new Map();
1408
+ for (const table of tables) for (const field of table.fields) fieldIdToNameMap.set(field.id, field.name);
1409
+ for (const [tableId, foreignKeys] of foreignKeyConstraintsMap) for (const fk of foreignKeys) {
1410
+ if (fk.fieldIds.length !== 1 || fk.refFieldIds.length !== 1) continue;
1411
+ const sourceTableName = tableIdToNameMap.get(tableId);
1412
+ const targetTableName = tableIdToNameMap.get(fk.refTableId);
1413
+ const sourceFieldName = fieldIdToNameMap.get(fk.fieldIds[0]);
1414
+ const targetFieldName = fieldIdToNameMap.get(fk.refFieldIds[0]);
1415
+ if (!sourceTableName || !targetTableName || !sourceFieldName || !targetFieldName) continue;
1416
+ relationships.push({
1417
+ id: fk.id,
1418
+ name: fk.name ?? void 0,
1419
+ sourceTable: tableId,
1420
+ sourceField: sourceFieldName,
1421
+ targetTable: fk.refTableId,
1422
+ targetField: targetFieldName,
1423
+ type: "one-to-many",
1424
+ onDelete: fk.deleteAction ?? ForeignKeyActions.NO_ACTION,
1425
+ onUpdate: fk.updateAction ?? ForeignKeyActions.NO_ACTION
1426
+ });
1427
+ }
1428
+ return relationships;
1429
+ }
1430
+ function transformUserDatabase(database, primaryKeyConstraintsMap, uniqueConstraintsMap, foreignKeyConstraintsMap, indicesMap) {
1431
+ const dbSchema = buildDbLightSchema(database, primaryKeyConstraintsMap, uniqueConstraintsMap, foreignKeyConstraintsMap, indicesMap);
1432
+ const fieldCount = dbSchema.tables.reduce((sum, table) => sum + table.fields.length, 0);
1433
+ const resolvedSchemaId = resolveSchemaId(database);
1434
+ if (resolvedSchemaId) {
1435
+ const metadata = dbSchema.metadata ?? {
1436
+ createdAt: DEFAULT_TIMESTAMP,
1437
+ updatedAt: DEFAULT_TIMESTAMP,
1438
+ tableCount: dbSchema.tables.length,
1439
+ fieldCount
1440
+ };
1441
+ dbSchema.metadata = {
1442
+ ...metadata,
1443
+ schemaId: resolvedSchemaId,
1444
+ tableCount: metadata.tableCount ?? dbSchema.tables.length,
1445
+ fieldCount: metadata.fieldCount ?? fieldCount
1446
+ };
1447
+ }
1448
+ const checksum = createChecksum(dbSchema);
1449
+ return {
1450
+ key: `db-${database.id}`,
1451
+ dbSchema,
1452
+ category: "Database",
1453
+ description: database.owner ? `Owner: ${database.owner.displayName ?? database.owner.username}` : void 0,
1454
+ checksum,
1455
+ databaseInfo: {
1456
+ id: database.id,
1457
+ name: database.name ?? "Untitled Database",
1458
+ label: database.label,
1459
+ schemaId: resolvedSchemaId ?? void 0,
1460
+ ownerName: database.owner?.displayName ?? database.owner?.username ?? void 0,
1461
+ ownerId: database.owner?.id ?? void 0,
1462
+ tableCount: dbSchema.tables.length,
1463
+ fieldCount
1464
+ }
1465
+ };
1466
+ }
1467
+ function transformUserDatabases(databases, primaryKeyConstraints, uniqueConstraints, foreignKeyConstraints, indices) {
1468
+ const primaryKeyConstraintsMap = /* @__PURE__ */ new Map();
1469
+ for (const constraint of primaryKeyConstraints) primaryKeyConstraintsMap.set(constraint.tableId, constraint);
1470
+ const uniqueConstraintsMap = /* @__PURE__ */ new Map();
1471
+ for (const constraint of uniqueConstraints) {
1472
+ const existing = uniqueConstraintsMap.get(constraint.tableId) ?? [];
1473
+ existing.push(constraint);
1474
+ uniqueConstraintsMap.set(constraint.tableId, existing);
1475
+ }
1476
+ const foreignKeyConstraintsMap = /* @__PURE__ */ new Map();
1477
+ for (const constraint of foreignKeyConstraints) {
1478
+ const existing = foreignKeyConstraintsMap.get(constraint.tableId) ?? [];
1479
+ existing.push(constraint);
1480
+ foreignKeyConstraintsMap.set(constraint.tableId, existing);
1481
+ }
1482
+ const indicesMap = /* @__PURE__ */ new Map();
1483
+ for (const index of indices) {
1484
+ const existing = indicesMap.get(index.tableId) ?? [];
1485
+ existing.push(index);
1486
+ indicesMap.set(index.tableId, existing);
1487
+ }
1488
+ return databases.map((database) => transformUserDatabase(database, primaryKeyConstraintsMap, uniqueConstraintsMap, foreignKeyConstraintsMap, indicesMap));
1489
+ }
1490
+
1491
+ //#endregion
1492
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/transformers/field-type-mapper.ts
1493
+ const SQL_KEYWORDS = /* @__PURE__ */ new Set([
1494
+ "CURRENT_TIMESTAMP",
1495
+ "CURRENT_DATE",
1496
+ "CURRENT_TIME",
1497
+ "LOCALTIME",
1498
+ "LOCALTIMESTAMP",
1499
+ "CURRENT_ROLE",
1500
+ "CURRENT_USER",
1501
+ "SESSION_USER",
1502
+ "USER",
1503
+ "CURRENT_CATALOG",
1504
+ "CURRENT_SCHEMA"
1505
+ ]);
1506
+ /**
1507
+ * Convert a backend type-name string into a structured FieldType object.
1508
+ *
1509
+ * Handles array suffixes (`'text[]'` → `{ name: 'text', array_dimensions: 1 }`)
1510
+ * since brackets fail the backend `is_valid_type_name` regex. Trailing `[]`
1511
+ * pairs are stripped and counted into `array_dimensions`.
1512
+ */
1513
+ function toFieldType(typeName) {
1514
+ let base = (typeName ?? "").trim();
1515
+ let dims = 0;
1516
+ while (base.endsWith("[]")) {
1517
+ base = base.slice(0, -2);
1518
+ dims += 1;
1519
+ }
1520
+ base = base.trim();
1521
+ const result = { name: base };
1522
+ if (dims > 0) result.array_dimensions = dims;
1523
+ return result;
1524
+ }
1525
+ /** Best-effort parse of a single function-arg literal into a scalar. */
1526
+ function parseScalarLiteral(token) {
1527
+ const t = token.trim();
1528
+ if (t === "") return "";
1529
+ if (t === "true") return true;
1530
+ if (t === "false") return false;
1531
+ if (t.toLowerCase() === "null") return null;
1532
+ if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
1533
+ if (t.startsWith("'") && t.endsWith("'") || t.startsWith("\"") && t.endsWith("\"")) return t.slice(1, -1);
1534
+ return t;
1535
+ }
1536
+ /**
1537
+ * Convert a backend default-expression string into a structured FieldDefault
1538
+ * object (or undefined when empty).
1539
+ *
1540
+ * Recognizes:
1541
+ * - function calls `uuidv7()` → `{ function: 'uuidv7' }`
1542
+ * - boolean / numeric literals `true` → `{ value: true }`, `42` → `{ value: 42 }`
1543
+ * - SQL keywords (allowlist) `CURRENT_TIMESTAMP` → `{ sql_keyword: 'CURRENT_TIMESTAMP' }`
1544
+ * - quoted / plain string `'draft'` → `{ value: 'draft' }`
1545
+ */
1546
+ function toFieldDefault(def) {
1547
+ if (def === void 0 || def === null) return void 0;
1548
+ const raw = String(def).trim();
1549
+ if (raw === "") return void 0;
1550
+ if (SQL_KEYWORDS.has(raw.toUpperCase())) return { sql_keyword: raw.toUpperCase() };
1551
+ const fnMatch = raw.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([\s\S]*)\)$/);
1552
+ if (fnMatch) {
1553
+ const fnName = fnMatch[1];
1554
+ const argsRaw = fnMatch[2].trim();
1555
+ const result = { function: fnName };
1556
+ if (argsRaw !== "") {
1557
+ const args = argsRaw.split(",").map((a) => parseScalarLiteral(a));
1558
+ if (args.length > 0) result.args = args;
1559
+ }
1560
+ return result;
1561
+ }
1562
+ if (raw === "true") return { value: true };
1563
+ if (raw === "false") return { value: false };
1564
+ if (/^-?\d+(\.\d+)?$/.test(raw)) return { value: Number(raw) };
1565
+ if (raw.startsWith("'") && raw.endsWith("'") || raw.startsWith("\"") && raw.endsWith("\"")) return { value: raw.slice(1, -1) };
1566
+ return { value: raw };
1567
+ }
1568
+ /**
1569
+ * Reverse of {@link toFieldType}: extract the type-name string from a structured
1570
+ * FieldType object (`{ name, array_dimensions? }` → `'name'` / `'name[]'`).
1571
+ *
1572
+ * Passes through if already a string; returns '' for null/undefined.
1573
+ */
1574
+ function fieldTypeToTypeName(t) {
1575
+ if (t == null) return "";
1576
+ if (typeof t === "string") return t;
1577
+ if (typeof t === "object") {
1578
+ const obj = t;
1579
+ if (typeof obj.name === "string") {
1580
+ const dims = typeof obj.array_dimensions === "number" && obj.array_dimensions > 0 ? obj.array_dimensions : 0;
1581
+ return obj.name + "[]".repeat(dims);
1582
+ }
1583
+ }
1584
+ return "";
1585
+ }
1586
+
1587
+ //#endregion
1588
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/database-shared-utils.ts
1589
+ /**
1590
+ * Transform SDK Field to DatabaseFieldNode
1591
+ * Handles the SDK's quirky types (chk can be {} | boolean | null)
1592
+ */
1593
+ function transformField(f) {
1594
+ return {
1595
+ id: f.id ?? "",
1596
+ name: f.name ?? "",
1597
+ type: fieldTypeToTypeName(f.type),
1598
+ chk: typeof f.chk === "boolean" ? f.chk : null,
1599
+ chkExpr: typeof f.chkExpr === "string" ? f.chkExpr : null,
1600
+ defaultValue: typeof f.defaultValue === "string" ? f.defaultValue : f.defaultValue != null ? JSON.stringify(f.defaultValue) : null,
1601
+ description: f.description ?? null,
1602
+ fieldOrder: f.fieldOrder ?? null,
1603
+ isRequired: f.isRequired ?? null,
1604
+ label: f.label ?? null,
1605
+ max: f.max ?? null,
1606
+ min: f.min ?? null,
1607
+ regexp: f.regexp ?? null,
1608
+ smartTags: f.smartTags ?? null
1609
+ };
1610
+ }
1611
+ /**
1612
+ * Transform SDK Table to DatabaseTableNode (without fields - compose separately)
1613
+ */
1614
+ function transformTable(t, fields = []) {
1615
+ return {
1616
+ id: t.id ?? "",
1617
+ name: t.name ?? "",
1618
+ label: t.label ?? null,
1619
+ description: t.description ?? null,
1620
+ pluralName: t.pluralName ?? null,
1621
+ singularName: t.singularName ?? null,
1622
+ smartTags: t.smartTags ?? null,
1623
+ timestamps: t.timestamps ?? null,
1624
+ databaseId: t.databaseId ?? "",
1625
+ schemaId: t.schemaId ?? "",
1626
+ category: t.category ?? null,
1627
+ fields: {
1628
+ totalCount: fields.length,
1629
+ nodes: fields
1630
+ }
1631
+ };
1632
+ }
1633
+ /**
1634
+ * Group fields by tableId into a Map for efficient lookup
1635
+ */
1636
+ function buildFieldsByTableMap(fields) {
1637
+ const map = /* @__PURE__ */ new Map();
1638
+ for (const f of fields) {
1639
+ if (!f.tableId) continue;
1640
+ const existing = map.get(f.tableId) ?? [];
1641
+ existing.push(transformField(f));
1642
+ map.set(f.tableId, existing);
1643
+ }
1644
+ return map;
1645
+ }
1646
+ /**
1647
+ * Group tables by databaseId into a Map for efficient lookup
1648
+ */
1649
+ function buildTablesByDatabaseMap(tables, fieldsByTable) {
1650
+ const map = /* @__PURE__ */ new Map();
1651
+ for (const t of tables) {
1652
+ if (!t.databaseId) continue;
1653
+ const existing = map.get(t.databaseId) ?? [];
1654
+ const fields = fieldsByTable.get(t.id ?? "") ?? [];
1655
+ existing.push(transformTable(t, fields));
1656
+ map.set(t.databaseId, existing);
1657
+ }
1658
+ return map;
1659
+ }
1660
+ /**
1661
+ * Extract non-null IDs from an array of objects with id property
1662
+ */
1663
+ function extractIds(items) {
1664
+ return items.map((item) => item.id).filter((id) => !!id);
1665
+ }
1666
+
1667
+ //#endregion
1668
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-accessible-databases.ts
1669
+ /**
1670
+ * Hook for fetching databases accessible to the current user (without constraints)
1671
+ * Tier 4 wrapper: Uses SDK hooks + composition
1672
+ *
1673
+ * This includes:
1674
+ * 1. Databases owned directly by the user
1675
+ * 2. Databases owned by organizations the user is a member of
1676
+ *
1677
+ * This hook fetches databases/tables/fields which change frequently.
1678
+ * For constraints/indexes (which change rarely), use useDatabaseConstraints.
1679
+ *
1680
+ * Split from the original mega-query to enable different caching strategies:
1681
+ * - Databases: 30s staleTime, respects cache on mount
1682
+ * - Constraints: 5min staleTime (see use-database-constraints.ts)
1683
+ */
1684
+ /**
1685
+ * Hook for fetching databases accessible to the current user
1686
+ *
1687
+ * This combines:
1688
+ * - User's personal databases (owned directly)
1689
+ * - Organization databases (owned by orgs the user belongs to)
1690
+ *
1691
+ * NOTE: This hook does NOT include constraints/indexes.
1692
+ * Use useDatabaseConstraints separately for those.
1693
+ *
1694
+ * @example
1695
+ * ```tsx
1696
+ * const { databases, isLoading } = useAccessibleDatabases();
1697
+ *
1698
+ * // Databases include both personal and org-owned databases
1699
+ * databases.forEach(db => {
1700
+ * console.log(db.name, db.owner?.displayName);
1701
+ * });
1702
+ * ```
1703
+ */
1704
+ function useAccessibleDatabases(options = {}) {
1705
+ const { enabled = true, context = "schema-builder" } = options;
1706
+ const { fetchApiSchemasQuery, fetchApisQuery, fetchDatabasesQuery, fetchFieldsQuery, fetchSchemasQuery, fetchTablesQuery } = useSchemaBuilderSdkClient();
1707
+ const { fetchUsersQuery } = useAuthSdkClient();
1708
+ const { databaseId, orgId, userId } = useSchemaBuilderConfig();
1709
+ const ownerIds = useMemo(() => [userId, orgId].filter((id) => Boolean(id)), [userId, orgId]);
1710
+ const { data, isFetched, isLoading: dbLoading, isFetching: dbFetching, error, refetch } = useQuery({
1711
+ queryKey: schemaBuilderQueryKey({
1712
+ orgId,
1713
+ databaseId,
1714
+ userId
1715
+ }, "core", "accessibleDatabases", {
1716
+ context,
1717
+ ownerIds
1718
+ }),
1719
+ queryFn: async () => {
1720
+ const databasesResult = await fetchDatabasesQuery({ selection: {
1721
+ fields: {
1722
+ id: true,
1723
+ name: true,
1724
+ label: true,
1725
+ ownerId: true
1726
+ },
1727
+ where: { ownerId: { in: ownerIds } },
1728
+ orderBy: ["CREATED_AT_ASC"]
1729
+ } });
1730
+ const rawDatabases = databasesResult.databases?.nodes ?? [];
1731
+ if (rawDatabases.length === 0) return { databases: {
1732
+ nodes: [],
1733
+ totalCount: 0,
1734
+ pageInfo: {
1735
+ hasNextPage: false,
1736
+ hasPreviousPage: false
1737
+ }
1738
+ } };
1739
+ const databaseIds = extractIds(rawDatabases);
1740
+ const uniqueOwnerIds = [...new Set(rawDatabases.map((d) => d.ownerId).filter((id) => !!id))];
1741
+ const [tablesResult, schemasResult, apisResult, ownersResult] = await Promise.all([
1742
+ fetchTablesQuery({ selection: {
1743
+ fields: {
1744
+ id: true,
1745
+ name: true,
1746
+ label: true,
1747
+ description: true,
1748
+ pluralName: true,
1749
+ singularName: true,
1750
+ smartTags: true,
1751
+ timestamps: true,
1752
+ databaseId: true,
1753
+ schemaId: true,
1754
+ category: true
1755
+ },
1756
+ where: { databaseId: { in: databaseIds } },
1757
+ orderBy: ["NAME_ASC"]
1758
+ } }),
1759
+ fetchSchemasQuery({ selection: {
1760
+ fields: {
1761
+ id: true,
1762
+ name: true,
1763
+ schemaName: true,
1764
+ databaseId: true
1765
+ },
1766
+ where: { databaseId: { in: databaseIds } },
1767
+ orderBy: ["NAME_ASC"]
1768
+ } }),
1769
+ fetchApisQuery({ selection: {
1770
+ fields: {
1771
+ id: true,
1772
+ name: true,
1773
+ databaseId: true
1774
+ },
1775
+ where: { databaseId: { in: databaseIds } },
1776
+ orderBy: ["NAME_ASC"]
1777
+ } }),
1778
+ uniqueOwnerIds.length > 0 ? fetchUsersQuery({ selection: {
1779
+ fields: {
1780
+ id: true,
1781
+ displayName: true,
1782
+ username: true,
1783
+ type: true
1784
+ },
1785
+ where: { id: { in: uniqueOwnerIds } }
1786
+ } }) : Promise.resolve({ users: { nodes: [] } })
1787
+ ]);
1788
+ const tableIds = extractIds(tablesResult.tables?.nodes ?? []);
1789
+ const apiIds = extractIds(apisResult.apis?.nodes ?? []);
1790
+ const [fieldsResult, apiSchemasResult] = await Promise.all([tableIds.length > 0 ? fetchFieldsQuery({ selection: {
1791
+ fields: {
1792
+ id: true,
1793
+ name: true,
1794
+ type: true,
1795
+ chk: true,
1796
+ chkExpr: true,
1797
+ defaultValue: true,
1798
+ description: true,
1799
+ fieldOrder: true,
1800
+ isRequired: true,
1801
+ label: true,
1802
+ max: true,
1803
+ min: true,
1804
+ regexp: true,
1805
+ smartTags: true,
1806
+ tableId: true
1807
+ },
1808
+ where: { tableId: { in: tableIds } }
1809
+ } }) : Promise.resolve({ fields: { nodes: [] } }), apiIds.length > 0 ? fetchApiSchemasQuery({ selection: {
1810
+ fields: {
1811
+ id: true,
1812
+ apiId: true,
1813
+ schemaId: true
1814
+ },
1815
+ where: { apiId: { in: apiIds } }
1816
+ } }) : Promise.resolve({ apiSchemas: { nodes: [] } })]);
1817
+ const ownerMap = /* @__PURE__ */ new Map();
1818
+ for (const u of ownersResult.users?.nodes ?? []) if (u.id) ownerMap.set(u.id, {
1819
+ id: u.id,
1820
+ displayName: u.displayName ?? null,
1821
+ username: u.username ?? null,
1822
+ type: u.type != null ? String(u.type) : null
1823
+ });
1824
+ const fieldsByTable = buildFieldsByTableMap(fieldsResult.fields?.nodes ?? []);
1825
+ const tablesByDatabase = buildTablesByDatabaseMap(tablesResult.tables?.nodes ?? [], fieldsByTable);
1826
+ const schemasByDatabase = /* @__PURE__ */ new Map();
1827
+ for (const s of schemasResult.schemas?.nodes ?? []) if (s.databaseId) {
1828
+ const existing = schemasByDatabase.get(s.databaseId) ?? [];
1829
+ existing.push({
1830
+ id: s.id ?? "",
1831
+ name: s.name ?? "",
1832
+ schemaName: s.schemaName ?? ""
1833
+ });
1834
+ schemasByDatabase.set(s.databaseId, existing);
1835
+ }
1836
+ const apiSchemasByApi = /* @__PURE__ */ new Map();
1837
+ for (const as of apiSchemasResult.apiSchemas?.nodes ?? []) if (as.apiId) {
1838
+ const existing = apiSchemasByApi.get(as.apiId) ?? [];
1839
+ existing.push({ schemaId: as.schemaId ?? "" });
1840
+ apiSchemasByApi.set(as.apiId, existing);
1841
+ }
1842
+ const apisByDatabase = /* @__PURE__ */ new Map();
1843
+ for (const a of apisResult.apis?.nodes ?? []) if (a.databaseId) {
1844
+ const existing = apisByDatabase.get(a.databaseId) ?? [];
1845
+ existing.push({
1846
+ id: a.id ?? "",
1847
+ name: a.name ?? "",
1848
+ apiSchemas: { nodes: apiSchemasByApi.get(a.id ?? "") ?? [] }
1849
+ });
1850
+ apisByDatabase.set(a.databaseId, existing);
1851
+ }
1852
+ return { databases: {
1853
+ nodes: rawDatabases.map((d) => {
1854
+ const tables = tablesByDatabase.get(d.id ?? "") ?? [];
1855
+ return {
1856
+ id: d.id ?? "",
1857
+ label: d.label ?? null,
1858
+ name: d.name ?? "",
1859
+ ownerId: d.ownerId ?? "",
1860
+ owner: d.ownerId ? ownerMap.get(d.ownerId) ?? null : null,
1861
+ tables: {
1862
+ edges: tables.map((t) => ({ node: t })),
1863
+ totalCount: tables.length
1864
+ },
1865
+ schemas: { nodes: schemasByDatabase.get(d.id ?? "") ?? [] },
1866
+ apis: { nodes: apisByDatabase.get(d.id ?? "") ?? [] }
1867
+ };
1868
+ }),
1869
+ totalCount: databasesResult.databases?.totalCount ?? 0,
1870
+ pageInfo: {
1871
+ hasNextPage: databasesResult.databases?.pageInfo?.hasNextPage ?? false,
1872
+ hasPreviousPage: databasesResult.databases?.pageInfo?.hasPreviousPage ?? false
1873
+ }
1874
+ } };
1875
+ },
1876
+ enabled: enabled && ownerIds.length > 0,
1877
+ staleTime: 30 * 1e3,
1878
+ refetchOnMount: true,
1879
+ placeholderData: keepPreviousData
1880
+ });
1881
+ const databases = data?.databases?.nodes ?? [];
1882
+ const totalCount = data?.databases?.totalCount ?? 0;
1883
+ const pageInfo = data?.databases?.pageInfo ?? {
1884
+ hasNextPage: false,
1885
+ hasPreviousPage: false
1886
+ };
1887
+ const isLoading = dbLoading;
1888
+ const isFetching = dbFetching;
1889
+ return {
1890
+ databases,
1891
+ totalCount,
1892
+ hasResolved: enabled && (ownerIds.length === 0 || isFetched || data !== void 0 || error != null),
1893
+ isLoading,
1894
+ isFetching,
1895
+ error,
1896
+ pageInfo,
1897
+ refetch
1898
+ };
1899
+ }
1900
+ /**
1901
+ * Generate query keys for consistent cache management
1902
+ */
1903
+ const accessibleDatabasesQueryKeys = {
1904
+ all: ["accessible-databases"],
1905
+ byContext: (context) => [...accessibleDatabasesQueryKeys.all, { context }],
1906
+ byOwners: (context, ownerIds) => [...accessibleDatabasesQueryKeys.byContext(context), { ownerIds: [...ownerIds].sort() }]
1907
+ };
1908
+
1909
+ //#endregion
1910
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/parse-list-field.ts
1911
+ /**
1912
+ * Parse list-like scalar values emitted by schema-builder ORM fields.
1913
+ *
1914
+ * Codegen v4 ORM types expose list columns (e.g. uuid[]) as `string | null`.
1915
+ * At runtime this value may be:
1916
+ * - a real array (already parsed)
1917
+ * - JSON array string: ["a","b"]
1918
+ * - PostgreSQL array literal: {a,b} or {"a","b"}
1919
+ * - single scalar string: a
1920
+ */
1921
+ function parseListField(value) {
1922
+ if (value == null) return [];
1923
+ if (Array.isArray(value)) return value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
1924
+ if (typeof value !== "string") return [];
1925
+ const input = value.trim();
1926
+ if (!input) return [];
1927
+ if (input.startsWith("[") && input.endsWith("]")) try {
1928
+ const parsed = JSON.parse(input);
1929
+ if (Array.isArray(parsed)) return parsed.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
1930
+ } catch {}
1931
+ if (input.startsWith("{") && input.endsWith("}")) {
1932
+ const inner = input.slice(1, -1).trim();
1933
+ if (!inner) return [];
1934
+ return splitPgArrayLiteral(inner).map(stripPgArrayItemQuotes).map((item) => item.trim()).filter((item) => item.length > 0 && item.toUpperCase() !== "NULL");
1935
+ }
1936
+ return [input];
1937
+ }
1938
+ function splitPgArrayLiteral(input) {
1939
+ const items = [];
1940
+ let current = "";
1941
+ let inQuotes = false;
1942
+ let escaped = false;
1943
+ for (let i = 0; i < input.length; i += 1) {
1944
+ const char = input[i];
1945
+ if (escaped) {
1946
+ current += char;
1947
+ escaped = false;
1948
+ continue;
1949
+ }
1950
+ if (char === "\\") {
1951
+ escaped = true;
1952
+ continue;
1953
+ }
1954
+ if (char === "\"") {
1955
+ inQuotes = !inQuotes;
1956
+ current += char;
1957
+ continue;
1958
+ }
1959
+ if (char === "," && !inQuotes) {
1960
+ items.push(current);
1961
+ current = "";
1962
+ continue;
1963
+ }
1964
+ current += char;
1965
+ }
1966
+ items.push(current);
1967
+ return items;
1968
+ }
1969
+ function stripPgArrayItemQuotes(item) {
1970
+ if (item.startsWith("\"") && item.endsWith("\"") && item.length >= 2) return item.slice(1, -1).replace(/\\"/g, "\"");
1971
+ return item;
1972
+ }
1973
+
1974
+ //#endregion
1975
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-database-constraints.ts
1976
+ /**
1977
+ * Hook for fetching database constraints and indexes
1978
+ * Tier 4 wrapper: Uses SDK hooks + cache invalidation
1979
+ *
1980
+ * This includes:
1981
+ * - Primary key constraints
1982
+ * - Unique constraints
1983
+ * - Foreign key constraints
1984
+ * - Indexes
1985
+ *
1986
+ * These are fetched globally (no databaseId filter) because:
1987
+ * - tableId is globally unique across all databases
1988
+ * - During transformation, constraints are mapped by tableId to correct tables
1989
+ * - See transformUserDatabases() in transformers.ts
1990
+ *
1991
+ * Split from the original mega-query to enable different caching strategies:
1992
+ * - Constraints: 5min staleTime (changes rarely)
1993
+ * - Databases: 30s staleTime (see use-accessible-databases.ts)
1994
+ */
1995
+ /**
1996
+ * Hook for fetching database constraints and indexes
1997
+ *
1998
+ * This fetches constraints/indexes which change rarely (5min staleTime).
1999
+ * For databases/tables/fields (which change more often), use useAccessibleDatabases.
2000
+ *
2001
+ * @example
2002
+ * ```tsx
2003
+ * const {
2004
+ * primaryKeyConstraints,
2005
+ * foreignKeyConstraints,
2006
+ * indexes,
2007
+ * isLoading
2008
+ * } = useDatabaseConstraints();
2009
+ *
2010
+ * // Constraints are mapped by tableId in the transformer
2011
+ * foreignKeyConstraints.forEach(fk => {
2012
+ * console.log(fk.name, fk.tableId, '->', fk.refTableId);
2013
+ * });
2014
+ * ```
2015
+ */
2016
+ function useDatabaseConstraints(options = {}) {
2017
+ const { enabled = true, context = "schema-builder" } = options;
2018
+ const { scope } = useSchemaBuilderRuntime();
2019
+ const { fetchForeignKeyConstraintsQuery, fetchIndicesQuery, fetchPrimaryKeyConstraintsQuery, fetchUniqueConstraintsQuery } = useSchemaBuilderSdkClient();
2020
+ const { data, isLoading, isFetching, error, refetch } = useQuery({
2021
+ queryKey: schemaBuilderQueryKey(scope, "core", "databaseConstraints", { context }),
2022
+ queryFn: async () => {
2023
+ const [pkResult, uqResult, fkResult, idxResult] = await Promise.all([
2024
+ fetchPrimaryKeyConstraintsQuery({ selection: { fields: {
2025
+ id: true,
2026
+ databaseId: true,
2027
+ tableId: true,
2028
+ name: true,
2029
+ type: true,
2030
+ fieldIds: true
2031
+ } } }),
2032
+ fetchUniqueConstraintsQuery({ selection: { fields: {
2033
+ id: true,
2034
+ databaseId: true,
2035
+ tableId: true,
2036
+ name: true,
2037
+ type: true,
2038
+ fieldIds: true
2039
+ } } }),
2040
+ fetchForeignKeyConstraintsQuery({ selection: {
2041
+ fields: {
2042
+ id: true,
2043
+ databaseId: true,
2044
+ tableId: true,
2045
+ name: true,
2046
+ type: true,
2047
+ fieldIds: true,
2048
+ refFieldIds: true,
2049
+ refTableId: true,
2050
+ deleteAction: true,
2051
+ updateAction: true,
2052
+ description: true,
2053
+ smartTags: true,
2054
+ createdAt: true
2055
+ },
2056
+ orderBy: ["CREATED_AT_DESC"]
2057
+ } }),
2058
+ fetchIndicesQuery({ selection: {
2059
+ fields: {
2060
+ id: true,
2061
+ databaseId: true,
2062
+ tableId: true,
2063
+ name: true,
2064
+ fieldIds: true,
2065
+ includeFieldIds: true,
2066
+ accessMethod: true,
2067
+ indexParams: true,
2068
+ whereClause: true,
2069
+ isUnique: true,
2070
+ createdAt: true
2071
+ },
2072
+ orderBy: ["CREATED_AT_DESC"]
2073
+ } })
2074
+ ]);
2075
+ return {
2076
+ primaryKeyConstraints: (pkResult.primaryKeyConstraints?.nodes ?? []).map((node) => ({
2077
+ databaseId: node.databaseId ?? "",
2078
+ fieldIds: parseListField(node.fieldIds),
2079
+ id: node.id ?? "",
2080
+ name: node.name ?? "",
2081
+ tableId: node.tableId ?? "",
2082
+ type: node.type ?? ""
2083
+ })),
2084
+ uniqueConstraints: (uqResult.uniqueConstraints?.nodes ?? []).map((node) => ({
2085
+ databaseId: node.databaseId ?? "",
2086
+ fieldIds: parseListField(node.fieldIds),
2087
+ id: node.id ?? "",
2088
+ name: node.name ?? "",
2089
+ tableId: node.tableId ?? "",
2090
+ type: node.type ?? ""
2091
+ })),
2092
+ foreignKeyConstraints: (fkResult.foreignKeyConstraints?.nodes ?? []).map((node) => ({
2093
+ createdAt: node.createdAt ?? null,
2094
+ databaseId: node.databaseId ?? "",
2095
+ deleteAction: node.deleteAction ?? null,
2096
+ description: node.description ?? null,
2097
+ fieldIds: parseListField(node.fieldIds),
2098
+ id: node.id ?? "",
2099
+ name: node.name ?? "",
2100
+ refFieldIds: parseListField(node.refFieldIds),
2101
+ refTableId: node.refTableId ?? "",
2102
+ smartTags: node.smartTags ?? null,
2103
+ tableId: node.tableId ?? "",
2104
+ type: node.type ?? "",
2105
+ updateAction: node.updateAction ?? null
2106
+ })),
2107
+ indexes: (idxResult.indices?.nodes ?? []).map((node) => ({
2108
+ accessMethod: node.accessMethod ?? null,
2109
+ createdAt: node.createdAt ?? null,
2110
+ databaseId: node.databaseId ?? "",
2111
+ fieldIds: parseListField(node.fieldIds),
2112
+ id: node.id ?? "",
2113
+ includeFieldIds: parseListField(node.includeFieldIds) ?? null,
2114
+ indexParams: typeof node.indexParams === "string" ? node.indexParams : null,
2115
+ isUnique: node.isUnique ?? null,
2116
+ name: node.name ?? "",
2117
+ tableId: node.tableId ?? "",
2118
+ whereClause: typeof node.whereClause === "string" ? node.whereClause : null
2119
+ }))
2120
+ };
2121
+ },
2122
+ enabled,
2123
+ staleTime: 300 * 1e3,
2124
+ refetchOnMount: true,
2125
+ placeholderData: keepPreviousData
2126
+ });
2127
+ return {
2128
+ primaryKeyConstraints: data?.primaryKeyConstraints ?? [],
2129
+ uniqueConstraints: data?.uniqueConstraints ?? [],
2130
+ foreignKeyConstraints: data?.foreignKeyConstraints ?? [],
2131
+ indexes: data?.indexes ?? [],
2132
+ isLoading,
2133
+ isFetching,
2134
+ error,
2135
+ refetch
2136
+ };
2137
+ }
2138
+ /**
2139
+ * Generate query keys for consistent cache management
2140
+ */
2141
+ const databaseConstraintsQueryKeys = {
2142
+ all: ["database-constraints"],
2143
+ byContext: (context) => [...databaseConstraintsQueryKeys.all, { context }]
2144
+ };
2145
+
2146
+ //#endregion
2147
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-schema-builder-selectors.ts
2148
+ /**
2149
+ * Schema Builder Selectors Hook
2150
+ *
2151
+ * This hook provides derived state by combining:
2152
+ * 1. React Query data from SchemaBuilderDataProvider
2153
+ * 2. Zustand selection state (selectedSchemaKey, selectedTableId, etc.)
2154
+ *
2155
+ * All derived values are computed via useMemo - nothing is stored redundantly.
2156
+ * This eliminates the sync layer that caused race conditions.
2157
+ */
2158
+ const { createContext: createContext$1, useContextSelector } = FluentContextSelector.default ?? FluentContextSelector;
2159
+ const EMPTY_SCHEMAS = [];
2160
+ const NOOP_SELECT_ORG = (_orgId) => void 0;
2161
+ const NOOP_SELECT_SCHEMA = (_schemaKey) => void 0;
2162
+ const NOOP_SET_ACTIVE_TAB = (_tab) => void 0;
2163
+ const IS_CUSTOM_SCHEMA = (schemaKey) => schemaKey.startsWith("custom-");
2164
+ const SchemaBuilderDataContext = createContext$1(null);
2165
+ function SchemaBuilderDataProvider({ children }) {
2166
+ const { databaseId, orgId } = useSchemaBuilderConfig();
2167
+ const shouldLoadFullSchemaData = Boolean(databaseId);
2168
+ const { databases, hasResolved: hasResolvedAccessibleDatabases, isLoading: dbLoading, isFetching: dbFetching, error: dbError, refetch: refetchDatabases } = useAccessibleDatabases({ enabled: shouldLoadFullSchemaData });
2169
+ const { primaryKeyConstraints, uniqueConstraints, foreignKeyConstraints, indexes, isLoading: constraintsLoading, isFetching: constraintsFetching, error: constraintsError } = useDatabaseConstraints({ enabled: shouldLoadFullSchemaData });
2170
+ const remoteSchemas = useMemo(() => {
2171
+ if (!shouldLoadFullSchemaData) return EMPTY_SCHEMAS;
2172
+ return transformUserDatabases(databases, primaryKeyConstraints, uniqueConstraints, foreignKeyConstraints, indexes).map((entry) => ({
2173
+ key: entry.key,
2174
+ name: entry.dbSchema.name,
2175
+ description: entry.description ?? entry.dbSchema.description ?? "",
2176
+ category: entry.category ?? "Database",
2177
+ nodeCount: entry.dbSchema.tables.length,
2178
+ edgeCount: entry.dbSchema.relationships?.length ?? 0,
2179
+ source: "database",
2180
+ schema: dbLightToSchemaData(entry.dbSchema),
2181
+ dbSchema: entry.dbSchema,
2182
+ checksum: entry.checksum,
2183
+ databaseInfo: entry.databaseInfo
2184
+ }));
2185
+ }, [
2186
+ databases,
2187
+ foreignKeyConstraints,
2188
+ indexes,
2189
+ primaryKeyConstraints,
2190
+ shouldLoadFullSchemaData,
2191
+ uniqueConstraints
2192
+ ]);
2193
+ const storeSelectedTableId = useSchemaBuilderRuntimeStore((state) => state.selectedTableId);
2194
+ const { selectTable: storeSelectTable } = useSchemaBuilderRuntime();
2195
+ const resolvedAvailableSchemas = shouldLoadFullSchemaData ? remoteSchemas : EMPTY_SCHEMAS;
2196
+ const hasResolvedDatabaseLookup = !databaseId ? true : hasResolvedAccessibleDatabases;
2197
+ const isLoading = shouldLoadFullSchemaData ? !hasResolvedAccessibleDatabases || dbLoading || constraintsLoading : false;
2198
+ const isFetching = shouldLoadFullSchemaData ? dbFetching || constraintsFetching : false;
2199
+ const error = shouldLoadFullSchemaData ? dbError || constraintsError : null;
2200
+ const selectedSchemaKey = useMemo(() => {
2201
+ if (!databaseId) return "";
2202
+ return resolvedAvailableSchemas.find((schema) => schema.databaseInfo?.id === databaseId)?.key ?? "";
2203
+ }, [resolvedAvailableSchemas, databaseId]);
2204
+ const currentSchemaInfo = useMemo(() => resolvedAvailableSchemas.find((schema) => schema.key === selectedSchemaKey) ?? null, [resolvedAvailableSchemas, selectedSchemaKey]);
2205
+ const currentSchema = currentSchemaInfo?.dbSchema ?? null;
2206
+ const selectedTableId = storeSelectedTableId;
2207
+ const currentTable = useMemo(() => currentSchema?.tables.find((table) => table.id === selectedTableId) ?? null, [currentSchema, selectedTableId]);
2208
+ const selectTable = useCallback((tableId, tableName) => {
2209
+ storeSelectTable(tableId, tableName);
2210
+ }, [storeSelectTable]);
2211
+ const refetch = useCallback(async () => {
2212
+ if (shouldLoadFullSchemaData) await refetchDatabases();
2213
+ }, [refetchDatabases, shouldLoadFullSchemaData]);
2214
+ const value = useMemo(() => ({
2215
+ availableSchemas: resolvedAvailableSchemas,
2216
+ routeOrgId: orgId,
2217
+ routeDatabaseId: databaseId,
2218
+ selectedSchemaKey,
2219
+ currentSchemaInfo,
2220
+ currentSchema,
2221
+ currentTable,
2222
+ selectedTableId,
2223
+ hasResolvedDatabaseLookup,
2224
+ isLoading,
2225
+ isFetching,
2226
+ error,
2227
+ refetch,
2228
+ selectTable
2229
+ }), [
2230
+ resolvedAvailableSchemas,
2231
+ orgId,
2232
+ databaseId,
2233
+ selectedSchemaKey,
2234
+ currentSchemaInfo,
2235
+ currentSchema,
2236
+ currentTable,
2237
+ selectedTableId,
2238
+ hasResolvedDatabaseLookup,
2239
+ isLoading,
2240
+ isFetching,
2241
+ error,
2242
+ refetch,
2243
+ selectTable
2244
+ ]);
2245
+ return createElement(SchemaBuilderDataContext.Provider, { value }, children);
2246
+ }
2247
+ function useSchemaBuilderDataSelector(selector) {
2248
+ return useContextSelector(SchemaBuilderDataContext, (state) => {
2249
+ if (!state) throw new Error("SchemaBuilderDataProvider is missing");
2250
+ return selector(state);
2251
+ });
2252
+ }
2253
+ function useSchemaBuilderSelectors() {
2254
+ const { scope, store, selectField: selectFieldFromContext, selectTable: selectTableFromContext } = useSchemaBuilderRuntime();
2255
+ const selectedFieldId = useSchemaBuilderRuntimeStore((state) => state.selectedFieldId);
2256
+ const currentDatabaseApi = useSchemaBuilderRuntimeStore((state) => state.currentDatabaseApi);
2257
+ const selectedOrgId = scope.orgId;
2258
+ const activeTab = "schemas";
2259
+ const customSchemas = EMPTY_SCHEMAS;
2260
+ const selectOrg = NOOP_SELECT_ORG;
2261
+ const selectSchema = NOOP_SELECT_SCHEMA;
2262
+ const selectField = useCallback((fieldId) => selectFieldFromContext(fieldId), [selectFieldFromContext]);
2263
+ const clearAllSelections = useCallback(() => {
2264
+ selectTableFromContext(null);
2265
+ selectFieldFromContext(null);
2266
+ }, [selectTableFromContext, selectFieldFromContext]);
2267
+ const setActiveTab = NOOP_SET_ACTIVE_TAB;
2268
+ const setCurrentDatabaseApi = useCallback((api) => store.getState().setCurrentDatabaseApi(api), [store]);
2269
+ const availableSchemas = useSchemaBuilderDataSelector((state) => state.availableSchemas);
2270
+ const selectedSchemaKey = useSchemaBuilderDataSelector((state) => state.selectedSchemaKey);
2271
+ const currentSchemaInfo = useSchemaBuilderDataSelector((state) => state.currentSchemaInfo);
2272
+ const currentSchema = useSchemaBuilderDataSelector((state) => state.currentSchema);
2273
+ const currentTable = useSchemaBuilderDataSelector((state) => state.currentTable);
2274
+ const selectedTableId = useSchemaBuilderDataSelector((state) => state.selectedTableId);
2275
+ const isLoading = useSchemaBuilderDataSelector((state) => state.isLoading);
2276
+ const isFetching = useSchemaBuilderDataSelector((state) => state.isFetching);
2277
+ const error = useSchemaBuilderDataSelector((state) => state.error);
2278
+ const refetch = useSchemaBuilderDataSelector((state) => state.refetch);
2279
+ const selectTableFromProvider = useSchemaBuilderDataSelector((state) => state.selectTable);
2280
+ const currentField = useMemo(() => currentTable?.fields.find((f) => f.id === selectedFieldId) ?? null, [currentTable, selectedFieldId]);
2281
+ const currentDatabase = useMemo(() => {
2282
+ if (!currentSchemaInfo?.databaseInfo) return null;
2283
+ return {
2284
+ schemaKey: selectedSchemaKey,
2285
+ databaseId: currentSchemaInfo.databaseInfo.id,
2286
+ name: currentSchemaInfo.databaseInfo.name,
2287
+ label: currentSchemaInfo.databaseInfo.label ?? null,
2288
+ schemaId: currentSchemaInfo.databaseInfo.schemaId ?? null
2289
+ };
2290
+ }, [currentSchemaInfo, selectedSchemaKey]);
2291
+ const isCustomSchema = IS_CUSTOM_SCHEMA;
2292
+ const getSchemaByKey = useCallback((key) => availableSchemas.find((schema) => schema.key === key) ?? null, [availableSchemas]);
2293
+ return {
2294
+ selectedOrgId,
2295
+ selectedSchemaKey,
2296
+ selectedTableId,
2297
+ selectedFieldId,
2298
+ activeTab,
2299
+ selectOrg,
2300
+ selectSchema,
2301
+ selectTable: useCallback((tableId, tableName) => {
2302
+ selectTableFromProvider(tableId, tableName);
2303
+ selectField(null);
2304
+ }, [selectTableFromProvider, selectField]),
2305
+ selectField,
2306
+ clearAllSelections,
2307
+ setActiveTab,
2308
+ availableSchemas,
2309
+ currentSchema,
2310
+ currentTable,
2311
+ currentField,
2312
+ currentDatabase,
2313
+ currentDatabaseApi,
2314
+ setCurrentDatabaseApi,
2315
+ isCustomSchema,
2316
+ getSchemaByKey,
2317
+ isLoading,
2318
+ isFetching,
2319
+ error,
2320
+ refetch,
2321
+ customSchemas
2322
+ };
2323
+ }
2324
+
2325
+ //#endregion
2326
+ //#region src/schema/schema-builder-core/lib/data/mutation-input.ts
2327
+ /**
2328
+ * Converts null, undefined, and empty strings to undefined.
2329
+ * Unlike `value || undefined`, this preserves `false`, `0`, and `[]`.
2330
+ */
2331
+ function stripEmpty(value) {
2332
+ if (value === null || value === void 0 || value === "") return void 0;
2333
+ return value;
2334
+ }
2335
+ /**
2336
+ * Casts a string array for array columns (e.g. `fieldIds`, `refFieldIds`).
2337
+ * Codegen types create inputs as `string[]` but patch inputs as `string` — runtime accepts both.
2338
+ */
2339
+ const asFieldIds = (ids) => ids;
2340
+
2341
+ //#endregion
2342
+ //#region src/schema/schema-builder-core/lib/gql/hooks/dashboard/dashboard-query-keys.ts
2343
+ function isDashboardCacheScopeKey(value) {
2344
+ if (!value || typeof value !== "object") return false;
2345
+ const candidate = value;
2346
+ return "databaseId" in candidate && "endpoint" in candidate;
2347
+ }
2348
+
2349
+ //#endregion
2350
+ //#region src/compat/modules-sdk.ts
2351
+ function useModuleMutation(operation, options) {
2352
+ const { adapter, scope, onInvalidate } = useSchemaBuilder();
2353
+ const feature = operation === "createRelationProvision" ? "relationships" : "policies";
2354
+ const operationFn = adapter[feature][operation];
2355
+ const selection = options?.selection?.fields;
2356
+ return useMutation({
2357
+ mutationFn: (variables) => operationFn(variables, {
2358
+ scope,
2359
+ selection
2360
+ }),
2361
+ onSuccess: () => onInvalidate?.({
2362
+ scope,
2363
+ feature,
2364
+ operation
2365
+ })
2366
+ });
2367
+ }
2368
+ const useCreateRelationProvisionMutation = (options) => useModuleMutation("createRelationProvision", options);
2369
+ const useCreateSecureTableProvisionMutation = (options) => useModuleMutation("createSecureTableProvision", options);
2370
+ const blueprintTemplateKeys = { all: ["schema-builder", "blueprint-templates"] };
2371
+
2372
+ //#endregion
2373
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/policies/use-database-policies.ts
2374
+ /**
2375
+ * Hook for fetching database policies
2376
+ * Tier 4 wrapper: Uses SDK hooks + composition
2377
+ */
2378
+ const BACKEND_MANAGED_POLICY_TYPES = /* @__PURE__ */ new Set(["AuthzNotReadOnly"]);
2379
+ const databasePoliciesQueryKeys = {
2380
+ all: ["database-policies"],
2381
+ byDatabase: (databaseId) => ["database-policies", databaseId]
2382
+ };
2383
+ function useDatabasePolicies(databaseId, options = {}) {
2384
+ const isEnabled = options.enabled !== false && Boolean(databaseId);
2385
+ const { scope } = useSchemaBuilderRuntime();
2386
+ const { fetchFieldsQuery, fetchPoliciesQuery, fetchSchemasQuery, fetchTablesQuery } = useSchemaBuilderSdkClient();
2387
+ return useQuery({
2388
+ queryKey: schemaBuilderQueryKey(scope, "core", "databasePolicies", { databaseId }),
2389
+ queryFn: async () => {
2390
+ const tables = (await fetchTablesQuery({ selection: {
2391
+ fields: {
2392
+ id: true,
2393
+ name: true,
2394
+ useRls: true,
2395
+ category: true,
2396
+ schemaId: true
2397
+ },
2398
+ where: { databaseId: { equalTo: databaseId } },
2399
+ orderBy: ["NAME_ASC"]
2400
+ } })).tables?.nodes ?? [];
2401
+ if (tables.length === 0) return [];
2402
+ const tableIds = tables.map((t) => t.id).filter((id) => !!id);
2403
+ const schemaIds = [...new Set(tables.map((t) => t.schemaId).filter((id) => !!id))];
2404
+ const [schemasResult, fieldsResult, policiesResult] = await Promise.all([
2405
+ schemaIds.length > 0 ? fetchSchemasQuery({ selection: {
2406
+ fields: {
2407
+ id: true,
2408
+ schemaName: true
2409
+ },
2410
+ where: { id: { in: schemaIds } }
2411
+ } }) : Promise.resolve({ schemas: { nodes: [] } }),
2412
+ tableIds.length > 0 ? fetchFieldsQuery({ selection: {
2413
+ fields: {
2414
+ id: true,
2415
+ name: true,
2416
+ type: true,
2417
+ fieldOrder: true,
2418
+ smartTags: true,
2419
+ tableId: true
2420
+ },
2421
+ where: { tableId: { in: tableIds } }
2422
+ } }) : Promise.resolve({ fields: { nodes: [] } }),
2423
+ tableIds.length > 0 ? fetchPoliciesQuery({ selection: {
2424
+ fields: {
2425
+ id: true,
2426
+ name: true,
2427
+ granteeName: true,
2428
+ privilege: true,
2429
+ permissive: true,
2430
+ disabled: true,
2431
+ policyType: true,
2432
+ data: true,
2433
+ createdAt: true,
2434
+ updatedAt: true,
2435
+ tableId: true
2436
+ },
2437
+ where: { tableId: { in: tableIds } },
2438
+ orderBy: ["CREATED_AT_DESC"]
2439
+ } }) : Promise.resolve({ policies: { nodes: [] } })
2440
+ ]);
2441
+ const schemaMap = /* @__PURE__ */ new Map();
2442
+ for (const schema of schemasResult.schemas?.nodes ?? []) if (schema.id) schemaMap.set(schema.id, {
2443
+ id: schema.id,
2444
+ schemaName: schema.schemaName ?? ""
2445
+ });
2446
+ const fieldsByTable = /* @__PURE__ */ new Map();
2447
+ for (const field of fieldsResult.fields?.nodes ?? []) if (field.tableId) {
2448
+ const existing = fieldsByTable.get(field.tableId) ?? [];
2449
+ existing.push({
2450
+ id: field.id ?? "",
2451
+ name: field.name ?? "",
2452
+ type: fieldTypeToTypeName(field.type),
2453
+ fieldOrder: field.fieldOrder ?? null,
2454
+ smartTags: field.smartTags ?? null
2455
+ });
2456
+ fieldsByTable.set(field.tableId, existing);
2457
+ }
2458
+ const policiesByTable = /* @__PURE__ */ new Map();
2459
+ for (const policy of policiesResult.policies?.nodes ?? []) {
2460
+ if (!policy.tableId) continue;
2461
+ if (policy.policyType && BACKEND_MANAGED_POLICY_TYPES.has(policy.policyType)) continue;
2462
+ const existing = policiesByTable.get(policy.tableId) ?? [];
2463
+ existing.push({
2464
+ id: policy.id ?? "",
2465
+ name: policy.name ?? null,
2466
+ granteeName: policy.granteeName ?? null,
2467
+ privilege: policy.privilege ?? null,
2468
+ permissive: policy.permissive ?? null,
2469
+ disabled: policy.disabled ?? null,
2470
+ policyType: policy.policyType ?? null,
2471
+ data: policy.data ?? null,
2472
+ createdAt: policy.createdAt ?? null,
2473
+ updatedAt: policy.updatedAt ?? null
2474
+ });
2475
+ policiesByTable.set(policy.tableId, existing);
2476
+ }
2477
+ return tables.map((table) => ({
2478
+ id: table.id ?? "",
2479
+ name: table.name ?? "",
2480
+ useRls: table.useRls ?? false,
2481
+ policies: policiesByTable.get(table.id ?? "") ?? [],
2482
+ fields: fieldsByTable.get(table.id ?? "") ?? [],
2483
+ schema: table.schemaId ? schemaMap.get(table.schemaId) ?? null : null,
2484
+ category: table.category ?? null
2485
+ }));
2486
+ },
2487
+ enabled: isEnabled,
2488
+ staleTime: 300 * 1e3,
2489
+ refetchOnMount: isEnabled,
2490
+ refetchOnWindowFocus: false,
2491
+ refetchOnReconnect: false
2492
+ });
2493
+ }
2494
+
2495
+ //#endregion
2496
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-database-tables.ts
2497
+ /**
2498
+ * Query keys for cache management
2499
+ */
2500
+ const databaseTablesQueryKeys = {
2501
+ all: ["database-tables"],
2502
+ byDatabase: (databaseId) => [...databaseTablesQueryKeys.all, { databaseId }],
2503
+ byDatabaseWithOptions: (databaseId, options) => [...databaseTablesQueryKeys.byDatabase(databaseId), options]
2504
+ };
2505
+
2506
+ //#endregion
2507
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-user-databases.ts
2508
+ /**
2509
+ * Generate query keys for consistent cache management
2510
+ */
2511
+ const userDatabasesQueryKeys = {
2512
+ all: ["user-databases"],
2513
+ byContext: (context) => [...userDatabasesQueryKeys.all, { context }],
2514
+ byUser: (context, userId) => [...userDatabasesQueryKeys.byContext(context), { ownerId: userId }]
2515
+ };
2516
+
2517
+ //#endregion
2518
+ //#region src/schema/schema-builder-core/lib/gql/hooks/schema-builder/modules/invalidate-database-entities.ts
2519
+ const invalidateQueryKey = (queryClient, queryKey) => queryClient.invalidateQueries({ queryKey });
2520
+ function invalidateDashboardQueries(queryClient, databaseId) {
2521
+ const matchesDashboard = (queryKey) => {
2522
+ const [root, scope] = queryKey;
2523
+ if (root !== "sheets") return false;
2524
+ if (!databaseId) return true;
2525
+ return isDashboardCacheScopeKey(scope) && scope.databaseId === databaseId;
2526
+ };
2527
+ queryClient.removeQueries({ predicate: (query) => {
2528
+ if (!matchesDashboard(query.queryKey)) return false;
2529
+ const type = query.queryKey[2];
2530
+ return type === "meta" || type === "relations";
2531
+ } });
2532
+ return queryClient.invalidateQueries({ predicate: (query) => matchesDashboard(query.queryKey) });
2533
+ }
2534
+ async function invalidateDatabaseEntities(queryClient, databaseId) {
2535
+ const tasks = [];
2536
+ tasks.push(invalidateQueryKey(queryClient, ["@constructive-io/schema-builder"]));
2537
+ if (databaseId) {
2538
+ tasks.push(invalidateQueryKey(queryClient, databaseTablesQueryKeys.byDatabase(databaseId)));
2539
+ tasks.push(invalidateQueryKey(queryClient, databasePoliciesQueryKeys.byDatabase(databaseId)));
2540
+ tasks.push(invalidateQueryKey(queryClient, domainKeys.lists()));
2541
+ tasks.push(invalidateQueryKey(queryClient, ["database-table"]));
2542
+ }
2543
+ tasks.push(invalidateDashboardQueries(queryClient, databaseId));
2544
+ tasks.push(invalidateQueryKey(queryClient, userDatabasesQueryKeys.all));
2545
+ tasks.push(invalidateQueryKey(queryClient, accessibleDatabasesQueryKeys.all));
2546
+ tasks.push(invalidateQueryKey(queryClient, databaseConstraintsQueryKeys.all));
2547
+ tasks.push(invalidateQueryKey(queryClient, apiKeys.all));
2548
+ tasks.push(invalidateQueryKey(queryClient, schemaKeys.all));
2549
+ tasks.push(invalidateQueryKey(queryClient, siteKeys.all));
2550
+ tasks.push(invalidateQueryKey(queryClient, blueprintTemplateKeys.all));
2551
+ tasks.push(invalidateQueryKey(queryClient, databaseTablesQueryKeys.all));
2552
+ tasks.push(invalidateQueryKey(queryClient, databasePoliciesQueryKeys.all));
2553
+ tasks.push(invalidateQueryKey(queryClient, domainKeys.all));
2554
+ await Promise.allSettled(tasks);
2555
+ }
2556
+
2557
+ //#endregion
2558
+ export { useDeleteUniqueConstraintMutation as A, getAllFieldTypes as B, useCreateUniqueConstraintMutation as C, useDeletePolicyMutation as D, useDeleteIndexMutation as E, useUpdatePolicyMutation as F, ForeignKeyActionLabels as G, getDefaultConstraintsForType as H, useUpdatePrimaryKeyConstraintMutation as I, RelationshipTypes as J, ForeignKeyActions as K, useUpdateTableMutation as L, useUpdateFieldMutation as M, useUpdateForeignKeyConstraintMutation as N, useDeletePrimaryKeyConstraintMutation as O, useUpdateIndexMutation as P, FIELD_TYPE_CATEGORIES as R, useCreateTableMutation as S, useDeleteForeignKeyConstraintMutation as T, getFieldTypeInfo as U, getBasicFieldTypes as V, searchFieldTypes as W, cn as Y, useCreateFieldMutation as _, useCreateSecureTableProvisionMutation as a, useCreatePrimaryKeyConstraintMutation as b, SchemaBuilderDataProvider as c, toFieldDefault as d, toFieldType as f, useSchemaBuilderRuntimeStore as g, useSchemaBuilderRuntime as h, useCreateRelationProvisionMutation as i, useSchemaBuilderSdkClient as j, useDeleteTableMutation as k, useSchemaBuilderSelectors as l, mapConstraintsToFieldPatch as m, databasePoliciesQueryKeys as n, asFieldIds as o, cellTypeToBackendType as p, INDEX_TYPE_LABELS as q, useDatabasePolicies as r, stripEmpty as s, invalidateDatabaseEntities as t, fieldTypeToTypeName as u, useCreateForeignKeyConstraintMutation as v, useDeleteFieldMutation as w, useCreateTableGrantMutation as x, useCreateIndexMutation as y, getAdvancedFieldTypes as z };
2559
+ //# sourceMappingURL=invalidate-database-entities-CmmOT3S0.js.map