Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-gar/src/table.rs

use std::sync::{Arc, OnceLock};

use arrow_array::{ArrayRef, RecordBatch, RecordBatchOptions, UInt32Array};
use arrow_buffer::ScalarBuffer;
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use async_trait::async_trait;
use datafusion::catalog::memory::MemorySourceConfig;
use datafusion::catalog::{SchemaProvider, Session, TableProvider};
use datafusion::datasource::TableType;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::context::SessionContext;
use datafusion::logical_expr::Expr;
use datafusion::physical_plan::ExecutionPlan;

use crate::graph::{EdgeType, GarGraph};

/// A vertex table or an edge table.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TableKind {
    /// One row per vertex.
    Vertex,
    /// One row per edge, by source.
    Edge,
}

/// Where a column's values come from.
#[derive(Debug)]
enum Source {
    /// A mapped column: the array is the file.
    Mapped(ArrayRef),
    /// The row number (a vertex id), made on the first scan that asks for it.
    RowId(usize, OnceLock<ArrayRef>),
    /// Each edge's source, expanded from the by-source offsets on the first scan that
    /// asks for it.
    EdgeStart(ScalarBuffer<u64>, OnceLock<ArrayRef>),
}

impl Source {
    fn array(&self) -> ArrayRef {
        match self {
            Source::Mapped(a) => a.clone(),
            Source::RowId(n, cell) => cell
                .get_or_init(|| Arc::new(UInt32Array::from_iter_values(0..*n as u32)))
                .clone(),
            Source::EdgeStart(off, cell) => cell
                .get_or_init(|| {
                    let mut src = Vec::with_capacity(*off.last().unwrap_or(&0) as usize);
                    for (i, w) in off.windows(2).enumerate() {
                        src.extend(std::iter::repeat_n(i as u32, (w[1] - w[0]) as usize));
                    }
                    Arc::new(UInt32Array::from(src))
                })
                .clone(),
        }
    }
}

/// One vertex or edge type as a DataFusion table: mapped columns handed to DataFusion as
/// they are, split into slices (no copy) over the session's target partitions.
#[derive(Debug)]
pub struct GarTable {
    name: String,
    kind: TableKind,
    rows: usize,
    schema: SchemaRef,
    sources: Vec<Source>,
}

fn field(name: &str, a: &ArrayRef) -> Field {
    Field::new(name, a.data_type().clone(), a.null_count() > 0)
}

impl GarTable {
    /// The vertex type `name`: `id`, then its stored columns.
    pub fn vertex(g: &GarGraph, name: &str) -> Result<Self> {
        let rows = g.vertex_count(name)? as usize;
        let mut fields = vec![Field::new("id", DataType::UInt32, false)];
        let mut sources = vec![Source::RowId(rows, OnceLock::new())];
        for col in g.vertex_columns(name)? {
            if col == "id" {
                return Err(DataFusionError::Plan(format!(
                    "vertex type {name}: a stored column named `id` hides the row id"
                )));
            }
            let a = g.vertex_column(name, &col)?;
            fields.push(field(&col, &a));
            sources.push(Source::Mapped(a));
        }
        Ok(GarTable {
            name: name.into(),
            kind: TableKind::Vertex,
            rows,
            schema: Arc::new(Schema::new(fields)),
            sources,
        })
    }

    /// The edge type `t`: `src`, `dst`, then its properties.
    pub fn edge(g: &GarGraph, t: &EdgeType) -> Result<Self> {
        let adj = g.adjacency(t)?;
        let rows = adj.out_neighbours.len();
        let dst: ArrayRef = Arc::new(UInt32Array::new(adj.out_neighbours.clone(), None));
        let mut fields = vec![
            Field::new("src", DataType::UInt32, false),
            Field::new("dst", DataType::UInt32, false),
        ];
        let mut sources = vec![
            Source::EdgeStart(adj.out_offsets.clone(), OnceLock::new()),
            Source::Mapped(dst),
        ];
        for p in g.edge_properties(t)? {
            if p == "src" || p == "dst" {
                return Err(DataFusionError::Plan(format!(
                    "edge type {}: a property named `{p}` hides an edge end",
                    t.table_name()
                )));
            }
            let a = g.edge_property(t, &p)?;
            fields.push(field(&p, &a));
            sources.push(Source::Mapped(a));
        }
        Ok(GarTable {
            name: t.table_name(),
            kind: TableKind::Edge,
            rows,
            schema: Arc::new(Schema::new(fields)),
            sources,
        })
    }

