Skip to content

fix: filter with LIKE operators #1357

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 2 commits into from
Jun 24, 2025
Merged

Conversation

parmesant
Copy link
Contributor

@parmesant parmesant commented Jun 24, 2025

Fixed bug in get_filter_string() where the columns and operators were being incorrectly parsed into the SQL string

Fixes #XXXX.

Description


This PR has:

  • been tested to ensure log ingestion and log query works.
  • added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
  • added documentation for new or modified features or behaviors.

Summary by CodeRabbit

  • Style
    • Improved code formatting and reorganized import statements for better readability across several modules.
    • Reformatted middleware wrapping for services to a more concise and consistent style.
  • Bug Fixes
    • Enhanced handling of string pattern-matching operators in filter expressions, improving accuracy for SQL queries.
  • Chores
    • Tidied up whitespace, blank lines, and logging statement formatting for clarity.
    • Simplified checks for empty string values by removing unnecessary trimming in alert conditions and validations.

Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

"""

Walkthrough

This set of changes refactors SQL filter string construction in get_filter_string to explicitly handle string pattern matching operators with SQL LIKE/NOT LIKE/ILIKE patterns and proper escaping. It also removes .trim() calls in empty string checks within alert condition validation. Additionally, several HTTP handler modules are reformatted for consistent middleware wrapping and import ordering, with no changes to core logic or public APIs.

Changes

File(s) Change Summary
src/alerts/alerts_utils.rs
src/alerts/mod.rs
Enhanced get_filter_string to handle string pattern matching operators with SQL LIKE patterns and escaping; removed .trim() calls in empty string checks.
src/handlers/http/modal/ingest_server.rs
src/handlers/http/modal/query_server.rs
src/handlers/http/modal/server.rs
Reformatted middleware wrapping calls and reordered imports for clarity; no logic changes.
src/handlers/http/resource_check.rs Reformatted imports, logging, and whitespace for style consistency; no logic changes.
src/handlers/http/mod.rs Changed the order of resource_check module declaration; no logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant get_filter_string
    participant SQL_Engine

    Caller->>get_filter_string: Provide column, operator, value
    get_filter_string->>get_filter_string: Match operator
    alt String-matching operator
        get_filter_string->>get_filter_string: Escape special chars and format SQL LIKE/NOT LIKE/ILIKE pattern
    else Other operator
        get_filter_string->>get_filter_string: Format with operator and value quoting
    end
    get_filter_string-->>Caller: Return SQL filter string
    Caller->>SQL_Engine: Use filter string in query
Loading

Possibly related PRs

  • null checks #1355: Also modifies get_filter_string, focusing on stricter null and empty string checks before value processing.
  • Updates for counts API #1347: Introduces the initial implementation of get_filter_string, which this PR builds upon by refining operator handling.

Poem

A bunny hops through SQL code,
Matching strings with patterns showed,
LIKE and NOT LIKE join the fun,
Middleware wraps—its job well done.
Imports tidy, code aligned,
In this patch, improvements find!
🐇✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec7722e and 29c95a3.

📒 Files selected for processing (1)
  • src/alerts/alerts_utils.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/alerts/alerts_utils.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
✨ 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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • 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
Contributor

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
src/alerts/alerts_utils.rs (1)

344-397: Consider using parameterized queries or DataFusion expressions for better security.

While the immediate SQL injection issue can be fixed with proper escaping, the get_filter_string function's approach of building raw SQL strings is inherently risky. The match_alert_operator function (lines 399-450) demonstrates a safer approach using DataFusion's expression builder.

Consider refactoring this function to:

  1. Use DataFusion's expression builder like match_alert_operator does
  2. Or implement a centralized SQL escaping utility function to ensure consistency
  3. Add unit tests specifically for SQL injection scenarios

This would eliminate the class of vulnerabilities entirely rather than relying on manual escaping.

♻️ Duplicate comments (1)
src/handlers/http/modal/ingest_server.rs (1)

71-74: Same helper recommended here

See the comment in query_server.rs; using a small helper eliminates three identical wrap(from_fn(...)) invocations in this file alone.

🧹 Nitpick comments (3)
src/handlers/http/resource_check.rs (1)

97-99: Redundant Arc wrapper

AtomicBool is already Sync + Send; wrapping it in Arc adds an extra indirection and heap allocation that isn’t required for a 'static global. Dropping Arc simplifies the API:

-static RESOURCE_CHECK_ENABLED: LazyLock<Arc<AtomicBool>> = LazyLock::new(|| Arc::new(AtomicBool::new(true)));
+static RESOURCE_CHECK_ENABLED: LazyLock<AtomicBool> = LazyLock::new(|| AtomicBool::new(true));

All call-sites remain the same (load, store).

src/handlers/http/modal/query_server.rs (1)

57-60: Avoid repetitive wrap(from_fn(...)) boilerplate

The middleware is applied in several places across this file (and others). Extract a helper to keep the configuration terse and consistent:

fn resource_guard() -> impl Transform<SrvReq, Service = SrvRes, Error = Error, InitError = ()> {
    from_fn(resource_check::check_resource_utilization_middleware)
}

// …
.service(Server::get_query_factory().wrap(resource_guard()))

This reduces noise and makes future replacement easier.

src/handlers/http/modal/server.rs (1)

77-82: DRY up middleware application across the monolith

resource_check::check_resource_utilization_middleware is repeated four times here (and elsewhere). A single helper (or even type Guard = fn(...)) keeps the huge route tree readable and removes the risk of forgetting the guard on a new endpoint.

Also applies to: 95-96, 106-108, 373-376

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 51d8fcd and ba215c4.

📒 Files selected for processing (6)
  • src/alerts/alerts_utils.rs (1 hunks)
  • src/handlers/http/mod.rs (1 hunks)
  • src/handlers/http/modal/ingest_server.rs (4 hunks)
  • src/handlers/http/modal/query_server.rs (2 hunks)
  • src/handlers/http/modal/server.rs (7 hunks)
  • src/handlers/http/resource_check.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
🔇 Additional comments (2)
src/handlers/http/resource_check.rs (1)

42-46: Zero-second interval panics

Duration::from_secs(resource_check_interval) will panic if the value is 0. Either validate the CLI/config input up-front or guard here:

let interval_secs = std::cmp::max(1, PARSEABLE.options.resource_check_interval);
let mut check_interval = interval(Duration::from_secs(interval_secs));
src/handlers/http/mod.rs (1)

49-49: Import re-ordering only – LGTM
No functional impact; matches the new logical grouping.

Comment on lines +37 to 39
static RESOURCE_CHECK_ENABLED: LazyLock<Arc<AtomicBool>> =
LazyLock::new(|| Arc::new(AtomicBool::new(false)));

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

Defaulting the gatekeeper to false blocks every request until the first tick

RESOURCE_CHECK_ENABLED is initialised to false, while spawn_resource_monitor() only flips it after the first interval.tick().
With the default resource_check_interval (often ≥ 30 s) the server will answer every incoming request with 503 for that entire window – effectively an unintended DoS right after startup or whenever the monitor hasn’t been spawned.

-static RESOURCE_CHECK_ENABLED: LazyLock<Arc<AtomicBool>> =
-    LazyLock::new(|| Arc::new(AtomicBool::new(false)));
+// Start in "healthy" mode – the monitor will turn it off if thresholds are exceeded.
+static RESOURCE_CHECK_ENABLED: LazyLock<Arc<AtomicBool>> =
+    LazyLock::new(|| Arc::new(AtomicBool::new(true)));

If you prefer a pessimistic default, call RESOURCE_CHECK_ENABLED.store(true, Ordering::SeqCst) before entering the loop so the flag is set immediately.

📝 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
static RESOURCE_CHECK_ENABLED: LazyLock<Arc<AtomicBool>> =
LazyLock::new(|| Arc::new(AtomicBool::new(false)));
static RESOURCE_CHECK_ENABLED: LazyLock<Arc<AtomicBool>> =
- LazyLock::new(|| Arc::new(AtomicBool::new(false)));
+ // Start in "healthy" mode – the monitor will turn it off if thresholds are exceeded.
+ LazyLock::new(|| Arc::new(AtomicBool::new(true)));
🤖 Prompt for AI Agents
In src/handlers/http/resource_check.rs around lines 37 to 39, the
RESOURCE_CHECK_ENABLED flag is initialized to false, causing all requests to be
blocked with a 503 response until the first interval tick occurs. To fix this,
set RESOURCE_CHECK_ENABLED to true before entering the monitoring loop by
calling RESOURCE_CHECK_ENABLED.store(true, Ordering::SeqCst) so the server
responds normally immediately after startup.

Fixed bug in `get_filter_string()` where the columns and operators were being incorrectly parsed into the SQL string
@nikhilsinhaparseable nikhilsinhaparseable changed the title bugfix & cargo clippy fix: filter with LIKE operators Jun 24, 2025
@nitisht nitisht merged commit bf6fc88 into parseablehq:main Jun 24, 2025
14 checks passed
@parmesant parmesant deleted the filter-message branch July 3, 2025 08:25
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.

2 participants