Skip to content

SQL: Use cratedb-sqlparse for implementing read-only mode #14

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

amotl
Copy link
Member

@amotl amotl commented May 11, 2025

About

Why not use cratedb-sqlparse?

Problem

I have not been able to remove the traditional sqlparse yet. The patch needs more work.

Copy link

coderabbitai bot commented May 11, 2025

Warning

Rate limit exceeded

@amotl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 70cdcb2 and 4e34716.

📒 Files selected for processing (2)
  • cratedb_mcp/util/sql.py (4 hunks)
  • pyproject.toml (1 hunks)

Walkthrough

The changes introduce the use of the cratedb-sqlparse library for SQL parsing within the SqlStatementClassifier class, supplementing the existing sqlparse usage. New methods and fields are added to support parsing and caching with cratedb-sqlparse, and parsing logic is updated to prioritize this library for statement classification. The new dependency is also added to the project configuration.

Changes

File(s) Change Summary
cratedb_mcp/util/sql.py Integrated cratedb-sqlparse for SQL parsing in SqlStatementClassifier; added parsing method and cache field; updated operation property to use new parser for classification; retained sqlparse for specific token checks.
pyproject.toml Added cratedb-sqlparse==0.0.14 to project dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SqlStatementClassifier
    participant cratedb_sqlparse
    participant sqlparse

    User->>SqlStatementClassifier: Create instance with SQL expression
    User->>SqlStatementClassifier: Access is_dql/operation
    SqlStatementClassifier->>cratedb_sqlparse: parse(expression)
    cratedb_sqlparse-->>SqlStatementClassifier: Parsed statement(s)
    SqlStatementClassifier-->>User: Return DQL status/operation type

    User->>SqlStatementClassifier: Access is_select_into
    SqlStatementClassifier->>sqlparse: parse(expression)
    sqlparse-->>SqlStatementClassifier: Parsed tokens
    SqlStatementClassifier-->>User: Return SELECT INTO detection
Loading

Poem

In the warren where queries leap and bound,
A new parser friend has just been found!
CrateDB’s wisdom, now parsed with care,
Joins old sqlparse in the data air.
Dependencies grow, and so does delight—
Hopping through SQL, parsing just right!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (3)
pyproject.toml (1)

23-28: Consider loosening / future-proofing the version pin for cratedb-sqlparse.

A hard pin (==0.0.14) guarantees reproducibility today but can block consumers from upgrading the library when bug-fixes or security patches are released.
Typical options:

  1. Pin an upper bound instead of an exact version:
"cratedb-sqlparse>=0.0.14,<0.1"
  1. Keep the hard pin here but add a comment (or dependabot ignore) explaining why we must stay on 0.0.14.

Either approach makes maintenance intent explicit.

cratedb_mcp/util/sql.py (2)

78-88: Minor optimisation: avoid double parsing.

is_dql currently:

  1. Parses via cratedb-sqlparse.
  2. Calls self.is_selectoperationparse_cratedb() again (after the fix above).

Because the result is cached the second call is cheap, but we can still skip it:

-        parsed = self.parse_cratedb()
+        parsed = self.parse_cratedb()  # cached

 # ... later
-        return self.is_select and not self.is_camouflage
+        is_select = parsed and parsed[0].type.upper() == "SELECT"
+        return is_select and not self.is_camouflage

Not critical, but trims a property indirection and keeps the logic self-contained.


123-125: Token flattening may miss nested INTOs.

[str(item).upper() for item in parsed[0]] iterates only the first-level tokens; nested groups (e.g., within parentheses) are ignored.
If full accuracy is required you might want to recurse with token.flatten() provided by sqlparse.

Not blocking, just flagging a potential false-negative edge-case.

🛑 Comments failed to post (1)
cratedb_mcp/util/sql.py (1)

43-57: ⚠️ Potential issue

Thread-safe lazy cache is good – but only half of the class uses it.

You introduced _parsed_cratedb and parse_cratedb() – nice!
However, some read-paths (see operation below) access _parsed_cratedb without guaranteeing that parse_cratedb() has been called first, which will crash on the first direct SqlStatementClassifier(...).operation call.

Consider always funnelling access through the helper:

     @property
     def operation(self) -> str:
         """
         The SQL operation: SELECT, INSERT, UPDATE, DELETE, CREATE, etc.
         """
-        return self._parsed_cratedb[0].type.upper()
+        parsed = self.parse_cratedb()
+        if not parsed:
+            return ""
+        return parsed[0].type.upper()

This keeps the lazy cache intact and removes NoneType surprises.

📝 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.

    @property
    def operation(self) -> str:
        """
        The SQL operation: SELECT, INSERT, UPDATE, DELETE, CREATE, etc.
        """
        parsed = self.parse_cratedb()
        if not parsed:
            return ""
        return parsed[0].type.upper()
🤖 Prompt for AI Agents (early access)
In cratedb_mcp/util/sql.py around lines 43 to 57, the _parsed_cratedb cache is
accessed directly in some places like the operation property without ensuring
parse_cratedb() has been called, which can cause NoneType errors. To fix this,
update all accesses to _parsed_cratedb to go through the parse_cratedb() method,
ensuring the cache is initialized before use and preventing crashes on first
access.

@amotl amotl force-pushed the stronger-read-only branch from be09e1e to 5b0d8e9 Compare May 11, 2025 19:52
@amotl amotl force-pushed the cratedb-sqlparse branch from 93b99ce to 1d89dc7 Compare May 11, 2025 19:54
@amotl amotl force-pushed the stronger-read-only branch from 5b0d8e9 to 4dadcbc Compare May 11, 2025 22:30
@amotl amotl force-pushed the cratedb-sqlparse branch from 1d89dc7 to 70cdcb2 Compare May 11, 2025 22:39
@amotl amotl force-pushed the stronger-read-only branch from f1aa610 to 01ddc74 Compare May 16, 2025 11:17
Base automatically changed from stronger-read-only to main May 16, 2025 11:19
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.

1 participant