feat(neo4j): visualize and edit graph query results

This commit is contained in:
Hand Sonic authored and GitHub committed 2026-10-09 01:36:42 +08:00
1 parent b06c499902
commit 7ca34d76a9
24 files changed
+1080 -60

No files matched your search

+1 -1
View File
@@ -23,7 +23,7 @@ This module replaces the Neo4j JDBC Agent with the official Neo4j Go Driver.
- Node labels use `CALL db.labels()`. - Node labels use `CALL db.labels()`.
- Properties use `db.schema.nodeTypeProperties()` with a sampled-node fallback. - Properties use `db.schema.nodeTypeProperties()` with a sampled-node fallback.
- Index uniqueness is derived from `SHOW INDEXES ... owningConstraint`, which is compatible with Neo4j 5.x. - Index uniqueness is derived from `SHOW INDEXES ... owningConstraint`, which is compatible with Neo4j 5.x.
- Query row values retain the previous Agent behavior: scalar and graph values are returned as displayable strings, while null remains null. - Scalar query values remain displayable strings and null remains null. Graph values carry a versioned envelope with the original display text, typed identities and properties for the shared graph result view.
## Validation ## Validation
+6 -12
View File
@@ -60,19 +60,13 @@ func openVerifiedRuntime(params connectParams) (*connectionRuntime, error) {
_ = driver.Close(context.Background()) _ = driver.Close(context.Background())
return nil, err return nil, err
} }
return &connectionRuntime{driver: driver, params: params, legacySingleDatabase: usesLegacySingleDatabase(ctx, driver)}, nil runtime := &connectionRuntime{driver: driver, params: params}
} if info, err := driver.GetServerInfo(ctx); err == nil {
// Older Bolt versions supply numeric IDs in the element-ID fields.
// usesLegacySingleDatabase reports whether the server negotiated Bolt 3 or runtime.legacySingleDatabase = info.ProtocolVersion().Major < 4
// older. Those servers only expose the default database, and the driver refuses runtime.legacyGraphIDs = info.ProtocolVersion().Major < 5
// to select a database name for them, so sessions must not send one. Probe
// failures keep the modern behavior.
func usesLegacySingleDatabase(ctx context.Context, driver neo4j.Driver) bool {
info, err := driver.GetServerInfo(ctx)
if err != nil {
return false
} }
return info.ProtocolVersion().Major < 4 return runtime, nil
} }
func openDriver(params connectParams) (neo4j.Driver, error) { func openDriver(params connectParams) (neo4j.Driver, error) {
+207
View File
@@ -0,0 +1,207 @@
package main
import (
"encoding/json"
"reflect"
"sort"
"strconv"
"strings"
neo4j "github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
type graphVID struct {
Type string `json:"type"`
Value string `json:"value"`
}
type graphProperty struct {
Owner string `json:"owner"`
Name string `json:"name"`
Type string `json:"type"`
Value any `json:"value"`
}
type graphNode struct {
ID string `json:"id"`
VID graphVID `json:"vid"`
Labels []string `json:"labels"`
Properties []graphProperty `json:"properties"`
}
type graphEdge struct {
ID string `json:"id"`
VID graphVID `json:"vid"`
Source string `json:"source"`
Target string `json:"target"`
SourceVID graphVID `json:"sourceVid"`
TargetVID graphVID `json:"targetVid"`
Type string `json:"type"`
Properties []graphProperty `json:"properties"`
}
type graphCell struct {
*nodeCell
Marker string `json:"__dbx_graph_cell"`
Kind string `json:"kind"`
Display any `json:"display"`
Nodes []graphNode `json:"nodes"`
Edges []graphEdge `json:"edges"`
DisplayParts []any `json:"displayParts,omitempty"`
}
func normalizeGraphQueryValue(value any, legacyIDs bool) any {
display := normalizeQueryValue(value)
cell := &graphCell{Marker: "neo4j-v1", Kind: strings.ToLower(neo4jTypeName(value)), Display: display, Nodes: []graphNode{}, Edges: []graphEdge{}}
if node, ok := value.(neo4j.Node); ok {
tableCell := normalizeNodeCell(node)
cell.nodeCell = &tableCell
cell.Kind = "vertex"
}
if _, ok := value.(neo4j.Relationship); ok {
cell.Kind = "edge"
}
appendGraphValue(value, cell, legacyIDs)
if len(cell.Nodes) == 0 && len(cell.Edges) == 0 {
return display
}
if cell.Kind != "vertex" && cell.Kind != "edge" {
appendGraphDisplay(value, &cell.DisplayParts, legacyIDs)
}
return cell
}
// Keep scalar JSON tokens intact while retaining references to editable entities.
func appendDisplayText(parts *[]any, text string) {
if len(*parts) > 0 {
if previous, ok := (*parts)[len(*parts)-1].(string); ok && len(previous)+len(text) <= 4096 {
(*parts)[len(*parts)-1] = previous + text
return
}
}
*parts = append(*parts, text)
}
func appendGraphDisplay(value any, parts *[]any, legacyIDs bool) {
switch typed := value.(type) {
case neo4j.Node:
*parts = append(*parts, map[string]string{"nodeId": graphIdentity("vertex", graphVIDFor(typed.ElementId, typed.Id, legacyIDs))})
case neo4j.Relationship:
*parts = append(*parts, map[string]string{"edgeId": graphIdentity("edge", graphVIDFor(typed.ElementId, typed.Id, legacyIDs))})
case neo4j.Path:
appendDisplayText(parts, `{"nodes":`)
appendGraphDisplay(typed.Nodes, parts, legacyIDs)
appendDisplayText(parts, `,"relationships":`)
appendGraphDisplay(typed.Relationships, parts, legacyIDs)
appendDisplayText(parts, "}")
case map[string]any:
keys := make([]string, 0, len(typed))
for key := range typed {
keys = append(keys, key)
}
sort.Strings(keys)
appendDisplayText(parts, "{")
for index, key := range keys {
if index > 0 {
appendDisplayText(parts, ",")
}
appendDisplayText(parts, formatJSONValue(key)+":")
appendGraphDisplay(typed[key], parts, legacyIDs)
}
appendDisplayText(parts, "}")
default:
value := reflect.ValueOf(value)
if value.IsValid() && (value.Kind() == reflect.Slice || value.Kind() == reflect.Array) {
appendDisplayText(parts, "[")
for i := 0; i < value.Len(); i++ {
if i > 0 {
appendDisplayText(parts, ",")
}
appendGraphDisplay(value.Index(i).Interface(), parts, legacyIDs)
}
appendDisplayText(parts, "]")
} else {
appendDisplayText(parts, formatJSONValue(typed))
}
}
}
func graphVIDFor(elementID string, legacyID int64, legacyIDs bool) graphVID {
if legacyIDs {
return graphVID{Type: "neo4j-id", Value: strconv.FormatInt(legacyID, 10)}
}
return graphVID{Type: "neo4j-element-id", Value: elementID}
}
func graphIdentity(kind string, vid graphVID) string {
encoded, _ := json.Marshal([]string{kind, vid.Type, vid.Value})
return string(encoded)
}
func graphPlaceholder(elementID string, legacyID int64, legacyIDs bool) graphNode {
vid := graphVIDFor(elementID, legacyID, legacyIDs)
return graphNode{ID: graphIdentity("vertex", vid), VID: vid, Labels: []string{}, Properties: []graphProperty{}}
}
func graphProperties(properties map[string]any) []graphProperty {
result := make([]graphProperty, 0, len(properties))
for name, value := range properties {
property := graphProperty{Name: name, Type: neo4jTypeName(value), Value: normalizeQueryValue(value)}
switch typed := value.(type) {
case string:
property.Type = "string"
case bool:
property.Type, property.Value = "bool", typed
case int, int64:
property.Type = "int"
case float64:
property.Type = "float"
case []byte:
property.Value = formatJSONValue(typed)
}
result = append(result, property)
}
sort.Slice(result, func(i, j int) bool { return result[i].Name < result[j].Name })
return result
}
func appendGraphValue(value any, cell *graphCell, legacyIDs bool) {
switch typed := value.(type) {
case neo4j.Node:
node := graphPlaceholder(typed.ElementId, typed.Id, legacyIDs)
node.Labels = append(node.Labels, typed.Labels...)
node.Properties = graphProperties(typed.Props)
cell.Nodes = append(cell.Nodes, node)
case neo4j.Relationship:
source := graphPlaceholder(typed.StartElementId, typed.StartId, legacyIDs)
target := graphPlaceholder(typed.EndElementId, typed.EndId, legacyIDs)
vid := graphVIDFor(typed.ElementId, typed.Id, legacyIDs)
cell.Nodes = append(cell.Nodes, source, target)
cell.Edges = append(cell.Edges, graphEdge{ID: graphIdentity("edge", vid), VID: vid, Source: source.ID, Target: target.ID, SourceVID: source.VID, TargetVID: target.VID, Type: typed.Type, Properties: graphProperties(typed.Props)})
case neo4j.Path:
for _, node := range typed.Nodes {
appendGraphValue(node, cell, legacyIDs)
}
for _, edge := range typed.Relationships {
appendGraphValue(edge, cell, legacyIDs)
}
case map[string]any:
keys := make([]string, 0, len(typed))
for key := range typed {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
appendGraphValue(typed[key], cell, legacyIDs)
}
case []byte:
return
default:
value := reflect.ValueOf(value)
if value.IsValid() && (value.Kind() == reflect.Slice || value.Kind() == reflect.Array) {
for i := 0; i < value.Len(); i++ {
appendGraphValue(value.Index(i).Interface(), cell, legacyIDs)
}
}
}
}
+67
View File
@@ -0,0 +1,67 @@
package main
import (
"encoding/json"
"reflect"
"strings"
"testing"
neo4j "github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
func TestGraphRecordPreservesScalarDisplayAndExactIdentity(t *testing.T) {
node := neo4j.Node{Id: 9007199254740993, ElementId: "4:test:1", Labels: []string{"Person", "Employee"}, Props: map[string]any{"name": "Sample A", "count": int64(9007199254740993), "enabled": true}}
for _, legacy := range []bool{false, true} {
row := normalizeRecord(&neo4j.Record{Values: []any{node, int64(42), nil, true}}, 4, legacy)
cell, ok := row[0].(*graphCell)
if !ok || cell.Marker != "neo4j-v1" || cell.Kind != "vertex" || cell.Display != formatNode(node) {
t.Fatalf("invalid graph cell: %#v", row[0])
}
if !reflect.DeepEqual(row[1:], []any{"42", nil, "true"}) {
t.Fatalf("scalar results changed: %#v", row[1:])
}
vid := cell.Nodes[0].VID
if legacy && (vid.Type != "neo4j-id" || vid.Value != "9007199254740993") || !legacy && (vid.Type != "neo4j-element-id" || vid.Value != "4:test:1") {
t.Fatalf("identity lost: %#v", vid)
}
encoded, err := json.Marshal(cell)
if err != nil || !strings.Contains(string(encoded), `"value":"9007199254740993"`) || !strings.Contains(string(encoded), `"value":true`) {
t.Fatalf("property types or precision lost: %s, %v", encoded, err)
}
}
}
func TestGraphPathsPreserveDirectionParallelEdgesAndSelfLoops(t *testing.T) {
a := neo4j.Node{ElementId: "a", Labels: []string{"Person"}}
b := neo4j.Node{ElementId: "b"}
reverse := neo4j.Relationship{ElementId: "r1", StartElementId: "b", EndElementId: "a", Type: "KNOWS"}
parallel := reverse
parallel.ElementId = "r2"
loop := neo4j.Relationship{ElementId: "a", StartElementId: "a", EndElementId: "a", Type: "SELF"}
path := neo4j.Path{Nodes: []neo4j.Node{a, b}, Relationships: []neo4j.Relationship{reverse, parallel, loop}}
cell := normalizeGraphQueryValue(map[string]any{"paths": []any{path}}, false).(*graphCell)
if len(cell.DisplayParts) == 0 {
t.Fatal("nested graph display references were lost")
}
if len(cell.Edges) != 3 || cell.Edges[0].Source != graphPlaceholder("b", 0, false).ID || cell.Edges[0].Target != graphPlaceholder("a", 0, false).ID {
t.Fatalf("relationship direction lost: %#v", cell.Edges)
}
if cell.Edges[0].ID == cell.Edges[1].ID || cell.Edges[2].ID == cell.Nodes[0].ID || cell.Edges[2].Source != cell.Edges[2].Target {
t.Fatal("parallel relationships, node IDs or self-loops collided")
}
if got := normalizeGraphQueryValue([]any{int64(1), "text"}, false); got != `[1,"text"]` {
t.Fatalf("scalar collection changed: %#v", got)
}
}
func TestGraphBinaryPropertyRetainsItsJSONRepresentation(t *testing.T) {
for _, bytes := range [][]byte{{}, {0, 34, 92, 128, 255}, []byte(`{"looks":"like JSON"}`)} {
node := neo4j.Node{ElementId: "binary", Labels: []string{"Sample"}, Props: map[string]any{"bytes": bytes, "name": "before"}}
cell := normalizeGraphQueryValue(node, false).(*graphCell)
property := cell.Nodes[0].Properties[0]
value, ok := property.Value.(string)
if !ok || !json.Valid([]byte(value)) || value != formatJSONValue(bytes) {
t.Fatalf("binary property cannot be reconstructed: %#v, want %s", property, formatJSONValue(bytes))
}
}
}
+1
View File
@@ -97,6 +97,7 @@ type connectionRuntime struct {
// legacySingleDatabase is set for servers that negotiated Bolt 3 or older: // legacySingleDatabase is set for servers that negotiated Bolt 3 or older:
// they have a single default database and reject session database selection. // they have a single default database and reject session database selection.
legacySingleDatabase bool legacySingleDatabase bool
legacyGraphIDs bool
references int references int
closed bool closed bool
mu sync.Mutex mu sync.Mutex
+14 -7
View File
@@ -13,8 +13,8 @@ func TestNodeResultKeepsSourceWidthAndExactPropertyValues(t *testing.T) {
node := neo4j.Node{Labels: []string{"Person"}, Props: map[string]any{ node := neo4j.Node{Labels: []string{"Person"}, Props: map[string]any{
"name": "Ada", "age": int64(9007199254740993), "active": true, "scores": []any{int64(1), int64(2)}, "name": "Ada", "age": int64(9007199254740993), "active": true, "scores": []any{int64(1), int64(2)},
}} }}
row := normalizeRecord(&neo4j.Record{Values: []any{node, int64(7), nil}}, 3) row := normalizeRecord(&neo4j.Record{Values: []any{node, int64(7), nil}}, 3, false)
cell, ok := row[0].(nodeCell) cell, ok := row[0].(*graphCell)
if !ok || len(row) != 3 || row[1] != "7" || row[2] != nil { if !ok || len(row) != 3 || row[1] != "7" || row[2] != nil {
t.Fatalf("unexpected record: %#v", row) t.Fatalf("unexpected record: %#v", row)
} }
@@ -24,11 +24,11 @@ func TestNodeResultKeepsSourceWidthAndExactPropertyValues(t *testing.T) {
{Name: "name", Type: "String", Value: "Ada"}, {Name: "name", Type: "String", Value: "Ada"},
{Name: "scores", Type: "List", Value: "[1,2]"}, {Name: "scores", Type: "List", Value: "[1,2]"},
} }
if cell.Marker != "v1" || cell.Display != formatNode(node) || !reflect.DeepEqual(cell.Properties, want) { if cell.nodeCell == nil || cell.nodeCell.Marker != "v1" || cell.Display != formatNode(node) || !reflect.DeepEqual(cell.nodeCell.Properties, want) {
t.Fatalf("unexpected node cell: %#v", cell) t.Fatalf("unexpected node cell: %#v", cell)
} }
encoded, err := json.Marshal(row) encoded, err := json.Marshal(row)
if err != nil || !strings.Contains(string(encoded), `"value":"9007199254740993"`) { if err != nil || !strings.Contains(string(encoded), `"value":"9007199254740993"`) || !strings.Contains(string(encoded), `"__dbx_neo4j_node":"v1"`) || !strings.Contains(string(encoded), `"__dbx_graph_cell":"neo4j-v1"`) {
t.Fatalf("inexact wire value: %s, err=%v", encoded, err) t.Fatalf("inexact wire value: %s, err=%v", encoded, err)
} }
} }
@@ -42,9 +42,16 @@ func TestEmptyNodeAndNonNodeValues(t *testing.T) {
for _, value := range []any{nil, "(:Person {\"name\":\"literal\"})", true, int64(42), for _, value := range []any{nil, "(:Person {\"name\":\"literal\"})", true, int64(42),
neo4j.Relationship{Type: "KNOWS"}, neo4j.Path{Nodes: []neo4j.Node{node}}, neo4j.Relationship{Type: "KNOWS"}, neo4j.Path{Nodes: []neo4j.Node{node}},
[]any{node}, map[string]any{"node": node}} { []any{node}, map[string]any{"node": node}} {
row := normalizeRecord(&neo4j.Record{Values: []any{value}}, 1) row := normalizeRecord(&neo4j.Record{Values: []any{value}}, 1, false)
if !reflect.DeepEqual(row[0], normalizeQueryValue(value)) { display := row[0]
t.Fatalf("non-node result changed for %T: %#v", value, row) if cell, ok := display.(*graphCell); ok {
if cell.nodeCell != nil {
t.Fatalf("non-node result has node table metadata for %T: %#v", value, cell)
}
display = cell.Display
}
if !reflect.DeepEqual(display, normalizeQueryValue(value)) {
t.Fatalf("non-node display changed for %T: %#v", value, row)
} }
} }
} }
+7 -11
View File
@@ -29,7 +29,7 @@ func (s *server) executeQuery(options queryOptions) (queryResult, error) {
return queryResult{}, err return queryResult{}, err
} }
maxRows := effectiveMaxRows(options.MaxRows) maxRows := effectiveMaxRows(options.MaxRows)
rows, columns, columnTypes, truncated, err := readResultPage(ctx, result, maxRows) rows, columns, columnTypes, truncated, err := readResultPage(ctx, result, maxRows, s.runtime.legacyGraphIDs)
if err != nil { if err != nil {
return queryResult{}, err return queryResult{}, err
} }
@@ -64,7 +64,7 @@ func (s *server) executeQueryPage(options queryOptions, pageSize int) (queryPage
s.endOperation(cancel) s.endOperation(cancel)
return queryPageResult{}, err return queryPageResult{}, err
} }
rows, columns, columnTypes, hasMore, err := readResultPage(ctx, result, pageSize) rows, columns, columnTypes, hasMore, err := readResultPage(ctx, result, pageSize, s.runtime.legacyGraphIDs)
if err != nil { if err != nil {
_ = session.Close(ctx) _ = session.Close(ctx)
s.endOperation(cancel) s.endOperation(cancel)
@@ -103,7 +103,7 @@ func (s *server) fetchQueryPage(id string, pageSize int) (queryPageResult, error
if pageSize > query.remaining { if pageSize > query.remaining {
pageSize = query.remaining pageSize = query.remaining
} }
rows, _, _, hasMore, err := readResultPage(query.ctx, query.result, pageSize) rows, _, _, hasMore, err := readResultPage(query.ctx, query.result, pageSize, s.runtime.legacyGraphIDs)
if err != nil { if err != nil {
s.closeQuerySession(id) s.closeQuerySession(id)
return queryPageResult{}, err return queryPageResult{}, err
@@ -202,7 +202,7 @@ func (s *server) executeBatch(params map[string]json.RawMessage) (queryResult, e
return emptyQueryResult(time.Since(started)), nil return emptyQueryResult(time.Since(started)), nil
} }
func readResultPage(ctx context.Context, result neo4j.Result, limit int) ([][]any, []string, []string, bool, error) { func readResultPage(ctx context.Context, result neo4j.Result, limit int, legacyGraphIDs bool) ([][]any, []string, []string, bool, error) {
if limit < 0 { if limit < 0 {
limit = 0 limit = 0
} }
@@ -222,7 +222,7 @@ func readResultPage(ctx context.Context, result neo4j.Result, limit int) ([][]an
} else { } else {
refineColumnTypes(columnTypes, record) refineColumnTypes(columnTypes, record)
} }
rows = append(rows, normalizeRecord(record, len(columns))) rows = append(rows, normalizeRecord(record, len(columns), legacyGraphIDs))
} }
if err := result.Err(); err != nil { if err := result.Err(); err != nil {
return nil, nil, nil, false, err return nil, nil, nil, false, err
@@ -237,17 +237,13 @@ func readResultPage(ctx context.Context, result neo4j.Result, limit int) ([][]an
return rows, columns, columnTypes, hasMore, nil return rows, columns, columnTypes, hasMore, nil
} }
func normalizeRecord(record *neo4j.Record, width int) []any { func normalizeRecord(record *neo4j.Record, width int, legacyGraphIDs bool) []any {
row := make([]any, width) row := make([]any, width)
if record == nil { if record == nil {
return row return row
} }
for index := 0; index < width && index < len(record.Values); index++ { for index := 0; index < width && index < len(record.Values); index++ {
if node, ok := record.Values[index].(neo4j.Node); ok { row[index] = normalizeGraphQueryValue(record.Values[index], legacyGraphIDs)
row[index] = normalizeNodeCell(node)
} else {
row[index] = normalizeQueryValue(record.Values[index])
}
} }
return row return row
} }
@@ -6,8 +6,8 @@ import { canReloadUnavailableDataTab, restoredDataTabReloadFilters } from "@/lib
import { defaultViewForResult } from "@/lib/query/queryResultDefaultView"; import { defaultViewForResult } from "@/lib/query/queryResultDefaultView";
import { extractNeo4jNodeCells, projectNeo4jNodeResult } from "@/lib/neo4j/neo4jNodeResult"; import { extractNeo4jNodeCells, projectNeo4jNodeResult } from "@/lib/neo4j/neo4jNodeResult";
import { useNeo4jNodeTableResult } from "@/composables/useNeo4jNodeTableResult"; import { useNeo4jNodeTableResult } from "@/composables/useNeo4jNodeTableResult";
import { extractGraphCells, type GraphEdge, type GraphNode, type GraphProperty, type GraphResult } from "@/lib/graph/graphResult"; import { extractGraphCells, graphPropertyFromUpdateResult, type GraphEdge, type GraphNode, type GraphProperty, type GraphResult } from "@/lib/graph/graphResult";
import { applyGraphPropertyToResult, buildNebulaGraphExpand, buildNebulaGraphPropertyUpdate, graphPropertyFromUpdateResult, graphPropertyMatchesValue } from "@/lib/graph/nebulaGraph"; import { graphAdapterForDatabase } from "@/lib/graph/graphAdapters";
import { queryResultMessages } from "@/lib/query/queryResultMessages"; import { queryResultMessages } from "@/lib/query/queryResultMessages";
import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError"; import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";
import { hasQueryOutput as tabHasQueryOutput } from "@/lib/query/queryOutput"; import { hasQueryOutput as tabHasQueryOutput } from "@/lib/query/queryOutput";
@@ -643,6 +643,7 @@ async function fetchGridResultForExport(onProgress?: (info: { rowsExported: numb
const result = await queryStore.fetchTabResultForExport(props.activeTab.id, onProgress); const result = await queryStore.fetchTabResultForExport(props.activeTab.id, onProgress);
if (!result || !isNeo4j) return result; if (!result || !isNeo4j) return result;
extractNeo4jNodeCells(result); extractNeo4jNodeCells(result);
extractGraphCells(result);
return projectNeo4jNodeResult(result); return projectNeo4jNodeResult(result);
} }
const activeResultSql = computed(() => resultSqlForGrid(props.activeTab)); const activeResultSql = computed(() => resultSqlForGrid(props.activeTab));
@@ -745,7 +746,8 @@ const redisConsoleResults = computed(() => (props.activeTab.results?.length ? pr
const canShowRedisConsoleOutput = computed(() => activeEffectiveDatabaseType.value === "redis" && (props.activeTab.isExecuting || redisConsoleResults.value.some((result) => result.execution_error === true || typeof result.redis_console_output === "string"))); const canShowRedisConsoleOutput = computed(() => activeEffectiveDatabaseType.value === "redis" && (props.activeTab.isExecuting || redisConsoleResults.value.some((result) => result.execution_error === true || typeof result.redis_console_output === "string")));
const redisResultViewMode = computed<RedisResultViewMode>(() => (activeEffectiveDatabaseType.value === "redis" ? (props.activeTab.uiState?.redisResultViewMode ?? "grid") : "grid")); const redisResultViewMode = computed<RedisResultViewMode>(() => (activeEffectiveDatabaseType.value === "redis" ? (props.activeTab.uiState?.redisResultViewMode ?? "grid") : "grid"));
const canShowResultOutput = computed(() => hasTabularResult.value || props.activeTab.isExecuting); const canShowResultOutput = computed(() => hasTabularResult.value || props.activeTab.isExecuting);
const canShowGraphOutput = computed(() => activeEffectiveDatabaseType.value === "nebula" && !!props.activeTab.result?.graph_data?.nodes.length); const activeGraphAdapter = computed(() => graphAdapterForDatabase(activeEffectiveDatabaseType.value));
const canShowGraphOutput = computed(() => !!activeGraphAdapter.value && !!props.activeTab.result?.graph_data?.nodes.length);
const canShowExplainOutput = computed(() => !!props.activeTab.explainPlan || !!props.activeTab.explainError || !!props.activeTab.explainTableResult || !!props.activeTab.explainTableError || props.activeTab.isExplaining === true); const canShowExplainOutput = computed(() => !!props.activeTab.explainPlan || !!props.activeTab.explainError || !!props.activeTab.explainTableResult || !!props.activeTab.explainTableError || props.activeTab.isExplaining === true);
// A batch can attach server messages to more than one statement result (for // A batch can attach server messages to more than one statement result (for
// example a `DO $$ RAISE NOTICE $$` block followed by a SELECT). The messages // example a `DO $$ RAISE NOTICE $$` block followed by a SELECT). The messages
@@ -761,9 +763,10 @@ const canShowMessagesOutput = computed(() => resultMessageCount.value > 0);
const showStandaloneResultToolbar = computed(() => activeElasticsearchJsonResponse.value || props.activeOutputView !== "result" || (redisResultViewMode.value === "console" && canShowRedisConsoleOutput.value) || !props.activeTab.result || !hasTabularResult.value); const showStandaloneResultToolbar = computed(() => activeElasticsearchJsonResponse.value || props.activeOutputView !== "result" || (redisResultViewMode.value === "console" && canShowRedisConsoleOutput.value) || !props.activeTab.result || !hasTabularResult.value);
const standaloneResultToolbarCompact = computed(() => isDataGridToolbarCompact(standaloneResultToolbarWidth.value, standaloneResultToolbarViewportWidth.value)); const standaloneResultToolbarCompact = computed(() => isDataGridToolbarCompact(standaloneResultToolbarWidth.value, standaloneResultToolbarViewportWidth.value));
async function saveNebulaGraphProperty(entity: GraphNode | GraphEdge, property: GraphProperty, value: string | boolean): Promise<GraphProperty | undefined> { async function saveGraphProperty(entity: GraphNode | GraphEdge, property: GraphProperty, value: string | boolean): Promise<GraphProperty | undefined> {
const connection = activeResultConnection.value; const connection = activeResultConnection.value;
if (activeEffectiveDatabaseType.value !== "nebula" || connectionIsEffectivelyReadOnly(connection)) throw new Error(t("graph.unavailable")); const adapter = activeGraphAdapter.value;
if (!adapter || connectionIsEffectivelyReadOnly(connection)) throw new Error(t("graph.unavailable"));
const tab = props.activeTab; const tab = props.activeTab;
const result = tab.result; const result = tab.result;
const connectionId = activeResultConnectionId.value; const connectionId = activeResultConnectionId.value;
@@ -772,7 +775,7 @@ async function saveNebulaGraphProperty(entity: GraphNode | GraphEdge, property:
const generation = tab.resultViewGeneration; const generation = tab.resultViewGeneration;
const sourceKey = graphViewKey.value; const sourceKey = graphViewKey.value;
const isCurrent = () => props.activeTab === tab && graphViewKey.value === sourceKey && (generation !== undefined ? !!tab.result?.graph_data : tab.result === result); const isCurrent = () => props.activeTab === tab && graphViewKey.value === sourceKey && (generation !== undefined ? !!tab.result?.graph_data : tab.result === result);
const statement = buildNebulaGraphPropertyUpdate(entity, property, value); const statement = adapter.buildPropertyUpdate(entity, property, value);
const production = productionContextForDatabase(connection, database); const production = productionContextForDatabase(connection, database);
if (production.active) { if (production.active) {
const confirmed = await productionSafetyStore.requestConfirmation({ sql: statement, connectionName: connection?.name, database, productionDatabases: production.databases, source: t("graph.title") }); const confirmed = await productionSafetyStore.requestConfirmation({ sql: statement, connectionName: connection?.name, database, productionDatabases: production.databases, source: t("graph.title") });
@@ -786,20 +789,21 @@ async function saveNebulaGraphProperty(entity: GraphNode | GraphEdge, property:
if (response.rows.length === 0) throw new Error(t("graph.conflict")); if (response.rows.length === 0) throw new Error(t("graph.conflict"));
const updated = graphPropertyFromUpdateResult(response, property); const updated = graphPropertyFromUpdateResult(response, property);
// A failed WHEN condition may still yield the stored value. // A failed WHEN condition may still yield the stored value.
if (!graphPropertyMatchesValue(updated, value)) throw new Error(t("graph.conflict")); if (!adapter.matchesPropertyValue(updated, value)) throw new Error(t("graph.conflict"));
applyGraphPropertyToResult(tab.result!, entity, property, updated); adapter.applyPropertyUpdate(tab.result!, entity, property, updated);
return updated; return updated;
} }
async function expandNebulaGraphNode(node: GraphNode): Promise<GraphResult | undefined> { async function expandGraphNode(node: GraphNode): Promise<GraphResult | undefined> {
const adapter = activeGraphAdapter.value;
const tab = props.activeTab; const tab = props.activeTab;
const result = tab.result; const result = tab.result;
const connectionId = activeResultConnectionId.value; const connectionId = activeResultConnectionId.value;
const database = activeResultDatabase.value; const database = activeResultDatabase.value;
const generation = tab.resultViewGeneration; const generation = tab.resultViewGeneration;
const sourceKey = graphViewKey.value; const sourceKey = graphViewKey.value;
if (activeEffectiveDatabaseType.value !== "nebula" || !connectionId || !database) return undefined; if (!adapter || !connectionId || !database) return undefined;
const response = await api.executeQuery(connectionId, database, buildNebulaGraphExpand(node), undefined, undefined, { maxRows: 200 }); const response = await api.executeQuery(connectionId, database, adapter.buildExpand(node), undefined, undefined, { maxRows: 200 });
if (props.activeTab !== tab || graphViewKey.value !== sourceKey || (generation === undefined && tab.result !== result)) return undefined; if (props.activeTab !== tab || graphViewKey.value !== sourceKey || (generation === undefined && tab.result !== result)) return undefined;
if (response.execution_error) throw new Error(response.error?.detail ?? t("graph.unavailable")); if (response.execution_error) throw new Error(response.error?.detail ?? t("graph.unavailable"));
return extractGraphCells(response).graph_data; return extractGraphCells(response).graph_data;
@@ -2472,8 +2476,8 @@ defineExpose({
:rows="activeTab.result.rows" :rows="activeTab.result.rows"
:columns="activeTab.result.columns" :columns="activeTab.result.columns"
:read-only="connectionIsEffectivelyReadOnly(activeResultConnection)" :read-only="connectionIsEffectivelyReadOnly(activeResultConnection)"
:save-property="saveNebulaGraphProperty" :save-property="saveGraphProperty"
:expand-node="expandNebulaGraphNode" :expand-node="expandGraphNode"
/> />
<div v-else-if="activeOutputView === 'summary'" class="flex flex-1 min-h-0 min-w-0 overflow-auto bg-background"> <div v-else-if="activeOutputView === 'summary'" class="flex flex-1 min-h-0 min-w-0 overflow-auto bg-background">
@@ -32,8 +32,9 @@ import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore"; import { useQueryStore } from "@/stores/queryStore";
import { useProductionSafetyStore } from "@/stores/productionSafetyStore"; import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
let databaseType: "nebula" | "neo4j" = "nebula";
function node(): GraphNode { function node(): GraphNode {
return { id: "shared", vid: { type: "string", value: "shared" }, labels: ["Person"], properties: [{ owner: "Person", name: "age", type: "int", value: "20" }] }; return { id: "shared", vid: { type: databaseType === "nebula" ? "string" : "neo4j-element-id", value: "shared" }, labels: ["Person"], properties: [{ owner: databaseType === "nebula" ? "Person" : "", name: "age", type: "int", value: "20" }] };
} }
function result(count = 1): QueryResult { function result(count = 1): QueryResult {
@@ -69,7 +70,7 @@ async function mountContentArea(production = false) {
const pinia = createPinia(); const pinia = createPinia();
setActivePinia(pinia); setActivePinia(pinia);
const connectionStore = useConnectionStore(); const connectionStore = useConnectionStore();
connectionStore.connections = ["a", "b"].map((id): ConnectionConfig => ({ id, name: `Synthetic ${id}`, db_type: "nebula", driver_profile: "nebula-v3", host: "localhost", port: 9669, username: "", password: "", is_production: production })); connectionStore.connections = ["a", "b"].map((id): ConnectionConfig => ({ id, name: `Synthetic ${id}`, db_type: databaseType, driver_profile: databaseType === "nebula" ? "nebula-v3" : "neo4j", host: "localhost", port: 9669, username: "", password: "", is_production: production }));
const queryStore = useQueryStore(); const queryStore = useQueryStore();
queryStore.tabs = ["a", "b"].map((id): QueryTab => ({ id, title: id, connectionId: id, database: `space_${id}`, mode: "query", sql: "MATCH (v) RETURN v", isExecuting: false, isCancelling: false, isExplaining: false, resultViewGeneration: `generation-${id}`, result: result(id === "a" ? 1 : 2) })); queryStore.tabs = ["a", "b"].map((id): QueryTab => ({ id, title: id, connectionId: id, database: `space_${id}`, mode: "query", sql: "MATCH (v) RETURN v", isExecuting: false, isCancelling: false, isExplaining: false, resultViewGeneration: `generation-${id}`, result: result(id === "a" ? 1 : 2) }));
const state = reactive({ activeTab: queryStore.tabs[0] }); const state = reactive({ activeTab: queryStore.tabs[0] });
@@ -118,12 +119,15 @@ afterEach(() => {
} }
}); });
describe("ContentArea graph actions", () => { describe.each(["nebula", "neo4j"] as const)("ContentArea %s graph actions", (type) => {
beforeEach(() => {
databaseType = type;
});
it("rejects a conditional update that returns a different stored value", async () => { it("rejects a conditional update that returns a different stored value", async () => {
const execute = vi.spyOn(api, "executeQuery").mockResolvedValue(response("21")); const execute = vi.spyOn(api, "executeQuery").mockResolvedValue(response("21"));
const { state } = await mountContentArea(); const { state } = await mountContentArea();
await expect(save(graphViews[0])).rejects.toThrow("graph.conflict"); await expect(save(graphViews[0])).rejects.toThrow("graph.conflict");
expect(execute).toHaveBeenCalledWith("a", "space_a", expect.stringContaining("WHEN `age` == 20"), undefined, undefined, { maxRows: 1 }); expect(execute).toHaveBeenCalledWith("a", "space_a", expect.stringContaining(type === "nebula" ? "WHEN `age` == 20" : "WITH n WHERE n.`age` = 20"), undefined, undefined, { maxRows: 1 });
expect(state.activeTab.result!.graph_data!.nodes[0].properties[0].value).toBe("20"); expect(state.activeTab.result!.graph_data!.nodes[0].properties[0].value).toBe("20");
expect(state.activeTab.result!.rows[0][0]).toBe("original"); expect(state.activeTab.result!.rows[0][0]).toBe("original");
}); });
@@ -133,7 +137,7 @@ describe("ContentArea graph actions", () => {
const { state } = await mountContentArea(); const { state } = await mountContentArea();
await expect(save(graphViews[0])).resolves.toEqual(expect.objectContaining({ value: "22" })); await expect(save(graphViews[0])).resolves.toEqual(expect.objectContaining({ value: "22" }));
expect(state.activeTab.result!.graph_data!.nodes[0].properties[0].value).toBe("22"); expect(state.activeTab.result!.graph_data!.nodes[0].properties[0].value).toBe("22");
expect(state.activeTab.result!.rows[0][0]).toContain("age: 22"); expect(state.activeTab.result!.rows[0][0]).toContain(type === "nebula" ? "age: 22" : '"age":22');
}); });
it("discards an expansion when switching to a tab with a superset of the same IDs", async () => { it("discards an expansion when switching to a tab with a superset of the same IDs", async () => {
@@ -197,6 +201,21 @@ describe("ContentArea graph actions", () => {
await flush(); await flush();
pending.resolve(response("22")); pending.resolve(response("22"));
await expect(saved).resolves.toEqual(expect.objectContaining({ value: "22" })); await expect(saved).resolves.toEqual(expect.objectContaining({ value: "22" }));
expect(state.activeTab.result!.rows.every((row) => String(row[0]).includes("age: 22"))).toBe(true); expect(state.activeTab.result!.rows.every((row) => String(row[0]).includes(type === "nebula" ? "age: 22" : '"age":22'))).toBe(true);
});
it("uses the adapter's precision when validating a saved float", async () => {
vi.spyOn(api, "executeQuery").mockResolvedValue(response("3.1500000948905659"));
const { state } = await mountContentArea();
const property = state.activeTab.result!.graph_data!.nodes[0].properties[0];
property.type = "float";
property.value = "3.14";
const saved = save(graphViews[0], "3.15");
if (type === "nebula") {
await expect(saved).resolves.toEqual(expect.objectContaining({ value: "3.1500000948905659" }));
} else {
await expect(saved).rejects.toThrow("graph.conflict");
expect(property.value).toBe("3.14");
}
}); });
}); });
@@ -0,0 +1,20 @@
import type { DatabaseType, QueryResult } from "@/types/database";
import { graphPropertyMatchesValue, type GraphEdge, type GraphNode, type GraphProperty } from "./graphResult";
import { applyGraphPropertyToResult, buildNebulaGraphExpand, buildNebulaGraphPropertyUpdate, graphPropertyMatchesValue as nebulaPropertyMatchesValue } from "./nebulaGraph";
import { applyNeo4jGraphPropertyToResult, buildNeo4jGraphExpand, buildNeo4jGraphPropertyUpdate } from "./neo4jGraph";
interface GraphAdapter {
buildPropertyUpdate: (entity: GraphNode | GraphEdge, property: GraphProperty, value: string | boolean) => string;
buildExpand: (node: GraphNode) => string;
applyPropertyUpdate: (result: QueryResult, entity: GraphNode | GraphEdge, property: GraphProperty, updated: GraphProperty) => void;
matchesPropertyValue: (property: GraphProperty, value: string | boolean) => boolean;
}
const adapters: Partial<Record<DatabaseType, GraphAdapter>> = {
nebula: { buildPropertyUpdate: buildNebulaGraphPropertyUpdate, buildExpand: buildNebulaGraphExpand, applyPropertyUpdate: applyGraphPropertyToResult, matchesPropertyValue: nebulaPropertyMatchesValue },
neo4j: { buildPropertyUpdate: buildNeo4jGraphPropertyUpdate, buildExpand: buildNeo4jGraphExpand, applyPropertyUpdate: applyNeo4jGraphPropertyToResult, matchesPropertyValue: graphPropertyMatchesValue },
};
export function graphAdapterForDatabase(type: DatabaseType | undefined): GraphAdapter | undefined {
return type ? adapters[type] : undefined;
}
+27 -4
View File
@@ -21,6 +21,7 @@ export interface GraphNode {
export interface GraphEdge { export interface GraphEdge {
id: string; id: string;
vid?: GraphVid;
source: string; source: string;
target: string; target: string;
sourceVid?: GraphVid; sourceVid?: GraphVid;
@@ -48,7 +49,7 @@ export interface GraphResult {
} }
interface GraphCellEnvelope { interface GraphCellEnvelope {
__dbx_graph_cell: "nebula-v1"; __dbx_graph_cell: "nebula-v1" | "neo4j-v1";
kind: string; kind: string;
display: string; display: string;
nodes: GraphNode[]; nodes: GraphNode[];
@@ -56,10 +57,10 @@ interface GraphCellEnvelope {
displayParts?: GraphDisplayPart[]; displayParts?: GraphDisplayPart[];
} }
function graphCellEnvelope(value: unknown): value is GraphCellEnvelope { export function isGraphCellEnvelope(value: unknown): value is GraphCellEnvelope {
if (!value || typeof value !== "object" || Array.isArray(value)) return false; if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const cell = value as Partial<GraphCellEnvelope>; const cell = value as Partial<GraphCellEnvelope>;
return cell.__dbx_graph_cell === "nebula-v1" && typeof cell.display === "string" && typeof cell.kind === "string" && Array.isArray(cell.nodes) && Array.isArray(cell.edges); return (cell.__dbx_graph_cell === "nebula-v1" || cell.__dbx_graph_cell === "neo4j-v1") && typeof cell.display === "string" && typeof cell.kind === "string" && Array.isArray(cell.nodes) && Array.isArray(cell.edges);
} }
function mergeProperties(left: GraphProperty[], right: GraphProperty[]): GraphProperty[] { function mergeProperties(left: GraphProperty[], right: GraphProperty[]): GraphProperty[] {
@@ -117,7 +118,7 @@ export function extractGraphCells(result: QueryResult): QueryResult {
const cells: GraphCellRef[] = []; const cells: GraphCellRef[] = [];
result.rows.forEach((row, rowIndex) => { result.rows.forEach((row, rowIndex) => {
row.forEach((value, columnIndex) => { row.forEach((value, columnIndex) => {
if (!graphCellEnvelope(value)) return; if (!isGraphCellEnvelope(value)) return;
rows ??= result.rows.map((original) => [...original]); rows ??= result.rows.map((original) => [...original]);
rows[rowIndex][columnIndex] = value.display; rows[rowIndex][columnIndex] = value.display;
for (const node of value.nodes) { for (const node of value.nodes) {
@@ -132,6 +133,28 @@ export function extractGraphCells(result: QueryResult): QueryResult {
return result; return result;
} }
export function graphPropertyFromUpdateResult(result: QueryResult, property: GraphProperty): GraphProperty {
if (result.execution_error) throw new Error(result.error?.detail ?? "Graph property update failed");
const value = result.rows[0]?.[0];
if (result.rows.length !== 1 || value === null || value === undefined) throw new Error("The graph property was not updated");
if (property.type === "int" && typeof value === "number" && !Number.isSafeInteger(value)) throw new Error("Inexact returned graph integer");
if (property.type === "bool") {
if (value !== true && value !== false && value !== "true" && value !== "false") throw new Error("Invalid boolean property returned by the database");
return { ...property, value: value === true || value === "true" };
}
return { ...property, value: String(value) };
}
export function graphPropertyMatchesValue(property: GraphProperty, value: string | boolean): boolean {
if (property.type === "int" && typeof property.value === "string" && typeof value === "string") {
return /^-?\d+$/u.test(property.value) && /^-?\d+$/u.test(value) && BigInt(property.value) === BigInt(value);
}
if (property.type === "float" && typeof property.value === "string" && typeof value === "string") {
return property.value.trim() !== "" && value.trim() !== "" && Number.isFinite(Number(property.value)) && Number(property.value) === Number(value);
}
return property.value === value;
}
export function updateGraphResultProperty(result: QueryResult, entity: GraphNode | GraphEdge, property: GraphProperty, updated: GraphProperty, formatNode: (node: GraphNode) => string, formatEdge: (edge: GraphEdge) => string, formatCell?: (cell: GraphCellRef) => string | undefined): void { export function updateGraphResultProperty(result: QueryResult, entity: GraphNode | GraphEdge, property: GraphProperty, updated: GraphProperty, formatNode: (node: GraphNode) => string, formatEdge: (edge: GraphEdge) => string, formatCell?: (cell: GraphCellRef) => string | undefined): void {
const graph = result.graph_data; const graph = result.graph_data;
if (!graph) return; if (!graph) return;
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import { applyNeo4jGraphPropertyToResult, buildNeo4jGraphExpand, buildNeo4jGraphPropertyUpdate } from "./neo4jGraph";
import { extractGraphCells, graphPropertyFromUpdateResult, type GraphEdge, type GraphNode } from "./graphResult";
import { graphAdapterForDatabase } from "./graphAdapters";
import type { QueryResult } from "@/types/database";
const node: GraphNode = { id: "n", vid: { type: "neo4j-element-id", value: "4:sample:1" }, labels: ["Person"], properties: [{ owner: "", name: "age", type: "int", value: "9007199254740993" }] };
const edge: GraphEdge = { id: "r", vid: { type: "neo4j-element-id", value: "5:sample:1" }, source: "n", target: "m", sourceVid: node.vid, targetVid: { type: "neo4j-element-id", value: "4:sample:2" }, type: "KNOWS", properties: [{ owner: "", name: "active", type: "bool", value: true }] };
describe("Neo4j graph adapter", () => {
it("retains double precision while Nebula uses its single-precision comparison", () => {
const returned = { owner: "", name: "weight", type: "float", value: "3.1500000948905659" };
expect(graphAdapterForDatabase("nebula")!.matchesPropertyValue(returned, "3.15")).toBe(true);
expect(graphAdapterForDatabase("neo4j")!.matchesPropertyValue(returned, "3.15")).toBe(false);
expect(graphAdapterForDatabase("neo4j")!.matchesPropertyValue({ ...returned, value: "3.15000010" }, "3.15000011")).toBe(false);
expect(graphAdapterForDatabase("neo4j")!.matchesPropertyValue({ ...returned, value: "3.15" }, "3.15")).toBe(true);
});
it("keeps legacy byte text from corrupting JSON when another property is edited", () => {
const binaryNode: GraphNode = {
...node,
properties: [
{ owner: "", name: "bytes", type: "List", value: '\u0000binary"\\text' },
{ owner: "", name: "name", type: "string", value: "before" },
],
};
const result = extractGraphCells({ columns: ["nested"], rows: [[{ __dbx_graph_cell: "neo4j-v1", kind: "map", display: "before", nodes: [binaryNode], edges: [], displayParts: ['{"node":', { nodeId: "n" }, "}"] }]] as unknown as QueryResult["rows"], affected_rows: 0, execution_time_ms: 0 });
applyNeo4jGraphPropertyToResult(result, binaryNode, binaryNode.properties[1], { ...binaryNode.properties[1], value: "after" });
expect(JSON.parse(String(result.rows[0][0])).node.properties).toEqual({ bytes: '\u0000binary"\\text', name: "after" });
});
it("preserves a normalized byte array and exact integer tokens after editing", () => {
const binaryNode: GraphNode = {
...node,
properties: [
{ owner: "", name: "bytes", type: "List", value: '["0","34","255"]' },
{ owner: "", name: "age", type: "int", value: "9007199254740993" },
],
};
const result = extractGraphCells({ columns: ["n"], rows: [[{ __dbx_graph_cell: "neo4j-v1", kind: "vertex", display: "before", nodes: [binaryNode], edges: [] }]] as unknown as QueryResult["rows"], affected_rows: 0, execution_time_ms: 0 });
applyNeo4jGraphPropertyToResult(result, binaryNode, binaryNode.properties[1], { ...binaryNode.properties[1], value: "9007199254740994" });
expect(result.rows[0][0]).toContain('"bytes":["0","34","255"]');
expect(result.rows[0][0]).toContain('"age":9007199254740994');
});
it("updates nested graph references without parsing or rounding scalar JSON tokens", () => {
const result = extractGraphCells({
columns: ["nested"],
rows: [[{ __dbx_graph_cell: "neo4j-v1", kind: "map", display: "before", nodes: [structuredClone(node)], edges: [structuredClone(edge)], displayParts: ['{"count":9007199254740997,"node":', { nodeId: "n" }, ',"edge":', { edgeId: "r" }, "}"] }]] as unknown as QueryResult["rows"],
affected_rows: 0,
execution_time_ms: 0,
});
applyNeo4jGraphPropertyToResult(result, node, node.properties[0], { ...node.properties[0], value: "9007199254740994" });
expect(result.rows[0][0]).toContain('"count":9007199254740997');
expect(result.rows[0][0]).toContain('"age":9007199254740994');
applyNeo4jGraphPropertyToResult(result, edge, edge.properties[0], { ...edge.properties[0], value: false });
expect(result.rows[0][0]).toContain('"active":false');
});
it("uses modern or legacy identities and preserves integer precision", () => {
const statement = buildNeo4jGraphPropertyUpdate(node, node.properties[0], "9007199254740994");
expect(statement).toContain('elementId(n) = "4:sample:1"');
expect(statement).toContain("SET n.`age` = n.`age` WITH n WHERE n.`age` = 9007199254740993 SET n.`age` = 9007199254740994");
expect(buildNeo4jGraphExpand({ ...node, vid: { type: "neo4j-id", value: "9007199254740993" } })).toBe("MATCH (n) WHERE id(n) = 9007199254740993 OPTIONAL MATCH (n)-[r]-(m) RETURN n, r, m LIMIT 200");
expect(buildNeo4jGraphPropertyUpdate(edge, edge.properties[0], false)).toContain('elementId(r) = "5:sample:1" AND elementId(s) = "4:sample:1" AND elementId(t) = "4:sample:2"');
});
it("quotes user values and identifiers, rejects invalid numbers, and preserves float types", () => {
const property = { owner: "", name: "odd`key", type: "string", value: "before" };
expect(buildNeo4jGraphPropertyUpdate(node, property, 'after"\\\n')).toContain('SET n.`odd``key` = "after\\\"\\\\\\n"');
expect(buildNeo4jGraphPropertyUpdate(node, { ...property, name: "weight", type: "float", value: "1.5" }, "2")).toContain('SET n.`weight` = toFloat("2")');
for (const value of ["1; DELETE n", "9223372036854775808", "1.5"]) expect(() => buildNeo4jGraphPropertyUpdate(node, node.properties[0], value)).toThrow();
expect(() => buildNeo4jGraphExpand({ ...node, vid: undefined })).toThrow();
});
it("keeps scalar results unchanged and refreshes direct graph cells after updates", () => {
const result = extractGraphCells({ columns: ["n", "count"], rows: [[{ __dbx_graph_cell: "neo4j-v1", kind: "vertex", display: "before", nodes: [structuredClone(node)], edges: [] }, "12"]] as unknown as QueryResult["rows"], affected_rows: 0, execution_time_ms: 0 });
expect(result.rows).toEqual([["before", "12"]]);
const updated = graphPropertyFromUpdateResult({ columns: ["dbx_value"], rows: [["9007199254740994"]], affected_rows: 0, execution_time_ms: 0 }, node.properties[0]);
applyNeo4jGraphPropertyToResult(result, node, node.properties[0], updated);
expect(result.rows[0][0]).toBe('(:Person {"age":9007199254740994})');
expect(result.graph_data?.nodes[0].properties[0].value).toBe("9007199254740994");
expect(graphAdapterForDatabase("neo4j")?.buildExpand).toBe(buildNeo4jGraphExpand);
expect(graphAdapterForDatabase("nebula")).toBeDefined();
expect(graphAdapterForDatabase("mysql")).toBeUndefined();
});
});
+99
View File
@@ -0,0 +1,99 @@
import { updateGraphResultProperty, type GraphEdge, type GraphNode, type GraphProperty, type GraphVid } from "./graphResult";
import type { QueryResult } from "@/types/database";
function quoteIdentifier(value: string): string {
if (!value || [...value].some((char) => (char.codePointAt(0) ?? 0) < 32)) throw new Error("Invalid Neo4j identifier");
return `\`${value.replaceAll("\\", "\\\\").replaceAll("`", "``")}\``;
}
function integer(value: string | boolean): string {
if (typeof value !== "string" || !/^-?(?:0|[1-9]\d*)$/u.test(value)) throw new Error("Invalid Neo4j integer");
const number = BigInt(value);
if (number < -9223372036854775808n || number > 9223372036854775807n) throw new Error("Neo4j integer is outside the signed 64-bit range");
return value;
}
function identity(variable: string, vid: GraphVid | undefined): string {
if (vid?.type === "neo4j-id") return `id(${variable}) = ${integer(vid.value)}`;
if (vid?.type === "neo4j-element-id" && vid.value) return `elementId(${variable}) = ${JSON.stringify(vid.value)}`;
throw new Error("Missing Neo4j entity identity");
}
function propertyValue(type: string, value: string | boolean | null): string {
if (type === "string" && typeof value === "string") return JSON.stringify(value);
if (type === "bool" && typeof value === "boolean") return value ? "true" : "false";
if (type === "int" && value !== null) return integer(value);
if (type === "float" && typeof value === "string" && /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/u.test(value) && Number.isFinite(Number(value))) return `toFloat(${JSON.stringify(value)})`;
throw new Error("Invalid value for this Neo4j property type");
}
export function buildNeo4jGraphPropertyUpdate(entity: GraphNode | GraphEdge, property: GraphProperty, value: string | boolean): string {
if (property.owner) throw new Error("Neo4j properties do not have a Tag owner");
const node = "labels" in entity;
const variable = node ? "n" : "r";
const pattern = node ? `(n${entity.labels.map((label) => `:${quoteIdentifier(label)}`).join("")})` : `(s)-[r:${quoteIdentifier(entity.type)}]->(t)`;
const predicates = [identity(variable, entity.vid)];
if (!node) predicates.push(identity("s", entity.sourceVid), identity("t", entity.targetVid));
const target = `${variable}.${quoteIdentifier(property.name)}`;
// The dependent SET acquires the write lock before checking the saved value.
return `MATCH ${pattern} WHERE ${predicates.join(" AND ")} SET ${target} = ${target} WITH ${variable} WHERE ${target} = ${propertyValue(property.type, property.value)} SET ${target} = ${propertyValue(property.type, value)} RETURN ${target} AS dbx_value`;
}
export function buildNeo4jGraphExpand(node: GraphNode): string {
return `MATCH (n) WHERE ${identity("n", node.vid)} OPTIONAL MATCH (n)-[r]-(m) RETURN n, r, m LIMIT 200`;
}
function propertiesJSON(properties: GraphProperty[]): string {
const values = [...properties]
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
.map((property) => {
const value = property.value;
let literal = JSON.stringify(value);
if (typeof value === "string" && ["int", "float", "List", "Map"].includes(property.type)) {
try {
const parsed: unknown = JSON.parse(value);
if ((["int", "float"].includes(property.type) && typeof parsed === "number" && Number.isFinite(parsed)) || (property.type === "List" && Array.isArray(parsed)) || (property.type === "Map" && parsed !== null && typeof parsed === "object" && !Array.isArray(parsed))) literal = value;
} catch {
// Older Agents may label raw byte text as List; quote it as text.
}
}
return `${JSON.stringify(property.name)}:${literal}`;
});
return `{${values.join(",")}}`;
}
export function applyNeo4jGraphPropertyToResult(result: QueryResult, entity: GraphNode | GraphEdge, property: GraphProperty, updated: GraphProperty): void {
const nodes = new Map(result.graph_data?.nodes.map((node) => [node.id, node]));
const edges = new Map(result.graph_data?.edges.map((edge) => [edge.id, edge]));
const propertiesDisplay = (properties: GraphProperty[]) => (properties.length ? ` ${propertiesJSON(properties)}` : "");
updateGraphResultProperty(
result,
entity,
property,
updated,
(node) => `(${node.labels.length ? `:${node.labels.join(":")}` : ""}${propertiesDisplay(node.properties)})`,
(edge) => `[:${edge.type}${propertiesDisplay(edge.properties)}]`,
(cell) => {
if (!cell.displayParts) return undefined;
const parts: string[] = [];
for (const part of cell.displayParts) {
if (typeof part === "string") parts.push(part);
else if ("nodeId" in part) {
const node = nodes.get(part.nodeId);
if (!node?.vid) return undefined;
parts.push(`{"elementId":${JSON.stringify(node.vid.value)},"labels":${JSON.stringify(node.labels)},"properties":${propertiesJSON(node.properties)}}`);
} else {
const edge = edges.get(part.edgeId);
if (!edge?.vid || !edge.sourceVid || !edge.targetVid) return undefined;
parts.push(`{"elementId":${JSON.stringify(edge.vid.value)},"endElementId":${JSON.stringify(edge.targetVid.value)},"properties":${propertiesJSON(edge.properties)},"startElementId":${JSON.stringify(edge.sourceVid.value)},"type":${JSON.stringify(edge.type)}}`);
}
}
return parts.join("");
},
);
if (!("labels" in entity) || !result.neo4j_node_cells?.length) return;
const affected = new Set(result.graph_data?.cells.filter((cell) => cell.kind === "vertex" && cell.nodeIds.includes(entity.id)).map((cell) => `${cell.row}:${cell.column}`));
result.neo4j_node_cells = result.neo4j_node_cells.map((cell) =>
affected.has(`${cell.row_index}:${cell.column_index}`) ? { ...cell, properties: cell.properties.map((candidate) => (candidate.name === property.name ? { ...candidate, value: updated.value === null ? null : String(updated.value) } : candidate)) } : cell,
);
}
+138
View File
@@ -0,0 +1,138 @@
import { computed, effectScope, ref } from "vue";
import { describe, expect, it } from "vitest";
import { useNeo4jNodeTableResult } from "@/composables/useNeo4jNodeTableResult";
import { extractNeo4jNodeCells, projectNeo4jNodeResult } from "@/lib/neo4j/neo4jNodeResult";
import { appendQueryResultSegment } from "@/stores/queryStore";
import type { QueryResult } from "@/types/database";
import { extractGraphCells, type GraphNode, type GraphProperty } from "./graphResult";
import { applyNeo4jGraphPropertyToResult } from "./neo4jGraph";
function vertex(id: string, name: string, age = "9007199254740993") {
const node: GraphNode = {
id,
vid: { type: "neo4j-element-id", value: id },
labels: ["Person"],
properties: [
{ owner: "", name: "name", type: "string", value: name },
{ owner: "", name: "age", type: "int", value: age },
{ owner: "", name: "active", type: "bool", value: true },
],
};
return {
__dbx_graph_cell: "neo4j-v1",
__dbx_neo4j_node: "v1",
kind: "vertex",
display: `(:Person {name: "${name}"})`,
nodes: [node],
edges: [],
properties: [
{ name: "name", type: "String", value: name },
{ name: "age", type: "Integer", value: age },
{ name: "active", type: "Boolean", value: "true" },
],
};
}
function page(rows: unknown[][]): QueryResult {
return { columns: ["p", "score"], rows: rows as QueryResult["rows"], affected_rows: 0, execution_time_ms: 1 };
}
function normalize(result: QueryResult): QueryResult {
extractNeo4jNodeCells(result);
return extractGraphCells(result);
}
describe("Neo4j graph and node-table compatibility", () => {
it("retains both wire contracts, exact properties, scalar columns, and idempotent extraction", () => {
const cell = vertex("qa-a", "QA Alice");
const result = page([[cell, "7"]]);
extractNeo4jNodeCells(result);
extractNeo4jNodeCells(result);
expect(result.neo4j_node_cells).toHaveLength(1);
expect(result.rows[0]?.[0]).toEqual(cell);
extractGraphCells(result);
normalize(result);
expect(result.graph_data?.nodes).toHaveLength(1);
expect(result.graph_data?.cells).toHaveLength(1);
const projected = projectNeo4jNodeResult(result);
expect(projected.columns).toEqual(["p", "score", "p.name", "p.age", "p.active"]);
expect(projected.rows).toEqual([[cell.display, "7", "QA Alice", "9007199254740993", "true"]]);
expect(projected.hidden_column_indexes).toEqual([0]);
expect(result.columns).toEqual(["p", "score"]);
expect(result.rows).toEqual([[cell.display, "7"]]);
});
it("keeps both metadata streams aligned across raw cursor pages and clips both at the cap", () => {
const first = normalize(page([[vertex("qa-a", "QA Alice"), "1"]]));
const combined = appendQueryResultSegment(
first,
page([
[vertex("qa-b", "QA Bob"), "2"],
[vertex("qa-omitted", "QA Omitted"), "3"],
]),
2,
);
expect(combined.rows).toHaveLength(2);
expect(combined.graph_data?.cells.map((cell) => cell.row)).toEqual([0, 1]);
expect(combined.graph_data?.nodes.map((node) => node.id)).toEqual(["qa-a", "qa-b"]);
expect(combined.neo4j_node_cells?.map((cell) => cell.row_index)).toEqual([0, 1]);
expect(projectNeo4jNodeResult(combined).rows.map((row) => row[2])).toEqual(["QA Alice", "QA Bob"]);
expect(appendQueryResultSegment(first, page([[vertex("qa-b", "QA Bob"), "2"]]), 1).neo4j_node_cells).toHaveLength(1);
});
it("updates all matching aliases in the graph, reactive node grid and export, without touching other nodes", () => {
const scope = effectScope();
const source = ref(
normalize(
page([
[vertex("qa-a", "QA Alice"), "1"],
[vertex("qa-a", "QA Alice"), "2"],
[vertex("qa-b", "QA Bob", "42"), "3"],
]),
),
);
const table = scope.run(() =>
useNeo4jNodeTableResult(
computed(() => source.value),
computed(() => "qa-result"),
),
)!;
expect(table.result.value?.rows.map((row) => row[2])).toEqual(["QA Alice", "QA Alice", "QA Bob"]);
const node = source.value.graph_data!.nodes[0]!;
for (const [name, value] of [
["name", "QA Updated"],
["age", "9007199254740994"],
["active", false],
] as const) {
const property = node.properties.find((property) => property.name === name)!;
applyNeo4jGraphPropertyToResult(source.value, node, property, { ...property, value } as GraphProperty);
}
expect(table.result.value?.rows.map((row) => row.slice(2))).toEqual([
["QA Updated", "9007199254740994", "false"],
["QA Updated", "9007199254740994", "false"],
["QA Bob", "42", "true"],
]);
expect(projectNeo4jNodeResult(source.value).rows).toEqual(table.result.value?.rows);
table.setSort("p.age", 3, "asc");
expect(table.result.value?.rows[0]?.[2]).toBe("QA Bob");
expect(source.value.graph_data?.nodes[0]?.properties.find((property) => property.name === "age")?.value).toBe("9007199254740994");
expect(source.value.graph_data?.cells.map((cell) => cell.row)).toEqual([0, 1, 2]);
scope.stop();
});
it("normalizes old node envelopes and malformed optional graph metadata without leaving object cells", () => {
const cell = vertex("qa-a", "QA Alice");
const result = normalize(
page([
[{ ...cell, nodes: null }, "1"],
[{ __dbx_neo4j_node: "v1", display: "(:Person)", properties: [] }, "2"],
]),
);
expect(result.rows).toEqual([
[cell.display, "1"],
["(:Person)", "2"],
]);
expect(result.neo4j_node_cells).toHaveLength(2);
expect(result.graph_data).toBeUndefined();
});
});
@@ -1,4 +1,5 @@
import type { QueryResult } from "@/types/database"; import type { QueryResult } from "@/types/database";
import { isGraphCellEnvelope } from "@/lib/graph/graphResult";
type CellValue = QueryResult["rows"][number][number]; type CellValue = QueryResult["rows"][number][number];
@@ -35,20 +36,21 @@ function nodeEnvelope(value: unknown): { display: string; properties: Neo4jNodeP
/** Normalize typed wire cells once, keeping primitive rows and original columns. */ /** Normalize typed wire cells once, keeping primitive rows and original columns. */
export function extractNeo4jNodeCells(result: QueryResult): void { export function extractNeo4jNodeCells(result: QueryResult): void {
let rows: QueryResult["rows"] | undefined; let rows: QueryResult["rows"] | undefined;
let cells: Neo4jNodeCell[] | undefined; let cells: Map<string, Neo4jNodeCell> | undefined;
result.rows.forEach((row, row_index) => { result.rows.forEach((row, row_index) => {
row.forEach((value, column_index) => { row.forEach((value, column_index) => {
if (column_index >= result.columns.length) return; if (column_index >= result.columns.length) return;
const cell = nodeEnvelope(value); const cell = nodeEnvelope(value);
if (!cell) return; if (!cell) return;
rows ??= result.rows.map((row) => [...row]); rows ??= result.rows.map((row) => [...row]);
cells ??= [...(result.neo4j_node_cells ?? [])]; cells ??= new Map((result.neo4j_node_cells ?? []).map((cell) => [`${cell.row_index}:${cell.column_index}`, cell]));
rows[row_index]![column_index] = cell.display; // Graph extraction still needs the typed envelope after table metadata extraction.
cells.push({ row_index, column_index, properties: cell.properties }); rows[row_index]![column_index] = isGraphCellEnvelope(value) ? value : cell.display;
cells.set(`${row_index}:${column_index}`, { row_index, column_index, properties: cell.properties });
}); });
}); });
if (rows) result.rows = rows; if (rows) result.rows = rows;
if (cells) result.neo4j_node_cells = cells; if (cells) result.neo4j_node_cells = [...cells.values()];
} }
export function appendNeo4jNodeCells(previous: QueryResult, segment: QueryResult, appendedRowCount: number): Neo4jNodeCell[] | undefined { export function appendNeo4jNodeCells(previous: QueryResult, segment: QueryResult, appendedRowCount: number): Neo4jNodeCell[] | undefined {
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { classifySqlRisk } from "./sqlRisk";
describe("Neo4j read-only query safety", () => {
it.each(["SHOW DATABASES", "EXPLAIN MATCH (n) RETURN n"])("preserves read-only metadata and plans: %s", (sql) => expect(classifySqlRisk(sql, { dialect: "neo4j" }).risk).toBe("read"));
it.each(["MATCH (n)-->(m) RETURN n,m", "MATCH (n) WHERE elementId(n) = '4:id:1' OPTIONAL MATCH (n)-[r]-(m) RETURN n,r,m LIMIT 200", "// SET is a comment\nMATCH (n:`DELETE`) WHERE n.name = 'CREATE; SET' RETURN n", "UNWIND [1,2] AS x RETURN x; RETURN 1", "/* comment */ WITH 1 AS x RETURN x"])(
"allows pure Cypher reads: %s",
(sql) => expect(classifySqlRisk(sql, { dialect: "neo4j" }).risk).toBe("read"),
);
it.each([
"MATCH (n)-->(m) SET n.x = 1 RETURN n",
"MATCH (n) RETURN n /* outer /* inner */ UNION MATCH (m) SET m.x=1 RETURN m /* */",
"MATCH (n) RETURN n; CREATE (m)",
"MATCH (n) WITH n DETACH DELETE n RETURN 1",
"MATCH (n) CALL { WITH n SET n.x = 1 } RETURN n",
"WITH 1 AS x CALL apoc.cypher.run('CREATE (n)', {}) YIELD value RETURN value",
"MATCH (n) FOREACH (x IN [1] | SET n.x = x) RETURN n",
"INSERT (n) RETURN n",
"SHOW TRANSACTIONS YIELD transactionId TERMINATE TRANSACTIONS transactionId",
"RETURN 'unterminated",
"RETURN 1 /*",
"",
"// read",
"MATCH (n) RETURN 'escaped\\' quote' SET n.x = 1 RETURN n",
])("blocks writes, calls and incomplete input: %s", (sql) => expect(classifySqlRisk(sql, { dialect: "neo4j" }).risk).not.toBe("read"));
it("does not enable MATCH for SQL dialects", () => expect(classifySqlRisk("MATCH (n) RETURN n", { dialect: "mysql" }).risk).not.toBe("read"));
it.each(["WITH {set: 1, delete: 2} AS m RETURN m.set, m.delete", "MATCH (n:SET) WHERE n.remove = $delete RETURN n", "MATCH (n) RETURN n./* property */set"])("allows keyword-named identifiers: %s", (sql) => expect(classifySqlRisk(sql, { dialect: "neo4j" }).risk).toBe("read"));
it.each([
String.raw`MATCH (n) \u0053ET n.p = 1 RETURN n`,
String.raw`MATCH (n) // hidden\u000ASET n.p = 1 RETURN n`,
String.raw`MATCH (n) RETURN n.\u0060name\u0060 SET n.p = 1 RETURN n`,
"WITH {set: 1} AS m MATCH (n) SET n.p = m.set RETURN n",
"MATCH (n:SET) DELETE n RETURN 1",
"MATCH (n) RETURN n.set; CALL dbms.killQuery('q')",
])("does not hide writes behind escapes or identifier names: %s", (sql) => expect(classifySqlRisk(sql, { dialect: "neo4j" }).risk).not.toBe("read"));
});
@@ -0,0 +1,63 @@
const UNSAFE_WORDS = new Set(["CREATE", "INSERT", "MERGE", "SET", "REMOVE", "DELETE", "DETACH", "DROP", "ALTER", "RENAME", "GRANT", "REVOKE", "DENY", "CALL", "FOREACH", "LOAD", "START", "STOP", "TERMINATE"]);
// Keep parity with dbx-sql-core/cypher_read_only.rs. `--` must remain an edge.
export function isProvenReadOnlyCypher(source: string): boolean {
// Neo4j expands Unicode escapes before lexing, including inside comments.
if (source.includes("\\u")) return false;
const statements: string[][] = [[]];
let index = 0;
while (index < source.length) {
const char = source[index];
const next = source[index + 1];
if (char === "/" && next === "/") {
index += 2;
while (index < source.length && !["\n", "\r"].includes(source[index])) index++;
} else if (char === "/" && next === "*") {
index += 2;
let depth = 1;
while (index < source.length && depth > 0) {
if (source[index] === "/" && source[index + 1] === "*") {
return false;
} else if (source[index] === "*" && source[index + 1] === "/") {
depth--;
index += 2;
} else index++;
}
if (depth !== 0) return false;
} else if (char === "'" || char === '"' || char === "`") {
index++;
let closed = false;
while (index < source.length) {
if (source[index] === "\\") index += 2;
else if (source[index] === char) {
index++;
if (source[index] === char) index++;
else {
closed = true;
break;
}
} else index++;
}
if (!closed) return false;
statements[statements.length - 1].push("<quoted>");
} else if (char === ";") {
statements.push([]);
index++;
} else if (/[A-Za-z_]/.test(char)) {
const start = index++;
while (index < source.length && /[\p{L}\p{N}_]/u.test(source[index])) index++;
statements[statements.length - 1].push(source.slice(start, index).toUpperCase());
} else {
if ([".", ":", "$"].includes(char)) statements[statements.length - 1].push(char);
else if (!/\s/u.test(char)) statements[statements.length - 1].push("<symbol>");
index++;
}
}
const nonempty = statements.filter((words) => words.length);
return (
nonempty.length > 0 &&
nonempty.every(
(words) => ["MATCH", "OPTIONAL", "RETURN", "WITH", "UNWIND", "SHOW", "EXPLAIN", "PROFILE"].includes(words[0]) && (words[0] === "SHOW" || words.includes("RETURN")) && !words.some((word, index) => UNSAFE_WORDS.has(word) && ![".", ":", "$"].includes(words[index - 1]) && words[index + 1] !== ":"),
)
);
}
+6
View File
@@ -3,6 +3,7 @@ import { classifySolrRequestRisk, classifySolrSourceRisk } from "@/lib/solr/solr
import { classifyCouchDbRequestRisk, classifyCouchDbSourceRisk, type CouchDbRequestRisk } from "@/lib/couchdb/couchdbRequestRisk"; import { classifyCouchDbRequestRisk, classifyCouchDbSourceRisk, type CouchDbRequestRisk } from "@/lib/couchdb/couchdbRequestRisk";
import { mongoAggregateWriteStage, splitMongoCommandRanges, type MongoCommand } from "@/lib/mongo/mongoShellCommand"; import { mongoAggregateWriteStage, splitMongoCommandRanges, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
import { isCouchDbDatabaseType, isElasticsearchCompatibleDatabaseType, isSolrDatabaseType, type DatabaseType } from "@/types/database"; import { isCouchDbDatabaseType, isElasticsearchCompatibleDatabaseType, isSolrDatabaseType, type DatabaseType } from "@/types/database";
import { isProvenReadOnlyCypher } from "./cypherReadOnly";
export type SqlRiskLevel = "read" | "write" | "ddl" | "transaction" | "unknown"; export type SqlRiskLevel = "read" | "write" | "ddl" | "transaction" | "unknown";
@@ -70,6 +71,10 @@ export function splitSqlStatementsForSafety(sql: string, dialect?: DatabaseType
} }
export function classifySqlRisk(sql: string, options: SqlRiskOptions = {}): SqlRiskAssessment { export function classifySqlRisk(sql: string, options: SqlRiskOptions = {}): SqlRiskAssessment {
if (options.dialect === "neo4j") {
const assessment: SqlRiskStatementAssessment = { risk: isProvenReadOnlyCypher(sql) ? "read" : "unknown", firstKeyword: "cypher" };
return { ...assessment, statements: [assessment] };
}
const mongoStatements = mongoShellStatements(sql, options.dialect); const mongoStatements = mongoShellStatements(sql, options.dialect);
if (mongoStatements) { if (mongoStatements) {
const highest = highestRiskStatement(mongoStatements); const highest = highestRiskStatement(mongoStatements);
@@ -88,6 +93,7 @@ export function classifySqlRisk(sql: string, options: SqlRiskOptions = {}): SqlR
} }
export function classifySqlStatementRisk(sql: string, options: SqlRiskOptions = {}): SqlRiskStatementAssessment { export function classifySqlStatementRisk(sql: string, options: SqlRiskOptions = {}): SqlRiskStatementAssessment {
if (options.dialect === "neo4j") return { risk: isProvenReadOnlyCypher(sql) ? "read" : "unknown", firstKeyword: "cypher" };
const mongoStatements = mongoShellStatements(sql, options.dialect); const mongoStatements = mongoShellStatements(sql, options.dialect);
if (mongoStatements) return highestRiskStatement(mongoStatements); if (mongoStatements) return highestRiskStatement(mongoStatements);
@@ -1105,6 +1105,8 @@ async fn export_query_result_core_inner(
let row_count = result.rows.len(); let row_count = result.rows.len();
if request.database_type == DatabaseType::Nebula { if request.database_type == DatabaseType::Nebula {
crate::text_export::normalize_nebula_export_rows(&mut result.rows); crate::text_export::normalize_nebula_export_rows(&mut result.rows);
} else if request.database_type == DatabaseType::Neo4j {
crate::text_export::normalize_neo4j_export_rows(&mut result.rows);
} }
let formatted_rows = crate::temporal_format::format_temporal_export_rows_with_string_types_cow( let formatted_rows = crate::temporal_format::format_temporal_export_rows_with_string_types_cow(
&result.rows, &result.rows,
+76 -1
View File
@@ -26,6 +26,22 @@ pub fn normalize_nebula_export_rows(rows: &mut [Vec<Value>]) {
} }
} }
pub fn normalize_neo4j_export_rows(rows: &mut [Vec<Value>]) {
for value in rows.iter_mut().flatten() {
let graph_cell = value.get("__dbx_graph_cell").and_then(Value::as_str) == Some("neo4j-v1")
&& value.get("kind").is_some_and(Value::is_string)
&& value.get("nodes").is_some_and(Value::is_array)
&& value.get("edges").is_some_and(Value::is_array);
let node_cell = value.get("__dbx_neo4j_node").and_then(Value::as_str) == Some("v1")
&& value.get("properties").is_some_and(Value::is_array);
if graph_cell || node_cell {
if let Some(display) = value.get("display").and_then(Value::as_str) {
*value = Value::String(display.to_owned());
}
}
}
}
pub fn format_json(data: &QueryResultTextExportData) -> Result<String, String> { pub fn format_json(data: &QueryResultTextExportData) -> Result<String, String> {
let rows = data let rows = data
.rows .rows
@@ -442,7 +458,10 @@ fn chrono_local_now() -> String {
mod tests { mod tests {
use serde_json::{json, Value}; use serde_json::{json, Value};
use super::{format_html, format_json, format_markdown, normalize_nebula_export_rows, QueryResultTextExportData}; use super::{
format_html, format_json, format_markdown, normalize_nebula_export_rows, normalize_neo4j_export_rows,
QueryResultTextExportData,
};
#[test] #[test]
fn nebula_exports_use_display_cells_without_leaking_graph_metadata() { fn nebula_exports_use_display_cells_without_leaking_graph_metadata() {
@@ -492,6 +511,62 @@ mod tests {
assert_eq!(rows[0][4], original[0][4]); assert_eq!(rows[0][4], original[0][4]);
} }
#[test]
fn neo4j_exports_use_display_cells_without_leaking_graph_metadata() {
let displays = [
("vertex", "(:Person {\"count\":9007199254740993})"),
("edge", "[:KNOWS]"),
("path", "{\"nodes\":[],\"relationships\":[]}"),
("map", "{\"count\":9007199254740993,\"node\":{\"labels\":[\"Person\"]}}"),
];
let mut rows = displays
.iter()
.map(|(kind, display)| {
vec![
json!({
"__dbx_graph_cell": "neo4j-v1", "kind": kind, "display": display,
"nodes": [], "edges": [], "displayParts": ["internal metadata"]
}),
json!(false),
Value::Null,
]
})
.collect::<Vec<_>>();
rows.push(vec![
json!({"__dbx_neo4j_node":"v1", "display":"(:Legacy)", "properties": []}),
json!(7),
json!("plain"),
]);
normalize_neo4j_export_rows(&mut rows);
for (index, (_, display)) in displays.iter().enumerate() {
assert_eq!(rows[index], vec![json!(display), json!(false), Value::Null]);
}
assert_eq!(rows[4], vec![json!("(:Legacy)"), json!(7), json!("plain")]);
let data = QueryResultTextExportData {
title: None,
columns: vec!["entity".into(), "value".into(), "note".into()],
rows,
};
let exported: Value = serde_json::from_str(&format_json(&data).unwrap()).unwrap();
assert_eq!(exported[0]["entity"], json!(displays[0].1));
assert_eq!(exported[1]["entity"], json!("[:KNOWS]"));
assert!(!format_markdown(&data).contains("__dbx_graph_cell"));
}
#[test]
fn neo4j_export_normalization_preserves_ordinary_and_unknown_objects() {
let mut rows = vec![vec![
json!({"display":"ordinary", "properties":[]}),
json!({"__dbx_graph_cell":"nebula-v1", "kind":"vertex", "display":"nebula", "nodes":[], "edges":[]}),
json!({"__dbx_graph_cell":"neo4j-v2", "kind":"vertex", "display":"future", "nodes":[], "edges":[]}),
json!({"__dbx_graph_cell":"neo4j-v1", "kind":"vertex", "display":42, "nodes":[], "edges":[]}),
json!({"__dbx_graph_cell":"neo4j-v1", "kind":"vertex", "display":"malformed", "nodes":null, "edges":[]}),
]];
let original = rows.clone();
normalize_neo4j_export_rows(&mut rows);
assert_eq!(rows, original);
}
#[test] #[test]
fn formats_json_rows_as_objects() { fn formats_json_rows_as_objects() {
let out = format_json(&QueryResultTextExportData { let out = format_json(&QueryResultTextExportData {
+168
View File
@@ -0,0 +1,168 @@
const UNSAFE_WORDS: &[&str] = &[
"CREATE",
"INSERT",
"MERGE",
"SET",
"REMOVE",
"DELETE",
"DETACH",
"DROP",
"ALTER",
"RENAME",
"GRANT",
"REVOKE",
"DENY",
"CALL",
"FOREACH",
"LOAD",
"START",
"STOP",
"TERMINATE",
];
// Cypher's `--` is a relationship, not a SQL line comment. Keep this scanner
// separate so trailing writes cannot disappear during SQL comment stripping.
pub(crate) fn is_proven_read_only_cypher(source: &str) -> bool {
// Neo4j expands Unicode escapes before lexing, including inside comments.
if source.contains("\\u") {
return false;
}
let chars: Vec<char> = source.chars().collect();
let mut index = 0;
let mut statements = vec![Vec::<String>::new()];
while index < chars.len() {
let ch = chars[index];
let next = chars.get(index + 1).copied();
if ch == '/' && next == Some('/') {
index += 2;
while index < chars.len() && !matches!(chars[index], '\n' | '\r') {
index += 1;
}
} else if ch == '/' && next == Some('*') {
index += 2;
let mut depth = 1;
while index < chars.len() && depth > 0 {
match (chars[index], chars.get(index + 1)) {
('/', Some('*')) => {
return false;
}
('*', Some('/')) => {
depth -= 1;
index += 2;
}
_ => index += 1,
}
}
if depth != 0 {
return false;
}
} else if matches!(ch, '\'' | '"' | '`') {
index += 1;
let mut closed = false;
while index < chars.len() {
if chars[index] == '\\' {
index += 2;
} else if chars[index] == ch {
index += 1;
if chars.get(index) == Some(&ch) {
index += 1;
} else {
closed = true;
break;
}
} else {
index += 1;
}
}
if !closed {
return false;
}
statements.last_mut().unwrap().push("<quoted>".into());
} else if ch == ';' {
statements.push(Vec::new());
index += 1;
} else if ch.is_ascii_alphabetic() || ch == '_' {
let start = index;
index += 1;
while index < chars.len() && (chars[index].is_alphanumeric() || chars[index] == '_') {
index += 1;
}
statements.last_mut().unwrap().push(chars[start..index].iter().collect::<String>().to_ascii_uppercase());
} else {
if matches!(ch, '.' | ':' | '$') {
statements.last_mut().unwrap().push(ch.to_string());
} else if !ch.is_whitespace() {
statements.last_mut().unwrap().push("<symbol>".into());
}
index += 1;
}
}
let statements: Vec<_> = statements.iter().filter(|words| !words.is_empty()).collect();
!statements.is_empty()
&& statements.iter().all(|words| {
matches!(
words.first().map(String::as_str),
Some("MATCH" | "OPTIONAL" | "RETURN" | "WITH" | "UNWIND" | "SHOW" | "EXPLAIN" | "PROFILE")
) && (words[0] == "SHOW" || words.iter().any(|word| word == "RETURN"))
&& !words.iter().enumerate().any(|(index, word)| {
UNSAFE_WORDS.contains(&word.as_str())
&& !matches!(
index.checked_sub(1).and_then(|previous| words.get(previous)).map(String::as_str),
Some("." | ":" | "$")
)
&& words.get(index + 1).map(String::as_str) != Some(":")
})
})
}
#[cfg(test)]
mod tests {
use crate::{models::connection::DatabaseType, query_execution_sql::check_read_only};
#[test]
fn cypher_reads_are_allowed_only_for_neo4j() {
for source in [
"MATCH (n)-->(m) RETURN n,m",
"MATCH (n) WHERE elementId(n) = '4:id:1' OPTIONAL MATCH (n)-[r]-(m) RETURN n,r,m LIMIT 200",
"// SET is a comment\nMATCH (n:`DELETE`) WHERE n.name = 'CREATE; SET' RETURN n",
"UNWIND [1,2] AS x RETURN x; RETURN 1",
"SHOW DATABASES",
"EXPLAIN MATCH (n) RETURN n",
"/* comment */ WITH 1 AS x RETURN x",
"WITH {set: 1, delete: 2} AS m RETURN m.set, m.delete",
"MATCH (n:SET) WHERE n.remove = $delete RETURN n",
"MATCH (n) RETURN n./* property */set",
] {
assert!(check_read_only(source, "test", DatabaseType::Neo4j).is_ok(), "{source}");
}
assert!(check_read_only("MATCH (n) RETURN n", "test", DatabaseType::Mysql).is_err());
}
#[test]
fn cypher_writes_procedures_and_incomplete_input_are_blocked() {
for source in [
"MATCH (n)-->(m) SET n.x = 1 RETURN n",
"MATCH (n) RETURN n /* outer /* inner */ UNION MATCH (m) SET m.x=1 RETURN m /* */",
"MATCH (n) RETURN n; CREATE (m)",
"MATCH (n) WITH n DETACH DELETE n RETURN 1",
"MATCH (n) CALL { WITH n SET n.x = 1 } RETURN n",
"WITH 1 AS x CALL apoc.cypher.run('CREATE (n)', {}) YIELD value RETURN value",
"MATCH (n) FOREACH (x IN [1] | SET n.x = x) RETURN n",
"INSERT (n) RETURN n",
"SHOW TRANSACTIONS YIELD transactionId TERMINATE TRANSACTIONS transactionId",
"RETURN 'unterminated",
"RETURN 1 /*",
"",
"// read",
"MATCH (n) RETURN 'escaped\\' quote' SET n.x = 1 RETURN n",
r"MATCH (n) \u0053ET n.p = 1 RETURN n",
r"MATCH (n) // hidden\u000ASET n.p = 1 RETURN n",
r"MATCH (n) RETURN n.\u0060name\u0060 SET n.p = 1 RETURN n",
"WITH {set: 1} AS m MATCH (n) SET n.p = m.set RETURN n",
"MATCH (n:SET) DELETE n RETURN 1",
"MATCH (n) RETURN n.set; CALL dbms.killQuery('q')",
] {
assert!(check_read_only(source, "test", DatabaseType::Neo4j).is_err(), "{source}");
}
}
}
+2
View File
@@ -2,6 +2,8 @@
pub use dbx_types::{database_manifest, models, types}; pub use dbx_types::{database_manifest, models, types};
mod cypher_read_only;
pub mod dml_preview_sql; pub mod dml_preview_sql;
pub mod mysql_ddl_normalize; pub mod mysql_ddl_normalize;
pub mod mysql_event_sql; pub mod mysql_event_sql;
@@ -427,6 +427,9 @@ pub fn is_write_sql(sql: &str) -> bool {
/// executable comments and file exports, plus PostgreSQL-family/SQL Server /// executable comments and file exports, plus PostgreSQL-family/SQL Server
/// `SELECT ... INTO` table creation. /// `SELECT ... INTO` table creation.
pub fn is_write_sql_for_database(sql: &str, database_type: DatabaseType) -> bool { pub fn is_write_sql_for_database(sql: &str, database_type: DatabaseType) -> bool {
if database_type == DatabaseType::Neo4j {
return !crate::cypher_read_only::is_proven_read_only_cypher(sql);
}
// VictoriaMetrics execution is hard-wired to the read-only query API; MetricsQL // VictoriaMetrics execution is hard-wired to the read-only query API; MetricsQL
// does not use SQL verbs and must not be rejected by SQL write classification. // does not use SQL verbs and must not be rejected by SQL write classification.
if database_type == DatabaseType::VictoriaMetrics { if database_type == DatabaseType::VictoriaMetrics {
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB