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