Skip to content

feat: [#358] Add OrWhere method for DB#910

Merged
hwbrzzl merged 7 commits intomasterfrom
bowen/#358-5
Feb 27, 2025
Merged

feat: [#358] Add OrWhere method for DB#910
hwbrzzl merged 7 commits intomasterfrom
bowen/#358-5

Conversation

@hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Feb 23, 2025

📑 Description

goravel/goravel#358

Summary by CodeRabbit

  • New Features

    • Introduced flexible filtering by adding support for combining conditions with OR logic in database queries.
  • Refactor

    • Streamlined query construction logic for more consistent and reliable filtering.
    • Enhanced error notifications in command operations to provide clearer, user-friendly feedback.

✅ Checks

  • Added test cases for my code

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 23, 2025

Walkthrough

This pull request enhances the database query interface by introducing a new OrWhere method across multiple layers. The change activates the OrWhere method in the Query interface and implements it within the query builder, including helper methods for assembling WHERE clauses. It also updates the corresponding mock implementations and tests to reflect the new functionality, including new test cases and adjustments to SQL query formatting. Additionally, error handling in a console command is modified to log errors internally.

Changes

File(s) Change Summary
contracts/.../db/db.go Activated the OrWhere(query any, args ...any) Query method in the Query interface.
database/db/conditions.go Added a new boolean field or to the Where struct to indicate OR conditions.
database/db/query.go Introduced the OrWhere method on the Query struct along with helper methods buildWhere, buildWheres, and toSqlizer for constructing SQL WHERE clauses.
database/db/query_test.go Updated test cases for delete, update, and where clauses with added parentheses; renamed tests for clarity; added a new TestOrWhere method.
event/console/listener_make_command.go Modified error handling in the Handle method to log errors using ctx.Error(err.Error()) instead of returning them.
mocks/.../Query.go Added a mock implementation for the OrWhere method with associated call types and helper methods (Run, Return, RunAndReturn).
tests/db_test.go Added a now field to the test suite for consistent timestamp handling; refactored tests and added a new TestOrWhere method.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant Q as Query Instance
    participant WB as Where Builder
    C->>Q: Call OrWhere(query, args...)
    Q->>WB: buildWhere(new condition with or=true)
    WB-->>Q: Return SQL condition
    Q->>WB: buildWheres(updated conditions)
    WB-->>Q: Return consolidated WHERE clause
    Q-->>C: Return new Query instance with OR condition applied
Loading
sequenceDiagram
    participant LMC as ListenerMakeCommand
    participant F as FileUtility
    participant CC as ConsoleContext
    LMC->>F: file.PutContent(...)
    alt Error occurs
      F-->>LMC: Return error
      LMC->>CC: Log error using ctx.Error(err.Error())
      LMC-->>CC: Complete without propagating error
    else No error
      F-->>LMC: Success
      LMC-->>CC: Complete normally
    end
Loading

Possibly related PRs

Suggested reviewers

  • almas1992

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)

✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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.

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

@codecov
Copy link

codecov bot commented Feb 23, 2025

Codecov Report

Attention: Patch coverage is 0% with 2 lines in your changes missing coverage. Please review.

Project coverage is 68.82%. Comparing base (06bd44b) to head (fb0b981).
Report is 7 commits behind head on master.

Files with missing lines Patch % Lines
event/console/listener_make_command.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #910      +/-   ##
==========================================
+ Coverage   68.01%   68.82%   +0.81%     
==========================================
  Files         154      154              
  Lines       10192    10191       -1     
==========================================
+ Hits         6932     7014      +82     
+ Misses       2934     2855      -79     
+ Partials      326      322       -4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@hwbrzzl hwbrzzl marked this pull request as ready for review February 27, 2025 08:03
Copilot AI review requested due to automatic review settings February 27, 2025 08:03
@hwbrzzl hwbrzzl requested a review from a team as a code owner February 27, 2025 08:03
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: 1

🧹 Nitpick comments (2)
database/db/query_test.go (1)

406-419: Added commented-out test case.

There's a commented-out test case for "nested condition" that's not being used. Consider either implementing it or removing it completely to avoid confusion.

-// s.Run("nested condition", func() {
-// 	var users []TestUser
-
-// 	s.mockDriver.EXPECT().Config().Return(database.Config{}).Once()
-// 	s.mockBuilder.EXPECT().Select(&users, "SELECT * FROM users WHERE age IN (?,?) AND name = ?", 25, 30, "John").Return(nil).Once()
-// 	s.mockDriver.EXPECT().Explain("SELECT * FROM users WHERE age IN (?,?) AND name = ?", 25, 30, "John").Return("SELECT * FROM users WHERE age IN (25,30) AND name = \"John\"").Once()
-// 	s.mockLogger.EXPECT().Trace(s.ctx, s.now, "SELECT * FROM users WHERE age IN (25,30) AND name = \"John\"", int64(0), nil).Return().Once()
-
-// 	err := s.query.Where(func(query db.Query) {
-// 		query.Where("age", []int{25, 30}).Where("name", "John")
-// 	}).Get(&users)
-// 	s.Nil(err)
-// })
database/db/query.go (1)

303-346: Comprehensive buildWheres implementation.

The buildWheres method effectively combines multiple WHERE conditions with proper handling of OR conditions. The logic for building nested AND/OR conditions is well-implemented and covers all scenarios.

One minor suggestion: consider adding comments to explain the logic flow for future maintainers.

 func (r *Query) buildWheres(wheres []Where) (sq.Sqlizer, error) {
 	if len(wheres) == 0 {
 		return nil, nil
 	}

 	var sqlizers []sq.Sqlizer
 	for _, where := range wheres {
 		query, args := r.buildWhere(where)

 		sqlizer, err := r.toSqlizer(query, args)
 		if err != nil {
 			return nil, err
 		}

 		if where.or && len(sqlizers) > 0 {
+			// Process OR condition by wrapping previous conditions
 			// If it's an OR condition and we have previous conditions,
 			// wrap the previous conditions in an AND and create an OR condition
 			if len(sqlizers) == 1 {
+				// Single previous condition - create simple OR
 				sqlizers = []sq.Sqlizer{
 					sq.Or{
 						sqlizers[0],
 						sqlizer,
 					},
 				}
 			} else {
+				// Multiple previous conditions - AND them together, then OR with new condition
 				sqlizers = []sq.Sqlizer{
 					sq.Or{
 						sq.And(sqlizers),
 						sqlizer,
 					},
 				}
 			}
 		} else {
 			// For regular WHERE conditions or the first condition
 			sqlizers = append(sqlizers, sqlizer)
 		}
 	}

+	// Return single condition or AND multiple conditions together
 	if len(sqlizers) == 1 {
 		return sqlizers[0], nil
 	}

 	return sq.And(sqlizers), nil
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 06bd44b and fb0b981.

📒 Files selected for processing (7)
  • contracts/database/db/db.go (1 hunks)
  • database/db/conditions.go (1 hunks)
  • database/db/query.go (6 hunks)
  • database/db/query_test.go (10 hunks)
  • event/console/listener_make_command.go (1 hunks)
  • mocks/database/db/Query.go (1 hunks)
  • tests/db_test.go (10 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
event/console/listener_make_command.go

[warning] 50-51: event/console/listener_make_command.go#L50-L51
Added lines #L50 - L51 were not covered by tests

🔇 Additional comments (18)
database/db/conditions.go (1)

11-11: Expanding query functionality with OR conditions ✅

The addition of the or field to the Where struct is a good enhancement that enables logical OR operations in query conditions. This field will determine whether a condition should be joined using OR logic instead of the default AND logic.

contracts/database/db/db.go (1)

53-53: Adding OrWhere method enriches the Query interface ✅

The addition of the OrWhere method to the Query interface allows for more flexible query building with OR conditions. This implementation follows the same pattern as the existing Where method, maintaining consistency in the API design.

tests/db_test.go (3)

16-16: Centralized timestamp management improves test consistency ✅

Adding the now field to the DBTestSuite struct centralizes timestamp management, which improves test consistency and maintainability by reducing duplication.


28-28: Good initialization of the centralized timestamp ✅

The timestamp is properly initialized in the SetupSuite method, ensuring it's available for all test cases.


242-264: Well-structured test case for OrWhere functionality ✅

The TestOrWhere function effectively validates the new OrWhere method by testing its ability to retrieve records that match either of the specified conditions. The test structure follows the existing patterns in the test suite, maintaining consistency.

database/db/query_test.go (5)

58-61: Test expectations updated to use parenthesized WHERE clauses.

The SQL queries in the mock expectations now include parentheses around the WHERE clause conditions, which aligns with the implementation of the new query builder.


72-74: Consistent formatting of WHERE clauses in error test cases.

The test cases for error handling have been consistently updated to match the new parenthesized WHERE clause format.


85-87: Mock expectations consistently updated for final test case.

The row affected error test case is also consistently updated to use the parenthesized WHERE format.


374-376: Test case naming improved for clarity.

The test case names have been updated to be more descriptive, making the purpose of each test clearer.


421-436: New test method for OrWhere functionality.

The new TestOrWhere method properly tests the ability to combine conditions with OR operators. The test demonstrates chaining multiple conditions with both Where and OrWhere methods.

database/db/query.go (6)

151-161: Well-implemented OrWhere method.

The OrWhere method correctly creates a new Query, maintains existing conditions, and adds the new condition with the 'or' flag set to true. This implementation enables proper chaining of query conditions.


214-217: Improved error handling in buildDelete.

The method now explicitly returns errors from buildWheres, ensuring that any issues with WHERE clause construction are properly propagated.


262-267: Consistent error handling in buildSelect.

Similar to buildDelete, this method now properly handles and returns errors from the buildWheres function.


280-286: Simplified buildUpdate method.

The buildUpdate method now uses the common buildWheres function and directly returns the result of the builder's ToSql method, making the code more consistent and maintainable.


288-301: Well-designed buildWhere helper method.

This method correctly handles different types of where conditions, including string-based conditions with special handling for single and multiple arguments, improving code reusability.


360-371: Type-safe toSqlizer helper method.

The toSqlizer method properly handles different input types and provides clear error messages for unsupported types, which will aid in debugging and development.

mocks/database/db/Query.go (2)

230-251: Mock implementation for OrWhere method.

The OrWhere method mock correctly handles the query parameter and variadic args, combining them into a single slice for the mock.Called method. The return value handling is also properly implemented.


253-287: Complete support for mocking OrWhere method.

The implementation includes all necessary helper types and methods for setting up mock expectations, running custom behavior, and returning values, which matches the pattern used for other methods in the file.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

PR Overview

This PR introduces flexible query filtering by adding an OrWhere method for both production and mock queries while also updating related tests and documentation. Key changes include the new OrWhere implementation in both the production and test code, updated grouping of WHERE conditions in query builders, and adjusted error handling in the listener make command.

Reviewed Changes

File Description
mocks/database/db/Query.go Adds mock functions and helpers for the new OrWhere method.
database/db/query.go Implements the OrWhere method and updates query builders to include grouped conditions.
database/db/query_test.go Updates expected query strings to reflect the new grouping with OrWhere.
tests/db_test.go Adjusts time handling and adds a test for OrWhere usage.
database/db/conditions.go Minor formatting update in the Conditions struct.
event/console/listener_make_command.go Changes error handling: logs error on context instead of returning the error.
contracts/database/db/db.go Updates interface comments to include the OrWhere method.

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

@hwbrzzl hwbrzzl merged commit e26aa18 into master Feb 27, 2025
11 of 14 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#358-5 branch February 27, 2025 08:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants