@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
|
@@ -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,208 @@
|
|
|
1
|
+
import { identifierParam, listed, strictObject, takeApprovedTable } from '@agentic-kit/harness';
|
|
2
|
+
import { buildPostGraphileDelete, toDeleteMutationName } from '@constructive-io/graphql-query/generators';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { DESCRIBE_SCHEMA, failureFromErrors, noRowsChanged } from '../failure';
|
|
5
|
+
import { answerText, thrownText } from '../graphql-http';
|
|
6
|
+
import { databaseTarget } from '../ready';
|
|
7
|
+
import { deleteEffects, pointOf, rowsOf, sqlName, tablesNotChecked } from '../records/delete-effects';
|
|
8
|
+
import { deleteRecordsReady } from '../records/delete-selection';
|
|
9
|
+
import { cleanTable, findMetaTable } from '../records/meta';
|
|
10
|
+
import { appReady, isSuspended, primaryKeyOf, recordsFailed, UNAVAILABLE } from '../records/rows';
|
|
11
|
+
const DeleteTableZod = strictObject('a table', {
|
|
12
|
+
table_name: identifierParam().describe('Name of the table to delete rows from (snake_case, singular or plural).'),
|
|
13
|
+
rows: z
|
|
14
|
+
.array(z.union([z.string(), z.number()]))
|
|
15
|
+
.min(1)
|
|
16
|
+
.describe('The rows to delete, by primary key, or "@<table>[<index>]" for a sample row seeded when the app was built.')
|
|
17
|
+
.optional(),
|
|
18
|
+
where: z
|
|
19
|
+
.record(z.string(), z.unknown())
|
|
20
|
+
.describe('Delete every row whose columns have these values: column name (snake_case) -> value; null matches an empty column.')
|
|
21
|
+
.optional(),
|
|
22
|
+
sample: z.literal(true).describe('Delete every sample row seeded when the app was built that is still there.').optional(),
|
|
23
|
+
all: z.literal(true).describe('Delete every row of the table that the person signed in to the app can see.').optional(),
|
|
24
|
+
});
|
|
25
|
+
const DeleteRecordsZod = strictObject('the input', {
|
|
26
|
+
tables: z
|
|
27
|
+
.array(DeleteTableZod)
|
|
28
|
+
.min(1)
|
|
29
|
+
.max(20)
|
|
30
|
+
.describe('The tables to delete rows from, each with exactly one of rows, where, sample or all.'),
|
|
31
|
+
});
|
|
32
|
+
/** The plan of a records delete: the exact rows as the target, and the card's preview. */
|
|
33
|
+
export function deleteRecordsPlan({ context, userId, selection, notes }) {
|
|
34
|
+
return {
|
|
35
|
+
target: { ...databaseTarget(context, userId), rows: selection.tables.map(({ tableName, keys }) => ({ tableName, keys })) },
|
|
36
|
+
preview: { kind: 'delete-records', ...selection },
|
|
37
|
+
...(notes.length ? { notes } : {}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const sameTarget = (a, b) => a.database.id === b.database.id && a.apiEndpoint === b.apiEndpoint && a.account.userId === b.account.userId &&
|
|
41
|
+
a.account.agent?.principalId === b.account.agent?.principalId && a.appUserId === b.appUserId;
|
|
42
|
+
/** The app table and key of each table of the rows to delete, still on the app API with a delete. */
|
|
43
|
+
function plannedRows(tables, rows) {
|
|
44
|
+
const planned = [];
|
|
45
|
+
for (const { tableName, keys } of rows) {
|
|
46
|
+
const table = tables.find((candidate) => sqlName(candidate) === tableName);
|
|
47
|
+
const key = table && primaryKeyOf(table);
|
|
48
|
+
if (!table || !key || !table.query?.delete) {
|
|
49
|
+
return {
|
|
50
|
+
kind: 'failed',
|
|
51
|
+
failure: {
|
|
52
|
+
code: 'failed',
|
|
53
|
+
message: `${tableName} changed on the app API after its rows were chosen, so nothing was deleted.`,
|
|
54
|
+
hint: 'Review the rows and approve a new request.',
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
planned.push({ tableName, table, keyName: key.name, keys });
|
|
59
|
+
}
|
|
60
|
+
return { kind: 'ok', value: planned };
|
|
61
|
+
}
|
|
62
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
|
|
63
|
+
const NO_ROW_DELETED = 'The backend answered without the deleted row, so it does not exist, or this account may not delete it.';
|
|
64
|
+
/** One delete per row, in order, until the database is suspended, and the call's result from each row's answer. */
|
|
65
|
+
async function deleteRows({ adapter, tables }, planned, kept) {
|
|
66
|
+
const all = tables.map(cleanTable);
|
|
67
|
+
const results = [];
|
|
68
|
+
const errors = [];
|
|
69
|
+
let suspended = false;
|
|
70
|
+
for (const { tableName, table: rawTable, keyName, keys } of planned) {
|
|
71
|
+
if (suspended)
|
|
72
|
+
break;
|
|
73
|
+
const table = cleanTable(rawTable);
|
|
74
|
+
const mutation = buildPostGraphileDelete(table, all).toString();
|
|
75
|
+
const mutationName = toDeleteMutationName(table.name, table);
|
|
76
|
+
const result = { tableName, deleted: 0, failed: [] };
|
|
77
|
+
results.push(result);
|
|
78
|
+
for (const key of keys) {
|
|
79
|
+
let rowErrors;
|
|
80
|
+
try {
|
|
81
|
+
const answer = await adapter.execute(mutation, { input: { [keyName]: key } });
|
|
82
|
+
if (answer.ok) {
|
|
83
|
+
if (answer.data?.[mutationName])
|
|
84
|
+
result.deleted += 1;
|
|
85
|
+
else
|
|
86
|
+
result.failed.push({ key, message: NO_ROW_DELETED });
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (isSuspended(answer.errors)) {
|
|
90
|
+
suspended = true;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
rowErrors = answer.errors;
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
// The request threw before any answer came back, so the error is the local one.
|
|
97
|
+
rowErrors = [{ message: thrownText(err), extensions: { code: 'NETWORK' } }];
|
|
98
|
+
}
|
|
99
|
+
errors.push(...rowErrors);
|
|
100
|
+
result.failed.push({ key, message: answerText(rowErrors) });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const deletedCount = results.reduce((sum, result) => sum + result.deleted, 0);
|
|
104
|
+
const failedCount = results.reduce((sum, result) => sum + result.failed.length, 0);
|
|
105
|
+
const details = { deletedCount, tables: [...results, ...kept.map((tableName) => ({ tableName, deleted: 0, kept: true, failed: [] }))] };
|
|
106
|
+
const done = results.filter((result) => result.deleted > 0);
|
|
107
|
+
const message = [
|
|
108
|
+
done.length ? `Deleted ${listed(done.map((result, index) => `${index === 0 ? plural(result.deleted, 'row') : result.deleted} from ${result.tableName}`))}.` : '',
|
|
109
|
+
...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}).`),
|
|
110
|
+
kept.length ? `Nothing was deleted from ${listed(kept)}: the person unticked ${kept.length === 1 ? 'it, or it' : 'them, or they'} had no rows to delete.` : '',
|
|
111
|
+
].filter(Boolean).join(' ');
|
|
112
|
+
const failed = (failure) => recordsFailed(failure, details);
|
|
113
|
+
if (suspended) {
|
|
114
|
+
const before = deletedCount === 0 ? 'No rows were deleted.' : `${deletedCount === 1 ? '1 row was' : `${deletedCount} rows were`} deleted before it stopped.`;
|
|
115
|
+
return failed({ code: 'database-unavailable', message: `${UNAVAILABLE} ${before}` });
|
|
116
|
+
}
|
|
117
|
+
if (failedCount > 0 && deletedCount === 0) {
|
|
118
|
+
const action = `Failed to delete rows from ${listed(results.map((result) => result.tableName))}`;
|
|
119
|
+
return failed(errors.length ? failureFromErrors(errors, action, { rows: { table: results[0].tableName } }) : noRowsChanged(action, DESCRIBE_SCHEMA));
|
|
120
|
+
}
|
|
121
|
+
if (failedCount > 0) {
|
|
122
|
+
return failed({
|
|
123
|
+
code: 'partial',
|
|
124
|
+
message,
|
|
125
|
+
hint: 'Fix what the backend said about the rows in details.tables, then call again with only those rows: the deleted rows are gone.',
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } };
|
|
129
|
+
}
|
|
130
|
+
/** Why the approved rows cannot go while the person keeps the table that `effect` reaches, and what to do instead. */
|
|
131
|
+
function keptReached(effect) {
|
|
132
|
+
const { parent, child } = effect;
|
|
133
|
+
const what = effect.effect === 'cascade'
|
|
134
|
+
? `deleting ${parent} deletes them too`
|
|
135
|
+
: effect.effect === 'set_null'
|
|
136
|
+
? `deleting ${parent} clears ${listed(effect.columns)} on them`
|
|
137
|
+
: effect.effect === 'set_default'
|
|
138
|
+
? `deleting ${parent} sets ${listed(effect.columns)} to ${effect.columns.length === 1 ? 'its default' : 'their defaults'} on them`
|
|
139
|
+
: `${parent} rows can't be deleted while they're there`;
|
|
140
|
+
return `You kept ${child}, but ${rowsOf(effect)} ${pointOf(effect)} at ${parent} you'd delete, and ${what}. Approve again with ${child} ticked, or keep ${parent} too.`;
|
|
141
|
+
}
|
|
142
|
+
/** Why the check could not rule out that the approved rows reach `table`, which the person kept, and what to do. */
|
|
143
|
+
function keptNotChecked(effect, table) {
|
|
144
|
+
if (effect.upTo)
|
|
145
|
+
return `Nothing was deleted: there are too many related rows to check that ${table} stays untouched. Delete in smaller steps, or tick ${table}.`;
|
|
146
|
+
const why = effect.uncounted
|
|
147
|
+
? `the ${effect.child} rows that point at ${effect.parent} can't be counted`
|
|
148
|
+
: `the rows that point at the ${effect.child} rows it deletes can't be followed`;
|
|
149
|
+
return `Nothing was deleted: ${why}, so it can't check that ${table} stays untouched. Tick ${table}, or keep ${effect.parent} too.`;
|
|
150
|
+
}
|
|
151
|
+
export const deleteRecordsTool = {
|
|
152
|
+
name: 'delete_records',
|
|
153
|
+
label: 'Delete records',
|
|
154
|
+
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.",
|
|
155
|
+
promptSnippet: 'delete_records: delete rows from one or many tables, by key, by column values, the sample rows, or all rows. Gated.',
|
|
156
|
+
parameters: DeleteRecordsZod,
|
|
157
|
+
effect: 'write',
|
|
158
|
+
async execute(params, ctx) {
|
|
159
|
+
const approved = ctx.toolCallId ? takeApprovedTable(ctx.toolCallId, ctx.cwd) : undefined;
|
|
160
|
+
const fail = (failure) => recordsFailed(failure, { deletedCount: 0, tables: [] });
|
|
161
|
+
if (!approved?.rows) {
|
|
162
|
+
// The same checks as the gate, so a call that cannot run fails the same way; a call that can still deletes
|
|
163
|
+
// nothing, because only an approved target says which rows the person saw and kept.
|
|
164
|
+
const ready = await deleteRecordsReady(params, ctx.cwd);
|
|
165
|
+
if (ready.kind === 'failed')
|
|
166
|
+
return fail(ready.failure);
|
|
167
|
+
return fail({
|
|
168
|
+
code: 'failed',
|
|
169
|
+
message: 'This delete has no approval (it may have expired), so nothing was deleted. Ask again to see the rows and approve them.',
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
const ready = await appReady(ctx.cwd, 'deleted');
|
|
173
|
+
if (ready.kind === 'failed')
|
|
174
|
+
return fail(ready.failure);
|
|
175
|
+
if (!sameTarget(approved, databaseTarget(ready.value.context, ready.value.userId))) {
|
|
176
|
+
return fail({
|
|
177
|
+
code: 'failed',
|
|
178
|
+
message: 'The current project or app sign-in does not match the approved delete target, so nothing was deleted.',
|
|
179
|
+
hint: 'Review the rows and approve a new request.',
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
const planned = plannedRows(ready.value.tables, approved.rows);
|
|
183
|
+
if (planned.kind === 'failed')
|
|
184
|
+
return fail(planned.failure);
|
|
185
|
+
// A table of the input that the approved rows leave out was unticked, or had no rows when the card was built.
|
|
186
|
+
const approvedTables = new Set(planned.value.map((entry) => entry.table));
|
|
187
|
+
const kept = params.tables
|
|
188
|
+
.map((input) => findMetaTable(ready.value.tables, input.table_name))
|
|
189
|
+
.filter((table) => Boolean(table) && !approvedTables.has(table))
|
|
190
|
+
.map(sqlName);
|
|
191
|
+
if (kept.length > 0) {
|
|
192
|
+
const found = await deleteEffects(ready.value, approved.rows);
|
|
193
|
+
if (found.kind === 'failed')
|
|
194
|
+
return fail(found.failure);
|
|
195
|
+
const { effects, model } = found.value;
|
|
196
|
+
const reached = effects.find((effect) => !effect.uncounted && kept.includes(effect.child));
|
|
197
|
+
if (reached)
|
|
198
|
+
return fail({ code: 'conflict', message: keptReached(reached) });
|
|
199
|
+
// An effect the check could not count or follow may still reach a kept table, so it counts as reaching it.
|
|
200
|
+
for (const effect of effects) {
|
|
201
|
+
const table = tablesNotChecked(effect, model).find((name) => kept.includes(name));
|
|
202
|
+
if (table)
|
|
203
|
+
return fail({ code: 'conflict', message: keptNotChecked(effect, table) });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return deleteRows(ready.value, planned.value, kept);
|
|
207
|
+
},
|
|
208
|
+
};
|
package/esm/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/esm/tools/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { tablePolicyFromBlueprint } from '../access';
|
|
|
2
2
|
import { fieldTypeToTypeName, toFieldDefault } from '../blueprint/field-type';
|
|
3
3
|
import { provisionDatabaseReady } from '../provision-database/provision';
|
|
4
4
|
import { accountTarget, databaseTarget, ownedProjectReady, projectReady } from '../ready';
|
|
5
|
+
import { deleteRecordsReady } from '../records/delete-selection';
|
|
5
6
|
import { renameNote } from '../schema-resolve';
|
|
6
7
|
import { columnChange, columnPlan, planTableAccess } from '../table-access';
|
|
7
8
|
import { addedByBackend, describePolicyTypeTool, explainAccessTool, readOnlyNotes, setAccessPlan, setAccessReady, setAccessTool } from './access';
|
|
@@ -9,6 +10,7 @@ import { addPoliciesPlan, addPoliciesReady, addPoliciesTool } from './add-polici
|
|
|
9
10
|
import { addRecordsReady, addRecordsTool } from './add-records';
|
|
10
11
|
import { addRelationReady, addRelationTool } from './add-relation';
|
|
11
12
|
import { createApiKeyReady, createApiKeyTool } from './create-api-key';
|
|
13
|
+
import { deleteRecordsPlan, deleteRecordsTool } from './delete-records';
|
|
12
14
|
import { describeSchemaTool } from './describe-schema';
|
|
13
15
|
import { createEntityTypeReady, createEntityTypeTool, deleteEntityTypeReady, deleteEntityTypeTool, listEntityTypesTool } from './entity-types';
|
|
14
16
|
import { createFieldReady, createFieldTool, deleteFieldReady, deleteFieldTool, deleteTableReady, deleteTableTool, retypeFieldReady, retypeFieldTool, updateFieldReady, updateFieldTool, } from './mutations';
|
|
@@ -16,6 +18,7 @@ import { provisionBlueprintReady, provisionBlueprintTool } from './provision-blu
|
|
|
16
18
|
import { provisionDatabaseTool, replaceDatabaseTool } from './provision-database';
|
|
17
19
|
import { runCodegenReady, runCodegenTool } from './run-codegen';
|
|
18
20
|
import { applyTemplateReady, applyTemplateTool, createTemplateTool, deleteTemplateTool, listTemplatesTool, templateReady, updateTemplateTool, } from './templates';
|
|
21
|
+
import { updateRecordsReady, updateRecordsTool } from './update-records';
|
|
19
22
|
/**
|
|
20
23
|
* The Constructive database tools, in registration order.
|
|
21
24
|
*
|
|
@@ -41,6 +44,8 @@ export const constructiveDbTools = [
|
|
|
41
44
|
updateTemplateTool,
|
|
42
45
|
deleteTemplateTool,
|
|
43
46
|
addRecordsTool,
|
|
47
|
+
updateRecordsTool,
|
|
48
|
+
deleteRecordsTool,
|
|
44
49
|
listEntityTypesTool,
|
|
45
50
|
createEntityTypeTool,
|
|
46
51
|
deleteEntityTypeTool,
|
|
@@ -132,6 +137,14 @@ export const toolPreconditions = new Map([
|
|
|
132
137
|
[updateTemplateTool.name, targeting(templateReady, ({ context }) => accountTarget(context))],
|
|
133
138
|
[deleteTemplateTool.name, targeting(templateReady, ({ context }) => accountTarget(context))],
|
|
134
139
|
[addRecordsTool.name, targeting(addRecordsReady, ({ context, userId }) => databaseTarget(context, userId))],
|
|
140
|
+
[updateRecordsTool.name, targeting(updateRecordsReady, ({ context, userId }) => databaseTarget(context, userId))],
|
|
141
|
+
[
|
|
142
|
+
deleteRecordsTool.name,
|
|
143
|
+
async (params, cwd) => {
|
|
144
|
+
const ready = await deleteRecordsReady(params, cwd);
|
|
145
|
+
return ready.kind === 'failed' ? ready : { kind: 'ok', value: deleteRecordsPlan(ready.value) };
|
|
146
|
+
},
|
|
147
|
+
],
|
|
135
148
|
[listEntityTypesTool.name, onDatabase(project)],
|
|
136
149
|
[createEntityTypeTool.name, onDatabase(createEntityTypeReady)],
|
|
137
150
|
[deleteEntityTypeTool.name, onDatabase(deleteEntityTypeReady)],
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type HarnessTool } from '@agentic-kit/harness';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import type { Result } from '../failure';
|
|
4
|
+
import { type RawField } from '../records/meta';
|
|
5
|
+
import { type RecordsDetails, type RecordsReady } from '../records/rows';
|
|
6
|
+
declare const UpdateRecordsZod: z.ZodObject<{
|
|
7
|
+
table_name: z.ZodString;
|
|
8
|
+
records: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
9
|
+
}, z.core.$strict>;
|
|
10
|
+
type UpdateRecordsParams = z.infer<typeof UpdateRecordsZod>;
|
|
11
|
+
/** What update_records checks before it changes anything: the table on the app's API, its key, and for every record the row it names and the columns it sets. */
|
|
12
|
+
export declare function updateRecordsReady(params: UpdateRecordsParams, cwd: string): Promise<Result<RecordsReady & {
|
|
13
|
+
primaryKey: RawField;
|
|
14
|
+
}>>;
|
|
15
|
+
export declare const updateRecordsTool: HarnessTool<typeof UpdateRecordsZod, RecordsDetails>;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { identifierParam, strictObject } from '@agentic-kit/harness';
|
|
2
|
+
import { buildPostGraphileUpdate, toPatchFieldName, toUpdateMutationName } from '@constructive-io/graphql-query/generators';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { cleanTable } from '../records/meta';
|
|
5
|
+
import { columnOf, fieldsOf, invalid, primaryKeyOf, recordsFailed, recordsReady, writeRecords } from '../records/rows';
|
|
6
|
+
const UpdateRecordsZod = strictObject('the input', {
|
|
7
|
+
table_name: identifierParam()
|
|
8
|
+
.describe('Name of the table whose rows to change (snake_case, singular or plural).'),
|
|
9
|
+
records: z
|
|
10
|
+
.array(z.record(z.string(), z.unknown()))
|
|
11
|
+
.describe('One object per row. Its primary key column (usually "id") names the row: its id, or "@<table>[<index>]" for a sample row seeded when the app was built. The other keys are the columns to set, by column name (snake_case); a value may also be "@<table>[<index>]".'),
|
|
12
|
+
});
|
|
13
|
+
/** What update_records checks before it changes anything: the table on the app's API, its key, and for every record the row it names and the columns it sets. */
|
|
14
|
+
export async function updateRecordsReady(params, cwd) {
|
|
15
|
+
const ready = await recordsReady('update', params, cwd);
|
|
16
|
+
if (ready.kind === 'failed')
|
|
17
|
+
return ready;
|
|
18
|
+
const { table, records } = ready.value;
|
|
19
|
+
const primaryKey = primaryKeyOf(table);
|
|
20
|
+
if (!primaryKey) {
|
|
21
|
+
return { kind: 'failed', failure: { code: 'unsupported', message: `${params.table_name} has no single-column primary key, so its rows can't be named.` } };
|
|
22
|
+
}
|
|
23
|
+
if (!table.query?.update) {
|
|
24
|
+
return { kind: 'failed', failure: { code: 'unsupported', message: `The app API can't update ${params.table_name} rows.` } };
|
|
25
|
+
}
|
|
26
|
+
const fields = new Map(fieldsOf(table).map((field) => [field.name, field]));
|
|
27
|
+
const keyColumn = columnOf(primaryKey);
|
|
28
|
+
for (const [index, { [primaryKey.name]: key, ...patch }] of records.entries()) {
|
|
29
|
+
if (key == null)
|
|
30
|
+
return invalid(`Row ${index} names no row: give its "${keyColumn}".`);
|
|
31
|
+
const kept = Object.keys(patch).find((name) => fields.get(name)?.isWritableOnUpdate === false);
|
|
32
|
+
if (kept)
|
|
33
|
+
return invalid(`Row ${index} sets "${columnOf(fields.get(kept))}", which the app API does not let anyone change.`);
|
|
34
|
+
if (Object.keys(patch).length === 0)
|
|
35
|
+
return invalid(`Row ${index} sets no column besides "${keyColumn}".`);
|
|
36
|
+
}
|
|
37
|
+
return { kind: 'ok', value: { ...ready.value, primaryKey } };
|
|
38
|
+
}
|
|
39
|
+
export const updateRecordsTool = {
|
|
40
|
+
name: 'update_records',
|
|
41
|
+
label: 'Update records',
|
|
42
|
+
description: "Set columns on rows that are already in the project's app database, each row named by its primary key. Use it to link rows, for example a key column of a row add_records made to a sample row seeded when the app was built.",
|
|
43
|
+
promptSnippet: 'update_records: set columns on existing rows by primary key, such as linking rows. Gated.',
|
|
44
|
+
parameters: UpdateRecordsZod,
|
|
45
|
+
effect: 'write',
|
|
46
|
+
async execute(params, ctx) {
|
|
47
|
+
const ready = await updateRecordsReady(params, ctx.cwd);
|
|
48
|
+
if (ready.kind === 'failed')
|
|
49
|
+
return recordsFailed(ready.failure);
|
|
50
|
+
const { tables, records, primaryKey } = ready.value;
|
|
51
|
+
const table = cleanTable(ready.value.table);
|
|
52
|
+
const patchField = toPatchFieldName(table.name, table);
|
|
53
|
+
const inputs = records.map(({ [primaryKey.name]: key, ...patch }) => ({ [primaryKey.name]: key, [patchField]: patch }));
|
|
54
|
+
const mutation = buildPostGraphileUpdate(table, tables.map(cleanTable)).toString();
|
|
55
|
+
return writeRecords('update', params.table_name, ready.value, mutation, toUpdateMutationName(table.name, table), inputs);
|
|
56
|
+
},
|
|
57
|
+
};
|
package/host.d.ts
CHANGED
|
@@ -177,6 +177,13 @@ export interface ToolsHost {
|
|
|
177
177
|
* the call fails with `binding-not-saved`.
|
|
178
178
|
*/
|
|
179
179
|
persistBinding?(binding: ProjectBinding): Promise<void>;
|
|
180
|
+
/**
|
|
181
|
+
* The ids of the sample rows the host seeded into the project's database, by table name, in seed order (null for
|
|
182
|
+
* a row that did not land). A value "@<table>[<index>]" in add_records, update_records or delete_records names one of them, and delete_records
|
|
183
|
+
* can delete every seeded row of a table that is still there.
|
|
184
|
+
* A host that seeds no rows leaves it out, and such a value then fails.
|
|
185
|
+
*/
|
|
186
|
+
seededRows?(cwd: string): Promise<Readonly<Record<string, readonly (string | null)[]>> | null>;
|
|
180
187
|
}
|
|
181
188
|
export declare const DEFAULT_DATA_TOKEN_SKEW_MS = 30000;
|
|
182
189
|
/** The advice for a database that is gone or under another account. */
|
package/index.d.ts
CHANGED
|
@@ -22,12 +22,13 @@ export { loadProvisionManifest, parseProvisionManifest, PROVISION_MANIFEST_FILE,
|
|
|
22
22
|
export { allModulePresets, DEFAULT_PROVISION_PRESET, getModulePreset, type ModulePreset, type ProvisionModule, } from './provision-database/presets';
|
|
23
23
|
export { provisionDatabase, type ProvisionDatabaseDetails, type ProvisionFailureCode, type ProvisionInput, } from './provision-database/provision';
|
|
24
24
|
export { moduleKey, type ProvisionOverlay, resolveProvisionModules, } from './provision-database/resolve';
|
|
25
|
+
export { type RecordsDetails } from './records/rows';
|
|
25
26
|
export { accessOf, type ColumnDefault, type FkAction, type ModelColumn, type ModelForeignKey, type ModelPolicy, type ModelTable, type ObjectCategory, readSchemaModel, type SchemaModel, SchemaReadError, type TableAccess, } from './schema-model';
|
|
26
27
|
export { accessState, asWritten, grantWords, planRule, ruleWords, type WrittenRule } from './table-access';
|
|
27
28
|
export { toolSchema } from './tool-schema';
|
|
28
29
|
export { describePolicyTypeTool, explainAccessTool, type ExplainedRule, type ExplainedTable, setAccessTool } from './tools/access';
|
|
29
30
|
export { type AddPoliciesDetails, addPoliciesTool } from './tools/add-policies';
|
|
30
|
-
export {
|
|
31
|
+
export { addRecordsTool } from './tools/add-records';
|
|
31
32
|
export { type AddRelationDetails, addRelationTool } from './tools/add-relation';
|
|
32
33
|
export { type CreateApiKeyDetails, createApiKeyTool } from './tools/create-api-key';
|
|
33
34
|
export { type DescribeSchemaDetails, describeSchemaTool } from './tools/describe-schema';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentic-kit/db-tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"author": "Constructive <developers@constructive.io>",
|
|
5
5
|
"description": "harness-neutral Constructive database tools — provisioning, schema, policies, records, templates and codegen as HarnessTools any adapter can bind",
|
|
6
6
|
"main": "index.js",
|
|
@@ -23,10 +23,10 @@
|
|
|
23
23
|
"ajv": "^8.20.0",
|
|
24
24
|
"zod": "^4.4.3",
|
|
25
25
|
"12factor-env": "^1.34.1",
|
|
26
|
-
"@agentic-kit/harness": "^0.
|
|
27
|
-
"@constructive-io/graphql-query": "^4.
|
|
28
|
-
"@constructive-io/sdk": "^1.22.
|
|
29
|
-
"node-type-registry": "^1.
|
|
26
|
+
"@agentic-kit/harness": "^0.21.0",
|
|
27
|
+
"@constructive-io/graphql-query": "^4.26.0",
|
|
28
|
+
"@constructive-io/sdk": "^1.22.2",
|
|
29
|
+
"node-type-registry": "^1.24.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"typebox": "^1.0.0"
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type DeleteRecordsLink } from '@agentic-kit/harness';
|
|
2
|
+
import { type Result } from '../failure';
|
|
3
|
+
import { type SchemaModel } from '../schema-model';
|
|
4
|
+
import { type RawMetaTable } from './meta';
|
|
5
|
+
import { type AppReady } from './rows';
|
|
6
|
+
/** The most rows one call deletes, over all its tables, and the most rows its effects read. */
|
|
7
|
+
export declare const MAX_DELETED_ROWS = 500;
|
|
8
|
+
/** The SQL name of an app table, as the person and the schema model name it. */
|
|
9
|
+
export declare const sqlName: (table: RawMetaTable) => string;
|
|
10
|
+
export type Read = {
|
|
11
|
+
total: number;
|
|
12
|
+
nodes: Record<string, unknown>[];
|
|
13
|
+
};
|
|
14
|
+
/** The first rows the filter selects, with the given fields, and how many it selects in all. */
|
|
15
|
+
export declare function readRows(ready: AppReady, { name, table }: {
|
|
16
|
+
name: string;
|
|
17
|
+
table: RawMetaTable;
|
|
18
|
+
}, filter: Record<string, unknown> | undefined, select: string[], first: number): Promise<Result<Read>>;
|
|
19
|
+
export type Effect = 'cascade' | 'set_null' | 'set_default' | 'restrict';
|
|
20
|
+
/**
|
|
21
|
+
* Rows of `child` that point at rows of `parent` the delete removes and that the delete does not select: what happens
|
|
22
|
+
* to them, by which columns, how many there are, and how many of the parent rows they point at. `upTo` is set when
|
|
23
|
+
* there were more than the read could take: then the count is at most that many. `unfollowed` is set when the rows go
|
|
24
|
+
* and other rows point at them, but `child` has no single-column key to follow them by. `uncounted` is set when the
|
|
25
|
+
* rows cannot be read on the app API, or the values the key points at cannot be read from the deleted rows.
|
|
26
|
+
*/
|
|
27
|
+
export type DeleteEffect = {
|
|
28
|
+
parent: string;
|
|
29
|
+
child: string;
|
|
30
|
+
effect: Effect;
|
|
31
|
+
columns: string[];
|
|
32
|
+
rows: number;
|
|
33
|
+
parents: number;
|
|
34
|
+
upTo?: number;
|
|
35
|
+
unfollowed?: true;
|
|
36
|
+
uncounted?: true;
|
|
37
|
+
};
|
|
38
|
+
export declare const rowsOf: (effect: DeleteEffect) => string;
|
|
39
|
+
/** "points" for one row, "point" for more. */
|
|
40
|
+
export declare const pointOf: (effect: DeleteEffect) => string;
|
|
41
|
+
/** One plain line for the card. */
|
|
42
|
+
export declare function effectLine(effect: DeleteEffect): string;
|
|
43
|
+
/** The foreign keys between the tables a delete names, one for each child, parent and effect, for the card to warn with. */
|
|
44
|
+
export declare function linksOf(names: readonly string[], model: SchemaModel): DeleteRecordsLink[];
|
|
45
|
+
/**
|
|
46
|
+
* The tables an effect may change that it does not count: its own table when its rows were not counted, and when its
|
|
47
|
+
* rows go and were not all followed, every table whose rows point at them.
|
|
48
|
+
*/
|
|
49
|
+
export declare function tablesNotChecked(effect: DeleteEffect, model: SchemaModel): string[];
|
|
50
|
+
type Key = string | number;
|
|
51
|
+
/**
|
|
52
|
+
* The schema model, and what deleting the selected rows does to the rows that point at them and are not selected, and
|
|
53
|
+
* through a cascade to the rows that point at those, each row followed once, over at most 500 rows read: one
|
|
54
|
+
* effect for each table, kind of effect and table it points at, with the union of the columns. A search chunk table the
|
|
55
|
+
* backend keeps is left out, because its rows always go with their parent row. A table with no rows there gives none.
|
|
56
|
+
*/
|
|
57
|
+
export declare function deleteEffects(ready: AppReady, selected: ReadonlyArray<{
|
|
58
|
+
tableName: string;
|
|
59
|
+
keys: readonly Key[];
|
|
60
|
+
}>): Promise<Result<{
|
|
61
|
+
model: SchemaModel;
|
|
62
|
+
effects: DeleteEffect[];
|
|
63
|
+
}>>;
|
|
64
|
+
export {};
|