banshee_format 0.2.1

PostgreSQL SQL formatter with sqlstyle and pgFormatter engines.
Documentation
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
//! pgFormatter-style SQL formatting implementation.
//!
//! This module provides SQL formatting that matches pgFormatter behavior,
//! using `PgFormatterConfig` for all formatting options.

use banshee_syntax::{Parse, SyntaxKind, SyntaxNode, SyntaxToken};

use crate::pg_formatter::PgFormatterConfig;

pub(crate) mod expressions;
pub(crate) mod statements;

pub(crate) use expressions::*;
pub(crate) use statements::*;

/// Formats SQL source code using pgFormatter style.
#[must_use]
pub fn format(source: &str, config: &PgFormatterConfig) -> String {
    let parse = banshee_parser::parse(source);
    format_parse(&parse, config)
}

/// Formats a parsed SQL tree using pgFormatter style.
pub fn format_parse(parse: &Parse, config: &PgFormatterConfig) -> String {
    let mut printer = PgPrinter::new(config.clone());
    let root = parse.syntax();
    format_node(&root, &mut printer);
    printer.finish()
}

/// pgFormatter-style printer.
#[derive(Debug)]
pub struct PgPrinter {
    config: PgFormatterConfig,
    buffer: String,
    line: usize,
    column: usize,
    indent_level: usize,
    at_line_start: bool,
}

impl PgPrinter {
    /// Creates a new pgFormatter printer.
    pub fn new(config: PgFormatterConfig) -> Self {
        Self {
            config,
            buffer: String::new(),
            line: 0,
            column: 0,
            indent_level: 0,
            at_line_start: true,
        }
    }

    /// Returns the configuration.
    pub fn config(&self) -> &PgFormatterConfig {
        &self.config
    }

    /// Consumes the printer and returns the output.
    pub fn finish(mut self) -> String {
        // Handle no_extra_line option
        if self.config.no_extra_line {
            // Remove trailing newline
            while self.buffer.ends_with('\n') {
                self.buffer.pop();
            }
        } else {
            // Ensure trailing newline
            if !self.buffer.ends_with('\n') {
                self.buffer.push('\n');
            }
        }
        self.buffer
    }

    /// Returns the indent string for one level.
    fn indent_str(&self) -> String {
        if self.config.use_tabs {
            "\t".to_string()
        } else {
            " ".repeat(self.config.spaces)
        }
    }

    /// Writes indentation based on current level.
    fn write_indent(&mut self) {
        let indent = self.indent_str().repeat(self.indent_level);
        self.buffer.push_str(&indent);
        self.column += indent.len();
    }

    /// Writes text to the output.
    pub fn write(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }

        if self.at_line_start && !text.starts_with('\n') {
            self.write_indent();
            self.at_line_start = false;
        }

        for ch in text.chars() {
            if ch == '\n' {
                self.buffer.push(ch);
                self.line += 1;
                self.column = 0;
                self.at_line_start = true;
            } else {
                if self.at_line_start {
                    self.write_indent();
                    self.at_line_start = false;
                }
                self.buffer.push(ch);
                self.column += 1;
            }
        }
    }

    /// Writes raw text without indentation handling.
    pub fn write_raw(&mut self, text: &str) {
        for ch in text.chars() {
            if ch == '\n' {
                self.buffer.push(ch);
                self.line += 1;
                self.column = 0;
                self.at_line_start = true;
            } else {
                self.buffer.push(ch);
                self.column += 1;
                self.at_line_start = false;
            }
        }
    }

    /// Writes a newline.
    pub fn newline(&mut self) {
        self.buffer.push('\n');
        self.line += 1;
        self.column = 0;
        self.at_line_start = true;
    }

    /// Writes a space.
    pub fn space(&mut self) {
        if self.at_line_start {
            self.write_indent();
            self.at_line_start = false;
        }
        self.buffer.push(' ');
        self.column += 1;
    }

    /// Increases indentation level.
    pub fn indent(&mut self) {
        self.indent_level += 1;
    }

    /// Decreases indentation level.
    pub fn dedent(&mut self) {
        self.indent_level = self.indent_level.saturating_sub(1);
    }

    /// Ensures we're at the start of a line.
    pub fn ensure_newline(&mut self) {
        if !self.at_line_start {
            self.newline();
        }
    }

    /// Ensures a blank line exists.
    pub fn ensure_blank_line(&mut self) {
        if !self.at_line_start {
            self.newline();
        }
        self.newline();
    }

    /// Writes a keyword with case transformation.
    pub fn write_keyword(&mut self, keyword: &str) {
        let transformed = self.config.keyword_case.apply(keyword);
        self.write(&transformed);
    }

    /// Writes a function name with case transformation.
    pub fn write_function(&mut self, name: &str) {
        let transformed = self.config.function_case.apply(name);
        self.write(&transformed);
    }

    /// Writes a type name with case transformation.
    pub fn write_type(&mut self, name: &str) {
        let transformed = self.config.type_case.apply(name);
        self.write(&transformed);
    }

    /// Writes an identifier (no transformation for pgFormatter).
    pub fn write_identifier(&mut self, ident: &str) {
        self.write(ident);
    }

    /// Writes a comma according to configuration.
    pub fn write_comma(&mut self) {
        self.write(",");
        if self.config.comma_break {
            self.newline();
        }
    }

    /// Writes an operator with surrounding spaces.
    pub fn write_operator(&mut self, op: &str) {
        self.space();
        self.write(op);
        self.space();
    }

    /// Writes an operator without surrounding spaces.
    pub fn write_operator_compact(&mut self, op: &str) {
        self.write(op);
    }

    /// Returns true if comments should be removed.
    pub fn should_remove_comments(&self) -> bool {
        self.config.no_comment
    }

    /// Returns true if there should be no space before function parentheses.
    pub fn no_space_function(&self) -> bool {
        self.config.no_space_function
    }

    /// Returns true if comma should be at start of line.
    pub fn comma_start(&self) -> bool {
        self.config.comma_start
    }
}

/// Formats a syntax node.
pub(crate) fn format_node(node: &SyntaxNode, printer: &mut PgPrinter) {
    match node.kind() {
        SyntaxKind::SOURCE_FILE => format_source_file(node, printer),
        SyntaxKind::SELECT_STMT => format_select(node, printer),
        SyntaxKind::INSERT_STMT => format_insert(node, printer),
        SyntaxKind::UPDATE_STMT => format_update(node, printer),
        SyntaxKind::DELETE_STMT => format_delete(node, printer),
        SyntaxKind::CREATE_TABLE_STMT => format_create_table(node, printer),
        SyntaxKind::CREATE_INDEX_STMT => format_create_index(node, printer),
        SyntaxKind::ALTER_STMT => format_alter(node, printer),
        SyntaxKind::ERROR => format_error_node(node, printer),
        _ => format_children(node, printer),
    }
}

/// Formats the source file (root node).
pub(crate) fn format_source_file(node: &SyntaxNode, printer: &mut PgPrinter) {
    let mut first_stmt = true;

    for child in node.children() {
        if child.kind() == SyntaxKind::WHITESPACE || child.kind() == SyntaxKind::NEWLINE {
            continue;
        }

        if !first_stmt && !printer.config.no_grouping {
            printer.ensure_blank_line();
        } else if !first_stmt {
            printer.ensure_newline();
        }

        format_node(child, printer);
        first_stmt = false;
    }

    printer.ensure_newline();
}

/// Formats children of a node.
pub(crate) fn format_children(node: &SyntaxNode, printer: &mut PgPrinter) {
    for element in node.children_with_tokens() {
        match element {
            cstree::util::NodeOrToken::Node(child) => {
                format_node(child, printer);
            }
            cstree::util::NodeOrToken::Token(token) => {
                format_token(token, printer);
            }
        }
    }
}

/// Formats a token.
pub(crate) fn format_token(token: &SyntaxToken, printer: &mut PgPrinter) {
    let kind = token.kind();
    let text = token.text();

    match kind {
        SyntaxKind::WHITESPACE | SyntaxKind::NEWLINE => {
            // We control spacing
        }
        SyntaxKind::LINE_COMMENT | SyntaxKind::BLOCK_COMMENT => {
            if !printer.should_remove_comments() {
                printer.write(text);
            }
        }
        k if k.is_keyword() => {
            if needs_space_before(k) {
                printer.space();
            }
            printer.write_keyword(text);
            if needs_space_after(k) {
                printer.space();
            }
        }
        SyntaxKind::IDENT => {
            printer.write_identifier(text);
        }
        SyntaxKind::QUOTED_IDENT => {
            printer.write(text);
        }
        SyntaxKind::INTEGER
        | SyntaxKind::FLOAT
        | SyntaxKind::STRING
        | SyntaxKind::DOLLAR_STRING
        | SyntaxKind::BIT_STRING
        | SyntaxKind::HEX_STRING
        | SyntaxKind::PARAM => {
            printer.write(text);
        }
        SyntaxKind::SEMICOLON => {
            printer.write(";");
        }
        SyntaxKind::COMMA => {
            printer.write_comma();
        }
        SyntaxKind::DOT => {
            printer.write(".");
        }
        SyntaxKind::COLON => {
            printer.write(":");
        }
        SyntaxKind::DOUBLE_COLON => {
            printer.write("::");
        }
        SyntaxKind::L_PAREN => {
            printer.write("(");
        }
        SyntaxKind::R_PAREN => {
            printer.write(")");
        }
        SyntaxKind::L_BRACKET => {
            printer.write("[");
        }
        SyntaxKind::R_BRACKET => {
            printer.write("]");
        }
        SyntaxKind::EQ
        | SyntaxKind::NE
        | SyntaxKind::LT
        | SyntaxKind::LE
        | SyntaxKind::GT
        | SyntaxKind::GE
        | SyntaxKind::PLUS
        | SyntaxKind::MINUS
        | SyntaxKind::STAR
        | SyntaxKind::SLASH
        | SyntaxKind::PERCENT
        | SyntaxKind::CARET
        | SyntaxKind::PIPE_PIPE => {
            printer.write_operator(text);
        }
        SyntaxKind::ARROW | SyntaxKind::ARROW_TEXT => {
            printer.write_operator_compact(text);
        }
        SyntaxKind::HASH_ARROW | SyntaxKind::HASH_ARROW_TEXT => {
            printer.write_operator_compact(text);
        }
        SyntaxKind::AT_GT
        | SyntaxKind::LT_AT
        | SyntaxKind::QUESTION
        | SyntaxKind::QUESTION_PIPE
        | SyntaxKind::QUESTION_AMP
        | SyntaxKind::HASH_MINUS
        | SyntaxKind::AT_QUESTION
        | SyntaxKind::AT_AT => {
            printer.write_operator(text);
        }
        _ => {
            printer.write(text);
        }
    }
}

