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