Skip to main content

coreason_engine/
federated_query.rs

1// Copyright (c) 2026 CoReason, Inc
2//
3// This software is proprietary and dual-licensed
4// Licensed under the Prosperity Public License 3.0 (the "License")
5// A copy of the license is available at <https://prosperitylicense.com/versions/3.0.0>
6// For details, see the LICENSE file
7// Commercial use beyond a 30-day trial requires a separate license
8//
9// Source Code: <https://github.com/CoReason-AI/coreason-runtime>
10
11use duckdb::Connection;
12use serde_json::Value;
13
14/// Zero-Copy Federated Query Executor using DuckDB.
15pub struct FederatedQueryExecutor;
16
17impl FederatedQueryExecutor {
18    /// Executes a SQL query against a list of presigned Parquet URLs.
19    /// The Parquet files are registered as a temporary view named `shared_table`.
20    pub fn execute(query: &str, parquet_urls: &[String]) -> Result<Value, String> {
21        let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
22
23        // Attempt to load HTTP and Parquet extensions for remote/http querying
24        let _ = conn.execute_batch("INSTALL parquet; LOAD parquet;");
25        let _ = conn.execute_batch("INSTALL httpfs; LOAD httpfs;");
26
27        // Register the Parquet files as temporary view 'shared_table' if URLs are provided
28        if !parquet_urls.is_empty() {
29            let urls_str = parquet_urls
30                .iter()
31                .map(|url| format!("'{}'", url))
32                .collect::<Vec<String>>()
33                .join(", ");
34            let create_view_sql = format!(
35                "CREATE TEMPORARY VIEW shared_table AS SELECT * FROM read_parquet([{}]);",
36                urls_str
37            );
38            conn.execute_batch(&create_view_sql)
39                .map_err(|e| e.to_string())?;
40        }
41
42        // Prepare and execute the user query
43        let mut stmt = conn.prepare(query).map_err(|e| e.to_string())?;
44        let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
45
46        let col_count = rows.as_ref().map(|s| s.column_count()).unwrap_or(0);
47        let col_names: Vec<String> = (0..col_count)
48            .map(|i| {
49                rows.as_ref()
50                    .and_then(|s| s.column_name(i).ok())
51                    .map(|s| s.to_string())
52                    .unwrap_or_else(|| format!("col_{}", i))
53            })
54            .collect();
55
56        let mut results = Vec::new();
57
58        while let Some(row) = rows.next().map_err(|e| e.to_string())? {
59            let mut row_map = serde_json::Map::new();
60            for (i, name) in col_names.iter().enumerate() {
61                // strict check of DuckDB types by trial conversion
62                let val: Value = if let Ok(s) = row.get::<usize, String>(i) {
63                    Value::String(s)
64                } else if let Ok(n) = row.get::<usize, i64>(i) {
65                    Value::Number(serde_json::Number::from(n))
66                } else if let Ok(f) = row.get::<usize, f64>(i) {
67                    if let Some(num) = serde_json::Number::from_f64(f) {
68                        Value::Number(num)
69                    } else {
70                        Value::Null
71                    }
72                } else if let Ok(b) = row.get::<usize, bool>(i) {
73                    Value::Bool(b)
74                } else {
75                    Value::Null
76                };
77                row_map.insert(name.clone(), val);
78            }
79            results.push(Value::Object(row_map));
80        }
81
82        Ok(Value::Array(results))
83    }
84}