sqruff_lib/templaters/
placeholder.rs

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
use std::collections::HashMap;
use std::sync::Arc;

use fancy_regex::Regex;
use sqruff_lib_core::errors::SQLFluffUserError;
use sqruff_lib_core::templaters::base::{RawFileSlice, TemplatedFile, TemplatedFileSlice};

use crate::cli::formatters::Formatter;
use crate::core::config::FluffConfig;
use crate::templaters::Templater;

#[derive(Default)]
pub struct PlaceholderTemplater;

pub fn get_known_styles() -> HashMap<&'static str, Regex> {
    let mut m = HashMap::new();

    // e.g. WHERE bla = :name
    m.insert(
        "colon",
        Regex::new(r"(?<![:\w\\]):(?P<param_name>\w+)(?!:)").unwrap(),
    );

    // e.g. WHERE bla = table:name - use with caution as more prone to false
    // positives
    m.insert(
        "colon_nospaces",
        Regex::new(r"(?<!:):(?P<param_name>\w+)").unwrap(),
    );

    // e.g. WHERE bla = :2
    m.insert(
        "numeric_colon",
        Regex::new(r"(?<![:\w\\]):(?P<param_name>\d+)").unwrap(),
    );

    // e.g. WHERE bla = %(name)s
    m.insert(
        "pyformat",
        Regex::new(r"(?<![:\w\\])%\((?P<param_name>[\w_]+)\)s").unwrap(),
    );

    // e.g. WHERE bla = $name or WHERE bla = ${name}
    m.insert(
        "dollar",
        Regex::new(r"(?<![:\w\\])\${?(?P<param_name>[\w_]+)}?").unwrap(),
    );

    // e.g. USE ${flyway:database}.schema_name;
    m.insert(
        "flyway_var",
        Regex::new(r#"\${(?P<param_name>\w+[:\w_]+)}"#).unwrap(),
    );

    // e.g. WHERE bla = ?
    m.insert("question_mark", Regex::new(r"(?<![:\w\\])\?").unwrap());

    // e.g. WHERE bla = $3 or WHERE bla = ${3}
    m.insert(
        "numeric_dollar",
        Regex::new(r"(?<![:\w\\])\${?(?P<param_name>[\d]+)}?").unwrap(),
    );

    // e.g. WHERE bla = %s
    m.insert("percent", Regex::new(r"(?<![:\w\\])%s").unwrap());

    // e.g. WHERE bla = &s or WHERE bla = &{s} or USE DATABASE {ENV}_MARKETING
    m.insert(
        "ampersand",
        Regex::new(r"(?<!&)&{?(?P<param_name>[\w]+)}?").unwrap(),
    );

    m
}

const DEFAULT_STYLE: &str = "colon";

const NO_PARAM_OR_STYLE: &str =
    "No param_regex nor param_style was provided to the placeholder templater.";

impl PlaceholderTemplater {
    fn derive_style(&self, config: Option<&FluffConfig>) -> Result<Regex, SQLFluffUserError> {
        if config.is_none() {
            return Ok(get_known_styles().get(DEFAULT_STYLE).unwrap().clone());
        }
        let config = config.ok_or(SQLFluffUserError::new(
            "No config provided to templater 'placeholder'".to_string(),
        ))?;
        let config = config
            .get("placeholder", "templater")
            .as_map()
            .ok_or(SQLFluffUserError::new(NO_PARAM_OR_STYLE.to_string()))?;
        match (config.get("param_regex"), config.get("param_style")) {
            (Some(_), Some(_)) => Err(SQLFluffUserError::new(
                "Both param_regex and param_style were provided to the placeholder templater."
                    .to_string(),
            )),
            (None, None) => Err(SQLFluffUserError::new(NO_PARAM_OR_STYLE.to_string())),
            (Some(param_regex), None) => {
                let param_regex = param_regex.as_string().ok_or(SQLFluffUserError::new(
                    "Invalid param_regex for templater 'placeholder'".to_string(),
                ))?;
                let regex = Regex::new(param_regex).map_err(|e| {
                    SQLFluffUserError::new(format!("Invalid regex for param_regex: {}", e))
                })?;
                Ok(regex)
            }
            (None, Some(param_style)) => {
                let param_style = param_style.as_string().ok_or(SQLFluffUserError::new(
                    "Invalid param_style for templater 'placeholder'".to_string(),
                ))?;
                let known_styles = get_known_styles();
                let regex = known_styles.get(param_style).ok_or_else(|| {
                    SQLFluffUserError::new(format!(
                        "Unknown param_style '{}' for templater 'placeholder'",
                        param_style
                    ))
                })?;
                Ok(regex.clone())
            }
        }
    }
}

