uni-query 1.1.0

OpenCypher query parser, planner, and vectorized executor for Uni
Documentation
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Dragonscale Team

//! External ID lookup execution plan for DataFusion.
//!
//! This module provides [`GraphExtIdLookupExec`], a DataFusion [`ExecutionPlan`] that
//! looks up a single vertex by its external ID (`ext_id`) in the main vertices table.
//!
//! # Column Naming Convention
//!
//! The output schema includes:
//! - `_vid` - vertex ID
//! - `ext_id` - external ID
//! - `_label` - vertex label name
//! - `{variable}.{property}` - materialized properties

use crate::query::df_graph::GraphExecutionContext;
use crate::query::df_graph::common::{arrow_err, compute_plan_properties};
use arrow_array::builder::StringBuilder;
use arrow_array::{ArrayRef, RecordBatch, UInt64Array};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use datafusion::common::Result as DFResult;
use datafusion::execution::{RecordBatchStream, SendableRecordBatchStream, TaskContext};
use datafusion::physical_plan::metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet};
use datafusion::physical_plan::{DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties};
use futures::Stream;
use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use uni_common::core::id::Vid;

/// Execution plan for looking up a vertex by external ID.
///
/// Queries the main vertices table to find a vertex matching the given `ext_id`,
/// then materializes the specified properties.
pub struct GraphExtIdLookupExec {
    /// Graph execution context for storage access.
    graph_ctx: Arc<GraphExecutionContext>,

    /// Variable name for column prefixing.
    variable: String,

    /// External ID to look up.
    ext_id: String,

    /// Properties to materialize.
    projected_properties: Vec<String>,

    /// Whether the lookup is optional (OPTIONAL MATCH).
    optional: bool,

    /// Output schema.
    schema: SchemaRef,

    /// Plan properties (cached).
    properties: PlanProperties,

    /// Execution metrics.
    metrics: ExecutionPlanMetricsSet,
}

impl fmt::Debug for GraphExtIdLookupExec {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GraphExtIdLookupExec")
            .field("variable", &self.variable)
            .field("ext_id", &self.ext_id)
            .field("projected_properties", &self.projected_properties)
            .field("optional", &self.optional)
            .finish()
    }
}

impl GraphExtIdLookupExec {
    /// Create a new external ID lookup executor.
    pub fn new(
        graph_ctx: Arc<GraphExecutionContext>,
        variable: impl Into<String>,
        ext_id: impl Into<String>,
        projected_properties: Vec<String>,
        optional: bool,
    ) -> Self {
        let variable = variable.into();
        let ext_id = ext_id.into();

        // Build output schema
        let schema = Self::build_schema(&variable, &projected_properties);
        let properties = compute_plan_properties(schema.clone());

        Self {
            graph_ctx,
            variable,
            ext_id,
            projected_properties,
            optional,
            schema,
            properties,
            metrics: ExecutionPlanMetricsSet::new(),
        }
    }

    /// Build the output schema.
    fn build_schema(variable: &str, properties: &[String]) -> SchemaRef {
        let mut fields = vec![
            Field::new(format!("{}._vid", variable), DataType::UInt64, false),
            Field::new(format!("{}.ext_id", variable), DataType::Utf8, false),
            Field::new(format!("{}._label", variable), DataType::Utf8, false),
        ];

        // Add property columns with variable prefix
        for prop in properties {
            let col_name = format!("{}.{}", variable, prop);
            fields.push(Field::new(&col_name, DataType::Utf8, true));
        }

        Arc::new(Schema::new(fields))
    }
}

impl DisplayAs for GraphExtIdLookupExec {
    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "GraphExtIdLookupExec: ext_id={}, variable={}, optional={}",
            self.ext_id, self.variable, self.optional
        )
    }
}

impl ExecutionPlan for GraphExtIdLookupExec {
    fn name(&self) -> &str {
        "GraphExtIdLookupExec"
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }

    fn properties(&self) -> &PlanProperties {
        &self.properties
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![]
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> DFResult<Arc<dyn ExecutionPlan>> {
        if !children.is_empty() {
            return Err(datafusion::error::DataFusionError::Internal(
                "GraphExtIdLookupExec has no children".to_string(),
            ));
        }
        Ok(self)
    }

    fn execute(
        &self,
        partition: usize,
        _context: Arc<TaskContext>,
    ) -> DFResult<SendableRecordBatchStream> {
        let metrics = BaselineMetrics::new(&self.metrics, partition);

        Ok(Box::pin(ExtIdLookupStream::new(
            self.graph_ctx.clone(),
            self.variable.clone(),
            self.ext_id.clone(),
            self.projected_properties.clone(),
            self.optional,
            self.schema.clone(),
            metrics,
        )))
    }

    fn metrics(&self) -> Option<MetricsSet> {
        Some(self.metrics.clone_inner())
    }
}

/// State machine for ext_id lookup stream.
enum ExtIdLookupState {
    /// Initial state, ready to start lookup.
    Init,
    /// Executing the async lookup.
    Executing(Pin<Box<dyn std::future::Future<Output = DFResult<Option<RecordBatch>>> + Send>>),
    /// Stream is done.
    Done,
}

/// Stream that looks up a vertex by external ID.
struct ExtIdLookupStream {
    /// Graph execution context.
    graph_ctx: Arc<GraphExecutionContext>,

    /// Variable name for column prefixing.
    variable: String,

    /// External ID to look up.
    ext_id: String,

    /// Properties to materialize.
    properties: Vec<String>,

    /// Whether the lookup is optional.
    optional: bool,

    /// Output schema.
    schema: SchemaRef,

    /// Stream state.
    state: ExtIdLookupState,

    /// Metrics.
    metrics: BaselineMetrics,
}

impl ExtIdLookupStream {
    fn new(
        graph_ctx: Arc<GraphExecutionContext>,
        variable: String,
        ext_id: String,
        properties: Vec<String>,
        optional: bool,
        schema: SchemaRef,
        metrics: BaselineMetrics,
    ) -> Self {
        Self {
            graph_ctx,
            variable,
            ext_id,
            properties,
            optional,
            schema,
            state: ExtIdLookupState::Init,
            metrics,
        }
    }
}

impl Stream for ExtIdLookupStream {
    type Item = DFResult<RecordBatch>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            let state = std::mem::replace(&mut self.state, ExtIdLookupState::Done);

            match state {
                ExtIdLookupState::Init => {
                    // Clone data for the async block
                    let graph_ctx = self.graph_ctx.clone();
                    let variable = self.variable.clone();
                    let ext_id = self.ext_id.clone();
                    let properties = self.properties.clone();
                    let optional = self.optional;
                    let schema = self.schema.clone();

                    let fut = async move {
                        // Check timeout
                        graph_ctx.check_timeout().map_err(|e| {
                            datafusion::error::DataFusionError::Execution(e.to_string())
                        })?;

                        execute_lookup(
                            &graph_ctx,
                            &variable,
                            &ext_id,
                            &properties,
                            optional,
                            &schema,
                        )
                        .await
                    };

                    self.state = ExtIdLookupState::Executing(Box::pin(fut));
                    // Continue loop to poll the future
                }
                ExtIdLookupState::Executing(mut fut) => match fut.as_mut().poll(cx) {
                    Poll::Ready(Ok(batch)) => {
                        self.state = ExtIdLookupState::Done;
                        self.metrics
                            .record_output(batch.as_ref().map(|b| b.num_rows()).unwrap_or(0));
                        return Poll::Ready(batch.map(Ok));
                    }
                    Poll::Ready(Err(e)) => {
                        self.state = ExtIdLookupState::Done;
                        return Poll::Ready(Some(Err(e)));
                    }
                    Poll::Pending => {
                        self.state = ExtIdLookupState::Executing(fut);
                        return Poll::Pending;
                    }
                },
                ExtIdLookupState::Done => {
                    return Poll::Ready(None);
                }
            }
        }
    }
}

impl RecordBatchStream for ExtIdLookupStream {
    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }
}

