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
// 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))
}
}