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: [#477] Configure camel case columns instead of snake case GORM #773

Merged
merged 3 commits into from
Dec 20, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Dec 18, 2024

📑 Description

Closes goravel/goravel#477

Summary by CodeRabbit

  • New Features

    • Expanded configuration options with the addition of NoLowerCase and NameReplacer fields to enhance string handling.
    • Updated naming strategy in the database configuration for improved flexibility.
  • Bug Fixes

    • Improved test coverage for new configuration parameters in the ConfigBuilder and Application classes.
  • Tests

    • Enhanced mock configurations for database drivers to include expectations for new parameters.
    • Added new expectations in the test suite for PostgreSQL database connections.

✅ Checks

  • Added test cases for my code

@hwbrzzl hwbrzzl requested a review from a team as a code owner December 18, 2024 11:16
Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces enhancements to the database configuration system, specifically focusing on providing more flexibility in database naming strategies. The changes add two new configuration options: NoLowerCase and NameReplacer to the FullConfig struct. These additions allow developers to control column naming conventions, such as preventing automatic snake_case conversion and implementing custom name replacements for database schema generation.

Changes

File Change Summary
contracts/database/config.go Added NoLowerCase bool and NameReplacer Replacer fields to FullConfig struct; Introduced new Replacer interface.
database/db/config_builder.go Updated fillDefault method to handle new configuration fields NoLowerCase and NameReplacer.
database/db/config_builder_test.go Added test cases for new configuration options, including no_lower_case and name_replacer.
database/gorm/gorm.go Modified init method to incorporate new NoLowerCase and NameReplacer fields in NamingStrategy.
database/gorm/test_utils.go Added mock configuration expectations for new configuration options.

Assessment against linked issues

Objective Addressed Explanation
Configure camel case columns
Prevent snake_case conversion
Support custom name replacements

Possibly related PRs

Suggested reviewers

  • kkumar-gcc

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 23687d0 and 3583964.

📒 Files selected for processing (8)
  • console/cli_helper.go (2 hunks)
  • contracts/database/config.go (1 hunks)
  • database/db/config_builder.go (1 hunks)
  • database/db/config_builder_test.go (9 hunks)
  • database/gorm/gorm.go (1 hunks)
  • database/gorm/test_utils.go (4 hunks)
  • foundation/application_test.go (1 hunks)
  • mocks/database/Replacer.go (1 hunks)

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.

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 (6)
contracts/database/config.go (1)

46-49: Consider adding documentation for the Replacer interface.

The interface design is clean and follows Go conventions, but could benefit from documentation explaining its purpose and usage in the context of column naming.

Add documentation like:

+// Replacer provides custom column name transformation logic.
+// It can be used to implement custom naming conventions (e.g., camelCase, PascalCase).
 type Replacer interface {
+    // Replace transforms the given database column name according to custom rules
     Replace(name string) string
 }
database/db/config_builder.go (2)

58-61: Enhance error handling for invalid NameReplacer configuration.

While the implementation works, it silently ignores invalid NameReplacer configurations. Consider adding validation and logging.

 if nameReplacer := c.config.Get(fmt.Sprintf("database.connections.%s.name_replacer", c.connection)); nameReplacer != nil {
     if replacer, ok := nameReplacer.(database.Replacer); ok {
+        if replacer == nil {
+            log.Printf("Warning: nil NameReplacer implementation provided for connection %s", c.connection)
+            continue
+        }
         fullConfig.NameReplacer = replacer
+    } else {
+        log.Printf("Warning: invalid NameReplacer type for connection %s", c.connection)
     }
 }

Line range hint 46-49: Would you like an example CamelCaseReplacer implementation?

The interface is well-designed, but users might benefit from a concrete example implementing camel case conversion.

I can help create an example implementation of the Replacer interface that converts snake_case to camelCase, along with its unit tests. Would you like me to generate this code or create a GitHub issue to track this enhancement?

database/db/config_builder_test.go (2)

76-77: Consider extracting duplicated mock expectations

The mock expectations for no_lower_case and name_replacer are duplicated in the Writes method. Consider extracting these common expectations into a helper method to improve maintainability.

Example refactor:

+func (s *ConfigTestSuite) setCommonConfigExpectations() {
+    s.mockConfig.EXPECT().GetBool(fmt.Sprintf("database.connections.%s.no_lower_case", s.connection)).Return(false)
+    s.mockConfig.EXPECT().Get(fmt.Sprintf("database.connections.%s.name_replacer", s.connection)).Return(nil)
+}

 func (s *ConfigTestSuite) TestWrites() {
     // ... existing code ...
-    s.mockConfig.EXPECT().GetBool(fmt.Sprintf("database.connections.%s.no_lower_case", s.connection)).Return(false)
-    s.mockConfig.EXPECT().Get(fmt.Sprintf("database.connections.%s.name_replacer", s.connection)).Return(nil)
+    s.setCommonConfigExpectations()
     
     // ... later in the test ...
-    s.mockConfig.EXPECT().GetBool(fmt.Sprintf("database.connections.%s.no_lower_case", s.connection)).Return(false)
-    s.mockConfig.EXPECT().Get(fmt.Sprintf("database.connections.%s.name_replacer", s.connection)).Return(nil)
+    s.setCommonConfigExpectations()

Also applies to: 99-100


125-125: LGTM: Test cases for new configuration options

The test cases properly verify the new configuration options. The nameReplacer is well-defined and the expectations are correctly set up.

Consider adding test cases for:

  • Different name replacement patterns
  • Edge cases where name replacer is invalid

Also applies to: 144-145, 164-165

database/gorm/test_utils.go (1)

298-299: LGTM: Consistent implementation across database drivers

The new configuration expectations are consistently implemented across all database drivers (MySQL, PostgreSQL, SQLite, and SQL Server).

Consider extracting these common expectations into a shared helper function to reduce code duplication and make future maintenance easier.

Example refactor:

+func addCommonConfigExpectations(mockConfig *mocksconfig.Config, connection string) {
+    mockConfig.EXPECT().GetBool(fmt.Sprintf("database.connections.%s.no_lower_case", connection)).Return(false)
+    mockConfig.EXPECT().Get(fmt.Sprintf("database.connections.%s.name_replacer", connection)).Return(nil)
+}

 func (r *MockMysql) basic() {
     // ... existing code ...
-    r.mockConfig.EXPECT().GetBool(fmt.Sprintf("database.connections.%s.no_lower_case", r.connection)).Return(false)
-    r.mockConfig.EXPECT().Get(fmt.Sprintf("database.connections.%s.name_replacer", r.connection)).Return(nil)
+    addCommonConfigExpectations(r.mockConfig, r.connection)
     mockPool(r.mockConfig)
 }

Also applies to: 373-374, 436-437, 504-505

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1a81ebb and 23687d0.

⛔ Files ignored due to path filters (1)
  • mocks/database/Replacer.go is excluded by !mocks/**
📒 Files selected for processing (5)
  • contracts/database/config.go (1 hunks)
  • database/db/config_builder.go (1 hunks)
  • database/db/config_builder_test.go (9 hunks)
  • database/gorm/gorm.go (1 hunks)
  • database/gorm/test_utils.go (4 hunks)
🔇 Additional comments (5)
contracts/database/config.go (1)

37-38: LGTM! Well-designed configuration options for column naming.

The new fields provide flexible control over column naming:

  • NoLowerCase: Toggle to prevent automatic case conversion
  • NameReplacer: Interface-based approach for custom naming strategies
database/gorm/gorm.go (1)

125-126: LGTM! Correct integration with GORM's naming strategy.

The implementation properly configures GORM's naming strategy with the new options:

  • NoLowerCase is directly mapped to GORM's field
  • NameReplacer is correctly integrated for custom naming
database/db/config_builder.go (1)

51-57: LGTM! Clean configuration loading implementation.

The configuration loading follows consistent patterns and properly initializes the new fields.

database/db/config_builder_test.go (1)

49-50: LGTM: Mock expectations for new configuration options

The new mock expectations for no_lower_case and name_replacer are properly added to the Reads test method.

database/gorm/test_utils.go (1)

Line range hint 1-1: Verify implementation files

The test changes look good, but the implementation files (FullConfig struct definition and the actual GORM configuration code) are not included in this review. Please ensure these files are also reviewed to verify:

  1. The implementation of NoLowerCase and NameReplacer in the FullConfig struct
  2. The GORM configuration code that uses these options to control column naming
✅ Verification successful

Implementation verified and properly integrated

The implementation is complete and correctly integrated across the codebase:

  1. The FullConfig struct in contracts/database/config.go properly defines both NoLowerCase and NameReplacer fields
  2. The GORM configuration in database/gorm/gorm.go correctly applies these options to GORM's NamingStrategy
  3. The config builder in database/db/config_builder.go properly loads these settings from the configuration:
    • NoLowerCase is loaded from the no_lower_case config key
    • NameReplacer is loaded with type safety checks from the name_replacer config key
  4. The implementation is well-tested in config_builder_test.go
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find the implementation files for the new configuration options

# Look for FullConfig struct definition
echo "Searching for FullConfig struct definition..."
ast-grep --pattern 'type FullConfig struct {
  $$$
  NoLowerCase bool
  NameReplacer $$$
  $$$
}'

# Look for GORM configuration code
echo "Searching for GORM configuration usage..."
rg -l "NoLowerCase|NameReplacer" --type go

Length of output: 1166


Script:

#!/bin/bash
# Let's examine the implementation of these configuration options

# Check the GORM implementation
echo "=== GORM Implementation ==="
rg "NoLowerCase|NameReplacer" database/gorm/gorm.go -C 5

# Check the config builder implementation
echo -e "\n=== Config Builder Implementation ==="
rg "NoLowerCase|NameReplacer" database/db/config_builder.go -C 5

# Look for any tests that verify this functionality
echo -e "\n=== Config Builder Tests ==="
rg "NoLowerCase|NameReplacer" database/db/config_builder_test.go -C 5

Length of output: 2474

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 18, 2024
kkumar-gcc
kkumar-gcc previously approved these changes Dec 19, 2024
Copy link
Member

@kkumar-gcc kkumar-gcc left a comment

Choose a reason for hiding this comment

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

LGTM

devhaozi
devhaozi previously approved these changes Dec 19, 2024
Copy link
Member

@devhaozi devhaozi left a comment

Choose a reason for hiding this comment

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

lgtm

@devhaozi devhaozi enabled auto-merge (squash) December 19, 2024 11:32
Copy link

codecov bot commented Dec 20, 2024

Codecov Report

Attention: Patch coverage is 76.25571% with 52 lines in your changes missing coverage. Please review.

Project coverage is 69.96%. Comparing base (05d69a6) to head (3583964).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
console/cli_helper.go 73.86% 40 Missing and 12 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #773      +/-   ##
==========================================
+ Coverage   69.94%   69.96%   +0.02%     
==========================================
  Files         213      213              
  Lines       18164    18177      +13     
==========================================
+ Hits        12705    12718      +13     
  Misses       4762     4762              
  Partials      697      697              

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

@hwbrzzl hwbrzzl disabled auto-merge December 20, 2024 04:16
@hwbrzzl hwbrzzl merged commit 04cd96a into master Dec 20, 2024
11 of 12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#477 branch December 20, 2024 04:16
hwbrzzl added a commit that referenced this pull request Dec 20, 2024
…773)

* feat: [#477] Configure camel case columns instead of snake case GORM

* chore: update mocks

* fix test

---------

Co-authored-by: hwbrzzl <[email protected]>
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.

✨ [Feature] Configure camel case columns instead of snake case GORM
3 participants