Skip to content

fix: Handle double quotes inside quoted identifiers correctly #411

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

Merged
merged 5 commits into from
Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ serde_json = { version = "1.0", optional = true }
[dev-dependencies]
simple_logger = "1.9"
matches = "0.1"
pretty_assertions = "1"

[package.metadata.release]
# Instruct `cargo release` to not run `cargo publish` locally:
Expand Down
15 changes: 13 additions & 2 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use alloc::{
string::{String, ToString},
vec::Vec,
};
use core::fmt;
use core::fmt::{self, Write};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -127,7 +127,18 @@ impl From<&str> for Ident {
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.quote_style {
Some(q) if q == '"' || q == '\'' || q == '`' => write!(f, "{}{}{}", q, self.value, q),
Some(q) if q == '"' || q == '\'' || q == '`' => {
f.write_char(q)?;
let mut first = true;
for s in self.value.split_inclusive(q) {
if !first {
f.write_char(q)?;
}
first = false;
f.write_str(s)?;
}
f.write_char(q)
}
Some(q) if q == '[' => write!(f, "[{}]", self.value),
None => f.write_str(&self.value),
_ => panic!("unexpected quote style"),
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@
#[cfg(not(feature = "std"))]
extern crate alloc;

#[macro_use]
#[cfg(test)]
extern crate pretty_assertions;

pub mod ast;
#[macro_use]
pub mod dialect;
Expand Down
42 changes: 40 additions & 2 deletions src/tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,9 @@ impl<'a> Tokenizer<'a> {
quote_start if self.dialect.is_delimited_identifier_start(quote_start) => {
chars.next(); // consume the opening quote
let quote_end = Word::matching_end_quote(quote_start);
let s = peeking_take_while(chars, |ch| ch != quote_end);
if chars.next() == Some(quote_end) {
let (s, last_char) = parse_quoted_ident(chars, quote_end);

if last_char == Some(quote_end) {
Ok(Some(Token::make_word(&s, Some(quote_start))))
} else {
self.tokenizer_error(format!(
Expand Down Expand Up @@ -728,6 +729,25 @@ fn peeking_take_while(
s
}

fn parse_quoted_ident(chars: &mut Peekable<Chars<'_>>, quote_end: char) -> (String, Option<char>) {
let mut last_char = None;
let mut s = String::new();
while let Some(ch) = chars.next() {
if ch == quote_end {
if chars.peek() == Some(&quote_end) {
chars.next();
s.push(ch);
} else {
last_char = Some(quote_end);
break;
}
} else {
s.push(ch);
}
}
(s, last_char)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -1276,6 +1296,24 @@ mod tests {
compare(expected, tokens);
}

#[test]
fn tokenize_quoted_identifier() {
let sql = r#" "a "" b" "a """ "c """"" "#;
let dialect = GenericDialect {};
let mut tokenizer = Tokenizer::new(&dialect, sql);
let tokens = tokenizer.tokenize().unwrap();
let expected = vec![
Token::Whitespace(Whitespace::Space),
Token::make_word(r#"a " b"#.into(), Some('"')),
Token::Whitespace(Whitespace::Space),
Token::make_word(r#"a ""#.into(), Some('"')),
Token::Whitespace(Whitespace::Space),
Token::make_word(r#"c """#.into(), Some('"')),
Token::Whitespace(Whitespace::Space),
];
compare(expected, tokens);
}

fn compare(expected: Vec<Token>, actual: Vec<Token>) {
//println!("------------------------------");
//println!("tokens = {:?}", actual);
Expand Down
31 changes: 31 additions & 0 deletions tests/sqlparser_mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,37 @@ fn parse_quote_identifiers() {
}
}

#[test]
fn parse_quote_identifiers_2() {
let sql = "SELECT `quoted `` identifier`";
assert_eq!(
mysql().verified_stmt(sql),
Statement::Query(Box::new(Query {
with: None,
body: SetExpr::Select(Box::new(Select {
distinct: false,
top: None,
projection: vec![SelectItem::UnnamedExpr(Expr::Identifier(Ident {
value: "quoted ` identifier".into(),
quote_style: Some('`'),
}))],
from: vec![],
lateral_views: vec![],
selection: None,
group_by: vec![],
cluster_by: vec![],
distribute_by: vec![],
sort_by: vec![],
having: None,
})),
order_by: vec![],
limit: None,
offset: None,
fetch: None,
}))
);
}

#[test]
fn parse_unterminated_escape() {
let sql = r#"SELECT 'I\'m not fine\'"#;
Expand Down
5 changes: 5 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,11 @@ fn parse_comments() {
}
}

#[test]
fn parse_quoted_identifier() {
pg_and_generic().verified_stmt(r#"SELECT "quoted "" ident""#);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps we can add a test for dialects (e.g. mysql) that this isn't parsed as an identifier?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a test for ` quoted strings in mysql

}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is definitely how postgres handles things

alamb=# SELECT "quoted "" ident" from t1;
ERROR:  column "quoted " ident" does not exist
LINE 1: SELECT "quoted "" ident" from t1;
             

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

However, msql treats this differently

Database changed
mysql> SELECT "quoted "" ident" from t1;
+----------------+
| quoted " ident |
+----------------+
| quoted " ident |
| quoted " ident |
| quoted " ident |
| quoted " ident |
| quoted " ident |
+----------------+
5 rows in set (0.00 sec)

mysql> SELECT "quoted  ident" from t1;
+---------------+
| quoted  ident |
+---------------+
| quoted  ident |
| quoted  ident |
| quoted  ident |
| quoted  ident |
| quoted  ident |
+---------------+
5 rows in set (0.00 sec)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

" is used for strings in mysql unless ANSI_QUOTES is enabled https://dev.mysql.com/doc/refman/8.0/en/identifiers.html . Neither double quoted strings or ANSI_QUOTES seems implemented in this crate and I don't think it is up to this PR to fix that.


fn pg() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(PostgreSqlDialect {})],
Expand Down