diff --git a/Makefile b/Makefile index 37590b2850..39646b2f97 100644 --- a/Makefile +++ b/Makefile @@ -245,6 +245,7 @@ E2E_DUCKDB_CLI_PATHS := \ tests/e2e/src/sqlbuild/cli/commands/main/debug \ tests/e2e/src/sqlbuild/cli/commands/main/format/test_description_layout.py \ tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_cache.py \ + tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_convergence.py \ tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_example_projects.py \ tests/e2e/src/sqlbuild/cli/commands/main/format/test_rule_fixes.py \ tests/e2e/src/sqlbuild/cli/commands/main/format/test_token_preservation.py \ diff --git a/benchmarks/duckshop/README.md b/benchmarks/duckshop/README.md index e58c0b5f9a..a4c1da2bd8 100644 --- a/benchmarks/duckshop/README.md +++ b/benchmarks/duckshop/README.md @@ -133,7 +133,7 @@ function, a hook-created JavaScript function, 200 unit tests and 5 scenarios, in | Ordering through arrays | an unordered `ARRAY_AGG` ranked under `LIMIT` by position, by name, through `IFF` and over `UNION ALL`, with fixtures whose pick does not depend on element order; order-free reads (`ARRAY_SIZE`, `ARRAY_CONTAINS`, `ARRAYS_OVERLAP`, `ARRAY_DISTINCT` of `ARRAY_CAT`, `FLATTEN` values through a CTE); `SELECT DISTINCT` over arrays repeated in different orders; `ARRAY_APPEND`, `ARRAY_INTERSECTION`, `ARRAY_SLICE` with negative bounds, `TO_ARRAY` and bracket array literals | | VARIANT comparisons | `ARRAY_MAX`, `ARRAY_MIN` and `ARRAY_REVERSE` over arrays mixing numbers, strings, booleans, JSON nulls and integers past 2^53; `MAX` across kinds and non-ASCII strings; `=` and `EQUAL_NULL` for `1`, `"1"` and `1.0`, reordered keys, JSON null and DATE or TIMESTAMP values held in a `VARIANT` against their text; `MIN_BY` and `MAX_BY` of `VARIANT` values; `PARTITION BY`, `SELECT DISTINCT` and `ARRAY_AGG(DISTINCT)` over `VARIANT`; JSON nulls in `ARRAY_REMOVE`, `ARRAY_DISTINCT` and `ARRAYS_OVERLAP`; decimals with trailing zeros in `ARRAY_CONTAINS` and `ARRAY_POSITION`; `OBJECT_CONSTRUCT(* EXCLUDE ("note"))` | | Dates and times | `TRY_TO_TIMESTAMP_NTZ` and its siblings over free text; epoch milliseconds as numbers and text; daylight-saving gaps and overlaps; fractional offsets; nanosecond truncation and epoch parts after 2242; pre-1970 text with sub-microsecond digits; date-part normalisation; month ends and leap days; week numbering across a year; sentinel timestamps; `DATEADD` past the end of a test's open cursor window, in a chained test whose upstream step lists some of its columns; a cursor window that touches no row, expected as an empty fixture; `TRY_TO_DATE` with numeric and month-name formats over unpadded fields, two-digit years, ISO `T` and `Z`, trailing letters, a long s, mixed separators and runs of spaces; text read as `TIMESTAMP_TZ` and `TIMESTAMP_LTZ` with `T`, `Z`, `+00:00`, `+0000`, `+09:00` and `-05:30`, back as the UTC instant, date, year and day start, and compared with text, `TIMESTAMP_NTZ` and `DATE`; `FIRST_VALUE` of a zoned value as a `DATE`; `DATEADD` and `TIMEADD` on `TIME(3)` and the type they return; `DATEDIFF` across units; `TIME(9)`, `FF3` and bare `FF` formats truncating; `DATE`, `TO_TIME`, `TRY_TO_TIMESTAMP` and `TO_TIMESTAMP_LTZ` of clock text, and `CURRENT_DATE` and `SYSDATE` read only for facts that hold on any day | -| Ordering, numbers and text | NULL ordering under `DESC`; ties in ordered aggregates, `MAX_BY`, `MODE` and `ANY_VALUE`; default window frames; `UNION ALL BY NAME`; `ROUND` half-way values, decimal division, `MOD` and 38-digit amounts; integers past 2^53 against `FLOAT`; regular expressions and backslash escapes, and a scoped SQL macro collapsing whitespace whose body opens with a block comment and holds a line comment; `LIKE ... ESCAPE` and `ILIKE ANY`; `SPLIT_PART` and `SUBSTR` before the start; `NOT IN` with a NULL; names in many scripts; `JOIN ... USING` between `NUMBER(18,0)`, `NUMBER(38,0)` and text keys, with the types of the merged and qualified keys; NULL arithmetic and the types of NULL, decimal and exponent literals, `COUNT`, `ROW_NUMBER`, `%` and `NULLIF`; `MEDIAN` at scales 0 to 15; `DIV0` by literal zeros; `MODE`, `MEDIAN` and `COUNT_IF` over no rows; aggregates inside window functions and `QUALIFY`; `ROLLUP` totals; `TRUNC` of `FLOAT`; infinity words in other scripts; `CASE` without `ELSE` and `DECODE` over text; regular expressions with a `?` after a lazy quantifier, classes opening with `]`, empty matches and `.` against a carriage return; case-insensitive matches outside ASCII; `ILIKE` with a long s; `JAROWINKLER_SIMILARITY` of accented names in both cases; Base64 text with line feeds; `STARTSWITH`, `ENDSWITH`, `SUBSTRING`, `POSITION` with `IN` and with a comma, `CHARINDEX`, `CHR`, `REGEXP_SUBSTR_ALL`, `::STRING` and `CAST ... AS STRING`; `HEX_ENCODE`, `HEX_DECODE_STRING`, `TRY_HEX_DECODE_STRING` and `TRY_BASE64_DECODE_BINARY`; a comment attached to a text literal; `FLOOR` with and without a scale, `BITAND`, `ZEROIFNULL`, `::BIGINT` and `::DOUBLE`; `IS NOT DISTINCT FROM` and `EQUAL_NULL`; a comma join after an explicit join; `HASH_AGG` read in two row orders | +| Ordering, numbers and text | NULL ordering under `DESC`; ties in ordered aggregates, `MAX_BY`, `MODE` and `ANY_VALUE`; default window frames; `UNION ALL BY NAME`; `ROUND` half-way values, decimal division, `MOD` and 38-digit amounts; integers past 2^53 against `FLOAT`; regular expressions and backslash escapes, and a scoped SQL macro collapsing whitespace whose body opens with a block comment and holds a line comment; a scoped SQL macro, `horner_ratio`, whose body nests polynomials in a subquery item without an alias, which a second `sqb format` leaves unchanged; `LIKE ... ESCAPE` and `ILIKE ANY`; `SPLIT_PART` and `SUBSTR` before the start; `NOT IN` with a NULL; names in many scripts; `JOIN ... USING` between `NUMBER(18,0)`, `NUMBER(38,0)` and text keys, with the types of the merged and qualified keys; NULL arithmetic and the types of NULL, decimal and exponent literals, `COUNT`, `ROW_NUMBER`, `%` and `NULLIF`; `MEDIAN` at scales 0 to 15; `DIV0` by literal zeros; `MODE`, `MEDIAN` and `COUNT_IF` over no rows; aggregates inside window functions and `QUALIFY`; `ROLLUP` totals; `TRUNC` of `FLOAT`; infinity words in other scripts; `CASE` without `ELSE` and `DECODE` over text; regular expressions with a `?` after a lazy quantifier, classes opening with `]`, empty matches and `.` against a carriage return; case-insensitive matches outside ASCII; `ILIKE` with a long s; `JAROWINKLER_SIMILARITY` of accented names in both cases; Base64 text with line feeds; `STARTSWITH`, `ENDSWITH`, `SUBSTRING`, `POSITION` with `IN` and with a comma, `CHARINDEX`, `CHR`, `REGEXP_SUBSTR_ALL`, `::STRING` and `CAST ... AS STRING`; `HEX_ENCODE`, `HEX_DECODE_STRING`, `TRY_HEX_DECODE_STRING` and `TRY_BASE64_DECODE_BINARY`; a comment attached to a text literal; `FLOOR` with and without a scale, `BITAND`, `ZEROIFNULL`, `::BIGINT` and `::DOUBLE`; `IS NOT DISTINCT FROM` and `EQUAL_NULL`; a comma join after an explicit join; `HASH_AGG` read in two row orders | | Lineage and analysis | clauses whose columns decide rows without being output (`WHERE`, `QUALIFY`, `GROUP BY` by position and `ALL`, `ORDER BY` under `LIMIT`, `EXISTS`, a `FLATTEN` input, `ROLLUP` by position, `EXCEPT` under `LIMIT`); `RIGHT JOIN ... USING`, `NATURAL JOIN`, a `USING` key under a later outer join, and unmatched `ASOF JOIN` rows; `CONNECT BY` beside a column named `level`; a recursive CTE without `RECURSIVE` whose columns shift per iteration; `LAST_DAY` with a date part; positional columns and the names Snowflake gives unaliased expressions; `TEXT(5)` and widened `COUNT` contracts; `LAG` and `LEAD` with one, two and three arguments; a comma-joined `LATERAL` whose nested derived table reads the left item; relations aliased `first` and `last`, one without `AS`, the words of Snowflake's read-order clauses; untyped and typed `FILTER` lambdas over `ARRAY_AGG` in a grouped query; column expression ranges in compiled SQL that SQL and Python macros, a variable and cursor bounds rewrote, and columns qualified by their reference call, whose ranges are dropped | | Python functions | volatile tokens and numbers from a column, a constant and no argument, and `DIV0` of a volatile call beside look-alike names, checked by assertions that hold for any values; a handler answering NULL input without `STRICT`; Python `None` as JSON null, and datetimes, Decimals and integers past 2^53 handed to `VARIANT` and `FLOAT` results | | Scenarios and lifecycle | typed values across model boundaries; `VARIANT` expected output; a star under a lower-case contract and a quoted camelCase export; a snapshot keyed and compared on quoted camelCase columns; a timestamp snapshot whose `updated_at` is a `DATE`, so its validity columns are `DATE` too; a cursor-window incremental model over far-apart fixture loads; a rolling-window microbatch model whose full refresh covers its `cursor_start` through the current day; a change log merged across two loads, checked against a full rebuild, a keyed cursor `delete_insert` copy of it whose rows move out of the window between loads, and a cursor `delete_insert` copy of every version that `replace_key` replaces per shipment | diff --git a/benchmarks/duckshop/project/sql/models/staging/edge_cases/_sqlbuild/_macros/sql/horner_ratio.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/_sqlbuild/_macros/sql/horner_ratio.sql new file mode 100644 index 0000000000..e10c208150 --- /dev/null +++ b/benchmarks/duckshop/project/sql/models/staging/edge_cases/_sqlbuild/_macros/sql/horner_ratio.sql @@ -0,0 +1,65 @@ +MACRO ( + description "x scaled by a ratio of two polynomials in Horner form at a fixed point; NULL for NULL x", + arguments (x FLOAT), + returns FLOAT, +); + +CASE + WHEN (@x) IS NULL + THEN NULL + ELSE @x * ( + SELECT + CASE + WHEN ABS(q) <= 0.5 + THEN q + * ( + ( + ( + ( + ( + ( + ( + 1111.1111111111111111 * r + 22222.222222222222222 + ) + * r + 33333.333333333333333 + ) + * r + 44444.444444444444444 + ) + * r + 5555.5555555555555555 + ) + * r + 666.66666666666666666 + ) + * r + 77.777777777777777777 + ) + * r + 8.8888888888888888888 + ) + / ( + ( + ( + ( + ( + ( + ( + 9999.999999999999999 * r + 11111.111111111111111 + ) + * r + 22222.22222222222222 + ) + * r + 3333.3333333333333333 + ) + * r + 444.44444444444444444 + ) + * r + 55.555555555555555555 + ) + * r + 6.6666666666666666666 + ) + * r + 1 + ) + ELSE 0 + END + FROM ( + SELECT + 0.125 AS q, + 0.234375 AS r + ) + ) +END diff --git a/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_payloads.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_payloads.sql index 7452ba3d8b..be6b05f7d6 100644 --- a/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_payloads.sql +++ b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_payloads.sql @@ -19,6 +19,7 @@ MODEL ( qty_text_units (type NUMBER(18, 2)), amount (type NUMBER(18, 2)), amount_float (type FLOAT), + amount_float_scaled (type FLOAT), amount_text (type VARCHAR), transaction_id_text (type VARCHAR), transaction_id (type NUMBER(38, 0)), @@ -63,6 +64,7 @@ final AS ( TRY_TO_NUMBER(l.payload:qty::VARCHAR, 18, 2)::NUMBER(18, 2) AS qty_text_units, l.payload:amount::NUMBER(18, 2) AS amount, l.payload:amount::FLOAT AS amount_float, + @sql.horner_ratio(l.payload:amount::FLOAT) AS amount_float_scaled, l.payload:amount::VARCHAR AS amount_text, l.payload:txn_id::VARCHAR AS transaction_id_text, l.payload:txn_id::NUMBER(38, 0) AS transaction_id, diff --git a/crates/sqlbuild-rules/src/lint_text/_helpers/format_bodies.rs b/crates/sqlbuild-rules/src/lint_text/_helpers/format_bodies.rs index dbf663df4c..1e6eb41730 100644 --- a/crates/sqlbuild-rules/src/lint_text/_helpers/format_bodies.rs +++ b/crates/sqlbuild-rules/src/lint_text/_helpers/format_bodies.rs @@ -21,10 +21,10 @@ use crate::dsl_headers::models::HeaderSpan; use crate::lint_text::_helpers::sites::compiled; use crate::lint_text::constants::{ BLOCK_COMMENT_OPENER, DECLARATION_GROUP_DIRECTORY, DECLINED_WITHOUT_REASON, - EXPRESSION_SELECT_PREFIX, FIXTURE_HEADER_KINDS, FORMAT_API_VERSION, FUNCTION_HEADER_KIND, - GLOBAL_NAMED_ROOTS, GROUPED_NAMED_ROLES, LINE_COMMENT_PREFIX, LINTED_EXPRESSION_ALIAS, - MACRO_HEADER_KIND, MOVED_EXPRESSION_ALIAS, MOVED_OMITTED_SELECT, OMITTED_CEREMONIAL_SELECT_SQL, - OMITTED_SELECT_SUFFIX_PATTERN, + EXPRESSION_SELECT_PREFIX, FIXTURE_HEADER_KINDS, FORMAT_API_VERSION, FORMAT_INDENT, + FUNCTION_HEADER_KIND, GLOBAL_NAMED_ROOTS, GROUPED_NAMED_ROLES, LINE_COMMENT_PREFIX, + LINTED_EXPRESSION_ALIAS, MACRO_HEADER_KIND, MOVED_EXPRESSION_ALIAS, MOVED_OMITTED_SELECT, + OMITTED_CEREMONIAL_SELECT_SQL, OMITTED_SELECT_SUFFIX_PATTERN, }; use crate::lint_text::errors::LintTextError; use crate::lint_text::main::neutralize_interpolation::neutralize_interpolation; @@ -70,7 +70,7 @@ impl RequestTable { dialect: options.0.to_string(), max_function_call_depth: Some(MAX_FUNCTION_CALL_DEPTH), line_width: Some(options.1), - indent: None, + indent: Some(FORMAT_INDENT), token_widths: widths.into_iter().collect(), }); let _ = self.index.insert(key, self.requests.len() - 1); @@ -176,7 +176,7 @@ pub(crate) fn prepare_file( let mut sql: String = if wraps_expression { format!( "{EXPRESSION_SELECT_PREFIX}{}\n{LINTED_EXPRESSION_ALIAS}", - neutralized.text + indented_continuation(&neutralized.text, dialect) ) } else { neutralized.text @@ -202,6 +202,29 @@ pub(crate) fn prepare_file( Ok(prepared) } +/// `body` with each code line after the first one step right, which [`unwrapped_expression`] takes off again, so lines the formatter keeps as written stay put. +fn indented_continuation(body: &str, dialect: &str) -> String { + let opaque: Vec<(usize, usize)> = + dialect_non_code_ranges(body, &dialect_lexical_syntax(dialect)); + let mut ranges = opaque.iter().peekable(); + let step: String = " ".repeat(FORMAT_INDENT); + let mut indented: String = String::with_capacity(body.len()); + let mut start: usize = 0; + for (index, line) in body.split('\n').enumerate() { + if index > 0 { + indented.push('\n'); + while ranges.next_if(|&&(_, end)| end <= start).is_some() {} + let inside: bool = ranges.peek().is_some_and(|&&(open, _)| open < start); + if !inside && !line.is_empty() { + indented.push_str(&step); + } + } + indented.push_str(line); + start += line.len() + 1; + } + indented +} + /// How a SQL macro or function body starts, which decides how it is formatted. enum MacroBodyForm { /// A `WITH` list, formatted with a final query added and removed again. diff --git a/crates/sqlbuild-rules/src/lint_text/constants.rs b/crates/sqlbuild-rules/src/lint_text/constants.rs index 8771b4cf37..992e8980cb 100644 --- a/crates/sqlbuild-rules/src/lint_text/constants.rs +++ b/crates/sqlbuild-rules/src/lint_text/constants.rs @@ -67,6 +67,8 @@ pub(crate) const UNIT_TEST_ROOT: [&str; 2] = ["tests", "unit"]; pub(crate) const SQL_SUFFIX: &str = ".sql"; pub(crate) const FORMAT_API_VERSION: u32 = 1; +/// Spaces per indent step that format requests ask for, and that an expression body is moved right by before formatting and left by after. +pub(crate) const FORMAT_INDENT: usize = 2; pub(crate) const OMITTED_CEREMONIAL_SELECT_SQL: &str = "\nSELECT 1"; pub(crate) const OMITTED_SELECT_SUFFIX_PATTERN: &str = r"(?i)\s*\bSELECT\s+1\s*\z"; pub(crate) const FIXTURE_HEADER_KINDS: [&str; 2] = ["TEST", "SCENARIO"]; diff --git a/crates/sqlbuild-rules/src/lint_text/tests.rs b/crates/sqlbuild-rules/src/lint_text/tests.rs index 5fb19d6a2d..51c2f2b7ab 100644 --- a/crates/sqlbuild-rules/src/lint_text/tests.rs +++ b/crates/sqlbuild-rules/src/lint_text/tests.rs @@ -1,5 +1,7 @@ #[path = "tests/test_fixture_formatting.rs"] mod fixture_formatting; +#[path = "tests/test_format_idempotence.rs"] +mod format_idempotence; #[path = "tests/test_format_settings.rs"] mod format_settings; #[path = "tests/helpers.rs"] diff --git a/crates/sqlbuild-rules/src/lint_text/tests/helpers.rs b/crates/sqlbuild-rules/src/lint_text/tests/helpers.rs index 4c59e34e9a..a394c79947 100644 --- a/crates/sqlbuild-rules/src/lint_text/tests/helpers.rs +++ b/crates/sqlbuild-rules/src/lint_text/tests/helpers.rs @@ -1,3 +1,5 @@ +use std::path::{Path, PathBuf}; + use crate::lint_text::constants::{DIRECTIVE_FIX_REASON, DIRECTIVE_MESSAGE}; use crate::lint_text::errors::LintTextError; use crate::lint_text::main::format_sql_bodies::format_sql_bodies; @@ -61,3 +63,54 @@ pub(crate) fn formatted_macro(contents: &str, dialect: &str) -> Result Vec<(PathBuf, Vec)> { + let listed = std::process::Command::new("git") + .args(["ls-files", "-z", "*sqlbuild_project.toml", "*.sql"]) + .current_dir(root) + .output() + .expect("git runs in the repository"); + assert!( + listed.status.success(), + "git lists the repository's files: {}", + String::from_utf8_lossy(&listed.stderr) + ); + let paths: Vec = String::from_utf8_lossy(&listed.stdout) + .split('\0') + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .collect(); + let projects: Vec = paths + .iter() + .filter(|path| path.ends_with("sqlbuild_project.toml")) + .filter_map(|path| path.parent().map(Path::to_path_buf)) + .collect(); + projects + .iter() + .map(|project| { + let files: Vec = paths + .iter() + .filter(|path| path.extension().is_some_and(|extension| extension == "sql")) + .filter(|path| { + projects + .iter() + .filter(|candidate| path.starts_with(candidate)) + .max_by_key(|candidate| candidate.components().count()) + == Some(project) + }) + .map(|path| FormatFile { + relative_parts: path.strip_prefix(project).ok().map(|relative| { + relative + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect() + }), + contents: std::fs::read_to_string(root.join(path)) + .expect("a tracked SQL file reads"), + }) + .collect(); + (root.join(project), files) + }) + .collect() +} diff --git a/crates/sqlbuild-rules/src/lint_text/tests/test_format_idempotence.rs b/crates/sqlbuild-rules/src/lint_text/tests/test_format_idempotence.rs new file mode 100644 index 0000000000..c6b59ba33c --- /dev/null +++ b/crates/sqlbuild-rules/src/lint_text/tests/test_format_idempotence.rs @@ -0,0 +1,87 @@ +use std::path::{Path, PathBuf}; + +use crate::lint_text::errors::LintTextError; +use crate::lint_text::main::format_sql_bodies::format_sql_bodies; +use crate::lint_text::models::FormatFile; +use crate::lint_text::tests::helpers::repository_projects; +use crate::lint_text::tests::test_types::FormatIdempotenceTestCase; + +#[test] +fn given_every_repository_project_when_formatting_twice_then_no_dialect_changes_the_second_pass() +-> Result<(), LintTextError> { + let root: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let projects: Vec<(PathBuf, Vec)> = repository_projects(&root); + let test_cases = [ + FormatIdempotenceTestCase { + description: "formatting as DuckDB settles in one pass", + dialect: "duckdb", + expected_second_pass_changes: Vec::new(), + }, + FormatIdempotenceTestCase { + description: "formatting as Snowflake settles in one pass", + dialect: "snowflake", + expected_second_pass_changes: Vec::new(), + }, + FormatIdempotenceTestCase { + description: "formatting as Databricks settles in one pass", + dialect: "databricks", + expected_second_pass_changes: Vec::new(), + }, + FormatIdempotenceTestCase { + description: "formatting as BigQuery settles in one pass", + dialect: "bigquery", + expected_second_pass_changes: Vec::new(), + }, + FormatIdempotenceTestCase { + description: "formatting as PostgreSQL settles in one pass", + dialect: "postgres", + expected_second_pass_changes: Vec::new(), + }, + FormatIdempotenceTestCase { + description: "formatting as SQL Server settles in one pass", + dialect: "tsql", + expected_second_pass_changes: Vec::new(), + }, + ]; + assert!( + projects.iter().any(|(project, files)| { + project.ends_with("benchmarks/duckshop/project") && !files.is_empty() + }), + "the corpus holds DuckShop" + ); + + for test_case in test_cases { + for (project, files) in &projects { + let once = format_sql_bodies(files, test_case.dialect, 100)?; + let formatted: Vec = once + .formatted + .into_iter() + .map(|(index, contents)| FormatFile { + relative_parts: files[index].relative_parts.clone(), + contents, + }) + .collect(); + let twice = format_sql_bodies(&formatted, test_case.dialect, 100)?; + let changed: Vec = twice + .formatted + .iter() + .map(|(index, _)| { + formatted[*index] + .relative_parts + .as_deref() + .unwrap_or_default() + .join("/") + }) + .collect(); + + assert_eq!( + changed, + test_case.expected_second_pass_changes, + "{} in {}", + test_case.description, + project.display() + ); + } + } + Ok(()) +} diff --git a/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs b/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs index 9823b6c84a..9f89d14f25 100644 --- a/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs +++ b/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs @@ -39,6 +39,12 @@ const E_STRING_MACRO: &str = "MACRO (arguments (v VARCHAR), returns VARCHAR);\n\ const E_STRING_FORMATTED: &str = "MACRO (arguments (v VARCHAR), returns VARCHAR);\n\nCONCAT(@v, E'O\\'Brien\n kept indent', 'tail')\n"; const BLOCK_COMMENT_MACRO: &str = "MACRO (arguments (v VARCHAR), returns VARCHAR);\n\nCOALESCE(\n @v, /* first\n second */\n 'x'\n)\n"; const BLOCK_COMMENT_FORMATTED: &str = "MACRO (arguments (v VARCHAR), returns VARCHAR);\n\nCOALESCE(\n @v, /* first\n second */ 'x'\n)\n"; +/// A Horner-form polynomial in a subquery whose select item has no alias, so Snowflake keeps it as written. +const HORNER_MACRO: &str = "MACRO (arguments (x FLOAT), returns FLOAT);\n\nCASE\n WHEN (\n @x\n ) IS NULL\n THEN NULL\n ELSE (\n SELECT\n CASE\n WHEN ABS(q) <= 0.5\n THEN q\n * (\n (\n (\n 1.5 * r + 2.5\n )\n * r + 3.5\n )\n * r + 4.5\n )\n ELSE 0\n END\n FROM (\n SELECT\n @x - 0.5 AS q,\n 0.25 - (@x - 0.5) * (@x - 0.5) AS r\n )\n )\nEND\n"; +const HORNER_MACRO_FORMATTED: &str = "MACRO (arguments (x FLOAT), returns FLOAT);\n\nCASE\n WHEN (@x) IS NULL\n THEN NULL\n ELSE (\n SELECT CASE\n WHEN ABS(q) <= 0.5\n THEN q\n * (\n (\n (\n 1.5 * r + 2.5\n )\n * r + 3.5\n )\n * r + 4.5\n )\n ELSE 0\n END\n FROM (\n SELECT\n @x - 0.5 AS q,\n 0.25 - (@x - 0.5) * (@x - 0.5) AS r\n )\n )\nEND\n"; +/// A subquery item without an alias, which Snowflake keeps as written, holding a line of spaces. +const KEPT_BLANK_LINE_MACRO: &str = "MACRO (arguments (x FLOAT), returns FLOAT);\n\nCOALESCE(\n (\n SELECT q\n + 1\n \n + 2\n FROM (SELECT @x AS q)\n ),\n 0\n)\n"; +const KEPT_BLANK_LINE_FORMATTED: &str = "MACRO (arguments (x FLOAT), returns FLOAT);\n\nCOALESCE(\n (\n SELECT q\n + 1\n \n + 2\n FROM (\n SELECT @x AS q\n )\n ),\n 0\n)\n"; const NORMALISE_NAME_FORMATTED: &str = "MACRO (\n description \"Normalise a name\",\n arguments (column_name VARCHAR),\n returns VARCHAR,\n);\n\nREGEXP_REPLACE(\n TRIM(\n UPPER(\n -- Collapse repeated spaces\n REGEXP_REPLACE(@column_name, '[[:space:]]+', ' ')\n )\n ),\n '(^| )([A-Z]) ',\n '\\\\1\\\\2'\n)\n"; #[test] @@ -1037,6 +1043,18 @@ fn given_expression_macro_bodies_when_formatting_twice_then_every_dialect_lays_t contents: nested_macro(15, ""), expected_formatted: nested_macro(15, " "), }, + ExpressionMacroFormatTestCase { + description: "a nested polynomial in a subquery item Snowflake keeps as written", + dialects: &["snowflake"], + contents: HORNER_MACRO.to_string(), + expected_formatted: HORNER_MACRO_FORMATTED.to_string(), + }, + ExpressionMacroFormatTestCase { + description: "a line of spaces inside a subquery item Snowflake keeps as written", + dialects: &["snowflake"], + contents: KEPT_BLANK_LINE_MACRO.to_string(), + expected_formatted: KEPT_BLANK_LINE_FORMATTED.to_string(), + }, ExpressionMacroFormatTestCase { description: "a multi-line string after a backslash-escaped quote", dialects: &["snowflake", "databricks"], diff --git a/crates/sqlbuild-rules/src/lint_text/tests/test_types.rs b/crates/sqlbuild-rules/src/lint_text/tests/test_types.rs index 767de51d4f..2b1b300ba5 100644 --- a/crates/sqlbuild-rules/src/lint_text/tests/test_types.rs +++ b/crates/sqlbuild-rules/src/lint_text/tests/test_types.rs @@ -127,3 +127,9 @@ pub(crate) struct ExpressionMacroFormatTestCase { pub(crate) contents: String, pub(crate) expected_formatted: String, } + +pub(crate) struct FormatIdempotenceTestCase { + pub(crate) description: &'static str, + pub(crate) dialect: &'static str, + pub(crate) expected_second_pass_changes: Vec, +} diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/format/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/format/_test_types.py index e391fdfb92..21cf21b090 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/format/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/format/_test_types.py @@ -166,3 +166,13 @@ class RefusedQuoteFixTestCase: path: str contents: str expected_fix: tuple[str, str, int, str] + + +@dataclass(frozen=True) +class FormatConvergenceTestCase: + """One adapter whose `sqb format` must leave its own output unchanged on a second run.""" + + description: str + adapter: str + expected_second_run_unchanged: bool + expected_check_returncode: int diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_convergence.py b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_convergence.py new file mode 100644 index 0000000000..feafb3184a --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_convergence.py @@ -0,0 +1,106 @@ +"""E2E coverage that `sqb format` settles: a second run changes nothing.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.format._test_types import ( + FormatConvergenceTestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb + +_MACRO_PATH: str = "sql/macros/sql/poly.sql" +# A polynomial in Horner form inside a subquery whose select item has no alias, which Snowflake +# names after its text, so the formatter keeps that item's lines as written. +_HORNER_MACRO: str = ( + "MACRO (\n" + ' description "Polynomial",\n' + " arguments (x FLOAT),\n" + " returns FLOAT,\n" + ");\n\n" + "CASE\n" + " WHEN (\n" + " @x\n" + " ) IS NULL\n" + " THEN NULL\n" + " ELSE (\n" + " SELECT\n" + " CASE\n" + " WHEN ABS(q) <= 0.5\n" + " THEN q\n" + " * (\n" + " (\n" + " (\n" + " (\n" + " 1.5 * r + 2.5\n" + " )\n" + " * r + 3.5\n" + " )\n" + " * r + 4.5\n" + " )\n" + " * r + 5.5\n" + " )\n" + " ELSE 0\n" + " END\n" + " FROM (\n" + " SELECT\n" + " @x - 0.5 AS q,\n" + " 0.25 - (@x - 0.5) * (@x - 0.5) AS r\n" + " )\n" + " )\n" + "END\n" +) + + +@pytest.mark.parametrize( + "test_case", + [ + FormatConvergenceTestCase( + description="snowflake_keeps_the_unaliased_item_where_the_first_run_left_it", + adapter="snowflake", + expected_second_run_unchanged=True, + expected_check_returncode=0, + ), + FormatConvergenceTestCase( + description="duckdb_settles_in_one_run", + adapter="duckdb", + expected_second_run_unchanged=True, + expected_check_returncode=0, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_nested_macro_expression_when_formatting_twice_then_the_second_run_changes_nothing( + test_case: FormatConvergenceTestCase, tmp_path: Path +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="shop", + repo_files={ + "sqlbuild_project.toml": f'name = "shop"\nadapter = "{test_case.adapter}"\n', + _MACRO_PATH: _HORNER_MACRO, + }, + ) + + first: subprocess.CompletedProcess[str] = run_sqb( + project_dir=project_dir, command=("--no-color", "format", "--no-cache") + ) + once: str = (project_dir / _MACRO_PATH).read_text(encoding="utf-8") + second: subprocess.CompletedProcess[str] = run_sqb( + project_dir=project_dir, command=("--no-color", "format", "--no-cache") + ) + twice: str = (project_dir / _MACRO_PATH).read_text(encoding="utf-8") + checked: subprocess.CompletedProcess[str] = run_sqb( + project_dir=project_dir, command=("--no-color", "format", "--check", "--no-cache") + ) + + assert first.returncode == 0, first.stdout + first.stderr + assert once != _HORNER_MACRO + assert second.returncode == 0, second.stdout + second.stderr + assert (twice == once) is test_case.expected_second_run_unchanged + assert checked.returncode == test_case.expected_check_returncode, ( + checked.stdout + checked.stderr + )