Skip to content

Enhance interpolateParams to correctly handle placeholders #1731

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

Closed
wants to merge 0 commits into from

Conversation

rusher
Copy link
Contributor

@rusher rusher commented Jul 4, 2025

Enhance client side statement to correctly handle placeholders in queries with comments, strings, and backticks.

  • Add findParamPositions to identify real parameter positions
  • Update and expand related tests.
Copy link

coderabbitai bot commented Jul 4, 2025

Walkthrough

A new function was added to accurately find SQL parameter placeholders ('?') in queries, ignoring those inside comments, strings, or backticks. The parameter interpolation logic was updated to use this function, ensuring only valid placeholders are replaced. Related tests were updated: a test was removed and a new comprehensive test was added for these scenarios.

Changes

File(s) Change Summary
connection.go Added findParamPositions to locate valid placeholders; updated interpolateParams to use it.
connection_test.go Removed TestInterpolateParamsPlaceholderInString; added TestInterpolateParamsWithComments.

Sequence Diagram(s)

sequenceDiagram participant Client participant mysqlConn Client->>mysqlConn: interpolateParams(query, args) mysqlConn->>mysqlConn: findParamPositions(query) alt Placeholder count matches args mysqlConn->>mysqlConn: Replace valid ? with args mysqlConn-->>Client: Return interpolated query else Mismatch or ambiguous mysqlConn-->>Client: Return driver.ErrSkip end 
Loading
✨ 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

@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: 1

🧹 Nitpick comments (1)
connection.go (1)

303-306: Consider adding carriage return handling for cross-platform compatibility.

The line ending detection only handles \n but not \r\n or \r. This could cause issues on Windows systems or with SQL files created on different platforms.

Consider adding carriage return handling:

case LINE_FEED_BYTE: if state == stateEOLComment { state = stateNormal } +case '\r': + if state == stateEOLComment { + state = stateNormal + }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 76c00e3 and 883c78c.

📒 Files selected for processing (2)
  • connection.go (4 hunks)
  • connection_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: shogo82148 PR: go-sql-driver/mysql#1576 File: CHANGELOG.md:1-6 Timestamp: 2024-07-26T20:55:56.049Z Learning: PRs #1562 and #1570 in the go-sql-driver/mysql repository collectively address the same underlying issue related to fixing a race condition when a context is canceled, as documented in the CHANGELOG.md for version 1.8.1. 
connection.go (1)
Learnt from: shogo82148 PR: go-sql-driver/mysql#1576 File: CHANGELOG.md:1-6 Timestamp: 2024-07-26T20:55:56.049Z Learning: PRs #1562 and #1570 in the go-sql-driver/mysql repository collectively address the same underlying issue related to fixing a race condition when a context is canceled, as documented in the CHANGELOG.md for version 1.8.1. 
🧬 Code Graph Analysis (1)
connection_test.go (1)
dsn.go (1)
  • Config (37-84)
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: test (windows-latest, 1.24, mariadb-11.1)
  • GitHub Check: test (windows-latest, 1.24, mariadb-10.6)
  • GitHub Check: test (windows-latest, 1.24, 5.7)
  • GitHub Check: test (windows-latest, 1.24, mariadb-11.2)
  • GitHub Check: test (macos-latest, 1.24, mariadb-11.2)
  • GitHub Check: test (windows-latest, 1.24, mariadb-10.5)
  • GitHub Check: test (macos-latest, 1.24, mariadb-10.6)
  • GitHub Check: test (windows-latest, 1.24, mariadb-11.4)
  • GitHub Check: test (windows-latest, 1.24, 9.0)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-10.5)
  • GitHub Check: test (windows-latest, 1.24, 8.4)
  • GitHub Check: test (macos-latest, 1.24, 8.4)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-10.6)
  • GitHub Check: test (ubuntu-latest, 1.24, 8.0)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-11.2)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-11.1)
  • GitHub Check: test (ubuntu-latest, 1.24, 8.4)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-11.4)
  • GitHub Check: lint
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
connection_test.go (1)

