Skip to content
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

feat: [#358] Add Update Delete methods for DB #904

Merged
merged 3 commits into from
Feb 21, 2025
Merged

feat: [#358] Add Update Delete methods for DB #904

merged 3 commits into from
Feb 21, 2025

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Feb 21, 2025

📑 Description

goravel/goravel#358

Summary by CodeRabbit

  • New Features

    • Enhanced record management by introducing robust delete and update operations, improving overall data handling reliability.
  • Tests

    • Added comprehensive tests to verify the correct behavior of delete and update operations, ensuring system stability.
  • Chores

    • Updated underlying dependencies to further boost performance and maintain consistency.

✅ Checks

  • Added test cases for my code

@hwbrzzl hwbrzzl requested a review from a team as a code owner February 21, 2025 10:50
Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

This pull request extends database query functionality by introducing Delete() and Update(data any) operations. The changes add these methods to the Query interface and their corresponding implementations, including SQL builder helper functions, error handling, and logging placeholders. Additionally, the test suites and mock components have been updated to verify and simulate these new operations. Minor adjustments to utility functions and dependency updates are also included.

Changes

File(s) Change Summary
contracts/database/db/db.go, database/db/query.go, mocks/database/db/Query.go Added Delete() and Update(data any) methods to the Query interface/struct. Implemented helper functions (buildDelete, buildUpdate) and extended mocking infrastructure with new call types and expectation methods.
database/db/query_test.go, tests/db_test.go Introduced new test methods (TestDelete, TestUpdate, TestUpdate_Delete) for delete and update operations. Updated test data structures (e.g., added Phone field) to reflect changes.
database/db/utils.go, database/db/utils_test.go Modified convertToMap to skip zero value fields and added a Length field in the Body struct, updating tests accordingly.
tests/go.mod Updated the golang.org/x/exp module version.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Query
    participant SQLBuilder
    participant Database

    Client->>Query: call Update(data)
    Query->>SQLBuilder: buildUpdate(data)
    SQLBuilder-->>Query: SQL statement & args
    Query->>Database: execute SQL query
    Database-->>Query: return result & error
    Query-->>Client: return result & error
Loading
sequenceDiagram
    participant Client
    participant Query
    participant SQLBuilder
    participant Database

    Client->>Query: call Delete()
    Query->>SQLBuilder: buildDelete()
    SQLBuilder-->>Query: SQL statement & args
    Query->>Database: execute SQL query
    Database-->>Query: return result & error
    Query-->>Client: return result & error
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 (Beta)

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. (Beta)
  • @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.

@@ -127,6 +127,9 @@ func convertToMap(data any) (map[string]any, error) {
if fieldValue.Kind() == reflect.Ptr && !fieldValue.IsNil() {
fieldValue = fieldValue.Elem()
}
if fieldValue.IsZero() {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Don't update or insert the zero value of struct.

Copy link

codecov bot commented Feb 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 67.78%. Comparing base (3cde68c) to head (124fdd7).
Report is 3 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #904   +/-   ##
=======================================
  Coverage   67.78%   67.78%           
=======================================
  Files         154      154           
  Lines       10194    10194           
=======================================
  Hits         6910     6910           
  Misses       2951     2951           
  Partials      333      333           

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

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.go (1)

147-174: Reduce code duplication in SQL building logic.

The where clause handling logic is duplicated across buildDelete, buildUpdate, and buildSelect. Consider extracting this into a helper method.

+func (r *Query) buildWhereClause(builder sq.SelectBuilder) sq.SelectBuilder {
+	for _, where := range r.conditions.where {
+		query, ok := where.query.(string)
+		if ok {
+			if !str.Of(query).Trim().Contains(" ", "?") {
+				if len(where.args) > 1 {
+					builder = builder.Where(sq.Eq{query: where.args})
+				} else if len(where.args) == 1 {
+					builder = builder.Where(sq.Eq{query: where.args[0]})
+				}
+				continue
+			}
+		}
+		builder = builder.Where(where.query, where.args...)
+	}
+	return builder
+}

Also applies to: 236-265

tests/db_test.go (1)

138-203: Consider adding error case tests.

The test thoroughly validates the happy path for update and delete operations. Consider adding test cases for error scenarios such as:

  1. Updating non-existent records
  2. Deleting non-existent records
  3. Invalid data types in updates
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3cde68c and c45f273.

⛔ Files ignored due to path filters (1)
  • tests/go.sum is excluded by !**/*.sum
📒 Files selected for processing (8)
  • contracts/database/db/db.go (1 hunks)
  • database/db/query.go (4 hunks)
  • database/db/query_test.go (3 hunks)
  • database/db/utils.go (1 hunks)
  • database/db/utils_test.go (2 hunks)
  • mocks/database/db/Query.go (2 hunks)
  • tests/db_test.go (3 hunks)
  • tests/go.mod (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/go.mod
🔇 Additional comments (10)
contracts/database/db/db.go (1)

11-11: LGTM! Well-structured interface additions.

The new Delete() and Update(data any) methods are consistent with the existing interface design and follow the same return type pattern as Insert().

Also applies to: 14-14

database/db/utils_test.go (1)

10-10: LGTM! Comprehensive test coverage for the new field.

The test cases thoroughly cover the new Length field across different scenarios including struct slices, pointer slices, and direct struct usage.

Also applies to: 35-35, 45-45, 55-55, 57-57

database/db/utils.go (1)

130-132: LGTM! Zero-value handling implemented as requested.

The implementation correctly skips zero-value fields during map conversion, addressing the previous feedback.

database/db/query.go (1)

31-52: LGTM! Well-implemented Delete and Update methods.

The implementations handle errors appropriately, use proper SQL building, and return affected rows count.

Also applies to: 108-134

database/db/query_test.go (3)

16-21: LGTM!

The TestUser struct has been updated with a new Phone field and appropriate database tags.


38-48: LGTM!

The test case thoroughly validates the deletion functionality by:

  1. Verifying the SQL statement construction
  2. Checking the rows affected
  3. Ensuring no errors occur

166-202: LGTM!

The test case thoroughly validates the update functionality by:

  1. Testing both struct and map update scenarios
  2. Verifying SQL statement construction for each case
  3. Checking the rows affected
  4. Ensuring no errors occur
tests/db_test.go (1)

40-42: LGTM!

Moving the now variable initialization outside the loop improves performance by avoiding repeated initialization.

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

23-78: LGTM!

The mock implementation for Delete is well-structured and provides comprehensive mocking capabilities including:

  1. Proper error handling
  2. Type assertions
  3. Flexible Run/Return methods

230-286: LGTM!

The mock implementation for Update is well-structured and provides comprehensive mocking capabilities including:

  1. Proper error handling
  2. Type assertions
  3. Flexible Run/Return methods

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: 0

🧹 Nitpick comments (1)
tests/db_test.go (1)

138-203: LGTM! Well-structured test implementation.

The test comprehensively covers update and delete operations with good validation of results.

Consider enhancing test coverage with edge cases.

Consider adding the following test cases to make the test suite more robust:

  1. Update/delete of non-existent records
  2. Verification of updated_at timestamp changes
  3. Update with invalid data types

Here's a suggested structure using sub-tests:

 func (s *DBTestSuite) TestUpdate_Delete() {
 	now := carbon.NewDateTime(carbon.FromDateTime(2025, 1, 2, 3, 4, 5))
 
 	for driver, query := range s.queries {
 		s.Run(driver, func() {
+			s.Run("successful operations", func() {
 				// Your existing test code
+			})
+
+			s.Run("edge cases", func() {
+				// Test updating non-existent record
+				result, err := query.DB().Table("products").Where("name", "non-existent").Update(map[string]any{
+					"name": "updated",
+				})
+				s.NoError(err)
+				s.Equal(int64(0), result.RowsAffected)
+
+				// Test deleting non-existent record
+				result, err = query.DB().Table("products").Where("name", "non-existent").Delete()
+				s.NoError(err)
+				s.Equal(int64(0), result.RowsAffected)
+
+				// Test update with invalid data type
+				result, err = query.DB().Table("products").Where("name", "test").Update(map[string]any{
+					"created_at": "invalid-date",
+				})
+				s.Error(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 c45f273 and 124fdd7.

📒 Files selected for processing (1)
  • tests/db_test.go (3 hunks)
⏰ Context from checks skipped due to timeout of 300000ms (1)
  • GitHub Check: test / windows (1.23)
🔇 Additional comments (1)
tests/db_test.go (1)

41-41: LGTM! Good performance optimization.

Moving the now variable initialization outside the loop reduces unnecessary object creation.

@hwbrzzl hwbrzzl merged commit 0fdfcff into master Feb 21, 2025
14 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#358-2 branch February 21, 2025 14:52
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.

1 participant