-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcypher_write.go
More file actions
356 lines (313 loc) · 9.79 KB
/
cypher_write.go
File metadata and controls
356 lines (313 loc) · 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package graphdb
import (
"context"
"fmt"
"time"
)
// ---------------------------------------------------------------------------
// Cypher Write Executor — handles CREATE statements.
//
// Supported:
// CREATE (n:Label {props}) — create a single node
// CREATE (a:L1 {p1})-[:REL {p2}]->(b:L2 {p3}) — create two nodes + edge
// CREATE (a)-[:REL]->(b), (c:Label {props}) — multiple patterns
// CREATE ... RETURN n, a, b — return created entities
//
// Variable bindings: each named node variable (e.g. "n" in "(n:Person)")
// is bound to the created *Node so that later patterns and RETURN can
// reference it.
// ---------------------------------------------------------------------------
// CypherCreateResult holds the result of a CREATE query execution.
type CypherCreateResult struct {
Columns []string // column names if RETURN was specified
Rows []map[string]any // projected rows if RETURN was specified
Stats CreateStats // mutation statistics
}
// CreateStats tracks what was created by a CREATE statement.
type CreateStats struct {
NodesCreated int `json:"nodes_created"`
EdgesCreated int `json:"edges_created"`
LabelsSet int `json:"labels_set"`
PropsSet int `json:"props_set"`
}
// executeCreate executes a parsed CypherWrite (CREATE) against the database.
func (db *DB) executeCreate(ctx context.Context, w *CypherWrite) (*CypherCreateResult, error) {
if db.isClosed() {
return nil, fmt.Errorf("graphdb: database is closed")
}
result := &CypherCreateResult{}
// bindings maps variable names to created *Node values.
bindings := make(map[string]any)
for _, cp := range w.Creates {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := db.executeCreatePattern(ctx, cp, bindings, &result.Stats); err != nil {
return nil, err
}
}
// Project RETURN if present.
if w.Return != nil {
for _, item := range w.Return.Items {
result.Columns = append(result.Columns, returnItemName(item))
}
row := make(map[string]any, len(w.Return.Items))
for _, item := range w.Return.Items {
colName := item.Alias
if colName == "" {
colName = returnItemName(item)
}
val, _ := evalExpr(&item.Expr, bindings)
row[colName] = val
}
result.Rows = append(result.Rows, row)
}
return result, nil
}
// executeCreatePattern creates nodes and edges for a single CREATE pattern.
func (db *DB) executeCreatePattern(ctx context.Context, cp CreatePattern, bindings map[string]any, stats *CreateStats) error {
if len(cp.Nodes) == 0 {
return fmt.Errorf("cypher exec: CREATE pattern has no nodes")
}
// Create (or resolve) each node in the pattern.
nodeIDs := make([]NodeID, len(cp.Nodes))
for i, np := range cp.Nodes {
if err := ctx.Err(); err != nil {
return err
}
// If the variable is already bound (from a previous pattern), reuse it.
if np.Variable != "" {
if existing, ok := bindings[np.Variable]; ok {
if n, ok := existing.(*Node); ok {
nodeIDs[i] = n.ID
continue
}
}
}
// Build props from the node pattern.
props := make(Props)
for k, v := range np.Props {
props[k] = v
stats.PropsSet++
}
// Use AddNodeWithLabels when labels are present — this enforces
// unique constraints atomically within the same transaction.
var id NodeID
if len(np.Labels) > 0 {
var err error
id, err = db.AddNodeWithLabels(np.Labels, props)
if err != nil {
return fmt.Errorf("cypher exec: CREATE node failed: %w", err)
}
stats.LabelsSet += len(np.Labels)
} else {
var err error
id, err = db.AddNode(props)
if err != nil {
return fmt.Errorf("cypher exec: CREATE node failed: %w", err)
}
}
nodeIDs[i] = id
stats.NodesCreated++
// Bind the variable.
if np.Variable != "" {
node, err := db.getNode(id)
if err != nil {
return err
}
bindings[np.Variable] = node
}
}
// Create edges between consecutive node pairs.
for i, rp := range cp.Rels {
if err := ctx.Err(); err != nil {
return err
}
fromID := nodeIDs[i]
toID := nodeIDs[i+1]
// Respect direction: if incoming (<-[]-), swap from/to.
if rp.Dir == Incoming {
fromID, toID = toID, fromID
}
label := rp.Label
if label == "" {
return fmt.Errorf("cypher exec: CREATE relationship requires a label (type)")
}
// Edge properties (from rel pattern inline props — currently parsed
// by parseRelPattern as part of the bracket content, but RelPattern
// doesn't have a Props field; we can add it later. For now edges are
// created without properties).
_, err := db.AddEdge(fromID, toID, label, nil)
if err != nil {
return fmt.Errorf("cypher exec: CREATE edge failed: %w", err)
}
stats.EdgesCreated++
// Bind edge variable if named.
if rp.Variable != "" {
// Fetch the edge we just created for binding.
edges, err := db.getEdgesForNode(fromID, Outgoing)
if err == nil {
for _, e := range edges {
if e.To == toID && e.Label == label {
bindings[rp.Variable] = e
break
}
}
}
}
}
return nil
}
// ---------------------------------------------------------------------------
// MERGE executor — match-or-create semantics.
//
// MERGE (n:Label {key: value}) tries to find an existing node with the given
// labels and properties. If found, it binds the node. If not found, it creates
// a new node with those labels and properties.
//
// When a unique constraint exists on (Label, key), the lookup is O(1) per shard
// via the unique index. Without a constraint, it falls back to a label scan
// with property filtering.
// ---------------------------------------------------------------------------
// executeMerge executes a parsed CypherMerge against the database.
func (db *DB) executeMerge(ctx context.Context, m *CypherMerge) (*CypherResult, error) {
if db.isClosed() {
return nil, fmt.Errorf("graphdb: database is closed")
}
mp := m.Pattern
bindings := make(map[string]any)
// Step 1: Try to find an existing node matching all labels and properties.
var matched *Node
if len(mp.Labels) > 0 && len(mp.Props) > 0 {
// Optimization: if a unique constraint exists, use O(1) lookup.
for propKey, propVal := range mp.Props {
if db.HasUniqueConstraint(mp.Labels[0], propKey) {
found, err := db.FindByUniqueConstraint(mp.Labels[0], propKey, propVal)
if err != nil {
return nil, fmt.Errorf("cypher exec: MERGE lookup failed: %w", err)
}
if found != nil {
// Verify all labels and all properties match.
if matchLabels(found.Labels, mp.Labels) && matchProps(found.Props, mp.Props) {
matched = found
}
}
break // Only need to check one constrained property.
}
}
}
// Fallback: label scan with property filtering.
if matched == nil && len(mp.Labels) > 0 {
candidates, err := db.FindByLabel(mp.Labels[0])
if err != nil {
return nil, fmt.Errorf("cypher exec: MERGE label scan failed: %w", err)
}
for _, n := range candidates {
if matchLabels(n.Labels, mp.Labels) && matchProps(n.Props, mp.Props) {
matched = n
break
}
}
}
// Step 2: If no match found, create the node.
wasCreated := false
if matched == nil {
if err := db.writeGuard(); err != nil {
return nil, err
}
props := make(Props, len(mp.Props))
for k, v := range mp.Props {
props[k] = v
}
id, err := db.AddNodeWithLabels(mp.Labels, props)
if err != nil {
return nil, fmt.Errorf("cypher exec: MERGE create failed: %w", err)
}
matched, err = db.getNode(id)
if err != nil {
return nil, err
}
wasCreated = true
}
// Bind the variable.
if mp.Variable != "" {
bindings[mp.Variable] = matched
}
// Step 3: Apply ON CREATE SET / ON MATCH SET clauses.
var setItems []SetItem
if wasCreated {
setItems = m.OnCreateSet
} else {
setItems = m.OnMatchSet
}
if len(setItems) > 0 {
// ON MATCH SET needs writeGuard (ON CREATE SET already passed through it).
if !wasCreated {
if err := db.writeGuard(); err != nil {
return nil, err
}
}
updateProps := make(Props, len(setItems))
for _, si := range setItems {
val, err := evalExpr(&si.Value, bindings)
if err != nil {
return nil, fmt.Errorf("cypher exec: MERGE SET value eval: %w", err)
}
updateProps[si.Property] = val
}
if err := db.UpdateNode(matched.ID, updateProps); err != nil {
return nil, fmt.Errorf("cypher exec: MERGE SET failed: %w", err)
}
// Refresh matched node to reflect updates.
matched, _ = db.getNode(matched.ID)
if mp.Variable != "" {
bindings[mp.Variable] = matched
}
}
// Build result.
result := &CypherResult{}
if m.Return != nil {
for _, item := range m.Return.Items {
result.Columns = append(result.Columns, returnItemName(item))
}
row := make(map[string]any, len(m.Return.Items))
for _, item := range m.Return.Items {
colName := item.Alias
if colName == "" {
colName = returnItemName(item)
}
val, _ := evalExpr(&item.Expr, bindings)
row[colName] = val
}
result.Rows = append(result.Rows, row)
}
return result, nil
}
// CypherCreate executes a CREATE Cypher query string.
// Accepts a context.Context for timeout/cancellation.
// Returns the result with creation statistics and optional RETURN data.
func (db *DB) CypherCreate(ctx context.Context, query string) (*CypherCreateResult, error) {
if db.isClosed() {
return nil, fmt.Errorf("graphdb: database is closed")
}
return safeExecuteResult(func() (*CypherCreateResult, error) {
parsed, err := parseCypher(query)
if err != nil {
return nil, err
}
if parsed.write == nil {
return nil, fmt.Errorf("cypher exec: expected CREATE query, got MATCH")
}
start := time.Now()
result, err := db.executeCreate(ctx, parsed.write)
elapsed := time.Since(start)
if db.metrics != nil {
db.metrics.QueriesTotal.Add(1)
db.metrics.recordQueryDuration(elapsed)
if err != nil {
db.metrics.QueryErrorTotal.Add(1)
}
}
return result, err
})
}