Skip to content

Align SQL comment parsing with CPython #5996

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 0 additions & 6 deletions Lib/test/test_sqlite3/test_dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,8 +769,6 @@ def test_execute_illegal_sql(self):
with self.assertRaises(sqlite.OperationalError):
self.cu.execute("select asdf")

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_execute_multiple_statements(self):
msg = "You can only execute one statement at a time"
dataset = (
Expand All @@ -793,8 +791,6 @@ def test_execute_multiple_statements(self):
with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
self.cu.execute(query)

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_execute_with_appended_comments(self):
dataset = (
"select 1; -- foo bar",
Expand Down Expand Up @@ -963,8 +959,6 @@ def test_rowcount_update_returning(self):
self.assertEqual(self.cu.fetchone()[0], 1)
self.assertEqual(self.cu.rowcount, 1)

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_rowcount_prefixed_with_comment(self):
# gh-79579: rowcount is updated even if query is prefixed with comments
self.cu.execute("""
Expand Down
50 changes: 33 additions & 17 deletions stdlib/src/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3068,36 +3068,52 @@ mod _sqlite {
}

fn lstrip_sql(sql: &[u8]) -> Option<&[u8]> {
let mut pos = sql;
loop {
match pos.first()? {
let mut pos = 0;

// This loop is borrowed from the SQLite source code.
while let Some(t_char) = sql.get(pos) {
match t_char {
b' ' | b'\t' | b'\x0c' | b'\n' | b'\r' => {
pos = &pos[1..];
// Skip whitespace.
pos += 1;
}
b'-' => {
if *pos.get(1)? == b'-' {
// line comments
pos = &pos[2..];
while *pos.first()? != b'\n' {
pos = &pos[1..];
// Skip line comments.
if sql.get(pos + 1) == Some(&b'-') {
pos += 2;
while let Some(&ch) = sql.get(pos) {
if ch == b'\n' {
break;
}
pos += 1;
}
let _ = sql.get(pos)?;
} else {
return Some(pos);
return Some(&sql[pos..]);
}
}
b'/' => {
if *pos.get(1)? == b'*' {
// c style comments
pos = &pos[2..];
while *pos.first()? != b'*' || *pos.get(1)? != b'/' {
pos = &pos[1..];
// Skip C style comments.
if sql.get(pos + 1) == Some(&b'*') {
pos += 2;
while let Some(&ch) = sql.get(pos) {
if ch == b'*' && sql.get(pos + 1) == Some(&b'/') {
break;
}
pos += 1;
}
let _ = sql.get(pos)?;
pos += 2;
} else {
return Some(pos);
return Some(&sql[pos..]);
}
}
_ => return Some(pos),
_ => {
return Some(&sql[pos..]);
}
}
}

None
}
Comment on lines 3070 to 3118
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Review the bounds checking logic in comment handling.

The refactored index-based approach looks good overall, but there are potential logical issues in the comment handling sections:

  1. Line 3090: let _ = sql.get(pos)?; - This line appears to be checking if pos is still valid after processing a line comment, but if it fails, the function returns None. This might not be the intended behavior. If we've reached the end of input after a line comment, we should return None (indicating everything was skipped), not fail.

  2. Line 3105: Similar issue with C-style comment handling.

The logic should be:

  • If we reach the end of input while processing comments, return None (everything was skipped)
  • Only return Some(&sql[pos..]) when we find non-skippable content

Consider this fix:

                b'-' => {
                    // Skip line comments.
                    if sql.get(pos + 1) == Some(&b'-') {
                        pos += 2;
                        while let Some(&ch) = sql.get(pos) {
                            if ch == b'\n' {
                                break;
                            }
                            pos += 1;
                        }
-                        let _ = sql.get(pos)?;
                    } else {
                        return Some(&sql[pos..]);
                    }
                }
                b'/' => {
                    // Skip C style comments.
                    if sql.get(pos + 1) == Some(&b'*') {
                        pos += 2;
                        while let Some(&ch) = sql.get(pos) {
                            if ch == b'*' && sql.get(pos + 1) == Some(&b'/') {
                                break;
                            }
                            pos += 1;
                        }
-                        let _ = sql.get(pos)?;
-                        pos += 2;
+                        if sql.get(pos).is_some() {
+                            pos += 2;
+                        }
                    } else {
                        return Some(&sql[pos..]);
                    }
                }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn lstrip_sql(sql: &[u8]) -> Option<&[u8]> {
let mut pos = sql;
loop {
match pos.first()? {
let mut pos = 0;
// This loop is borrowed from the SQLite source code.
while let Some(t_char) = sql.get(pos) {
match t_char {
b' ' | b'\t' | b'\x0c' | b'\n' | b'\r' => {
pos = &pos[1..];
// Skip whitespace.
pos += 1;
}
b'-' => {
if *pos.get(1)? == b'-' {
// line comments
pos = &pos[2..];
while *pos.first()? != b'\n' {
pos = &pos[1..];
// Skip line comments.
if sql.get(pos + 1) == Some(&b'-') {
pos += 2;
while let Some(&ch) = sql.get(pos) {
if ch == b'\n' {
break;
}
pos += 1;
}
let _ = sql.get(pos)?;
} else {
return Some(pos);
return Some(&sql[pos..]);
}
}
b'/' => {
if *pos.get(1)? == b'*' {
// c style comments
pos = &pos[2..];
while *pos.first()? != b'*' || *pos.get(1)? != b'/' {
pos = &pos[1..];
// Skip C style comments.
if sql.get(pos + 1) == Some(&b'*') {
pos += 2;
while let Some(&ch) = sql.get(pos) {
if ch == b'*' && sql.get(pos + 1) == Some(&b'/') {
break;
}
pos += 1;
}
let _ = sql.get(pos)?;
pos += 2;
} else {
return Some(pos);
return Some(&sql[pos..]);
}
}
_ => return Some(pos),
_ => {
return Some(&sql[pos..]);
}
}
}
None
}
fn lstrip_sql(sql: &[u8]) -> Option<&[u8]> {
let mut pos = 0;
// This loop is borrowed from the SQLite source code.
while let Some(t_char) = sql.get(pos) {
match t_char {
b' ' | b'\t' | b'\x0c' | b'\n' | b'\r' => {
// Skip whitespace.
pos += 1;
}
b'-' => {
// Skip line comments.
if sql.get(pos + 1) == Some(&b'-') {
pos += 2;
while let Some(&ch) = sql.get(pos) {
if ch == b'\n' {
break;
}
pos += 1;
}
} else {
return Some(&sql[pos..]);
}
}
b'/' => {
// Skip C style comments.
if sql.get(pos + 1) == Some(&b'*') {
pos += 2;
while let Some(&ch) = sql.get(pos) {
if ch == b'*' && sql.get(pos + 1) == Some(&b'/') {
break;
}
pos += 1;
}
if sql.get(pos).is_some() {
pos += 2;
}
} else {
return Some(&sql[pos..]);
}
}
_ => {
return Some(&sql[pos..]);
}
}
}
None
}
🤖 Prompt for AI Agents
In stdlib/src/sqlite.rs between lines 3070 and 3118, the bounds checking after
processing line and C-style comments uses sql.get(pos)? which returns None if
pos is out of bounds, causing the function to return None prematurely. To fix
this, replace these checks with explicit bounds checks: if pos is at or beyond
the input length after skipping comments, return None to indicate all input was
skipped; otherwise, continue processing. This ensures the function correctly
returns None only when all content is skipped and returns Some with the
remaining slice when non-skippable content is found.

💡 Verification agent

🧩 Analysis chain

Verify alignment with CPython's SQL comment parsing behavior.

Since the PR objective is to "align SQL comment parsing with CPython," please verify that this implementation correctly matches CPython's behavior, particularly:

  1. Edge cases: How CPython handles malformed comments (e.g., /* without closing */, -- at end of input)
  2. Comment nesting: Whether CPython supports nested C-style comments
  3. Whitespace handling: Exact whitespace characters that CPython skips

Run this script to compare behavior with CPython:


🏁 Script executed:

#!/bin/bash
# Description: Test SQL comment parsing edge cases against CPython behavior
# Expected: Verify that RustPython matches CPython's sqlite3 behavior

# Test cases for edge cases
python3 -c "
import sqlite3
test_cases = [
    '/* incomplete comment',
    '-- comment at end',
    '/* nested /* comment */ */',
    '  \t\n  SELECT 1',
    '-- comment\nSELECT 1',
    '/* comment */SELECT 1'
]

for case in test_cases:
    try:
        result = sqlite3.complete_statement(case)
        print(f'{case!r}: {result}')
    except Exception as e:
        print(f'{case!r}: ERROR - {e}')
"

Length of output: 633


🏁 Script executed:

#!/bin/bash
# Check how CPython's sqlite3.complete_statement handles various ASCII whitespace characters
python3 - <<'PYCODE'
import sqlite3

cases = [
    ('space', ' SELECT 1;'),
    ('tab', '\tSELECT 1;'),
    ('newline', '\nSELECT 1;'),
    ('carriage_return', '\rSELECT 1;'),
    ('form_feed', '\fSELECT 1;'),
    ('vertical_tab', '\vSELECT 1;'),
]

print("Whitespace Skip Tests (should be True if whitespace is skipped):")
for name, stmt in cases:
    result = sqlite3.complete_statement(stmt)
    print(f"{name:15s}: {result}")
PYCODE

Length of output: 208


Include ASCII vertical tab in whitespace skip and document comment nesting

CPython’s sqlite3.complete_statement skips all standard ASCII whitespace—including vertical tab (\v)—and does not support nested C-style comments. To fully align RustPython’s parsing:

  • Update the whitespace match in lstrip_sql to include b'\x0b' (vertical tab).
  • Add a note in the code comment that nested /*…*/ comments aren’t supported, matching CPython behavior.
  • Add tests covering nested comments (with and without trailing semicolon) to lock in this behavior.

Suggested diff for stdlib/src/sqlite.rs around line 3073:

-    while let Some(t_char) = sql.get(pos) {
-        match t_char {
-            b' ' | b'\t' | b'\x0c' | b'\n' | b'\r' => {
+    while let Some(t_char) = sql.get(pos) {
+        match t_char {
+            // Skip all ASCII whitespace (space, tab, form-feed, newline, carriage-return, vertical-tab)
+            b' ' | b'\t' | b'\x0c' | b'\n' | b'\r' | b'\x0b' => {
                 pos += 1;
             }

And above the C-style comment logic, add:

// Note: Nested C-style comments (e.g., /* /* … */ */) are not supported,
// mirroring CPython’s sqlite3.complete_statement behavior.
🤖 Prompt for AI Agents
In stdlib/src/sqlite.rs around lines 3070 to 3118, update the whitespace
matching in the lstrip_sql function to include the ASCII vertical tab character
(b'\x0b') so it skips this whitespace as well. Add a comment above the C-style
comment handling code to document that nested C-style comments are not
supported, matching CPython's sqlite3.complete_statement behavior. Additionally,
create tests that cover nested C-style comments with and without trailing
semicolons to ensure this behavior is maintained.

}
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy