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

fix: [#280] prefix is not added to table #665

Merged
merged 2 commits into from
Oct 3, 2024
Merged

fix: [#280] prefix is not added to table #665

merged 2 commits into from
Oct 3, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Oct 3, 2024

📑 Description

If the DB configuration sets the prefix parameter: goravel_, then call facades.Orm().Query().Table("users").Get(), the SQL will be select * from users, expect: select * from goravel_users.

Due to the Orm module having a huge refactor, this change will not be merged to v1.14.

Summary by CodeRabbit

  • New Features

    • Enhanced query configuration management for improved database interactions.
    • Added comprehensive tests for CRUD operations, associations, and transaction handling.
  • Bug Fixes

    • Improved error handling and condition management in query operations.
  • Tests

    • Expanded test coverage for various functionalities, including advanced query operations and event triggers.

✅ Checks

  • Added test cases for my code

Copy link
Contributor

coderabbitai bot commented Oct 3, 2024

Walkthrough

The changes in this pull request involve significant modifications to the Query method and the Query struct within the GORM database layer. The Query method now utilizes a fullConfig parameter instead of a connection string, enhancing how queries are constructed and configured. Additionally, the testing suite for Query has been expanded with numerous new test cases to cover various database operations, including CRUD functionalities and error handling. Adjustments were also made to the ApplicationTestSuite to accommodate new expectations for PostgreSQL database configurations.

Changes

File Change Summary
database/gorm/event.go Modified the Query method to use e.query.fullConfig instead of e.query.connection.
database/gorm/query.go Removed connection field from Query struct, added fullConfig field. Updated NewQuery constructor and several methods to utilize fullConfig. Adjusted buildTable method for table name construction.
database/gorm/query_test.go Expanded QueryTestSuite with numerous new tests for associations, event triggers, CRUD operations, advanced query functionalities, transaction handling, connection management, and error handling.
foundation/application_test.go Updated TestMakeOrm method to set multiple expectations for PostgreSQL configuration keys in the mock configuration.

Possibly related PRs

  • fix: transaction error #654: Modifications to the Query interface and its methods, directly related to the changes in the Query struct.
  • feat: Optimize the Delete and ForceDelete methods of Orm #655: Optimizations for the Delete and ForceDelete methods in the Query interface, aligning with changes in deletion operations.
  • chore: orm test #658: Simplification of the test_utils.go file and introduction of different test models for improved testing speed, relevant to testing improvements in the main PR.
  • chore: remove wire #660: Removal of the "wire" component and restructuring of database configuration management, indirectly related to database query handling improvements.

Suggested reviewers

  • kkumar-gcc
  • devhaozi

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

@hwbrzzl hwbrzzl marked this pull request as ready for review October 3, 2024 09:16
@hwbrzzl hwbrzzl requested a review from a team as a code owner October 3, 2024 09:16
Copy link

codecov bot commented Oct 3, 2024

Codecov Report

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

Project coverage is 70.57%. Comparing base (aeaf75d) to head (553523f).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
database/gorm/query.go 80.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #665      +/-   ##
==========================================
- Coverage   70.58%   70.57%   -0.01%     
==========================================
  Files         186      186              
  Lines       11874    11877       +3     
==========================================
+ Hits         8381     8382       +1     
- Misses       2923     2924       +1     
- Partials      570      571       +1     

☔ 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: 4

🧹 Outside diff range and nitpick comments (8)
database/gorm/query.go (1)

53-56: Clarify error message for missing database configuration

The error message "not found database configuration" could be more descriptive to aid troubleshooting.

Consider updating the error message to specify which connection is missing configuration:

if len(writeConfigs) == 0 {
-	return nil, errors.New("not found database configuration")
+	return nil, errors.New("no database configuration found for connection: " + connection)
}
database/gorm/query_test.go (7)

Line range hint 2709-2737: Handle potential errors when asserting NotNil

In TestCustomConnection, after calling query.Create(&person), you assert that an error should occur and that person.ID should be 0:

assert.NotNil(t, query.Create(&person))
assert.True(t, person.ID == 0)

Ensure that the error returned by Create is the expected one, and consider using assert.Error with a specific error message to make the test more robust.


Line range hint 2325-2339: Avoid direct comparison with nil in error assertions

In TestObserverEvent, you're comparing errors directly with nil:

assert.EqualError(t, getObserverEvent(contractsorm.EventRetrieved, &UserObserver{})(nil), "retrieved")

Consider using assert.Error or assert.NoError for better clarity and consistency in your tests.


Line range hint 2429-2443: Synchronize goroutines in TestLockForUpdate to prevent data races

In TestLockForUpdate, you're launching goroutines without synchronization, which may lead to data races:

for i := 0; i < 10; i++ {
    go func() {
        // ...
    }()
}

Use a sync.WaitGroup to wait for all goroutines to finish before proceeding. Also, ensure that shared resources are properly synchronized.


Line range hint 2761-2771: Check for errors after rolling back transactions

In TestTransactionError, after rolling back the transaction, you proceed without checking for errors:

tx, err := query.Query().Begin()
s.Nil(err)
s.Nil(tx.Create(&user))
// ...
s.Nil(tx.Rollback())

Ensure you check the error returned by Rollback to handle any potential issues during the rollback process.


Line range hint 2874-2880: Handle errors returned by Save in tests

In TestEvent_IsDirty, when saving the user after modification, you should handle the error returned by Save:

s.Nil(query.Query().Save(&user))

Consider capturing and asserting the error to ensure that the save operation is successful.


Line range hint 3196-3202: Remove redundant assertions after Create operations

In TestPaginate, you assert that user3.ID > 0 after creation:

user3 := User{Name: "paginate_user", Avatar: "paginate_avatar3"}
s.Nil(query.Query().Create(&user3))
s.True(user3.ID > 0)

This assertion is redundant since Create should already ensure that the ID is set. You can remove this assertion to keep the test concise.


Line range hint 3388-3390: Correct duplicate test names in TestFirstOrFail

In TestFirstOrFail, it appears there are duplicate test cases with the name "trigger when FirstOrFail". This could cause confusion when interpreting test results.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between aeaf75d and 553523f.

📒 Files selected for processing (4)
  • database/gorm/event.go (1 hunks)
  • database/gorm/query.go (6 hunks)
  • database/gorm/query_test.go (1 hunks)
  • foundation/application_test.go (1 hunks)
🔇 Additional comments (5)
database/gorm/query.go (5)

35-39: Well-structured incorporation of fullConfig into NewQuery

The addition of fullConfig to the NewQuery function and the Query struct enhances the configuration management and allows for more comprehensive handling of database settings.


63-63: Ensure correct selection of write configuration

When accessing writeConfigs[0], ensure that the write configurations are ordered correctly, and the first one is the intended default.

Please verify that writeConfigs[0] is the appropriate configuration to use as the default. If there are multiple write configurations, confirm that the selection logic aligns with the expected behavior.


Line range hint 1125-1129: Consistent use of fullConfig in nested queries

The use of r.fullConfig when creating a new Query instance within the buildWith method ensures consistent configuration across nested queries.


1259-1260: Maintain consistency in new method

The new method correctly passes r.fullConfig to maintain consistent configuration in new Query instances.


Line range hint 1319-1337: Verify connection comparison logic in refreshConnection

Ensure that the comparison connection == r.fullConfig.Connection accurately determines when to refresh the connection, considering any potential differences in connection naming conventions or case sensitivity.

Please confirm that connection and r.fullConfig.Connection are consistently formatted and that there are no edge cases where the comparison might fail due to casing or whitespace differences.

database/gorm/event.go Show resolved Hide resolved
foundation/application_test.go Show resolved Hide resolved
database/gorm/query.go Show resolved Hide resolved
database/gorm/query_test.go Show resolved Hide resolved
@hwbrzzl hwbrzzl merged commit 2c6c7e7 into master Oct 3, 2024
11 of 12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/fix-table branch October 3, 2024 09:49
@coderabbitai coderabbitai bot mentioned this pull request Oct 3, 2024
1 task
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