190-236: Excellent comprehensive test coverage for the new parameter interpolation logic.

The test thoroughly covers all the critical scenarios:

  • Single-line comments with -- and #
  • Multi-line comments with /* */
  • String literals with single quotes
  • Backtick identifiers
  • Complex queries with multiple comment types and parameter mismatches

The test structure is clean and the expected behavior is correctly validated.

connection.go (2)

346-347: Well-implemented parameter interpolation using the new parsing logic.

The updated interpolateParams function correctly:

  • Uses findParamPositions to identify real parameter locations
  • Validates parameter count matches argument count
  • Reconstructs the query by copying segments between parameters
  • Maintains proper error handling with driver.ErrSkip

Also applies to: 361-371, 434-436


248-343: Overall excellent state machine implementation for SQL parsing.

The state machine approach is well-designed and handles the complex parsing requirements:

  • Proper string literal handling with escape sequences
  • Correct multi-line comment detection
  • Backtick identifier support
  • Clean state transitions

This significantly improves the robustness of parameter interpolation by preventing incorrect replacement of placeholders within comments and strings.

connection.go Outdated
Comment on lines 248 to 343
// findParamPositions returns the positions of real parameter holders ('?') in the query, ignoring those in comments, strings, or backticks.
func findParamPositions(query string) []int {
const (
stateNormal = iota
stateString
stateEscape
stateEOLComment
stateSlashStarComment
stateBacktick
)

var (
QUOTE_BYTE = byte('\'')
DBL_QUOTE_BYTE = byte('"')
BACKSLASH_BYTE = byte('\\')
QUESTION_MARK_BYTE = byte('?')
SLASH_BYTE = byte('/')
STAR_BYTE = byte('*')
HASH_BYTE = byte('#')
MINUS_BYTE = byte('-')
LINE_FEED_BYTE = byte('\n')
RADICAL_BYTE = byte('`')
)

paramPositions := make([]int, 0)
state := stateNormal
singleQuotes := false
lastChar := byte(0)
lenq := len(query)
for i := 0; i < lenq; i++ {
currentChar := query[i]
if state == stateEscape && !((currentChar == QUOTE_BYTE && singleQuotes) || (currentChar == DBL_QUOTE_BYTE && !singleQuotes)) {
state = stateString
lastChar = currentChar
continue
}
switch currentChar {
case STAR_BYTE:
if state == stateNormal && lastChar == SLASH_BYTE {
state = stateSlashStarComment
}
case SLASH_BYTE:
if state == stateSlashStarComment && lastChar == STAR_BYTE {
state = stateNormal
} else if state == stateNormal && lastChar == SLASH_BYTE {
state = stateEOLComment
}
case HASH_BYTE:
if state == stateNormal {
state = stateEOLComment
}
case MINUS_BYTE:
if state == stateNormal && lastChar == MINUS_BYTE {
state = stateEOLComment
}
case LINE_FEED_BYTE:
if state == stateEOLComment {
state = stateNormal
}
case DBL_QUOTE_BYTE:
if state == stateNormal {
state = stateString
singleQuotes = false
} else if state == stateString && !singleQuotes {
state = stateNormal
} else if state == stateEscape {
state = stateString
}
case QUOTE_BYTE:
if state == stateNormal {
state = stateString
singleQuotes = true
} else if state == stateString && singleQuotes {
state = stateNormal
} else if state == stateEscape {
state = stateString
}
case BACKSLASH_BYTE:
if state == stateString {
state = stateEscape
}
case QUESTION_MARK_BYTE:
if state == stateNormal {
paramPositions = append(paramPositions, i)
}
case RADICAL_BYTE:
if state == stateBacktick {
state = stateNormal
} else if state == stateNormal {
state = stateBacktick
}
}
lastChar = currentChar
}
return paramPositions
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect // comment detection for MySQL compatibility.

The state machine incorrectly treats // as a comment delimiter (lines 292-294), but MySQL does not support // comments. MySQL only supports:

  • -- (two dashes followed by space) for single-line comments
  • # for single-line comments
  • /* */ for multi-line comments

This could cause valid // sequences in SQL to be incorrectly treated as comments.

Remove the // comment detection:

case SLASH_BYTE: if state == stateSlashStarComment && lastChar == STAR_BYTE { state = stateNormal - } else if state == stateNormal && lastChar == SLASH_BYTE { - state = stateEOLComment }
📝 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
// findParamPositions returns the positions of real parameter holders ('?') in the query, ignoring those in comments, strings, or backticks.
func findParamPositions(query string) []int {
const (
stateNormal = iota
stateString
stateEscape
stateEOLComment
stateSlashStarComment
stateBacktick
)
var (
QUOTE_BYTE = byte('\'')
DBL_QUOTE_BYTE = byte('"')
BACKSLASH_BYTE = byte('\\')
QUESTION_MARK_BYTE = byte('?')
SLASH_BYTE = byte('/')
STAR_BYTE = byte('*')
HASH_BYTE = byte('#')
MINUS_BYTE = byte('-')
LINE_FEED_BYTE = byte('\n')
RADICAL_BYTE = byte('`')
)
paramPositions := make([]int, 0)
state := stateNormal
singleQuotes := false
lastChar := byte(0)
lenq := len(query)
for i := 0; i < lenq; i++ {
currentChar := query[i]
if state == stateEscape && !((currentChar == QUOTE_BYTE && singleQuotes) || (currentChar == DBL_QUOTE_BYTE && !singleQuotes)) {
state = stateString
lastChar = currentChar
continue
}
switch currentChar {
case STAR_BYTE:
if state == stateNormal && lastChar == SLASH_BYTE {
state = stateSlashStarComment
}
case SLASH_BYTE:
if state == stateSlashStarComment && lastChar == STAR_BYTE {
state = stateNormal
} else if state == stateNormal && lastChar == SLASH_BYTE {
state = stateEOLComment
}
case HASH_BYTE:
if state == stateNormal {
state = stateEOLComment
}
case MINUS_BYTE:
if state == stateNormal && lastChar == MINUS_BYTE {
state = stateEOLComment
}
case LINE_FEED_BYTE:
if state == stateEOLComment {
state = stateNormal
}
case DBL_QUOTE_BYTE:
if state == stateNormal {
state = stateString
singleQuotes = false
} else if state == stateString && !singleQuotes {
state = stateNormal
} else if state == stateEscape {
state = stateString
}
case QUOTE_BYTE:
if state == stateNormal {
state = stateString
singleQuotes = true
} else if state == stateString && singleQuotes {
state = stateNormal
} else if state == stateEscape {
state = stateString
}
case BACKSLASH_BYTE:
if state == stateString {
state = stateEscape
}
case QUESTION_MARK_BYTE:
if state == stateNormal {
paramPositions = append(paramPositions, i)
}
case RADICAL_BYTE:
if state == stateBacktick {
state = stateNormal
} else if state == stateNormal {
state = stateBacktick
}
}
lastChar = currentChar
}
return paramPositions
}
// in connection.go, within the switch over currentChar:
case SLASH_BYTE:
if state == stateSlashStarComment && lastChar == STAR_BYTE {
state = stateNormal
}
🤖 Prompt for AI Agents
In connection.go from lines 248 to 343, the current state machine incorrectly treats double slashes '//' as single-line comment delimiters, which is not compatible with MySQL syntax. To fix this, remove the logic that sets the state to stateEOLComment when encountering two consecutive SLASH_BYTE characters. Instead, ensure only '-- ' (two dashes followed by a space), '#' for single-line comments, and '/* */' for multi-line comments are recognized as comment delimiters. Adjust the conditions around lines 292-294 to eliminate handling of '//' comments. 
@coveralls
Copy link

Coverage Status

coverage: 82.376% (-0.1%) from 82.508%
when pulling 883c78c on rusher:InterpolateParams
into 76c00e3 on go-sql-driver:master.

@rusher rusher closed this Jul 4, 2025
@rusher rusher force-pushed the InterpolateParams branch from 883c78c to 76c00e3 Compare July 4, 2025 15:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants