@romedb/studio 0.0.0-stage → 0.1.1
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/LICENSE.md +20 -0
- package/README.md +15 -2
- package/package.json +36 -4
- package/src/components/CodeEditor.ts +298 -0
- package/src/components/studio/BrowseTab.ts +457 -0
- package/src/components/studio/CellEditorSheet.ts +165 -0
- package/src/components/studio/DatabaseTab.ts +148 -0
- package/src/components/studio/GraphCanvas.ts +90 -0
- package/src/components/studio/GraphTab.ts +110 -0
- package/src/components/studio/InsertRowSheet.ts +180 -0
- package/src/components/studio/MapCanvas.ts +177 -0
- package/src/components/studio/MapTab.ts +121 -0
- package/src/components/studio/NewObjectSheet.ts +235 -0
- package/src/components/studio/QueryHistorySheet.ts +111 -0
- package/src/components/studio/RowSheets.ts +226 -0
- package/src/components/studio/SqlConsole.ts +281 -0
- package/src/components/studio/StructureTab.ts +209 -0
- package/src/components/studio/icon-button.ts +21 -0
- package/src/lib/filters.ts +44 -0
- package/src/lib/graph.ts +214 -0
- package/src/lib/romeql.ts +106 -0
- package/src/lib/spatial.ts +518 -0
- package/src/lib/sql-text.ts +208 -0
- package/src/lib/studio-types.ts +268 -0
- package/src/lib/values.ts +305 -0
- package/src/monaco-standalone.d.ts +27 -0
- package/src/schema-draft.ts +41 -0
- package/src/schema-store.ts +8 -0
- package/src/server/backend.ts +77 -0
- package/src/server/data.ts +142 -0
- package/src/server/edits.ts +92 -0
- package/src/server/graph.ts +66 -0
- package/src/server/queries.ts +108 -0
- package/src/server/schema.ts +272 -0
- package/src/server/spatial.ts +74 -0
- package/src/studio-page.ts +84 -0
- package/src/workspace/StudioWorkspace.ts +1970 -0
- package/src/workspace/workspace.css +38 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { decodeValue, type PortableValue, type Statement, type Value } from '@romedb/client';
|
|
3
|
+
import { workspaceConnections } from './backend';
|
|
4
|
+
|
|
5
|
+
export type EditInput = { table: string; action: 'insert' | 'update' | 'delete'; revision: number; key: Record<string, PortableValue>; body: string };
|
|
6
|
+
|
|
7
|
+
export async function saveEdit(context: Context, connectionId: string, operationId: string, input: EditInput) {
|
|
8
|
+
const actor = context.get('user') as { id?: string } | undefined;
|
|
9
|
+
if (!actor?.id) throw new Error('Studio session required');
|
|
10
|
+
try {
|
|
11
|
+
if (!input || !Number.isSafeInteger(input.revision) || input.revision < 0) throw new Error('Load an object revision before saving');
|
|
12
|
+
const connections = workspaceConnections(context);
|
|
13
|
+
const metadata = await connections.execute(actor.id, connectionId, crypto.randomUUID(), [{ sql: `INFO FOR TABLE ${editIdentifier(input.table)}` }], 'read');
|
|
14
|
+
if (!('results' in metadata) || !metadata.results) return metadata;
|
|
15
|
+
if (metadata.sequence !== input.revision) return { error: { code: 'RDB_CONFLICT', message: 'This edit snapshot is stale. Reload the row or document before saving.', outcome: 'not-sent' as const, sequence: metadata.sequence } };
|
|
16
|
+
const info = metadata.results[0]?.rows[0]?.[0];
|
|
17
|
+
if (info?.type !== 'Object') throw new Error('Cannot verify the editable object');
|
|
18
|
+
const statement = editStatement(input, info);
|
|
19
|
+
return await connections.execute(actor.id, connectionId, operationId, [statement], 'write', input.revision, { rowMutations: 1, vmSteps: 1000000 }, true);
|
|
20
|
+
} catch (error) { return { error: { code: 'STUDIO_EDIT', message: error instanceof Error ? error.message.slice(0, 512) : 'Invalid edit draft', outcome: 'not-sent' as const } }; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function saveBatchEdit(context: Context, connectionId: string, operationId: string, inputs: EditInput[]) {
|
|
24
|
+
const actor = context.get('user') as {id?: string} | undefined;
|
|
25
|
+
if (!actor?.id) throw new Error('Studio session required');
|
|
26
|
+
try {
|
|
27
|
+
if (!Array.isArray(inputs) || inputs.length < 1 || inputs.length > 32) throw new Error('Select 1–32 rows for one atomic batch');
|
|
28
|
+
const first = inputs[0];
|
|
29
|
+
if (!first || !Number.isSafeInteger(first.revision) || first.revision < 0 || !['update','delete'].includes(first.action)) throw new Error('Load an editable snapshot before applying a batch');
|
|
30
|
+
if (inputs.some(input => input.table !== first.table || input.revision !== first.revision || input.action !== first.action)) throw new Error('A batch must use one object, revision and action');
|
|
31
|
+
const identities = inputs.map(input => JSON.stringify(Object.entries(input.key).sort(([a],[b]) => a.localeCompare(b))));
|
|
32
|
+
if (new Set(identities).size !== inputs.length) throw new Error('Each selected row must have a distinct stable key');
|
|
33
|
+
const connections = workspaceConnections(context);
|
|
34
|
+
const metadata = await connections.execute(actor.id, connectionId, crypto.randomUUID(), [{sql: `INFO FOR TABLE ${editIdentifier(first.table)}`}], 'read');
|
|
35
|
+
if (!('results' in metadata)) return metadata;
|
|
36
|
+
if (metadata.sequence !== first.revision) return {error: {code: 'RDB_CONFLICT', message: 'This selection is stale. Reload before applying the batch.', outcome: 'not-sent' as const, sequence: metadata.sequence}};
|
|
37
|
+
const info = metadata.results[0]?.rows[0]?.[0];
|
|
38
|
+
if (info?.type !== 'Object') throw new Error('Cannot verify the editable object');
|
|
39
|
+
const statements = inputs.map(input => editStatement(input, info));
|
|
40
|
+
return await connections.execute(actor.id, connectionId, operationId, statements, 'write', first.revision, {rowMutations: inputs.length, vmSteps: 1000000}, true);
|
|
41
|
+
} catch (error) { return {error: {code: 'STUDIO_EDIT', message: error instanceof Error ? error.message.slice(0,512) : 'Invalid batch draft', outcome: 'not-sent' as const}}; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function editStatement(input: EditInput, info: Extract<PortableValue, { type: 'Object' }>): Statement {
|
|
45
|
+
const table = editIdentifier(input.table);
|
|
46
|
+
if (!['insert', 'update', 'delete'].includes(input.action) || info.value.kind?.type === 'String' && info.value.kind.value === 'view') throw new Error('Choose an editable table or collection');
|
|
47
|
+
if (!input.key || typeof input.key !== 'object' || Array.isArray(input.key)) throw new Error('Invalid edit identity');
|
|
48
|
+
if (typeof input.body !== 'string' || Buffer.byteLength(input.body) > 65536) throw new Error('Edit drafts are limited to 64 KiB');
|
|
49
|
+
const body: unknown = input.action === 'delete' ? {} : JSON.parse(input.body);
|
|
50
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('Use a typed field object for the edit draft');
|
|
51
|
+
if (info.value.model?.type === 'String' && info.value.model.value === 'document') return documentStatement(input, table, body as Record<string, PortableValue>);
|
|
52
|
+
const columns = info.value.columns;
|
|
53
|
+
if (columns?.type !== 'Array') throw new Error('Cannot verify relational fields');
|
|
54
|
+
const fields = columns.value.flatMap(column => column.type === 'Object' && column.value.name?.type === 'String' ? [{ name: column.value.name.value, primary: column.value.pk?.type === 'Integer' && Number(column.value.pk.value) > 0, hidden: column.value.hidden?.type === 'Integer' && column.value.hidden.value !== '0' }] : []);
|
|
55
|
+
const primary = fields.filter(field => field.primary).map(field => field.name);
|
|
56
|
+
if (!primary.length) throw new Error('This table has no explicit primary key and remains read only');
|
|
57
|
+
const params: Record<string, Value> = {};
|
|
58
|
+
const where = primary.map((name, index) => {
|
|
59
|
+
if (input.action !== 'insert' && (!Object.hasOwn(input.key, name) || input.key[name].type === 'Null')) throw new Error('All non-null primary-key fields are required');
|
|
60
|
+
if (input.action !== 'insert') params[`$key${index}`] = decodeValue(input.key[name]);
|
|
61
|
+
return `${editIdentifier(name)}=$key${index}`;
|
|
62
|
+
}).join(' AND ');
|
|
63
|
+
if (input.action !== 'insert' && Object.keys(input.key).some(name => !primary.includes(name))) throw new Error('Unexpected key field');
|
|
64
|
+
if (input.action === 'delete') return { sql: `DELETE FROM ${table} WHERE ${where} RETURNING *`, params };
|
|
65
|
+
const names = Object.keys(body);
|
|
66
|
+
if (!names.length || names.length > 128) throw new Error('Choose 1–128 editable fields');
|
|
67
|
+
for (const [index, name] of names.entries()) {
|
|
68
|
+
if (!fields.some(field => field.name === name && !field.hidden) || input.action === 'update' && primary.includes(name)) throw new Error('Primary keys and generated fields cannot be changed');
|
|
69
|
+
params[`$value${index}`] = decodeValue((body as Record<string, PortableValue>)[name]);
|
|
70
|
+
}
|
|
71
|
+
return input.action === 'insert'
|
|
72
|
+
? { sql: `INSERT INTO ${table} (${names.map(editIdentifier).join(',')}) VALUES (${names.map((_name, index) => `$value${index}`).join(',')}) RETURNING *`, params }
|
|
73
|
+
: { sql: `UPDATE ${table} SET ${names.map((name, index) => `${editIdentifier(name)}=$value${index}`).join(',')} WHERE ${where} RETURNING *`, params };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function documentStatement(input: EditInput, table: string, body: Record<string, PortableValue>): Statement {
|
|
77
|
+
const identity = input.action === 'insert' ? body.id : input.key.id;
|
|
78
|
+
if (identity?.type !== 'Record' || identity.value.table.toLowerCase() !== input.table.toLowerCase()) throw new Error('Use a typed record ID belonging to this collection');
|
|
79
|
+
const params: Record<string, Value> = { '$id': decodeValue(identity) };
|
|
80
|
+
if (input.action === 'delete') return { sql: `DELETE FROM ${table} WHERE id=$id RETURNING *`, params };
|
|
81
|
+
if (body.id?.type !== 'Record' || body.id.value.table.toLowerCase() !== identity.value.table.toLowerCase() || body.id.value.key.type !== identity.value.key.type || body.id.value.key.value !== identity.value.key.value) throw new Error('Document IDs cannot be removed or changed');
|
|
82
|
+
const values = Object.fromEntries(Object.entries(body).map(([name, value]) => [name, decodeValue(value)]));
|
|
83
|
+
if (input.action === 'insert') return { sql: `INSERT INTO ${table} DOCUMENT $body RETURNING *`, params: { '$body': values } };
|
|
84
|
+
delete values.id;
|
|
85
|
+
params.$body = values;
|
|
86
|
+
return { sql: `UPDATE ${table} CONTENT $body WHERE id=$id RETURNING *`, params };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function editIdentifier(name: string): string {
|
|
90
|
+
if (typeof name !== 'string' || !name || name.length > 1024 || name.includes('\0') || /^(?:__romedb_|__turso_internal_|sqlite_)/i.test(name)) throw new Error('Choose a logical object or field');
|
|
91
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
92
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { decodeValue, type PortableValue } from '@romedb/client';
|
|
3
|
+
import { workspaceConnections } from './backend';
|
|
4
|
+
import { statementResult } from './data';
|
|
5
|
+
import { exploreGraph, graphQuery } from '../lib/graph';
|
|
6
|
+
import { quoteIdentifier } from '../lib/sql-text';
|
|
7
|
+
import type { GraphRequest, GraphView, StudioObject } from '../lib/studio-types';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Reads the neighborhood of one record through an edge table. The edge and root
|
|
11
|
+
* declarations are re-read in the same request family so the generated GRAPH
|
|
12
|
+
* query always matches the database, not a cached client schema.
|
|
13
|
+
*/
|
|
14
|
+
export async function exploreNeighborhood(context: Context, connectionId: string, request: GraphRequest): Promise<GraphView> {
|
|
15
|
+
const actor = context.get('user') as { id?: string } | undefined;
|
|
16
|
+
if (!actor?.id) throw new Error('Studio session required');
|
|
17
|
+
const started = performance.now();
|
|
18
|
+
const empty: GraphView = { nodes: [], edges: [], query: '', durationMs: 0, sequence: 0 };
|
|
19
|
+
try {
|
|
20
|
+
if (request?.root?.type !== 'Record') throw new Error('Enter a record ID such as people:alice.');
|
|
21
|
+
decodeValue(request.root);
|
|
22
|
+
if (typeof request.edge !== 'string' || !request.edge || /^(?:__romedb_|__turso_internal_|sqlite_)/i.test(request.edge)) throw new Error('Choose an edge table.');
|
|
23
|
+
if (!['out', 'in', 'both'].includes(request.direction)) throw new Error('Choose a direction.');
|
|
24
|
+
const connections = workspaceConnections(context);
|
|
25
|
+
const metadata = await connections.execute(actor.id, connectionId, crypto.randomUUID(), [
|
|
26
|
+
{ sql: `INFO FOR TABLE ${quoteIdentifier(request.edge)}` },
|
|
27
|
+
{ sql: `INFO FOR TABLE ${quoteIdentifier(request.root.value.table)}` },
|
|
28
|
+
], 'read');
|
|
29
|
+
if (!('results' in metadata) || !metadata.results) {
|
|
30
|
+
throw new Error('error' in metadata && metadata.error ? metadata.error.message : 'Invalid database response');
|
|
31
|
+
}
|
|
32
|
+
const objects = metadata.results.map(result => describe(result.rows[0]?.[0]));
|
|
33
|
+
const built = graphQuery({ connection: null, objects, sequence: metadata.sequence }, request);
|
|
34
|
+
const reply = await connections.execute(actor.id, connectionId, crypto.randomUUID(), [
|
|
35
|
+
{ sql: built.sql, params: { $root: decodeValue(request.root) } },
|
|
36
|
+
], 'read');
|
|
37
|
+
if (!('results' in reply) || !reply.results) {
|
|
38
|
+
return { ...empty, query: built.display, durationMs: performance.now() - started, error: 'error' in reply && reply.error ? `${reply.error.code}: ${reply.error.message}` : 'Invalid database response' };
|
|
39
|
+
}
|
|
40
|
+
const result = statementResult(reply.results[0]?.columns ?? [], reply.results[0]?.rows ?? []);
|
|
41
|
+
const graph = exploreGraph(request.root, request.edge, result);
|
|
42
|
+
return { ...graph, query: built.display, durationMs: performance.now() - started, sequence: reply.sequence };
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return { ...empty, durationMs: performance.now() - started, error: error instanceof Error ? error.message.slice(0, 512) : 'Cannot explore this record' };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function describe(info: PortableValue | undefined): StudioObject {
|
|
49
|
+
if (info?.type !== 'Object' || info.value.model?.type !== 'String' || info.value.name?.type !== 'String') {
|
|
50
|
+
throw new Error('Database returned invalid table metadata');
|
|
51
|
+
}
|
|
52
|
+
const edge = info.value.edge?.type === 'Object' ? info.value.edge.value : null;
|
|
53
|
+
const name = (value: PortableValue | undefined) => value?.type === 'String' ? value.value : '';
|
|
54
|
+
return {
|
|
55
|
+
name: info.value.name.value,
|
|
56
|
+
kind: 'table',
|
|
57
|
+
model: info.value.model.value === 'document' ? 'document' : 'relational',
|
|
58
|
+
sql: null,
|
|
59
|
+
columns: [],
|
|
60
|
+
indexes: [],
|
|
61
|
+
foreignKeys: [],
|
|
62
|
+
keyFields: [],
|
|
63
|
+
editable: false,
|
|
64
|
+
...(edge ? { edge: { source: name(edge.source), target: name(edge.target), onDelete: name(edge.on_delete) === 'cascade' ? 'cascade' : 'restrict' } } : {}),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { decodeValue, type Statement, type WorkLimits } from '@romedb/client';
|
|
3
|
+
import { workspaceConnections } from './backend';
|
|
4
|
+
import { statementResult } from './data';
|
|
5
|
+
import type { SqlRun } from '../lib/studio-types';
|
|
6
|
+
|
|
7
|
+
export type QueryInput = { statements: { sql: string; parameters: string }[]; mode: 'read' | 'write'; ifSequence?: number; limits?: WorkLimits };
|
|
8
|
+
|
|
9
|
+
export async function runQuery(context: Context, connectionId: string, operationId: string, input: QueryInput) {
|
|
10
|
+
const actor = queryActor(context);
|
|
11
|
+
try {
|
|
12
|
+
const statements = queryStatements(input);
|
|
13
|
+
if (input.mode === 'read' && statements.some(statement => /^\s*(?:INSERT|UPDATE|DELETE|UPSERT|RELATE|CREATE|ALTER|DROP|DEFINE|REMOVE|REINDEX)\b/i.test(statement.sql))) {
|
|
14
|
+
return { error: { code: 'STUDIO_QUERY_MODE', message: 'This statement writes to the database. Select Atomic write and confirm execution. RomeQL document insert syntax: INSERT INTO users { id: users:tan, foo: \'Bar\' } (without VALUES).', outcome: 'not-sent' as const } };
|
|
15
|
+
}
|
|
16
|
+
return await workspaceConnections(context).execute(actor, connectionId, operationId, statements, input.mode, input.ifSequence, input.limits, true);
|
|
17
|
+
} catch (error) {
|
|
18
|
+
return { error: { code: 'STUDIO_QUERY', message: error instanceof Error ? error.message.slice(0, 512) : 'Invalid query request', outcome: 'not-sent' as const } };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function recoverQuery(context: Context, connectionId: string, operationId: string, recoveryId: string) {
|
|
23
|
+
const actor = queryActor(context);
|
|
24
|
+
try { return await workspaceConnections(context).recover(actor, connectionId, recoveryId, operationId, true); }
|
|
25
|
+
catch (error) { return { error: { code: 'STUDIO_RECOVERY', message: error instanceof Error ? error.message.slice(0, 512) : 'Recovery could not start', outcome: 'not-sent' as const } }; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function acknowledgeQuery(context: Context, connectionId: string, recoveryId: string, nonce: string) {
|
|
29
|
+
await workspaceConnections(context).acknowledge(queryActor(context), connectionId, recoveryId, nonce);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function savedRecoveryRequests(context: Context, connectionIds: string[]) {
|
|
33
|
+
const actor = queryActor(context);
|
|
34
|
+
if (!Array.isArray(connectionIds) || connectionIds.length > 16) throw new Error('Invalid connection list');
|
|
35
|
+
const connections = workspaceConnections(context);
|
|
36
|
+
const entries = [];
|
|
37
|
+
for (const id of connectionIds) entries.push([id, await connections.recoveryIds(actor, id)] as const);
|
|
38
|
+
return Object.fromEntries(entries);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function cancelQuery(context: Context, operationId: string) {
|
|
42
|
+
workspaceConnections(context).cancel(queryActor(context), operationId);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function queryStatements(input: QueryInput): Statement[] {
|
|
46
|
+
if (!input || !['read', 'write'].includes(input.mode) || !Array.isArray(input.statements) || input.statements.length < 1 || input.statements.length > 32) throw new Error('Choose 1–32 statements and a read or atomic write request');
|
|
47
|
+
if (input.ifSequence !== undefined && (!Number.isSafeInteger(input.ifSequence) || input.ifSequence < 0)) throw new Error('Expected revision must be a nonnegative safe integer');
|
|
48
|
+
if (input.limits !== undefined) {
|
|
49
|
+
if (!input.limits || typeof input.limits !== 'object' || Array.isArray(input.limits)) throw new Error('Invalid query work limits');
|
|
50
|
+
for (const [key, value] of Object.entries(input.limits)) if (!['rowsRead', 'rowMutations', 'vmSteps'].includes(key) || !Number.isSafeInteger(value) || value < 0 || value > 1000000) throw new Error('Query work limits require integers from 0 to 1000000');
|
|
51
|
+
}
|
|
52
|
+
let size = 0;
|
|
53
|
+
return input.statements.map(statement => {
|
|
54
|
+
if (!statement || typeof statement.sql !== 'string' || !statement.sql.trim() || typeof statement.parameters !== 'string') throw new Error('Enter SQL and a JSON parameter object for each statement');
|
|
55
|
+
size += Buffer.byteLength(statement.sql) + Buffer.byteLength(statement.parameters);
|
|
56
|
+
if (size > 65536) throw new Error('Query SQL and parameters exceed the 64 KiB editor limit');
|
|
57
|
+
const parameters: unknown = JSON.parse(statement.parameters);
|
|
58
|
+
if (!parameters || typeof parameters !== 'object' || Array.isArray(parameters) || Object.keys(parameters).length > 128) throw new Error('Parameters require an object with at most 128 named values');
|
|
59
|
+
const params = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {
|
|
60
|
+
if (!/^[\$:@][A-Za-z_][A-Za-z0-9_]{0,127}$/.test(key)) throw new Error('Parameter keys must include their SQL prefix, for example $id');
|
|
61
|
+
return [key, decodeValue(value)];
|
|
62
|
+
}));
|
|
63
|
+
return { sql: statement.sql, params };
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function queryActor(context: Context): string {
|
|
68
|
+
const user = context.get('user') as { id?: string } | undefined;
|
|
69
|
+
if (!user?.id) throw new Error('Studio session required');
|
|
70
|
+
return user.id;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Runs editor statements and converts each result into grid rows. Write
|
|
75
|
+
* receipts are returned so the page can acknowledge them or recover an
|
|
76
|
+
* uncertain outcome.
|
|
77
|
+
*/
|
|
78
|
+
export async function runSql(context: Context, connectionId: string, operationId: string, input: QueryInput) {
|
|
79
|
+
const started = performance.now();
|
|
80
|
+
const reply = await runQuery(context, connectionId, operationId, input);
|
|
81
|
+
const durationMs = performance.now() - started;
|
|
82
|
+
const receipt = {
|
|
83
|
+
...('recoveryId' in reply && reply.recoveryId ? { recoveryId: reply.recoveryId } : {}),
|
|
84
|
+
...('acknowledgement' in reply && reply.acknowledgement ? { acknowledgement: reply.acknowledgement } : {}),
|
|
85
|
+
};
|
|
86
|
+
if ('error' in reply && reply.error) {
|
|
87
|
+
const run: SqlRun = { results: [], durationMs, sequence: 'sequence' in reply.error && typeof reply.error.sequence === 'number' ? reply.error.sequence : 0, mode: input.mode, error: { code: reply.error.code, message: errorHint(reply.error.message), outcome: reply.error.outcome } };
|
|
88
|
+
return { run, ...receipt };
|
|
89
|
+
}
|
|
90
|
+
if (!('results' in reply) || !reply.results) return { run: { results: [], durationMs, sequence: 0, mode: input.mode, error: { code: 'STUDIO_QUERY', message: 'Invalid database response', outcome: 'read-failed' } } satisfies SqlRun, ...receipt };
|
|
91
|
+
const run: SqlRun = {
|
|
92
|
+
results: reply.results.map(result => ({ ...statementResult(result.columns, result.rows), affectedRows: Number(result.affected) })),
|
|
93
|
+
durationMs,
|
|
94
|
+
sequence: reply.sequence,
|
|
95
|
+
mode: input.mode,
|
|
96
|
+
};
|
|
97
|
+
return { run, ...receipt };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Services before this fix ran data writes in a concurrent transaction, so a
|
|
102
|
+
* document insert that creates its missing collection was rejected. Current
|
|
103
|
+
* services rerun such a write in an exclusive transaction instead.
|
|
104
|
+
*/
|
|
105
|
+
export function errorHint(message: string): string {
|
|
106
|
+
if (!/DDL statements require an exclusive transaction/i.test(message)) return message;
|
|
107
|
+
return `${message}. This usually means the statement creates a collection or table that does not exist yet. Create it first (for example CREATE TABLE posts, or the + button next to the object search), then run the statement again.`;
|
|
108
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { PortableValue } from '@romedb/client';
|
|
3
|
+
import { workspaceConnections, type WorkspaceDescriptor } from './backend';
|
|
4
|
+
import { parseForeignKeys, parseIndexColumns, quoteIdentifier } from '../lib/sql-text';
|
|
5
|
+
import { displayValue } from '../lib/values';
|
|
6
|
+
import { spatialIndexDetails } from '../lib/spatial';
|
|
7
|
+
import type { StudioColumn, StudioConnectionInfo, StudioIndex, StudioObject, StudioSchema } from '../lib/studio-types';
|
|
8
|
+
|
|
9
|
+
type ObjectValue = Extract<PortableValue, { type: 'Object' }>;
|
|
10
|
+
type SchemaRow = { type: string; name: string; table: string; sql: string | null };
|
|
11
|
+
|
|
12
|
+
const INTERNAL = /^(?:__romedb_|__turso_internal_|sqlite_)/i;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Builds the Studio schema for one open connection from RomeDB's logical
|
|
16
|
+
* metadata (`INFO FOR DB` and `INFO FOR TABLE`) plus the stored SQL text for
|
|
17
|
+
* definitions, foreign keys and index columns.
|
|
18
|
+
*/
|
|
19
|
+
export async function loadSchema(context: Context, connectionId: string): Promise<StudioSchema> {
|
|
20
|
+
if (!connectionId) return { connection: null, objects: [], sequence: 0 };
|
|
21
|
+
const actor = actorId(context);
|
|
22
|
+
const connections = workspaceConnections(context);
|
|
23
|
+
try {
|
|
24
|
+
const descriptor = await connections.describe(actor, connectionId);
|
|
25
|
+
const first = await connections.execute(actor, connectionId, crypto.randomUUID(), [
|
|
26
|
+
{ sql: 'INFO FOR DB' },
|
|
27
|
+
{ sql: 'SELECT type, name, tbl_name, sql FROM sqlite_schema' },
|
|
28
|
+
{ sql: 'SELECT sqlite_version()' },
|
|
29
|
+
], 'read');
|
|
30
|
+
if (!('results' in first) || !first.results) throw new Error('error' in first && first.error ? first.error.message : 'Invalid database response');
|
|
31
|
+
const database = first.results[0]?.rows[0]?.[0];
|
|
32
|
+
if (database?.type !== 'Object') throw new Error('Database returned invalid logical metadata');
|
|
33
|
+
const stored: SchemaRow[] = (first.results[1]?.rows ?? []).map(row => ({
|
|
34
|
+
type: text(row[0]) ?? '',
|
|
35
|
+
name: text(row[1]) ?? '',
|
|
36
|
+
table: text(row[2]) ?? '',
|
|
37
|
+
sql: text(row[3]),
|
|
38
|
+
}));
|
|
39
|
+
const listed: { name: string; view: boolean; model: string }[] = [];
|
|
40
|
+
for (const key of ['tables', 'views'] as const) {
|
|
41
|
+
const entries = database.value[key];
|
|
42
|
+
if (entries?.type !== 'Array') continue;
|
|
43
|
+
for (const entry of entries.value) {
|
|
44
|
+
if (entry.type !== 'Object') continue;
|
|
45
|
+
const name = text(entry.value.name);
|
|
46
|
+
if (!name || INTERNAL.test(name)) continue;
|
|
47
|
+
listed.push({ name, view: key === 'views', model: text(entry.value.model) ?? (key === 'views' ? 'view' : 'relational') });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const infos: (PortableValue | undefined)[] = [];
|
|
51
|
+
let sequence = first.sequence;
|
|
52
|
+
for (let offset = 0; offset < listed.length; offset += 32) {
|
|
53
|
+
const chunk = listed.slice(offset, offset + 32);
|
|
54
|
+
const reply = await connections.execute(actor, connectionId, crypto.randomUUID(), chunk.map(object => ({ sql: `INFO FOR TABLE ${quoteIdentifier(object.name)}` })), 'read');
|
|
55
|
+
if (!('results' in reply) || !reply.results) throw new Error('error' in reply && reply.error ? reply.error.message : 'Invalid database response');
|
|
56
|
+
sequence = reply.sequence;
|
|
57
|
+
infos.push(...reply.results.map(result => result.rows[0]?.[0]));
|
|
58
|
+
}
|
|
59
|
+
const primaryKeys = new Map<string, string[]>();
|
|
60
|
+
listed.forEach((object, index) => {
|
|
61
|
+
const info = infos[index];
|
|
62
|
+
if (info?.type === 'Object') primaryKeys.set(object.name.toLowerCase(), relationalColumns(info).filter(column => column.primaryKeyPosition).sort((a, b) => a.primaryKeyPosition - b.primaryKeyPosition).map(column => column.name));
|
|
63
|
+
});
|
|
64
|
+
const objects = listed.map((object, index) => buildObject(object, infos[index], stored, table => primaryKeys.get(table.toLowerCase()) ?? []));
|
|
65
|
+
objects.sort((left, right) => left.name.localeCompare(right.name));
|
|
66
|
+
return { connection: connectionInfo(descriptor, text(first.results[2]?.rows[0]?.[0])), objects, sequence };
|
|
67
|
+
} catch (error) {
|
|
68
|
+
let connection: StudioConnectionInfo | null = null;
|
|
69
|
+
try { connection = connectionInfo(await connections.describe(actor, connectionId)); } catch {}
|
|
70
|
+
return { connection, objects: [], sequence: 0, error: error instanceof Error ? error.message.slice(0, 512) : 'Cannot load database metadata' };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function connectionInfo(descriptor: WorkspaceDescriptor, databaseVersion?: string | null): StudioConnectionInfo {
|
|
75
|
+
return {
|
|
76
|
+
connectionId: descriptor.connectionId,
|
|
77
|
+
profileId: descriptor.profileId,
|
|
78
|
+
name: descriptor.name,
|
|
79
|
+
kind: descriptor.kind,
|
|
80
|
+
endpoint: descriptor.endpoint,
|
|
81
|
+
databaseId: descriptor.databaseId,
|
|
82
|
+
sequence: descriptor.sequence,
|
|
83
|
+
remote: descriptor.kind === 'url' && !isLoopback(descriptor.endpoint),
|
|
84
|
+
capabilities: { ...descriptor.capabilities },
|
|
85
|
+
limits: { ...descriptor.limits },
|
|
86
|
+
...(descriptor.journalMode ? { journalMode: descriptor.journalMode } : {}),
|
|
87
|
+
...engineVersions(descriptor, databaseVersion),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* RomeDB 2.7.0 and later report their version when Studio connects. A file is
|
|
93
|
+
* opened by Studio's own SDK, so its version is known even when the SDK is
|
|
94
|
+
* older. A database URL that reports no version runs RomeDB 2.6 or older.
|
|
95
|
+
*/
|
|
96
|
+
function engineVersions(descriptor: { kind: 'file' | 'url'; engineVersion?: string; clientVersion?: string }, sqliteVersion?: string | null) {
|
|
97
|
+
const engine = descriptor.engineVersion ?? (descriptor.kind === 'file' ? descriptor.clientVersion : undefined);
|
|
98
|
+
const romedb = engine ? `RomeDB ${engine}` : descriptor.kind === 'url' ? 'RomeDB 2.6 or older' : '';
|
|
99
|
+
return {
|
|
100
|
+
...(engine ? { engineVersion: engine } : {}),
|
|
101
|
+
...(descriptor.clientVersion ? { clientVersion: descriptor.clientVersion } : {}),
|
|
102
|
+
databaseVersion: [romedb, sqliteVersion ? `SQLite ${sqliteVersion}` : ''].filter(Boolean).join(' · '),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function isLoopback(endpoint: string): boolean {
|
|
107
|
+
try {
|
|
108
|
+
const host = new URL(endpoint).hostname.replace(/^\[|\]$/g, '');
|
|
109
|
+
return host === 'localhost' || host === '::1' || /^127\./.test(host);
|
|
110
|
+
} catch { return false; }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function buildObject(object: { name: string; view: boolean; model: string }, info: PortableValue | undefined, stored: SchemaRow[], primaryKeyOf: (table: string) => string[]): StudioObject {
|
|
114
|
+
const definition = stored.find(row => (row.type === 'table' || row.type === 'view') && row.name.toLowerCase() === object.name.toLowerCase())?.sql ?? null;
|
|
115
|
+
if (info?.type !== 'Object') {
|
|
116
|
+
return { name: object.name, kind: object.view ? 'view' : 'table', model: object.view ? 'view' : object.model === 'document' ? 'document' : 'relational', sql: definition, columns: [], indexes: [], foreignKeys: [], keyFields: [], editable: false, readOnlyReason: 'Metadata for this object is unavailable.' };
|
|
117
|
+
}
|
|
118
|
+
if (object.view || text(info.value.kind) === 'view') {
|
|
119
|
+
return { name: object.name, kind: 'view', model: 'view', sql: definition, columns: relationalColumns(info), indexes: [], foreignKeys: [], keyFields: [], editable: false, readOnlyReason: 'Views are read only. Edit the underlying tables instead.' };
|
|
120
|
+
}
|
|
121
|
+
if (text(info.value.model) === 'document') {
|
|
122
|
+
const fields = array(info.value.fields).flatMap((field): StudioColumn[] => {
|
|
123
|
+
if (field.type !== 'Object') return [];
|
|
124
|
+
const path = array(field.value.path).map(part => text(part) ?? '').filter(Boolean).join('.');
|
|
125
|
+
if (!path || path === 'id') return [];
|
|
126
|
+
const type = text(field.value.type) ?? 'any';
|
|
127
|
+
const element = text(field.value.element_type);
|
|
128
|
+
return [{
|
|
129
|
+
name: path,
|
|
130
|
+
dataType: element ? `${type}<${element}>` : type,
|
|
131
|
+
affinity: 'any',
|
|
132
|
+
nullable: flag(field.value.nullable) || !flag(field.value.required),
|
|
133
|
+
defaultValue: flag(field.value.has_default) ? metadataText(field.value.default) : null,
|
|
134
|
+
primaryKeyPosition: 0,
|
|
135
|
+
hidden: false,
|
|
136
|
+
required: flag(field.value.required),
|
|
137
|
+
readonly: flag(field.value.readonly),
|
|
138
|
+
check: text(field.value.check),
|
|
139
|
+
}];
|
|
140
|
+
});
|
|
141
|
+
const indexes = array(info.value.indexes).flatMap((index): StudioIndex[] => {
|
|
142
|
+
if (index.type !== 'Object') return [];
|
|
143
|
+
const name = text(index.value.name);
|
|
144
|
+
if (!name || INTERNAL.test(name)) return [];
|
|
145
|
+
const paths = array(index.value.paths).length
|
|
146
|
+
? array(index.value.paths).map(path => array(path).map(part => text(part) ?? '').join('.'))
|
|
147
|
+
: [array(index.value.path).map(part => text(part) ?? '').join('.')];
|
|
148
|
+
const kind = text(index.value.kind);
|
|
149
|
+
return [{
|
|
150
|
+
name, kind: indexKind(kind), unique: flag(index.value.unique), origin: 'c', partial: false, columns: paths.filter(Boolean),
|
|
151
|
+
...(kind === 'spatial' ? spatialIndexDetails({ geometry: text(index.value.geometry), format: text(index.value.format) }, name, stored) : {}),
|
|
152
|
+
}];
|
|
153
|
+
});
|
|
154
|
+
const edgeInfo = info.value.edge?.type === 'Object' ? info.value.edge.value : null;
|
|
155
|
+
const edge = edgeInfo && text(edgeInfo.source) && text(edgeInfo.target)
|
|
156
|
+
? { source: text(edgeInfo.source)!, target: text(edgeInfo.target)!, onDelete: text(edgeInfo.on_delete) === 'cascade' ? 'cascade' as const : 'restrict' as const }
|
|
157
|
+
: undefined;
|
|
158
|
+
const endpoints: StudioColumn[] = edge
|
|
159
|
+
? (['source', 'target'] as const).map(name => ({
|
|
160
|
+
name, dataType: `record<${edge[name]}>`, affinity: 'any' as const, nullable: false, defaultValue: null,
|
|
161
|
+
primaryKeyPosition: 0, hidden: false, required: true, readonly: true,
|
|
162
|
+
}))
|
|
163
|
+
: [];
|
|
164
|
+
const edgeTables = array(info.value.edge_tables).map(entry => text(entry) ?? '').filter(Boolean);
|
|
165
|
+
return {
|
|
166
|
+
name: object.name,
|
|
167
|
+
kind: 'table',
|
|
168
|
+
model: 'document',
|
|
169
|
+
sql: null,
|
|
170
|
+
...(edge ? { edge } : {}),
|
|
171
|
+
...(edgeTables.length ? { edgeTables } : {}),
|
|
172
|
+
columns: [{ name: 'id', dataType: 'record', affinity: 'any', nullable: false, defaultValue: null, primaryKeyPosition: 1, hidden: false, required: true }, ...endpoints, ...fields],
|
|
173
|
+
indexes,
|
|
174
|
+
foreignKeys: [],
|
|
175
|
+
keyFields: ['id'],
|
|
176
|
+
editable: true,
|
|
177
|
+
strict: flag(info.value.strict),
|
|
178
|
+
capabilities: array(info.value.capabilities).map(entry => text(entry) ?? '').filter(Boolean),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
const columns = relationalColumns(info);
|
|
182
|
+
const keyFields = columns.filter(column => column.primaryKeyPosition).sort((a, b) => a.primaryKeyPosition - b.primaryKeyPosition).map(column => column.name);
|
|
183
|
+
const indexes = array(info.value.indexes).flatMap((index): StudioIndex[] => {
|
|
184
|
+
if (index.type !== 'Object') return [];
|
|
185
|
+
const name = text(index.value.name);
|
|
186
|
+
if (!name || /^(?:__romedb_|__turso_internal_)/i.test(name)) return [];
|
|
187
|
+
const sql = stored.find(row => row.type === 'index' && row.name === name)?.sql ?? null;
|
|
188
|
+
const origin = text(index.value.origin) ?? 'c';
|
|
189
|
+
return [{
|
|
190
|
+
name,
|
|
191
|
+
kind: 'B-tree',
|
|
192
|
+
unique: flag(index.value.unique),
|
|
193
|
+
origin: origin === 'pk' ? 'primary key' : origin === 'u' ? 'unique constraint' : 'CREATE INDEX',
|
|
194
|
+
partial: flag(index.value.partial),
|
|
195
|
+
columns: parseIndexColumns(sql),
|
|
196
|
+
}];
|
|
197
|
+
});
|
|
198
|
+
return {
|
|
199
|
+
name: object.name,
|
|
200
|
+
kind: 'table',
|
|
201
|
+
model: 'relational',
|
|
202
|
+
sql: definition,
|
|
203
|
+
columns,
|
|
204
|
+
indexes,
|
|
205
|
+
foreignKeys: parseForeignKeys(definition, primaryKeyOf),
|
|
206
|
+
keyFields,
|
|
207
|
+
editable: keyFields.length > 0,
|
|
208
|
+
...(keyFields.length ? {} : { readOnlyReason: 'This table has no explicit primary key, so Studio cannot identify rows for editing. Browsing remains available.' }),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function relationalColumns(info: ObjectValue): StudioColumn[] {
|
|
213
|
+
return array(info.value.columns).flatMap((column): StudioColumn[] => {
|
|
214
|
+
if (column.type !== 'Object') return [];
|
|
215
|
+
const name = text(column.value.name);
|
|
216
|
+
if (!name) return [];
|
|
217
|
+
const dataType = text(column.value.type) ?? '';
|
|
218
|
+
return [{
|
|
219
|
+
name,
|
|
220
|
+
dataType,
|
|
221
|
+
affinity: affinity(dataType),
|
|
222
|
+
nullable: !flag(column.value.notnull),
|
|
223
|
+
defaultValue: column.value.dflt_value && column.value.dflt_value.type !== 'Null' ? metadataText(column.value.dflt_value) : null,
|
|
224
|
+
primaryKeyPosition: Number(text(column.value.pk) ?? 0) || 0,
|
|
225
|
+
hidden: flag(column.value.hidden),
|
|
226
|
+
}];
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** SQLite type affinity rules, section 3.1 of the datatype documentation. */
|
|
231
|
+
export function affinity(type: string): StudioColumn['affinity'] {
|
|
232
|
+
const upper = type.toUpperCase();
|
|
233
|
+
if (!upper) return 'blob';
|
|
234
|
+
if (upper.includes('INT')) return 'integer';
|
|
235
|
+
if (/CHAR|CLOB|TEXT/.test(upper)) return 'text';
|
|
236
|
+
if (upper.includes('BLOB')) return 'blob';
|
|
237
|
+
if (/REAL|FLOA|DOUB/.test(upper)) return 'real';
|
|
238
|
+
return 'numeric';
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function indexKind(kind: string | null): string {
|
|
242
|
+
const kinds: Record<string, string> = { scalar: 'Scalar', array: 'Array', fulltext: 'Full-text', vector: 'Vector', spatial: 'Spatial' };
|
|
243
|
+
return kind && Object.hasOwn(kinds, kind) ? kinds[kind] : kind ?? 'Scalar';
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function text(value: PortableValue | undefined): string | null {
|
|
247
|
+
if (!value) return null;
|
|
248
|
+
if (value.type === 'String' || value.type === 'Integer') return value.value;
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function flag(value: PortableValue | undefined): boolean {
|
|
253
|
+
if (!value) return false;
|
|
254
|
+
if (value.type === 'Boolean') return value.value;
|
|
255
|
+
if (value.type === 'Integer') return value.value !== '0';
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function array(value: PortableValue | undefined): PortableValue[] {
|
|
260
|
+
return value?.type === 'Array' ? value.value : [];
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function metadataText(value: PortableValue | undefined): string | null {
|
|
264
|
+
if (!value || value.type === 'Null') return null;
|
|
265
|
+
return displayValue(value);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function actorId(context: Context): string {
|
|
269
|
+
const actor = context.get('user') as { id?: string } | undefined;
|
|
270
|
+
if (!actor?.id) throw new Error('Studio session required');
|
|
271
|
+
return actor.id;
|
|
272
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { PortableValue } from '@romedb/client';
|
|
3
|
+
import { workspaceConnections } from './backend';
|
|
4
|
+
import { statementResult } from './data';
|
|
5
|
+
import { mapQuery, resultFeatures, SPATIAL_SCHEMA_SQL, spatialIndexDetails } from '../lib/spatial';
|
|
6
|
+
import { quoteIdentifier } from '../lib/sql-text';
|
|
7
|
+
import type { MapRequest, MapView } from '../lib/studio-types';
|
|
8
|
+
|
|
9
|
+
const INTERNAL = /^(?:__romedb_|__turso_internal_|sqlite_)/i;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Loads one bounded page of geometry for the Map tab. The index declaration
|
|
13
|
+
* (and, before 2.5.1, its stored schema) is re-read for each request, so the query
|
|
14
|
+
* always matches the database rather than a cached client schema. All reads
|
|
15
|
+
* use the connection's normal read path and work budgets.
|
|
16
|
+
*/
|
|
17
|
+
export async function loadMap(context: Context, connectionId: string, request: MapRequest): Promise<MapView> {
|
|
18
|
+
const actor = context.get('user') as { id?: string } | undefined;
|
|
19
|
+
if (!actor?.id) throw new Error('Studio session required');
|
|
20
|
+
const started = performance.now();
|
|
21
|
+
const empty: MapView = { features: [], rows: 0, limit: request?.limit ?? 0, truncated: false, query: '', durationMs: 0, sequence: 0 };
|
|
22
|
+
try {
|
|
23
|
+
if (typeof request?.table !== 'string' || !request.table || INTERNAL.test(request.table)) throw new Error('Choose a collection.');
|
|
24
|
+
if (typeof request.index !== 'string' || !request.index || request.index.length > 1024 || INTERNAL.test(request.index)) throw new Error('Choose a spatial index.');
|
|
25
|
+
const connections = workspaceConnections(context);
|
|
26
|
+
const metadata = await connections.execute(actor.id, connectionId, crypto.randomUUID(), [
|
|
27
|
+
{ sql: `INFO FOR TABLE ${quoteIdentifier(request.table)}` },
|
|
28
|
+
], 'read');
|
|
29
|
+
if (!('results' in metadata) || !metadata.results) {
|
|
30
|
+
throw new Error('error' in metadata && metadata.error ? metadata.error.message : 'Invalid database response');
|
|
31
|
+
}
|
|
32
|
+
const info = metadata.results[0]?.rows[0]?.[0];
|
|
33
|
+
if (info?.type !== 'Object' || text(info.value.model) !== 'document') throw new Error(`${request.table} is not a document collection.`);
|
|
34
|
+
const declared = array(info.value.indexes).find(index => index.type === 'Object' && text(index.value.name) === request.index && text(index.value.kind) === 'spatial');
|
|
35
|
+
if (declared?.type !== 'Object') throw new Error(`${request.index} is not a spatial index on ${request.table}.`);
|
|
36
|
+
const path = array(declared.value.path).map(part => text(part) ?? '');
|
|
37
|
+
let { geometry } = spatialIndexDetails({ geometry: text(declared.value.geometry) }, request.index);
|
|
38
|
+
if (!geometry) {
|
|
39
|
+
// Engines before 2.5.1 do not report the geometry kind; read the stored schema instead.
|
|
40
|
+
const schema = await connections.execute(actor.id, connectionId, crypto.randomUUID(), [{ sql: SPATIAL_SCHEMA_SQL, params: { $index: request.index } }], 'read');
|
|
41
|
+
if ('results' in schema && schema.results) {
|
|
42
|
+
const stored = (schema.results[0]?.rows ?? []).map(row => ({ type: text(row[0]) ?? '', name: text(row[1]) ?? '', table: text(row[2]) ?? '', sql: text(row[3]) }));
|
|
43
|
+
geometry = spatialIndexDetails({}, request.index, stored).geometry;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const built = mapQuery({ name: text(info.value.name) ?? request.table }, path, request.index, geometry, request);
|
|
47
|
+
const reply = await connections.execute(actor.id, connectionId, crypto.randomUUID(), [{ sql: built.sql, params: built.params }], 'read');
|
|
48
|
+
if (!('results' in reply) || !reply.results) {
|
|
49
|
+
return { ...empty, geometry, query: built.display, durationMs: performance.now() - started, error: 'error' in reply && reply.error ? `${reply.error.code}: ${reply.error.message}` : 'Invalid database response' };
|
|
50
|
+
}
|
|
51
|
+
const result = statementResult(reply.results[0]?.columns ?? [], reply.results[0]?.rows ?? []);
|
|
52
|
+
const { features, truncated } = resultFeatures(result);
|
|
53
|
+
return {
|
|
54
|
+
features,
|
|
55
|
+
rows: result.rows.length,
|
|
56
|
+
limit: request.limit,
|
|
57
|
+
truncated: truncated || result.rows.length >= request.limit,
|
|
58
|
+
geometry,
|
|
59
|
+
query: built.display,
|
|
60
|
+
durationMs: performance.now() - started,
|
|
61
|
+
sequence: reply.sequence,
|
|
62
|
+
};
|
|
63
|
+
} catch (error) {
|
|
64
|
+
return { ...empty, durationMs: performance.now() - started, error: error instanceof Error ? error.message.slice(0, 512) : 'Cannot load the map' };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function text(value: PortableValue | undefined): string | null {
|
|
69
|
+
return value?.type === 'String' ? value.value : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function array(value: PortableValue | undefined): PortableValue[] {
|
|
73
|
+
return value?.type === 'Array' ? value.value : [];
|
|
74
|
+
}
|