Skip to content

feat: added support to mssql for execute query #6200

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
May 1, 2025

Conversation

Ice3man543
Copy link
Member

@Ice3man543 Ice3man543 commented Apr 28, 2025

Proposed changes

Support for execute to mssql

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Added the ability to execute SQL queries directly on MS SQL databases and view structured results.

Closes #6156
Failing functional tests tracked at #6157

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

Walkthrough

A new method named ExecuteQuery was introduced to the MSSQLClient struct within the MSSQL library. This method handles establishing a connection to an MS SQL database with specified credentials and parameters, executes a provided SQL query, and returns the results in a structured format. The implementation includes validation for host and port, network policy checks, connection management, query execution, result unmarshaling, error handling for partial results, and proper resource cleanup.

Changes

File(s) Change Summary
pkg/js/libs/mssql/mssql.go Added the ExecuteQuery method to MSSQLClient for connecting, executing queries, handling results, and errors.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant MSSQLClient
    participant NetworkPolicy
    participant Database
    participant Utils

    Caller->>MSSQLClient: ExecuteQuery(host, port, username, password, dbName, query)
    MSSQLClient->>NetworkPolicy: Validate host and port
    MSSQLClient->>Database: Open connection
    Database-->>MSSQLClient: Connection object
    MSSQLClient->>Database: Execute query
    Database-->>MSSQLClient: Query result rows
    MSSQLClient->>Utils: Unmarshal rows into SQLResult
    Utils-->>MSSQLClient: SQLResult or error (with possible partial data)
    MSSQLClient->>Database: Close connection
    MSSQLClient-->>Caller: Return SQLResult or error
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement Execute Query method on MS SQL module (#6156)

Poem

In the warren, code hops anew,
MSSQL queries now leap through!
With connections neat and queries bright,
Results return from day to night.
If errors nibble, partials stay—
The rabbit ensures data finds its way!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between b14e634 and 088425d.

📒 Files selected for processing (1)
  • pkg/js/libs/mssql/mssql.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/js/libs/mssql/mssql.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (macOS-latest)
  • GitHub Check: Tests (windows-latest)
  • GitHub Check: Tests (ubuntu-latest)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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 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.

@Ice3man543 Ice3man543 marked this pull request as ready for review April 28, 2025 13:27
@auto-assign auto-assign bot requested a review from dogancanbakir April 28, 2025 13:27
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

🧹 Nitpick comments (1)
pkg/js/libs/mssql/mssql.go (1)

147-162: Consider extracting common connection setup code.

This validation and connection string setup logic is duplicated from the existing connect function. Consider refactoring to extract this common code into a reusable helper function.

+func buildConnectionString(host string, port int, username, password, dbName string) (string, error) {
+	if host == "" || port <= 0 {
+		return "", fmt.Errorf("invalid host or port")
+	}
+	if !protocolstate.IsHostAllowed(host) {
+		// host is not valid according to network policy
+		return "", protocolstate.ErrHostDenied.Msgf(host)
+	}
+
+	target := net.JoinHostPort(host, fmt.Sprintf("%d", port))
+
+	connString := fmt.Sprintf("sqlserver://%s:%s@%s?database=%s&connection+timeout=30",
+		url.PathEscape(username),
+		url.PathEscape(password),
+		target,
+		dbName)
+
+	return connString, nil
+}

// In ExecuteQuery:
-	if host == "" || port <= 0 {
-		return nil, fmt.Errorf("invalid host or port")
-	}
-	if !protocolstate.IsHostAllowed(host) {
-		// host is not valid according to network policy
-		return nil, protocolstate.ErrHostDenied.Msgf(host)
-	}
-
-	target := net.JoinHostPort(host, fmt.Sprintf("%d", port))
-
-	connString := fmt.Sprintf("sqlserver://%s:%s@%s?database=%s&connection+timeout=30",
-		url.PathEscape(username),
-		url.PathEscape(password),
-		target,
-		dbName)
+	connString, err := buildConnectionString(host, port, username, password, dbName)
+	if err != nil {
+		return nil, err
+	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c4c1496 and b14e634.

⛔ Files ignored due to path filters (1)
  • pkg/js/generated/ts/mssql.ts is excluded by !**/generated/**
📒 Files selected for processing (1)
  • pkg/js/libs/mssql/mssql.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (macOS-latest)
  • GitHub Check: Tests (windows-latest)
  • GitHub Check: Tests (ubuntu-latest)
🔇 Additional comments (4)
pkg/js/libs/mssql/mssql.go (4)

14-14: Import looks good.

The addition of the utils package is appropriate for the new ExecuteQuery functionality, specifically for unmarshaling SQL query results.


137-146: Documentation is clear and helpful.

The JSDoc-style comments and example usage provide good guidance for developers using this method.


177-183: Clarify the handling of partial results.

The current implementation returns partial data when unmarshaling fails. While this might be useful in some scenarios, it could also lead to confusion or incorrect behavior. Consider:

  1. Adding a comment explaining this behavior
  2. Returning a warning along with the partial data
  3. Making this behavior configurable

Is this behavior of returning partial results intentional and are there scenarios where this is beneficial? If so, consider documenting this behavior in the function's comments.


137-185: Overall implementation looks good.

The new ExecuteQuery method successfully implements MSSQL query execution capability with proper connection management and error handling. It's well-documented with clear examples and follows the pattern established by other methods in this file.

Comment on lines +172 to +176
rows, err := db.Query(query)
if err != nil {
return nil, err
}

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add explicit rows.Close() to ensure proper resource cleanup.

Although many SQL drivers automatically close rows when the connection is closed, it's a best practice to explicitly close the rows after they're no longer needed. This prevents resource leaks, especially in case of errors.

	rows, err := db.Query(query)
	if err != nil {
		return nil, err
	}
+	defer rows.Close()

Comment on lines +172 to +175
rows, err := db.Query(query)
if err != nil {
return nil, err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using parameterized queries for security.

The current implementation passes the query string directly to the database, which could potentially lead to SQL injection if the query contains user input. Consider adding a parameter validation mechanism or using parameterized queries.

-	rows, err := db.Query(query)
+	// For queries without parameters
+	rows, err := db.Query(query)
+	
+	// For queries with parameters, consider using:
+	// rows, err := db.Query(query, param1, param2, ...)
📝 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
rows, err := db.Query(query)
if err != nil {
return nil, err
}
// For queries without parameters
rows, err := db.Query(query)
// For queries with parameters, consider using:
// rows, err := db.Query(query, param1, param2, ...)
if err != nil {
return nil, err
}

@Mzack9999 Mzack9999 merged commit b9d0f25 into dev May 1, 2025
19 of 20 checks passed
@Mzack9999 Mzack9999 deleted the msssql-exec-query-support branch May 1, 2025 21: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.

[FEATURE] ... Required Execute Query on MsSQL module
2 participants