Skip to content

Commit 54913be

Browse files
committed
Merge wip/formatter-tsql-spans-4: record SQL Server spans on variables, operators and assignments, and the ASOF JOIN keyword-alias span on located parses
2 parents 4b23a66 + 89784c1 commit 54913be

35 files changed

Lines changed: 439 additions & 49 deletions

File tree

‎corpora/everyday/queries.toml‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2713,8 +2713,8 @@ expect_repository = "refused SQ0002 fn:CURRENT_WAREHOUSE at 7..26"
27132713
[[query]]
27142714
category = "misc"
27152715
sql = '''SELECT $1 FROM orders'''
2716-
expect = "refused SQ0009 syntax:unaliased_output_name at 0..21"
2717-
expect_repository = "refused SQ0009 syntax:unaliased_output_name at 0..21"
2716+
expect = "refused SQ0009 syntax:unaliased_output_name at 7..9"
2717+
expect_repository = "refused SQ0009 syntax:unaliased_output_name at 7..9"
27182718

27192719
[[query]]
27202720
category = "misc"
@@ -2725,8 +2725,8 @@ expect_repository = "refused SQ0002 node:table at 21..44"
27252725
[[query]]
27262726
category = "misc"
27272727
sql = '''SELECT order_id FROM orders WHERE customer_id = :customer_id'''
2728-
expect = "refused SQ0002 node:parameter at 34..60"
2729-
expect_repository = "refused SQ0002 node:parameter at 34..60"
2728+
expect = "refused SQ0002 node:parameter at 48..60"
2729+
expect_repository = "refused SQ0002 node:parameter at 48..60"
27302730

27312731
[[query]]
27322732
category = "misc"

‎crates/sqlquack-format/src/format/_helpers/identifiers.rs‎

Lines changed: 83 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use serde_json::Value;
44
use sqlquack_syntax::Expression;
55

66
use crate::format::_helpers::lexemes::Lexeme;
7-
use crate::format::constants::BINARY_OPERATOR_NODES;
7+
use crate::format::constants::{ASSIGNMENT_OPERATOR, BINARY_OPERATOR_NODES};
88

99
/// The fields of a serialised identifier node.
1010
const IDENTIFIER_FIELDS: [&str; 4] = ["name", "quoted", "trailing_comments", "span"];
@@ -19,6 +19,16 @@ const RIGHT_FIELD: &str = "right";
1919
const COLUMN_ALIASES_FIELD: &str = "column_aliases";
2020
/// The field of a serialised UPDATE that holds its `column = value` pairs.
2121
const SET_FIELD: &str = "set";
22+
/// The fields and nodes of the assignments the tree keeps outside binary operator nodes.
23+
const NAME_FIELD: &str = "name";
24+
const VALUE_FIELD: &str = "value";
25+
const KIND_FIELD: &str = "kind";
26+
const DEFAULT_FIELD: &str = "default";
27+
const OPERATOR_NODE: &str = "operator";
28+
const VAR_NODE: &str = "var";
29+
const DECLARE_ITEM_NODE: &str = "declare_item";
30+
/// Value nodes printed as one token, such as `1`, `'x'`, `NULL` or `DEFAULT`.
31+
const SINGLE_TOKEN_NODES: [&str; 4] = ["literal", "null", "boolean", "var"];
2232

