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 parsing of negative values #1419

Merged
merged 6 commits into from
Sep 16, 2024
Merged

Conversation

agscpp
Copy link
Contributor

@agscpp agscpp commented Sep 9, 2024

Currently, when passing negative numbers, the sql parser returns an error. While the PostgreSQL syntax allows you to specify negative values ​​when creating a sequence.

Example:

CREATE SEQUENCE seq START -100 INCREMENT -10 MINVALUE -1000 MAXVALUE 1;

Error text:

ParserError("Expected: a value, found: -")

Link to PostgreSQL documentation:
https://www.postgresql.org/docs/current/sql-createsequence.html

@agscpp
Copy link
Contributor Author

agscpp commented Sep 10, 2024

Hi @alamb .

Can you please take a look at my pull request?

@@ -7274,6 +7274,16 @@ impl<'a> Parser<'a> {
let placeholder = tok.to_string() + &ident.value;
Ok(Value::Placeholder(placeholder))
}
tok @ Token::Minus => {
Copy link
Member

Choose a reason for hiding this comment

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

Should handle + as well? And for the sign number value, another place represents it with UnaryOp, guess should keep consistent? cc @iffyio

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Code that can handle prefixes is not well suited for handling numbers.

I added a handler for "+"

Copy link
Member

Choose a reason for hiding this comment

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

Oh, what I mean is if we should return the negative number as the UnaryOp expression like the previous implementation.

@@ -277,6 +277,16 @@ fn parse_create_sequence() {
"CREATE TEMPORARY SEQUENCE IF NOT EXISTS name3 INCREMENT 1 NO MINVALUE MAXVALUE 20 OWNED BY NONE",
);

let sql7 = "CREATE SEQUENCE name4
Copy link
Member

Choose a reason for hiding this comment

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

This change didn't guard with the PostgreSQL dialect guard, so should move test case to common.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Can I put the entire "parse_create_sequence" function in a common module?

Copy link
Member

Choose a reason for hiding this comment

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

I think it should be good to keep it inside PostgreSQL unless more dialects support this syntax.

@@ -7274,6 +7274,16 @@ impl<'a> Parser<'a> {
let placeholder = tok.to_string() + &ident.value;
Ok(Value::Placeholder(placeholder))
}
tok @ Token::Minus | tok @ Token::Plus => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Normally I would expect that the - is included as part of the token itself otherwise negative numbers wouldn't be able to be parsed at all anywhere

I wonder if the issue is that the of token being handled by create sequence needs to be expanded 🤔

Copy link
Member

Choose a reason for hiding this comment

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

@alamb Not sure if I understand your point correctly. token::Minus might be a sign symbol for a number or a binary operation, and this cannot be determined when parsing it into a token.

Copy link
Contributor

Choose a reason for hiding this comment

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

My primary concern is that this change seems to have much larger potential scope than simply supporting negative numbers for CREATE SEQUENCE -- it seems like it would change parsing of all values.

However, I am clearly confused -- I added a test that shows that -10 is parsed as -(10) (aka a unary minus). See #1421. That test still passes on this PR, so it must not have as much of an impact as I thought

Copy link
Member

Choose a reason for hiding this comment

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

My primary concern is that this change seems to have much larger potential scope than simply supporting negative numbers for CREATE SEQUENCE -- it seems like it would change parsing of all values.

It did affect the parsing of all values.

However, I am clearly confused -- I added a test that shows that -10 is parsed as -(10) (aka a unary minus). See #1421. That test still passes on this PR, so it must not have as much of an impact as I thought

Yes, I also mentioned this in the comment #1419 (comment), the negative number will be parsed into an unary operation. So I'm wondering if we should keep it consistent by parsing it as an unary operation in PR as well.

Copy link
Contributor

Choose a reason for hiding this comment

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

It seems when parsing expressions, the signed number literals are handled by the precedence logic when looking to parse a sub expr here is where we usually land. From what I could tell, we don't end up hitting the new code when parsing expressions due to calling parse_prefix beforehand - though I can't tell how well the change works with dialect overrides to the precedence logic so there might be some potential for surprising behavior. Also can't say for sure if there are other considerations other than when parsing subexpressions

The doc for Token::Number at least explicitly says it contains unsigned number and since that's what Value::Number maps to, I think it might be reasonable to continue to always represent signed numbers as unary Exprs vs sometimes baked into the Value.

For this PR, issue seems that the clauses in CREATE SEQUENCE specifically are looking to parse number literals but the parse_number_value helper currently looks to parse exactly a Value::Number, maybe they can instead be updated to call parse_expr, expecially since the expected types on the enum are already Expr.

There are few similar calls to parse_number_value() I suspect they could have similar issue of rejecting signed numbers, so if we end up keeping the current behavior, a follow up might be to make it explicit what parse_number_value returns/rejects.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for your important comments. I have made some edits. Please check again.

@iffyio @alamb @git-hulk

@alamb
Copy link
Contributor

alamb commented Sep 10, 2024

I started the CI tests and there appear to be some problems with this PR

@coveralls
Copy link

coveralls commented Sep 10, 2024

Pull Request Test Coverage Report for Build 10881901043

Details

  • 24 of 27 (88.89%) changed or added relevant lines in 3 files are covered.
  • 12 unchanged lines in 1 file lost coverage.
  • Overall coverage increased (+0.007%) to 89.336%

Changes Missing Coverage Covered Lines Changed/Added Lines %
src/parser/mod.rs 13 14 92.86%
tests/sqlparser_postgres.rs 4 6 66.67%
Files with Coverage Reduction New Missed Lines %
src/parser/mod.rs 12 93.33%
Totals Coverage Status
Change from base Build 10817360923: 0.007%
Covered Lines: 29446
Relevant Lines: 32961

💛 - Coveralls

@agscpp agscpp force-pushed the fix-parse-sequence-options branch 2 times, most recently from 50936e0 to 2648917 Compare September 10, 2024 14:43
Copy link
Contributor

@alamb alamb left a comment

Choose a reason for hiding this comment

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

Thank you @agscpp -- this is a very nice contribution.

I think this PR needs a test with the originally reported SQL error (and some examples without spaces between minus signs) but is otherwise good to go from my perspective.

I would appreciate someone else taking a look too (cc @iffyio @jmhain ) as I can't stop worrying this will have unintended consequences

@@ -2819,6 +2819,29 @@ fn parse_window_function_null_treatment_arg() {
);
}

