Skip to content
Open
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
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/duckshop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down Expand Up @@ -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,
Expand Down
35 changes: 29 additions & 6 deletions crates/sqlbuild-rules/src/lint_text/_helpers/format_bodies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlbuild-rules/src/lint_text/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlbuild-rules/src/lint_text/tests.rs
Original file line number Diff line number Diff line change
@@ -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"]
Expand Down
53 changes: 53 additions & 0 deletions crates/sqlbuild-rules/src/lint_text/tests/helpers.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -61,3 +63,54 @@ pub(crate) fn formatted_macro(contents: &str, dialect: &str) -> Result<String, L
.next()
.map_or_else(|| contents.to_string(), |(_, text)| text))
}

/// Each SQLBuild project Git tracks under `root`, with the tracked `.sql` files whose innermost project it is.
pub(crate) fn repository_projects(root: &Path) -> Vec<(PathBuf, Vec<FormatFile>)> {
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<PathBuf> = String::from_utf8_lossy(&listed.stdout)
.split('\0')
.filter(|path| !path.is_empty())
.map(PathBuf::from)
.collect();
let projects: Vec<PathBuf> = 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<FormatFile> = 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()
}
Loading
Loading