Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion sqlctx-rs/include/sqlctx.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,51 @@ typedef struct SqlctxCompiler SqlctxCompiler;
SqlctxCompiler *sqlctx_compiler_create(const char *snapshot, char **error);
SqlctxRewriteResult sqlctx_compiler_rewrite(const SqlctxCompiler *compiler, const char *sql);
SqlctxRewriteResult sqlctx_compiler_explain(const SqlctxCompiler *compiler, const char *sql);
/* Warnings are newline-separated compiler diagnostics, never emitted at bind time.
* Free all three owned strings with sqlctx_free_diagnostics_result. */
typedef struct {
char *sql;
char *warnings;
char *error;
} SqlctxDiagnosticsResult;
SqlctxDiagnosticsResult sqlctx_snapshot_rewrite_with_warnings(const char *snapshot, const char *sql);
SqlctxDiagnosticsResult sqlctx_compiler_rewrite_with_warnings(const SqlctxCompiler *compiler, const char *sql);
void sqlctx_free_diagnostics_result(SqlctxDiagnosticsResult result);
void sqlctx_compiler_free(SqlctxCompiler *compiler);
/* Returns a JSON compiler report in result.sql; free with sqlctx_free_result. */
SqlctxRewriteResult sqlctx_snapshot_explain(const char *snapshot, const char *sql);

/* Host routing can compile multiple catalog-scoped parts of one query. Retain
* their real compiler reports while returning SQL for the host AST lowering.
* Free all owned strings with sqlctx_free_plan_explanation. */
typedef struct {
char *sql;
char *report;
char *error;
} SqlctxPlanExplanation;
SqlctxPlanExplanation sqlctx_snapshot_plan_explanation(const char *snapshot, const char *sql);
void sqlctx_free_plan_explanation(SqlctxPlanExplanation result);

/* Explicit capability opt-in for DuckDB hosts implementing the native measure
* window, aggregate-decoration and joined-visibility AST lowerers. These calls
* may return internal __sqlctx_* payloads, not standalone executable SQL.
* Original entrypoints reject unsupported native operations. A native compiler
* retains this capability for rewrite, diagnostics and explanation calls.
* Ownership and error handling are identical to the original entrypoints. */
SqlctxCompiler *sqlctx_compiler_create_native(const char *snapshot, char **error);
SqlctxRewriteResult sqlctx_snapshot_rewrite_native(const char *snapshot, const char *sql);
SqlctxDiagnosticsResult sqlctx_snapshot_rewrite_with_warnings_native(const char *snapshot, const char *sql);
SqlctxPlanExplanation sqlctx_snapshot_plan_explanation_native(const char *snapshot, const char *sql);

/* reports is a JSON array of the reports returned above. result.sql contains
* one JSON report with final host SQL and the collected compiler observations. */
SqlctxRewriteResult sqlctx_combine_plan_explanations(const char *sql, const char *reports);

typedef struct {
char *name;
char **fields;
size_t field_count;
bool is_measure_view;
} SqlctxModelInfo;

typedef struct {
Expand Down Expand Up @@ -236,7 +273,8 @@ SqlctxRewriteResult sqlctx_rewrite_for_context(const char *context, const char *
/*
* Stateless, policy-aware SemanticInput v1 entrypoints. All arguments must be
* non-NULL, NUL-terminated UTF-8 strings. Context is query context JSON (use
* "{}" for no caller attributes). Neither function changes loaded YAML models.
* "{}" for no caller attributes). A missing input_dialect defaults to "duckdb".
* Neither function changes loaded YAML models.
* Free every returned result with sqlctx_free_result(). On success sql is
* non-NULL and was_rewritten is true; on failure error is non-NULL.
*/
Expand Down
65 changes: 45 additions & 20 deletions sqlctx-rs/src/config/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub fn load_from_string_with_metadata(content: &str) -> Result<LoadedGraphMetada

/// Parse caller-supplied YAML literally, without access to process environment variables.
pub fn load_literal_yaml_with_metadata(content: &str) -> Result<LoadedGraphMetadata> {
let format = detect_format(content);
let format = detect_format(content)?;
let parsed = parse_literal_content_with_extends(content, format)?;
let ParsedConfig {
models,
Expand Down Expand Up @@ -513,7 +513,9 @@ fn load_sources_with_metadata(

match ext.as_deref() {
Some("yml") | Some("yaml") => {
let format = detect_format(&content);
let format = detect_format(&content).map_err(|error| {
SqlctxError::Validation(format!("Cannot load {path}: {error}"))
})?;
let parsed = if expand_environment {
parse_content(&content, format)?
} else {
Expand Down Expand Up @@ -682,21 +684,34 @@ fn deep_merge_json(target: &mut serde_json::Value, incoming: serde_json::Value)
}

/// Detect the config format from content
fn detect_format(content: &str) -> ConfigFormat {
let Ok(serde_yaml::Value::Mapping(root)) = serde_yaml::from_str(content) else {
return ConfigFormat::Sqlctx;
fn detect_format(content: &str) -> Result<ConfigFormat> {
let root = serde_yaml::from_str(content)
.map_err(|e| SqlctxError::Validation(format!("YAML parse error: {e}")))?;
let root = match root {
serde_yaml::Value::Mapping(root) => root,
serde_yaml::Value::Null => return Ok(ConfigFormat::Sqlctx),
_ => {
// A text file can be a valid YAML scalar. Deserializing that scalar
// into SqlctxConfig would include its entire contents in the error.
return Err(SqlctxError::Validation(
"Expected a YAML mapping with a model definition (for example, models: or cubes:)"
.into(),
));
}
};
if root.get("version").and_then(serde_yaml::Value::as_str) == Some("0.3.0.dev0") {
ConfigFormat::Ossie
} else if root.contains_key("cubes") {
ConfigFormat::Cube
} else if root.contains_key("semantic_model") || root.contains_key("ontology_mappings") {
ConfigFormat::Osi
} else if root.contains_key("datasets") {
ConfigFormat::Ossie
} else {
ConfigFormat::Sqlctx
}
Ok(
if root.get("version").and_then(serde_yaml::Value::as_str) == Some("0.3.0.dev0") {
ConfigFormat::Ossie
} else if root.contains_key("cubes") {
ConfigFormat::Cube
} else if root.contains_key("semantic_model") || root.contains_key("ontology_mappings") {
ConfigFormat::Osi
} else if root.contains_key("datasets") {
ConfigFormat::Ossie
} else {
ConfigFormat::Sqlctx
},
)
}

/// Parse content based on detected format
Expand Down Expand Up @@ -1325,27 +1340,37 @@ mod tests {
#[test]
fn test_detect_format_sqlctx() {
let content = "models:\n - name: orders";
assert_eq!(detect_format(content), ConfigFormat::Sqlctx);
assert_eq!(detect_format(content).unwrap(), ConfigFormat::Sqlctx);
}

#[test]
fn test_detect_format_cube() {
let content = "cubes:\n - name: orders";
assert_eq!(detect_format(content), ConfigFormat::Cube);
assert_eq!(detect_format(content).unwrap(), ConfigFormat::Cube);
}

#[test]
fn test_detect_format_osi() {
assert_eq!(
detect_format("semantic_model:\n - name: m"),
detect_format("semantic_model:\n - name: m").unwrap(),
ConfigFormat::Osi
);
assert_eq!(
detect_format("ontology_mappings:\n - name: m"),
detect_format("ontology_mappings:\n - name: m").unwrap(),
ConfigFormat::Osi
);
}

#[test]
fn unrelated_text_is_not_returned_in_yaml_import_error() {
let contents = "example private file contents\nsecond line";
let error = load_literal_yaml_with_metadata(contents)
.unwrap_err()
.to_string();
assert!(error.contains("Expected a YAML mapping"), "{error}");
assert!(!error.contains("private file contents"), "{error}");
}

#[test]
fn test_load_from_string_auto_detects_osi() {
let yaml = r#"
Expand Down
5 changes: 4 additions & 1 deletion sqlctx-rs/src/core/dependency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,9 @@ pub(crate) fn is_aggregate_ast_kind(kind: &str) -> bool {
| "array_concat_agg"
| "array_unique_agg"
| "bool_xor_agg"
| "bitwise_and_agg"
| "bitwise_or_agg"
| "bitwise_xor_agg"
)
}

Expand All @@ -192,7 +195,7 @@ pub(crate) fn is_aggregate_ast_node(node: &serde_json::Value) -> bool {
|| (kind == "function"
&& value["quoted"].as_bool() != Some(true)
&& value["name"].as_str().is_some_and(|name| {
["LIST", "APPROX_QUANTILE", "APPROX_QUANTILES", "APPROX_PERCENTILE"]
["LIST", "PRODUCT", "APPROX_QUANTILE", "APPROX_QUANTILES", "APPROX_PERCENTILE"]
.iter().any(|aggregate| name.eq_ignore_ascii_case(aggregate))
}))
}
Expand Down
5 changes: 3 additions & 2 deletions sqlctx-rs/src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1499,7 +1499,8 @@ pub extern "C" fn sqlctx_compile_semantic_input(
semantic_result((|| {
let input = c_string_arg(input_json, "input_json")?;
let query = c_string_arg(query_json, "query_json")?;
crate::semantic_input::compile_with_semantic_input(&input, &query).map_err(semantic_error)
crate::semantic_input::compile_with_default_dialect(&input, &query, Some("duckdb"))
.map_err(semantic_error)
})())
}

Expand All @@ -1515,7 +1516,7 @@ pub extern "C" fn sqlctx_rewrite_semantic_input(
let input = c_string_arg(input_json, "input_json")?;
let sql = c_string_arg(sql, "sql")?;
let context = c_string_arg(context_json, "context_json")?;
crate::semantic_input::rewrite_with_semantic_input_context(&input, &sql, &context)
crate::semantic_input::rewrite_with_default_dialect(&input, &sql, &context, Some("duckdb"))
.map_err(semantic_error)
})())
}
Expand Down
Loading
Loading