impl Templater for PlaceholderTemplater {
    fn name(&self) -> &'static str {
        "placeholder"
    }

    fn description(&self) -> &'static str {
        r#"Libraries such as SQLAlchemy or Psycopg use different parameter placeholder styles to mark where a parameter has to be inserted in the query.

For example a query in SQLAlchemy can look like this:

```sql
SELECT * FROM table WHERE id = :myid
```

At runtime :myid will be replace by a value provided by the application and escaped as needed, but this is not standard SQL and cannot be parsed as is.

In order to parse these queries is then necessary to replace these placeholders with sample values, and this is done with the placeholder templater.

Placeholder templating can be enabled in the config using:

```ini
[sqruff]
templater = placeholder
```

A few common styles are supported:

```sql
 -- colon
 WHERE bla = :my_name

 -- colon_nospaces
 -- (use with caution as more prone to false positives)
 WHERE bla = table:my_name

 -- colon_optional_quotes
 SELECT :"column" FROM :table WHERE bla = :'my_name'

 -- numeric_colon
 WHERE bla = :2

 -- pyformat
 WHERE bla = %(my_name)s

 -- dollar
 WHERE bla = $my_name or WHERE bla = ${my_name}

 -- question_mark
 WHERE bla = ?

 -- numeric_dollar
 WHERE bla = $3 or WHERE bla = ${3}

 -- percent
 WHERE bla = %s

 -- ampersand
 WHERE bla = &s or WHERE bla = &{s} or USE DATABASE MARK_{ENV}
```

The can be configured by setting `param_style` in the config file. For example:

```ini
[sqruff:templater:placeholder]
param_style = colon
my_name = 'john'
```

then you can set sample values for each parameter, like my_name above. Notice that the value needs to be escaped as it will be replaced as a string during parsing. When the sample values aren’t provided, the templater will use parameter names themselves by default.

When parameters are positional, like question_mark, then their name is simply the order in which they appear, starting with 1.

```ini
[sqruff:templater:placeholder]
param_style = question_mark
1 = 'john'
```

In case you nbeed a parameter style different from the ones provided, you can set `param_regex` in the config file. For example:

```ini
[sqruff:templater:placeholder]
param_regex = __(?P<param_name>[\w_]+)__
my_name = 'john'
```

N.B. quotes around param_regex in the config are interpreted literally by the templater. e.g. param_regex=’__(?P<param_name>[w_]+)__’ matches ‘__some_param__’ not __some_param__

the named parameter param_name will be used as the key to replace, if missing, the parameter is assumed to be positional and numbers are used instead.

Also consider making a pull request to the project to have your style added, it may be useful to other people and simplify your configuration."#
    }

    fn process(
        &self,
        in_str: &str,
        f_name: &str,
        config: Option<&FluffConfig>,
        _: &Option<Arc<dyn Formatter>>,
    ) -> Result<TemplatedFile, SQLFluffUserError> {
        let mut template_slices = vec![];
        let mut raw_slices = vec![];
        let mut last_pos_raw = 0usize;
        let mut last_pos_templated = 0;
        let mut out_str = "".to_string();

        // when the param has no name, use a 1-based index
        let mut param_counter = 1;
        let regex = self.derive_style(config)?;

        let template_config =
            config.and_then(|config| config.get("placeholder", "templater").as_map());

        for cap in regex.captures_iter(in_str) {
            let cap = cap.unwrap();
            let span = cap.get(0).unwrap().range();

            let param_name = if let Some(name) = cap.name("param_name") {
                name.as_str().to_string()
            } else {
                let name = param_counter.to_string();
                param_counter += 1;
                name
            };

            let last_literal_length = span.start - last_pos_raw;
            let replacement = template_config
                .and_then(|config| config.get(&param_name))
                .map_or(Ok(param_name.clone()), |v| {
                    match (v.as_string(), v.as_int(), v.as_bool()) {
                        (Some(s), None, None) => Ok(s.to_string()),
                        (None, Some(i), None) => Ok(i.to_string()),
                        (None, None, Some(b)) => Ok(if b {
                            "true".to_string()
                        } else {
                            "false".to_string()
                        }),
                        _ => Err(SQLFluffUserError::new(format!(
                            "Invalid value for parameter replacement: {}",
                            param_name
                        ))),
                    }
                })?;

            // Add the literal to the slices
            template_slices.push(TemplatedFileSlice {
                slice_type: "literal".to_string(),
                source_slice: last_pos_raw..span.start,
                templated_slice: last_pos_templated..last_pos_templated + last_literal_length,
            });

            raw_slices.push(RawFileSlice::new(
                in_str[last_pos_raw..span.start].to_string(),
                "literal".to_string(),
                last_pos_raw,
                None,
                None,
            ));

            out_str.push_str(&in_str[last_pos_raw..span.start]);

            // Add the current replaced element
            let start_template_pos = last_pos_templated + last_literal_length;
            template_slices.push(TemplatedFileSlice {
                slice_type: "templated".to_string(),
                source_slice: span.clone(),
                templated_slice: start_template_pos..start_template_pos + replacement.len(),
            });

            let raw_file_slice = RawFileSlice::new(
                in_str[span.clone()].to_string(),
                "templated".to_string(),
                span.start,
                None,
                None,
            );
            raw_slices.push(raw_file_slice);

            out_str.push_str(&replacement);

            // Update the indexes
            last_pos_raw = span.end;
            last_pos_templated = start_template_pos + replacement.len();
        }

        // Add the last literal, if any
        if in_str.len() > last_pos_raw {
            template_slices.push(TemplatedFileSlice {
                slice_type: "literal".to_string(),
                source_slice: last_pos_raw..in_str.len(),
                templated_slice: last_pos_templated
                    ..last_pos_templated + (in_str.len() - last_pos_raw),
            });

            let raw_file_slice = RawFileSlice::new(
                in_str[last_pos_raw..].to_string(),
                "literal".to_string(),
                last_pos_raw,
                None,
                None,
            );
            raw_slices.push(raw_file_slice);

            out_str.push_str(&in_str[last_pos_raw..]);
        }

        let templated_file = TemplatedFile::new(
            in_str.to_string(),
            f_name.to_string(),
            Some(out_str),
            Some(template_slices),
            Some(raw_slices),
        )
        .unwrap();

        Ok(templated_file)
    }
}

#[cfg(test)]
mod tests {
    use std::mem::take;

    use super::*;
    use crate::core::linter::core::Linter;

    #[test]
    /// Test the templaters when nothing has to be replaced.
    fn test_templater_no_replacement() {
        let templater = PlaceholderTemplater {};
        let in_str = "SELECT * FROM {{blah}} WHERE %(gnepr)s OR e~':'";
        let out_str = templater.process(in_str, "test.sql", None, &None).unwrap();
        let out = out_str.templated();
        assert_eq!(in_str, out)
    }

