@agentic-kit/db-tools 0.14.0 → 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/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
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// What a records delete does to rows it does not select, counted on the app API as the person signed in to the app:
|
|
3
|
+
// the rows that point at the deleted rows, by the foreign keys the schema model reads.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.pointOf = exports.rowsOf = exports.sqlName = exports.MAX_DELETED_ROWS = void 0;
|
|
6
|
+
exports.readRows = readRows;
|
|
7
|
+
exports.effectLine = effectLine;
|
|
8
|
+
exports.linksOf = linksOf;
|
|
9
|
+
exports.tablesNotChecked = tablesNotChecked;
|
|
10
|
+
exports.deleteEffects = deleteEffects;
|
|
11
|
+
const harness_1 = require("@agentic-kit/harness");
|
|
12
|
+
const generators_1 = require("@constructive-io/graphql-query/generators");
|
|
13
|
+
const failure_1 = require("../failure");
|
|
14
|
+
const schema_model_1 = require("../schema-model");
|
|
15
|
+
const meta_1 = require("./meta");
|
|
16
|
+
const rows_1 = require("./rows");
|
|
17
|
+
/** The most rows one call deletes, over all its tables, and the most rows its effects read. */
|
|
18
|
+
exports.MAX_DELETED_ROWS = 500;
|
|
19
|
+
/** The SQL name of an app table, as the person and the schema model name it. */
|
|
20
|
+
const sqlName = (table) => table.tableName ?? table.name;
|
|
21
|
+
exports.sqlName = sqlName;
|
|
22
|
+
/** The first rows the filter selects, with the given fields, and how many it selects in all. */
|
|
23
|
+
async function readRows(ready, { name, table }, filter, select, first) {
|
|
24
|
+
const clean = (0, meta_1.cleanTable)(table);
|
|
25
|
+
const variables = { first, ...(filter ? { where: filter } : {}) };
|
|
26
|
+
const query = (0, generators_1.buildSelect)(clean, ready.tables.map(meta_1.cleanTable), { ...variables, fieldSelection: { select } }).toString();
|
|
27
|
+
const action = `Failed to read the rows of ${name}`;
|
|
28
|
+
try {
|
|
29
|
+
const result = await ready.adapter.execute(query, variables);
|
|
30
|
+
if (!result.ok) {
|
|
31
|
+
const failure = (0, rows_1.isSuspended)(result.errors)
|
|
32
|
+
? { code: 'database-unavailable', message: `${rows_1.UNAVAILABLE} No rows were deleted.` }
|
|
33
|
+
: (0, failure_1.failureFromErrors)(result.errors, action, { rows: { table: name } });
|
|
34
|
+
return { kind: 'failed', failure };
|
|
35
|
+
}
|
|
36
|
+
const connection = result.data?.[(0, generators_1.toCamelCasePlural)(clean.name, clean)];
|
|
37
|
+
const nodes = (connection?.nodes ?? []).filter((node) => Boolean(node));
|
|
38
|
+
return { kind: 'ok', value: { total: connection?.totalCount ?? nodes.length, nodes } };
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, action) };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const EFFECTS = {
|
|
45
|
+
cascade: 'cascade',
|
|
46
|
+
set_null: 'set_null',
|
|
47
|
+
set_default: 'set_default',
|
|
48
|
+
restrict: 'restrict',
|
|
49
|
+
no_action: 'restrict',
|
|
50
|
+
};
|
|
51
|
+
const rowsOf = (effect) => {
|
|
52
|
+
const count = effect.upTo ?? effect.rows;
|
|
53
|
+
return `${effect.upTo ? 'up to ' : ''}${count} ${effect.child} row${count === 1 ? '' : 's'}`;
|
|
54
|
+
};
|
|
55
|
+
exports.rowsOf = rowsOf;
|
|
56
|
+
const one = (effect) => !effect.upTo && effect.rows === 1;
|
|
57
|
+
/** "points" for one row, "point" for more. */
|
|
58
|
+
const pointOf = (effect) => (one(effect) ? 'points' : 'point');
|
|
59
|
+
exports.pointOf = pointOf;
|
|
60
|
+
/** One plain line for the card. */
|
|
61
|
+
function effectLine(effect) {
|
|
62
|
+
if (effect.uncounted)
|
|
63
|
+
return `Deleting ${effect.parent} may also change the ${effect.child} rows that point at them (not counted).`;
|
|
64
|
+
const point = (0, exports.pointOf)(effect);
|
|
65
|
+
switch (effect.effect) {
|
|
66
|
+
case 'cascade': {
|
|
67
|
+
const further = effect.unfollowed ? ', and the rows that point at those go too, not counted' : '';
|
|
68
|
+
return `Also deletes ${(0, exports.rowsOf)(effect)} that ${point} at the ${effect.parent} you delete${further}.`;
|
|
69
|
+
}
|
|
70
|
+
case 'set_null':
|
|
71
|
+
return `Clears ${(0, harness_1.listed)(effect.columns)} on ${(0, exports.rowsOf)(effect)} that ${point} at the ${effect.parent} you delete.`;
|
|
72
|
+
case 'set_default': {
|
|
73
|
+
const defaults = effect.columns.length === 1 ? 'its default' : 'their defaults';
|
|
74
|
+
return `Sets ${(0, harness_1.listed)(effect.columns)} to ${defaults} on ${(0, exports.rowsOf)(effect)} that ${point} at the ${effect.parent} you delete.`;
|
|
75
|
+
}
|
|
76
|
+
case 'restrict': {
|
|
77
|
+
const parents = effect.upTo ? `Some ${effect.parent} rows` : `${effect.parents} ${effect.parent} row${effect.parents === 1 ? '' : 's'}`;
|
|
78
|
+
return `${parents} can't be deleted while ${(0, exports.rowsOf)(effect)} ${point} at ${effect.parents === 1 && !effect.upTo ? 'it' : 'them'}.`;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** The foreign keys between the tables a delete names, one for each child, parent and effect, for the card to warn with. */
|
|
83
|
+
function linksOf(names, model) {
|
|
84
|
+
const named = new Set(names);
|
|
85
|
+
const links = new Map();
|
|
86
|
+
for (const child of model.tables.filter((table) => named.has(table.name))) {
|
|
87
|
+
for (const fk of child.foreignKeys) {
|
|
88
|
+
const effect = EFFECTS[fk.onDelete];
|
|
89
|
+
if (fk.targetTable === child.name || !named.has(fk.targetTable))
|
|
90
|
+
continue;
|
|
91
|
+
// A set-default key loses its link the way a set-null key does, which is what the card warns about.
|
|
92
|
+
const link = effect === 'set_default' ? 'set_null' : effect;
|
|
93
|
+
links.set(JSON.stringify([fk.targetTable, child.name, link]), { parent: fk.targetTable, child: child.name, effect: link });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return [...links.values()];
|
|
97
|
+
}
|
|
98
|
+
/** Every table whose rows point at rows of `table`, directly or through other tables. */
|
|
99
|
+
function pointingAt(table, model) {
|
|
100
|
+
const reached = new Set();
|
|
101
|
+
const queue = [table];
|
|
102
|
+
while (queue.length > 0) {
|
|
103
|
+
const parent = queue.shift();
|
|
104
|
+
for (const child of model.tables.filter((other) => other.foreignKeys.some((fk) => fk.targetTable === parent))) {
|
|
105
|
+
if (reached.has(child.name))
|
|
106
|
+
continue;
|
|
107
|
+
reached.add(child.name);
|
|
108
|
+
queue.push(child.name);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return reached;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The tables an effect may change that it does not count: its own table when its rows were not counted, and when its
|
|
115
|
+
* rows go and were not all followed, every table whose rows point at them.
|
|
116
|
+
*/
|
|
117
|
+
function tablesNotChecked(effect, model) {
|
|
118
|
+
const own = effect.uncounted ? [effect.child] : [];
|
|
119
|
+
const further = effect.effect === 'cascade' && (effect.uncounted || effect.upTo || effect.unfollowed) ? pointingAt(effect.child, model) : [];
|
|
120
|
+
return [...new Set([...own, ...further])];
|
|
121
|
+
}
|
|
122
|
+
/** The ids of the search chunk tables the backend keeps for the database's tables (`embedding_chunks`). */
|
|
123
|
+
async function chunkTableIds({ api, databaseId }) {
|
|
124
|
+
const data = await api.embeddingChunk
|
|
125
|
+
.findMany({ select: { chunksTableId: true }, where: { databaseId: { equalTo: databaseId } } })
|
|
126
|
+
.unwrap();
|
|
127
|
+
return new Set((data.embeddingChunks?.nodes ?? []).flatMap((node) => (node?.chunksTableId ? [node.chunksTableId] : [])));
|
|
128
|
+
}
|
|
129
|
+
const isKey = (value) => typeof value === 'string' || typeof value === 'number';
|
|
130
|
+
/**
|
|
131
|
+
* The child field the key sets, and the values it has on the rows that point at the deleted parent rows: their keys,
|
|
132
|
+
* or for a key on another unique column, that column read from them. Null when the key cannot be read that way.
|
|
133
|
+
*/
|
|
134
|
+
async function linkValues(ready, parent, keys, fk, childTable) {
|
|
135
|
+
const at = fk.targetColumns.indexOf((0, rows_1.columnOf)(parent.key));
|
|
136
|
+
if (at >= 0) {
|
|
137
|
+
const field = (0, rows_1.fieldNamed)(childTable, fk.columns[at]);
|
|
138
|
+
return { kind: 'ok', value: field ? { field, values: [...keys] } : null };
|
|
139
|
+
}
|
|
140
|
+
const target = fk.targetColumns.length === 1 ? (0, rows_1.fieldNamed)(parent.table, fk.targetColumns[0]) : undefined;
|
|
141
|
+
const field = (0, rows_1.fieldNamed)(childTable, fk.columns[0]);
|
|
142
|
+
if (!target || !field)
|
|
143
|
+
return { kind: 'ok', value: null };
|
|
144
|
+
const read = await readRows(ready, parent, { [parent.key.name]: { in: keys } }, [target.name], keys.length + 1);
|
|
145
|
+
if (read.kind === 'failed')
|
|
146
|
+
return read;
|
|
147
|
+
return { kind: 'ok', value: { field, values: read.value.nodes.map((node) => node[target.name]).filter((value) => value !== null && value !== undefined) } };
|
|
148
|
+
}
|
|
149
|
+
const entryOf = (parent, child, effect) => ({
|
|
150
|
+
effect: { parent, child, effect, columns: [], rows: 0, parents: 0 },
|
|
151
|
+
rows: new Set(),
|
|
152
|
+
keyless: 0,
|
|
153
|
+
parents: new Set(),
|
|
154
|
+
columns: new Set(),
|
|
155
|
+
});
|
|
156
|
+
/**
|
|
157
|
+
* The schema model, and what deleting the selected rows does to the rows that point at them and are not selected, and
|
|
158
|
+
* through a cascade to the rows that point at those, each row followed once, over at most 500 rows read: one
|
|
159
|
+
* effect for each table, kind of effect and table it points at, with the union of the columns. A search chunk table the
|
|
160
|
+
* backend keeps is left out, because its rows always go with their parent row. A table with no rows there gives none.
|
|
161
|
+
*/
|
|
162
|
+
async function deleteEffects(ready, selected) {
|
|
163
|
+
let model;
|
|
164
|
+
let chunks;
|
|
165
|
+
try {
|
|
166
|
+
[model, chunks] = await Promise.all([(0, schema_model_1.readSchemaModel)(ready.context), chunkTableIds(ready.context)]);
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to read the foreign keys of the project database') };
|
|
170
|
+
}
|
|
171
|
+
const tables = new Map(ready.tables.map((table) => [(0, exports.sqlName)(table), table]));
|
|
172
|
+
const going = new Map(selected.map(({ tableName, keys }) => [tableName, new Set(keys)]));
|
|
173
|
+
const queue = selected.map(({ tableName, keys }) => ({ parent: tableName, keys: [...keys] }));
|
|
174
|
+
const found = new Map();
|
|
175
|
+
const pointedAt = (table) => model.tables.some((other) => !chunks.has(other.id) && other.foreignKeys.some((fk) => fk.targetTable === table));
|
|
176
|
+
let budget = exports.MAX_DELETED_ROWS;
|
|
177
|
+
while (queue.length > 0) {
|
|
178
|
+
const { parent, keys } = queue.shift();
|
|
179
|
+
const parentTable = tables.get(parent);
|
|
180
|
+
const parentKey = parentTable && (0, rows_1.primaryKeyOf)(parentTable);
|
|
181
|
+
if (!parentKey)
|
|
182
|
+
continue;
|
|
183
|
+
for (const child of model.tables.filter((table) => !chunks.has(table.id))) {
|
|
184
|
+
const childTable = tables.get(child.name);
|
|
185
|
+
// Without a single-column key the rows are counted, but they cannot be told apart or followed further.
|
|
186
|
+
const childKey = childTable && (0, rows_1.primaryKeyOf)(childTable);
|
|
187
|
+
const toParent = child.foreignKeys.filter((key) => key.targetTable === parent);
|
|
188
|
+
// Rows without a key cannot be told apart, so two keys to the parent could count one row twice.
|
|
189
|
+
const countable = childTable && (childKey || toParent.length === 1);
|
|
190
|
+
for (const fk of toParent) {
|
|
191
|
+
const effect = EFFECTS[fk.onDelete];
|
|
192
|
+
const id = JSON.stringify([parent, child.name, effect]);
|
|
193
|
+
const link = countable ? await linkValues(ready, { name: parent, table: parentTable, key: parentKey }, keys, fk, childTable) : undefined;
|
|
194
|
+
if (link?.kind === 'failed')
|
|
195
|
+
return link;
|
|
196
|
+
if (!childTable || !link?.value) {
|
|
197
|
+
found.set(id, { ...(found.get(id) ?? entryOf(parent, child.name, effect)), uncounted: true });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const { field, values } = link.value;
|
|
201
|
+
if (values.length === 0)
|
|
202
|
+
continue;
|
|
203
|
+
const select = childKey ? [childKey.name, field.name] : [field.name];
|
|
204
|
+
const read = await readRows(ready, { name: child.name, table: childTable }, { [field.name]: { in: values } }, select, budget + 1);
|
|
205
|
+
if (read.kind === 'failed')
|
|
206
|
+
return read;
|
|
207
|
+
budget = Math.max(0, budget - read.value.nodes.length);
|
|
208
|
+
const own = going.get(child.name);
|
|
209
|
+
const outside = childKey ? read.value.nodes.filter((node) => !own?.has(node[childKey.name])) : read.value.nodes;
|
|
210
|
+
const truncated = childKey !== undefined && read.value.total > read.value.nodes.length;
|
|
211
|
+
if (outside.length === 0 && !truncated)
|
|
212
|
+
continue;
|
|
213
|
+
const entry = found.get(id) ?? entryOf(parent, child.name, effect);
|
|
214
|
+
found.set(id, entry);
|
|
215
|
+
(fk.deleteSetColumns ?? fk.columns).forEach((column) => entry.columns.add(column));
|
|
216
|
+
for (const node of outside) {
|
|
217
|
+
if (childKey && isKey(node[childKey.name]))
|
|
218
|
+
entry.rows.add(node[childKey.name]);
|
|
219
|
+
if (isKey(node[field.name]))
|
|
220
|
+
entry.parents.add(node[field.name]);
|
|
221
|
+
}
|
|
222
|
+
if (!childKey) {
|
|
223
|
+
entry.keyless += read.value.total;
|
|
224
|
+
if (effect === 'cascade' && pointedAt(child.name))
|
|
225
|
+
entry.effect.unfollowed = true;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (truncated) {
|
|
229
|
+
// Past the read limit the count is only an upper bound, so this branch stops here.
|
|
230
|
+
entry.effect.upTo = Math.max(entry.effect.upTo ?? 0, read.value.total);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (effect !== 'cascade')
|
|
234
|
+
continue;
|
|
235
|
+
// The cascaded rows go too, so the rows that point at them are followed once each.
|
|
236
|
+
const cascaded = outside.map((node) => node[childKey.name]).filter(isKey);
|
|
237
|
+
going.set(child.name, new Set([...(own ?? []), ...cascaded]));
|
|
238
|
+
queue.push({ parent: child.name, keys: cascaded });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const effects = [...found.values()].map(({ effect, rows, keyless, parents, columns, uncounted }) => ({
|
|
243
|
+
...effect,
|
|
244
|
+
columns: [...columns],
|
|
245
|
+
rows: rows.size + keyless,
|
|
246
|
+
parents: parents.size,
|
|
247
|
+
...(uncounted ? { uncounted } : {}),
|
|
248
|
+
}));
|
|
249
|
+
return { kind: 'ok', value: { model, effects } };
|
|
250
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type DeleteRecordsLink, type DeleteRecordsTable } from '@agentic-kit/harness';
|
|
2
|
+
import { type Result } from '../failure';
|
|
3
|
+
import { type AppReady } from './rows';
|
|
4
|
+
export type DeleteTableInput = {
|
|
5
|
+
table_name: string;
|
|
6
|
+
rows?: Array<string | number>;
|
|
7
|
+
where?: Record<string, unknown>;
|
|
8
|
+
sample?: true;
|
|
9
|
+
all?: true;
|
|
10
|
+
};
|
|
11
|
+
export type DeleteSelection = {
|
|
12
|
+
tables: DeleteRecordsTable[];
|
|
13
|
+
effects: string[];
|
|
14
|
+
links: DeleteRecordsLink[];
|
|
15
|
+
};
|
|
16
|
+
export type DeleteRecordsReady = AppReady & {
|
|
17
|
+
selection: DeleteSelection;
|
|
18
|
+
/** A table the input names that has no rows to delete, one sentence each. */
|
|
19
|
+
notes: string[];
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* What a records delete checks before it deletes anything, and the exact rows it deletes: one selector for each
|
|
23
|
+
* table, the project, an app sign-in, each table on the app's API with a key and a delete, the rows each selector
|
|
24
|
+
* names that are there (no more than 500 in all), the order that deletes a row before the rows it points at, and
|
|
25
|
+
* what the delete does to the rows it does not select.
|
|
26
|
+
*/
|
|
27
|
+
export declare function deleteRecordsReady(params: {
|
|
28
|
+
tables: DeleteTableInput[];
|
|
29
|
+
}, cwd: string): Promise<Result<DeleteRecordsReady>>;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The rows a records delete removes, resolved once from the call's input as the person signed in to the app: the
|
|
3
|
+
// gate's precondition and the tool both use `deleteRecordsReady`, so the card and the delete cannot disagree.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.deleteRecordsReady = deleteRecordsReady;
|
|
6
|
+
const harness_1 = require("@agentic-kit/harness");
|
|
7
|
+
const failure_1 = require("../failure");
|
|
8
|
+
const delete_effects_1 = require("./delete-effects");
|
|
9
|
+
const meta_1 = require("./meta");
|
|
10
|
+
const rows_1 = require("./rows");
|
|
11
|
+
const SELECTORS = ['rows', 'where', 'sample', 'all'];
|
|
12
|
+
/** The filter that selects the rows the input names, null when it names none, or why the input is not valid. */
|
|
13
|
+
function filterOf({ input, table, name, key }, seeded) {
|
|
14
|
+
if (input.rows) {
|
|
15
|
+
const keys = input.rows.map((value) => (0, rows_1.seededValue)(value, seeded));
|
|
16
|
+
const missing = input.rows.find((_, index) => keys[index] === undefined);
|
|
17
|
+
if (missing !== undefined)
|
|
18
|
+
return (0, rows_1.invalid)(`${name} names "${missing}", but no sample row was seeded there: use the row's ${key.columnName ?? key.name}.`);
|
|
19
|
+
return { kind: 'ok', value: { [key.name]: { in: keys } } };
|
|
20
|
+
}
|
|
21
|
+
if (input.where) {
|
|
22
|
+
const unknown = (0, rows_1.notAColumn)(table, name, Object.keys(input.where));
|
|
23
|
+
if (unknown)
|
|
24
|
+
return (0, rows_1.invalid)(`The where of ${name} names ${unknown}`);
|
|
25
|
+
const filter = {};
|
|
26
|
+
for (const [column, given] of Object.entries(input.where)) {
|
|
27
|
+
const value = (0, rows_1.seededValue)(given, seeded);
|
|
28
|
+
if (value === undefined)
|
|
29
|
+
return (0, rows_1.invalid)(`The where of ${name} names "${given}", but no sample row was seeded there: use the row's id.`);
|
|
30
|
+
filter[(0, rows_1.fieldNamed)(table, column).name] = value === null ? { isNull: true } : { equalTo: value };
|
|
31
|
+
}
|
|
32
|
+
return { kind: 'ok', value: filter };
|
|
33
|
+
}
|
|
34
|
+
if (input.sample) {
|
|
35
|
+
const ids = (seeded.get((0, rows_1.tableKey)(name)) ?? seeded.get((0, rows_1.tableKey)(input.table_name)) ?? []).filter((id) => Boolean(id));
|
|
36
|
+
return { kind: 'ok', value: ids.length ? { [key.name]: { in: ids } } : null };
|
|
37
|
+
}
|
|
38
|
+
return { kind: 'ok', value: undefined };
|
|
39
|
+
}
|
|
40
|
+
const NONE_LEFT = {
|
|
41
|
+
rows: (name) => `${name} has none of the rows given.`,
|
|
42
|
+
where: (name) => `${name} has no rows that match.`,
|
|
43
|
+
sample: (name) => `${name} has no sample rows left.`,
|
|
44
|
+
all: (name) => `${name} has no rows.`,
|
|
45
|
+
};
|
|
46
|
+
const selectorOf = (input) => SELECTORS.find((selector) => input[selector] !== undefined) ?? 'all';
|
|
47
|
+
const READABLE_TYPES = new Set(['String', 'Int', 'Float', 'BigFloat', 'BigInt', 'Boolean', 'Date', 'Datetime']);
|
|
48
|
+
/** Up to three columns that tell rows apart on the card, text first; keys of other rows say nothing to a person. */
|
|
49
|
+
function readableFields(table, key) {
|
|
50
|
+
return (0, rows_1.fieldsOf)(table)
|
|
51
|
+
.filter((field) => field !== key && !field.type.isArray && READABLE_TYPES.has(field.type.gqlType) && !/Id$/.test(field.name))
|
|
52
|
+
.sort((a, b) => Number(b.type.gqlType === 'String') - Number(a.type.gqlType === 'String'))
|
|
53
|
+
.slice(0, 3);
|
|
54
|
+
}
|
|
55
|
+
/** The tables in an order that deletes a row before the rows it points at: each table before the listed tables it points at. */
|
|
56
|
+
function childrenFirst(tables, model) {
|
|
57
|
+
const pointsAt = new Map(model.tables.map((table) => [table.name, new Set(table.foreignKeys.map((fk) => fk.targetTable))]));
|
|
58
|
+
const left = [...tables];
|
|
59
|
+
const ordered = [];
|
|
60
|
+
while (left.length > 0) {
|
|
61
|
+
const pointedAt = (table) => left.some((other) => other !== table && pointsAt.get(other.tableName)?.has(table.tableName));
|
|
62
|
+
// A cycle leaves no table that nothing points at, so the rest keep the order of the input.
|
|
63
|
+
const next = left.find((table) => !pointedAt(table)) ?? left[0];
|
|
64
|
+
ordered.push(next);
|
|
65
|
+
left.splice(left.indexOf(next), 1);
|
|
66
|
+
}
|
|
67
|
+
return ordered;
|
|
68
|
+
}
|
|
69
|
+
/** Every table the input names on the app API, once each, with a key the API deletes by. */
|
|
70
|
+
function pickTables(tables, inputs) {
|
|
71
|
+
const picked = [];
|
|
72
|
+
for (const input of inputs) {
|
|
73
|
+
const table = (0, meta_1.findMetaTable)(tables, input.table_name);
|
|
74
|
+
if (!table) {
|
|
75
|
+
const nearest = (0, harness_1.nearestName)(input.table_name, tables.map(delete_effects_1.sqlName));
|
|
76
|
+
return {
|
|
77
|
+
kind: 'failed',
|
|
78
|
+
failure: {
|
|
79
|
+
code: 'not-found',
|
|
80
|
+
message: `Table "${input.table_name}" was not found in the app database${nearest ? `: use "${nearest}".` : '.'}`,
|
|
81
|
+
hint: 'Check the table names that exist, then retry.',
|
|
82
|
+
calls: [failure_1.DESCRIBE_SCHEMA],
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
const name = (0, delete_effects_1.sqlName)(table);
|
|
87
|
+
const twice = picked.find((other) => other.table === table);
|
|
88
|
+
if (twice)
|
|
89
|
+
return (0, rows_1.invalid)(`The call names ${name} twice ("${twice.input.table_name}" and "${input.table_name}"): name each table once, with all its rows in one selection.`);
|
|
90
|
+
const key = (0, rows_1.primaryKeyOf)(table);
|
|
91
|
+
if (!key)
|
|
92
|
+
return { kind: 'failed', failure: { code: 'unsupported', message: `${name} has no single-column primary key, so its rows can't be named.` } };
|
|
93
|
+
if (!table.query?.delete) {
|
|
94
|
+
return {
|
|
95
|
+
kind: 'failed',
|
|
96
|
+
failure: {
|
|
97
|
+
code: 'unsupported',
|
|
98
|
+
message: `The app API can't delete ${name} rows.`,
|
|
99
|
+
hint: 'The rules of the table may let no one delete rows: read them to see who they let delete.',
|
|
100
|
+
calls: [(0, failure_1.explainAccessCall)(name)],
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
picked.push({ input, table, name, key });
|
|
105
|
+
}
|
|
106
|
+
return { kind: 'ok', value: picked };
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* What a records delete checks before it deletes anything, and the exact rows it deletes: one selector for each
|
|
110
|
+
* table, the project, an app sign-in, each table on the app's API with a key and a delete, the rows each selector
|
|
111
|
+
* names that are there (no more than 500 in all), the order that deletes a row before the rows it points at, and
|
|
112
|
+
* what the delete does to the rows it does not select.
|
|
113
|
+
*/
|
|
114
|
+
async function deleteRecordsReady(params, cwd) {
|
|
115
|
+
for (const input of params.tables) {
|
|
116
|
+
const given = SELECTORS.filter((selector) => input[selector] !== undefined);
|
|
117
|
+
if (given.length === 0)
|
|
118
|
+
return (0, rows_1.invalid)(`Nothing says which rows of ${input.table_name} to delete: give one of rows, where, sample or all.`);
|
|
119
|
+
if (given.length > 1)
|
|
120
|
+
return (0, rows_1.invalid)(`${input.table_name} gives ${(0, harness_1.listed)(given)}: give only one of rows, where, sample and all.`);
|
|
121
|
+
if (input.where && Object.keys(input.where).length === 0) {
|
|
122
|
+
return (0, rows_1.invalid)(`The where of ${input.table_name} names no column: give a column and the value its rows have, or use all for every row.`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const ready = await (0, rows_1.appReady)(cwd, 'deleted');
|
|
126
|
+
if (ready.kind === 'failed')
|
|
127
|
+
return ready;
|
|
128
|
+
const picked = pickTables(ready.value.tables, params.tables);
|
|
129
|
+
if (picked.kind === 'failed')
|
|
130
|
+
return picked;
|
|
131
|
+
const needsSeeded = params.tables.some((input) => input.sample || input.rows?.some(rows_1.isRowRef) || Object.values(input.where ?? {}).some(rows_1.isRowRef));
|
|
132
|
+
const seeded = needsSeeded ? await (0, rows_1.seededIds)(cwd) : { kind: 'ok', value: new Map() };
|
|
133
|
+
if (seeded.kind === 'failed')
|
|
134
|
+
return seeded;
|
|
135
|
+
const tables = [];
|
|
136
|
+
const notes = [];
|
|
137
|
+
let total = 0;
|
|
138
|
+
for (const pick of picked.value) {
|
|
139
|
+
const filter = filterOf(pick, seeded.value);
|
|
140
|
+
if (filter.kind === 'failed')
|
|
141
|
+
return filter;
|
|
142
|
+
const select = [pick.key.name, ...readableFields(pick.table, pick.key).map((field) => field.name)];
|
|
143
|
+
const read = filter.value === null
|
|
144
|
+
? { kind: 'ok', value: { total: 0, nodes: [] } }
|
|
145
|
+
: await (0, delete_effects_1.readRows)(ready.value, pick, filter.value, select, delete_effects_1.MAX_DELETED_ROWS + 1);
|
|
146
|
+
if (read.kind === 'failed')
|
|
147
|
+
return read;
|
|
148
|
+
total += read.value.total;
|
|
149
|
+
const keys = read.value.nodes.map((node) => node[pick.key.name]).filter((key) => typeof key === 'string' || typeof key === 'number');
|
|
150
|
+
if (keys.length === 0) {
|
|
151
|
+
notes.push(NONE_LEFT[selectorOf(pick.input)](pick.name));
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const missing = new Set(pick.input.rows ?? []).size - keys.length;
|
|
155
|
+
if (missing > 0)
|
|
156
|
+
notes.push(`${missing} of the rows given for ${pick.name} ${missing === 1 ? 'is' : 'are'} not there, so the delete leaves ${missing === 1 ? 'it' : 'them'} out.`);
|
|
157
|
+
tables.push({ tableName: pick.name, keyName: pick.key.name, keys, count: keys.length, rows: read.value.nodes.slice(0, 5) });
|
|
158
|
+
}
|
|
159
|
+
if (total > delete_effects_1.MAX_DELETED_ROWS) {
|
|
160
|
+
return (0, rows_1.invalid)(`The call selects ${total} rows in all, more than the ${delete_effects_1.MAX_DELETED_ROWS} one call deletes: narrow it with rows or where, or delete the tables in several calls.`);
|
|
161
|
+
}
|
|
162
|
+
if (tables.length === 0)
|
|
163
|
+
return { kind: 'failed', failure: { code: 'not-found', message: notes.join(' ') } };
|
|
164
|
+
const found = await (0, delete_effects_1.deleteEffects)(ready.value, tables);
|
|
165
|
+
if (found.kind === 'failed')
|
|
166
|
+
return found;
|
|
167
|
+
const { model, effects } = found.value;
|
|
168
|
+
const ordered = childrenFirst(tables, model);
|
|
169
|
+
const links = (0, delete_effects_1.linksOf)(ordered.map((table) => table.tableName), model);
|
|
170
|
+
return { kind: 'ok', value: { ...ready.value, selection: { tables: ordered, effects: effects.map(delete_effects_1.effectLine), links }, notes } };
|
|
171
|
+
}
|
package/records/rows.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type HarnessToolResult, type ToolFailure } from '@agentic-kit/harness';
|
|
2
2
|
import type { ProjectContext } from '../context';
|
|
3
3
|
import { type Result } from '../failure';
|
|
4
|
-
import { statusAdapter } from '../graphql-http';
|
|
4
|
+
import { type GraphQLError, statusAdapter } from '../graphql-http';
|
|
5
5
|
import { type RawField, type RawMetaTable } from './meta';
|
|
6
6
|
export type RecordsDetails = {
|
|
7
7
|
success: boolean;
|
|
@@ -21,19 +21,32 @@ export type RecordsDetails = {
|
|
|
21
21
|
}[];
|
|
22
22
|
};
|
|
23
23
|
type Verb = 'insert' | 'update';
|
|
24
|
-
export declare
|
|
24
|
+
export declare 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.";
|
|
25
|
+
export declare const isSuspended: (errors: readonly GraphQLError[]) => boolean;
|
|
26
|
+
type RecordsFlags = {
|
|
27
|
+
success: boolean;
|
|
28
|
+
message: string;
|
|
29
|
+
needsAuth?: boolean;
|
|
30
|
+
code?: 'database-unavailable';
|
|
31
|
+
};
|
|
32
|
+
export declare function recordsFailed<D extends RecordsFlags = RecordsDetails>(failure: ToolFailure, extra?: Partial<NoInfer<D>>): HarnessToolResult<D>;
|
|
25
33
|
export declare const invalid: (message: string) => Result<never>;
|
|
26
|
-
|
|
34
|
+
/** The app's tables as the person signed in to the app sees them, and the API to reach them. */
|
|
35
|
+
export type AppReady = {
|
|
27
36
|
context: ProjectContext;
|
|
28
37
|
token: string;
|
|
29
38
|
userId?: string;
|
|
30
39
|
/** The app's own API, as the person signed in to the app. */
|
|
31
40
|
adapter: ReturnType<typeof statusAdapter>;
|
|
32
41
|
tables: RawMetaTable[];
|
|
42
|
+
};
|
|
43
|
+
export type RecordsReady = AppReady & {
|
|
33
44
|
table: RawMetaTable;
|
|
34
45
|
/** The records with each key as the API's field name. */
|
|
35
46
|
records: Record<string, unknown>[];
|
|
36
47
|
};
|
|
48
|
+
/** The project, its data endpoint, an app sign-in, and the tables of the app's API; `done` ends a suspended message. */
|
|
49
|
+
export declare function appReady(cwd: string, done: string): Promise<Result<AppReady>>;
|
|
37
50
|
/**
|
|
38
51
|
* What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app
|
|
39
52
|
* sign-in, the table on the app's API, and every record's keys and seeded-row values.
|
|
@@ -46,7 +59,11 @@ export declare const fieldsOf: (table: RawMetaTable) => RawField[];
|
|
|
46
59
|
export declare const columnOf: (field: RawField) => string;
|
|
47
60
|
/** The table's single-column primary key, or undefined for none or a composite one. */
|
|
48
61
|
export declare function primaryKeyOf(table: RawMetaTable): RawField | undefined;
|
|
49
|
-
|
|
62
|
+
export declare const isRowRef: (value: unknown) => value is string;
|
|
63
|
+
export declare const tableKey: (value: string) => string;
|
|
64
|
+
export type SeededIds = ReadonlyMap<string, readonly (string | null)[]>;
|
|
65
|
+
/** The ids of the sample rows the host seeded, by `tableKey`; none on a host that seeds no rows. */
|
|
66
|
+
export declare function seededIds(cwd: string): Promise<Result<SeededIds>>;
|
|
50
67
|
/**
|
|
51
68
|
* 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
|
|
52
69
|
* value wins when both carry one; an empty value never replaces a given one. With nothing but empty values, a column
|
|
@@ -54,6 +71,12 @@ type SeededIds = ReadonlyMap<string, readonly (string | null)[]>;
|
|
|
54
71
|
* seeded row's id.
|
|
55
72
|
*/
|
|
56
73
|
export declare function recordAsFields(table: RawMetaTable, tableName: string, index: number, record: Record<string, unknown>, seeded: SeededIds, clear: boolean): Result<Record<string, unknown>>;
|
|
74
|
+
/** The value, or the id of the seeded row a "@<table>[<index>]" value names: undefined when none was seeded there. */
|
|
75
|
+
export declare function seededValue(value: unknown, seeded: SeededIds): unknown;
|
|
76
|
+
/** The first key that names no column (or field) of the table, with the column to use instead, as the end of a sentence. */
|
|
77
|
+
export declare function notAColumn(table: RawMetaTable, tableName: string, keys: readonly string[]): string | undefined;
|
|
78
|
+
/** The field a key names, by its field name or its column name. */
|
|
79
|
+
export declare const fieldNamed: (table: RawMetaTable, key: string) => RawField | undefined;
|
|
57
80
|
/** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */
|
|
58
81
|
export declare function writeRecords(verb: Verb, tableName: string, { adapter, table: rawTable }: RecordsReady, mutation: string, mutationName: string, inputs: readonly Record<string, unknown>[]): Promise<HarnessToolResult<RecordsDetails>>;
|
|
59
82
|
export {};
|