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
18,756 changes: 9,378 additions & 9,378 deletions coverage/sql-size/baseline.json

Large diffs are not rendered by default.

16 changes: 14 additions & 2 deletions crates/sqlquack-blocks/src/floats/_helpers/sums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ pub(crate) fn aggregated_sum(value: &str, distinct: &str, over: &str, raise: &st

/// The sum from one list of the values, so a long `value` is written once.
pub(crate) fn listed_sum(value: &str, distinct: bool, over: &str, raise: &str) -> String {
values_sum(&listed_values(value, over), distinct, raise)
}

/// The list of a group's non-NULL `value`s as doubles.
pub(crate) fn listed_values(value: &str, over: &str) -> String {
format!(
"list_filter(coalesce(list(CAST({value} AS DOUBLE)){over}, \
CAST([] AS DOUBLE[])), lambda float_sum_x: float_sum_x IS NOT NULL)"
)
}

/// The sum of the list `values`, which holds no NULL.
pub(crate) fn values_sum(values: &str, distinct: bool, raise: &str) -> String {
let each = |body: &str| format!("list_transform(float_sum_values, lambda float_sum_x: {body})");
let exact: Vec<String> = EXACT_SUM_SCALES
.iter()
Expand All @@ -51,8 +64,7 @@ pub(crate) fn listed_sum(value: &str, distinct: bool, over: &str, raise: &str) -
false => "float_sum_values",
};
format!(
"list_transform([list_filter(coalesce(list(CAST({value} AS DOUBLE)){over}, \
CAST([] AS DOUBLE[])), lambda float_sum_x: float_sum_x IS NOT NULL)], \
"list_transform([{values}], \
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 \
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlquack-blocks/src/floats/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,5 @@ pub const POWER_OF_TEN: &str = "duckdb.power_of_ten";
pub const EXPONENTIAL: &str = "duckdb.exponential";
/// SQRT, a negative number raising: `duckdb.square_root`.
pub const SQUARE_ROOT: &str = "duckdb.square_root";
/// The lambda parameter holding a group's non-NULL FLOAT values, listed once for its moments.
pub const FLOAT_MOMENT_VALUES: &str = "float_moment_values";
32 changes: 32 additions & 0 deletions crates/sqlquack-blocks/src/floats/main/exact_float_moments.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//! `exact_float_moments`: a group's count, exact FLOAT sum and exact sum of squares, the values listed once.

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

use crate::floats::_helpers::sums::{listed_values, values_sum};
use crate::floats::constants::{EXACT_FLOAT_SUM, FLOAT_MOMENT_VALUES, FLOAT_SUM_ORDER};
use crate::raises::main::raised::raised;

/// `body(count, total, squares)` over `value`'s group, `value` written once; each sum raises as `exact_float_sum`'s.
pub fn exact_float_moments(
value: &str,
over: &str,
body: impl FnOnce(&str, &str, &str) -> String,
log: &ProvenanceLog,
) -> String {
log.building_block(EXACT_FLOAT_SUM);
let raise = raised(&format!(
"{FLOAT_SUM_ORDER}: a FLOAT sum whose value depends on the order of addition"
));
let squares = format!(
"list_transform({FLOAT_MOMENT_VALUES}, lambda float_moment_x: float_moment_x * float_moment_x)"
);
format!(
"list_transform([{}], lambda {FLOAT_MOMENT_VALUES}: {})[1]",
listed_values(value, over),
body(
&format!("len({FLOAT_MOMENT_VALUES})"),
&values_sum(FLOAT_MOMENT_VALUES, false, &raise),
&values_sum(&squares, false, &raise)
)
)
}
1 change: 1 addition & 0 deletions crates/sqlquack-blocks/src/floats/main/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! One building block per module.

pub mod exact_float_moments;
pub mod exact_float_sum;
pub mod exponential;
pub mod float_literal;
Expand Down
1 change: 1 addition & 0 deletions crates/sqlquack-blocks/src/semi_structured/_helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
pub(crate) mod guards;
pub(crate) mod lambdas;
pub(crate) mod paths;
pub(crate) mod plain_json;
pub(crate) mod writing;
184 changes: 184 additions & 0 deletions crates/sqlquack-blocks/src/semi_structured/_helpers/plain_json.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
//! Whether a JSON literal is one `json_checked_v1`'s fast check reads as it is, checked in Rust.

use std::collections::HashSet;

/// The deepest nesting checked; deeper text keeps the macro call.
const DEEPEST: usize = 64;
/// The most digits of a whole number the fast check clears, so no number leaves 64 bits.
const WHOLE_DIGITS: usize = 18;
/// The most digits before a decimal point the fast check clears.
const INTEGER_DIGITS: usize = 9;
/// The most digits after a decimal point the fast check clears.
const FRACTION_DIGITS: usize = 5;

/// Whether `text` is JSON `json_checked_v1`'s fast check reads as it is, read more strictly: no key escaped or repeated.
pub(crate) fn plain_json(text: &str) -> bool {
let mut reader = Reader {
bytes: text.as_bytes(),
at: 0,
};
reader.blank();
let read = reader.value(0);
reader.blank();
read && reader.at == reader.bytes.len()
}

struct Reader<'a> {
bytes: &'a [u8],
at: usize,
}

impl<'a> Reader<'a> {
fn peek(&self) -> Option<u8> {
self.bytes.get(self.at).copied()
}

fn taken(&mut self, byte: u8) -> bool {
let found = self.peek() == Some(byte);
self.at += usize::from(found);
found
}

fn blank(&mut self) {
while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
self.at += 1;
}
}

fn value(&mut self, depth: usize) -> bool {
match self.peek() {
_ if depth > DEEPEST => false,
Some(b'{') => self.object(depth),
Some(b'[') => self.array(depth),
Some(b'"') => self.string().is_some(),
Some(b'-' | b'0'..=b'9') => self.number(),
Some(_) => ["true", "false", "null"].iter().any(|word| self.word(word)),
None => false,
}
}

fn word(&mut self, word: &str) -> bool {
let found = self.bytes[self.at..].starts_with(word.as_bytes());
self.at += if found { word.len() } else { 0 };
found
}

fn object(&mut self, depth: usize) -> bool {
self.at += 1;
self.blank();
if self.taken(b'}') {
return true;
}
let mut keys: HashSet<&'a [u8]> = HashSet::new();
loop {
self.blank();
let Some(key) = self.string() else {
return false;
};
if key.contains(&b'\\') || !keys.insert(key) {
return false;
}
self.blank();
if !self.taken(b':') {
return false;
}
self.blank();
if !self.value(depth + 1) {
return false;
}
self.blank();
if self.taken(b'}') {
return true;
}
if !self.taken(b',') {
return false;
}
}
}

fn array(&mut self, depth: usize) -> bool {
self.at += 1;
self.blank();
if self.taken(b']') {
return true;
}
loop {
self.blank();
if !self.value(depth + 1) {
return false;
}
self.blank();
if self.taken(b']') {
return true;
}
if !self.taken(b',') {
return false;
}
}
}

/// A string without a raw control character, an escaped backslash or a UTF-16 surrogate escape; its bytes inside the quotes.
fn string(&mut self) -> Option<&'a [u8]> {
if !self.taken(b'"') {
return None;
}
let start = self.at;
loop {
let byte = self.peek()?;
self.at += 1;
match byte {
b'"' => return Some(&self.bytes[start..self.at - 1]),
0x00..=0x1f => return None,
b'\\' => {
let escaped = self.peek()?;
self.at += 1;
match escaped {
b'"' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {}
b'u' => {
let digits = self.bytes.get(self.at..self.at + 4)?;
let surrogate = matches!(digits[0], b'd' | b'D')
&& !matches!(digits[1], b'0'..=b'7');
if surrogate || !digits.iter().all(u8::is_ascii_hexdigit) {
return None;
}
self.at += 4;
}
_ => return None,
}
}
_ => {}
}
}
}

fn number(&mut self) -> bool {
let start = self.at;
while matches!(
self.peek(),
Some(b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9')
) {
self.at += 1;
}
plain_number(&self.bytes[start..self.at])
}
}

/// A whole number of up to 18 digits but -0, or a decimal of up to 9 + 5 digits not all zero after the point.
fn plain_number(token: &[u8]) -> bool {
let unsigned = token.strip_prefix(b"-").unwrap_or(token);
let digits = |part: &[u8]| !part.is_empty() && part.iter().all(u8::is_ascii_digit);
let leading = |part: &[u8], most: usize| {
digits(part) && part.len() <= most && (part == b"0" || part[0] != b'0')
};
match unsigned.iter().position(|byte| *byte == b'.') {
None if unsigned == b"0" => unsigned.len() == token.len(),
None => leading(unsigned, WHOLE_DIGITS) && unsigned[0] != b'0',
Some(point) => {
let (whole, fraction) = (&unsigned[..point], &unsigned[point + 1..]);
leading(whole, INTEGER_DIGITS)
&& digits(fraction)
&& fraction.len() <= FRACTION_DIGITS
&& fraction.iter().any(|byte| *byte != b'0')
}
}
}
20 changes: 19 additions & 1 deletion crates/sqlquack-blocks/src/semi_structured/main/json_guarded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@ use crate::macros::constants::JSON_CHECKED_V1;
use crate::macros::main::helper_call::helper_call;
use crate::raises::constants::UNIDENTIFIED_SITE;
use crate::semi_structured::_helpers::paths::{path_list, plain_step, scoped_paths};
use crate::semi_structured::_helpers::plain_json::plain_json;
use crate::semi_structured::constants::JSON_GUARDED;
use crate::semi_structured::models::PathStep;

/// Text as DuckDB `JSON`, raising where read differently; only `reads`' paths are checked for repeats.
/// Text as DuckDB `JSON`, raising where read differently, a literal the fast check clears read by `json`; only `reads`' paths are checked for repeats.
pub fn json_guarded(
sql: &str,
trying: bool,
reads: Option<&[Vec<PathStep>]>,
log: &ProvenanceLog,
) -> String {
log.building_block(JSON_GUARDED);
if literal_text(sql).is_some_and(|text| plain_json(&text)) {
return format!("json({sql})");
}
let (objects, values) = match reads {
Some(paths) if paths.iter().flatten().all(plain_step) => scoped_paths(paths),
_ => (Vec::new(), vec!["$".to_owned()]),
Expand All @@ -32,3 +36,17 @@ pub fn json_guarded(
],
)
}

/// The text of the single-quoted literal `sql`, its doubled quotes undone; `None` for other SQL.
fn literal_text(sql: &str) -> Option<String> {
let inner = sql.strip_prefix('\'')?.strip_suffix('\'')?;
let mut text = String::with_capacity(inner.len());
let mut characters = inner.chars();
while let Some(character) = characters.next() {
if character == '\'' && characters.next() != Some('\'') {
return None;
}
text.push(character);
}
Some(text)
}
2 changes: 2 additions & 0 deletions crates/sqlquack-blocks/src/semi_structured/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#[path = "tests/helpers.rs"]
mod helpers;
#[path = "tests/test_folded_literals.rs"]
mod test_folded_literals;
#[path = "tests/test_sorted_text.rs"]
mod test_sorted_text;
#[path = "tests/test_try_guarded.rs"]
Expand Down
Loading
Loading