    #[test]
    fn test_all_the_known_styles() {
        // in, param_style, expected_out, values
        let cases: [(&str, &str, &str, Vec<(&str, &str)>); 16] = [
            (
                "SELECT * FROM f, o, o WHERE a < 10\n\n",
                "colon",
                "SELECT * FROM f, o, o WHERE a < 10\n\n",
                vec![],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE userid = :user_id AND date > :start_date
"#,
                "colon",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE userid = 42 AND date > '2020-01-01'
"#,
                vec![
                    ("user_id", "42"),
                    ("start_date", "'2020-01-01'"),
                    ("city_ids", "(1, 2, 3)"),
                ],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE userid = :user_id AND date > :start_date"#,
                "colon",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE userid = 42 AND date > '2020-01-01'"#,
                vec![
                    ("user_id", "42"),
                    ("start_date", "'2020-01-01'"),
                    ("city_ids", "(1, 2, 3)"),
                ],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN :city_ids
AND date > '2020-10-01'
            "#,
                "colon",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN (1, 2, 3)
AND date > '2020-10-01'
            "#,
                vec![
                    ("user_id", "42"),
                    ("start_date", "'2020-01-01'"),
                    ("city_ids", "(1, 2, 3)"),
                ],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data:table_suffix
"#,
                "colon_nospaces",
                r#"
SELECT user_mail, city_id
FROM users_data42
"#,
                vec![("table_suffix", "42")],
            ),
            (
                // Postgres uses double-colons for type casts, see
                // https://www.postgresql.org/docs/current/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS
                // This test ensures we don't confuse them with colon placeholders.
                r#"
SELECT user_mail, city_id, joined::date
FROM users_date:table_suffix
"#,
                "colon_nospaces",
                r#"
SELECT user_mail, city_id, joined::date
FROM users_date42
"#,
                vec![("table_suffix", "42")],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN ?
AND date > ?
            "#,
                "question_mark",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN (1, 2, 3, 45)
AND date > '2020-10-01'
            "#,
                vec![("1", "(1, 2, 3, 45)"), ("2", "'2020-10-01'")],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN :1
AND date > :45
            "#,
                "numeric_colon",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN (1, 2, 3, 45)
AND date > '2020-10-01'
            "#,
                vec![("1", "(1, 2, 3, 45)"), ("45", "'2020-10-01'")],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN %(city_id)s
AND date > %(date)s
AND someflag = %(someflag)s
LIMIT %(limit)s
            "#,
                "pyformat",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN (1, 2, 3, 45)
AND date > '2020-10-01'
AND someflag = false
LIMIT 15
            "#,
                vec![
                    ("city_id", "(1, 2, 3, 45)"),
                    ("date", "'2020-10-01'"),
                    ("limit", "15"),
                    ("someflag", "false"),
                ],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN $city_id
AND date > $date
OR date = ${date}
            "#,
                "dollar",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN (1, 2, 3, 45)
AND date > '2020-10-01'
OR date = '2020-10-01'
            "#,
                vec![("city_id", "(1, 2, 3, 45)"), ("date", "'2020-10-01'")],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN $12
AND date > $90
            "#,
                "numeric_dollar",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN (1, 2, 3, 45)
AND date > '2020-10-01'
            "#,
                vec![("12", "(1, 2, 3, 45)"), ("90", "'2020-10-01'")],
            ),
            (
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN %s
AND date > %s
            "#,
                "percent",
                r#"
SELECT user_mail, city_id
FROM users_data
WHERE (city_id) IN (1, 2, 3, 45)
AND date > '2020-10-01'
            "#,
                vec![("1", "(1, 2, 3, 45)"), ("2", "'2020-10-01'")],
            ),
            (
                r#"
USE DATABASE &{env}_MARKETING;
USE SCHEMA &&EMEA;
SELECT user_mail, city_id
FROM users_data
WHERE userid = &user_id AND date > &{start_date}
            "#,
                "ampersand",
                r#"
USE DATABASE PRD_MARKETING;
USE SCHEMA &&EMEA;
SELECT user_mail, city_id
FROM users_data
WHERE userid = 42 AND date > '2021-10-01'
            "#,
                vec![
                    ("env", "PRD"),
                    ("user_id", "42"),
                    ("start_date", "'2021-10-01'"),
                ],
            ),
            (
                "USE ${flywaydatabase}.test_schema;",
                "flyway_var",
                "USE test_db.test_schema;",
                vec![("flywaydatabase", "test_db")],
            ),
            (
                "SELECT metadata$filename, $1 FROM @stg_data_export_${env_name};",
                "flyway_var",
                "SELECT metadata$filename, $1 FROM @stg_data_export_staging;",
                vec![("env_name", "staging")],
            ),
            (
                "SELECT metadata$filename, $1 FROM @stg_data_export_${env_name};",
                "flyway_var",
                "SELECT metadata$filename, $1 FROM @stg_data_export_env_name;",
                vec![],
            ),
        ];

        for (in_str, param_style, expected_out, values) in cases {
            let config = FluffConfig::from_source(
                format!(
                    r#"
[sqruff:templater:placeholder]
param_style = {}
{}
"#,
                    param_style,
                    values
                        .iter()
                        .map(|(k, v)| format!("{} = {}", k, v))
                        .collect::<Vec<String>>()
                        .join("\n")
                )
                .as_str(),
            );
            let templater = PlaceholderTemplater {};
            let out_str = templater
                .process(in_str, "test.sql", Some(&config), &None)
                .unwrap();
            let out = out_str.templated();
            assert_eq!(expected_out, out)
        }
    }

