diff --git a/coverage/translation/results-baseline.json b/coverage/translation/results-baseline.json index 989ffa696..48af01e81 100644 --- a/coverage/translation/results-baseline.json +++ b/coverage/translation/results-baseline.json @@ -14213,7 +14213,7 @@ "sf.functions.object-construct-keep-null-structured": "refused", "sf.functions.object-delete": "refused", "sf.functions.object-insert": "refused", - "sf.functions.object-keys": "refused", + "sf.functions.object-keys": "matching", "sf.functions.object-pick": "refused", "sf.functions.octet-length": "refused", "sf.functions.online-feature-table-refresh-history": "not_translatable", @@ -14318,7 +14318,7 @@ "sf.functions.rpad": "unmet_obligations", "sf.functions.rtrim": "matching", "sf.functions.rtrimmed-length": "refused", - "sf.functions.sanitize-webhook-content": "unmeasured", + "sf.functions.sanitize-webhook-content": "refused", "sf.functions.scheduled-time": "not_translatable", "sf.functions.search": "refused", "sf.functions.search-ip": "refused", @@ -14761,8 +14761,8 @@ "sf.functions.task-dependents": "not_translatable", "sf.functions.task-graph-changes": "not_translatable", "sf.functions.task-history": "not_translatable", - "sf.functions.text-html": "unmeasured", - "sf.functions.text-plain": "unmeasured", + "sf.functions.text-html": "refused", + "sf.functions.text-plain": "refused", "sf.functions.thread-messages-snowflake-cortex": "not_translatable", "sf.functions.time-from-parts": "refused", "sf.functions.time-slice": "refused", diff --git a/crates/sqlbabel-convert/src/snowflake/analysis/_helpers/volatile_calls.rs b/crates/sqlbabel-convert/src/snowflake/analysis/_helpers/volatile_calls.rs index 2dd85cfe7..595661c1d 100644 --- a/crates/sqlbabel-convert/src/snowflake/analysis/_helpers/volatile_calls.rs +++ b/crates/sqlbabel-convert/src/snowflake/analysis/_helpers/volatile_calls.rs @@ -1,6 +1,9 @@ //! Volatile Python function calls, which converted SQL must not repeat. -use crate::snowflake::conversion::models::Converted; +use crate::snowflake::conversion::constants::METHOD_CALL_KIND; +use crate::snowflake::conversion::main::_qualified_call_key::qualified_call_key; +use crate::snowflake::conversion::main::_statement_tree::statement_tree; +use crate::snowflake::conversion::models::{ConversionOptions, Converted}; use serde_json::Value; use sqlbabel_diagnostics::refusals::models::{Refusal, RefusalCategory}; use sqlbabel_policy::policy::constants::PROJECT_UDF; @@ -14,7 +17,7 @@ use crate::snowflake::analysis::constants::CALL_NODE_KINDS; pub(crate) fn volatile_calls_kept( converted: Converted, statement: &Expression, - schema: &Schema, + (schema, options): (&Schema, &ConversionOptions), ) -> Result { let tree = std::cell::OnceCell::new(); let prefix = format!("{PROJECT_UDF}:"); @@ -31,8 +34,9 @@ pub(crate) fn volatile_calls_kept( }) .find(|name| { let emitted = converted.sql.matches(&format!("\"{name}\"(")).count(); - let tree = tree.get_or_init(|| serde_json::to_value(statement).unwrap_or_default()); - let written = call_nodes(tree, name); + let tree = tree.get_or_init(|| statement_tree(statement, options)); + let written = call_nodes(tree, name) + + qualified_call_nodes(tree, name, (schema, options.current_database.as_ref())); emitted > written }); match repeated { @@ -67,3 +71,25 @@ pub(crate) fn call_nodes(tree: &Value, name: &str) -> usize { _ => 0, } } + +/// How many qualified call nodes in `tree`, such as `analytics.dev.shout(x)`, call the schema function `key`. +fn qualified_call_nodes(tree: &Value, key: &str, lookup: (&Schema, Option<&String>)) -> usize { + match tree { + Value::Object(fields) => fields + .iter() + .map(|(kind, value)| { + let call = kind == METHOD_CALL_KIND + && value + .as_object() + .and_then(|call| qualified_call_key(call, lookup)) + .is_some_and(|(_, called)| called.is_ok_and(|called| called == key)); + usize::from(call) + qualified_call_nodes(value, key, lookup) + }) + .sum(), + Value::Array(items) => items + .iter() + .map(|item| qualified_call_nodes(item, key, lookup)) + .sum(), + _ => 0, + } +} diff --git a/crates/sqlbabel-convert/src/snowflake/analysis/main/analyze.rs b/crates/sqlbabel-convert/src/snowflake/analysis/main/analyze.rs index 54c22af23..c0db1792f 100644 --- a/crates/sqlbabel-convert/src/snowflake/analysis/main/analyze.rs +++ b/crates/sqlbabel-convert/src/snowflake/analysis/main/analyze.rs @@ -65,7 +65,7 @@ pub fn analyze( analysis.occurrences.extend(occurrences); if !refused { match convert_within_budget(statement, sql, (schema, options, &lines)) - .and_then(|converted| volatile_calls_kept(converted, statement, schema)) + .and_then(|converted| volatile_calls_kept(converted, statement, (schema, options))) .and_then(|converted| overrides_applied(converted, statement, options)) { Ok(converted) => analysis.conversions.push(converted), diff --git a/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/project_functions.rs b/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/project_functions.rs index 5630bd478..7b5911219 100644 --- a/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/project_functions.rs +++ b/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/project_functions.rs @@ -9,6 +9,7 @@ use sqlbabel_blocks::semi_structured::main::json_guarded::json_guarded; use sqlbabel_diagnostics::classification::models::Construct; use sqlbabel_diagnostics::provenance::models::ProvenanceLog; use sqlbabel_diagnostics::refusals::constants::NEEDS_DIVERGENCE; +use sqlbabel_diagnostics::refusals::main::missing::missing; use sqlbabel_diagnostics::refusals::main::outside_conditions::outside_conditions; use sqlbabel_diagnostics::refusals::main::refused_divergence::refused_divergence; use sqlbabel_diagnostics::refusals::models::Refusal; @@ -17,9 +18,13 @@ use sqlbabel_semantics::snowflake::typing::models::SnowflakeType; use crate::snowflake::conversion::_helpers::expressions::scalar::convert_expression; use crate::snowflake::conversion::_helpers::support::scope::{Context, Emitted}; use crate::snowflake::conversion::_helpers::support::site::Site; +use crate::snowflake::conversion::_helpers::support::tree::{ + function_construct, list, node_construct, payload_object, require_understood, +}; +use crate::snowflake::conversion::main::_qualified_call_key::qualified_call_key; use crate::snowflake::conversion::constants::{ - PROJECT_FUNCTION_CALL, SEMI_STRUCTURED_HOLDING, USER_OVERRIDE_RULE, + METHOD_CALL_KIND, PROJECT_FUNCTION_CALL, SEMI_STRUCTURED_HOLDING, USER_OVERRIDE_RULE, }; use crate::snowflake::conversion::main::override_macro_name::override_macro_name; use crate::snowflake::conversion::models::UserOverride; @@ -27,6 +32,28 @@ use sqlbabel_policy::policy::constants::{PROJECT_UDF, PYTHON_VALUE_CROSSING, USE use sqlbabel_semantics::schemas::models::{FunctionLanguage, FunctionTraits}; use sqlbabel_semantics::snowflake::typing::types::{FunctionReturns, FunctionSpec}; +/// A call written with its schema, and maybe database, such as `analytics.dev.shout(x)`: the project function the schema declares under that name. +pub(crate) fn qualified_call(payload: &Value, site: Site<'_>) -> Result { + let construct = node_construct(METHOD_CALL_KIND); + let call = payload_object(payload, &construct)?; + let context = site.context; + let lookup = (context.schema, context.options.current_database.as_ref()); + let (written, key) = qualified_call_key(call, lookup).ok_or_else(|| { + missing( + construct.clone(), + format!("no rule converts node:{METHOD_CALL_KIND}"), + ) + })?; + let construct = function_construct(&written); + require_understood(call, &["this", "method", "args"], &construct)?; + let key = key.map_err(|refusal| Refusal { + construct: Some(construct.clone()), + ..refusal + })?; + let spec = &context.schema.functions[&key]; + project_call((&key, spec), list(call, "args"), &construct, site) +} + /// A scalar project function call: arguments coerced to the parameters, the result to its type. pub(crate) fn project_call( (name, spec): (&str, &FunctionSpec), diff --git a/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/scalar.rs b/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/scalar.rs index e1765b259..4c97a5972 100644 --- a/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/scalar.rs +++ b/crates/sqlbabel-convert/src/snowflake/conversion/_helpers/expressions/scalar.rs @@ -36,6 +36,7 @@ use crate::snowflake::conversion::_helpers::expressions::ordered_aggregates::{ use crate::snowflake::conversion::_helpers::expressions::predicates::{ between, exists, in_predicate, null_test, }; +use crate::snowflake::conversion::_helpers::expressions::project_functions::qualified_call; use crate::snowflake::conversion::_helpers::expressions::result_types::result_type; use crate::snowflake::conversion::_helpers::expressions::semi_structured::{ variant_path, variant_subscript, @@ -66,10 +67,11 @@ use crate::snowflake::conversion::_helpers::support::tree::{ function_construct, node_construct, node_kind, payload_object, require_understood, }; use crate::snowflake::conversion::constants::{ - AGGREGATE_CALL_KIND, ARRAY_LITERAL_KIND, CALL_KIND, IFF_NAME, NONDETERMINISTIC_FUNCTIONS, - OBJECT_CONSTANT_KIND, RLIKE_PAIR, SUBQUERY_READS_LAMBDA, SYSTEM_TYPEOF_NAME, - TYPE_SUFFIX_UNREMOVED, VARIANT_HELD_UNREAD, VOLATILE_SUBQUERY_IN_LAMBDA, + AGGREGATE_CALL_KIND, ARRAY_LITERAL_KIND, CALL_KIND, IFF_NAME, METHOD_CALL_KIND, + NONDETERMINISTIC_FUNCTIONS, OBJECT_CONSTANT_KIND, RLIKE_PAIR, SUBQUERY_READS_LAMBDA, + SYSTEM_TYPEOF_NAME, TYPE_SUFFIX_UNREMOVED, VARIANT_HELD_UNREAD, VOLATILE_SUBQUERY_IN_LAMBDA, }; +use crate::snowflake::conversion::main::_qualified_call_key::qualified_call_key; /// One scalar expression, located; VARIANT-held values refused, collected refusals as placeholders. pub(crate) fn convert_expression(node: &Value, site: Site<'_>) -> Result { @@ -256,7 +258,17 @@ fn calls_volatile(node: &Value, context: &Context<'_>) -> bool { let called = (kind == CALL_KIND || kind == AGGREGATE_CALL_KIND) .then(|| call_name(value)) .is_some_and(|name| volatile_call(&name, context)); - called || calls_volatile(value, context) + let qualified = kind == METHOD_CALL_KIND + && value + .as_object() + .and_then(|call| { + qualified_call_key( + call, + (context.schema, context.options.current_database.as_ref()), + ) + }) + .is_some_and(|(_, key)| key.is_ok_and(|key| volatile_call(&key, context))); + called || qualified || calls_volatile(value, context) }), Value::Array(items) => items.iter().any(|item| calls_volatile(item, context)), _ => false, @@ -406,6 +418,7 @@ fn convert_kind(node: &Value, site: Site<'_>) -> Result { "an aggregate is not allowed here".to_owned(), )), "within_group" => within_group(payload, site, None), + METHOD_CALL_KIND => qualified_call(payload, site), other => Err(missing( node_construct(other), format!("no rule converts node:{other}"), diff --git a/crates/sqlbabel-convert/src/snowflake/conversion/constants.rs b/crates/sqlbabel-convert/src/snowflake/conversion/constants.rs index fb0ef5d2f..78f41d7a9 100644 --- a/crates/sqlbabel-convert/src/snowflake/conversion/constants.rs +++ b/crates/sqlbabel-convert/src/snowflake/conversion/constants.rs @@ -679,6 +679,8 @@ pub const WINDOW_AGGREGATE: &str = "rule.window_aggregate"; pub const AVG_NAME: &str = "AVG"; /// The node kind of a plain call. pub const CALL_KIND: &str = "function"; +/// The node kind of a call written with a qualifier, such as `dev.shout(x)`. +pub const METHOD_CALL_KIND: &str = "method_call"; /// The call the RLIKE operator is converted as, proven by recorded RLIKE and REGEXP_LIKE pairs. pub const REGEXP_LIKE_NAME: &str = "REGEXP_LIKE"; /// The node kind of an aggregate call. diff --git a/crates/sqlbabel-convert/src/snowflake/conversion/main/_qualified_call_key.rs b/crates/sqlbabel-convert/src/snowflake/conversion/main/_qualified_call_key.rs new file mode 100644 index 000000000..fead3e161 --- /dev/null +++ b/crates/sqlbabel-convert/src/snowflake/conversion/main/_qualified_call_key.rs @@ -0,0 +1,45 @@ +//! `qualified_call_key`: the schema function a call written with its schema, and maybe database, names. + +use serde_json::{Map, Value}; +use sqlbabel_diagnostics::refusals::models::Refusal; +use sqlbabel_semantics::schemas::constants::{ + FULL_NAME_PARTS, RELATION_KEY_SEPARATOR, SCHEMA_NAME_PARTS, +}; +use sqlbabel_semantics::schemas::main::function_key::function_key; +use sqlbabel_semantics::snowflake::typing::types::Schema; + +use crate::snowflake::conversion::_helpers::support::tree::{identifier_name, node_kind}; + +/// A qualified call's written name, such as `ANALYTICS.DEV.SHOUT`, and the schema function it names, the session's database completing a two-part name; none unless it is written as two or three names. +pub(in crate::snowflake) fn qualified_call_key( + call: &Map, + (schema, current_database): (&Schema, Option<&String>), +) -> Option<(String, Result)> { + let mut parts: Vec = qualifier(call.get("this")?)?; + parts.push(call.get("method").and_then(identifier_name)?); + if !(SCHEMA_NAME_PARTS..=FULL_NAME_PARTS).contains(&parts.len()) { + return None; + } + let written = parts.join(RELATION_KEY_SEPARATOR); + if let (SCHEMA_NAME_PARTS, Some(database)) = (parts.len(), current_database) { + parts.insert(0, database.clone()); + } + Some((written, function_key(&parts, schema))) +} + +/// The resolved names of a call's qualifier written as a name, such as `analytics.dev`; none for any other expression. +fn qualifier(this: &Value) -> Option> { + match node_kind(this)? { + ("column", column) => { + let mut names: Vec = column + .get("table") + .and_then(identifier_name) + .into_iter() + .collect(); + names.push(column.get("name").and_then(identifier_name)?); + Some(names) + } + ("identifier", identifier) => Some(vec![identifier_name(identifier)?]), + _ => None, + } +} diff --git a/crates/sqlbabel-convert/src/snowflake/conversion/main/_statement_tree.rs b/crates/sqlbabel-convert/src/snowflake/conversion/main/_statement_tree.rs new file mode 100644 index 000000000..b279e334b --- /dev/null +++ b/crates/sqlbabel-convert/src/snowflake/conversion/main/_statement_tree.rs @@ -0,0 +1,16 @@ +//! `statement_tree`: a statement's tree as conversion reads its names. + +use serde_json::Value; +use sqlbabel_syntax::Expression; + +use crate::snowflake::conversion::_helpers::support::tree::session_tree; +use crate::snowflake::conversion::models::ConversionOptions; + +/// `statement` as a tree with quoted identifiers folded when the session ignores their case, so a count over it resolves names as conversion did; a statement conversion could not fold never reaches a count, and stays as written. +pub(in crate::snowflake) fn statement_tree( + statement: &Expression, + options: &ConversionOptions, +) -> Value { + let raw = serde_json::to_value(statement).unwrap_or_default(); + session_tree(&raw, options.quoted_identifiers_ignore_case).unwrap_or(raw) +} diff --git a/crates/sqlbabel-convert/src/snowflake/conversion/main/mod.rs b/crates/sqlbabel-convert/src/snowflake/conversion/main/mod.rs index ca52e802c..ee4ab42d9 100644 --- a/crates/sqlbabel-convert/src/snowflake/conversion/main/mod.rs +++ b/crates/sqlbabel-convert/src/snowflake/conversion/main/mod.rs @@ -1,4 +1,6 @@ pub(in crate::snowflake) mod _convert_function_body; +pub(in crate::snowflake) mod _qualified_call_key; +pub(in crate::snowflake) mod _statement_tree; pub mod collect_refusals; pub mod convert_statement; pub mod override_macro; diff --git a/crates/sqlbabel-diagnostics/src/diagnostics/constants.rs b/crates/sqlbabel-diagnostics/src/diagnostics/constants.rs index 486372b45..20bab8274 100644 --- a/crates/sqlbabel-diagnostics/src/diagnostics/constants.rs +++ b/crates/sqlbabel-diagnostics/src/diagnostics/constants.rs @@ -10,6 +10,15 @@ pub const CASE_ONLY_MATCH: &str = "only without regard to case"; pub const CASE_ONLY_MATCH_HELP: &str = "Snowflake folds unquoted names to upper case, so declare \ the relation or column in a source file as the SQL resolves it (`ORDERS` for `FROM orders`), or \ quote the name in the SQL to keep its case"; +/// How an unresolved qualified function call's reason ends when no schema function has its name. +pub const UNKNOWN_FUNCTION_SUFFIX: &str = + "` is not in the schema; declare it under its qualified name, such as `DATABASE.SCHEMA.NAME`"; +/// How an unresolved qualified function call's reason ends when it names functions in several databases. +pub const AMBIGUOUS_FUNCTION_SUFFIX: &str = + " in the schema; call it by its full name, or set the session's DATABASE, to pick one"; +/// The help for an unresolved qualified function call, replacing SBL0004's own. +pub const FUNCTION_NAME_HELP: &str = "declare the function in the project's `functions/` folder, or \ + in the schema's functions, under the qualified name the call resolves to"; /// The words of an unresolved name's reason when two result columns share a name. pub const REPEATED_RESULT_NAME: &str = "repeats an earlier result column's name"; /// The label of an unaliased item Snowflake names after its text. diff --git a/crates/sqlbabel-diagnostics/src/diagnostics/main/diagnose.rs b/crates/sqlbabel-diagnostics/src/diagnostics/main/diagnose.rs index 5fc05bfca..9c8b35724 100644 --- a/crates/sqlbabel-diagnostics/src/diagnostics/main/diagnose.rs +++ b/crates/sqlbabel-diagnostics/src/diagnostics/main/diagnose.rs @@ -7,11 +7,12 @@ use crate::diagnostics::_helpers::jinja::holds_jinja; use crate::diagnostics::_helpers::line_index::LineIndex; use crate::diagnostics::_helpers::plain_keys::plain_keys; use crate::diagnostics::constants::{ - CASE_ONLY_MATCH, CASE_ONLY_MATCH_HELP, CONVERSION_BUDGET, DIVERGENCE_REFUSED, - FUNCTION_OPERAND_HELP, GUARD_PREFIX, JINJA_HELP, MISSING_RULE, NOT_EXPRESSIBLE, PARSE_FIDELITY, - REPEATED_RESULT_NAME, REPEATED_RESULT_NAME_HELP, SUGGESTED_NAME_MAX_CHARS, TYPE_CONDITION, - UNALIASED_OUTPUT_NAME, UNALIASED_QUOTED_NAME, UNALIASED_QUOTED_NAME_HELP, UNPARSED_PREFIX, - UNRESOLVED_NAME, ZONED_LOCAL_TIME, ZONED_LOCAL_TIME_HELP, ZONED_LOCAL_TIME_NOTE, + AMBIGUOUS_FUNCTION_SUFFIX, CASE_ONLY_MATCH, CASE_ONLY_MATCH_HELP, CONVERSION_BUDGET, + DIVERGENCE_REFUSED, FUNCTION_NAME_HELP, FUNCTION_OPERAND_HELP, GUARD_PREFIX, JINJA_HELP, + MISSING_RULE, NOT_EXPRESSIBLE, PARSE_FIDELITY, REPEATED_RESULT_NAME, REPEATED_RESULT_NAME_HELP, + SUGGESTED_NAME_MAX_CHARS, TYPE_CONDITION, UNALIASED_OUTPUT_NAME, UNALIASED_QUOTED_NAME, + UNALIASED_QUOTED_NAME_HELP, UNKNOWN_FUNCTION_SUFFIX, UNPARSED_PREFIX, UNRESOLVED_NAME, + ZONED_LOCAL_TIME, ZONED_LOCAL_TIME_HELP, ZONED_LOCAL_TIME_NOTE, }; use crate::diagnostics::models::Diagnostic; use crate::refusals::models::{Refusal, RefusalCategory}; @@ -34,6 +35,12 @@ pub fn diagnose(refusals: &[Refusal], source: &str) -> Vec { { diagnostic.help = Some(REPEATED_RESULT_NAME_HELP.to_owned()); } + if refusal.category == RefusalCategory::UnresolvedName + && (refusal.reason.contains(UNKNOWN_FUNCTION_SUFFIX) + || refusal.reason.contains(AMBIGUOUS_FUNCTION_SUFFIX)) + { + diagnostic.help = Some(FUNCTION_NAME_HELP.to_owned()); + } if refusal.category == RefusalCategory::ParseFidelity && holds_jinja(refusal, source) { diagnostic.help = Some(JINJA_HELP.to_owned()); } diff --git a/crates/sqlbabel-semantics/src/schemas/constants.rs b/crates/sqlbabel-semantics/src/schemas/constants.rs index 3021b4f20..3b451c549 100644 --- a/crates/sqlbabel-semantics/src/schemas/constants.rs +++ b/crates/sqlbabel-semantics/src/schemas/constants.rs @@ -1,5 +1,9 @@ -//! Refusal texts for relation names. +//! Refusal texts for relation and function names. +/// The parts of a function call written by schema and name, such as `dev.shout`. +pub const SCHEMA_NAME_PARTS: usize = 2; +/// The parts of a complete function name: database, schema and name. +pub const FULL_NAME_PARTS: usize = 3; /// How a refusal for a relation without known columns begins, before the relation's name. pub const UNKNOWN_RELATION_PREFIX: &str = "relation `"; /// How it ends, after the name. @@ -9,3 +13,5 @@ pub const RELATION_KEY_SEPARATOR: &str = "."; /// How a refusal for a name matching several schema relations ends, after the relations. pub const AMBIGUOUS_RELATION_SUFFIX: &str = " in the project's sources; qualify it, or set the session's DATABASE and SCHEMA, to pick one"; +/// How a refusal for a qualified call no schema function matches begins, before the call's name; it ends in `UNKNOWN_FUNCTION_SUFFIX`. +pub const UNKNOWN_FUNCTION_PREFIX: &str = "the function `"; diff --git a/crates/sqlbabel-semantics/src/schemas/main/function_key.rs b/crates/sqlbabel-semantics/src/schemas/main/function_key.rs new file mode 100644 index 000000000..e1b0652b0 --- /dev/null +++ b/crates/sqlbabel-semantics/src/schemas/main/function_key.rs @@ -0,0 +1,54 @@ +//! `function_key`: the schema function a call written with its schema, and maybe database, names. + +use sqlbabel_diagnostics::diagnostics::constants::{ + AMBIGUOUS_FUNCTION_SUFFIX, UNKNOWN_FUNCTION_SUFFIX, +}; +use sqlbabel_diagnostics::refusals::main::unresolved::unresolved; +use sqlbabel_diagnostics::refusals::models::Refusal; + +use crate::schemas::constants::{ + FULL_NAME_PARTS, RELATION_KEY_SEPARATOR, SCHEMA_NAME_PARTS, UNKNOWN_FUNCTION_PREFIX, +}; +use crate::schemas::models::Schema; +use crate::schemas::types::DialectType; + +/// The declared key `parts` name: the key equal to them, else for a schema and name the one three-part key ending in them; none or a tie refuses. +pub fn function_key( + parts: &[String], + schema: &Schema, +) -> Result { + let written = parts.join(RELATION_KEY_SEPARATOR); + if schema.functions.contains_key(&written) { + return Ok(written); + } + let matches: Vec<&String> = schema + .functions + .keys() + .filter(|key| ends_in(key, parts)) + .collect(); + match matches.as_slice() { + [key] => Ok((*key).clone()), + [] => Err(unresolved(format!( + "{UNKNOWN_FUNCTION_PREFIX}{written}{UNKNOWN_FUNCTION_SUFFIX}" + ))), + keys => Err(unresolved(format!( + "function `{written}` matches `{}`{AMBIGUOUS_FUNCTION_SUFFIX}", + keys.iter() + .map(|key| key.as_str()) + .collect::>() + .join("`, `"), + ))), + } +} + +/// Whether a two-part `parts` names the three-part `key` in some database; a three-part name is complete, and a key in another schema, a bare key or a longer key never matches. +fn ends_in(key: &str, parts: &[String]) -> bool { + let key_parts: Vec<&str> = key.split(RELATION_KEY_SEPARATOR).collect(); + parts.len() == SCHEMA_NAME_PARTS + && key_parts.len() == FULL_NAME_PARTS + && key_parts + .iter() + .rev() + .zip(parts.iter().rev()) + .all(|(key_part, written)| key_part == written) +} diff --git a/crates/sqlbabel-semantics/src/schemas/main/mod.rs b/crates/sqlbabel-semantics/src/schemas/main/mod.rs index 9ee6be646..9294fc159 100644 --- a/crates/sqlbabel-semantics/src/schemas/main/mod.rs +++ b/crates/sqlbabel-semantics/src/schemas/main/mod.rs @@ -1 +1,2 @@ +pub mod function_key; pub mod relation_key; diff --git a/crates/sqlbabel-semantics/src/snowflake/names/tests.rs b/crates/sqlbabel-semantics/src/snowflake/names/tests.rs index e92f2ae2c..4be1d074a 100644 --- a/crates/sqlbabel-semantics/src/snowflake/names/tests.rs +++ b/crates/sqlbabel-semantics/src/snowflake/names/tests.rs @@ -1,5 +1,7 @@ #[path = "tests/helpers.rs"] mod helpers; +#[path = "tests/test_function_key.rs"] +mod test_function_key; #[path = "tests/test_relation_columns.rs"] mod test_relation_columns; #[path = "tests/test_resolve_name.rs"] diff --git a/crates/sqlbabel-semantics/src/snowflake/names/tests/test_function_key.rs b/crates/sqlbabel-semantics/src/snowflake/names/tests/test_function_key.rs new file mode 100644 index 000000000..91039ac4b --- /dev/null +++ b/crates/sqlbabel-semantics/src/snowflake/names/tests/test_function_key.rs @@ -0,0 +1,97 @@ +use crate::schemas::main::function_key::function_key; +use crate::schemas::models::{FunctionLanguage, FunctionTraits}; +use crate::snowflake::names::tests::test_types::FunctionKeyTestCase; +use crate::snowflake::typing::models::SnowflakeType; +use crate::snowflake::typing::types::{FunctionReturns, FunctionSpec, Schema}; + +#[test] +fn given_declared_functions_when_resolving_a_qualified_call_then_only_the_function_it_names_matches() + { + let mut schema = Schema::default(); + for key in [ + "ANALYTICS.DEV.SHOUT", + "ANALYTICS.PROD.SHOUT", + "ANALYTICS.DEV.LABEL", + "OTHER.DEV.LABEL", + "WHISPER", + "OUTER.ANALYTICS.DEV.QUIET", + ] { + schema.functions.insert( + key.to_owned(), + FunctionSpec { + language: FunctionLanguage::Python, + arguments: Vec::new(), + returns: FunctionReturns::Scalar(SnowflakeType::Varchar), + traits: FunctionTraits::default(), + }, + ); + } + let test_cases = [ + FunctionKeyTestCase { + description: "a three-part call names its key exactly", + parts: &["ANALYTICS", "DEV", "SHOUT"], + expected_outcome: Ok("ANALYTICS.DEV.SHOUT"), + }, + FunctionKeyTestCase { + description: "a same-name function in another schema is never chosen", + parts: &["ANALYTICS", "PROD", "SHOUT"], + expected_outcome: Ok("ANALYTICS.PROD.SHOUT"), + }, + FunctionKeyTestCase { + description: "a two-part call matches the one key ending in it", + parts: &["PROD", "SHOUT"], + expected_outcome: Ok("ANALYTICS.PROD.SHOUT"), + }, + FunctionKeyTestCase { + description: "a two-part call matching keys in two databases refuses", + parts: &["DEV", "LABEL"], + expected_outcome: Err( + "function `DEV.LABEL` matches `ANALYTICS.DEV.LABEL`, `OTHER.DEV.LABEL` in the schema; call it by its full name, or set the session's DATABASE, to pick one", + ), + }, + FunctionKeyTestCase { + description: "a qualified call never reads a bare key", + parts: &["DEV", "WHISPER"], + expected_outcome: Err( + "the function `DEV.WHISPER` is not in the schema; declare it under its qualified name, such as `DATABASE.SCHEMA.NAME`", + ), + }, + FunctionKeyTestCase { + description: "a three-part call is complete and never reads a longer key ending in it", + parts: &["ANALYTICS", "DEV", "QUIET"], + expected_outcome: Err( + "the function `ANALYTICS.DEV.QUIET` is not in the schema; declare it under its qualified name, such as `DATABASE.SCHEMA.NAME`", + ), + }, + FunctionKeyTestCase { + description: "a two-part call reads only three-part keys", + parts: &["DEV", "QUIET"], + expected_outcome: Err( + "the function `DEV.QUIET` is not in the schema; declare it under its qualified name, such as `DATABASE.SCHEMA.NAME`", + ), + }, + FunctionKeyTestCase { + description: "a call in a schema with no such function refuses, naming it", + parts: &["ANALYTICS", "STAGING", "SHOUT"], + expected_outcome: Err( + "the function `ANALYTICS.STAGING.SHOUT` is not in the schema; declare it under its qualified name, such as `DATABASE.SCHEMA.NAME`", + ), + }, + ]; + for test_case in test_cases { + let parts: Vec = test_case + .parts + .iter() + .map(|part| (*part).to_owned()) + .collect(); + assert_eq!( + function_key(&parts, &schema).map_err(|refusal| refusal.reason), + test_case + .expected_outcome + .map(str::to_owned) + .map_err(str::to_owned), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbabel-semantics/src/snowflake/names/tests/test_types.rs b/crates/sqlbabel-semantics/src/snowflake/names/tests/test_types.rs index 2c2a3fae3..932167158 100644 --- a/crates/sqlbabel-semantics/src/snowflake/names/tests/test_types.rs +++ b/crates/sqlbabel-semantics/src/snowflake/names/tests/test_types.rs @@ -8,3 +8,8 @@ pub(crate) struct ResolveNameTestCase { pub(crate) name: (Option<&'static str>, &'static str), pub(crate) expected_outcome: Result<&'static str, &'static str>, } +pub(crate) struct FunctionKeyTestCase { + pub(crate) description: &'static str, + pub(crate) parts: &'static [&'static str], + pub(crate) expected_outcome: Result<&'static str, &'static str>, +} diff --git a/crates/sqlbabel/tests/cli.rs b/crates/sqlbabel/tests/cli.rs index b06ea7a4c..09192fb41 100644 --- a/crates/sqlbabel/tests/cli.rs +++ b/crates/sqlbabel/tests/cli.rs @@ -42,6 +42,8 @@ mod test_joins; mod test_output_names; #[path = "cli/test_project.rs"] mod test_project; +#[path = "cli/test_qualified_calls.rs"] +mod test_qualified_calls; #[path = "cli/test_read_check.rs"] mod test_read_check; #[path = "cli/test_review.rs"] diff --git a/crates/sqlbabel/tests/cli/fixtures/volatile_lookback/functions/sql/analytics.dev.lookback.sql b/crates/sqlbabel/tests/cli/fixtures/volatile_lookback/functions/sql/analytics.dev.lookback.sql new file mode 100644 index 000000000..2422da260 --- /dev/null +++ b/crates/sqlbabel/tests/cli/fixtures/volatile_lookback/functions/sql/analytics.dev.lookback.sql @@ -0,0 +1,5 @@ +FUNCTION ( + arguments (), + returns NUMBER(1,0), +); +1 diff --git a/crates/sqlbabel/tests/cli/test_qualified_calls.rs b/crates/sqlbabel/tests/cli/test_qualified_calls.rs new file mode 100644 index 000000000..9ddf76e8f --- /dev/null +++ b/crates/sqlbabel/tests/cli/test_qualified_calls.rs @@ -0,0 +1,33 @@ +//! Calls written with their schema, and maybe database, such as `analytics.dev.lookback()`. + +use crate::helpers::{convert_outcome, run_convert}; +use crate::test_types::ConvertTestCase; + +#[test] +fn given_a_qualified_call_when_converting_then_it_is_checked_like_the_function_it_names() { + let test_cases = [ + ConvertTestCase { + description: "a subquery calling a qualified volatile function refuses where a lambda wraps it", + sql: "SELECT DATEADD(day, -3, (SELECT MAX(occurred_at) FROM events \ + WHERE event_id > analytics.dev.lookback())) AS d", + flags: &["--project", "tests/cli/fixtures/volatile_lookback"], + mention: "a subquery calling a function whose result can change between calls", + expected_outcome: convert_outcome(1, false), + }, + ConvertTestCase { + description: "a qualified call to an undeclared function says where functions are declared", + sql: "SELECT analytics.dev.missing() AS m", + flags: &["--project", "tests/cli/fixtures/volatile_lookback"], + mention: "help: declare the function in the project's `functions/` folder", + expected_outcome: convert_outcome(1, false), + }, + ]; + for test_case in test_cases { + assert_eq!( + run_convert(test_case.sql, test_case.flags, test_case.mention), + test_case.expected_outcome, + "{}", + test_case.description + ); + } +} diff --git a/python/pyproject.toml b/python/pyproject.toml index 2370a1421..4338119a4 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -13,6 +13,11 @@ dynamic = ["version"] # The `sqlbabel` command, as a native executable built from the same sources. dependencies = ["sqlbabel-cli==0.40.0"] # x-release-please-version +[project.optional-dependencies] +# `register_functions` runs Python functions only on the duckdb release SQLBabel links; it must +# equal PINNED_DUCKDB_VERSION in python_runtime/constants.py. +runtime = ["duckdb==2.0.0"] + [tool.maturin] manifest-path = "../crates/sqlbabel-python/Cargo.toml" python-source = "src" diff --git a/tests/unit/python/src/sqlbabel/python_runtime/main/_test_types.py b/tests/unit/python/src/sqlbabel/python_runtime/main/_test_types.py index e4df87c44..60807364e 100644 --- a/tests/unit/python/src/sqlbabel/python_runtime/main/_test_types.py +++ b/tests/unit/python/src/sqlbabel/python_runtime/main/_test_types.py @@ -39,3 +39,26 @@ class RegistrationTestCase: duckdb_version: str handler_names: tuple[str, ...] expected_message: str + + +@dataclass(frozen=True) +class QualifiedCallTestCase: + description: str + sql: str + session: Mapping[str, str] + bind_check: bool + expected_rows: tuple[tuple[Any, ...], ...] + + +@dataclass(frozen=True) +class QualifiedRefusalTestCase: + description: str + sql: str + expected_refusal: str + + +@dataclass(frozen=True) +class RuntimeExtraTestCase: + description: str + extra: str + expected_requirements: tuple[str, ...] diff --git a/tests/unit/python/src/sqlbabel/python_runtime/main/test_register_functions.py b/tests/unit/python/src/sqlbabel/python_runtime/main/test_register_functions.py index 3b283271f..d57276d84 100644 --- a/tests/unit/python/src/sqlbabel/python_runtime/main/test_register_functions.py +++ b/tests/unit/python/src/sqlbabel/python_runtime/main/test_register_functions.py @@ -4,21 +4,41 @@ import datetime import re +import tomllib from decimal import Decimal +from pathlib import Path +from typing import Any import duckdb import pytest import sqlbabel from sqlbabel import RegistrationError +from sqlbabel.python_runtime.constants import PINNED_DUCKDB_VERSION from tests.unit.python.src.sqlbabel.python_runtime.main._test_types import ( CallTestCase, CrossingTestCase, + QualifiedCallTestCase, + QualifiedRefusalTestCase, RegistrationTestCase, + RuntimeExtraTestCase, VolatilityTestCase, ) from tests.unit.python.src.sqlbabel.python_runtime.main.helpers import function, never_called +_SHOUT: dict[str, Any] = { + "language": "python", + "arguments": [["TEXT", "VARCHAR"]], + "returns": "VARCHAR", +} +_QUALIFIED_SCHEMA: dict[str, Any] = { + "relations": {"ORDERS": [["STATUS", "VARCHAR"]]}, + "functions": {"ANALYTICS.DEV.SHOUT": _SHOUT, "ANALYTICS.PROD.SHOUT": _SHOUT}, +} +_HANDLERS: dict[str, Any] = { + "ANALYTICS.DEV.SHOUT": lambda text: None if text is None else text.upper() + "!", + "ANALYTICS.PROD.SHOUT": lambda text: None if text is None else "prod " + text, +} _ZONED: datetime.datetime = datetime.datetime(2026, 1, 1, 10, 0, 0, 500, tzinfo=datetime.UTC) @@ -245,3 +265,133 @@ def test_given_a_function_the_runtime_cannot_honour_when_registered_then_it_refu assert connection.execute( "SELECT count(*) FROM duckdb_functions() WHERE function_name IN ('F', 'G')" ).fetchone() == (0,) + + +@pytest.mark.parametrize( + "test_case", + ( + QualifiedCallTestCase( + description="a call by database, schema and name runs its handler, NULL included", + sql="SELECT analytics.dev.shout(status) AS loud FROM orders", + session={}, + bind_check=False, + expected_rows=(("COMPLETED!",), (None,)), + ), + QualifiedCallTestCase( + description="the bind check binds the qualified call too", + sql="SELECT analytics.dev.shout(status) AS loud FROM orders", + session={}, + bind_check=True, + expected_rows=(("COMPLETED!",), (None,)), + ), + QualifiedCallTestCase( + description="a same-name function in another schema runs its own handler", + sql="SELECT analytics.prod.shout(status) AS loud FROM orders", + session={}, + bind_check=False, + expected_rows=(("prod completed",), (None,)), + ), + QualifiedCallTestCase( + description="a quoted schema folded by the session runs once, as it is written once", + sql='SELECT analytics."dev".shout(status) AS loud FROM orders', + session={"QUOTED_IDENTIFIERS_IGNORE_CASE": "TRUE"}, + bind_check=False, + expected_rows=(("COMPLETED!",), (None,)), + ), + QualifiedCallTestCase( + description="a call by schema and name takes the session's database", + sql="SELECT dev.shout(status) AS loud FROM orders", + session={"DATABASE": "ANALYTICS"}, + bind_check=False, + expected_rows=(("COMPLETED!",), (None,)), + ), + ), + ids=lambda case: case.description, +) +def test_given_a_qualified_call_to_a_project_function_when_converted_and_registered_then_it_runs( + test_case: QualifiedCallTestCase, +) -> None: + conversion: sqlbabel.Conversion = sqlbabel.convert( + sql=test_case.sql, + options=sqlbabel.ConvertOptions( + no_config=True, + schema=_QUALIFIED_SCHEMA, + session=test_case.session, + python_runtime=True, + bind_check=test_case.bind_check, + ), + ) + connection: duckdb.DuckDBPyConnection = duckdb.connect() + connection.execute( + 'CREATE TABLE "ORDERS" AS SELECT * FROM (VALUES (\'completed\'), (NULL)) AS v("STATUS")' + ) + sqlbabel.register_functions( + connection=connection, + functions=conversion.report["python_functions"], + handlers=_HANDLERS, + ) + for macro in conversion.macros: + connection.execute(macro) + + assert conversion.converted, conversion.report["refusals"] + assert tuple(connection.execute(conversion.sql).fetchall()) == test_case.expected_rows + + +@pytest.mark.parametrize( + "test_case", + ( + QualifiedRefusalTestCase( + description="a call to a function the schema does not declare refuses, naming it", + sql="SELECT analytics.staging.shout(status) AS loud FROM orders", + expected_refusal="the function `ANALYTICS.STAGING.SHOUT` is not in the schema", + ), + QualifiedRefusalTestCase( + description="a call by schema and name matching two databases refuses, naming both", + sql="SELECT dev.shout(status) AS loud FROM orders", + expected_refusal="function `DEV.SHOUT` matches `ANALYTICS.DEV.SHOUT`, `OTHER.DEV.SHOUT`", + ), + ), + ids=lambda case: case.description, +) +def test_given_a_qualified_call_no_schema_function_answers_when_converting_then_it_refuses_naming_it( + test_case: QualifiedRefusalTestCase, +) -> None: + conversion: sqlbabel.Conversion = sqlbabel.convert( + sql=test_case.sql, + options=sqlbabel.ConvertOptions( + no_config=True, + schema={ + **_QUALIFIED_SCHEMA, + "functions": {**_QUALIFIED_SCHEMA["functions"], "OTHER.DEV.SHOUT": _SHOUT}, + }, + python_runtime=True, + bind_check=False, + ), + ) + reasons: str = str([refusal["reason"] for refusal in conversion.report["refusals"]]) + + assert not conversion.converted + assert test_case.expected_refusal in reasons + assert "METHOD" not in reasons.upper() + + +@pytest.mark.parametrize( + "test_case", + ( + RuntimeExtraTestCase( + description="the runtime extra pins the duckdb register_functions checks for", + extra="runtime", + expected_requirements=(f"duckdb=={PINNED_DUCKDB_VERSION}",), + ), + ), + ids=lambda case: case.description, +) +def test_given_the_package_extras_when_read_then_they_pin_the_duckdb_the_runtime_needs( + test_case: RuntimeExtraTestCase, +) -> None: + pyproject: Path = Path(__file__).resolve().parents[7] / "python" / "pyproject.toml" + extras: dict[str, list[str]] = tomllib.loads(pyproject.read_text(encoding="utf-8"))["project"][ + "optional-dependencies" + ] + + assert tuple(extras[test_case.extra]) == test_case.expected_requirements diff --git a/website/src/content/docs/docs/python.mdx b/website/src/content/docs/docs/python.mdx index 7faa413f5..4233ace54 100644 --- a/website/src/content/docs/docs/python.mdx +++ b/website/src/content/docs/docs/python.mdx @@ -120,8 +120,10 @@ the command line. `register_functions(*, connection, functions, handlers)` registers a project's [Python functions](/docs/project/#functions) in a DuckDB connection, so the converted SQL that calls them runs. Pass the conversion's `report["python_functions"]` as `functions`, and one -handler per function in `handlers`, keyed by the name the report lists. Here the project holds -the `label` function from [Functions](/docs/project/#functions) and sets `python_runtime = true`: +handler per function in `handlers`, keyed by the name the report lists. It needs the duckdb +release SQLBabel links, which the `runtime` extra installs: `pip install "sqlbabel[runtime]"`. Here +the project holds the `label` function from [Functions](/docs/project/#functions) and sets +`python_runtime = true`: {/* example: python-functions python */} ```python @@ -141,8 +143,11 @@ for macro in conversion.macros: connection.execute(conversion.sql).fetchall() # [('Shipped',)] ``` -The report names each function as Snowflake resolves it, so `label` is listed as `LABEL`. Each -entry of `python_functions` has these fields: +The report names each function as Snowflake resolves it, so `label` is listed as `LABEL`. A +function declared in `schema` under its qualified name, such as `ANALYTICS.DEV.SHOUT`, is called as +`analytics.dev.shout(...)`, or as `dev.shout(...)` when the session's `DATABASE` is `ANALYTICS`, and +is listed under that name. A qualified call to a function `schema` does not declare is refused with +the name. Each entry of `python_functions` has these fields: | Field | Meaning | |-------|---------|