@romedb/studio 0.0.0-stage → 0.1.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/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 +1984 -0
- package/src/workspace/workspace.css +38 -0
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
import type { PortableValue } from '@romedb/client';
|
|
2
|
+
import type { Geometry, MapFeature, MapRequest, Position, SpatialGeometryKind, StatementResult, StudioIndex, StudioObject, StudioSchema } from './studio-types';
|
|
3
|
+
import { quoteIdentifier } from './sql-text';
|
|
4
|
+
import { displayValue, numberText, recordText } from './values';
|
|
5
|
+
|
|
6
|
+
/** Row limits offered by the Map tab. Reads still use the connection's work budgets. */
|
|
7
|
+
export const MAP_LIMITS = [100, 250, 500, 1000];
|
|
8
|
+
export const MAX_MAP_FEATURES = 2000;
|
|
9
|
+
/** Total positions drawn in one map, so a few large regions cannot stall the page. */
|
|
10
|
+
export const MAX_MAP_VERTICES = 200_000;
|
|
11
|
+
/** Contract limit on positions in one geometry. Larger objects are shown as JSON. */
|
|
12
|
+
const MAX_POSITIONS = 100_000;
|
|
13
|
+
/** Smallest extent the map zooms to, in degrees, so a single point still has a frame. */
|
|
14
|
+
const MIN_SPAN = 0.01;
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Values.
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Decodes a RomeDB geometry: an object with exactly `type` and `coordinates`,
|
|
21
|
+
* holding a Point, Polygon or MultiPolygon in longitude/latitude order. Other
|
|
22
|
+
* objects, including invalid coordinates or open rings, return null and keep
|
|
23
|
+
* their ordinary JSON display.
|
|
24
|
+
*/
|
|
25
|
+
export function geometryOf(value: PortableValue | undefined): Geometry | null {
|
|
26
|
+
if (value?.type !== 'Object') return null;
|
|
27
|
+
const members = value.value;
|
|
28
|
+
const keys = Object.keys(members);
|
|
29
|
+
if (keys.length !== 2 || !members.type || !members.coordinates) return null;
|
|
30
|
+
if (members.type.type !== 'String') return null;
|
|
31
|
+
const budget = { positions: 0 };
|
|
32
|
+
switch (members.type.value) {
|
|
33
|
+
case 'Point': {
|
|
34
|
+
const point = position(members.coordinates);
|
|
35
|
+
return point ? { type: 'Point', coordinates: point } : null;
|
|
36
|
+
}
|
|
37
|
+
case 'Polygon': {
|
|
38
|
+
const rings = polygon(members.coordinates, budget);
|
|
39
|
+
return rings ? { type: 'Polygon', coordinates: rings } : null;
|
|
40
|
+
}
|
|
41
|
+
case 'MultiPolygon': {
|
|
42
|
+
if (members.coordinates.type !== 'Array' || !members.coordinates.value.length) return null;
|
|
43
|
+
const polygons: Position[][][] = [];
|
|
44
|
+
for (const entry of members.coordinates.value) {
|
|
45
|
+
const rings = polygon(entry, budget);
|
|
46
|
+
if (!rings) return null;
|
|
47
|
+
polygons.push(rings);
|
|
48
|
+
}
|
|
49
|
+
return { type: 'MultiPolygon', coordinates: polygons };
|
|
50
|
+
}
|
|
51
|
+
default: return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function coordinate(value: PortableValue | undefined): number | null {
|
|
56
|
+
if (value?.type === 'Integer') return Number(value.value);
|
|
57
|
+
if (value?.type === 'Number') return Number(numberText(value.value));
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function position(value: PortableValue | undefined): Position | null {
|
|
62
|
+
if (value?.type !== 'Array' || value.value.length !== 2) return null;
|
|
63
|
+
const longitude = coordinate(value.value[0]);
|
|
64
|
+
const latitude = coordinate(value.value[1]);
|
|
65
|
+
if (longitude === null || latitude === null || !Number.isFinite(longitude) || !Number.isFinite(latitude)) return null;
|
|
66
|
+
if (longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) return null;
|
|
67
|
+
return [longitude, latitude];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function polygon(value: PortableValue | undefined, budget: { positions: number }): Position[][] | null {
|
|
71
|
+
if (value?.type !== 'Array' || !value.value.length) return null;
|
|
72
|
+
const rings: Position[][] = [];
|
|
73
|
+
for (const entry of value.value) {
|
|
74
|
+
if (entry.type !== 'Array' || entry.value.length < 4) return null;
|
|
75
|
+
budget.positions += entry.value.length;
|
|
76
|
+
if (budget.positions > MAX_POSITIONS) return null;
|
|
77
|
+
const ring: Position[] = [];
|
|
78
|
+
for (const point of entry.value) {
|
|
79
|
+
const decoded = position(point);
|
|
80
|
+
if (!decoded) return null;
|
|
81
|
+
ring.push(decoded);
|
|
82
|
+
}
|
|
83
|
+
const first = ring[0];
|
|
84
|
+
const last = ring[ring.length - 1];
|
|
85
|
+
if (first[0] !== last[0] || first[1] !== last[1]) return null;
|
|
86
|
+
rings.push(ring);
|
|
87
|
+
}
|
|
88
|
+
return rings;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Distinct vertices of a polygon: each closed ring repeats its first position. */
|
|
92
|
+
function vertexCount(rings: Position[][]): number {
|
|
93
|
+
return rings.reduce((total, ring) => total + ring.length - 1, 0);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function plural(count: number, noun: string, nouns = `${noun}s`): string {
|
|
97
|
+
return `${count} ${count === 1 ? noun : nouns}`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** One-line description: `POINT(106.7 10.8)`, `Polygon · 4 vertices`, `MultiPolygon · 2 polygons · 8 vertices`. */
|
|
101
|
+
export function geometrySummary(geometry: Geometry): string {
|
|
102
|
+
switch (geometry.type) {
|
|
103
|
+
case 'Point': return `POINT(${geometry.coordinates[0]} ${geometry.coordinates[1]})`;
|
|
104
|
+
case 'Polygon': {
|
|
105
|
+
const holes = geometry.coordinates.length - 1;
|
|
106
|
+
return `Polygon · ${plural(vertexCount(geometry.coordinates), 'vertex', 'vertices')}${holes ? ` · ${plural(holes, 'hole')}` : ''}`;
|
|
107
|
+
}
|
|
108
|
+
case 'MultiPolygon': {
|
|
109
|
+
const vertices = geometry.coordinates.reduce((total, rings) => total + vertexCount(rings), 0);
|
|
110
|
+
return `MultiPolygon · ${plural(geometry.coordinates.length, 'polygon')} · ${plural(vertices, 'vertex', 'vertices')}`;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Grid text: a compact summary for geometry, otherwise the ordinary display value. */
|
|
116
|
+
export function cellText(value: PortableValue | undefined): string {
|
|
117
|
+
const geometry = geometryOf(value);
|
|
118
|
+
return geometry ? geometrySummary(geometry) : displayValue(value);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
// Result rows to map features.
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Collects geometry values from result rows: top-level columns and fields one
|
|
126
|
+
* level inside object columns (for example `address.location`). The `id`
|
|
127
|
+
* column, when it is a record ID, identifies each feature.
|
|
128
|
+
*/
|
|
129
|
+
export function resultFeatures(result: StatementResult, maxFeatures = MAX_MAP_FEATURES, maxVertices = MAX_MAP_VERTICES): { features: MapFeature[]; truncated: boolean } {
|
|
130
|
+
const features: MapFeature[] = [];
|
|
131
|
+
let vertices = 0;
|
|
132
|
+
let truncated = false;
|
|
133
|
+
result.rows.forEach((row, rowIndex) => {
|
|
134
|
+
if (truncated) return;
|
|
135
|
+
const id = row.id?.type === 'Record' ? row.id : null;
|
|
136
|
+
const label = id ? recordText(id.value) : `Row ${rowIndex + 1}`;
|
|
137
|
+
const add = (column: string, geometry: Geometry) => {
|
|
138
|
+
const size = geometry.type === 'Point' ? 1 : geometry.type === 'Polygon' ? vertexCount(geometry.coordinates) : geometry.coordinates.reduce((total, rings) => total + vertexCount(rings), 0);
|
|
139
|
+
if (features.length >= maxFeatures || vertices + size > maxVertices) { truncated = true; return; }
|
|
140
|
+
vertices += size;
|
|
141
|
+
features.push({ key: `${label}#${column}`, id, label, table: id ? id.value.table : column, column, geometry, summary: geometrySummary(geometry) });
|
|
142
|
+
};
|
|
143
|
+
for (const column of result.columns) {
|
|
144
|
+
if (truncated) return;
|
|
145
|
+
if (column === 'id') continue;
|
|
146
|
+
const value = row[column];
|
|
147
|
+
const geometry = geometryOf(value);
|
|
148
|
+
if (geometry) { add(column, geometry); continue; }
|
|
149
|
+
if (value?.type !== 'Object') continue;
|
|
150
|
+
for (const [field, inner] of Object.entries(value.value)) {
|
|
151
|
+
const nested = geometryOf(inner);
|
|
152
|
+
if (nested) add(`${column}.${field}`, nested);
|
|
153
|
+
if (truncated) return;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
return { features, truncated };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
// Bounds and projection.
|
|
162
|
+
|
|
163
|
+
export interface MapBounds {
|
|
164
|
+
/** Western edge in degrees. */
|
|
165
|
+
west: number;
|
|
166
|
+
/** Eastern edge; above 180 when the data crosses the antimeridian. */
|
|
167
|
+
east: number;
|
|
168
|
+
south: number;
|
|
169
|
+
north: number;
|
|
170
|
+
/** Longitudes below this value are drawn 360 degrees east. Null when nothing wraps. */
|
|
171
|
+
pivot: number | null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Longitude interval of each point and each polygon component. Polygon edges never wrap. */
|
|
175
|
+
function components(geometry: Geometry): Position[][] {
|
|
176
|
+
switch (geometry.type) {
|
|
177
|
+
case 'Point': return [[geometry.coordinates]];
|
|
178
|
+
case 'Polygon': return [geometry.coordinates[0]];
|
|
179
|
+
case 'MultiPolygon': return geometry.coordinates.map(rings => rings[0]);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Smallest longitude range that holds every feature, allowing it to cross the
|
|
185
|
+
* antimeridian. Each point and polygon component is an interval (RomeDB
|
|
186
|
+
* polygon edges are straight in longitude/latitude, and regions crossing 180
|
|
187
|
+
* are stored as split components). The largest longitude gap not covered by
|
|
188
|
+
* any interval is left out of the view. Longitudes -180 and 180 are the same
|
|
189
|
+
* place, so data on both seams fits a narrow view around 180.
|
|
190
|
+
*/
|
|
191
|
+
export function mapBounds(geometries: Geometry[]): MapBounds | null {
|
|
192
|
+
const intervals: [number, number][] = [];
|
|
193
|
+
let south = Infinity;
|
|
194
|
+
let north = -Infinity;
|
|
195
|
+
for (const geometry of geometries) {
|
|
196
|
+
for (const ring of components(geometry)) {
|
|
197
|
+
let west = Infinity;
|
|
198
|
+
let east = -Infinity;
|
|
199
|
+
for (const [longitude, latitude] of ring) {
|
|
200
|
+
west = Math.min(west, longitude);
|
|
201
|
+
east = Math.max(east, longitude);
|
|
202
|
+
south = Math.min(south, latitude);
|
|
203
|
+
north = Math.max(north, latitude);
|
|
204
|
+
}
|
|
205
|
+
intervals.push([west, east]);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (!intervals.length) return null;
|
|
209
|
+
intervals.sort((left, right) => left[0] - right[0] || left[1] - right[1]);
|
|
210
|
+
const merged: [number, number][] = [];
|
|
211
|
+
for (const interval of intervals) {
|
|
212
|
+
const last = merged[merged.length - 1];
|
|
213
|
+
if (last && interval[0] <= last[1]) last[1] = Math.max(last[1], interval[1]);
|
|
214
|
+
else merged.push([...interval]);
|
|
215
|
+
}
|
|
216
|
+
// The gap across the antimeridian wins ties, so ordinary data never wraps.
|
|
217
|
+
let gap = merged[0][0] + 360 - merged[merged.length - 1][1];
|
|
218
|
+
let after = -1;
|
|
219
|
+
for (let index = 0; index + 1 < merged.length; index += 1) {
|
|
220
|
+
const inner = merged[index + 1][0] - merged[index][1];
|
|
221
|
+
if (inner > gap) { gap = inner; after = index; }
|
|
222
|
+
}
|
|
223
|
+
if (after < 0) return { west: merged[0][0], east: merged[merged.length - 1][1], south, north, pivot: null };
|
|
224
|
+
return {
|
|
225
|
+
west: merged[after + 1][0],
|
|
226
|
+
east: merged[after][1] + 360,
|
|
227
|
+
south,
|
|
228
|
+
north,
|
|
229
|
+
pivot: (merged[after][1] + merged[after + 1][0]) / 2,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export interface MapProjection {
|
|
234
|
+
width: number;
|
|
235
|
+
height: number;
|
|
236
|
+
/** Visible extent; east may exceed 180 and latitudes may pass the poles. */
|
|
237
|
+
west: number;
|
|
238
|
+
east: number;
|
|
239
|
+
south: number;
|
|
240
|
+
north: number;
|
|
241
|
+
project(position: Position): [number, number];
|
|
242
|
+
/** Linear placement of an unwrapped longitude or a latitude, for graticule lines. */
|
|
243
|
+
x(longitude: number): number;
|
|
244
|
+
y(latitude: number): number;
|
|
245
|
+
/** Inverse of project, with longitude normalized to [-180, 180] and latitude clamped. */
|
|
246
|
+
invert(x: number, y: number): Position;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Normalizes a longitude to [-180, 180]. 180 stays 180. */
|
|
250
|
+
export function normalizeLongitude(longitude: number): number {
|
|
251
|
+
if (longitude >= -180 && longitude <= 180) return longitude;
|
|
252
|
+
const wrapped = ((((longitude + 180) % 360) + 360) % 360) - 180;
|
|
253
|
+
return wrapped === -180 && longitude > 0 ? 180 : wrapped;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Equirectangular projection fitted to bounds inside a width × height frame.
|
|
258
|
+
* Longitudes are scaled by the cosine of the center latitude (limited to
|
|
259
|
+
* 0.25 near the poles) so shapes keep their local proportions.
|
|
260
|
+
*/
|
|
261
|
+
export function createProjection(bounds: MapBounds, width = 960, height = 540, padding = 28): MapProjection {
|
|
262
|
+
const lonSpan = Math.max(bounds.east - bounds.west, MIN_SPAN);
|
|
263
|
+
const latSpan = Math.max(bounds.north - bounds.south, MIN_SPAN);
|
|
264
|
+
const centerLon = (bounds.west + bounds.east) / 2;
|
|
265
|
+
const centerLat = (bounds.south + bounds.north) / 2;
|
|
266
|
+
const cosine = Math.min(1, Math.max(0.25, Math.cos((centerLat * Math.PI) / 180)));
|
|
267
|
+
const scale = Math.min((width - 2 * padding) / (lonSpan * cosine), (height - 2 * padding) / latSpan);
|
|
268
|
+
const horizontal = cosine * scale;
|
|
269
|
+
const shift = (longitude: number) => bounds.pivot !== null && longitude < bounds.pivot ? longitude + 360 : longitude;
|
|
270
|
+
return {
|
|
271
|
+
width,
|
|
272
|
+
height,
|
|
273
|
+
west: centerLon - width / 2 / horizontal,
|
|
274
|
+
east: centerLon + width / 2 / horizontal,
|
|
275
|
+
south: centerLat - height / 2 / scale,
|
|
276
|
+
north: centerLat + height / 2 / scale,
|
|
277
|
+
project: ([longitude, latitude]) => [width / 2 + (shift(longitude) - centerLon) * horizontal, height / 2 - (latitude - centerLat) * scale],
|
|
278
|
+
x: longitude => width / 2 + (longitude - centerLon) * horizontal,
|
|
279
|
+
y: latitude => height / 2 - (latitude - centerLat) * scale,
|
|
280
|
+
invert: (x, y) => [
|
|
281
|
+
normalizeLongitude(centerLon + (x - width / 2) / horizontal),
|
|
282
|
+
Math.min(90, Math.max(-90, centerLat - (y - height / 2) / scale)),
|
|
283
|
+
],
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const STEPS = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 45, 90];
|
|
288
|
+
|
|
289
|
+
/** Graticule lines inside the visible extent: meridians may exceed 180, parallels stay within the poles. */
|
|
290
|
+
export function graticule(projection: MapProjection, target = 8): { step: number; meridians: number[]; parallels: number[] } {
|
|
291
|
+
const span = Math.max(projection.east - projection.west, projection.north - projection.south);
|
|
292
|
+
const step = STEPS.find(candidate => span / candidate <= target) ?? 90;
|
|
293
|
+
const lines = (from: number, to: number) => {
|
|
294
|
+
const values: number[] = [];
|
|
295
|
+
for (let index = Math.ceil(from / step); index * step <= to && values.length < 64; index += 1) values.push(Number((index * step).toFixed(3)));
|
|
296
|
+
return values;
|
|
297
|
+
};
|
|
298
|
+
return {
|
|
299
|
+
step,
|
|
300
|
+
meridians: lines(projection.west, projection.east),
|
|
301
|
+
parallels: lines(Math.max(-90, projection.south), Math.min(90, projection.north)),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Degree label for a graticule line: 170°E, 170°W (for 190), 0°, 10.5°S. */
|
|
306
|
+
export function degreeLabel(value: number, axis: 'lon' | 'lat'): string {
|
|
307
|
+
const normalized = axis === 'lon' ? normalizeLongitude(value) : value;
|
|
308
|
+
const magnitude = Number(Math.abs(normalized).toFixed(3));
|
|
309
|
+
if (magnitude === 0 || (axis === 'lon' && magnitude === 180)) return `${magnitude}°`;
|
|
310
|
+
const hemisphere = axis === 'lon' ? (normalized > 0 ? 'E' : 'W') : (normalized > 0 ? 'N' : 'S');
|
|
311
|
+
return `${magnitude}°${hemisphere}`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** SVG path data for a Polygon or MultiPolygon; holes rely on the even-odd fill rule. */
|
|
315
|
+
export function geometryPath(geometry: Geometry, projection: MapProjection): string {
|
|
316
|
+
const polygons = geometry.type === 'Polygon' ? [geometry.coordinates] : geometry.type === 'MultiPolygon' ? geometry.coordinates : [];
|
|
317
|
+
return polygons.flatMap(rings => rings.map(ring => ring.slice(0, -1).map((point, index) => {
|
|
318
|
+
const [x, y] = projection.project(point);
|
|
319
|
+
return `${index ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`;
|
|
320
|
+
}).join('') + 'Z')).join('');
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Turns a dragged rectangle into `search::bbox` arguments. Longitudes are
|
|
325
|
+
* normalized, so a box over the antimeridian has `west > east`; a box wider
|
|
326
|
+
* than the world covers every longitude.
|
|
327
|
+
*/
|
|
328
|
+
export function selectionBounds(projection: MapProjection, x1: number, y1: number, x2: number, y2: number): [number, number, number, number] {
|
|
329
|
+
const left = Math.min(x1, x2);
|
|
330
|
+
const right = Math.max(x1, x2);
|
|
331
|
+
const [, north] = projection.invert(left, Math.min(y1, y2));
|
|
332
|
+
const [, south] = projection.invert(left, Math.max(y1, y2));
|
|
333
|
+
const width = ((right - left) / projection.width) * (projection.east - projection.west);
|
|
334
|
+
const round = (value: number) => Number(value.toFixed(6));
|
|
335
|
+
if (width >= 360) return [-180, round(south), 180, round(north)];
|
|
336
|
+
return [round(projection.invert(left, 0)[0]), round(south), round(projection.invert(right, 0)[0]), round(north)];
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
// Spatial indexes.
|
|
341
|
+
|
|
342
|
+
export type StoredSchemaRow = { type: string; name: string; table: string; sql: string | null };
|
|
343
|
+
export type SpatialDetails = Pick<StudioIndex, 'geometry' | 'spatialFormat'>;
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Geometry kind and format of a spatial index. RomeDB 2.5.1 and later report
|
|
347
|
+
* `geometry` ("point" or "region") and `format` ("latitude" for the released
|
|
348
|
+
* 2.4.0 format, "two_dimensional" otherwise) in INFO FOR TABLE and INFO FOR
|
|
349
|
+
* INDEX. Older engines report only `kind: 'spatial'`; then the stored schema is
|
|
350
|
+
* the fallback (`stored`, when given).
|
|
351
|
+
*/
|
|
352
|
+
export function spatialIndexDetails(reported: { geometry?: string | null; format?: string | null }, name: string, stored?: StoredSchemaRow[]): SpatialDetails {
|
|
353
|
+
const format = reported.format === 'latitude' || reported.format === 'two_dimensional' ? reported.format : undefined;
|
|
354
|
+
if (reported.geometry === 'point' || reported.geometry === 'region') {
|
|
355
|
+
return { geometry: reported.geometry, ...(format ? { spatialFormat: format } : {}) };
|
|
356
|
+
}
|
|
357
|
+
const fallback = stored ? spatialIndexInfo(name, stored) : {};
|
|
358
|
+
return format ? { ...fallback, spatialFormat: format } : fallback;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Fallback for engines whose INFO does not report `geometry` (2.5.0 and
|
|
363
|
+
* older): a region index keeps a `<entries>_shapes` side table, a
|
|
364
|
+
* two-dimensional point index covers longitude and latitude, and the released
|
|
365
|
+
* latitude format indexes only its key. Returns {} when the schema rows are not
|
|
366
|
+
* visible on this connection.
|
|
367
|
+
*/
|
|
368
|
+
export function spatialIndexInfo(name: string, stored: StoredSchemaRow[]): SpatialDetails {
|
|
369
|
+
const index = stored.find(row => row.type === 'index' && row.name === name);
|
|
370
|
+
if (!index) return {};
|
|
371
|
+
if (stored.some(row => row.type === 'table' && row.name === `${index.table}_shapes`)) return { geometry: 'region', spatialFormat: 'two_dimensional' };
|
|
372
|
+
return { geometry: 'point', spatialFormat: /\blongitude\b/i.test(index.sql ?? '') ? 'two_dimensional' : 'latitude' };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** SQL that reads the stored schema rows the fallback needs for one index. */
|
|
376
|
+
export const SPATIAL_SCHEMA_SQL = "SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE (type = 'index' AND name = $index) OR (type = 'table' AND name IN (SELECT tbl_name || '_shapes' FROM sqlite_schema WHERE type = 'index' AND name = $index))";
|
|
377
|
+
|
|
378
|
+
export interface SpatialIndexRef { table: string; index: StudioIndex }
|
|
379
|
+
|
|
380
|
+
/** Spatial indexes of document collections, in schema order. */
|
|
381
|
+
export function spatialIndexes(schema: StudioSchema): SpatialIndexRef[] {
|
|
382
|
+
return schema.objects.flatMap(object => object.model === 'document'
|
|
383
|
+
? object.indexes.filter(index => index.kind === 'Spatial').map(index => ({ table: object.name, index }))
|
|
384
|
+
: []);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export function spatialKindLabel(index: StudioIndex): string {
|
|
388
|
+
if (index.kind !== 'Spatial') return index.kind;
|
|
389
|
+
if (!index.geometry) return 'Spatial';
|
|
390
|
+
return `Spatial · ${index.geometry}${index.spatialFormat === 'latitude' ? ' · latitude format' : ''}`;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function finite(value: unknown, low: number, high: number, label: string): number {
|
|
394
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < low || value > high) throw new Error(`${label} must be a number from ${low} to ${high}.`);
|
|
395
|
+
return value;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Builds the bounded read for the Map tab. Point indexes search the viewport
|
|
400
|
+
* with `search::bbox`; region indexes find the regions covering a point with
|
|
401
|
+
* `search::containing`, or read the first rows when no point is given. Each
|
|
402
|
+
* form returns the record ID and the indexed field, at most `limit` rows.
|
|
403
|
+
*/
|
|
404
|
+
export function mapQuery(object: Pick<StudioObject, 'name'>, path: string[], index: string, geometry: SpatialGeometryKind | undefined, request: Pick<MapRequest, 'limit' | 'bbox' | 'point'>): { sql: string; params: Record<string, string | number>; display: string } {
|
|
405
|
+
if (!MAP_LIMITS.includes(request.limit)) throw new Error(`Choose a limit of ${MAP_LIMITS.join(', ')} rows.`);
|
|
406
|
+
if (!path.length || path.some(part => !part)) throw new Error('The spatial index has no field path.');
|
|
407
|
+
const table = quoteIdentifier(object.name);
|
|
408
|
+
const field = `studio_row.${path.map(quoteIdentifier).join('.')}`;
|
|
409
|
+
const select = `SELECT studio_row.id AS id, ${field} AS ${quoteIdentifier(path.join('.'))}`;
|
|
410
|
+
const join = ` AS studio_hit JOIN ${table} AS studio_row ON studio_row.id = studio_hit.id`;
|
|
411
|
+
const limit = ` LIMIT ${request.limit}`;
|
|
412
|
+
const literal = `'${index.replaceAll("'", "''")}'`;
|
|
413
|
+
if (geometry === 'point' && request.bbox) {
|
|
414
|
+
const [west, south, east, north] = request.bbox;
|
|
415
|
+
finite(west, -180, 180, 'West');
|
|
416
|
+
finite(east, -180, 180, 'East');
|
|
417
|
+
finite(south, -90, 90, 'South');
|
|
418
|
+
finite(north, -90, 90, 'North');
|
|
419
|
+
if (south > north) throw new Error('South must not be above north.');
|
|
420
|
+
return {
|
|
421
|
+
sql: `${select} FROM search::bbox($index, $west, $south, $east, $north)${join}${limit}`,
|
|
422
|
+
params: { $index: index, $west: west, $south: south, $east: east, $north: north },
|
|
423
|
+
display: `${select} FROM search::bbox(${literal}, ${west}, ${south}, ${east}, ${north})${join}${limit}`,
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
if (geometry === 'region' && request.point) {
|
|
427
|
+
const [longitude, latitude] = request.point;
|
|
428
|
+
finite(longitude, -180, 180, 'Longitude');
|
|
429
|
+
finite(latitude, -90, 90, 'Latitude');
|
|
430
|
+
return {
|
|
431
|
+
sql: `${select} FROM search::containing($index, geo::point($lng, $lat), 'covers')${join}${limit}`,
|
|
432
|
+
params: { $index: index, $lng: longitude, $lat: latitude },
|
|
433
|
+
display: `${select} FROM search::containing(${literal}, geo::point(${longitude}, ${latitude}), 'covers')${join}${limit}`,
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
const plain = `${select} FROM ${table} AS studio_row${limit}`;
|
|
437
|
+
return { sql: plain, params: {}, display: plain };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// ---------------------------------------------------------------------------
|
|
441
|
+
// Editor completion.
|
|
442
|
+
|
|
443
|
+
/** Native spatial functions and their PostGIS aliases, from the RomeDB 2.5 contract. */
|
|
444
|
+
export const SPATIAL_FUNCTIONS: { name: string; signature: string; detail: string }[] = [
|
|
445
|
+
{ name: 'geo::point', signature: '(lng, lat)', detail: 'Point' },
|
|
446
|
+
{ name: 'geo::lng', signature: '(point)', detail: 'longitude' },
|
|
447
|
+
{ name: 'geo::lat', signature: '(point)', detail: 'latitude' },
|
|
448
|
+
{ name: 'geo::from_geojson', signature: '(text)', detail: 'geometry from GeoJSON text' },
|
|
449
|
+
{ name: 'geo::to_geojson', signature: '(geometry)', detail: 'GeoJSON text' },
|
|
450
|
+
{ name: 'geo::envelope', signature: '(west, south, east, north)', detail: 'Polygon' },
|
|
451
|
+
{ name: 'geo::distance', signature: '(point, point)', detail: 'meters on the sphere' },
|
|
452
|
+
{ name: 'geo::within', signature: '(point, center, radius_m)', detail: 'radius test' },
|
|
453
|
+
{ name: 'geo::contains', signature: '(region, point)', detail: 'interior test' },
|
|
454
|
+
{ name: 'geo::covers', signature: '(region, point)', detail: 'interior or boundary test' },
|
|
455
|
+
{ name: 'geo::inside', signature: '(point, region)', detail: 'interior test' },
|
|
456
|
+
{ name: 'geo::intersects', signature: '(point, region)', detail: 'interior or boundary test' },
|
|
457
|
+
{ name: 'geo::cell', signature: '(point, resolution)', detail: 'H3 cell' },
|
|
458
|
+
{ name: 'geo::cell_center', signature: '(cell)', detail: 'Point' },
|
|
459
|
+
{ name: 'geo::cell_boundary', signature: '(cell)', detail: 'Polygon or MultiPolygon' },
|
|
460
|
+
{ name: 'geo::cell_parent', signature: '(cell, resolution)', detail: 'H3 cell' },
|
|
461
|
+
{ name: 'geo::cell_children', signature: '(cell, resolution)', detail: 'array of cells' },
|
|
462
|
+
{ name: 'geo::cell_disk', signature: '(cell, k)', detail: 'array of cells' },
|
|
463
|
+
{ name: 'geo::cell_resolution', signature: '(cell)', detail: 'integer' },
|
|
464
|
+
{ name: 'geo::cell_distance', signature: '(cell, cell)', detail: 'grid steps' },
|
|
465
|
+
{ name: 'geo::cell_area', signature: '(cell)', detail: 'square meters' },
|
|
466
|
+
{ name: 'geo::cell_compact', signature: '(cells)', detail: 'array of cells' },
|
|
467
|
+
{ name: 'geo::cell_uncompact', signature: '(cells, resolution)', detail: 'array of cells' },
|
|
468
|
+
{ name: 'ST_Point', signature: '(lng, lat[, 4326])', detail: 'geo::point' },
|
|
469
|
+
{ name: 'ST_MakePoint', signature: '(lng, lat)', detail: 'geo::point' },
|
|
470
|
+
{ name: 'ST_X', signature: '(point)', detail: 'geo::lng' },
|
|
471
|
+
{ name: 'ST_Y', signature: '(point)', detail: 'geo::lat' },
|
|
472
|
+
{ name: 'ST_GeomFromGeoJSON', signature: '(text)', detail: 'geo::from_geojson' },
|
|
473
|
+
{ name: 'ST_AsGeoJSON', signature: '(geometry)', detail: 'geo::to_geojson' },
|
|
474
|
+
{ name: 'ST_MakeEnvelope', signature: '(west, south, east, north[, 4326])', detail: 'geo::envelope' },
|
|
475
|
+
{ name: 'ST_DistanceSphere', signature: '(point, point)', detail: 'geo::distance' },
|
|
476
|
+
{ name: 'ST_DWithin', signature: '(point, point, meters[, false])', detail: 'geo::within' },
|
|
477
|
+
{ name: 'ST_Contains', signature: '(region, point)', detail: 'geo::contains' },
|
|
478
|
+
{ name: 'ST_Covers', signature: '(region, point)', detail: 'geo::covers' },
|
|
479
|
+
{ name: 'ST_Within', signature: '(point, region)', detail: 'geo::inside' },
|
|
480
|
+
{ name: 'ST_Intersects', signature: '(point, region)', detail: 'geo::intersects' },
|
|
481
|
+
];
|
|
482
|
+
|
|
483
|
+
/** Indexed spatial sources. */
|
|
484
|
+
export const SPATIAL_SOURCES: { name: string; signature: string; detail: string }[] = [
|
|
485
|
+
{ name: 'search::near', signature: "('index', center, radius_m)", detail: 'id, distance_m' },
|
|
486
|
+
{ name: 'search::bbox', signature: "('index', west, south, east, north)", detail: 'id' },
|
|
487
|
+
{ name: 'search::polygon', signature: "('index', region, 'contains' | 'covers')", detail: 'id' },
|
|
488
|
+
{ name: 'search::nearest', signature: "('index', center, k[, allowed_ids])", detail: 'id, distance_m' },
|
|
489
|
+
{ name: 'search::containing', signature: "('index', point, 'contains' | 'covers')", detail: 'id of stored regions' },
|
|
490
|
+
];
|
|
491
|
+
|
|
492
|
+
export const SPATIAL_KEYWORDS = ['SEARCH', 'USING', 'SPATIAL', 'REINDEX'];
|
|
493
|
+
|
|
494
|
+
export interface SpatialCompletion { label: string; insertText: string; filterText: string; detail: string; kind: 'function' | 'snippet' }
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Spatial completions for the text before the cursor. After `geo::` or
|
|
498
|
+
* `search::` only that namespace's names are offered, completing the part
|
|
499
|
+
* after `::`. After `USING SPATIAL` the region option is offered.
|
|
500
|
+
*/
|
|
501
|
+
export function spatialCompletions(linePrefix: string): SpatialCompletion[] {
|
|
502
|
+
const namespace = /\b(geo|search)::\w*$/i.exec(linePrefix)?.[1]?.toLowerCase();
|
|
503
|
+
const entries = [...SPATIAL_FUNCTIONS, ...SPATIAL_SOURCES];
|
|
504
|
+
if (namespace) {
|
|
505
|
+
return entries.filter(entry => entry.name.startsWith(`${namespace}::`)).map(entry => ({
|
|
506
|
+
label: entry.name,
|
|
507
|
+
insertText: entry.name.slice(namespace.length + 2),
|
|
508
|
+
filterText: entry.name.slice(namespace.length + 2),
|
|
509
|
+
detail: `${entry.signature} → ${entry.detail}`,
|
|
510
|
+
kind: 'function',
|
|
511
|
+
}));
|
|
512
|
+
}
|
|
513
|
+
const completions: SpatialCompletion[] = entries.map(entry => ({ label: entry.name, insertText: entry.name, filterText: entry.name, detail: `${entry.signature} → ${entry.detail}`, kind: 'function' }));
|
|
514
|
+
if (/\bUSING\s+SPATIAL\s+\w*$/i.test(linePrefix)) {
|
|
515
|
+
completions.unshift({ label: "WITH (geometry = 'region')", insertText: "WITH (geometry = 'region')", filterText: 'WITH', detail: 'Region index for Polygon and MultiPolygon values', kind: 'snippet' });
|
|
516
|
+
}
|
|
517
|
+
return completions;
|
|
518
|
+
}
|