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
4,062 changes: 2,031 additions & 2,031 deletions coverage/sql-size/baseline.json

Large diffs are not rendered by default.

36 changes: 16 additions & 20 deletions crates/sqlquack-blocks/src/blocks/_helpers/division.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,17 @@ pub(crate) fn null_checks(left_sql: &str, right_sql: &str, constant: bool) -> St
}
}

/// The integer quotient `rounded` at the result scale, as the result type.
/// The integer quotient in units of `places` decimal places as the result type, rounding any spare.
pub(crate) fn scaled(
rounded: &str,
(result, result_scale): (SnowflakeType, u8),
quotient: &str,
(result, places): (SnowflakeType, u8),
log: &ProvenanceLog,
) -> Result<String, String> {
match result_scale {
0 => cast(rounded, result, log),
match places {
0 => cast(quotient, result, log),
scale => cast(
&format!(
"CAST({rounded} AS DECIMAL(38,0)) * 0.{}1",
"CAST({quotient} AS DECIMAL(38,0)) * 0.{}1",
"0".repeat(usize::from(scale) - 1)
),
result,
Expand All @@ -44,12 +44,12 @@ pub(crate) fn scaled(
}
}

/// The quotient in units of the result scale when the scaled dividend fits 128 bits; else `None`.
/// The quotient and the places it is in units of, one spare when rounding, if it fits 128 bits.
pub(crate) fn short_quotient(
(left, right): (Operand<'_>, Operand<'_>),
(result_scale, truncated): (u8, bool),
constant: Option<u128>,
) -> Option<String> {
) -> Option<(String, u8)> {
let (_, left_precision, left_scale) = left;
let (_, right_precision, right_scale) = right;
let shift = (result_scale + right_scale).checked_sub(left_scale)?;
Expand All @@ -62,8 +62,9 @@ pub(crate) fn short_quotient(
&& fits_unscaled(right_precision, right_scale)
&& digits <= room;
let doubles = digits <= SHORT_FORM_DIGITS && usize::from(right_precision) <= SHORT_FORM_DIGITS;
let spare = !truncated && (constant.is_some() || doubles);
fits.then(|| {
once_bound(
let quotient = once_bound(
&unscaled(left, left_scale + shift),
"quotient_dividend",
|n| match constant {
Expand All @@ -72,7 +73,8 @@ pub(crate) fn short_quotient(
column_quotient(n, d, (truncated, doubles))
}),
},
)
);
(quotient, result_scale + u8::from(spare))
})
}

Expand Down Expand Up @@ -137,25 +139,19 @@ pub(crate) fn unscaled_literal(text: &str, scale: u8) -> Option<u128> {
)
}

/// The scaled dividend `n` over a known non-zero divisor, rounded half away from zero or truncated.
/// The scaled dividend `n` over a known non-zero divisor, truncated or with one place spare.
fn constant_quotient(n: &str, divisor: u128, truncated: bool) -> String {
match truncated {
true => format!("({n} // {})", integer(divisor)),
false => format!(
"(sign({n}) * ((2 * abs({n}) + {}) // {}))",
integer(divisor),
integer(2 * divisor)
),
false => format!("(({n} * 10) // {})", integer(divisor)),
}
}

/// The scaled dividend `n` over the divisor `d`, doubling to round when both leave a digit spare.
/// The scaled dividend `n` over the divisor `d`, with one place spare when both leave a digit.
fn column_quotient(n: &str, d: &str, (truncated, doubles): (bool, bool)) -> String {
match (truncated, doubles) {
(true, _) => format!("({n} // {d})"),
(false, true) => {
format!("(sign({n}) * sign({d}) * ((2 * abs({n}) + abs({d})) // (2 * abs({d}))))")
}
(false, true) => format!("(({n} * 10) // {d})"),
(false, false) => format!(
"({n} // {d} + (CASE WHEN abs({n} % {d}) >= abs({d}) - abs({n} % {d}) \
THEN sign({n}) * sign({d}) ELSE 0 END))"
Expand Down
24 changes: 23 additions & 1 deletion crates/sqlquack-blocks/src/blocks/_helpers/numbers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,29 @@ pub(crate) fn largest_number(precision: u8, scale: u8) -> String {
}
}

/// The CASE reading the text `sql` as `target`, accepting only spellings Snowflake reads.
/// The CASE reading the text `sql` as `target` in the spellings Snowflake reads, trimmed once.
pub(crate) fn read_trimmed_number(sql: &str, target: &NumberTarget) -> String {
let wrapped =
|(before, after): &(String, String), value: &str| format!("{before}{value}{after}");
let trimmed = "number_trimmed";
let overflow = &target.overflow;
format!(
"(CASE WHEN {sql} IS NULL THEN NULL ELSE list_transform([{}], lambda {trimmed}: \
CASE WHEN regexp_matches({trimmed}, '[eE]') AND abs({}) > {largest} THEN {overflow} \
WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}|{BARE_EXPONENT_PATTERN}') \
THEN coalesce({}, {overflow}) \
WHEN regexp_full_match({trimmed}, '{MANTISSA_FREE_PATTERN}') THEN {} \
ELSE {} END)[1] END)",
space_trimmed(sql),
wrapped(&target.try_cast, trimmed),
wrapped(&target.try_cast, &format!("rtrim({trimmed}, 'eE')")),
wrapped(&target.cast, "0"),
target.unrecognised,
largest = target.largest,
)
}

/// The CASE reading the text `sql` as `target` in released variant_number_v1, whose body is pinned.
pub(crate) fn read_number_as(sql: &str, target: &NumberTarget) -> String {
let wrapped =
|(before, after): &(String, String), value: &str| format!("{before}{value}{after}");
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlquack-blocks/src/blocks/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ pub const MANTISSA_FREE_PATTERN: &str = "[eE][+-]?[0-9]+";
pub const INLINE_ARGUMENT_LIMIT: usize = 256;
/// Whitespace conversions ignore around a value (space, tab, line feed; not no-break space).
pub const CONVERSION_WHITESPACE: &str = "(' ' || chr(9) || chr(10))";
/// The characters of CONVERSION_WHITESPACE, for trimming a literal at compile time.
pub const CONVERSION_WHITESPACE_CHARS: [char; 3] = [' ', '\t', '\n'];
/// Words Snowflake reads as a non-finite FLOAT, lower-cased, with their DuckDB spelling.
pub const NON_FINITE_FLOAT_WORDS: &[(&str, &str)] = &[
("nan", "nan"),
Expand Down
22 changes: 12 additions & 10 deletions crates/sqlquack-blocks/src/blocks/main/exact_decimal_divide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ use crate::blocks::_helpers::division::{
long_quotient, null_checks, scaled, short_quotient, unscaled_literal,
};
use crate::blocks::constants::EXACT_DECIMAL_DIVIDE;
use crate::blocks::models::Divisor;

/// Exact division, rounded or `truncated`, by a literal `constant` divisor if given; may it raise?
/// Exact division, rounded or `truncated`, by the right operand as `divisor`; may it raise?
pub fn exact_decimal_divide(
left: (&str, u8, u8),
right: (&str, u8, u8),
(result, truncated, constant): (SnowflakeType, bool, Option<&str>),
(result, truncated, divisor): (SnowflakeType, bool, Divisor<'_>),
log: &ProvenanceLog,
) -> Result<(String, bool), String> {
log.building_block(EXACT_DECIMAL_DIVIDE);
Expand All @@ -25,17 +26,18 @@ pub fn exact_decimal_divide(
"exact division needs a NUMBER result, not {result}"
));
};
let constant = constant
.and_then(|text| unscaled_literal(text, right.2))
.filter(|divisor| *divisor != 0);
let constant = match divisor {
Divisor::Literal(text) => unscaled_literal(text, right.2).filter(|value| *value != 0),
Divisor::Checked | Divisor::Guarded => None,
};
let checks = null_checks(left.0, right.0, constant.is_some());
let rounding = (result_scale, truncated);
if let Some(quotient) = short_quotient((left, right), rounding, constant) {
let value = scaled(&quotient, (result, result_scale), log)?;
if let Some((quotient, places)) = short_quotient((left, right), rounding, constant) {
let value = scaled(&quotient, (result, places), log)?;
return Ok((
match constant {
Some(_) => value,
None => format!("(CASE {checks} ELSE {value} END)"),
match constant.is_none() && divisor != Divisor::Guarded {
false => value,
true => format!("(CASE {checks} ELSE {value} END)"),
},
false,
));
Expand Down
44 changes: 34 additions & 10 deletions crates/sqlquack-blocks/src/blocks/main/text_to_float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,46 @@ use crate::blocks::models::TextFailure;
/// Text to a double; special-value words in ASCII only; other unrecorded text fails, or is NULL trying.
pub fn text_to_float(sql: &str, failure: TextFailure, log: &ProvenanceLog) -> String {
log.building_block(TEXT_TO_FLOAT);
once_bound(sql, "float_text", |sql| read_float(sql, failure))
once_bound(sql, "float_text", |sql| match failure {
TextFailure::Variant => released_read_float(sql),
TextFailure::Text | TextFailure::Null => read_float(sql, failure),
})
}

/// The CASE reading the text `sql` as a double.
/// The CASE reading the text `sql` as a double, its trimmed text bound once.
fn read_float(sql: &str, failure: TextFailure) -> String {
let trimmed = "float_trimmed";
let unread = conversion_failure(
failure,
(NUMBER_NOT_RECOGNIZED, "Numeric value is not recognized"),
);
let infinite = "(?i:[+-]?inf|-?infinity)";
let finite = match failure {
TextFailure::Null | TextFailure::Variant => format!(
"WHEN regexp_full_match({trimmed}, '{infinite}') THEN CAST({trimmed} AS DOUBLE) \
WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}') THEN \
(CASE WHEN isinf(CAST({trimmed} AS DOUBLE)) THEN NULL ELSE CAST({trimmed} AS DOUBLE) END)"
),
TextFailure::Text => format!(
"WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}|{infinite}') \
THEN CAST({trimmed} AS DOUBLE)"
),
};
format!(
"(CASE WHEN {sql} IS NULL THEN NULL ELSE list_transform([{}], lambda {trimmed}: \
CASE WHEN regexp_full_match({trimmed}, '(?i:-?nan)') THEN CAST('nan' AS DOUBLE) \
{finite} ELSE {unread} END)[1] END)",
space_trimmed(sql)
)
}

/// The CASE reading the text `sql` as a double in released variant_float_v1, whose body is pinned.
fn released_read_float(sql: &str) -> String {
let trimmed = space_trimmed(sql);
let unread = format!(
"CAST({} AS DOUBLE)",
conversion_failure(
failure,
TextFailure::Variant,
(NUMBER_NOT_RECOGNIZED, "Numeric value is not recognized")
)
);
Expand All @@ -32,15 +62,9 @@ fn read_float(sql: &str, failure: TextFailure) -> String {
)
})
.collect();
let overflow = match failure {
TextFailure::Null => format!(
"(CASE WHEN isinf(CAST({trimmed} AS DOUBLE)) THEN {unread} ELSE CAST({trimmed} AS DOUBLE) END)"
),
TextFailure::Text | TextFailure::Variant => format!("CAST({trimmed} AS DOUBLE)"),
};
format!(
"(CASE WHEN {sql} IS NULL THEN NULL{words} \
WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}') THEN {overflow} \
WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}') THEN CAST({trimmed} AS DOUBLE) \
ELSE {unread} END)"
)
}
15 changes: 6 additions & 9 deletions crates/sqlquack-blocks/src/blocks/main/text_to_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use sqlquack_diagnostics::failures::constants::NUMBER_NOT_RECOGNIZED;
use sqlquack_diagnostics::provenance::models::ProvenanceLog;
use sqlquack_semantics::snowflake::typing::models::SnowflakeType;

use crate::blocks::_helpers::numbers::{largest_number, read_number_as};
use crate::blocks::_helpers::numbers::{largest_number, read_number_as, read_trimmed_number};
use crate::blocks::_helpers::text::{conversion_failure, once_bound, overflow_failure};
use crate::blocks::_helpers::types_map::duckdb_type;
use crate::blocks::constants::TEXT_TO_NUMBER;
Expand Down Expand Up @@ -39,19 +39,16 @@ fn read_number(
failure: TextFailure,
) -> String {
let largest = largest_number(precision, scale);
read_number_as(
read_trimmed_number(
sql,
&NumberTarget {
cast: ("CAST(".to_owned(), format!(" AS {target})")),
try_cast: ("TRY_CAST(".to_owned(), format!(" AS {target})")),
largest: format!("CAST('{largest}' AS {target})"),
overflow: format!("CAST({} AS {target})", overflow_failure(failure)),
unrecognised: format!(
"CAST({} AS {target})",
conversion_failure(
failure,
(NUMBER_NOT_RECOGNIZED, "Numeric value is not recognized")
)
overflow: overflow_failure(failure),
unrecognised: conversion_failure(
failure,
(NUMBER_NOT_RECOGNIZED, "Numeric value is not recognized"),
),
},
)
Expand Down
11 changes: 11 additions & 0 deletions crates/sqlquack-blocks/src/blocks/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,14 @@ pub struct NumberTarget {
/// What text Snowflake does not read as a number yields.
pub unrecognised: String,
}

/// The divisor of an exact decimal division.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Divisor<'a> {
/// One that may be NULL or zero.
Checked,
/// A literal number, by its text.
Literal(&'a str),
/// One whose caller already makes the quotient NULL where an operand is NULL or it is zero.
Guarded,
}
4 changes: 2 additions & 2 deletions crates/sqlquack-blocks/src/floats/_helpers/sums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub(crate) fn aggregated_sum(value: &str, distinct: &str, over: &str, raise: &st
WHEN bool_or(isnan({value})){over} THEN CAST('nan' AS DOUBLE) \
WHEN count({value}){over} <= 2 OR {} OR {dominant} \
THEN sum({distinct}{value}){over} \
+ 0.0 ELSE CAST({raise} AS DOUBLE) END)",
+ 0.0 ELSE {raise} END)",
exact.join(" OR "),
)
}
Expand Down Expand Up @@ -56,7 +56,7 @@ pub(crate) fn listed_sum(value: &str, distinct: bool, over: &str, raise: &str) -
lambda float_sum_values: CASE WHEN len(float_sum_values) = 0 THEN NULL \
WHEN list_bool_or({}) THEN CAST('nan' AS DOUBLE) \
WHEN len(float_sum_values) <= 2 OR {} OR {} THEN list_sum({summed}) + 0.0 \
ELSE CAST({raise} AS DOUBLE) END)[1]",
ELSE {raise} END)[1]",
each("isnan(float_sum_x)"),
exact.join(" OR "),
dominant(
Expand Down
46 changes: 46 additions & 0 deletions crates/sqlquack-blocks/src/floats/main/float_literal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//! `float_literal`: a text literal cast to FLOAT, folded to the double it converts to.

use sqlquack_diagnostics::provenance::models::ProvenanceLog;

use crate::blocks::constants::{
CONVERSION_WHITESPACE_CHARS, NON_FINITE_FLOAT_WORDS, TEXT_TO_FLOAT,
};

/// The double the text converts to as text_to_float reads it; `None` when that fails or overflows.
pub fn float_literal(text: &str, log: &ProvenanceLog) -> Option<String> {
let trimmed = text.trim_matches(CONVERSION_WHITESPACE_CHARS);
let lower = trimmed.to_ascii_lowercase();
let word = NON_FINITE_FLOAT_WORDS
.iter()
.find(|(word, _)| trimmed.is_ascii() && *word == lower)
.map(|(_, duckdb)| *duckdb);
let value = match word {
Some(duckdb) => duckdb,
None if is_decimal_text(trimmed) && trimmed.parse::<f64>().is_ok_and(f64::is_finite) => {
trimmed
}
None => return None,
};
log.building_block(TEXT_TO_FLOAT);
Some(format!("CAST('{value}' AS DOUBLE)"))
}

/// Whether `text` is all of DECIMAL_TEXT_PATTERN: a signed mantissa with an optional exponent.
fn is_decimal_text(text: &str) -> bool {
let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
let unsigned = text.strip_prefix(['+', '-']).unwrap_or(text);
let (mantissa, exponent) = match unsigned.split_once(['e', 'E']) {
Some((mantissa, exponent)) => (mantissa, Some(exponent)),
None => (unsigned, None),
};
let mantissa_ok = match mantissa.split_once('.') {
Some((whole, fraction)) => {
(digits(whole) && (fraction.is_empty() || digits(fraction)))
|| (whole.is_empty() && digits(fraction))
}
None => digits(mantissa),
};
mantissa_ok
&& exponent
.is_none_or(|exponent| digits(exponent.strip_prefix(['+', '-']).unwrap_or(exponent)))
}
23 changes: 9 additions & 14 deletions crates/sqlquack-blocks/src/floats/main/float_to_decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,18 @@ pub fn float_to_decimal(
ELSE (2 * {significand} * CAST({unit} AS HUGEINT) + (CAST(1 AS HUGEINT) << {shift})) \
// (CAST(1 AS HUGEINT) << ({shift} + 1)) END)"
);
let overflow = format!(
"CAST({} AS {target})",
raised(&tagged_message(NUMBER_OUT_OF_RANGE, NUMBER_RANGE_MESSAGE))
);
let unproven = format!(
"CAST({} AS {target})",
raised(&format!(
"{FLOAT_DECIMAL_DIGITS}: a FLOAT rounded to more significant digits than recordings show"
))
);
let overflow = raised(&tagged_message(NUMBER_OUT_OF_RANGE, NUMBER_RANGE_MESSAGE));
let unproven = raised(&format!(
"{FLOAT_DECIMAL_DIGITS}: a FLOAT rounded to more significant digits than recordings show"
));
let body = format!(
"(CASE WHEN {sql} IS NULL THEN NULL \
WHEN isnan({sql}) OR isinf({sql}) OR {magnitude} >= 1e{whole} THEN {overflow} \
WHEN {units} >= CAST({limit} AS HUGEINT) THEN {overflow} \
WHEN {units} >= CAST({FLOAT_DECIMAL_UNITS_LIMIT} AS HUGEINT) THEN {unproven} \
ELSE CAST(CAST(CASE WHEN {sql} < 0 THEN -{units} ELSE {units} END AS DECIMAL(38,0)) \
* CAST('1e-{scale}' AS DECIMAL(38,{scale})) AS {target}) END)",
ELSE list_transform([{units}], lambda float_units: \
CASE WHEN float_units >= CAST({limit} AS HUGEINT) THEN {overflow} \
WHEN float_units >= CAST({FLOAT_DECIMAL_UNITS_LIMIT} AS HUGEINT) THEN {unproven} \
ELSE CAST(CAST(CASE WHEN {sql} < 0 THEN -float_units ELSE float_units END AS DECIMAL(38,0)) \
* CAST('1e-{scale}' AS DECIMAL(38,{scale})) AS {target}) END)[1] END)",
whole = precision - scale
);
Ok(bound(value, sql, &body))
Expand Down
1 change: 1 addition & 0 deletions crates/sqlquack-blocks/src/floats/main/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

pub mod exact_float_sum;
pub mod exponential;
pub mod float_literal;
pub mod float_to_decimal;
pub mod float_to_text;
pub mod natural_logarithm;
Expand Down
Loading
Loading