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