    #[test]
    /// Test the error raised when config is incomplete, as in no param_regex
    /// nor param_style.
    fn test_templater_setup_none() {
        let config = FluffConfig::from_source(
            r#"
            "#,
        );
        let templater = PlaceholderTemplater {};
        let in_str = "SELECT 2+2";
        let out_str = templater.process(in_str, "test.sql", Some(&config), &None);

        assert!(out_str.is_err());
        assert_eq!(
            out_str.err().unwrap().value,
            "No param_regex nor param_style was provided to the placeholder templater."
        );
    }

    #[test]
    /// Test the error raised when both param_regex and param_style are
    /// provided.
    fn test_templater_setup_both_provided() {
        let config = FluffConfig::from_source(
            r#"
[sqruff:templater:placeholder]
param_regex = __(?P<param_name>[\w_]+)__
param_style = colon
            "#,
        );
        let templater = PlaceholderTemplater {};
        let in_str = "SELECT 2+2";
        let out_str = templater.process(in_str, "test.sql", Some(&config), &None);

        assert!(out_str.is_err());
        assert_eq!(
            out_str.err().unwrap().value,
            "Both param_regex and param_style were provided to the placeholder templater."
        );
    }

    #[test]
    /// Test custom regex templating.
    fn test_templater_custom_regex() {
        let config = FluffConfig::from_source(
            r#"
[sqruff:templater:placeholder]
param_regex = __(?P<param_name>[\w_]+)__
my_name = john
"#,
        );
        let templater = PlaceholderTemplater {};
        let in_str = "SELECT bla FROM blob WHERE id = __my_name__";
        let out_str = templater
            .process(in_str, "test", Some(&config), &None)
            .unwrap();
        let out = out_str.templated();
        assert_eq!("SELECT bla FROM blob WHERE id = john", out)
    }

    #[test]
    /// Test the exception raised when parameter styles is unknown.
    fn test_templater_styles_not_existing() {
        let config = FluffConfig::from_source(
            r#"
[sqruff:templater:placeholder]
param_style = unknown
            "#,
        );
        let templater = PlaceholderTemplater {};
        let in_str = "SELECT * FROM {{blah}} WHERE %(gnepr)s OR e~':'";
        let out_str = templater.process(in_str, "test.sql", Some(&config), &None);

        assert!(out_str.is_err());
        assert_eq!(
            out_str.err().unwrap().value,
            "Unknown param_style 'unknown' for templater 'placeholder'"
        );
    }

    #[test]
    /// Test the linter fully with this templater.
    fn test_templater_placeholder() {
        let config = FluffConfig::from_source(
            r#"
[sqruff]
dialect = ansi
templater = placeholder
rules = all

[sqruff:templater:placeholder]
param_style = percent
"#,
        );
        let sql = "SELECT a,b FROM users WHERE a = %s";

        let mut linter = Linter::new(config, None, None);
        let mut result = linter.lint_string_wrapped(sql, None, true);
        let result = take(&mut result.paths[0].files[0]).fix_string();

        assert_eq!(result, "SELECT\n    a,\n    b\nFROM users WHERE a = %s\n");
    }
}