@agentic-kit/db-tools 0.14.0 → 0.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/esm/host.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/rows.d.ts +27 -4
- package/esm/records/rows.js +53 -36
- package/esm/schema-model.d.ts +2 -0
- package/esm/schema-model.js +2 -0
- 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 +10 -0
- package/host.d.ts +2 -1
- package/package.json +3 -3
- 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/rows.d.ts +27 -4
- package/records/rows.js +64 -39
- package/schema-model.d.ts +2 -0
- package/schema-model.js +2 -0
- 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 +10 -0
package/records/rows.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// What
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.columnOf = exports.fieldsOf = exports.invalid = void 0;
|
|
6
|
+
exports.fieldNamed = exports.tableKey = exports.isRowRef = exports.columnOf = exports.fieldsOf = exports.invalid = exports.isSuspended = exports.UNAVAILABLE = void 0;
|
|
7
7
|
exports.recordsFailed = recordsFailed;
|
|
8
|
+
exports.appReady = appReady;
|
|
8
9
|
exports.recordsReady = recordsReady;
|
|
9
10
|
exports.primaryKeyOf = primaryKeyOf;
|
|
11
|
+
exports.seededIds = seededIds;
|
|
10
12
|
exports.recordAsFields = recordAsFields;
|
|
13
|
+
exports.seededValue = seededValue;
|
|
14
|
+
exports.notAColumn = notAColumn;
|
|
11
15
|
exports.writeRecords = writeRecords;
|
|
12
16
|
const harness_1 = require("@agentic-kit/harness");
|
|
13
17
|
const generators_1 = require("@constructive-io/graphql-query/generators");
|
|
@@ -39,21 +43,17 @@ const WORDS = {
|
|
|
39
43
|
noRows: (action, tableName) => (0, failure_1.noRowsChanged)(action, (0, failure_1.explainAccessCall)(tableName)),
|
|
40
44
|
},
|
|
41
45
|
};
|
|
42
|
-
|
|
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.";
|
|
43
47
|
const isSuspended = (errors) => (0, graphql_http_1.classifyBackendErrors)(errors) === 'suspended';
|
|
48
|
+
exports.isSuspended = isSuspended;
|
|
44
49
|
function recordsFailed(failure, extra = {}) {
|
|
45
50
|
const flag = failure.code === 'app-signed-out' ? { needsAuth: true } : failure.code === 'database-unavailable' ? { code: failure.code } : {};
|
|
46
51
|
return (0, failure_1.failedResult)(failure, { success: false, message: (0, failure_1.failureText)(failure), ...flag, ...extra });
|
|
47
52
|
}
|
|
48
53
|
const invalid = (message) => ({ kind: 'failed', failure: { code: 'invalid-input', message, calls: [failure_1.DESCRIBE_SCHEMA] } });
|
|
49
54
|
exports.invalid = invalid;
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
* sign-in, the table on the app's API, and every record's keys and seeded-row values.
|
|
53
|
-
*/
|
|
54
|
-
async function recordsReady(verb, params, cwd) {
|
|
55
|
-
if (params.records.length === 0)
|
|
56
|
-
return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } };
|
|
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
57
|
const ready = await (0, ready_1.projectReady)(cwd);
|
|
58
58
|
if (ready.kind === 'failed')
|
|
59
59
|
return ready;
|
|
@@ -76,8 +76,8 @@ async function recordsReady(verb, params, cwd) {
|
|
|
76
76
|
try {
|
|
77
77
|
const meta = await adapter.execute(meta_1.META_QUERY);
|
|
78
78
|
if (!meta.ok) {
|
|
79
|
-
const failure = isSuspended(meta.errors)
|
|
80
|
-
? { code: 'database-unavailable', message: `${UNAVAILABLE} No rows were ${
|
|
79
|
+
const failure = (0, exports.isSuspended)(meta.errors)
|
|
80
|
+
? { code: 'database-unavailable', message: `${exports.UNAVAILABLE} No rows were ${done}.` }
|
|
81
81
|
: (0, failure_1.failureFromErrors)(meta.errors, 'Failed to read schema from the app database');
|
|
82
82
|
return { kind: 'failed', failure };
|
|
83
83
|
}
|
|
@@ -86,7 +86,19 @@ async function recordsReady(verb, params, cwd) {
|
|
|
86
86
|
catch (err) {
|
|
87
87
|
return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to query the app database schema') };
|
|
88
88
|
}
|
|
89
|
-
|
|
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);
|
|
90
102
|
if (!table) {
|
|
91
103
|
return {
|
|
92
104
|
kind: 'failed',
|
|
@@ -98,7 +110,8 @@ async function recordsReady(verb, params, cwd) {
|
|
|
98
110
|
},
|
|
99
111
|
};
|
|
100
112
|
}
|
|
101
|
-
const
|
|
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() };
|
|
102
115
|
if (seeded.kind === 'failed')
|
|
103
116
|
return seeded;
|
|
104
117
|
const records = [];
|
|
@@ -108,7 +121,7 @@ async function recordsReady(verb, params, cwd) {
|
|
|
108
121
|
return row;
|
|
109
122
|
records.push(row.value);
|
|
110
123
|
}
|
|
111
|
-
return { kind: 'ok', value: {
|
|
124
|
+
return { kind: 'ok', value: { ...ready.value, table, records } };
|
|
112
125
|
}
|
|
113
126
|
const fieldsOf = (table) => (table.fields ?? []).filter((f) => Boolean(f));
|
|
114
127
|
exports.fieldsOf = fieldsOf;
|
|
@@ -120,16 +133,18 @@ function primaryKeyOf(table) {
|
|
|
120
133
|
return keys.length === 1 ? keys[0] : undefined;
|
|
121
134
|
}
|
|
122
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;
|
|
123
138
|
const tableKey = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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) {
|
|
127
142
|
const host = (0, host_1.getHost)();
|
|
128
|
-
if (!
|
|
143
|
+
if (!host.seededRows)
|
|
129
144
|
return { kind: 'ok', value: new Map() };
|
|
130
145
|
try {
|
|
131
146
|
const rows = (await host.seededRows(cwd)) ?? {};
|
|
132
|
-
return { kind: 'ok', value: new Map(Object.entries(rows).map(([table, ids]) => [tableKey(table), ids])) };
|
|
147
|
+
return { kind: 'ok', value: new Map(Object.entries(rows).map(([table, ids]) => [(0, exports.tableKey)(table), ids])) };
|
|
133
148
|
}
|
|
134
149
|
catch (err) {
|
|
135
150
|
return { kind: 'failed', failure: { code: 'failed', message: `Could not read the sample rows seeded for this project: ${(0, graphql_http_1.thrownText)(err)}` } };
|
|
@@ -144,14 +159,9 @@ const isEmpty = (value) => value === undefined || value === null || value === ''
|
|
|
144
159
|
*/
|
|
145
160
|
function recordAsFields(table, tableName, index, record, seeded, clear) {
|
|
146
161
|
const fields = (0, exports.fieldsOf)(table);
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const columns = fields.map(exports.columnOf);
|
|
151
|
-
const nearest = (0, harness_1.nearestName)(unknown, columns);
|
|
152
|
-
const next = nearest ? `use "${nearest}".` : `its columns are ${(0, harness_1.listed)(columns.map((c) => `"${c}"`))}.`;
|
|
153
|
-
return (0, exports.invalid)(`Row ${index} names "${unknown}", which is not a column of ${tableName}: ${next}`);
|
|
154
|
-
}
|
|
162
|
+
const unknown = notAColumn(table, tableName, Object.keys(record));
|
|
163
|
+
if (unknown)
|
|
164
|
+
return (0, exports.invalid)(`Row ${index} names ${unknown}`);
|
|
155
165
|
const row = {};
|
|
156
166
|
for (const field of fields) {
|
|
157
167
|
const given = [field.name, (0, exports.columnOf)(field)].filter((key) => Object.hasOwn(record, key)).map((key) => record[key]);
|
|
@@ -163,18 +173,33 @@ function recordAsFields(table, tableName, index, record, seeded, clear) {
|
|
|
163
173
|
row[field.name] = null;
|
|
164
174
|
continue;
|
|
165
175
|
}
|
|
166
|
-
const
|
|
167
|
-
if (
|
|
168
|
-
row[field.name] = value;
|
|
169
|
-
continue;
|
|
170
|
-
}
|
|
171
|
-
const id = seeded.get(tableKey(ref[1]))?.[Number(ref[2])];
|
|
172
|
-
if (!id)
|
|
176
|
+
const id = seededValue(value, seeded);
|
|
177
|
+
if (id === undefined)
|
|
173
178
|
return (0, exports.invalid)(`Row ${index} names "${value}", but no sample row was seeded there: use the row's id.`);
|
|
174
179
|
row[field.name] = id;
|
|
175
180
|
}
|
|
176
181
|
return { kind: 'ok', value: row };
|
|
177
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;
|
|
178
203
|
/** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */
|
|
179
204
|
async function writeRecords(verb, tableName, { adapter, table: rawTable }, mutation, mutationName, inputs) {
|
|
180
205
|
const words = WORDS[verb];
|
|
@@ -196,7 +221,7 @@ async function writeRecords(verb, tableName, { adapter, table: rawTable }, mutat
|
|
|
196
221
|
failedRows.push({ index, message: words.noRow });
|
|
197
222
|
continue;
|
|
198
223
|
}
|
|
199
|
-
if (isSuspended(result.errors)) {
|
|
224
|
+
if ((0, exports.isSuspended)(result.errors)) {
|
|
200
225
|
suspended = true;
|
|
201
226
|
break;
|
|
202
227
|
}
|
|
@@ -219,7 +244,7 @@ async function writeRecords(verb, tableName, { adapter, table: rawTable }, mutat
|
|
|
219
244
|
};
|
|
220
245
|
const failed = (failure) => recordsFailed(failure, { ...(rows.length > 0 ? details : {}), ...(failedRows.length > 0 ? { failedRows } : {}) });
|
|
221
246
|
if (suspended) {
|
|
222
|
-
const message = rows.length > 0 ? `${UNAVAILABLE} ${rows.length} row(s) were ${done} before it stopped.` : `${UNAVAILABLE} No rows were ${done}.`;
|
|
247
|
+
const message = rows.length > 0 ? `${exports.UNAVAILABLE} ${rows.length} row(s) were ${done} before it stopped.` : `${exports.UNAVAILABLE} No rows were ${done}.`;
|
|
223
248
|
return failed({ code: 'database-unavailable', message });
|
|
224
249
|
}
|
|
225
250
|
if (rows.length === 0) {
|
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
|
}),
|
|
@@ -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 {};
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.deleteRecordsTool = void 0;
|
|
4
|
+
exports.deleteRecordsPlan = deleteRecordsPlan;
|
|
5
|
+
const harness_1 = require("@agentic-kit/harness");
|
|
6
|
+
const generators_1 = require("@constructive-io/graphql-query/generators");
|
|
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
|
+
const delete_effects_1 = require("../records/delete-effects");
|
|
12
|
+
const delete_selection_1 = require("../records/delete-selection");
|
|
13
|
+
const meta_1 = require("../records/meta");
|
|
14
|
+
const rows_1 = require("../records/rows");
|
|
15
|
+
const DeleteTableZod = (0, harness_1.strictObject)('a table', {
|
|
16
|
+
table_name: (0, harness_1.identifierParam)().describe('Name of the table to delete rows from (snake_case, singular or plural).'),
|
|
17
|
+
rows: zod_1.z
|
|
18
|
+
.array(zod_1.z.union([zod_1.z.string(), zod_1.z.number()]))
|
|
19
|
+
.min(1)
|
|
20
|
+
.describe('The rows to delete, by primary key, or "@<table>[<index>]" for a sample row seeded when the app was built.')
|
|
21
|
+
.optional(),
|
|
22
|
+
where: zod_1.z
|
|
23
|
+
.record(zod_1.z.string(), zod_1.z.unknown())
|
|
24
|
+
.describe('Delete every row whose columns have these values: column name (snake_case) -> value; null matches an empty column.')
|
|
25
|
+
.optional(),
|
|
26
|
+
sample: zod_1.z.literal(true).describe('Delete every sample row seeded when the app was built that is still there.').optional(),
|
|
27
|
+
all: zod_1.z.literal(true).describe('Delete every row of the table that the person signed in to the app can see.').optional(),
|
|
28
|
+
});
|
|
29
|
+
const DeleteRecordsZod = (0, harness_1.strictObject)('the input', {
|
|
30
|
+
tables: zod_1.z
|
|
31
|
+
.array(DeleteTableZod)
|
|
32
|
+
.min(1)
|
|
33
|
+
.max(20)
|
|
34
|
+
.describe('The tables to delete rows from, each with exactly one of rows, where, sample or all.'),
|
|
35
|
+
});
|
|
36
|
+
/** The plan of a records delete: the exact rows as the target, and the card's preview. */
|
|
37
|
+
function deleteRecordsPlan({ context, userId, selection, notes }) {
|
|
38
|
+
return {
|
|
39
|
+
target: { ...(0, ready_1.databaseTarget)(context, userId), rows: selection.tables.map(({ tableName, keys }) => ({ tableName, keys })) },
|
|
40
|
+
preview: { kind: 'delete-records', ...selection },
|
|
41
|
+
...(notes.length ? { notes } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const sameTarget = (a, b) => a.database.id === b.database.id && a.apiEndpoint === b.apiEndpoint && a.account.userId === b.account.userId &&
|
|
45
|
+
a.account.agent?.principalId === b.account.agent?.principalId && a.appUserId === b.appUserId;
|
|
46
|
+
/** The app table and key of each table of the rows to delete, still on the app API with a delete. */
|
|
47
|
+
function plannedRows(tables, rows) {
|
|
48
|
+
const planned = [];
|
|
49
|
+
for (const { tableName, keys } of rows) {
|
|
50
|
+
const table = tables.find((candidate) => (0, delete_effects_1.sqlName)(candidate) === tableName);
|
|
51
|
+
const key = table && (0, rows_1.primaryKeyOf)(table);
|
|
52
|
+
if (!table || !key || !table.query?.delete) {
|
|
53
|
+
return {
|
|
54
|
+
kind: 'failed',
|
|
55
|
+
failure: {
|
|
56
|
+
code: 'failed',
|
|
57
|
+
message: `${tableName} changed on the app API after its rows were chosen, so nothing was deleted.`,
|
|
58
|
+
hint: 'Review the rows and approve a new request.',
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
planned.push({ tableName, table, keyName: key.name, keys });
|
|
63
|
+
}
|
|
64
|
+
return { kind: 'ok', value: planned };
|
|
65
|
+
}
|
|
66
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
|
|
67
|
+
const NO_ROW_DELETED = 'The backend answered without the deleted row, so it does not exist, or this account may not delete it.';
|
|
68
|
+
/** One delete per row, in order, until the database is suspended, and the call's result from each row's answer. */
|
|
69
|
+
async function deleteRows({ adapter, tables }, planned, kept) {
|
|
70
|
+
const all = tables.map(meta_1.cleanTable);
|
|
71
|
+
const results = [];
|
|
72
|
+
const errors = [];
|
|
73
|
+
let suspended = false;
|
|
74
|
+
for (const { tableName, table: rawTable, keyName, keys } of planned) {
|
|
75
|
+
if (suspended)
|
|
76
|
+
break;
|
|
77
|
+
const table = (0, meta_1.cleanTable)(rawTable);
|
|
78
|
+
const mutation = (0, generators_1.buildPostGraphileDelete)(table, all).toString();
|
|
79
|
+
const mutationName = (0, generators_1.toDeleteMutationName)(table.name, table);
|
|
80
|
+
const result = { tableName, deleted: 0, failed: [] };
|
|
81
|
+
results.push(result);
|
|
82
|
+
for (const key of keys) {
|
|
83
|
+
let rowErrors;
|
|
84
|
+
try {
|
|
85
|
+
const answer = await adapter.execute(mutation, { input: { [keyName]: key } });
|
|
86
|
+
if (answer.ok) {
|
|
87
|
+
if (answer.data?.[mutationName])
|
|
88
|
+
result.deleted += 1;
|
|
89
|
+
else
|
|
90
|
+
result.failed.push({ key, message: NO_ROW_DELETED });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if ((0, rows_1.isSuspended)(answer.errors)) {
|
|
94
|
+
suspended = true;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
rowErrors = answer.errors;
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
// The request threw before any answer came back, so the error is the local one.
|
|
101
|
+
rowErrors = [{ message: (0, graphql_http_1.thrownText)(err), extensions: { code: 'NETWORK' } }];
|
|
102
|
+
}
|
|
103
|
+
errors.push(...rowErrors);
|
|
104
|
+
result.failed.push({ key, message: (0, graphql_http_1.answerText)(rowErrors) });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const deletedCount = results.reduce((sum, result) => sum + result.deleted, 0);
|
|
108
|
+
const failedCount = results.reduce((sum, result) => sum + result.failed.length, 0);
|
|
109
|
+
const details = { deletedCount, tables: [...results, ...kept.map((tableName) => ({ tableName, deleted: 0, kept: true, failed: [] }))] };
|
|
110
|
+
const done = results.filter((result) => result.deleted > 0);
|
|
111
|
+
const message = [
|
|
112
|
+
done.length ? `Deleted ${(0, harness_1.listed)(done.map((result, index) => `${index === 0 ? plural(result.deleted, 'row') : result.deleted} from ${result.tableName}`))}.` : '',
|
|
113
|
+
...results.filter((result) => result.failed.length > 0).map(({ tableName, failed: [first, ...rest] }) => `${plural(rest.length + 1, 'row')} of ${tableName} ${rest.length ? 'were' : 'was'} not deleted (${first.key}: ${first.message}).`),
|
|
114
|
+
kept.length ? `Nothing was deleted from ${(0, harness_1.listed)(kept)}: the person unticked ${kept.length === 1 ? 'it, or it' : 'them, or they'} had no rows to delete.` : '',
|
|
115
|
+
].filter(Boolean).join(' ');
|
|
116
|
+
const failed = (failure) => (0, rows_1.recordsFailed)(failure, details);
|
|
117
|
+
if (suspended) {
|
|
118
|
+
const before = deletedCount === 0 ? 'No rows were deleted.' : `${deletedCount === 1 ? '1 row was' : `${deletedCount} rows were`} deleted before it stopped.`;
|
|
119
|
+
return failed({ code: 'database-unavailable', message: `${rows_1.UNAVAILABLE} ${before}` });
|
|
120
|
+
}
|
|
121
|
+
if (failedCount > 0 && deletedCount === 0) {
|
|
122
|
+
const action = `Failed to delete rows from ${(0, harness_1.listed)(results.map((result) => result.tableName))}`;
|
|
123
|
+
return failed(errors.length ? (0, failure_1.failureFromErrors)(errors, action, { rows: { table: results[0].tableName } }) : (0, failure_1.noRowsChanged)(action, failure_1.DESCRIBE_SCHEMA));
|
|
124
|
+
}
|
|
125
|
+
if (failedCount > 0) {
|
|
126
|
+
return failed({
|
|
127
|
+
code: 'partial',
|
|
128
|
+
message,
|
|
129
|
+
hint: 'Fix what the backend said about the rows in details.tables, then call again with only those rows: the deleted rows are gone.',
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } };
|
|
133
|
+
}
|
|
134
|
+
/** Why the approved rows cannot go while the person keeps the table that `effect` reaches, and what to do instead. */
|
|
135
|
+
function keptReached(effect) {
|
|
136
|
+
const { parent, child } = effect;
|
|
137
|
+
const what = effect.effect === 'cascade'
|
|
138
|
+
? `deleting ${parent} deletes them too`
|
|
139
|
+
: effect.effect === 'set_null'
|
|
140
|
+
? `deleting ${parent} clears ${(0, harness_1.listed)(effect.columns)} on them`
|
|
141
|
+
: effect.effect === 'set_default'
|
|
142
|
+
? `deleting ${parent} sets ${(0, harness_1.listed)(effect.columns)} to ${effect.columns.length === 1 ? 'its default' : 'their defaults'} on them`
|
|
143
|
+
: `${parent} rows can't be deleted while they're there`;
|
|
144
|
+
return `You kept ${child}, but ${(0, delete_effects_1.rowsOf)(effect)} ${(0, delete_effects_1.pointOf)(effect)} at ${parent} you'd delete, and ${what}. Approve again with ${child} ticked, or keep ${parent} too.`;
|
|
145
|
+
}
|
|
146
|
+
/** Why the check could not rule out that the approved rows reach `table`, which the person kept, and what to do. */
|
|
147
|
+
function keptNotChecked(effect, table) {
|
|
148
|
+
if (effect.upTo)
|
|
149
|
+
return `Nothing was deleted: there are too many related rows to check that ${table} stays untouched. Delete in smaller steps, or tick ${table}.`;
|
|
150
|
+
const why = effect.uncounted
|
|
151
|
+
? `the ${effect.child} rows that point at ${effect.parent} can't be counted`
|
|
152
|
+
: `the rows that point at the ${effect.child} rows it deletes can't be followed`;
|
|
153
|
+
return `Nothing was deleted: ${why}, so it can't check that ${table} stays untouched. Tick ${table}, or keep ${effect.parent} too.`;
|
|
154
|
+
}
|
|
155
|
+
exports.deleteRecordsTool = {
|
|
156
|
+
name: 'delete_records',
|
|
157
|
+
label: 'Delete records',
|
|
158
|
+
description: "Delete rows from one or more tables in the project's app database: rows named by primary key, the rows whose columns have given values, the sample rows seeded when the app was built, or every row. One call for every table: the person sees the exact rows first and can keep any table.",
|
|
159
|
+
promptSnippet: 'delete_records: delete rows from one or many tables, by key, by column values, the sample rows, or all rows. Gated.',
|
|
160
|
+
parameters: DeleteRecordsZod,
|
|
161
|
+
effect: 'write',
|
|
162
|
+
async execute(params, ctx) {
|
|
163
|
+
const approved = ctx.toolCallId ? (0, harness_1.takeApprovedTable)(ctx.toolCallId, ctx.cwd) : undefined;
|
|
164
|
+
const fail = (failure) => (0, rows_1.recordsFailed)(failure, { deletedCount: 0, tables: [] });
|
|
165
|
+
if (!approved?.rows) {
|
|
166
|
+
// The same checks as the gate, so a call that cannot run fails the same way; a call that can still deletes
|
|
167
|
+
// nothing, because only an approved target says which rows the person saw and kept.
|
|
168
|
+
const ready = await (0, delete_selection_1.deleteRecordsReady)(params, ctx.cwd);
|
|
169
|
+
if (ready.kind === 'failed')
|
|
170
|
+
return fail(ready.failure);
|
|
171
|
+
return fail({
|
|
172
|
+
code: 'failed',
|
|
173
|
+
message: 'This delete has no approval (it may have expired), so nothing was deleted. Ask again to see the rows and approve them.',
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
const ready = await (0, rows_1.appReady)(ctx.cwd, 'deleted');
|
|
177
|
+
if (ready.kind === 'failed')
|
|
178
|
+
return fail(ready.failure);
|
|
179
|
+
if (!sameTarget(approved, (0, ready_1.databaseTarget)(ready.value.context, ready.value.userId))) {
|
|
180
|
+
return fail({
|
|
181
|
+
code: 'failed',
|
|
182
|
+
message: 'The current project or app sign-in does not match the approved delete target, so nothing was deleted.',
|
|
183
|
+
hint: 'Review the rows and approve a new request.',
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
const planned = plannedRows(ready.value.tables, approved.rows);
|
|
187
|
+
if (planned.kind === 'failed')
|
|
188
|
+
return fail(planned.failure);
|
|
189
|
+
// A table of the input that the approved rows leave out was unticked, or had no rows when the card was built.
|
|
190
|
+
const approvedTables = new Set(planned.value.map((entry) => entry.table));
|
|
191
|
+
const kept = params.tables
|
|
192
|
+
.map((input) => (0, meta_1.findMetaTable)(ready.value.tables, input.table_name))
|
|
193
|
+
.filter((table) => Boolean(table) && !approvedTables.has(table))
|
|
194
|
+
.map(delete_effects_1.sqlName);
|
|
195
|
+
if (kept.length > 0) {
|
|
196
|
+
const found = await (0, delete_effects_1.deleteEffects)(ready.value, approved.rows);
|
|
197
|
+
if (found.kind === 'failed')
|
|
198
|
+
return fail(found.failure);
|
|
199
|
+
const { effects, model } = found.value;
|
|
200
|
+
const reached = effects.find((effect) => !effect.uncounted && kept.includes(effect.child));
|
|
201
|
+
if (reached)
|
|
202
|
+
return fail({ code: 'conflict', message: keptReached(reached) });
|
|
203
|
+
// An effect the check could not count or follow may still reach a kept table, so it counts as reaching it.
|
|
204
|
+
for (const effect of effects) {
|
|
205
|
+
const table = (0, delete_effects_1.tablesNotChecked)(effect, model).find((name) => kept.includes(name));
|
|
206
|
+
if (table)
|
|
207
|
+
return fail({ code: 'conflict', message: keptNotChecked(effect, table) });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return deleteRows(ready.value, planned.value, kept);
|
|
211
|
+
},
|
|
212
|
+
};
|
package/tools/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AnyHarnessTool, PlanTableAccess, PlanTarget } from '@agentic-kit/harness';
|
|
1
|
+
import type { AnyHarnessTool, ConfirmPreview, PlanTableAccess, PlanTarget } from '@agentic-kit/harness';
|
|
2
2
|
import type { Result } from '../failure';
|
|
3
3
|
/**
|
|
4
4
|
* The Constructive database tools, in registration order.
|
|
@@ -8,11 +8,15 @@ import type { Result } from '../failure';
|
|
|
8
8
|
* dependency (see `toPiTool` in `@agentic-kit/pi` for that binding).
|
|
9
9
|
*/
|
|
10
10
|
export declare const constructiveDbTools: readonly AnyHarnessTool[];
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* What a plan names that the tool's check resolved: its target, the access of the tables it creates or changes, what
|
|
13
|
+
* it must say that the input does not, and the card's preview when only the check can build it.
|
|
14
|
+
*/
|
|
12
15
|
export type Resolved = {
|
|
13
16
|
target: PlanTarget;
|
|
14
17
|
access?: PlanTableAccess[];
|
|
15
18
|
notes?: string[];
|
|
19
|
+
preview?: ConfirmPreview;
|
|
16
20
|
};
|
|
17
21
|
type Precondition = (params: any, cwd: string) => Promise<Result<Resolved>>;
|
|
18
22
|
/**
|
package/tools/index.js
CHANGED
|
@@ -5,6 +5,7 @@ const access_1 = require("../access");
|
|
|
5
5
|
const field_type_1 = require("../blueprint/field-type");
|
|
6
6
|
const provision_1 = require("../provision-database/provision");
|
|
7
7
|
const ready_1 = require("../ready");
|
|
8
|
+
const delete_selection_1 = require("../records/delete-selection");
|
|
8
9
|
const schema_resolve_1 = require("../schema-resolve");
|
|
9
10
|
const table_access_1 = require("../table-access");
|
|
10
11
|
const access_2 = require("./access");
|
|
@@ -12,6 +13,7 @@ const add_policies_1 = require("./add-policies");
|
|
|
12
13
|
const add_records_1 = require("./add-records");
|
|
13
14
|
const add_relation_1 = require("./add-relation");
|
|
14
15
|
const create_api_key_1 = require("./create-api-key");
|
|
16
|
+
const delete_records_1 = require("./delete-records");
|
|
15
17
|
const describe_schema_1 = require("./describe-schema");
|
|
16
18
|
const entity_types_1 = require("./entity-types");
|
|
17
19
|
const mutations_1 = require("./mutations");
|
|
@@ -46,6 +48,7 @@ exports.constructiveDbTools = [
|
|
|
46
48
|
templates_1.deleteTemplateTool,
|
|
47
49
|
add_records_1.addRecordsTool,
|
|
48
50
|
update_records_1.updateRecordsTool,
|
|
51
|
+
delete_records_1.deleteRecordsTool,
|
|
49
52
|
entity_types_1.listEntityTypesTool,
|
|
50
53
|
entity_types_1.createEntityTypeTool,
|
|
51
54
|
entity_types_1.deleteEntityTypeTool,
|
|
@@ -138,6 +141,13 @@ exports.toolPreconditions = new Map([
|
|
|
138
141
|
[templates_1.deleteTemplateTool.name, targeting(templates_1.templateReady, ({ context }) => (0, ready_1.accountTarget)(context))],
|
|
139
142
|
[add_records_1.addRecordsTool.name, targeting(add_records_1.addRecordsReady, ({ context, userId }) => (0, ready_1.databaseTarget)(context, userId))],
|
|
140
143
|
[update_records_1.updateRecordsTool.name, targeting(update_records_1.updateRecordsReady, ({ context, userId }) => (0, ready_1.databaseTarget)(context, userId))],
|
|
144
|
+
[
|
|
145
|
+
delete_records_1.deleteRecordsTool.name,
|
|
146
|
+
async (params, cwd) => {
|
|
147
|
+
const ready = await (0, delete_selection_1.deleteRecordsReady)(params, cwd);
|
|
148
|
+
return ready.kind === 'failed' ? ready : { kind: 'ok', value: (0, delete_records_1.deleteRecordsPlan)(ready.value) };
|
|
149
|
+
},
|
|
150
|
+
],
|
|
141
151
|
[entity_types_1.listEntityTypesTool.name, onDatabase(project)],
|
|
142
152
|
[entity_types_1.createEntityTypeTool.name, onDatabase(entity_types_1.createEntityTypeReady)],
|
|
143
153
|
[entity_types_1.deleteEntityTypeTool.name, onDatabase(entity_types_1.deleteEntityTypeReady)],
|