#[test]
fn parse_signed_value() {
let sql1 = "CREATE SEQUENCE name1
Copy link
Contributor

Choose a reason for hiding this comment

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

I double checked that this syntax is indeed valid in postgres (🤯 )

postgres=# CREATE SEQUENCE name1
    AS BIGINT
    INCREMENT   -15
    MINVALUE - 2000  MAXVALUE -50
    START WITH -   60;
CREATE SEQUENCE

postgres=# SELECT *
FROM information_schema.sequences
ORDER BY sequence_name;
 sequence_catalog | sequence_schema | sequence_name | data_type | numeric_precision | numeric_precision_radix | numeric_scale | start_value | minimum_value | maximum_value | increment | cycle_option
------------------+-----------------+---------------+-----------+-------------------+-------------------------+---------------+-------------+---------------+---------------+-----------+--------------
 postgres         | public          | name1         | bigint    |                64 |                       2 |             0 | -60         | -2000         | -50           | -15       | NO
(1 row)

@@ -7274,6 +7274,16 @@ impl<'a> Parser<'a> {
let placeholder = tok.to_string() + &ident.value;
Ok(Value::Placeholder(placeholder))
}
tok @ Token::Minus | tok @ Token::Plus => {
Copy link
Contributor

Choose a reason for hiding this comment

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

My primary concern is that this change seems to have much larger potential scope than simply supporting negative numbers for CREATE SEQUENCE -- it seems like it would change parsing of all values.

However, I am clearly confused -- I added a test that shows that -10 is parsed as -(10) (aka a unary minus). See #1421. That test still passes on this PR, so it must not have as much of an impact as I thought

"CREATE SEQUENCE name2 AS BIGINT INCREMENT 10 MINVALUE 30 MAXVALUE 5000 START WITH 45",
);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you also please add a test for your original reproducer?

CREATE SEQUENCE seq START -100 INCREMENT -10 MINVALUE -1000 MAXVALUE 1;

I tried adding it locally and it doesn't seem to pass for me


CREATE SEQUENCE seq START -100 INCREMENT -10 MINVALUE -1000 MAXVALUE 1;: ParserError("Expected: end of statement, found: INCREMENT")
thread 'parse_create_sequence' panicked at src/test_utils.rs:119:61:
CREATE SEQUENCE seq START -100 INCREMENT -10 MINVALUE -1000 MAXVALUE 1;: ParserError("Expected: end of statement, found: INCREMENT")
stack backtrace:

I tested like this:

andrewlamb@Andrews-MacBook-Pro-2:~/Software/sqlparser-rs$ git diff 99b98ca86cf0591a89a644e06742758a70aa04ea
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
index 1ebb5d5..89aee71 100644
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -277,6 +277,14 @@ fn parse_create_sequence() {
         "CREATE TEMPORARY SEQUENCE IF NOT EXISTS name3 INCREMENT 1 NO MINVALUE MAXVALUE 20 OWNED BY NONE",
     );

+    // negative increments
+    let sql7 = "CREATE SEQUENCE seq START -100 INCREMENT -10 MINVALUE -1000 MAXVALUE 1;";
+    pg().one_statement_parses_to(
+        sql7,
+        "CREATE TEMPORARY SEQUENCE IF NOT EXISTS name3 INCREMENT 1 NO MINVALUE MAXVALUE 20 OWNED BY NONE",
+    );
+
+
     assert!(matches!(
         pg().parse_sql_statements("CREATE SEQUENCE foo INCREMENT 1 NO MINVALUE NO"),
         Err(ParserError::ParserError(_))

Then ran with

cargo test --test sqlparser_postgres

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The example from the task description does not work, since the order of options is important for sqlparser-rs.

Try running it like this

CREATE SEQUENCE seq INCREMENT -10 MINVALUE -1000 MAXVALUE 1 START -100;

#1102

Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks -- could you please add at least one test with this syntax (no space between - and the numbers)? I think this is important coverage as goes down a different parsing path

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, but @git-hulk is comment made me think about the correctness of the solution. Perhaps the function really should return UnaryOp

By the way, do tests really need to be moved to a common module? Tests for sequences are currently written only for PostgreSQL

Copy link
Contributor

Choose a reason for hiding this comment

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

By the way, do tests really need to be moved to a common module? Tests for sequences are currently written only for PostgreSQL

That seems like it might be a good idea to make them more discoverable

Comment on lines 2850 to 2852
let sql4 = "SELECT -1";
one_statement_parses_to(sql4, "SELECT -1");
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

My code doesn't affect this case, but I wrote a test for it so that the logic doesn't break in the future.

Comment on lines +7315 to +7314
self.prev_token();
Ok(Expr::Value(self.parse_number_value()?))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is done to avoid code duplication.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If there is no sign, it will not turn into "UnaryOp" so as not to break the old behavior.

Comment on lines +2824 to +2825
let sql1 = "SELECT -1";
one_statement_parses_to(sql1, "SELECT -1");
Copy link
Contributor Author

Choose a reason for hiding this comment

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

My code doesn't affect this case, but I wrote a test for it so that the logic doesn't break in the future.

@@ -7295,6 +7295,29 @@ impl<'a> Parser<'a> {
}
}

pub fn parse_number_value_with_sign(&mut self) -> Result<Expr, ParserError> {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
pub fn parse_number_value_with_sign(&mut self) -> Result<Expr, ParserError> {
pub fn parse_number(&mut self) -> Result<Expr, ParserError> {

Also thinking especially since this is made a public function, that we should write a doc comment about what it does? and potentially mention that the return type for signed is a Unary Expr

Copy link
Contributor Author

Choose a reason for hiding this comment

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

OK, I'll add a comment

Copy link
Contributor

Choose a reason for hiding this comment

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

Can we update the method name as well? the current parse_number_value_with_sign somewhat suggests that only signed numbers will be parsed which might be misleading

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Which name is better?
I can rename the second method to "parse_unsigned_number_value" to make this "parse_number_value"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Contributor

Choose a reason for hiding this comment

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

Ah so I was thinking as in the original suggestion - if it would make sense to just call this parse_number()?

Comment on lines 7301 to 7313
tok @ Token::Minus | tok @ Token::Plus => {
if tok == Token::Plus {
Ok(Expr::UnaryOp {
op: UnaryOperator::Plus,
expr: Box::new(Expr::Value(self.parse_number_value()?)),
})
} else {
Ok(Expr::UnaryOp {
op: UnaryOperator::Minus,
expr: Box::new(Expr::Value(self.parse_number_value()?)),
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
tok @ Token::Minus | tok @ Token::Plus => {
if tok == Token::Plus {
Ok(Expr::UnaryOp {
op: UnaryOperator::Plus,
expr: Box::new(Expr::Value(self.parse_number_value()?)),
})
} else {
Ok(Expr::UnaryOp {
op: UnaryOperator::Minus,
expr: Box::new(Expr::Value(self.parse_number_value()?)),
})
}
}
Token::Minus => {
Ok(Expr::UnaryOp {
op: UnaryOperator::Minus,
expr: Box::new(Expr::Value(self.parse_number_value()?)),
})
}
Token::Plus => {
Ok(Expr::UnaryOp {
op: UnaryOperator::Plus,
expr: Box::new(Expr::Value(self.parse_number_value()?)),
})
}

thinking we can avoid the double work of match+comparison?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, you are right. I did write the code suboptimally.

@agscpp agscpp force-pushed the fix-parse-sequence-options branch 2 times, most recently from 0fefac1 to bf1412a Compare September 12, 2024 07:17
Copy link
Contributor

@iffyio iffyio left a comment

Choose a reason for hiding this comment

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

Left a couple minor comments, otherwise LGTM!

Comment on lines 7299 to 7300
/// Parse a numeric literal and return Expr::UnaryOp if the number is signed,
/// otherwise return Expr::Value
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
/// Parse a numeric literal and return Expr::UnaryOp if the number is signed,
/// otherwise return Expr::Value
/// Parse a numeric literal as an expression. Returns a [`Expr::UnaryOp`] if the number is signed,
/// otherwise returns a [`Expr::Value`]

@@ -7295,6 +7295,29 @@ impl<'a> Parser<'a> {
}
}

pub fn parse_number_value_with_sign(&mut self) -> Result<Expr, ParserError> {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we update the method name as well? the current parse_number_value_with_sign somewhat suggests that only signed numbers will be parsed which might be misleading

Copy link
Contributor

@alamb alamb left a comment

Choose a reason for hiding this comment

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

Thank you @agscpp as well as @iffyio and @git-hulk for the review

I think there are a few more suggestions about comments from @iffyio but otherwise I think this PR is good to go

@@ -11609,29 +11630,29 @@ impl<'a> Parser<'a> {
if self.parse_keywords(&[Keyword::INCREMENT]) {
if self.parse_keywords(&[Keyword::BY]) {
sequence_options.push(SequenceOptions::IncrementBy(
Expr::Value(self.parse_number_value()?),
self.parse_number_value_with_sign()?,
Copy link
Contributor

Choose a reason for hiding this comment

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

❤️

"CREATE SEQUENCE name2 AS BIGINT INCREMENT 10 MINVALUE 30 MAXVALUE 5000 START WITH 45",
);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

By the way, do tests really need to be moved to a common module? Tests for sequences are currently written only for PostgreSQL

That seems like it might be a good idea to make them more discoverable

Copy link
Contributor

@iffyio iffyio left a comment

Choose a reason for hiding this comment

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

LGTM!

@alamb
Copy link
Contributor

alamb commented Sep 16, 2024

🚀 -- thanks everyone

@alamb alamb merged commit 246838a into apache:main Sep 16, 2024
10 checks passed
agscpp added a commit to agscpp/datafusion-sqlparser-rs that referenced this pull request Oct 22, 2024
Co-authored-by: Agaev Huseyn <h.agaev@vkteam.ru>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants