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
8 changes: 4 additions & 4 deletions coverage/translation/results-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<Converted, Refusal> {
let tree = std::cell::OnceCell::new();
let prefix = format!("{PROJECT_UDF}:");
Expand All @@ -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 {
Expand Down Expand Up @@ -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,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -17,16 +18,42 @@ 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;
use sqlbabel_policy::policy::constants::{PROJECT_UDF, PYTHON_VALUE_CROSSING, USER_OVERRIDE};
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<Emitted, Refusal> {
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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<Emitted, Refusal> {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -406,6 +418,7 @@ fn convert_kind(node: &Value, site: Site<'_>) -> Result<Emitted, Refusal> {
"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}"),
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlbabel-convert/src/snowflake/conversion/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, Value>,
(schema, current_database): (&Schema, Option<&String>),
) -> Option<(String, Result<String, Refusal>)> {
let mut parts: Vec<String> = 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<Vec<String>> {
match node_kind(this)? {
("column", column) => {
let mut names: Vec<String> = 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,
}
}
Original file line number Diff line number Diff line change
@@ -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)
}
2 changes: 2 additions & 0 deletions crates/sqlbabel-convert/src/snowflake/conversion/main/mod.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
9 changes: 9 additions & 0 deletions crates/sqlbabel-diagnostics/src/diagnostics/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 12 additions & 5 deletions crates/sqlbabel-diagnostics/src/diagnostics/main/diagnose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -34,6 +35,12 @@ pub fn diagnose(refusals: &[Refusal], source: &str) -> Vec<Diagnostic> {
{
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());
}
Expand Down
8 changes: 7 additions & 1 deletion crates/sqlbabel-semantics/src/schemas/constants.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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 `";
Loading
Loading