2333
/// Per-token facts from the parse tree, and how many select lists it has.
2434
pub(crate) struct ParsedNames {
@@ -40,6 +50,8 @@ struct Binary {
4050
span: Option<(usize, usize)>,
4151
left_end: Option<usize>,
4252
right_start: Option<usize>,
53+
/// Whether the right operand is the single last token of the range, so the operator is the token before it.
54+
before_last: bool,
4355
}
4456

4557
/// The ranges the parse tree records: every identifier and every alias name, in characters.
@@ -134,6 +146,9 @@ fn binary_operators(
134146
.iter()
135147
.copied()
136148
.rfind(|&index| lexemes[index].end <= right_start),
149+
(None, None) if binary.before_last => {
150+
inside.len().checked_sub(2).map(|before| inside[before])
151+
}
137152
(None, None) if binary.span.is_some() => {
138153
let candidates: Vec<usize> = inside
139154
.iter()
@@ -303,25 +318,84 @@ fn binary(value: &Value) -> Option<Binary> {
303318
.and_then(|span| Some((span_offset(span, "start")?, span_offset(span, "end")?))),
304319
left_end: operand_span(LEFT_FIELD).and_then(|span| span_offset(span, "end")),
305320
right_start: operand_span(RIGHT_FIELD).and_then(|span| span_offset(span, "start")),
321+
before_last: false,
306322
})
307323
}
308324

309-
/// The `=` of each `column = value` pair of an UPDATE's SET, which the tree keeps as a pair, not a comparison.
325+
/// The `=` of each assignment the tree keeps outside a binary operator node: an UPDATE's `column = value` pairs, a `SET @v = value` item, a `SELECT @v = value` item, and the value of a declared variable, a procedure parameter or an EXEC argument.
310326
fn assignments(value: &Value) -> Vec<Binary> {
311-
let pairs = value.get(SET_FIELD).and_then(Value::as_array);
312-
pairs
327+
let after = |end: usize| Binary {
328+
spellings: &[ASSIGNMENT_OPERATOR],
329+
span: None,
330+
left_end: Some(end),
331+
right_start: None,
332+
before_last: false,
333+
};
334+
let pairs = value
335+
.get(SET_FIELD)
336+
.and_then(Value::as_array)
313337
.into_iter()
314338
.flatten()
315339
.filter_map(|pair| identifier_range(pair.as_array()?.first()?))
316-
.map(|(_, end)| Binary {
317-
spellings: &["="],
318-
span: None,
319-
left_end: Some(end),
320-
right_start: None,
340+
.map(|(_, end)| end);
341+
let set_item = value
342+
.get(VALUE_FIELD)
343+
.filter(|_| value.get(KIND_FIELD).is_some_and(Value::is_null))
344+
.and_then(|_| node_range(value.get(NAME_FIELD)?))
345+
.map(|(_, end)| end);
346+
let select_assignment = value
347+
.get(OPERATOR_NODE)
348+
.filter(|node| {
349+
node.get(OPERATOR_NODE)
350+
.and_then(|operator| operator.get(VAR_NODE)?.get(ALIASED_FIELD))
351+
.is_some_and(|spelling| spelling == ASSIGNMENT_OPERATOR)
321352
})
353+
.and_then(|node| node_range(node.get(ALIASED_FIELD)?))
354+
.map(|(_, end)| end);
355+
pairs
356+
.chain(set_item)
357+
.chain(select_assignment)
358+
.map(after)
359+
.chain(valued(value))
322360
.collect()
323361
}
324362

363+
/// The `=` before the value of a declared variable, a procedure parameter or a named EXEC argument, placed by the node's range and its value's.
364+
fn valued(value: &Value) -> Option<Binary> {
365+
let node = value.get(DECLARE_ITEM_NODE).unwrap_or(value);
366+
let span = node.get(SPAN_FIELD)?;
367+
let (start, end) = (span_offset(span, "start")?, span_offset(span, "end")?);
368+
let argument = node.get(NAME_FIELD).and_then(Value::as_str);
369+
let assigned = node.get(DEFAULT_FIELD).or(node.get(VALUE_FIELD))?;
370+
if let Some(name) = argument.filter(|name| !name.is_empty()) {
371+
return Some(Binary {
372+
spellings: &[ASSIGNMENT_OPERATOR],
373+
span: None,
374+
left_end: Some(start + name.chars().count()),
375+
right_start: None,
376+
before_last: false,
377+
});
378+
}
379+
let right_start = node_range(assigned).map(|(start, _)| start);
380+
let single_token = assigned
381+
.as_object()
382+
.and_then(|fields| fields.keys().next())
383+
.is_some_and(|kind| SINGLE_TOKEN_NODES.contains(&kind.as_str()));
384+
(right_start.is_some() || single_token).then_some(Binary {
385+
spellings: &[ASSIGNMENT_OPERATOR],
386+
span: Some((start, end)),
387+
left_end: None,
388+
right_start,
389+
before_last: right_start.is_none(),
390+
})
391+
}
392+
393+
/// The range of the node one-field wrapper `value` holds, when recorded.
394+
fn node_range(value: &Value) -> Option<(usize, usize)> {
395+
let span = value.as_object()?.values().next()?.get(SPAN_FIELD)?;
396+
Some((span_offset(span, "start")?, span_offset(span, "end")?))
397+
}
398+
325399
/// The character range of `value` when it is an identifier node with a recorded span.
326400
fn identifier_range(value: &Value) -> Option<(usize, usize)> {
327401
let fields = value.as_object()?;

‎crates/sqlquack-format/src/format/constants.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,8 @@ pub(crate) const GUARD_OPERATORS: [&str; 22] = [
412412
"->>", "<=>", "||", "<=", ">=", "<>", "!=", "=>", "->", "::", ":=", "/*", "*/", "--", "**",
413413
"//", "<<", ">>", "|>", "!~", "~*", "#>",
414414
];
415+
/// The operator of an assignment the tree keeps outside a binary operator node, such as `SET @v = 1`.
416+
pub(crate) const ASSIGNMENT_OPERATOR: &str = "=";
415417
/// Binary operators that whitespace may separate from a token they touch.
416418
pub(crate) const SEPARABLE_OPERATORS: [&str; 12] = [
417419
"=", "<>", "!=", "<", ">", "<=", ">=", "+", "-", "*", "||", "->",

‎crates/sqlquack-format/src/format/tests/test_format_sql.rs‎

Lines changed: 102 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -386,8 +386,108 @@ fn given_sql_whose_spacing_carries_meaning_when_formatting_then_it_is_kept_or_re
386386
expected_outcome: Ok("SELECT *\nFROM t\nWHERE\n a = @x AND @y <> b"),
387387
},
388388
test_types::FormatSqlTestCase {
389-
description: "an operator touching a SQL Server variable and a literal is refused, since neither operand has a source position",
390-
sql: "SELECT @v+1",
389+
description: "a comparison of a SQL Server variable with a literal written touching is spaced",
390+
sql: "select 1 where @a=1",
391+
line_width: None,
392+
dialect: FormatDialect::SqlServer,
393+
expected_outcome: Ok("SELECT 1\nWHERE @a = 1"),
394+
},
395+
test_types::FormatSqlTestCase {
396+
description: "a comparison of a literal with a SQL Server variable written touching is spaced",
397+
sql: "select 1 where 1=@a",
398+
line_width: None,
399+
dialect: FormatDialect::SqlServer,
400+
expected_outcome: Ok("SELECT 1\nWHERE 1 = @a"),
401+
},
402+
test_types::FormatSqlTestCase {
403+
description: "a comparison touching only its literal is spaced",
404+
sql: "select 1 where @a =1",
405+
line_width: None,
406+
dialect: FormatDialect::SqlServer,
407+
expected_outcome: Ok("SELECT 1\nWHERE @a = 1"),
408+
},
409+
test_types::FormatSqlTestCase {
410+
description: "an IF condition over a SQL Server variable written touching is spaced",
411+
sql: "if @a=1 select 1",
412+
line_width: None,
413+
dialect: FormatDialect::SqlServer,
414+
expected_outcome: Ok("IF @a = 1\n SELECT 1"),
415+
},
416+
test_types::FormatSqlTestCase {
417+
description: "arithmetic on a SQL Server variable written touching is spaced",
418+
sql: "select @a+1",
419+
line_width: None,
420+
dialect: FormatDialect::SqlServer,
421+
expected_outcome: Ok("SELECT @a + 1"),
422+
},
423+
test_types::FormatSqlTestCase {
424+
description: "arithmetic on a SQL Server system variable written touching is spaced",
425+
sql: "select @@rowcount+1",
426+
line_width: None,
427+
dialect: FormatDialect::SqlServer,
428+
expected_outcome: Ok("SELECT @@rowcount + 1"),
429+
},
430+
test_types::FormatSqlTestCase {
431+
description: "comparisons over SQL Server variables inside an AND are spaced",
432+
sql: "select 1 where @a=1 and b=2",
433+
line_width: None,
434+
dialect: FormatDialect::SqlServer,
435+
expected_outcome: Ok("SELECT 1\nWHERE\n @a = 1 AND b = 2"),
436+
},
437+
test_types::FormatSqlTestCase {
438+
description: "a DECLARE value written touching its type is spaced",
439+
sql: "declare @a int=1",
440+
line_width: None,
441+
dialect: FormatDialect::SqlServer,
442+
expected_outcome: Ok("DECLARE @a int = 1"),
443+
},
444+
test_types::FormatSqlTestCase {
445+
description: "a procedure parameter default written touching its type is spaced",
446+
sql: "create procedure p @a int=1 as select 1",
447+
line_width: None,
448+
dialect: FormatDialect::SqlServer,
449+
expected_outcome: Ok("CREATE PROCEDURE p @a int = 1\nAS\nSELECT 1"),
450+
},
451+
test_types::FormatSqlTestCase {
452+
description: "a comparison in a procedure body's IF written touching is spaced",
453+
sql: "create procedure p @a int = 1 as begin if @a=1 select 1 end",
454+
line_width: None,
455+
dialect: FormatDialect::SqlServer,
456+
expected_outcome: Ok(
457+
"CREATE PROCEDURE p @a int = 1\nAS\nBEGIN\n IF @a = 1\n SELECT 1\nEND",
458+
),
459+
},
460+
test_types::FormatSqlTestCase {
461+
description: "a SELECT assignment to a SQL Server variable written touching is spaced",
462+
sql: "select @a=1",
463+
line_width: None,
464+
dialect: FormatDialect::SqlServer,
465+
expected_outcome: Ok("SELECT @a = 1"),
466+
},
467+
test_types::FormatSqlTestCase {
468+
description: "a SET assignment written touching is spaced",
469+
sql: "set @a=1",
470+
line_width: None,
471+
dialect: FormatDialect::SqlServer,
472+
expected_outcome: Ok("SET @a = 1"),
473+
},
474+
test_types::FormatSqlTestCase {
475+
description: "a SET assignment of arithmetic on the variable written touching is spaced",
476+
sql: "set @a=@a+1",
477+
line_width: None,
478+
dialect: FormatDialect::SqlServer,
479+
expected_outcome: Ok("SET @a = @a + 1"),
480+
},
481+
test_types::FormatSqlTestCase {
482+
description: "a named EXEC argument written touching is spaced",
483+
sql: "exec p @a=1",
484+
line_width: None,
485+
dialect: FormatDialect::SqlServer,
486+
expected_outcome: Ok("EXEC p @a = 1"),
487+
},
488+
test_types::FormatSqlTestCase {
489+
description: "a compound assignment stays refused when touching, since `+=` is one operator",
490+
sql: "set @a+=1",
391491
line_width: None,
392492
dialect: FormatDialect::SqlServer,
393493
expected_outcome: Err(SEPARATION_FAILURE),

‎crates/sqlquack-syntax-bigquery/src/parse/_helpers/tree/nodes.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ pub(crate) fn parameter(name: Option<String>) -> Expression {
9292
quoted: false,
9393
string_quoted: false,
9494
expression: None,
95+
span: SourceSpan::default(),
9596
}))
9697
}
9798

‎crates/sqlquack-syntax-clickhouse/src/parse/_helpers/commands/ddl.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use sqlquack_syntax::expressions::tables::models::{
1616
CreateTable, DropTable, EngineProperty, OnCluster, PartitionedByProperty, SampleProperty,
1717
SchemaCommentProperty, SettingsProperty,
1818
};
19+
use sqlquack_syntax::tokens::models::SourceSpan;
1920

2021
use crate::parse::_helpers::commands::statements::alter;
2122
use crate::parse::_helpers::tree::cursor::{Parser, Parsing};
@@ -420,6 +421,7 @@ impl Parser<'_> {
420421
mode: None,
421422
default: None,
422423
mode_text: None,
424+
span: SourceSpan::default(),
423425
})
424426
.collect();
425427
node.body = Some(FunctionBody::Expression(Expression::Lambda(lambda)));