    /// The table name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Vertex or edge.
    pub fn kind(&self) -> TableKind {
        self.kind
    }

    /// The number of rows.
    pub fn rows(&self) -> usize {
        self.rows
    }

    /// The columns at `projection` (all when `None`) as one batch: mapped columns as they
    /// are, made columns built once and kept.
    pub fn batch(&self, projection: Option<&[usize]>) -> Result<RecordBatch> {
        let all: Vec<usize> = (0..self.sources.len()).collect();
        let idx = projection.unwrap_or(&all[..]);
        let schema = Arc::new(self.schema.project(idx)?);
        let columns: Vec<ArrayRef> = idx.iter().map(|&i| self.sources[i].array()).collect();
        let opts = RecordBatchOptions::new().with_row_count(Some(self.rows));
        Ok(RecordBatch::try_new_with_options(schema, columns, &opts)?)
    }

    /// One column by name.
    pub fn column(&self, name: &str) -> Result<ArrayRef> {
        let i = self.schema.index_of(name)?;
        Ok(self.sources[i].array())
    }
}

#[async_trait]
impl TableProvider for GarTable {
    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }

    fn table_type(&self) -> TableType {
        TableType::Base
    }

    async fn scan(
        &self,
        state: &dyn Session,
        projection: Option<&[usize]>,
        _filters: &[Expr],
        _limit: Option<usize>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        let batch = self.batch(projection)?;
        let parts = state.config().target_partitions().max(1);
        let size = self.rows.div_ceil(parts).max(1);
        let partitions: Vec<Vec<RecordBatch>> = (0..self.rows)
            .step_by(size)
            .map(|start| vec![batch.slice(start, size.min(self.rows - start))])
            .collect();
        let partitions = if partitions.is_empty() {
            vec![vec![batch.clone()]]
        } else {
            partitions
        };
        let exec = MemorySourceConfig::try_new_exec(&partitions, batch.schema(), None)?;
        Ok(exec)
    }
}

/// An X.gar directory as a DataFusion schema: one table per vertex type and per edge type.
#[derive(Debug)]
pub struct GarSchema {
    graph: GarGraph,
}

impl GarSchema {
    /// The schema of `graph`.
    pub fn new(graph: GarGraph) -> Self {
        GarSchema { graph }
    }

    /// The graph.
    pub fn graph(&self) -> &GarGraph {
        &self.graph
    }

    /// Serve `graph` in `ctx`'s default catalog as schema `name` (tables are then
    /// `name.<table>`).
    pub fn register(graph: GarGraph, ctx: &SessionContext, name: &str) -> Result<()> {
        let catalog_name = ctx
            .state()
            .config()
            .options()
            .catalog
            .default_catalog
            .clone();
        let catalog = ctx
            .catalog(&catalog_name)
            .ok_or_else(|| DataFusionError::Plan(format!("no catalog named {catalog_name}")))?;
        catalog.register_schema(name, Arc::new(GarSchema::new(graph)))?;
        Ok(())
    }
}

#[async_trait]
impl SchemaProvider for GarSchema {
    fn table_names(&self) -> Vec<String> {
        self.graph.table_names()
    }

    async fn table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
        Ok(self.graph.table(name)?.map(|t| t as Arc<dyn TableProvider>))
    }

    fn table_exist(&self, name: &str) -> bool {
        self.graph.kind(name).is_some()
    }
}