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
11 changes: 9 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ PYTHON_TYPED := scripts tests/unit/scripts python/src $(PYTHON_API_TESTS)
PYTHON_TESTS := tests/unit/scripts $(PYTHON_API_TESTS)
endif

.PHONY: distribution-notices format rust-lint python-check fensu syntax-coverage website-figures website-figures-update depth-probe depth-probe-debug instruction-counts instruction-baseline gate-build engine-free bundled-extensions dialect-builds generate-cases generated-cases generate-syntax-cases syntax-obligations syntax-cases dialect-cases dialect-validate corpus-rerecord corpus-verdicts corpus-verdicts-baseline generate-referee-cases referee-cases referee-pending translation-files translation-results help pending check-syntax record-syntax check-convert record-convert sql-sizes sql-size-baseline sql-benchmark check-ci check-merge test test-rust test-python python-build python-module python-api python-wheel verify-recorded verify-changed replay-scope test-crate check-pr-metadata evidence-clone evidence-refresh evidence-pin evidence-pin-check clutter-guard census-duckshop fuzz-smoke gate gate-parallel census duckshop-compiled duckshop-measure
.PHONY: distribution-notices format rust-lint python-check fensu syntax-coverage website-figures website-figures-update website-examples depth-probe depth-probe-debug instruction-counts instruction-baseline gate-build engine-free bundled-extensions dialect-builds generate-cases generated-cases generate-syntax-cases syntax-obligations syntax-cases dialect-cases dialect-validate corpus-rerecord corpus-verdicts corpus-verdicts-baseline generate-referee-cases referee-cases referee-pending translation-files translation-results help pending check-syntax record-syntax check-convert record-convert sql-sizes sql-size-baseline sql-benchmark check-ci check-merge test test-rust test-python python-build python-module python-api python-wheel verify-recorded verify-changed replay-scope test-crate check-pr-metadata evidence-clone evidence-refresh evidence-pin evidence-pin-check clutter-guard census-duckshop fuzz-smoke gate gate-parallel census duckshop-compiled duckshop-measure

format:
cargo fmt --all
Expand Down Expand Up @@ -76,6 +76,13 @@ website-figures website-figures-update: gate-build
$(GATE_DIR)/syntax-coverage summary --evidence $(call syntax_evidence_dir,snowflake) --json > $(SYNTAX_SUMMARY_FILE)
uv run python -m scripts.check_website_figures $(if $(filter website-figures-update,$@),write,check) $(SYNTAX_SUMMARY_FILE)

# Fails when an example the website shows (homepage terminals and docs blocks marked as examples)
# differs from what the built sqlquack prints for its inputs in website/examples, or when a
# terminal or console block names no example.
website-examples: gate-build python-module
PYTHONPATH=$(abspath python/src) LD_LIBRARY_PATH=$(abspath $(PYTHON_PACKAGE)) \
uv run python -m scripts.check_website_examples $(GATE_DIR)/sqlquack

# Fails when a native parser crashes, panics or hangs on deeply nested SQL on a 2 MiB thread and
# coverage/deep-nesting.toml does not list it, or when a listed failure no longer happens.
depth-probe: gate-build
Expand Down Expand Up @@ -249,7 +256,7 @@ referee-pending:
uv run python -m scripts.write_referee_pending $(REFEREE_ARGS)

# The static gate, the first step of `gate`, and the Python API's tests.
check-ci: rust-lint python-check fensu syntax-coverage website-figures depth-probe instruction-counts corpus-verdicts evidence-pin-check clutter-guard engine-free bundled-extensions dialect-builds generated-cases syntax-obligations syntax-cases dialect-cases dialect-validate referee-cases translation-files python-api distribution-notices replay-scope ## The static gate CI runs.
check-ci: rust-lint python-check fensu syntax-coverage website-figures website-examples depth-probe instruction-counts corpus-verdicts evidence-pin-check clutter-guard engine-free bundled-extensions dialect-builds generated-cases syntax-obligations syntax-cases dialect-cases dialect-validate referee-cases translation-files python-api distribution-notices replay-scope ## The static gate CI runs.

