forked from shssoichiro/sqlformat-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2697 lines (2449 loc) · 75.4 KB
/
lib.rs
File metadata and controls
2697 lines (2449 loc) · 75.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This crate is a port of https://github.com/kufii/sql-formatter-plus
//! written in Rust. It is intended to be usable as a pure-Rust library
//! for formatting SQL queries.
#![type_length_limit = "99999999"]
#![forbid(unsafe_code)]
// Maintains semver compatibility for older Rust versions
#![allow(clippy::manual_strip)]
// This lint is overly pedantic and annoying
#![allow(clippy::needless_lifetimes)]
mod formatter;
mod indentation;
mod inline_block;
mod params;
mod tokenizer;
#[cfg(feature = "debug")]
mod debug;
/// Formats whitespace in a SQL string to make it easier to read.
/// Optionally replaces parameter placeholders with `params`.
pub fn format(query: &str, params: &QueryParams, options: &FormatOptions) -> String {
let named_placeholders = matches!(params, QueryParams::Named(_));
let tokens = tokenizer::tokenize(query, named_placeholders, options);
formatter::format(&tokens, params, options)
}
/// The SQL dialect to use. This affects parsing of special characters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dialect {
/// Generic SQL syntax, most dialect-specific constructs are disabled
Generic,
/// Enables array syntax (`[`, `]`) and operators
PostgreSql,
/// Enables `[bracketed identifiers]` and `@variables`
SQLServer,
}
/// Options for controlling how the library formats SQL
#[derive(Debug, Clone)]
pub struct FormatOptions<'a> {
/// Controls the type and length of indentation to use
///
/// Default: 2 spaces
pub indent: Indent,
/// When set, changes reserved keywords to ALL CAPS
///
/// Default: false
pub uppercase: Option<bool>,
/// Controls the number of line breaks after a query
///
/// Default: 1
pub lines_between_queries: u8,
/// Ignore case conversion for specified strings in the array.
///
/// Default: None
pub ignore_case_convert: Option<Vec<&'a str>>,
/// Keep the query in a single line
///
/// Default: false
pub inline: bool,
/// Maximum length of an inline block
///
/// Default: 50
pub max_inline_block: usize,
/// Maximum length of inline arguments
///
/// If unset keep every argument in a separate line
///
/// Default: None
pub max_inline_arguments: Option<usize>,
/// Inline the argument at the top level if they would fit a line of this length
///
/// Default: None
pub max_inline_top_level: Option<usize>,
/// Consider any JOIN statement as a top level keyword instead of a reserved keyword
///
/// Default: false,
pub joins_as_top_level: bool,
/// Tell the SQL dialect to use
///
/// Default: Generic
pub dialect: Dialect,
}
impl<'a> Default for FormatOptions<'a> {
fn default() -> Self {
FormatOptions {
indent: Indent::Spaces(2),
uppercase: None,
lines_between_queries: 1,
ignore_case_convert: None,
inline: false,
max_inline_block: 50,
max_inline_arguments: None,
max_inline_top_level: None,
joins_as_top_level: false,
dialect: Dialect::Generic,
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum Indent {
Spaces(u8),
Tabs,
}
#[derive(Debug, Clone, Default)]
pub enum QueryParams {
Named(Vec<(String, String)>),
Indexed(Vec<String>),
#[default]
None,
}
#[derive(Default, Debug, Clone)]
pub(crate) struct SpanInfo {
pub full_span: usize,
pub blocks: usize,
pub newline_before: bool,
pub newline_after: bool,
pub arguments: usize,
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
use pretty_assertions::assert_eq;
#[test]
fn test_sqlite_blob_literal_fmt() {
let options = FormatOptions::default();
let input = "SELECT x'73716c69676874' AS BLOB_VAL;";
let expected = indoc!(
"
SELECT
x'73716c69676874' AS BLOB_VAL;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
let input = "SELECT X'73716c69676874' AS BLOB_VAL;";
let expected = indoc!(
"
SELECT
X'73716c69676874' AS BLOB_VAL;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_uses_given_indent_config_for_indentation() {
let input = "SELECT count(*),Column1 FROM Table1;";
let options = FormatOptions {
indent: Indent::Spaces(4),
..FormatOptions::default()
};
let expected = indoc!(
"
SELECT
count(*),
Column1
FROM
Table1;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_simple_set_schema_queries() {
let input = "SET SCHEMA schema1; SET CURRENT SCHEMA schema2;";
let options = FormatOptions::default();
let expected = indoc!(
"
SET SCHEMA
schema1;
SET CURRENT SCHEMA
schema2;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_simple_select_query() {
let input = "SELECT count(*),Column1 FROM Table1;";
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
count(*),
Column1
FROM
Table1;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_complex_select() {
let input =
"SELECT DISTINCT name, ROUND(age/7) field1, 18 + 20 AS field2, 'some string' FROM foo;";
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT DISTINCT
name,
ROUND(age / 7) field1,
18 + 20 AS field2,
'some string'
FROM
foo;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_over_with_window() {
let input =
"SELECT id, val, at, SUM(val) OVER win AS cumulative FROM data WINDOW win AS (PARTITION BY id ORDER BY at);";
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
id,
val,
at,
SUM(val) OVER win AS cumulative
FROM
data
WINDOW
win AS (
PARTITION BY
id
ORDER BY
at
);"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_distinct_from() {
let input = "SELECT bar IS DISTINCT FROM 'baz', IS NOT DISTINCT FROM 'foo' FROM foo;";
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
bar IS DISTINCT FROM 'baz',
IS NOT DISTINCT FROM 'foo'
FROM
foo;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn keep_select_arguments_inline() {
let input = indoc! {
"
SELECT
a,
b,
c,
d,
e,
f,
g,
h
FROM foo;"
};
let options = FormatOptions {
max_inline_arguments: Some(50),
..Default::default()
};
let expected = indoc! {
"
SELECT
a, b, c, d, e, f, g, h
FROM
foo;"
};
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn split_select_arguments_inline_top_level() {
let input = indoc! {
"
SELECT
a,
b,
c,
d,
e,
f,
g,
h
FROM foo;"
};
let options = FormatOptions {
max_inline_arguments: Some(50),
max_inline_top_level: Some(50),
..Default::default()
};
let expected = indoc! {
"
SELECT a, b, c, d, e, f, g, h
FROM foo;"
};
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn inline_arguments_when_possible() {
let input = indoc! {
"
SELECT
a,
b,
c,
d,
e,
f,
g,
h
FROM foo;"
};
let options = FormatOptions {
max_inline_arguments: Some(50),
max_inline_top_level: Some(20),
..Default::default()
};
let expected = indoc! {
"
SELECT
a, b, c, d, e, f, g, h
FROM foo;"
};
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn inline_single_block_argument() {
let input = "SELECT a, b, c FROM ( SELECT (e+f) AS a, (m+o) AS b FROM d) WHERE (a != b) OR (c IS NULL AND a == b)";
let options = FormatOptions {
max_inline_arguments: Some(10),
max_inline_top_level: Some(20),
..Default::default()
};
let expected = indoc! {
"
SELECT a, b, c
FROM (
SELECT
(e + f) AS a,
(m + o) AS b
FROM d
)
WHERE
(a != b)
OR (
c IS NULL
AND a == b
)"
};
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_with_complex_where() {
let input = indoc!(
"
SELECT * FROM foo WHERE Column1 = 'testing'
AND ( (Column2 = Column3 OR Column4 >= NOW()) );
"
);
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
*
FROM
foo
WHERE
Column1 = 'testing'
AND (
(
Column2 = Column3
OR Column4 >= NOW()
)
);"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_with_complex_where_inline() {
let input = indoc!(
"
SELECT * FROM foo WHERE Column1 = 'testing'
AND ( (Column2 = Column3 OR Column4 >= NOW()) );
"
);
let options = FormatOptions {
max_inline_arguments: Some(100),
..Default::default()
};
let expected = indoc!(
"
SELECT
*
FROM
foo
WHERE
Column1 = 'testing' AND ((Column2 = Column3 OR Column4 >= NOW()));"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_with_top_level_reserved_words() {
let input = indoc!(
"
SELECT * FROM foo WHERE name = 'John' GROUP BY some_column
HAVING column > 10 ORDER BY other_column LIMIT 5;
"
);
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
*
FROM
foo
WHERE
name = 'John'
GROUP BY
some_column
HAVING
column > 10
ORDER BY
other_column
LIMIT
5;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_with_for_update_of() {
let input: &'static str = "SELECT id FROM users WHERE disabled_at IS NULL FOR UPDATE OF users SKIP LOCKED LIMIT 1";
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
id
FROM
users
WHERE
disabled_at IS NULL
FOR UPDATE
OF users SKIP LOCKED
LIMIT
1"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_limit_with_two_comma_separated_values_on_single_line() {
let input = "LIMIT 5, 10;";
let options = FormatOptions::default();
let expected = indoc!(
"
LIMIT
5, 10;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_limit_of_single_value_followed_by_another_select_using_commas() {
let input = "LIMIT 5; SELECT foo, bar;";
let options = FormatOptions::default();
let expected = indoc!(
"
LIMIT
5;
SELECT
foo,
bar;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_type_specifiers() {
let input = "SELECT id, ARRAY [] :: UUID [] FROM UNNEST($1 :: UUID []) WHERE $1::UUID[] IS NOT NULL;";
let options = FormatOptions {
dialect: Dialect::PostgreSql,
..Default::default()
};
let expected = indoc!(
"
SELECT
id,
ARRAY[]::UUID[]
FROM
UNNEST($1::UUID[])
WHERE
$1::UUID[] IS NOT NULL;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_arrays_as_function_arguments() {
let input =
"SELECT array_position(ARRAY['sun','mon','tue', 'wed', 'thu','fri', 'sat'], 'mon');";
let options = FormatOptions {
dialect: Dialect::PostgreSql,
..Default::default()
};
let expected = indoc!(
"
SELECT
array_position(
ARRAY['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
'mon'
);"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_arrays_as_values() {
let input = " INSERT INTO t VALUES('a', ARRAY[0, 1,2,3], ARRAY[['a','b'], ['c' ,'d']]);";
let options = FormatOptions {
dialect: Dialect::PostgreSql,
max_inline_block: 10,
max_inline_top_level: Some(50),
..Default::default()
};
let expected = indoc!(
"
INSERT INTO t
VALUES (
'a',
ARRAY[0, 1, 2, 3],
ARRAY[
['a', 'b'],
['c', 'd']
]
);"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_array_index_notation() {
let input = "SELECT a [ 1 ] + b [ 2 ] [ 5+1 ] > c [3] ;";
let options = FormatOptions {
dialect: Dialect::PostgreSql,
..Default::default()
};
let expected = indoc!(
"
SELECT
a[1] + b[2][5 + 1] > c[3];"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_limit_of_single_value_and_offset() {
let input = "LIMIT 5 OFFSET 8;";
let options = FormatOptions::default();
let expected = indoc!(
"
LIMIT
5 OFFSET 8;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_recognizes_limit_in_lowercase() {
let input = "limit 5, 10;";
let options = FormatOptions::default();
let expected = indoc!(
"
limit
5, 10;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_preserves_case_of_keywords() {
let input = "select distinct * frOM foo left join bar WHERe a > 1 and b = 3";
let options = FormatOptions::default();
let expected = indoc!(
"
select distinct
*
frOM
foo
left join bar
WHERe
a > 1
and b = 3"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_query_with_select_query_inside_it() {
let input = "SELECT *, SUM(*) AS sum FROM (SELECT * FROM Posts LIMIT 30) WHERE a > b";
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
*,
SUM(*) AS sum
FROM
(
SELECT
*
FROM
Posts
LIMIT
30
)
WHERE
a > b"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_does_format_drop() {
let input = indoc!(
"
DROP INDEX IF EXISTS idx_a;
DROP INDEX IF EXISTS idx_b;
"
);
let options = FormatOptions {
..Default::default()
};
let expected = indoc!(
"
DROP INDEX IF EXISTS
idx_a;
DROP INDEX IF EXISTS
idx_b;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
let input = indoc!(
r#"
-- comment
DROP TABLE IF EXISTS "public"."table_name";
"#
);
let expected = indoc!(
r#"
-- comment
DROP TABLE IF EXISTS
"public"."table_name";"#
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_query_with_inner_join() {
let input = indoc!(
"
SELECT customer_id.from, COUNT(order_id) AS total FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;"
);
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
customer_id.from,
COUNT(order_id) AS total
FROM
customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_query_with_non_standard_join() {
let input = indoc!(
"
SELECT customer_id.from, COUNT(order_id) AS total FROM customers
INNER ANY JOIN orders ON customers.customer_id = orders.customer_id
LEFT
SEMI JOIN foo ON foo.id = customers.id
PASTE
JOIN bar
;"
);
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
customer_id.from,
COUNT(order_id) AS total
FROM
customers
INNER ANY JOIN orders ON customers.customer_id = orders.customer_id
LEFT SEMI JOIN foo ON foo.id = customers.id
PASTE JOIN bar;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_query_with_non_standard_join_as_toplevel() {
let input = indoc!(
"
SELECT customer_id.from, COUNT(order_id) AS total FROM customers
INNER ANY JOIN orders ON customers.customer_id = orders.customer_id
LEFT
SEMI JOIN foo ON foo.id = customers.id
PASTE
JOIN bar
;"
);
let options = FormatOptions {
joins_as_top_level: true,
max_inline_top_level: Some(40),
max_inline_arguments: Some(40),
..Default::default()
};
let expected = indoc!(
"
SELECT
customer_id.from,
COUNT(order_id) AS total
FROM customers
INNER ANY JOIN
orders ON customers.customer_id = orders.customer_id
LEFT SEMI JOIN foo ON foo.id = customers.id
PASTE JOIN bar;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_select_query_with_different_comments() {
let input = indoc!(
"
SELECT
/*
* This is a block comment
*/
* FROM
-- This is another comment
MyTable # One final comment
WHERE 1 = 2;"
);
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
/*
* This is a block comment
*/
*
FROM
-- This is another comment
MyTable # One final comment
WHERE
1 = 2;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_maintains_block_comment_indentation() {
let input = indoc!(
"
SELECT
/*
* This is a block comment
*/
*
FROM
MyTable
WHERE
1 = 2;"
);
let options = FormatOptions::default();
assert_eq!(format(input, &QueryParams::None, &options), input);
}
#[test]
fn it_formats_simple_insert_query() {
let input = "INSERT INTO Customers (ID, MoneyBalance, Address, City) VALUES (12,-123.4, 'Skagen 2111','Stv');";
let options = FormatOptions::default();
let expected = indoc!(
"
INSERT INTO
Customers (ID, MoneyBalance, Address, City)
VALUES
(12, -123.4, 'Skagen 2111', 'Stv');"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_complex_insert_query() {
let input = "
INSERT INTO t(id, a, min, max) SELECT input.id, input.a, input.min, input.max FROM ( SELECT id, a, min, max FROM foo WHERE a IN ('a', 'b') ) AS input WHERE (SELECT true FROM condition) ON CONFLICT ON CONSTRAINT a_id_key DO UPDATE SET id = EXCLUDED.id, a = EXCLUDED.severity, min = EXCLUDED.min, max = EXCLUDED.max RETURNING *; ";
let max_line = 50;
let options = FormatOptions {
max_inline_block: max_line,
max_inline_arguments: Some(max_line),
max_inline_top_level: Some(max_line),
..Default::default()
};
let expected = indoc!(
"
INSERT INTO t(id, a, min, max)
SELECT input.id, input.a, input.min, input.max
FROM (
SELECT id, a, min, max
FROM foo
WHERE a IN ('a', 'b')
) AS input
WHERE (SELECT true FROM condition)
ON CONFLICT ON CONSTRAINT a_id_key DO UPDATE SET
id = EXCLUDED.id,
a = EXCLUDED.severity,
min = EXCLUDED.min,
max = EXCLUDED.max
RETURNING *;"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_keeps_short_parenthesized_list_with_nested_parenthesis_on_single_line() {
let input = "SELECT (a + b * (c - NOW()));";
let options = FormatOptions::default();
let expected = indoc!(
"
SELECT
(a + b * (c - NOW()));"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_breaks_long_parenthesized_lists_to_multiple_lines() {
let input = indoc!(
"
INSERT INTO some_table (id_product, id_shop, id_currency, id_country, id_registration) (
SELECT IF(dq.id_discounter_shopping = 2, dq.value, dq.value / 100),
IF (dq.id_discounter_shopping = 2, 'amount', 'percentage') FROM foo);"
);
let options = FormatOptions::default();
let expected = indoc!(
"
INSERT INTO
some_table (
id_product,
id_shop,
id_currency,
id_country,
id_registration
) (
SELECT
IF (
dq.id_discounter_shopping = 2,
dq.value,
dq.value / 100
),
IF (
dq.id_discounter_shopping = 2,
'amount',
'percentage'
)
FROM
foo
);"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_keep_long_parenthesized_lists_to_multiple_lines() {
let input = indoc!(
"
INSERT INTO some_table (id_product, id_shop, id_currency, id_country, id_registration) (
SELECT IF (dq.id_discounter_shopping = 2, dq.value, dq.value / 100),
IF (dq.id_discounter_shopping = 2, 'amount', 'percentage') FROM foo);"
);
let options = FormatOptions {
max_inline_block: 100,
..Default::default()
};
let expected = indoc!(
"
INSERT INTO
some_table (id_product, id_shop, id_currency, id_country, id_registration) (
SELECT
IF (dq.id_discounter_shopping = 2, dq.value, dq.value / 100),
IF (dq.id_discounter_shopping = 2, 'amount', 'percentage')
FROM
foo
);"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_simple_update_query() {
let input = "UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste';";
let options = FormatOptions::default();
let expected = indoc!(
"
UPDATE
Customers
SET
ContactName = 'Alfred Schmidt',
City = 'Hamburg'
WHERE
CustomerName = 'Alfreds Futterkiste';"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_simple_update_query_inlining_set() {
let input = "UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste';";
let options = FormatOptions {
max_inline_top_level: Some(20),
max_inline_arguments: Some(10),
..Default::default()
};
let expected = indoc!(
"
UPDATE Customers SET
ContactName = 'Alfred Schmidt',
City = 'Hamburg'
WHERE
CustomerName = 'Alfreds Futterkiste';"
);
assert_eq!(format(input, &QueryParams::None, &options), expected);
}
#[test]
fn it_formats_simple_delete_query() {