coreason-engine 0.1.0

Coreason execution engine for deterministic computation
Documentation
// Copyright (c) 2026 CoReason, Inc
//
// This software is proprietary and dual-licensed
// Licensed under the Prosperity Public License 3.0 (the "License")
// A copy of the license is available at <https://prosperitylicense.com/versions/3.0.0>
// For details, see the LICENSE file
// Commercial use beyond a 30-day trial requires a separate license
//
// Source Code: <https://github.com/CoReason-AI/coreason-runtime>

use duckdb::Connection;
use serde_json::Value;

/// Zero-Copy Federated Query Executor using DuckDB.
pub struct FederatedQueryExecutor;

impl FederatedQueryExecutor {
    /// Executes a SQL query against a list of presigned Parquet URLs.
    /// The Parquet files are registered as a temporary view named `shared_table`.
    pub fn execute(query: &str, parquet_urls: &[String]) -> Result<Value, String> {
        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;

        // Attempt to load HTTP and Parquet extensions for remote/http querying
        let _ = conn.execute_batch("INSTALL parquet; LOAD parquet;");
        let _ = conn.execute_batch("INSTALL httpfs; LOAD httpfs;");

        // Register the Parquet files as temporary view 'shared_table' if URLs are provided
        if !parquet_urls.is_empty() {
            let urls_str = parquet_urls
                .iter()
                .map(|url| format!("'{}'", url))
                .collect::<Vec<String>>()
                .join(", ");
            let create_view_sql = format!(
                "CREATE TEMPORARY VIEW shared_table AS SELECT * FROM read_parquet([{}]);",
                urls_str
            );
            conn.execute_batch(&create_view_sql)
                .map_err(|e| e.to_string())?;
        }

        // Prepare and execute the user query
        let mut stmt = conn.prepare(query).map_err(|e| e.to_string())?;
        let mut rows = stmt.query([]).map_err(|e| e.to_string())?;

        let col_count = rows.as_ref().map(|s| s.column_count()).unwrap_or(0);
        let col_names: Vec<String> = (0..col_count)
            .map(|i| {
                rows.as_ref()
                    .and_then(|s| s.column_name(i).ok())
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| format!("col_{}", i))
            })
            .collect();

        let mut results = Vec::new();

        while let Some(row) = rows.next().map_err(|e| e.to_string())? {
            let mut row_map = serde_json::Map::new();
            for (i, name) in col_names.iter().enumerate() {
                // strict check of DuckDB types by trial conversion
                let val: Value = if let Ok(s) = row.get::<usize, String>(i) {
                    Value::String(s)
                } else if let Ok(n) = row.get::<usize, i64>(i) {
                    Value::Number(serde_json::Number::from(n))
                } else if let Ok(f) = row.get::<usize, f64>(i) {
                    if let Some(num) = serde_json::Number::from_f64(f) {
                        Value::Number(num)
                    } else {
                        Value::Null
                    }
                } else if let Ok(b) = row.get::<usize, bool>(i) {
                    Value::Bool(b)
                } else {
                    Value::Null
                };
                row_map.insert(name.clone(), val);
            }
            results.push(Value::Object(row_map));
        }

        Ok(Value::Array(results))
    }
}