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