@agentic-kit/db-tools 0.13.0 → 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/esm/tools/add-records.js
CHANGED
|
@@ -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 {
|
|
5
|
-
import {
|
|
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
|
|
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,
|
|
36
|
-
export
|
|
37
|
-
|
|
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
|
-
|
|
96
|
-
|
|
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
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
};
|
package/esm/tools/index.js
CHANGED
|
@@ -16,6 +16,7 @@ import { provisionBlueprintReady, provisionBlueprintTool } from './provision-blu
|
|
|
16
16
|
import { provisionDatabaseTool, replaceDatabaseTool } from './provision-database';
|
|
17
17
|
import { runCodegenReady, runCodegenTool } from './run-codegen';
|
|
18
18
|
import { applyTemplateReady, applyTemplateTool, createTemplateTool, deleteTemplateTool, listTemplatesTool, templateReady, updateTemplateTool, } from './templates';
|
|
19
|
+
import { updateRecordsReady, updateRecordsTool } from './update-records';
|
|
19
20
|
/**
|
|
20
21
|
* The Constructive database tools, in registration order.
|
|
21
22
|
*
|
|
@@ -41,6 +42,7 @@ export const constructiveDbTools = [
|
|
|
41
42
|
updateTemplateTool,
|
|
42
43
|
deleteTemplateTool,
|
|
43
44
|
addRecordsTool,
|
|
45
|
+
updateRecordsTool,
|
|
44
46
|
listEntityTypesTool,
|
|
45
47
|
createEntityTypeTool,
|
|
46
48
|
deleteEntityTypeTool,
|
|
@@ -132,6 +134,7 @@ export const toolPreconditions = new Map([
|
|
|
132
134
|
[updateTemplateTool.name, targeting(templateReady, ({ context }) => accountTarget(context))],
|
|
133
135
|
[deleteTemplateTool.name, targeting(templateReady, ({ context }) => accountTarget(context))],
|
|
134
136
|
[addRecordsTool.name, targeting(addRecordsReady, ({ context, userId }) => databaseTarget(context, userId))],
|
|
137
|
+
[updateRecordsTool.name, targeting(updateRecordsReady, ({ context, userId }) => databaseTarget(context, userId))],
|
|
135
138
|
[listEntityTypesTool.name, onDatabase(project)],
|
|
136
139
|
[createEntityTypeTool.name, onDatabase(createEntityTypeReady)],
|
|
137
140
|
[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,12 @@ 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 record value "@<table>[<index>]" in add_records or update_records names one of them.
|
|
183
|
+
* A host that seeds no rows leaves it out, and such a value then fails.
|
|
184
|
+
*/
|
|
185
|
+
seededRows?(cwd: string): Promise<Readonly<Record<string, readonly (string | null)[]>> | null>;
|
|
180
186
|
}
|
|
181
187
|
export declare const DEFAULT_DATA_TOKEN_SKEW_MS = 30000;
|
|
182
188
|
/** 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.14.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
|
-
"@
|
|
27
|
-
"@constructive-io/sdk": "^1.22.
|
|
28
|
-
"
|
|
29
|
-
"
|
|
26
|
+
"@constructive-io/graphql-query": "^4.26.0",
|
|
27
|
+
"@constructive-io/sdk": "^1.22.2",
|
|
28
|
+
"node-type-registry": "^1.24.0",
|
|
29
|
+
"@agentic-kit/harness": "^0.20.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"typebox": "^1.0.0"
|
package/records/meta.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Table, TableInflection } from '@constructive-io/graphql-query/types/schema';
|
|
2
|
-
export declare const META_QUERY = "\n query DbToolsMeta {\n _meta {\n tables {\n name\n query { all one create update delete }\n inflection {\n allRows\n conditionType\n connection\n createInputType\n createPayloadType\n deletePayloadType\n edge\n filterType\n orderByType\n patchType\n tableType\n updatePayloadType\n }\n fields {\n name\n isNotNull\n hasDefault\n type {\n gqlType\n isArray\n pgType\n subtype\n isNotNull\n hasDefault\n }\n }\n }\n }\n }\n";
|
|
2
|
+
export declare const META_QUERY = "\n query DbToolsMeta {\n _meta {\n tables {\n name\n tableName\n query { all one create update delete }\n inflection {\n allRows\n conditionType\n connection\n createInputType\n createPayloadType\n deletePayloadType\n edge\n filterType\n orderByType\n patchType\n tableType\n updatePayloadType\n }\n fields {\n name\n columnName\n isNotNull\n hasDefault\n isPrimaryKey\n isWritableOnUpdate\n type {\n gqlType\n isArray\n pgType\n subtype\n isNotNull\n hasDefault\n }\n }\n }\n }\n }\n";
|
|
3
3
|
type RawType = {
|
|
4
4
|
gqlType: string;
|
|
5
5
|
isArray: boolean;
|
|
@@ -11,10 +11,13 @@ type RawType = {
|
|
|
11
11
|
isNotNull?: boolean | null;
|
|
12
12
|
hasDefault?: boolean | null;
|
|
13
13
|
};
|
|
14
|
-
type RawField = {
|
|
14
|
+
export type RawField = {
|
|
15
15
|
name: string;
|
|
16
|
+
columnName?: string | null;
|
|
16
17
|
isNotNull?: boolean | null;
|
|
17
18
|
hasDefault?: boolean | null;
|
|
19
|
+
isPrimaryKey?: boolean | null;
|
|
20
|
+
isWritableOnUpdate?: boolean | null;
|
|
18
21
|
type: RawType;
|
|
19
22
|
};
|
|
20
23
|
type RawInflection = Partial<Record<keyof TableInflection, string | null>>;
|
|
@@ -27,6 +30,8 @@ type RawQuery = {
|
|
|
27
30
|
};
|
|
28
31
|
export type RawMetaTable = {
|
|
29
32
|
name: string;
|
|
33
|
+
/** The SQL name; `name` is the GraphQL type. */
|
|
34
|
+
tableName?: string | null;
|
|
30
35
|
query?: RawQuery | null;
|
|
31
36
|
inflection?: RawInflection | null;
|
|
32
37
|
fields?: (RawField | null)[] | null;
|
package/records/meta.js
CHANGED
|
@@ -18,6 +18,7 @@ exports.META_QUERY = `
|
|
|
18
18
|
_meta {
|
|
19
19
|
tables {
|
|
20
20
|
name
|
|
21
|
+
tableName
|
|
21
22
|
query { all one create update delete }
|
|
22
23
|
inflection {
|
|
23
24
|
allRows
|
|
@@ -35,8 +36,11 @@ exports.META_QUERY = `
|
|
|
35
36
|
}
|
|
36
37
|
fields {
|
|
37
38
|
name
|
|
39
|
+
columnName
|
|
38
40
|
isNotNull
|
|
39
41
|
hasDefault
|
|
42
|
+
isPrimaryKey
|
|
43
|
+
isWritableOnUpdate
|
|
40
44
|
type {
|
|
41
45
|
gqlType
|
|
42
46
|
isArray
|
|
@@ -145,24 +149,29 @@ function getTableLookupVariants(value) {
|
|
|
145
149
|
}
|
|
146
150
|
// Resolve a user-supplied table name (snake_case singular or plural) against the
|
|
147
151
|
// PascalCase-singular `_meta` table names, tolerating pluralization differences.
|
|
152
|
+
// Every table's GraphQL names are indexed before any SQL name, so a GraphQL name always finds its own table.
|
|
148
153
|
function findMetaTable(tables, requested) {
|
|
149
154
|
const index = new Map();
|
|
155
|
+
const add = (table, keys) => {
|
|
156
|
+
for (const key of keys) {
|
|
157
|
+
for (const variant of getTableLookupVariants(key)) {
|
|
158
|
+
if (!index.has(variant))
|
|
159
|
+
index.set(variant, table);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
};
|
|
150
163
|
for (const table of tables) {
|
|
151
|
-
|
|
164
|
+
add(table, [
|
|
152
165
|
table.name,
|
|
153
166
|
table.query?.all,
|
|
154
167
|
table.query?.one,
|
|
155
168
|
table.inflection?.tableType,
|
|
156
169
|
table.inflection?.tableFieldName,
|
|
157
170
|
table.inflection?.allRows,
|
|
158
|
-
];
|
|
159
|
-
for (const key of keys) {
|
|
160
|
-
for (const variant of getTableLookupVariants(key)) {
|
|
161
|
-
if (!index.has(variant))
|
|
162
|
-
index.set(variant, table);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
171
|
+
]);
|
|
165
172
|
}
|
|
173
|
+
for (const table of tables)
|
|
174
|
+
add(table, [table.tableName]);
|
|
166
175
|
for (const variant of getTableLookupVariants(requested)) {
|
|
167
176
|
const match = index.get(variant);
|
|
168
177
|
if (match)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type HarnessToolResult, type ToolFailure } from '@agentic-kit/harness';
|
|
2
|
+
import type { ProjectContext } from '../context';
|
|
3
|
+
import { type Result } from '../failure';
|
|
4
|
+
import { 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 function recordsFailed(failure: ToolFailure, extra?: Partial<RecordsDetails>): HarnessToolResult<RecordsDetails>;
|
|
25
|
+
export declare const invalid: (message: string) => Result<never>;
|
|
26
|
+
export type RecordsReady = {
|
|
27
|
+
context: ProjectContext;
|
|
28
|
+
token: string;
|
|
29
|
+
userId?: string;
|
|
30
|
+
/** The app's own API, as the person signed in to the app. */
|
|
31
|
+
adapter: ReturnType<typeof statusAdapter>;
|
|
32
|
+
tables: RawMetaTable[];
|
|
33
|
+
table: RawMetaTable;
|
|
34
|
+
/** The records with each key as the API's field name. */
|
|
35
|
+
records: Record<string, unknown>[];
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app
|
|
39
|
+
* sign-in, the table on the app's API, and every record's keys and seeded-row values.
|
|
40
|
+
*/
|
|
41
|
+
export declare function recordsReady(verb: Verb, params: {
|
|
42
|
+
table_name: string;
|
|
43
|
+
records: Record<string, unknown>[];
|
|
44
|
+
}, cwd: string): Promise<Result<RecordsReady>>;
|
|
45
|
+
export declare const fieldsOf: (table: RawMetaTable) => RawField[];
|
|
46
|
+
export declare const columnOf: (field: RawField) => string;
|
|
47
|
+
/** The table's single-column primary key, or undefined for none or a composite one. */
|
|
48
|
+
export declare function primaryKeyOf(table: RawMetaTable): RawField | undefined;
|
|
49
|
+
type SeededIds = ReadonlyMap<string, readonly (string | null)[]>;
|
|
50
|
+
/**
|
|
51
|
+
* A record with each key as the API's field name. A key may be a field name or a column name, and the field name's
|
|
52
|
+
* value wins when both carry one; an empty value never replaces a given one. With nothing but empty values, a column
|
|
53
|
+
* is left out so the server's default applies, or set to null when `clear`. A "@<table>[<index>]" value becomes that
|
|
54
|
+
* seeded row's id.
|
|
55
|
+
*/
|
|
56
|
+
export declare function recordAsFields(table: RawMetaTable, tableName: string, index: number, record: Record<string, unknown>, seeded: SeededIds, clear: boolean): Result<Record<string, unknown>>;
|
|
57
|
+
/** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */
|
|
58
|
+
export declare function writeRecords(verb: Verb, tableName: string, { adapter, table: rawTable }: RecordsReady, mutation: string, mutationName: string, inputs: readonly Record<string, unknown>[]): Promise<HarnessToolResult<RecordsDetails>>;
|
|
59
|
+
export {};
|