-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatabase-designer.js
289 lines (268 loc) · 8.33 KB
/
database-designer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
const Field = require("@saltcorn/data/models/field");
const Table = require("@saltcorn/data/models/table");
const Form = require("@saltcorn/data/models/form");
const View = require("@saltcorn/data/models/view");
const Trigger = require("@saltcorn/data/models/trigger");
const { findType } = require("@saltcorn/data/models/discovery");
const { save_menu_items } = require("@saltcorn/data/models/config");
const db = require("@saltcorn/data/db");
const Workflow = require("@saltcorn/data/models/workflow");
const { renderForm } = require("@saltcorn/markup");
const { div, script, domReady, pre, code } = require("@saltcorn/markup/tags");
const { getState } = require("@saltcorn/data/db/state");
const {
getCompletion,
getPromptFromTemplate,
incompleteCfgMsg,
} = require("./common");
const { Parser } = require("node-sql-parser");
const parser = new Parser();
const { initial_config_all_fields } = require("@saltcorn/data/plugin-helper");
const get_state_fields = () => [];
const getForm = async ({ viewname, body, hasCode }) => {
const fields = [
{
name: "prompt",
label: "Database description",
fieldview: "textarea",
sublabel: "What would you like to design a database for?",
type: "String",
},
...(hasCode
? [
{
name: "code",
label: "Generated code",
fieldview: "textarea",
attributes: { mode: "application/javascript" },
input_type: "code",
},
{
name: "basic_views",
label: "Generate views",
sublabel:
"Also generate basic views (Show, Edit, List) for the generated tables",
type: "Bool",
},
]
: []),
];
const form = new Form({
action: `/view/${viewname}`,
fields,
submitLabel: body?.prompt
? "Re-generate database design"
: "Generate database design",
additionalButtons: body?.prompt
? [
{
label: "Save this database permanently",
onclick: "save_database(this)",
class: "btn btn-primary",
afterSave: true,
},
]
: undefined,
});
return form;
};
const js = (viewname) =>
script(`
function save_database(that) {
const form = $(that).closest('form');
view_post("${viewname}", "save_database", $(form).serialize())
}
`);
const run = async (table_id, viewname, cfg, state, { res, req }) => {
const form = await getForm({ viewname });
const cfgMsg = incompleteCfgMsg();
if (cfgMsg) return cfgMsg;
else return renderForm(form, req.csrfToken());
};
const runPost = async (
table_id,
viewname,
config,
state,
body,
{ req, res }
) => {
const form = await getForm({ viewname, body, hasCode: true });
form.validate(body);
form.hasErrors = false;
form.errors = {};
const fullPrompt = await getPromptFromTemplate(
"database-designer.txt",
form.values.prompt
);
const completion = await getCompletion("SQL", fullPrompt);
form.values.code = completion;
res.sendWrap("Databse Designer Copilot", [
renderForm(form, req.csrfToken()),
js(viewname),
]);
};
const moreTypes = {
decimal: "Float",
numeric: "Float",
varchar: "String",
};
const save_database = async (table_id, viewname, config, body, { req }) => {
const form = await getForm({ viewname, body, hasCode: true });
form.validate(body);
if (!form.hasErrors) {
const genTables = [];
const { tableList, ast } = parser.parse(form.values.code, {
database: "PostgreSQL",
});
const tables_to_create = [];
for (const { type, keyword, create_definitions, table } of ast) {
if (type !== "create" || keyword !== "table" || !table?.length) continue;
const tblName = table[0].table;
const fields = [];
for (const {
column,
definition,
primary_key,
reference_definition,
resource,
} of create_definitions) {
if (primary_key) continue;
if (resource === "constraint") continue;
let type =
findType(definition.dataType.toLowerCase()) ||
moreTypes[definition.dataType.toLowerCase()];
if (reference_definition)
type = `Key to ${reference_definition.table[0].table}`;
const constraint = create_definitions.find(
(cd) =>
cd.resource === "constraint" &&
cd.definition?.[0]?.column === column.column
);
if (constraint?.reference_definition) {
type = `Key to ${constraint.reference_definition.table[0].table}`;
}
fields.push({
name: column.column,
type,
});
//onsole.log(fld, definition.dataType);
}
tables_to_create.push({ name: tblName, fields });
}
for (const table of tables_to_create) await Table.create(table.name);
for (const tbl of tables_to_create) {
const table = Table.findOne({ name: tbl.name });
for (const field of tbl.fields) {
field.table = table;
console.log("field", field.name, "type", field.type);
//pick summary field
if (field.type === "Key to users") {
field.attributes = { summary_field: "email" };
} else if (field.type.startsWith("Key to ")) {
const reftable_name = field.type.replace("Key to ", "");
const reftable = tables_to_create.find(
(t) => t.name === reftable_name
);
const summary_field = reftable.fields.find(
(f) => f.type === "String"
);
if (summary_field)
field.attributes = { summary_field: summary_field.name };
else field.attributes = { summary_field: "id" };
}
await Field.create(field);
}
}
if (form.values.basic_views)
for (const { name } of tables_to_create) {
const table = Table.findOne({ name });
const list = await initial_view(table, "List");
const edit = await initial_view(table, "Edit");
const show = await initial_view(table, "Show");
await View.update(
{
configuration: {
...list.configuration,
columns: [
...list.configuration.columns,
{
type: "ViewLink",
view: `Own:Show ${name}`,
view_name: `Show ${name}`,
link_style: "",
view_label: "Show",
header_label: "Show",
},
{
type: "ViewLink",
view: `Own:Edit ${name}`,
view_name: `Edit ${name}`,
link_style: "",
view_label: "Edit",
header_label: "Edit",
},
{
type: "Action",
action_name: "Delete",
action_style: "btn-primary",
},
],
view_to_create: `Edit ${name}`,
},
},
list.id
);
await View.update(
{
configuration: {
...edit.configuration,
view_when_done: `List ${name}`,
destination_type: "View",
},
},
edit.id
);
await add_to_menu({
label: name,
type: "View",
min_role: 100,
viewname: `List ${name}`,
});
}
return { json: { success: "ok", notify: `Database created` } };
}
return { json: { error: "Form incomplete" } };
};
const add_to_menu = async (item) => {
const current_menu = getState().getConfigCopy("menu_items", []);
const existing = current_menu.findIndex((m) => m.label === item.label);
if (existing >= 0) current_menu[existing] = item;
else current_menu.push(item);
await save_menu_items(current_menu);
};
const initial_view = async (table, viewtemplate) => {
const configuration = await initial_config_all_fields(
viewtemplate === "Edit"
)({ table_id: table.id });
//console.log(configuration);
const name = `${viewtemplate} ${table.name}`;
const view = await View.create({
name,
configuration,
viewtemplate,
table_id: table.id,
min_role: 100,
});
return view;
};
module.exports = {
name: "Database Design Copilot",
display_state_form: false,
get_state_fields,
tableless: true,
singleton: true,
run,
runPost: runPost,
routes: { save_database },
};