# Each distribution ships the licence and third-party notices; its copies must match the root files.
distribution-notices:
Expand Down
336 changes: 168 additions & 168 deletions coverage/sql-size/baseline.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions crates/sqlquack-blocks/src/arrays/main/json_array_written.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ pub fn json_array_written(
log.building_block(JSON_ARRAY_WRITTEN);
let body = match separator {
None => format!(
"('[' || array_to_string(list_transform(a, lambda e: CASE WHEN e IS NULL THEN \
'{UNDEFINED_TEXT}' ELSE {} END), ',') || ']')",
"('[' || coalesce(list_aggr(list_transform(a, lambda e: CASE WHEN e IS NULL THEN \
'{UNDEFINED_TEXT}' ELSE {} END), 'string_agg', ','), '') || ']')",
json_serialized("e", log)
),
Some(separator) => format!(
"(CASE WHEN {separator} IS NULL THEN NULL \
WHEN list_contains(list_transform(a, lambda e: json_type(e)), 'NULL') \
THEN CAST({} AS VARCHAR) \
ELSE array_to_string(list_transform(a, lambda e: \
CASE WHEN e IS NULL THEN '' ELSE {} END), {separator}) END)",
ELSE coalesce(list_aggr(list_transform(a, lambda e: \
CASE WHEN e IS NULL THEN '' ELSE {} END), 'string_agg', {separator}), '') END)",
raised(&tagged_message(
VARIANT_NOT_CAST,
ARRAY_ELEMENT_NOT_TEXT_MESSAGE
Expand Down
45 changes: 28 additions & 17 deletions crates/sqlquack-blocks/src/blocks/_helpers/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,45 @@ use sqlquack_diagnostics::failures::models::SnowflakeCode;
use sqlquack_diagnostics::provenance::models::ProvenanceLog;

use crate::blocks::constants::{
CONVERSION_WHITESPACE, INLINE_ARGUMENT_LIMIT, NUMBER_RANGE_MESSAGE, VARIANT_CAST_MESSAGE,
CONVERSION_WHITESPACE, EXPANSION_SEPARATOR, INLINE_ARGUMENT_LIMIT, NUMBER_RANGE_MESSAGE,
VARIANT_CAST_MESSAGE,
};
use crate::blocks::main::string_literal::string_literal;
use crate::blocks::models::TextFailure;
use crate::raises::main::raised::raised;

/// `sql` with each one-character key of `expansions` spelled as its text, by a single lookup.
/// `sql` with each key of `expansions` replaced by its text, one `replace` per key.
pub(crate) fn replaced(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceLog) -> String {
expansions.iter().fold(sql.to_owned(), |text, (from, to)| {
format!(
"replace({text}, {}, {})",
string_literal(from, log),
string_literal(to, log)
)
})
}

/// `sql` with each key of `expansions` spelled out; list_aggr joins, as array_to_string pastes twice.
pub(crate) fn expanded(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceLog) -> String {
let class: String = expansions
.iter()
.flat_map(|(from, _)| from.chars())
.map(|character| format!("\\x{{{:x}}}", u32::from(character)))
.collect();
let list = |texts: Vec<&str>| {
texts
.into_iter()
.map(|text| string_literal(text, log))
.collect::<Vec<String>>()
.join(", ")
};
let keys = list(expansions.iter().map(|(from, _)| *from).collect());
let values = list(expansions.iter().map(|(_, to)| *to).collect());
format!(
"list_transform([{sql}], lambda case_text: CASE WHEN regexp_matches(case_text, '[{class}]') \
THEN array_to_string(list_transform(string_split(case_text, ''), lambda case_character: \
coalesce([{values}][list_position([{keys}], case_character)], case_character)), '') \
ELSE case_text END)[1]"
)
let keys = string_literal(
&expansions.iter().map(|(from, _)| *from).collect::<String>(),
log,
);
let targets = expansions.iter().map(|(_, to)| *to).collect::<Vec<&str>>();
let targets = string_literal(&targets.join(EXPANSION_SEPARATOR), log);
once_bound(sql, "case_text", |text| {
format!(
"CASE WHEN regexp_matches({text}, '[{class}]') \
THEN list_aggr(list_transform(string_split({text}, ''), lambda case_character: \
coalesce(string_split({targets}, chr(31))[instr({keys}, case_character)], case_character)), 'string_agg', '') \
ELSE {text} END"
)
})
}

/// What a failed conversion yields: NULL when trying, else text's error `code` or a VARIANT's.
Expand Down
4 changes: 4 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))";
/// CONVERSION_WHITESPACE as one literal, binding no calls; pinned macro bodies keep the original.
pub const CONVERSION_WHITESPACE_LITERAL: &str = "E' \\t\\n'";
/// 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.
Expand All @@ -172,6 +174,8 @@ pub const TRUE_WORDS: &[&str] = &["true", "t", "yes", "y", "on", "1"];
pub const FALSE_WORDS: &[&str] = &["false", "f", "no", "n", "off", "0"];
/// DuckDB's largest DECIMAL precision.
pub const MAX_DECIMAL_PRECISION: u8 = 38;
/// What separates the mapped texts in an expansion lookup; `chr(31)` in the emitted SQL.
pub const EXPANSION_SEPARATOR: &str = "\u{1f}";
/// Characters whose full uppercase mapping has several characters.
pub const UPPERCASE_EXPANSIONS: &[(&str, &str)] = &[
("\u{df}", "SS"),
Expand Down
4 changes: 2 additions & 2 deletions crates/sqlquack-blocks/src/blocks/main/full_case_lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

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

use crate::blocks::_helpers::text::expanded;
use crate::blocks::_helpers::text::replaced;
use crate::blocks::constants::{FULL_CASE_MAPPING, LOWERCASE_EXPANSIONS};

/// LOWER with full Unicode case mapping: multi-character mappings first, then DuckDB's lower.
pub fn full_case_lower(sql: &str, log: &ProvenanceLog) -> String {
log.building_block(FULL_CASE_MAPPING);
format!("lower({})", expanded(sql, LOWERCASE_EXPANSIONS, log))
format!("lower({})", replaced(sql, LOWERCASE_EXPANSIONS, log))
}
10 changes: 7 additions & 3 deletions crates/sqlquack-blocks/src/blocks/main/split_text_part.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ use sqlquack_diagnostics::provenance::models::ProvenanceLog;
use crate::blocks::_helpers::text::once_bound;
use crate::blocks::constants::SPLIT_TEXT_PART;

/// The part at `part` (0 read as 1) of `text` split on `delimiter`; long text is bound with both.
/// The part at `part` (0 read as 1, a literal here) of `text` split on `delimiter`; long text bound.
pub fn split_text_part(text: &str, (delimiter, part): (&str, &str), log: &ProvenanceLog) -> String {
log.building_block(SPLIT_TEXT_PART);
let split = |text: &str, delimiter: &str, part: &str| {
format!("split_part({text}, {delimiter}, (CASE WHEN {part} = 0 THEN 1 ELSE {part} END))")
let split = |text: &str, delimiter: &str, part: &str| match part.parse::<i64>() {
Ok(0) => format!("split_part({text}, {delimiter}, 1)"),
Ok(_) => format!("split_part({text}, {delimiter}, {part})"),
Err(_) => format!(
"split_part({text}, {delimiter}, (CASE WHEN {part} = 0 THEN 1 ELSE {part} END))"
),
};
let bound = once_bound(text, "part_text", |name| name.to_owned());
match bound == text {
Expand Down
20 changes: 11 additions & 9 deletions crates/sqlquack-blocks/src/blocks/main/text_to_float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use sqlquack_diagnostics::failures::constants::NUMBER_NOT_RECOGNIZED;
use sqlquack_diagnostics::provenance::models::ProvenanceLog;

use crate::blocks::_helpers::text::{conversion_failure, once_bound, space_trimmed};
use crate::blocks::constants::{DECIMAL_TEXT_PATTERN, NON_FINITE_FLOAT_WORDS, TEXT_TO_FLOAT};
use crate::blocks::constants::{
CONVERSION_WHITESPACE_LITERAL, DECIMAL_TEXT_PATTERN, NON_FINITE_FLOAT_WORDS, TEXT_TO_FLOAT,
};
use crate::blocks::models::TextFailure;

/// Text to a double; special-value words in ASCII only; other unrecorded text fails, or is NULL trying.
Expand All @@ -16,7 +18,7 @@ pub fn text_to_float(sql: &str, failure: TextFailure, log: &ProvenanceLog) -> St
})
}

/// The CASE reading the text `sql` as a double, its trimmed text bound once.
/// The CASE reading the text `sql` as a double, its trimmed text bound once; numbers tested first.
fn read_float(sql: &str, failure: TextFailure) -> String {
let trimmed = "float_trimmed";
let unread = conversion_failure(
Expand All @@ -26,20 +28,20 @@ fn read_float(sql: &str, failure: TextFailure) -> String {
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)"
"WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}') THEN \
(CASE WHEN isinf(CAST({trimmed} AS DOUBLE)) THEN NULL ELSE CAST({trimmed} AS DOUBLE) END) \
WHEN regexp_full_match({trimmed}, '{infinite}') THEN CAST({trimmed} AS DOUBLE)"
),
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)
"(CASE WHEN {sql} IS NULL THEN NULL ELSE list_transform([trim({sql}, \
{CONVERSION_WHITESPACE_LITERAL})], lambda {trimmed}: CASE {finite} \
WHEN regexp_full_match({trimmed}, '(?i:-?nan)') THEN CAST('nan' AS DOUBLE) \
ELSE {unread} END)[1] END)"
)
}

Expand Down
24 changes: 20 additions & 4 deletions crates/sqlquack-blocks/src/macros/_helpers/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::macros::_helpers::temporal::{
timestamp_body, utc_zoned_body, zone_name_body, zoned_body,
};
use crate::macros::_helpers::writing::{
escaped_body, held_written_body, json_text_body, text_body,
escaped_body, held_written_body, json_text_body, json_text_body_v2, text_body, text_body_v2,
};
use crate::macros::constants::{
DATE_TEXT_V1, DECIMAL_QUOTIENT_V1, DIVIDEND_PARAMETER, DIVISOR_PARAMETER, HELPER_CALL_PREFIX,
Expand All @@ -19,13 +19,13 @@ use crate::macros::constants::{
TEXT_PARAMETER, TIME_ZONE_V1, TIMESTAMP_TEXT_V1, TRY_DATE_TEXT_V1, TRY_TIMESTAMP_TEXT_V1,
TRY_UTC_ZONED_TEXT_V1, TRY_ZONED_TEXT_V1, TRYING_PARAMETER, UTC_ZONED_TEXT_V1, VALUE_PARAMETER,
VALUES_PARAMETER, VARIANT_BOOLEAN_V1, VARIANT_DATE_V1, VARIANT_FLOAT_V1, VARIANT_JSON_TEXT_V1,
VARIANT_NUMBER_V1, VARIANT_TEXT_V1, VARIANT_TIMESTAMP_NTZ_V1, VARIANT_WRITTEN_V1,
ZONED_TEXT_V1,
VARIANT_JSON_TEXT_V2, VARIANT_NUMBER_V1, VARIANT_TEXT_V1, VARIANT_TEXT_V2,
VARIANT_TIMESTAMP_NTZ_V1, VARIANT_WRITTEN_V1, ZONED_TEXT_V1,
};
use crate::macros::models::HelperMacro;

/// The helper macros, dependencies first.
pub(crate) fn helper_macros() -> [HelperMacro; 21] {
pub(crate) fn helper_macros() -> [HelperMacro; 23] {
[
HelperMacro {
name: TIME_ZONE_V1,
Expand Down Expand Up @@ -158,6 +158,22 @@ pub(crate) fn helper_macros() -> [HelperMacro; 21] {
object's keys in byte order at every depth. Raises json_fidelity where \
DuckDB could sort the keys only by rewriting a number.",
},
HelperMacro {
name: VARIANT_TEXT_V2,
parameters: &[SITE_PARAMETER, VALUE_PARAMETER],
body: text_body_v2,
explain: "variant_text_v1's result. A number or boolean is written as it is, and \
the text chosen takes Snowflake's escapes once, so DuckDB binds the escape \
once a call, not twice.",
},
HelperMacro {
name: VARIANT_JSON_TEXT_V2,
parameters: &[SITE_PARAMETER, VALUE_PARAMETER],
body: json_text_body_v2,
explain: "variant_json_text_v1's result. A number, boolean or null is written as it \
is, and the text chosen takes Snowflake's escapes once, so DuckDB binds \
the escape once a call, not twice.",
},
HelperMacro {
name: VARIANT_NUMBER_V1,
parameters: &[
Expand Down
53 changes: 47 additions & 6 deletions crates/sqlquack-blocks/src/macros/_helpers/writing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ use crate::semi_structured::constants::{
};
use crate::semi_structured::main::json_escaped::json_escaped;

/// Where the written text takes Snowflake's escapes.
#[derive(Clone, Copy)]
enum Escape {
/// On each text that may be chosen, as the released version-1 macros do.
EachText,
/// Once, on the text chosen: DuckDB pastes the escape's body in at every use.
Chosen,
}

/// The text of `json_value` with every object's keys in byte order, from DuckDB's `VARIANT`.
const RESORTED: &str = "CAST(CAST(CAST(json_value AS VARIANT) AS JSON) AS VARCHAR)";

Expand All @@ -20,15 +29,36 @@ pub(crate) fn text_body() -> String {
"(CASE WHEN json_value IS NULL OR json_type(json_value) = 'NULL' THEN NULL \
WHEN json_type(json_value) = 'VARCHAR' THEN json_extract_string(json_value, '$') \
ELSE {} END)",
sorted()
sorted(Escape::EachText)
))
}

/// A VARIANT as JSON text, JSON null as `null`, as TO_JSON writes it.
pub(crate) fn json_text_body() -> String {
written(&format!(
"(CASE WHEN json_value IS NULL THEN NULL ELSE {} END)",
sorted()
sorted(Escape::EachText)
))
}

/// variant_text_v1's result, a number or boolean written as it is and other values escaped once.
pub(crate) fn text_body_v2() -> String {
written(&format!(
"(CASE WHEN json_value IS NULL OR json_type(json_value) = 'NULL' THEN NULL \
WHEN json_type(json_value) = 'VARCHAR' THEN json_extract_string(json_value, '$') \
WHEN json_type(json_value) NOT IN ('OBJECT', 'ARRAY') THEN CAST(json_value AS VARCHAR) \
ELSE {} END)",
sorted(Escape::Chosen)
))
}

/// variant_json_text_v1's result, a number, boolean or null written as it is, others escaped once.
pub(crate) fn json_text_body_v2() -> String {
written(&format!(
"(CASE WHEN json_value IS NULL THEN NULL \
WHEN json_type(json_value) NOT IN ('OBJECT', 'ARRAY', 'VARCHAR') \
THEN CAST(json_value AS VARCHAR) ELSE {} END)",
sorted(Escape::Chosen)
))
}

Expand Down Expand Up @@ -60,8 +90,11 @@ fn written(body: &str) -> String {
}

/// The JSON text of `json_value`, its objects' keys resorted through DuckDB's VARIANT if needed.
fn sorted() -> String {
let escaped = |sql: &str| helper_call(JSON_ESCAPED_V1, &[sql]);
fn sorted(escape: Escape) -> String {
let escaped = |sql: &str| match escape {
Escape::EachText => helper_call(JSON_ESCAPED_V1, &[sql]),
Escape::Chosen => sql.to_owned(),
};
let resorted = bound(
RESORTED,
"json_resorted",
Expand All @@ -75,7 +108,7 @@ fn sorted() -> String {
escaped("json_resorted"),
),
);
bound(
let chosen = bound(
&format!(
"struct_pack(text := CAST(json_value AS VARCHAR), unsorted := {})",
keys_unsorted("json_value")
Expand All @@ -85,7 +118,15 @@ fn sorted() -> String {
"(CASE WHEN NOT json_written['unsorted'] THEN {} ELSE {resorted} END)",
escaped("json_written['text']"),
),
)
);
match escape {
Escape::EachText => chosen,
Escape::Chosen => bound(
&chosen,
"json_chosen",
&helper_call(JSON_ESCAPED_V1, &["json_chosen"]),
),
}
}

/// The numbers of the JSON text `sql`, outside strings, in byte order.
Expand Down
4 changes: 4 additions & 0 deletions crates/sqlquack-blocks/src/macros/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ pub const JSON_ESCAPED_V1: &str = "json_escaped_v1";
pub const VARIANT_TEXT_V1: &str = "variant_text_v1";
/// A VARIANT as JSON text, as Snowflake writes it.
pub const VARIANT_JSON_TEXT_V1: &str = "variant_json_text_v1";
/// A VARIANT cast to VARCHAR as variant_text_v1 writes it, with one escape a call.
pub const VARIANT_TEXT_V2: &str = "variant_text_v2";
/// A VARIANT as JSON text as variant_json_text_v1 writes it, with one escape a call.
pub const VARIANT_JSON_TEXT_V2: &str = "variant_json_text_v2";
/// A VARIANT cast to a NUMBER.
pub const VARIANT_NUMBER_V1: &str = "variant_number_v1";
/// A VARIANT cast to FLOAT.
Expand Down
Loading
Loading