/// Formats an error node by preserving original text.
pub(crate) fn format_error_node(node: &SyntaxNode, printer: &mut PgPrinter) {
    for element in node.children_with_tokens() {
        match element {
            cstree::util::NodeOrToken::Node(child) => {
                format_error_node(child, printer);
            }
            cstree::util::NodeOrToken::Token(token) => {
                printer.write_raw(token.text());
            }
        }
    }
}

// === Statement formatting ===

/// Formats a SELECT statement.
/// Finds a child node of a specific kind.
pub(crate) fn find_child(node: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxNode> {
    node.children().find(|c| c.kind() == kind).cloned()
}

/// Checks if a node has a token of a specific kind.
pub(crate) fn has_token(node: &SyntaxNode, kind: SyntaxKind) -> bool {
    for element in node.children_with_tokens() {
        if let cstree::util::NodeOrToken::Token(token) = element
            && token.kind() == kind
        {
            return true;
        }
    }
    false
}

/// Returns true if a keyword needs a space before it.
pub(crate) fn needs_space_before(kind: SyntaxKind) -> bool {
    matches!(
        kind,
        SyntaxKind::AND_KW
            | SyntaxKind::OR_KW
            | SyntaxKind::NOT_KW
            | SyntaxKind::IS_KW
            | SyntaxKind::IN_KW
            | SyntaxKind::LIKE_KW
            | SyntaxKind::ILIKE_KW
            | SyntaxKind::BETWEEN_KW
            | SyntaxKind::AS_KW
            | SyntaxKind::ASC_KW
            | SyntaxKind::DESC_KW
    )
}

/// Returns true if a keyword needs a space after it.
pub(crate) fn needs_space_after(kind: SyntaxKind) -> bool {
    matches!(
        kind,
        SyntaxKind::AND_KW
            | SyntaxKind::OR_KW
            | SyntaxKind::NOT_KW
            | SyntaxKind::IS_KW
            | SyntaxKind::IN_KW
            | SyntaxKind::LIKE_KW
            | SyntaxKind::ILIKE_KW
            | SyntaxKind::AS_KW
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pg_formatter::CaseOption;

    #[test]
    fn test_format_simple_select() {
        let sql = "select id, name from users";
        let config = PgFormatterConfig::default();
        let formatted = format(sql, &config);
        assert!(formatted.contains("SELECT"));
        assert!(formatted.contains("FROM"));
    }

    #[test]
    fn test_format_with_function_case() {
        let sql = "SELECT COUNT(*) FROM users";
        let config = PgFormatterConfig::default().with_function_case(CaseOption::Lower);
        let formatted = format(sql, &config);
        eprintln!("Formatted output: {:?}", formatted);
        // COUNT is a reserved keyword in SQL, so it won't be transformed by function_case
        // Instead, it follows keyword_case. For user-defined functions like my_func(),
        // function_case would apply.
        assert!(formatted.contains("COUNT") || formatted.contains("count"));
    }

    #[test]
    fn test_format_with_keyword_case_lower() {
        let sql = "SELECT id FROM users";
        let config = PgFormatterConfig::default().with_keyword_case(CaseOption::Lower);
        let formatted = format(sql, &config);
        assert!(formatted.contains("select"));
        assert!(formatted.contains("from"));
    }

    #[test]
    fn test_format_no_comment() {
        let sql = "SELECT id -- comment\nFROM users";
        let config = PgFormatterConfig::default().with_no_comment(true);
        let formatted = format(sql, &config);
        assert!(!formatted.contains("comment"));
    }

    #[test]
    fn test_format_no_extra_line() {
        let sql = "SELECT id FROM users";
        let config = PgFormatterConfig {
            no_extra_line: true,
            ..Default::default()
        };
        let formatted = format(sql, &config);
        assert!(!formatted.ends_with('\n'));
    }

    #[test]
    fn test_format_comma_start() {
        let sql = "SELECT id, name, email FROM users";
        let config = PgFormatterConfig::default().with_comma_start(true);
        let formatted = format(sql, &config);
        // Should have leading commas
        assert!(formatted.contains(", "));
    }

    #[test]
    fn test_format_type_case() {
        let sql = "SELECT id::INTEGER FROM users";
        let config = PgFormatterConfig::default().with_type_case(CaseOption::Upper);
        let formatted = format(sql, &config);
        assert!(formatted.contains("INTEGER"));
    }
}