/// Execute the ext_id lookup and materialize properties.
async fn execute_lookup(
    graph_ctx: &GraphExecutionContext,
    variable: &str,
    ext_id: &str,
    properties: &[String],
    optional: bool,
    schema: &SchemaRef,
) -> DFResult<Option<RecordBatch>> {
    let storage = graph_ctx.storage();

    // Look up vertex by ext_id with snapshot isolation
    let found_vid = storage
        .find_vertex_by_ext_id(ext_id)
        .await
        .map_err(|e| datafusion::error::DataFusionError::Execution(e.to_string()))?;

    let Some(vid) = found_vid else {
        // No match found
        if optional {
            return Ok(Some(build_null_row(variable, properties, schema)?));
        }
        return Ok(Some(RecordBatch::new_empty(schema.clone())));
    };

    // Load properties
    let property_manager = graph_ctx.property_manager();
    let query_ctx = graph_ctx.query_context();

    let props_opt = property_manager
        .get_all_vertex_props_with_ctx(vid, Some(&query_ctx))
        .await
        .map_err(|e| datafusion::error::DataFusionError::Execution(e.to_string()))?;

    let Some(props) = props_opt else {
        // Vertex was deleted
        if optional {
            return Ok(Some(build_null_row(variable, properties, schema)?));
        }
        return Ok(Some(RecordBatch::new_empty(schema.clone())));
    };

    // Get labels for the vertex
    let labels = storage
        .find_vertex_labels_by_vid(vid)
        .await
        .map_err(|e| datafusion::error::DataFusionError::Execution(e.to_string()))?
        .unwrap_or_default();

    let label_name = labels
        .first()
        .cloned()
        .unwrap_or_else(|| "Unknown".to_string());

    // Build the result batch
    let batch = build_result_row(
        vid,
        ext_id,
        &label_name,
        &props,
        variable,
        properties,
        schema,
    )?;
    Ok(Some(batch))
}

/// Build a null row for optional matches with no result.
fn build_null_row(
    _variable: &str,
    _properties: &[String],
    schema: &SchemaRef,
) -> DFResult<RecordBatch> {
    // For optional match with no result, we return a row with nulls
    let mut columns: Vec<ArrayRef> = Vec::with_capacity(schema.fields().len());

    // All columns are null for the optional case
    for field in schema.fields().iter() {
        match field.data_type() {
            DataType::UInt64 => {
                columns.push(Arc::new(arrow_array::UInt64Array::from(vec![
                    None as Option<u64>,
                ])));
            }
            DataType::Utf8 => {
                let mut builder = StringBuilder::new();
                builder.append_null();
                columns.push(Arc::new(builder.finish()));
            }
            _ => {
                let mut builder = StringBuilder::new();
                builder.append_null();
                columns.push(Arc::new(builder.finish()));
            }
        }
    }

    RecordBatch::try_new(schema.clone(), columns).map_err(arrow_err)
}

/// Build a result row with the found vertex data.
fn build_result_row(
    vid: Vid,
    ext_id: &str,
    label: &str,
    props: &HashMap<String, uni_common::Value>,
    _variable: &str,
    properties: &[String],
    schema: &SchemaRef,
) -> DFResult<RecordBatch> {
    let mut columns: Vec<ArrayRef> = Vec::with_capacity(schema.fields().len());

    // _vid column
    columns.push(Arc::new(UInt64Array::from(vec![vid.as_u64()])));

    // ext_id column
    let mut ext_id_builder = StringBuilder::new();
    ext_id_builder.append_value(ext_id);
    columns.push(Arc::new(ext_id_builder.finish()));

    // _label column
    let mut label_builder = StringBuilder::new();
    label_builder.append_value(label);
    columns.push(Arc::new(label_builder.finish()));

    // Property columns
    for prop in properties {
        let mut builder = StringBuilder::new();
        if let Some(val) = props.get(prop) {
            match val {
                uni_common::Value::String(s) => builder.append_value(s),
                uni_common::Value::Null => builder.append_null(),
                other => builder.append_value(other.to_string()),
            }
        } else {
            builder.append_null();
        }
        columns.push(Arc::new(builder.finish()));
    }

    RecordBatch::try_new(schema.clone(), columns).map_err(arrow_err)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_schema() {
        let schema =
            GraphExtIdLookupExec::build_schema("n", &["name".to_string(), "age".to_string()]);

        assert_eq!(schema.fields().len(), 5);
        assert_eq!(schema.field(0).name(), "n._vid");
        assert_eq!(schema.field(1).name(), "n.ext_id");
        assert_eq!(schema.field(2).name(), "n._label");
        assert_eq!(schema.field(3).name(), "n.name");
        assert_eq!(schema.field(4).name(), "n.age");
    }
}