forked from darshanDevrai/brahmand
-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconnection.rs
More file actions
1937 lines (1826 loc) · 75.4 KB
/
connection.rs
File metadata and controls
1937 lines (1826 loc) · 75.4 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `Connection` — executes Cypher queries against a `Database`.
//!
//! Analogous to `kuzu::Connection`. Multiple connections can share one `Database`.
//! Each `Connection` holds a reference to the `Database`'s executor and schema.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use clickgraph::executor::QueryExecutor;
use clickgraph::graph_catalog::graph_schema::GraphSchema;
use super::database::Database;
use super::error::EmbeddedError;
use super::export::{build_export_sql, ExportOptions};
use super::graph_result::{parse_element_id, transform_rows_to_graph, GraphResult, StoreStats};
use super::query_result::QueryResult;
use super::value::Value;
use super::write_helpers;
/// Default maximum CTE recursion depth for Cypher→SQL translation.
const DEFAULT_MAX_CTE_DEPTH: u32 = 100;
/// A connection to an embedded ClickGraph database.
///
/// # Example
///
/// ```no_run
/// use clickgraph_embedded::{Database, Connection, SystemConfig};
///
/// let db = Database::new("schema.yaml", SystemConfig::default()).unwrap();
/// let conn = Connection::new(&db).unwrap();
///
/// let mut result = conn.query("MATCH (u:User) RETURN u.name LIMIT 10").unwrap();
/// for row in result {
/// println!("{}", row[0]);
/// }
/// ```
pub struct Connection<'db> {
executor: Arc<dyn QueryExecutor>,
remote_executor: Option<Arc<dyn QueryExecutor>>,
schema: Arc<GraphSchema>,
db: &'db Database,
/// Query timeout in milliseconds. 0 = no timeout (default).
query_timeout_ms: u64,
}
impl<'db> Connection<'db> {
/// Create a new connection to `db`.
pub fn new(db: &'db Database) -> Result<Self, EmbeddedError> {
Ok(Connection {
executor: Arc::clone(&db.executor),
remote_executor: db.remote_executor.as_ref().map(Arc::clone),
schema: Arc::clone(&db.schema),
db,
query_timeout_ms: 0,
})
}
/// Set the query timeout in milliseconds. 0 = no timeout (default).
///
/// Mirrors `kuzu::Connection::set_query_timeout()`. Applies to
/// `query()`, `query_remote()`, `query_graph()`, and `query_remote_graph()`.
pub fn set_query_timeout(&mut self, timeout_ms: u64) {
self.query_timeout_ms = timeout_ms;
}
/// Get the current query timeout in milliseconds. 0 = no timeout.
pub fn get_query_timeout(&self) -> u64 {
self.query_timeout_ms
}
/// Execute a Cypher query and return an iterator over the result rows.
///
/// This is synchronous — it blocks until the query completes.
///
/// # Example
///
/// ```no_run
/// # use clickgraph_embedded::{Database, Connection, SystemConfig};
/// # let db = Database::new("schema.yaml", SystemConfig::default()).unwrap();
/// # let conn = Connection::new(&db).unwrap();
/// let mut result = conn.query("MATCH (u:User) RETURN u.name").unwrap();
/// while let Some(row) = result.next() {
/// println!("{}", row[0]);
/// }
/// ```
pub fn query(&self, cypher: &str) -> Result<QueryResult, EmbeddedError> {
self.db
.runtime
.block_on(self.with_timeout(self.query_async(cypher)))
}
/// Execute a Cypher query and return the generated SQL without executing it.
///
/// Useful for debugging and understanding what SQL ClickGraph generates.
pub fn query_to_sql(&self, cypher: &str) -> Result<String, EmbeddedError> {
use clickgraph::clickhouse_query_generator::cypher_to_sql;
use clickgraph::server::query_context::{
set_current_schema, with_query_context, QueryContext,
};
let schema = Arc::clone(&self.schema);
let cypher = cypher.to_string();
self.db.runtime.block_on(async move {
let context = QueryContext::new(None);
with_query_context(context, async move {
set_current_schema(Arc::clone(&schema));
cypher_to_sql(&cypher, &schema, 100).map_err(EmbeddedError::Query)
})
.await
})
}
/// Export Cypher query results to a file.
///
/// Translates the Cypher query to SQL, wraps it in
/// `INSERT INTO FUNCTION file(...)`, and executes via chdb.
/// The file is written directly by chdb — results are streamed to disk
/// without buffering the full result set in memory.
///
/// # Example
///
/// ```no_run
/// # use clickgraph_embedded::{Database, Connection, SystemConfig, ExportOptions};
/// # let db = Database::new("schema.yaml", SystemConfig::default()).unwrap();
/// # let conn = Connection::new(&db).unwrap();
/// // Auto-detect format from extension
/// conn.export("MATCH (u:User) RETURN u.name", "users.parquet", ExportOptions::default()).unwrap();
///
/// // CSV with explicit options
/// conn.export("MATCH (u:User) RETURN u.name", "users.csv", ExportOptions::default()).unwrap();
/// ```
pub fn export(
&self,
cypher: &str,
output_path: &str,
options: ExportOptions,
) -> Result<(), EmbeddedError> {
self.db
.runtime
.block_on(self.export_async(cypher, output_path, options))
}
/// Generate the export SQL without executing it (for debugging).
pub fn export_to_sql(
&self,
cypher: &str,
output_path: &str,
options: ExportOptions,
) -> Result<String, EmbeddedError> {
let select_sql = self.query_to_sql(cypher)?;
build_export_sql(&select_sql, output_path, &options).map_err(EmbeddedError::Query)
}
/// Execute a raw SQL statement (DDL, DML, or administrative command).
pub fn execute_sql(&self, sql: &str) -> Result<(), EmbeddedError> {
self.db.runtime.block_on(async {
self.executor
.execute_text(sql, "TabSeparated", None)
.await
.map_err(EmbeddedError::from)?;
Ok(())
})
}
/// Execute a Cypher query against the remote ClickHouse cluster.
///
/// Requires `RemoteConfig` to have been provided when opening the database.
/// Returns an error if no remote executor is configured.
pub fn query_remote(&self, cypher: &str) -> Result<QueryResult, EmbeddedError> {
let remote = self.get_remote_executor()?;
self.db
.runtime
.block_on(self.with_timeout(self.query_with_executor_async(cypher, remote)))
}
/// Execute a Cypher query locally and return a structured graph result.
///
/// Uses `cypher_to_sql_with_metadata()` to get plan metadata, then
/// transforms the result rows into `GraphNode`s and `GraphEdge`s.
pub fn query_graph(&self, cypher: &str) -> Result<GraphResult, EmbeddedError> {
self.db
.runtime
.block_on(self.with_timeout(self.query_graph_async(cypher, &self.executor)))
}
/// Execute a Cypher query on the remote cluster and return a structured graph result.
///
/// Combines remote execution with graph decomposition. The returned
/// `GraphResult` can be passed to `store_subgraph()` to persist locally.
pub fn query_remote_graph(&self, cypher: &str) -> Result<GraphResult, EmbeddedError> {
let remote = self.get_remote_executor()?;
self.db
.runtime
.block_on(self.with_timeout(self.query_graph_async(cypher, remote)))
}
/// Store a `GraphResult` (from `query_graph` or `query_remote_graph`) into
/// local writable tables.
///
/// Decomposes the graph into nodes grouped by label and edges grouped by
/// type, then batch-inserts each group via `create_nodes()` / `create_edges()`.
///
/// **Note**: Multi-labeled nodes are stored under their first label only.
/// This matches ClickGraph's schema model where each node belongs to exactly
/// one label (table).
pub fn store_subgraph(&self, graph: &GraphResult) -> Result<StoreStats, EmbeddedError> {
let mut nodes_stored = 0usize;
let mut edges_stored = 0usize;
// Group nodes by label
let mut nodes_by_label: HashMap<String, Vec<HashMap<String, Value>>> = HashMap::new();
for node in graph.nodes() {
let label = node
.labels
.first()
.ok_or_else(|| EmbeddedError::Validation("Node has no labels".to_string()))?;
nodes_by_label
.entry(label.clone())
.or_default()
.push(node.properties.clone());
}
// Group edges by type, extracting raw IDs from element_id strings
let mut edges_by_type: HashMap<String, Vec<(String, String, HashMap<String, Value>)>> =
HashMap::new();
for edge in graph.edges() {
let (_, from_raw_id) = parse_element_id(&edge.from_id).ok_or_else(|| {
EmbeddedError::Validation(format!("Invalid from element_id: {}", edge.from_id))
})?;
let (_, to_raw_id) = parse_element_id(&edge.to_id).ok_or_else(|| {
EmbeddedError::Validation(format!("Invalid to element_id: {}", edge.to_id))
})?;
edges_by_type
.entry(edge.type_name.clone())
.or_default()
.push((
from_raw_id.to_string(),
to_raw_id.to_string(),
edge.properties.clone(),
));
}
// Batch-insert nodes
for (label, batch) in nodes_by_label {
nodes_stored += batch.len();
self.create_nodes(&label, batch)?;
}
// Batch-insert edges
for (edge_type, batch) in edges_by_type {
edges_stored += batch.len();
self.create_edges(&edge_type, batch)?;
}
Ok(StoreStats {
nodes_stored,
edges_stored,
})
}
/// Create a node with the given label and properties.
pub fn create_node(
&self,
label: &str,
properties: HashMap<String, Value>,
) -> Result<String, EmbeddedError> {
let node_schema = self.get_node_schema(label)?;
let id_columns = node_schema.node_id.id.columns();
let id_col_strs: Vec<&str> = id_columns.iter().copied().collect();
let property_mappings =
write_helpers::extract_property_mappings(&node_schema.property_mappings);
write_helpers::validate_properties(&properties, &property_mappings, &id_col_strs)?;
let id_key = id_columns.first().copied().unwrap_or("id");
let node_id = if let Some(v) = properties.get(id_key) {
match v {
Value::String(s) => s.clone(),
other => other
.to_sql_literal()
.map_err(EmbeddedError::Validation)?
.trim_matches('\'')
.to_string(),
}
} else {
uuid::Uuid::new_v4().to_string()
};
let mut columns = vec![id_key.to_string()];
let mut values = vec![Value::String(node_id.clone())
.to_sql_literal()
.map_err(EmbeddedError::Validation)?];
for (cypher_name, value) in &properties {
if cypher_name == id_key {
continue;
}
let col_name = property_mappings
.get(cypher_name.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| cypher_name.clone());
columns.push(col_name);
values.push(value.to_sql_literal().map_err(EmbeddedError::Validation)?);
}
let sql = write_helpers::build_insert_sql(
&node_schema.database,
&node_schema.table_name,
&columns,
&[values],
);
self.execute_sql(&sql)?;
Ok(node_id)
}
/// Create an edge between two nodes.
pub fn create_edge(
&self,
edge_type: &str,
from_id: &str,
to_id: &str,
properties: HashMap<String, Value>,
) -> Result<(), EmbeddedError> {
let rel_schema = self.get_rel_schema(edge_type)?;
let from_id_cols = rel_schema.from_id.columns();
let to_id_cols = rel_schema.to_id.columns();
let mut id_col_strs: Vec<&str> = Vec::new();
id_col_strs.extend(from_id_cols.iter().copied());
id_col_strs.extend(to_id_cols.iter().copied());
let property_mappings =
write_helpers::extract_property_mappings(&rel_schema.property_mappings);
write_helpers::validate_properties(&properties, &property_mappings, &id_col_strs)?;
let mut columns = Vec::new();
let mut values = Vec::new();
let from_col = from_id_cols.first().copied().unwrap_or("from_id");
let to_col = to_id_cols.first().copied().unwrap_or("to_id");
columns.push(from_col.to_string());
values.push(
Value::String(from_id.to_string())
.to_sql_literal()
.map_err(EmbeddedError::Validation)?,
);
columns.push(to_col.to_string());
values.push(
Value::String(to_id.to_string())
.to_sql_literal()
.map_err(EmbeddedError::Validation)?,
);
for (cypher_name, value) in &properties {
let col_name = property_mappings
.get(cypher_name.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| cypher_name.clone());
columns.push(col_name);
values.push(value.to_sql_literal().map_err(EmbeddedError::Validation)?);
}
let sql = write_helpers::build_insert_sql(
&rel_schema.database,
&rel_schema.table_name,
&columns,
&[values],
);
self.execute_sql(&sql)
}
/// Parse and load graph data from a Cypher CREATE block.
///
/// Handles the subset of CREATE syntax used in test fixtures and data loading:
/// - Labeled nodes with properties: `(n:Person {name: 'Alice', age: 30})`
/// - Directed edges: `(n)-[:KNOWS {since: 2020}]->(m)`
/// - Multi-statement blocks (multiple CREATE statements in one string)
///
/// Returns [`LoadStats`] with counts of nodes and edges inserted.
///
/// # Notes
///
/// Edges whose endpoint variables are not defined in the same CREATE block
/// are silently skipped (no error is returned). Ensure all referenced node
/// variables appear earlier in the same block.
///
/// # Example
///
/// ```no_run
/// # use clickgraph_embedded::{Database, Connection, SystemConfig};
/// # let db = Database::new("schema.yaml", SystemConfig::default()).unwrap();
/// # let conn = Connection::new(&db).unwrap();
/// let stats = conn.load_cypher_create(
/// "CREATE (a:Person {name: 'Alice'})-[:KNOWS]->(b:Person {name: 'Bob'})"
/// ).unwrap();
/// assert_eq!(stats.nodes_loaded, 2);
/// assert_eq!(stats.edges_loaded, 1);
/// ```
pub fn load_cypher_create(
&self,
cypher: &str,
) -> Result<crate::cypher_loader::LoadStats, EmbeddedError> {
use crate::cypher_loader::{parse_create_block, LoadStats};
let mut var_map = std::collections::HashMap::new();
let parsed = parse_create_block(cypher, &mut var_map);
let mut stats = LoadStats::default();
// Insert nodes; track var → assigned ID for edge resolution.
let mut node_ids: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for node in &parsed.nodes {
let label = node.label.as_deref().unwrap_or("__Unlabeled");
let var = node.var.as_deref().unwrap_or("").to_string();
let props: HashMap<String, Value> = node
.props
.iter()
.map(|(k, v)| (k.clone(), v.to_value()))
.collect();
let node_id = self.create_node(label, props)?;
if !var.is_empty() {
node_ids.insert(var, node_id);
}
stats.nodes_loaded += 1;
}
// Insert edges using the resolved node IDs.
for edge in &parsed.edges {
let from_id = match node_ids.get(&edge.from_var) {
Some(id) => id.clone(),
None => continue, // unresolved variable — skip
};
let to_id = match node_ids.get(&edge.to_var) {
Some(id) => id.clone(),
None => continue,
};
let props: HashMap<String, Value> = edge
.props
.iter()
.map(|(k, v)| (k.clone(), v.to_value()))
.collect();
self.create_edge(&edge.rel_type, &from_id, &to_id, props)?;
stats.edges_loaded += 1;
}
Ok(stats)
}
/// Upsert a node (INSERT with ReplacingMergeTree deduplication).
pub fn upsert_node(
&self,
label: &str,
properties: HashMap<String, Value>,
) -> Result<String, EmbeddedError> {
let node_schema = self.get_node_schema(label)?;
let id_columns = node_schema.node_id.id.columns();
let id_key = id_columns.first().copied().unwrap_or("id");
if !properties.contains_key(id_key) {
return Err(EmbeddedError::Validation(format!(
"Missing required node_id property '{}' for upsert",
id_key
)));
}
self.create_node(label, properties)
}
/// Upsert an edge (INSERT with ReplacingMergeTree deduplication).
pub fn upsert_edge(
&self,
edge_type: &str,
from_id: &str,
to_id: &str,
properties: HashMap<String, Value>,
) -> Result<(), EmbeddedError> {
self.create_edge(edge_type, from_id, to_id, properties)
}
/// Create multiple nodes in a single batch INSERT.
pub fn create_nodes(
&self,
label: &str,
batch: Vec<HashMap<String, Value>>,
) -> Result<Vec<String>, EmbeddedError> {
if batch.is_empty() {
return Ok(vec![]);
}
let node_schema = self.get_node_schema(label)?;
let id_columns = node_schema.node_id.id.columns();
let id_col_strs: Vec<&str> = id_columns.iter().copied().collect();
let id_key = id_columns.first().copied().unwrap_or("id");
let property_mappings =
write_helpers::extract_property_mappings(&node_schema.property_mappings);
for row_props in &batch {
write_helpers::validate_properties(row_props, &property_mappings, &id_col_strs)?;
}
let mut all_columns: Vec<String> = Vec::new();
let mut seen_columns = std::collections::HashSet::new();
for row_props in &batch {
if row_props.contains_key(id_key) && !seen_columns.contains(id_key) {
all_columns.push(id_key.to_string());
seen_columns.insert(id_key.to_string());
}
for cypher_name in row_props.keys() {
if cypher_name == id_key {
continue;
}
let col_name = property_mappings
.get(cypher_name.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| cypher_name.clone());
if !seen_columns.contains(&col_name) {
all_columns.push(col_name.clone());
seen_columns.insert(col_name);
}
}
}
let mut reverse_map: HashMap<String, String> = HashMap::new();
for (cypher_name, ch_col) in &property_mappings {
reverse_map.insert(ch_col.to_string(), cypher_name.to_string());
}
let mut all_values_rows = Vec::new();
let mut ids = Vec::new();
for row_props in &batch {
let node_id = if let Some(v) = row_props.get(id_key) {
match v {
Value::String(s) => s.clone(),
other => other
.to_sql_literal()
.map_err(EmbeddedError::Validation)?
.trim_matches('\'')
.to_string(),
}
} else {
uuid::Uuid::new_v4().to_string()
};
ids.push(node_id.clone());
let mut row_values = Vec::new();
for col in &all_columns {
if col == id_key {
row_values.push(
Value::String(node_id.clone())
.to_sql_literal()
.map_err(EmbeddedError::Validation)?,
);
} else {
let cypher_name = reverse_map.get(col).unwrap_or(col);
if let Some(val) = row_props.get(cypher_name) {
row_values.push(val.to_sql_literal().map_err(EmbeddedError::Validation)?);
} else {
row_values.push("DEFAULT".to_string());
}
}
}
all_values_rows.push(row_values);
}
let sql = write_helpers::build_insert_sql(
&node_schema.database,
&node_schema.table_name,
&all_columns,
&all_values_rows,
);
self.execute_sql(&sql)?;
Ok(ids)
}
/// Create multiple edges in a single batch INSERT.
pub fn create_edges(
&self,
edge_type: &str,
batch: Vec<(String, String, HashMap<String, Value>)>,
) -> Result<(), EmbeddedError> {
if batch.is_empty() {
return Ok(());
}
let rel_schema = self.get_rel_schema(edge_type)?;
let from_id_cols = rel_schema.from_id.columns();
let to_id_cols = rel_schema.to_id.columns();
let mut id_col_strs: Vec<&str> = Vec::new();
id_col_strs.extend(from_id_cols.iter().copied());
id_col_strs.extend(to_id_cols.iter().copied());
let from_col = from_id_cols.first().copied().unwrap_or("from_id");
let to_col = to_id_cols.first().copied().unwrap_or("to_id");
let property_mappings =
write_helpers::extract_property_mappings(&rel_schema.property_mappings);
for (_, _, row_props) in &batch {
write_helpers::validate_properties(row_props, &property_mappings, &id_col_strs)?;
}
let mut prop_columns: Vec<String> = Vec::new();
let mut seen_columns = std::collections::HashSet::new();
for (_, _, row_props) in &batch {
for cypher_name in row_props.keys() {
let col_name = property_mappings
.get(cypher_name.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| cypher_name.clone());
if !seen_columns.contains(&col_name) {
prop_columns.push(col_name.clone());
seen_columns.insert(col_name);
}
}
}
let mut columns = vec![from_col.to_string(), to_col.to_string()];
columns.extend(prop_columns.iter().cloned());
let mut reverse_map: HashMap<String, String> = HashMap::new();
for (cypher_name, ch_col) in &property_mappings {
reverse_map.insert(ch_col.to_string(), cypher_name.to_string());
}
let mut all_values_rows = Vec::new();
for (from_id, to_id, row_props) in &batch {
let mut row_values = vec![
Value::String(from_id.clone())
.to_sql_literal()
.map_err(EmbeddedError::Validation)?,
Value::String(to_id.clone())
.to_sql_literal()
.map_err(EmbeddedError::Validation)?,
];
for col in &prop_columns {
let cypher_name = reverse_map.get(col).unwrap_or(col);
if let Some(val) = row_props.get(cypher_name) {
row_values.push(val.to_sql_literal().map_err(EmbeddedError::Validation)?);
} else {
row_values.push("DEFAULT".to_string());
}
}
all_values_rows.push(row_values);
}
let sql = write_helpers::build_insert_sql(
&rel_schema.database,
&rel_schema.table_name,
&columns,
&all_values_rows,
);
self.execute_sql(&sql)
}
/// Delete nodes matching the given label and filter criteria.
///
/// Uses lightweight `DELETE FROM` — synchronous and low-overhead compared to
/// the old `ALTER TABLE DELETE` mutation path.
pub fn delete_nodes(
&self,
label: &str,
filters: HashMap<String, Value>,
) -> Result<(), EmbeddedError> {
let node_schema = self.get_node_schema(label)?;
write_helpers::check_writable(&node_schema.source, label)?;
let id_columns = node_schema.node_id.id.columns();
let id_col_strs: Vec<&str> = id_columns.iter().copied().collect();
let property_mappings =
write_helpers::extract_property_mappings(&node_schema.property_mappings);
write_helpers::validate_properties(&filters, &property_mappings, &id_col_strs)?;
let sql = write_helpers::build_delete_sql(
&node_schema.database,
&node_schema.table_name,
&filters,
&property_mappings,
&id_col_strs,
)?;
self.execute_sql(&sql)?;
Ok(())
}
/// Delete edges matching the given type and filter criteria.
pub fn delete_edges(
&self,
edge_type: &str,
filters: HashMap<String, Value>,
) -> Result<(), EmbeddedError> {
let rel_schema = self.get_rel_schema(edge_type)?;
write_helpers::check_writable(&rel_schema.source, edge_type)?;
let from_id_cols = rel_schema.from_id.columns();
let to_id_cols = rel_schema.to_id.columns();
let mut id_col_strs: Vec<&str> = Vec::new();
id_col_strs.extend(from_id_cols.iter().copied());
id_col_strs.extend(to_id_cols.iter().copied());
let property_mappings =
write_helpers::extract_property_mappings(&rel_schema.property_mappings);
let mut extended_mappings = property_mappings.clone();
let from_col = from_id_cols.first().copied().unwrap_or("from_id");
let to_col = to_id_cols.first().copied().unwrap_or("to_id");
extended_mappings.insert("from_id", from_col);
extended_mappings.insert("to_id", to_col);
write_helpers::validate_properties(&filters, &extended_mappings, &id_col_strs)?;
let sql = write_helpers::build_delete_sql(
&rel_schema.database,
&rel_schema.table_name,
&filters,
&extended_mappings,
&id_col_strs,
)?;
self.execute_sql(&sql)?;
Ok(())
}
/// Import nodes from inline newline-delimited JSON (JSONEachRow format).
pub fn import_json(&self, label: &str, json_lines: &str) -> Result<(), EmbeddedError> {
let node_schema = self.get_node_schema(label)?;
write_helpers::check_writable(&node_schema.source, label)?;
let id_columns = node_schema.node_id.id.columns();
let id_col_strs: Vec<&str> = id_columns.iter().copied().collect();
let property_mappings =
write_helpers::extract_property_mappings(&node_schema.property_mappings);
let (transformed_json, line_count) =
write_helpers::transform_json_keys(json_lines, &property_mappings, &id_col_strs)?;
if line_count == 0 {
return Ok(());
}
let sql = format!(
"INSERT INTO `{}`.`{}` FORMAT JSONEachRow\n{}",
node_schema.database, node_schema.table_name, transformed_json
);
self.execute_sql(&sql)?;
Ok(())
}
/// Import nodes from a JSON file (JSONEachRow format).
pub fn import_json_file(&self, label: &str, file_path: &str) -> Result<(), EmbeddedError> {
self.import_file_with_format(label, file_path, "JSONEachRow")
}
/// Import nodes from a CSV file (CSVWithNames format — first row is header).
pub fn import_csv_file(&self, label: &str, file_path: &str) -> Result<(), EmbeddedError> {
self.import_file_with_format(label, file_path, "CSVWithNames")
}
/// Import nodes from a Parquet file.
pub fn import_parquet_file(&self, label: &str, file_path: &str) -> Result<(), EmbeddedError> {
self.import_file_with_format(label, file_path, "Parquet")
}
/// Import nodes from a file, auto-detecting the format from the extension.
///
/// Supported extensions: `.parquet`/`.pq`, `.csv`, `.tsv`/`.tab`,
/// `.json`/`.ndjson`/`.jsonl`.
///
/// **Column mapping**: File columns should use Cypher property names (mapped
/// automatically via the schema's `property_mappings`) or ClickHouse column
/// names directly (used as-is when no mapping applies).
///
/// **Note**: This imports nodes only. For edge import from files, use
/// `execute_sql()` with a manual `INSERT INTO ... SELECT ... FROM file()`.
pub fn import_file(&self, label: &str, file_path: &str) -> Result<(), EmbeddedError> {
let format = write_helpers::import_format_from_extension(file_path).ok_or_else(|| {
EmbeddedError::Validation(format!(
"Cannot determine import format from '{}'. \
Use import_csv_file(), import_parquet_file(), or import_json_file() instead.",
file_path
))
})?;
self.import_file_with_format(label, file_path, format)
}
/// Internal: import nodes from a file with an explicit ClickHouse format name.
fn import_file_with_format(
&self,
label: &str,
file_path: &str,
format: &str,
) -> Result<(), EmbeddedError> {
if !std::path::Path::new(file_path).exists() {
return Err(EmbeddedError::Io(format!("File not found: {}", file_path)));
}
write_helpers::validate_file_path(file_path)?;
let node_schema = self.get_node_schema(label)?;
write_helpers::check_writable(&node_schema.source, label)?;
let id_columns = node_schema.node_id.id.columns();
let id_col_strs: Vec<&str> = id_columns.iter().copied().collect();
let property_mappings =
write_helpers::extract_property_mappings(&node_schema.property_mappings);
let sql = write_helpers::build_import_file_sql(
&node_schema.database,
&node_schema.table_name,
file_path,
format,
&property_mappings,
&id_col_strs,
);
self.execute_sql(&sql)?;
Ok(())
}
fn get_node_schema(
&self,
label: &str,
) -> Result<&clickgraph::graph_catalog::graph_schema::NodeSchema, EmbeddedError> {
self.schema.all_node_schemas().get(label).ok_or_else(|| {
EmbeddedError::Validation(format!(
"Unknown node label '{}'. Valid labels: {:?}",
label,
self.schema.all_node_schemas().keys().collect::<Vec<_>>()
))
})
}
fn get_rel_schema(
&self,
edge_type: &str,
) -> Result<&clickgraph::graph_catalog::graph_schema::RelationshipSchema, EmbeddedError> {
self.schema.get_rel_schema(edge_type).map_err(|_| {
EmbeddedError::Validation(format!(
"Unknown relationship type '{}'. Valid types: {:?}",
edge_type,
self.schema
.get_relationships_schemas()
.keys()
.collect::<Vec<_>>()
))
})
}
async fn export_async(
&self,
cypher: &str,
output_path: &str,
options: ExportOptions,
) -> Result<(), EmbeddedError> {
use clickgraph::clickhouse_query_generator::cypher_to_sql;
use clickgraph::server::query_context::{
set_current_schema, with_query_context, QueryContext,
};
let schema = Arc::clone(&self.schema);
let executor = Arc::clone(&self.executor);
let cypher = cypher.to_string();
let output_path = output_path.to_string();
with_query_context(QueryContext::new(None), async move {
set_current_schema(Arc::clone(&schema));
let select_sql = cypher_to_sql(&cypher, &schema, 100).map_err(EmbeddedError::Query)?;
let export_sql = build_export_sql(&select_sql, &output_path, &options)
.map_err(EmbeddedError::Query)?;
executor
.execute_text(&export_sql, "TabSeparated", None)
.await
.map_err(EmbeddedError::from)?;
Ok(())
})
.await
}
/// Handle `CALL apoc.export.{csv|json|parquet}.query(...)` in embedded mode.
///
/// Parses arguments, translates inner Cypher to SQL, builds export SQL, executes.
/// Returns a single-row result with export status.
async fn handle_export_call(&self, cypher: &str) -> Result<QueryResult, EmbeddedError> {
use clickgraph::clickhouse_query_generator::cypher_to_sql;
use clickgraph::open_cypher_parser;
use clickgraph::open_cypher_parser::ast::CypherStatement;
use clickgraph::procedures::apoc_export;
use clickgraph::server::query_context::{
set_current_schema, with_query_context, QueryContext,
};
let schema = Arc::clone(&self.schema);
let executor = Arc::clone(&self.executor);
let cypher = cypher.to_string();
with_query_context(QueryContext::new(None), async move {
set_current_schema(Arc::clone(&schema));
let (_, stmt) = open_cypher_parser::parse_cypher_statement(&cypher)
.map_err(|e| EmbeddedError::Query(format!("Parse error: {}", e)))?;
let (proc_name, expressions): (String, Vec<_>) = match &stmt {
CypherStatement::ProcedureCall(pc) => {
(pc.procedure_name.to_string(), pc.arguments.iter().collect())
}
CypherStatement::Query { query, .. } => {
let cc = query
.call_clause
.as_ref()
.ok_or_else(|| EmbeddedError::Query("No CALL clause found".to_string()))?;
(
cc.procedure_name.to_string(),
cc.arguments.iter().map(|a| &a.value).collect(),
)
}
CypherStatement::CopyTo(_) => {
return Err(EmbeddedError::Query(
"COPY TO should be handled before reaching APOC export path".to_string(),
));
}
};
let ch_format = apoc_export::format_from_procedure_name(&proc_name)
.map_err(EmbeddedError::Query)?;
let args =
apoc_export::parse_export_call(&expressions).map_err(EmbeddedError::Query)?;
let inner_sql =
cypher_to_sql(&args.cypher_query, &schema, 100).map_err(EmbeddedError::Query)?;
let export_sql = apoc_export::build_export_sql(
&inner_sql,
&args.destination,
ch_format,
&args.config,
)
.map_err(EmbeddedError::Query)?;
executor
.execute_text(&export_sql, "TabSeparated", None)
.await
.map_err(EmbeddedError::from)?;
Ok(QueryResult::new(
vec![
"file".to_string(),
"format".to_string(),
"source".to_string(),
],
vec![vec![
Value::String(args.destination),
Value::String(ch_format.to_string()),
Value::String(args.cypher_query),
]],
))
})
.await
}
/// Handle `COPY (<cypher>) TO '<destination>' [FORMAT <fmt>] [(options)]` in embedded mode.
async fn handle_copy_to(
&self,
inner_cypher: &str,
destination: &str,
format: Option<&str>,
options: &[(&str, clickgraph::open_cypher_parser::ast::Expression<'_>)],
) -> Result<QueryResult, EmbeddedError> {
use clickgraph::clickhouse_query_generator::cypher_to_sql;
use clickgraph::procedures::apoc_export;
use clickgraph::server::query_context::{
set_current_schema, with_query_context, QueryContext,
};
let ch_format = if let Some(fmt) = format {
apoc_export::format_from_copy_format(fmt).map_err(EmbeddedError::Query)?
} else {
apoc_export::format_from_extension(destination).ok_or_else(|| {
EmbeddedError::Query(format!(
"Cannot determine format from '{}'. Use FORMAT clause.",
destination
))
})?
};
let config = apoc_export::ExportConfig::from_copy_options(options);
let schema = Arc::clone(&self.schema);
let executor = Arc::clone(&self.executor);
let inner_cypher = inner_cypher.to_string();
let destination = destination.to_string();
with_query_context(QueryContext::new(None), async move {
set_current_schema(Arc::clone(&schema));
let inner_sql =
cypher_to_sql(&inner_cypher, &schema, 100).map_err(EmbeddedError::Query)?;
let export_sql =
apoc_export::build_export_sql(&inner_sql, &destination, ch_format, &config)
.map_err(EmbeddedError::Query)?;
executor
.execute_text(&export_sql, "TabSeparated", None)
.await
.map_err(EmbeddedError::from)?;
Ok(QueryResult::new(
vec![
"file".to_string(),
"format".to_string(),
"source".to_string(),
],
vec![vec![
Value::String(destination),
Value::String(ch_format.to_string()),
Value::String(inner_cypher),
]],
))
})
.await
}
/// Handle `CALL db.index.vector.queryNodes(...)` in embedded mode.
async fn handle_vector_search_call(&self, cypher: &str) -> Result<QueryResult, EmbeddedError> {
use clickgraph::open_cypher_parser;
use clickgraph::open_cypher_parser::ast::CypherStatement;
use clickgraph::procedures::vector_search;
let schema = Arc::clone(&self.schema);
let executor = Arc::clone(&self.executor);
let cypher = cypher.to_string();
let (_, stmt) = open_cypher_parser::parse_cypher_statement(&cypher)
.map_err(|e| EmbeddedError::Query(format!("Parse error: {}", e)))?;
let expressions: Vec<_> = match &stmt {
CypherStatement::ProcedureCall(pc) => pc.arguments.iter().collect(),
CypherStatement::Query { query, .. } => {
let cc = query
.call_clause
.as_ref()
.ok_or_else(|| EmbeddedError::Query("No CALL clause found".to_string()))?;
cc.arguments.iter().map(|a| &a.value).collect()
}
CypherStatement::CopyTo(_) => {
return Err(EmbeddedError::Query(
"Unexpected COPY TO in vector search context".to_string(),
));
}
};
let search_args =
vector_search::parse_vector_search_args(&expressions).map_err(EmbeddedError::Query)?;
let index_config = vector_search::resolve_vector_index(&schema, &search_args.index_name)
.map_err(EmbeddedError::Query)?;
let search_sql = vector_search::build_vector_search_sql(&search_args, index_config)
.map_err(EmbeddedError::Query)?;
let json_rows = executor
.execute_json(&search_sql, None)
.await
.map_err(EmbeddedError::from)?;
let columns: Vec<String> = if let Some(first_row) = json_rows.first() {
if let serde_json::Value::Object(map) = first_row {
map.keys().cloned().collect()
} else {
vec!["result".to_string()]
}
} else {
return Ok(QueryResult::new(
vec!["node".to_string(), "score".to_string()],