@agentic-kit/db-tools 0.13.1 → 0.15.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/README.md +3 -3
- package/access/provisioning.js +1 -0
- package/esm/access/provisioning.js +1 -0
- package/esm/host.d.ts +7 -0
- package/esm/index.d.ts +2 -1
- package/esm/records/delete-effects.d.ts +64 -0
- package/esm/records/delete-effects.js +239 -0
- package/esm/records/delete-selection.d.ts +29 -0
- package/esm/records/delete-selection.js +168 -0
- package/esm/records/meta.d.ts +7 -2
- package/esm/records/meta.js +17 -8
- package/esm/records/rows.d.ts +82 -0
- package/esm/records/rows.js +250 -0
- package/esm/schema-model.d.ts +2 -0
- package/esm/schema-model.js +2 -0
- package/esm/tools/add-records.d.ts +5 -32
- package/esm/tools/add-records.js +15 -145
- package/esm/tools/add-relation-schema.d.ts +4 -4
- package/esm/tools/delete-records.d.ts +33 -0
- package/esm/tools/delete-records.js +208 -0
- package/esm/tools/index.d.ts +6 -2
- package/esm/tools/index.js +13 -0
- package/esm/tools/update-records.d.ts +16 -0
- package/esm/tools/update-records.js +57 -0
- package/host.d.ts +7 -0
- package/index.d.ts +2 -1
- package/package.json +5 -5
- package/records/delete-effects.d.ts +64 -0
- package/records/delete-effects.js +250 -0
- package/records/delete-selection.d.ts +29 -0
- package/records/delete-selection.js +171 -0
- package/records/meta.d.ts +7 -2
- package/records/meta.js +17 -8
- package/records/rows.d.ts +82 -0
- package/records/rows.js +269 -0
- package/schema-model.d.ts +2 -0
- package/schema-model.js +2 -0
- package/tools/add-records.d.ts +5 -32
- package/tools/add-records.js +14 -144
- package/tools/add-relation-schema.d.ts +4 -4
- package/tools/delete-records.d.ts +33 -0
- package/tools/delete-records.js +212 -0
- package/tools/index.d.ts +6 -2
- package/tools/index.js +13 -0
- package/tools/update-records.d.ts +16 -0
- package/tools/update-records.js +61 -0
package/records/rows.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// What the record tools share: the app tables, read from the app API's `_meta` as the person signed in to the app;
|
|
3
|
+
// each record's keys as the API's field names, with "@<table>[<index>]" as the id of a sample row the host seeded;
|
|
4
|
+
// and one write per row, with what each row's answer was.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.fieldNamed = exports.tableKey = exports.isRowRef = exports.columnOf = exports.fieldsOf = exports.invalid = exports.isSuspended = exports.UNAVAILABLE = void 0;
|
|
7
|
+
exports.recordsFailed = recordsFailed;
|
|
8
|
+
exports.appReady = appReady;
|
|
9
|
+
exports.recordsReady = recordsReady;
|
|
10
|
+
exports.primaryKeyOf = primaryKeyOf;
|
|
11
|
+
exports.seededIds = seededIds;
|
|
12
|
+
exports.recordAsFields = recordAsFields;
|
|
13
|
+
exports.seededValue = seededValue;
|
|
14
|
+
exports.notAColumn = notAColumn;
|
|
15
|
+
exports.writeRecords = writeRecords;
|
|
16
|
+
const harness_1 = require("@agentic-kit/harness");
|
|
17
|
+
const generators_1 = require("@constructive-io/graphql-query/generators");
|
|
18
|
+
const failure_1 = require("../failure");
|
|
19
|
+
const graphql_http_1 = require("../graphql-http");
|
|
20
|
+
const host_1 = require("../host");
|
|
21
|
+
const ready_1 = require("../ready");
|
|
22
|
+
const meta_1 = require("./meta");
|
|
23
|
+
const WORDS = {
|
|
24
|
+
insert: {
|
|
25
|
+
done: 'Inserted',
|
|
26
|
+
into: 'into',
|
|
27
|
+
action: 'Failed to insert into',
|
|
28
|
+
count: 'createdCount',
|
|
29
|
+
noRow: failure_1.NO_NEW_ROW,
|
|
30
|
+
// A row the backend answers without was refused by, or is hidden by, the read rule.
|
|
31
|
+
noRows: (action, tableName) => ({
|
|
32
|
+
...(0, failure_1.noRowCreated)(action),
|
|
33
|
+
hint: "The table's read rules may hide the new row from this person: read the rules of the table to see who they let read.",
|
|
34
|
+
calls: [(0, failure_1.explainAccessCall)(tableName)],
|
|
35
|
+
}),
|
|
36
|
+
},
|
|
37
|
+
update: {
|
|
38
|
+
done: 'Updated',
|
|
39
|
+
into: 'in',
|
|
40
|
+
action: 'Failed to update',
|
|
41
|
+
count: 'updatedCount',
|
|
42
|
+
noRow: 'The backend answered without the row, so it does not exist, or this account may not change or read it.',
|
|
43
|
+
noRows: (action, tableName) => (0, failure_1.noRowsChanged)(action, (0, failure_1.explainAccessCall)(tableName)),
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
exports.UNAVAILABLE = "The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. Retrying won't help until it is restored.";
|
|
47
|
+
const isSuspended = (errors) => (0, graphql_http_1.classifyBackendErrors)(errors) === 'suspended';
|
|
48
|
+
exports.isSuspended = isSuspended;
|
|
49
|
+
function recordsFailed(failure, extra = {}) {
|
|
50
|
+
const flag = failure.code === 'app-signed-out' ? { needsAuth: true } : failure.code === 'database-unavailable' ? { code: failure.code } : {};
|
|
51
|
+
return (0, failure_1.failedResult)(failure, { success: false, message: (0, failure_1.failureText)(failure), ...flag, ...extra });
|
|
52
|
+
}
|
|
53
|
+
const invalid = (message) => ({ kind: 'failed', failure: { code: 'invalid-input', message, calls: [failure_1.DESCRIBE_SCHEMA] } });
|
|
54
|
+
exports.invalid = invalid;
|
|
55
|
+
/** The project, its data endpoint, an app sign-in, and the tables of the app's API; `done` ends a suspended message. */
|
|
56
|
+
async function appReady(cwd, done) {
|
|
57
|
+
const ready = await (0, ready_1.projectReady)(cwd);
|
|
58
|
+
if (ready.kind === 'failed')
|
|
59
|
+
return ready;
|
|
60
|
+
if (!ready.value.dataEndpoint) {
|
|
61
|
+
return {
|
|
62
|
+
kind: 'failed',
|
|
63
|
+
failure: {
|
|
64
|
+
code: 'missing-credentials',
|
|
65
|
+
message: 'Cannot resolve the app data endpoint (DATABASE_NAME missing from .env).',
|
|
66
|
+
hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const session = await (0, ready_1.appSessionReady)(ready.value);
|
|
71
|
+
if (session.kind === 'failed')
|
|
72
|
+
return session;
|
|
73
|
+
// Keeps the status and extensions.code that the SDK adapter drops.
|
|
74
|
+
const adapter = (0, graphql_http_1.statusAdapter)(ready.value.dataEndpoint, { Authorization: `Bearer ${session.value.token}` });
|
|
75
|
+
let tables;
|
|
76
|
+
try {
|
|
77
|
+
const meta = await adapter.execute(meta_1.META_QUERY);
|
|
78
|
+
if (!meta.ok) {
|
|
79
|
+
const failure = (0, exports.isSuspended)(meta.errors)
|
|
80
|
+
? { code: 'database-unavailable', message: `${exports.UNAVAILABLE} No rows were ${done}.` }
|
|
81
|
+
: (0, failure_1.failureFromErrors)(meta.errors, 'Failed to read schema from the app database');
|
|
82
|
+
return { kind: 'failed', failure };
|
|
83
|
+
}
|
|
84
|
+
tables = (meta.data._meta?.tables ?? []).filter((t) => Boolean(t));
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to query the app database schema') };
|
|
88
|
+
}
|
|
89
|
+
return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables } };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app
|
|
93
|
+
* sign-in, the table on the app's API, and every record's keys and seeded-row values.
|
|
94
|
+
*/
|
|
95
|
+
async function recordsReady(verb, params, cwd) {
|
|
96
|
+
if (params.records.length === 0)
|
|
97
|
+
return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } };
|
|
98
|
+
const ready = await appReady(cwd, WORDS[verb].done.toLowerCase());
|
|
99
|
+
if (ready.kind === 'failed')
|
|
100
|
+
return ready;
|
|
101
|
+
const table = (0, meta_1.findMetaTable)(ready.value.tables, params.table_name);
|
|
102
|
+
if (!table) {
|
|
103
|
+
return {
|
|
104
|
+
kind: 'failed',
|
|
105
|
+
failure: {
|
|
106
|
+
code: 'not-found',
|
|
107
|
+
message: `Table "${params.table_name}" was not found in the app database.`,
|
|
108
|
+
hint: 'Check the table names that exist, then retry.',
|
|
109
|
+
calls: [failure_1.DESCRIBE_SCHEMA],
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const named = params.records.some((record) => Object.values(record).some(exports.isRowRef));
|
|
114
|
+
const seeded = named ? await seededIds(cwd) : { kind: 'ok', value: new Map() };
|
|
115
|
+
if (seeded.kind === 'failed')
|
|
116
|
+
return seeded;
|
|
117
|
+
const records = [];
|
|
118
|
+
for (const [index, record] of params.records.entries()) {
|
|
119
|
+
const row = recordAsFields(table, params.table_name, index, record, seeded.value, verb === 'update');
|
|
120
|
+
if (row.kind === 'failed')
|
|
121
|
+
return row;
|
|
122
|
+
records.push(row.value);
|
|
123
|
+
}
|
|
124
|
+
return { kind: 'ok', value: { ...ready.value, table, records } };
|
|
125
|
+
}
|
|
126
|
+
const fieldsOf = (table) => (table.fields ?? []).filter((f) => Boolean(f));
|
|
127
|
+
exports.fieldsOf = fieldsOf;
|
|
128
|
+
const columnOf = (field) => field.columnName ?? field.name;
|
|
129
|
+
exports.columnOf = columnOf;
|
|
130
|
+
/** The table's single-column primary key, or undefined for none or a composite one. */
|
|
131
|
+
function primaryKeyOf(table) {
|
|
132
|
+
const keys = (0, exports.fieldsOf)(table).filter((field) => field.isPrimaryKey);
|
|
133
|
+
return keys.length === 1 ? keys[0] : undefined;
|
|
134
|
+
}
|
|
135
|
+
const ROW_REF = /^@([a-z][a-z0-9_]*)\[(\d+)\]$/i;
|
|
136
|
+
const isRowRef = (value) => typeof value === 'string' && ROW_REF.test(value);
|
|
137
|
+
exports.isRowRef = isRowRef;
|
|
138
|
+
const tableKey = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
139
|
+
exports.tableKey = tableKey;
|
|
140
|
+
/** The ids of the sample rows the host seeded, by `tableKey`; none on a host that seeds no rows. */
|
|
141
|
+
async function seededIds(cwd) {
|
|
142
|
+
const host = (0, host_1.getHost)();
|
|
143
|
+
if (!host.seededRows)
|
|
144
|
+
return { kind: 'ok', value: new Map() };
|
|
145
|
+
try {
|
|
146
|
+
const rows = (await host.seededRows(cwd)) ?? {};
|
|
147
|
+
return { kind: 'ok', value: new Map(Object.entries(rows).map(([table, ids]) => [(0, exports.tableKey)(table), ids])) };
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
return { kind: 'failed', failure: { code: 'failed', message: `Could not read the sample rows seeded for this project: ${(0, graphql_http_1.thrownText)(err)}` } };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const isEmpty = (value) => value === undefined || value === null || value === '';
|
|
154
|
+
/**
|
|
155
|
+
* A record with each key as the API's field name. A key may be a field name or a column name, and the field name's
|
|
156
|
+
* value wins when both carry one; an empty value never replaces a given one. With nothing but empty values, a column
|
|
157
|
+
* is left out so the server's default applies, or set to null when `clear`. A "@<table>[<index>]" value becomes that
|
|
158
|
+
* seeded row's id.
|
|
159
|
+
*/
|
|
160
|
+
function recordAsFields(table, tableName, index, record, seeded, clear) {
|
|
161
|
+
const fields = (0, exports.fieldsOf)(table);
|
|
162
|
+
const unknown = notAColumn(table, tableName, Object.keys(record));
|
|
163
|
+
if (unknown)
|
|
164
|
+
return (0, exports.invalid)(`Row ${index} names ${unknown}`);
|
|
165
|
+
const row = {};
|
|
166
|
+
for (const field of fields) {
|
|
167
|
+
const given = [field.name, (0, exports.columnOf)(field)].filter((key) => Object.hasOwn(record, key)).map((key) => record[key]);
|
|
168
|
+
if (given.length === 0)
|
|
169
|
+
continue;
|
|
170
|
+
const value = given.find((v) => !isEmpty(v));
|
|
171
|
+
if (value === undefined) {
|
|
172
|
+
if (clear)
|
|
173
|
+
row[field.name] = null;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const id = seededValue(value, seeded);
|
|
177
|
+
if (id === undefined)
|
|
178
|
+
return (0, exports.invalid)(`Row ${index} names "${value}", but no sample row was seeded there: use the row's id.`);
|
|
179
|
+
row[field.name] = id;
|
|
180
|
+
}
|
|
181
|
+
return { kind: 'ok', value: row };
|
|
182
|
+
}
|
|
183
|
+
/** The value, or the id of the seeded row a "@<table>[<index>]" value names: undefined when none was seeded there. */
|
|
184
|
+
function seededValue(value, seeded) {
|
|
185
|
+
const ref = typeof value === 'string' ? value.match(ROW_REF) : null;
|
|
186
|
+
return ref ? seeded.get((0, exports.tableKey)(ref[1]))?.[Number(ref[2])] ?? undefined : value;
|
|
187
|
+
}
|
|
188
|
+
/** The first key that names no column (or field) of the table, with the column to use instead, as the end of a sentence. */
|
|
189
|
+
function notAColumn(table, tableName, keys) {
|
|
190
|
+
const fields = (0, exports.fieldsOf)(table);
|
|
191
|
+
const names = new Set(fields.flatMap((field) => [field.name, (0, exports.columnOf)(field)]));
|
|
192
|
+
const unknown = keys.find((key) => !names.has(key));
|
|
193
|
+
if (unknown === undefined)
|
|
194
|
+
return undefined;
|
|
195
|
+
const columns = fields.map(exports.columnOf);
|
|
196
|
+
const nearest = (0, harness_1.nearestName)(unknown, columns);
|
|
197
|
+
const next = nearest ? `use "${nearest}".` : `its columns are ${(0, harness_1.listed)(columns.map((c) => `"${c}"`))}.`;
|
|
198
|
+
return `"${unknown}", which is not a column of ${tableName}: ${next}`;
|
|
199
|
+
}
|
|
200
|
+
/** The field a key names, by its field name or its column name. */
|
|
201
|
+
const fieldNamed = (table, key) => (0, exports.fieldsOf)(table).find((field) => field.name === key) ?? (0, exports.fieldsOf)(table).find((field) => (0, exports.columnOf)(field) === key);
|
|
202
|
+
exports.fieldNamed = fieldNamed;
|
|
203
|
+
/** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */
|
|
204
|
+
async function writeRecords(verb, tableName, { adapter, table: rawTable }, mutation, mutationName, inputs) {
|
|
205
|
+
const words = WORDS[verb];
|
|
206
|
+
const table = (0, meta_1.cleanTable)(rawTable);
|
|
207
|
+
const singularName = (0, generators_1.toCamelCaseSingular)(table.name, table);
|
|
208
|
+
const rows = [];
|
|
209
|
+
const errors = [];
|
|
210
|
+
const failedRows = [];
|
|
211
|
+
let suspended = false;
|
|
212
|
+
for (const [index, input] of inputs.entries()) {
|
|
213
|
+
let rowErrors;
|
|
214
|
+
try {
|
|
215
|
+
const result = await adapter.execute(mutation, { input });
|
|
216
|
+
if (result.ok) {
|
|
217
|
+
const row = result.data?.[mutationName]?.[singularName];
|
|
218
|
+
if (row)
|
|
219
|
+
rows.push(row);
|
|
220
|
+
else
|
|
221
|
+
failedRows.push({ index, message: words.noRow });
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if ((0, exports.isSuspended)(result.errors)) {
|
|
225
|
+
suspended = true;
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
rowErrors = result.errors;
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
// The request threw before any answer came back, so the error is the local one.
|
|
232
|
+
rowErrors = [{ message: (0, graphql_http_1.thrownText)(err), extensions: { code: 'NETWORK' } }];
|
|
233
|
+
}
|
|
234
|
+
errors.push(...rowErrors);
|
|
235
|
+
failedRows.push({ index, message: (0, graphql_http_1.answerText)(rowErrors) });
|
|
236
|
+
}
|
|
237
|
+
const done = words.done.toLowerCase();
|
|
238
|
+
const details = {
|
|
239
|
+
tableName: rawTable.name,
|
|
240
|
+
columns: table.fields.map((f) => f.name),
|
|
241
|
+
rows,
|
|
242
|
+
[words.count]: rows.length,
|
|
243
|
+
asOf: new Date().toISOString(),
|
|
244
|
+
};
|
|
245
|
+
const failed = (failure) => recordsFailed(failure, { ...(rows.length > 0 ? details : {}), ...(failedRows.length > 0 ? { failedRows } : {}) });
|
|
246
|
+
if (suspended) {
|
|
247
|
+
const message = rows.length > 0 ? `${exports.UNAVAILABLE} ${rows.length} row(s) were ${done} before it stopped.` : `${exports.UNAVAILABLE} No rows were ${done}.`;
|
|
248
|
+
return failed({ code: 'database-unavailable', message });
|
|
249
|
+
}
|
|
250
|
+
if (rows.length === 0) {
|
|
251
|
+
const action = `${words.action} "${tableName}"`;
|
|
252
|
+
return failed(errors.length ? (0, failure_1.failureFromErrors)(errors, action, { rows: { table: tableName } }) : words.noRows(action, tableName));
|
|
253
|
+
}
|
|
254
|
+
if (failedRows.length > 0) {
|
|
255
|
+
const [first] = failedRows;
|
|
256
|
+
return failed({
|
|
257
|
+
code: 'partial',
|
|
258
|
+
message: `${words.done} ${rows.length} of ${inputs.length} rows ${words.into} ${tableName}; ${failedRows.length} were not ${done} (row ${first.index}: ${first.message}).`,
|
|
259
|
+
hint: `Fix the rows listed in details.failedRows, then call again with only those rows: the ${done} rows stay.`,
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
const message = `${words.done} ${rows.length} row(s) ${words.into} ${tableName}.${verb === 'insert' ? keysLine(rows, primaryKeyOf(rawTable)?.name) : ''}`;
|
|
263
|
+
return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } };
|
|
264
|
+
}
|
|
265
|
+
/** The line that gives the new rows' keys, so a later call can point another row at one. */
|
|
266
|
+
function keysLine(rows, key) {
|
|
267
|
+
const keys = key ? rows.map((row) => row[key]).filter((value) => value !== undefined && value !== null) : [];
|
|
268
|
+
return keys.length ? `\nThe new rows' ${key} values, in insert order: ${keys.map((value) => JSON.stringify(value)).join(', ')}.` : '';
|
|
269
|
+
}
|
package/schema-model.d.ts
CHANGED
|
@@ -54,6 +54,8 @@ export type ModelForeignKey = {
|
|
|
54
54
|
targetCategory: ObjectCategory | null;
|
|
55
55
|
targetColumns: string[];
|
|
56
56
|
onDelete: FkAction;
|
|
57
|
+
/** The columns a delete of the target row sets to null or their default, when the key names only some of its own. */
|
|
58
|
+
deleteSetColumns?: string[];
|
|
57
59
|
onUpdate: FkAction;
|
|
58
60
|
};
|
|
59
61
|
export type ModelPolicy = {
|
package/schema-model.js
CHANGED
|
@@ -191,6 +191,7 @@ async function readSchemaModel(context) {
|
|
|
191
191
|
refTableId: true,
|
|
192
192
|
refFieldIds: true,
|
|
193
193
|
deleteAction: true,
|
|
194
|
+
deleteSetFieldIds: true,
|
|
194
195
|
updateAction: true,
|
|
195
196
|
},
|
|
196
197
|
where: inApp,
|
|
@@ -296,6 +297,7 @@ async function readSchemaModel(context) {
|
|
|
296
297
|
targetCategory: target?.category ?? null,
|
|
297
298
|
targetColumns: names(fk.refFieldIds),
|
|
298
299
|
onDelete: (0, normalize_1.fkAction)(fk.deleteAction),
|
|
300
|
+
...(fk.deleteSetFieldIds?.length ? { deleteSetColumns: names(fk.deleteSetFieldIds) } : {}),
|
|
299
301
|
onUpdate: (0, normalize_1.fkAction)(fk.updateAction),
|
|
300
302
|
};
|
|
301
303
|
}),
|
package/tools/add-records.d.ts
CHANGED
|
@@ -1,40 +1,13 @@
|
|
|
1
1
|
import { type HarnessTool } from '@agentic-kit/harness';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import type {
|
|
4
|
-
import { type
|
|
5
|
-
import { statusAdapter } from '../graphql-http';
|
|
6
|
-
import { type RawMetaTable } from '../records/meta';
|
|
7
|
-
export type AddRecordsDetails = {
|
|
8
|
-
success: boolean;
|
|
9
|
-
message: string;
|
|
10
|
-
tableName?: string;
|
|
11
|
-
columns?: string[];
|
|
12
|
-
rows?: Record<string, unknown>[];
|
|
13
|
-
createdCount?: number;
|
|
14
|
-
asOf?: string;
|
|
15
|
-
needsAuth?: boolean;
|
|
16
|
-
code?: 'database-unavailable';
|
|
17
|
-
/** The rows that were not inserted: their place in `records` and what the backend said. */
|
|
18
|
-
failedRows?: {
|
|
19
|
-
index: number;
|
|
20
|
-
message: string;
|
|
21
|
-
}[];
|
|
22
|
-
};
|
|
3
|
+
import type { Result } from '../failure';
|
|
4
|
+
import { type RecordsDetails, type RecordsReady } from '../records/rows';
|
|
23
5
|
declare const AddRecordsZod: z.ZodObject<{
|
|
24
6
|
table_name: z.ZodString;
|
|
25
7
|
records: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
26
8
|
}, z.core.$strict>;
|
|
27
9
|
type AddRecordsParams = z.infer<typeof AddRecordsZod>;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
userId?: string;
|
|
32
|
-
/** The app's own API, as the person signed in to the app. */
|
|
33
|
-
adapter: ReturnType<typeof statusAdapter>;
|
|
34
|
-
tables: RawMetaTable[];
|
|
35
|
-
table: RawMetaTable;
|
|
36
|
-
};
|
|
37
|
-
/** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in, and the table on the app's API. */
|
|
38
|
-
export declare function addRecordsReady(params: AddRecordsParams, cwd: string): Promise<Result<AddRecordsReady>>;
|
|
39
|
-
export declare const addRecordsTool: HarnessTool<typeof AddRecordsZod, AddRecordsDetails>;
|
|
10
|
+
/** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in, the table on the app's API, and every record's keys and seeded-row values. */
|
|
11
|
+
export declare function addRecordsReady(params: AddRecordsParams, cwd: string): Promise<Result<RecordsReady>>;
|
|
12
|
+
export declare const addRecordsTool: HarnessTool<typeof AddRecordsZod, RecordsDetails>;
|
|
40
13
|
export {};
|
package/tools/add-records.js
CHANGED
|
@@ -5,86 +5,18 @@ exports.addRecordsReady = addRecordsReady;
|
|
|
5
5
|
const harness_1 = require("@agentic-kit/harness");
|
|
6
6
|
const generators_1 = require("@constructive-io/graphql-query/generators");
|
|
7
7
|
const zod_1 = require("zod");
|
|
8
|
-
const failure_1 = require("../failure");
|
|
9
|
-
const graphql_http_1 = require("../graphql-http");
|
|
10
|
-
const ready_1 = require("../ready");
|
|
11
8
|
const meta_1 = require("../records/meta");
|
|
12
|
-
|
|
13
|
-
return (0, failure_1.failedResult)(failure, { success: false, message: (0, failure_1.failureText)(failure), ...extra });
|
|
14
|
-
}
|
|
15
|
-
const UNAVAILABLE = "The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. Retrying won't help until it is restored.";
|
|
16
|
-
function unavailable(inserted = 0) {
|
|
17
|
-
const message = inserted > 0 ? `${UNAVAILABLE} ${inserted} row(s) were inserted before it stopped.` : `${UNAVAILABLE} No rows were inserted.`;
|
|
18
|
-
return fail({ code: 'database-unavailable', message }, { code: 'database-unavailable', ...(inserted > 0 ? { createdCount: inserted } : {}) });
|
|
19
|
-
}
|
|
20
|
-
const isSuspended = (errors) => (0, graphql_http_1.classifyBackendErrors)(errors) === 'suspended';
|
|
21
|
-
// Mirror @constructive-io/data's prepareCreateInput (create semantics): drop
|
|
22
|
-
// undefined/null/empty-string so server defaults apply; keep false/0/[]/objects.
|
|
23
|
-
function stripForCreate(record) {
|
|
24
|
-
const out = {};
|
|
25
|
-
for (const [key, value] of Object.entries(record)) {
|
|
26
|
-
if (value === undefined || value === null || value === '')
|
|
27
|
-
continue;
|
|
28
|
-
out[key] = value;
|
|
29
|
-
}
|
|
30
|
-
return out;
|
|
31
|
-
}
|
|
9
|
+
const rows_1 = require("../records/rows");
|
|
32
10
|
const AddRecordsZod = (0, harness_1.strictObject)('the input', {
|
|
33
11
|
table_name: (0, harness_1.identifierParam)()
|
|
34
12
|
.describe('Name of the table to insert rows into (snake_case, singular or plural).'),
|
|
35
13
|
records: zod_1.z
|
|
36
14
|
.array(zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()))
|
|
37
|
-
.describe('Rows to insert. Each is an object of column → value
|
|
15
|
+
.describe('Rows to insert. Each is an object of the table\'s column names (snake_case) → value. A value "@<table>[<index>]" is the id of a sample row seeded when the app was built.'),
|
|
38
16
|
});
|
|
39
|
-
/** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in,
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } };
|
|
43
|
-
const ready = await (0, ready_1.projectReady)(cwd);
|
|
44
|
-
if (ready.kind === 'failed')
|
|
45
|
-
return ready;
|
|
46
|
-
if (!ready.value.dataEndpoint) {
|
|
47
|
-
return {
|
|
48
|
-
kind: 'failed',
|
|
49
|
-
failure: {
|
|
50
|
-
code: 'missing-credentials',
|
|
51
|
-
message: 'Cannot resolve the app data endpoint (DATABASE_NAME missing from .env).',
|
|
52
|
-
hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
|
|
53
|
-
},
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
const session = await (0, ready_1.appSessionReady)(ready.value);
|
|
57
|
-
if (session.kind === 'failed')
|
|
58
|
-
return session;
|
|
59
|
-
// Keeps the status and extensions.code that the SDK adapter drops.
|
|
60
|
-
const adapter = (0, graphql_http_1.statusAdapter)(ready.value.dataEndpoint, { Authorization: `Bearer ${session.value.token}` });
|
|
61
|
-
let tables;
|
|
62
|
-
try {
|
|
63
|
-
const meta = await adapter.execute(meta_1.META_QUERY);
|
|
64
|
-
if (!meta.ok) {
|
|
65
|
-
const failure = isSuspended(meta.errors)
|
|
66
|
-
? { code: 'database-unavailable', message: `${UNAVAILABLE} No rows were inserted.` }
|
|
67
|
-
: (0, failure_1.failureFromErrors)(meta.errors, 'Failed to read schema from the app database');
|
|
68
|
-
return { kind: 'failed', failure };
|
|
69
|
-
}
|
|
70
|
-
tables = (meta.data._meta?.tables ?? []).filter((t) => Boolean(t));
|
|
71
|
-
}
|
|
72
|
-
catch (err) {
|
|
73
|
-
return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to query the app database schema') };
|
|
74
|
-
}
|
|
75
|
-
const table = (0, meta_1.findMetaTable)(tables, params.table_name);
|
|
76
|
-
if (!table) {
|
|
77
|
-
return {
|
|
78
|
-
kind: 'failed',
|
|
79
|
-
failure: {
|
|
80
|
-
code: 'not-found',
|
|
81
|
-
message: `Table "${params.table_name}" was not found in the app database.`,
|
|
82
|
-
hint: 'Check the table names that exist, then retry.',
|
|
83
|
-
calls: [failure_1.DESCRIBE_SCHEMA],
|
|
84
|
-
},
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables, table } };
|
|
17
|
+
/** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in, the table on the app's API, and every record's keys and seeded-row values. */
|
|
18
|
+
function addRecordsReady(params, cwd) {
|
|
19
|
+
return (0, rows_1.recordsReady)('insert', params, cwd);
|
|
88
20
|
}
|
|
89
21
|
exports.addRecordsTool = {
|
|
90
22
|
name: 'add_records',
|
|
@@ -95,82 +27,20 @@ exports.addRecordsTool = {
|
|
|
95
27
|
effect: 'write',
|
|
96
28
|
async execute(params, ctx) {
|
|
97
29
|
const ready = await addRecordsReady(params, ctx.cwd);
|
|
98
|
-
if (ready.kind === 'failed')
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const { userId, adapter, tables, table: rawTable } = ready.value;
|
|
103
|
-
const table = (0, meta_1.cleanTable)(rawTable);
|
|
104
|
-
const allTables = tables.map(meta_1.cleanTable);
|
|
105
|
-
const mutation = (0, generators_1.buildPostGraphileCreate)(table, allTables).toString();
|
|
106
|
-
const mutationName = (0, generators_1.toCreateMutationName)(table.name, table);
|
|
30
|
+
if (ready.kind === 'failed')
|
|
31
|
+
return (0, rows_1.recordsFailed)(ready.failure);
|
|
32
|
+
const { userId, tables, records } = ready.value;
|
|
33
|
+
const table = (0, meta_1.cleanTable)(ready.value.table);
|
|
107
34
|
const singularName = (0, generators_1.toCamelCaseSingular)(table.name, table);
|
|
108
35
|
// Constructive app tables scope rows by entityId (the owning user's id). The
|
|
109
36
|
// create input requires it, but callers won't know it — backfill it with the
|
|
110
37
|
// signed-in user's id from the Preview session when the table has the column
|
|
111
38
|
// and the record omits it.
|
|
112
39
|
const hasEntityId = table.fields.some((f) => f.name === 'entityId');
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
? { ...record, entityId: userId }
|
|
119
|
-
: record;
|
|
120
|
-
const variables = { input: { [singularName]: stripForCreate(prepared) } };
|
|
121
|
-
let rowErrors;
|
|
122
|
-
try {
|
|
123
|
-
const result = await adapter.execute(mutation, variables);
|
|
124
|
-
if (result.ok) {
|
|
125
|
-
const payload = result.data?.[mutationName];
|
|
126
|
-
const row = payload?.[singularName];
|
|
127
|
-
if (row) {
|
|
128
|
-
created.push(row);
|
|
129
|
-
}
|
|
130
|
-
else {
|
|
131
|
-
failedRows.push({ index, message: failure_1.NO_NEW_ROW });
|
|
132
|
-
}
|
|
133
|
-
continue;
|
|
134
|
-
}
|
|
135
|
-
if (isSuspended(result.errors))
|
|
136
|
-
return unavailable(created.length);
|
|
137
|
-
rowErrors = result.errors;
|
|
138
|
-
}
|
|
139
|
-
catch (err) {
|
|
140
|
-
// The request threw before any answer came back, so the error is the local one.
|
|
141
|
-
rowErrors = [{ message: (0, graphql_http_1.thrownText)(err), extensions: { code: 'NETWORK' } }];
|
|
142
|
-
}
|
|
143
|
-
errors.push(...rowErrors);
|
|
144
|
-
failedRows.push({ index, message: (0, graphql_http_1.answerText)(rowErrors) });
|
|
145
|
-
}
|
|
146
|
-
const columns = table.fields.map((f) => f.name);
|
|
147
|
-
const rowDetails = {
|
|
148
|
-
tableName: rawTable.name,
|
|
149
|
-
columns,
|
|
150
|
-
rows: created,
|
|
151
|
-
createdCount: created.length,
|
|
152
|
-
asOf: new Date().toISOString(),
|
|
153
|
-
};
|
|
154
|
-
if (created.length === 0) {
|
|
155
|
-
const action = `Failed to insert into "${params.table_name}"`;
|
|
156
|
-
const rows = { table: params.table_name };
|
|
157
|
-
// A row the backend answers without was refused by, or is hidden by, the read rule.
|
|
158
|
-
const hidden = {
|
|
159
|
-
...(0, failure_1.noRowCreated)(action),
|
|
160
|
-
hint: "The table's read rules may hide the new row from this person: read the rules of the table to see who they let read.",
|
|
161
|
-
calls: [(0, failure_1.explainAccessCall)(params.table_name)],
|
|
162
|
-
};
|
|
163
|
-
return fail(errors.length ? (0, failure_1.failureFromErrors)(errors, action, { rows }) : hidden, { failedRows });
|
|
164
|
-
}
|
|
165
|
-
if (failedRows.length > 0) {
|
|
166
|
-
const first = failedRows[0];
|
|
167
|
-
return fail({
|
|
168
|
-
code: 'partial',
|
|
169
|
-
message: `Inserted ${created.length} of ${params.records.length} rows into ${params.table_name}; ${failedRows.length} were not inserted (row ${first.index}: ${first.message}).`,
|
|
170
|
-
hint: 'Fix the rows listed in details.failedRows, then call again with only those rows: the inserted rows stay.',
|
|
171
|
-
}, { ...rowDetails, failedRows });
|
|
172
|
-
}
|
|
173
|
-
const message = `Inserted ${created.length} row(s) into ${params.table_name}.`;
|
|
174
|
-
return { content: [{ type: 'text', text: message }], details: { success: true, message, ...rowDetails } };
|
|
40
|
+
const inputs = records.map((record) => ({
|
|
41
|
+
[singularName]: hasEntityId && userId && record.entityId == null ? { ...record, entityId: userId } : record,
|
|
42
|
+
}));
|
|
43
|
+
const mutation = (0, generators_1.buildPostGraphileCreate)(table, tables.map(meta_1.cleanTable)).toString();
|
|
44
|
+
return (0, rows_1.writeRecords)('insert', params.table_name, ready.value, mutation, (0, generators_1.toCreateMutationName)(table.name, table), inputs);
|
|
175
45
|
},
|
|
176
46
|
};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { BlueprintRelation } from 'node-type-registry';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
export declare const DeleteAction: z.ZodEnum<{
|
|
4
|
-
a: "a";
|
|
5
4
|
c: "c";
|
|
6
|
-
r: "r";
|
|
7
5
|
n: "n";
|
|
6
|
+
r: "r";
|
|
7
|
+
a: "a";
|
|
8
8
|
d: "d";
|
|
9
9
|
}>;
|
|
10
10
|
export declare const AddRelationZod: z.ZodObject<{
|
|
@@ -17,10 +17,10 @@ export declare const AddRelationZod: z.ZodObject<{
|
|
|
17
17
|
field_name: z.ZodOptional<z.ZodString>;
|
|
18
18
|
junction_table_name: z.ZodOptional<z.ZodString>;
|
|
19
19
|
delete_action: z.ZodOptional<z.ZodEnum<{
|
|
20
|
-
a: "a";
|
|
21
20
|
c: "c";
|
|
22
|
-
r: "r";
|
|
23
21
|
n: "n";
|
|
22
|
+
r: "r";
|
|
23
|
+
a: "a";
|
|
24
24
|
d: "d";
|
|
25
25
|
}>>;
|
|
26
26
|
is_required: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type HarnessTool } from '@agentic-kit/harness';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { type DeleteRecordsReady } from '../records/delete-selection';
|
|
4
|
+
import type { Resolved } from './index';
|
|
5
|
+
declare const DeleteRecordsZod: z.ZodObject<{
|
|
6
|
+
tables: z.ZodArray<z.ZodObject<{
|
|
7
|
+
table_name: z.ZodString;
|
|
8
|
+
rows: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
|
|
9
|
+
where: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
10
|
+
sample: z.ZodOptional<z.ZodLiteral<true>>;
|
|
11
|
+
all: z.ZodOptional<z.ZodLiteral<true>>;
|
|
12
|
+
}, z.core.$strict>>;
|
|
13
|
+
}, z.core.$strict>;
|
|
14
|
+
export type DeleteRecordsDetails = {
|
|
15
|
+
success: boolean;
|
|
16
|
+
message: string;
|
|
17
|
+
deletedCount: number;
|
|
18
|
+
tables: Array<{
|
|
19
|
+
tableName: string;
|
|
20
|
+
deleted: number;
|
|
21
|
+
kept?: true;
|
|
22
|
+
failed: Array<{
|
|
23
|
+
key: string | number;
|
|
24
|
+
message: string;
|
|
25
|
+
}>;
|
|
26
|
+
}>;
|
|
27
|
+
needsAuth?: boolean;
|
|
28
|
+
code?: 'database-unavailable';
|
|
29
|
+
};
|
|
30
|
+
/** The plan of a records delete: the exact rows as the target, and the card's preview. */
|
|
31
|
+
export declare function deleteRecordsPlan({ context, userId, selection, notes }: DeleteRecordsReady): Resolved;
|
|
32
|
+
export declare const deleteRecordsTool: HarnessTool<typeof DeleteRecordsZod, DeleteRecordsDetails>;
|
|
33
|
+
export {};
|