Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Possible to provide an escape hatch for expressions #51

Merged
merged 8 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ categories = ["development-tools"]
[dependencies]
nom = "7.0.0"
unicode_categories = "0.1.1"
lazy_static = "1"
shssoichiro marked this conversation as resolved.
Show resolved Hide resolved
regex = "=1.6"

[dev-dependencies]
criterion = "0.5"
Expand Down
46 changes: 36 additions & 10 deletions src/formatter.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use regex::Regex;
use std::borrow::Cow;

use crate::indentation::Indentation;
Expand All @@ -6,12 +7,42 @@ use crate::params::Params;
use crate::tokenizer::{Token, TokenKind};
use crate::{FormatOptions, QueryParams};

use lazy_static::lazy_static;

lazy_static! {
static ref RE: Regex = Regex::new(r"(?i)^(--|/\*)\s*fmt\s*:\s*(off|on)").unwrap();
}

pub(crate) fn check_fmt_off(s: &str) -> Option<bool> {
RE.captures(s)?
.get(2)
.map(|matched| matched.as_str().eq_ignore_ascii_case("off"))
}

pub(crate) fn format(tokens: &[Token<'_>], params: &QueryParams, options: FormatOptions) -> String {
let mut formatter = Formatter::new(tokens, params, options);
let mut formatted_query = String::new();
let mut is_fmt_enabled = true;
let mut is_prev_token_fmt_switch = false;
for (index, token) in tokens.iter().enumerate() {
if is_prev_token_fmt_switch {
is_prev_token_fmt_switch = false;
continue;
}
if matches!(token.kind, TokenKind::LineComment | TokenKind::BlockComment) {
if let Some(is_fmt_off) = check_fmt_off(token.value) {
is_fmt_enabled = !is_fmt_off;
is_prev_token_fmt_switch = true;
continue;
}
}
formatter.index = index;

if !is_fmt_enabled {
formatter.format_no_change(token, &mut formatted_query);
continue;
}

if token.kind == TokenKind::Whitespace {
// ignore (we do our own whitespace formatting)
} else if token.kind == TokenKind::LineComment {
Expand Down Expand Up @@ -79,16 +110,7 @@ impl<'a> Formatter<'a> {
self.next_token(1).map_or(false, |current_token| {
current_token.kind == TokenKind::Whitespace
&& self.next_token(2).map_or(false, |next_token| {
matches!(
next_token.kind,
TokenKind::Number
| TokenKind::String
| TokenKind::Word
| TokenKind::ReservedTopLevel
| TokenKind::ReservedTopLevelNoIndent
| TokenKind::ReservedNewline
| TokenKind::Reserved
)
!matches!(next_token.kind, TokenKind::Operator)
})
});

Expand Down Expand Up @@ -314,4 +336,8 @@ impl<'a> Formatter<'a> {
None
}
}

fn format_no_change(&self, token: &Token<'_>, query: &mut String) {
query.push_str(token.value);
}
}
39 changes: 39 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! This crate is a port of https://github.com/kufii/sql-formatter-plus

Check warning on line 1 in src/lib.rs

View workflow job for this annotation

GitHub Actions / build-test-unix (latest-stable)

this URL is not a hyperlink
//! written in Rust. It is intended to be usable as a pure-Rust library
//! for formatting SQL queries.

Expand Down Expand Up @@ -1658,4 +1658,43 @@

assert_eq!(format(input, &QueryParams::None, options), expected);
}

#[test]
fn it_recognizes_fmt_off() {
let input = indoc!(
"SELECT * FROM sometable
WHERE
-- comment test here
-- fmt: off
first_key.second_key = 1
-- json:first_key.second_key = 1
-- fmt: on
AND
-- fm1t: off
first_key.second_key = 1
-- json:first_key.second_key = 1
-- fmt:on"
);
let options = FormatOptions {
indent: Indent::Spaces(4),
..Default::default()
};
let expected = indoc!(
"
SELECT
*
FROM
sometable
WHERE
-- comment test here
first_key.second_key = 1
-- json:first_key.second_key = 1
AND
-- fm1t: off
first_key.second_key = 1
-- json:first_key.second_key = 1"
);

assert_eq!(format(input, &QueryParams::None, options), expected);
}
}
Loading