‎crates/sqlquack-syntax-clickhouse/src/parse/_helpers/tree/nodes.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ pub(crate) fn parameter(name: Option<String>) -> Expression {
8989
quoted: false,
9090
string_quoted: false,
9191
expression: None,
92+
span: SourceSpan::default(),
9293
}))
9394
}
9495

‎crates/sqlquack-syntax-databricks/src/parse/_helpers/commands/routines.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use sqlquack_syntax::expressions::schema_objects::models::{
1010
use sqlquack_syntax::expressions::tables::models::{
1111
LocationProperty, Properties, SchemaCommentProperty,
1212
};
13+
use sqlquack_syntax::tokens::models::SourceSpan;
1314

1415
use crate::parse::_helpers::commands::creates::{Head, property};
1516
use crate::parse::_helpers::tree::cursor::{Parser, Parsing};
@@ -121,6 +122,7 @@ impl Parser<'_> {
121122
mode: None,
122123
default,
123124
mode_text: None,
125+
span: SourceSpan::default(),
124126
})
125127
}
126128

‎crates/sqlquack-syntax-databricks/src/parse/_helpers/commands/utility.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use sqlquack_syntax::expressions::statements::models::{
99
Cache, Comment, Declare, DeclareItem, Describe, ResetStatement, SetItem, SetStatement, Show,
1010
Truncate, Uncache, Use, UseKind,
1111
};
12+
use sqlquack_syntax::tokens::models::SourceSpan;
1213

1314
use crate::parse::_helpers::commands::alters::partition;
1415
use crate::parse::_helpers::tree::cursor::{Parser, Parsing, is_identifier};
@@ -881,6 +882,7 @@ impl Parser<'_> {
881882
default,
882883
has_as: false,
883884
additional_names: names,
885+
span: SourceSpan::default(),
884886
};
885887
Ok(Expression::Declare(Box::new(Declare {
886888
expressions: vec![Expression::DeclareItem(Box::new(item))],

‎crates/sqlquack-syntax-databricks/src/parse/_helpers/tree/nodes.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ pub(crate) fn parameter(name: Option<String>) -> Expression {
9292
quoted: false,
9393
string_quoted: false,
9494
expression: None,
95+
span: SourceSpan::default(),
9596
}))
9697
}
9798

0 commit comments

Comments
 (0)