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

chore: remove wire #660

Merged
merged 12 commits into from
Oct 1, 2024
Merged

chore: remove wire #660

merged 12 commits into from
Oct 1, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Oct 1, 2024

📑 Description

Summary by CodeRabbit

  • New Features

    • Introduced a ConfigBuilder for managing database configurations with methods for reading and writing configurations.
    • Enhanced configuration retrieval process with default population for various database drivers.
  • Refactor

    • Streamlined DSN generation logic and consolidated database driver handling under a unified function.
    • Removed obsolete ORM-related structures and interfaces to enhance clarity and maintainability.
    • Updated the Dialector implementation to simplify the creation of GORM dialectors.
    • Restructured testing approach for database dialectors to improve readability and reduce boilerplate code.

✅ Checks

  • Added test cases for my code

@hwbrzzl hwbrzzl requested a review from a team as a code owner October 1, 2024 03:01
@hwbrzzl hwbrzzl marked this pull request as draft October 1, 2024 03:01
Copy link
Contributor

coderabbitai bot commented Oct 1, 2024

Walkthrough

The pull request introduces a new configs.go file in the database/db package, featuring a ConfigBuilder struct for managing database configurations. This struct includes methods for retrieving read and write configurations, as well as a method for populating default values. Additionally, the dialector.go file has been refactored to consolidate the creation of GORM dialectors into a single function. The test suite for database dialectors has also been restructured to simplify testing.

Changes

File Path Change Summary
database/db/configs.go Introduced a ConfigBuilder struct for managing database configurations, including methods for retrieving read (Reads) and write (Writes) configurations, and a fillDefault method for populating default values in configurations.
database/gorm/dialector.go Removed the Dialector interface and DialectorImpl struct, introducing a new getDialectors function that creates GORM dialectors based on configurations.
database/gorm/dialector_test.go Restructured the test suite for database dialectors, consolidating tests into a single function that handles multiple cases.

Possibly related PRs

Suggested reviewers

  • devhaozi
  • kkumar-gcc

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.

Copy link

codecov bot commented Oct 1, 2024

Codecov Report

Attention: Patch coverage is 87.91946% with 54 lines in your changes missing coverage. Please review.

Project coverage is 70.58%. Comparing base (cd17022) to head (61aa33f).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
database/orm.go 48.38% 15 Missing and 1 partial ⚠️
database/gorm/query.go 94.51% 9 Missing ⚠️
database/service_provider.go 0.00% 8 Missing ⚠️
database/gorm/gorm.go 75.00% 2 Missing and 3 partials ⚠️
database/gorm/test_utils.go 95.60% 4 Missing ⚠️
database/console/migrate_creator.go 25.00% 3 Missing ⚠️
database/db/configs.go 93.47% 2 Missing and 1 partial ⚠️
database/gorm/dialector.go 90.90% 2 Missing ⚠️
database/migration/schema.go 50.00% 2 Missing ⚠️
database/db/dsn.go 93.33% 1 Missing ⚠️
... and 1 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #660      +/-   ##
==========================================
+ Coverage   70.36%   70.58%   +0.21%     
==========================================
  Files         189      186       -3     
  Lines       11926    11874      -52     
==========================================
- Hits         8392     8381      -11     
+ Misses       2956     2923      -33     
+ Partials      578      570       -8     

☔ 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 October 1, 2024 11:12
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: 37

🧹 Outside diff range and nitpick comments (34)
testing/docker/database.go (1)

53-60: LGTM: Build method refactored effectively.

The Build method has been successfully refactored to use the new ORM-based approach. The changes improve the build process by adding database port configuration and explicitly calling migrations.

A minor suggestion for improvement:

Consider extracting the string "database.connections.%s.port" into a constant for better maintainability. For example:

+const databaseConnectionPortFormat = "database.connections.%s.port"

 func (r *Database) Build() error {
     if err := r.DatabaseDriver.Build(); err != nil {
         return err
     }

-    r.config.Add(fmt.Sprintf("database.connections.%s.port", r.connection), r.DatabaseDriver.Config().Port)
+    r.config.Add(fmt.Sprintf(databaseConnectionPortFormat, r.connection), r.DatabaseDriver.Config().Port)
     r.artisan.Call("migrate")
     r.orm.Refresh()

     return nil
 }
database/db/dsn_test.go (2)

28-33: LGTM: Improved test structure with table-driven tests.

The new TestDsn function implements a table-driven test approach, which is more maintainable and allows for easy addition of new test cases. This structure effectively covers multiple database configurations in a single test function.

Consider adding a comment above the tests slice to briefly explain the purpose of these test cases, enhancing readability for future maintainers.


34-80: LGTM: Comprehensive test cases for various database configurations.

The test cases cover a wide range of scenarios including empty config, MySQL, PostgreSQL, SQLite, and SQL Server. Each case is well-structured with a clear name, configuration, and expected DSN string.

Consider adding a test case for a configuration with non-default values (e.g., different charset, sslmode, or timezone) to ensure the DSN generation handles custom settings correctly.

database/service_provider.go (1)

22-29: Approve changes with a suggestion for context handling.

The changes in the Register method look good overall. The receiver name change to r is consistent with Go conventions, and the error message update is appropriate.

Consider using a more specific context instead of context.Background(). If this is part of an HTTP request handler, you might want to use the request's context. If it's part of a longer-running process, consider passing a cancellable context from the caller.

Example:

func (r *ServiceProvider) Register(app foundation.Application) {
    app.Singleton(BindingOrm, func(app foundation.Application) (any, error) {
        // Use a context with timeout or one passed from the caller
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        
        // Rest of the code...
    })
    // Rest of the method...
}
database/migration/schema.go (1)

77-87: LGTM! Consider addressing TODOs in future PRs.

The changes to use contractsdatabase instead of contractsorm for driver constants are consistent and maintain the function's logic. However, there are still TODO comments for MySQL, SQL Server, and SQLite drivers that should be addressed in future pull requests to improve the implementation.

Consider creating issues to track the implementation of these drivers:

  1. MySQL driver implementation
  2. SQL Server driver implementation
  3. SQLite driver implementation
support/docker/postgres.go (1)

Line range hint 1-124: Summary of changes and potential impact

The changes in this file are part of a larger refactoring effort to move from an ORM-specific structure to a more general database structure. This aligns with the PR objective of removing the "wire" component. The changes are minimal, focused, and well-implemented.

Key points:

  1. The import statement has been updated to use the more general database package.
  2. The Driver() method has been modified to return database.Driver instead of orm.Driver.

These changes appear to be consistent and don't introduce any apparent issues. However, it's crucial to ensure that these modifications are consistent across the entire codebase and don't break any existing functionality that might depend on the old structure.

Consider updating the documentation to reflect these architectural changes, especially if this is part of a larger refactoring effort. This will help maintain clear and up-to-date documentation for developers working on the project.

database/console/test_utils.go (1)

Line range hint 1-116: Summary: Changes align with PR objective and maintain functionality.

The modifications in this file successfully remove references to the "wire" component by updating import statements and type references from contractsorm to database. These changes are consistent throughout the file and maintain the existing functionality.

To ensure the completeness of this refactoring effort:

  1. Verify that similar changes have been made in other relevant files across the codebase.
  2. Update any documentation or comments that may reference the old contractsorm package.
  3. Run the full test suite to confirm that these changes haven't introduced any regressions.

Consider adding a brief comment at the top of the file explaining the rationale behind using the database package instead of contractsorm. This will help future maintainers understand the design decision.

database/migration/sql_driver.go (1)

Line range hint 1-103: Summary: Changes align with PR objective and maintain existing functionality.

The changes in this file are consistent with the PR objective of removing the "wire" component. The import path change and the corresponding update to the switch statement reflect a refactoring of the package structure from orm to database. These changes maintain the existing functionality of the SqlDriver struct and its methods while simplifying the overall package structure.

To ensure a smooth transition:

  1. Verify that all files importing the old orm package have been updated.
  2. Confirm that the constant definitions in the new database package match the ones previously defined in the orm package.
  3. Run the test cases mentioned in the PR description to ensure no regressions.

Consider updating the package documentation to reflect these changes and their rationale, which will help other developers understand the new structure.

database/console/migrate_creator.go (1)

Line range hint 1-98: Summary of changes and suggestion for documentation update.

The changes in this file are part of the larger effort to remove the "wire" component and refactor from an orm-specific implementation to a more general database implementation. The functionality of the MigrateCreator struct and its methods remains unchanged, with only the import and switch statement being updated to use the new database package instead of orm.

Consider updating any relevant documentation or comments in the codebase to reflect this change from orm to database, ensuring consistency across the project.

database/migration/schema_test.go (2)

28-28: LGTM: SchemaSuite struct updated correctly.

The change from contractsorm.Driver to contractsdatabase.Driver for the driverToTestDB map is consistent with the overall update in the file. This reflects a transition from ORM-specific to more general database contracts.

Consider renaming driverToTestDB to driverToTestDatabase for improved clarity, given the shift from ORM to general database contracts.


55-56: Driver type updated correctly, but consider improving test coverage.

The change from contractsorm.Driver to contractsdatabase.Driver is consistent with previous updates. However, hardcoding the connection string to "postgres" might limit the test coverage to only PostgreSQL.

Consider parameterizing the connection string to allow testing with multiple database drivers. This could be achieved by iterating over the s.driverToTestDB map or using a test table. For example:

for driver, testDB := range s.driverToTestDB {
    s.Run(driver.String(), func() {
        connection := driver.String()
        // ... rest of the test logic
    })
}

This approach would ensure that the TestConnection method covers all supported database drivers.

support/docker/mysql.go (1)

Line range hint 1-138: Summary: Changes align with PR objective and suggest larger refactoring effort.

The modifications in this file, specifically the import statement change and the Driver method update, are consistent with the PR objective of removing the "wire" component. These changes appear to be part of a larger refactoring effort to simplify and consolidate database-related code in the Goravel framework.

The limited scope of changes in this file suggests that the removal of the "wire" component mainly affects the database interfaces and not the implementation details of the MySQL driver. This approach maintains the existing functionality while moving towards a more abstract and flexible database interface.

To ensure the consistency and completeness of this refactoring effort across the entire codebase, consider the following actions:

  1. Review other database-related files for similar changes.
  2. Update any documentation or guides that reference the old database package structure.
  3. Ensure that all tests related to database functionality are updated and passing with these changes.

Would you like assistance in generating a checklist for these follow-up actions or in creating any necessary documentation updates?

foundation/container_test.go (1)

107-113: Good completion of Refresh test case

The addition of re-binding the Singleton after refresh completes the test case effectively. It ensures that the container can properly handle re-binding after a refresh operation. The checks for existence, shared status, and non-nil concrete are thorough.

Consider adding an assertion to verify that the concrete implementation of the re-bound Singleton is as expected:

s.True(ins.shared)
s.NotNil(ins.concrete)
+switch concrete := ins.concrete.(type) {
+case func(app foundation.Application) (any, error):
+    concreteImpl, err := concrete(nil)
+    s.Equal(1, concreteImpl)
+    s.Nil(err)
+default:
+    s.Fail("Unexpected concrete type after re-binding")
+}

This addition would ensure that the re-bound Singleton behaves as expected.

database/gorm/event.go (1)

Line range hint 1-368: Summary: Changes align with PR objective. Suggest comprehensive testing.

The modifications in this file consistently move away from the QueryImpl type to a more generic Query type, aligning with the PR objective of removing the "wire" component. These changes appear to be part of a larger refactoring effort.

To ensure the integrity of the framework after these changes:

  1. Verify that all related components have been updated to use the new Query type instead of QueryImpl.
  2. Run a comprehensive test suite to catch any potential regressions or unintended side effects.
  3. Consider updating any documentation or examples that may reference the old QueryImpl type.

Would you like assistance in generating a test plan or updating documentation?

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

21-22: LGTM! Consider enhancing the method comment.

The addition of the Refresh() method to the Orm interface is a good improvement. It provides a way to reset the ORM instance, which can be useful in various scenarios.

Consider expanding the comment to provide more context about when and why this method might be used. For example:

// Refresh resets the Orm instance, clearing any cached data or temporary state.
// This can be useful after bulk operations or when switching between different database operations.
Refresh()
foundation/container.go (1)

334-336: LGTM! Consider adding a comment for clarity.

The Refresh method is a good addition to the Container struct. It allows for the removal of cached instances, which can be useful for refreshing bindings or clearing stale data.

Consider adding a comment to explain the purpose of this method, for example:

// Refresh removes the instance associated with the given key from the container,
// allowing for re-creation of the instance on subsequent requests.
func (c *Container) Refresh(key any) {
	c.instances.Delete(key)
}
database/migration/blueprint_test.go (1)

Line range hint 1-380: Summary: Changes consistently update driver types and maintain test functionality.

The modifications in this file successfully transition from orm.Driver to database.Driver, aligning with the PR objective. All changes are consistent and maintain the existing test functionality while updating to the new driver type.

To ensure completeness:

  1. Verify that all instances of orm.Driver have been replaced throughout the codebase.
  2. Consider updating the PR description to mention this specific change from orm to database package for driver types.
  3. Ensure that any documentation referencing the old orm.Driver is updated accordingly.
database/gorm/query_test.go (4)

Line range hint 612-619: LGTM: Improved type safety in driver comparison

The switch statement now uses database.Driver* constants instead of string literals, which enhances type safety and maintainability. This is a good practice.

Consider using a switch driver.(type) statement instead of comparing the string representation. This would provide even better type safety and potentially better performance. For example:

switch driver.(type) {
case *database.DriverSqlserver, *database.DriverMysql:
    // ...
default:
    // ...
}

2047-2047: LGTM: SQLite excluded from LockForUpdate test

Excluding SQLite from the LockForUpdate test is appropriate, as SQLite likely doesn't support this feature or behaves differently from other databases.

Consider adding a brief comment explaining why SQLite is excluded from this test. This would help other developers understand the reasoning behind this condition. For example:

// SQLite doesn't support FOR UPDATE locks in the same way as other databases
if driver != database.DriverSqlite {
    // ...
}

2778-2778: LGTM: SQLite excluded from SharedLock test

Excluding SQLite from the SharedLock test is consistent with the approach taken in the LockForUpdate test. This ensures the test runs correctly for supported databases.

For consistency, consider adding a similar comment here as suggested for the LockForUpdate test. This maintains a uniform explanation throughout the code. For example:

// SQLite doesn't support shared locks in the same way as other databases
if driver != database.DriverSqlite {
    // ...
}

3659-3659: LGTM: Added mock config parameter to mockCommonConnection

The addition of the mockConfig parameter to the mockCommonConnection function enhances flexibility in testing by allowing the injection of a mock configuration. This is a good practice for improving testability.

Consider updating the function's documentation (if it exists) to reflect this new parameter. If there's no existing documentation, it would be beneficial to add a brief comment explaining the purpose of this function and its parameters. For example:

// mockCommonConnection sets up a mock database connection for testing purposes.
// It takes a mock configuration, a test query, and a connection string as parameters.
func mockCommonConnection(mockConfig *mocksconfig.Config, testQuery *TestQuery, connection string) {
    // ...
}
contracts/database/config.go (1)

25-26: Improve the Comment for FullConfig Struct

The comment // FullConfig Fill the default value for Config could be more descriptive. Consider revising it to better explain the purpose of FullConfig.

Apply this diff to enhance the comment:

-// FullConfig Fill the default value for Config
+// FullConfig extends Config with additional database configuration options.
database/gorm/dialector.go (2)

19-43: Handle Errors Without Halting the Entire Process

Currently, if an error occurs for a single configuration (e.g., empty DSN or unsupported driver), the function returns the error and halts processing. This means that valid configurations after the erroneous one are not processed.

Consider accumulating errors and processing all configurations. You could collect all successful dialectors and any errors, returning both so the caller can decide how to proceed.


16-44: Ensure Unit Test Coverage for All Scenarios

To maintain robustness, ensure that unit tests cover:

  • Successful dialector creation for each supported driver.
  • Handling of empty DSNs.
  • Behavior when encountering an unsupported driver.
  • Scenarios with multiple configurations, including both valid and invalid entries.
database/gorm/dialector_test.go (1)

25-26: Consider renaming expectDialectors to expectDialector for clarity

The field expectDialectors represents a function that checks a single dialector. Renaming it to expectDialector (singular) would enhance readability and accurately reflect its purpose.

database/console/migrate.go (1)

Line range hint 35-53: Refactor to eliminate duplicated code across driver cases

The logic within each case block of the switch statement is largely duplicated for each database driver. Each block performs similar steps:

  • Retrieve the DSN.
  • Check if the DSN is empty.
  • Open a database connection.
  • Handle potential errors.
  • Create an instance specific to the database.
  • Return the migration instance.

Consider refactoring this repeated logic into a helper function or utilizing a factory pattern to reduce code duplication and improve maintainability.

Also applies to: 54-72, 73-91, 92-111

database/orm.go (1)

Line range hint 58-64: Consider returning an error instead of nil when connection initialization fails

In the Connection method, if gorm.BuildQuery fails, the function prints an error message and returns nil. Returning nil for an interface can lead to nil pointer dereferences if the caller does not check for nil. It's advisable to return an explicit error so that callers can handle it appropriately.

Apply this diff to modify the function signature and handle errors:

-func (r *Orm) Connection(name string) contractsorm.Orm {
+func (r *Orm) Connection(name string) (contractsorm.Orm, error) {
    if name == "" {
        name = r.config.GetString("database.default")
    }
    if instance, exist := r.queries[name]; exist {
        return &Orm{
            ctx:        r.ctx,
            config:     r.config,
            connection: name,
            query:      instance,
            queries:    r.queries,
-       }
+       }, nil
    }

    queue, err := gorm.BuildQuery(r.ctx, r.config, name)
    if err != nil || queue == nil {
        color.Red().Println(fmt.Sprintf("[Orm] Init %s connection error: %v", name, err))

-       return nil
+       return nil, err
    }

    r.queries[name] = queue

    return &Orm{
        ctx:        r.ctx,
        config:     r.config,
        connection: name,
        query:      queue,
        queries:    r.queries,
-   }
+   }, nil
}
database/gorm/gorm.go (1)

Line range hint 108-112: Use dynamic log level in logger configuration

In the NewLogger initialization, the LogLevel is hardcoded to gormlogger.Info, which overrides the logLevel determined by the app.debug setting. This could lead to unintended logging levels in different environments. Please set LogLevel to use the dynamic logLevel variable to ensure consistent logging behavior.

Apply this diff to fix the issue:

 logger := NewLogger(log.New(os.Stdout, "\r\n", log.LstdFlags), gormlogger.Config{
 	SlowThreshold:             200 * time.Millisecond,
-	LogLevel:                  gormlogger.Info,
+	LogLevel:                  logLevel,
 	IgnoreRecordNotFoundError: true,
 	Colorful:                  true,
 })
database/db/configs_test.go (1)

118-232: Enhance test coverage with additional edge cases

The TestFillDefault() function covers several scenarios, but there may be other edge cases worth testing. Consider adding tests for:

  • Configurations with missing optional fields to ensure defaults are correctly applied.
  • Configurations with invalid values to verify error handling.
  • Multiple configurations with mixed validity to confirm that each is processed appropriately.

Adding these tests will improve the robustness of the fillDefault() method and ensure it behaves correctly under various conditions.

database/gorm/query.go (3)

35-41: Inconsistent variable naming: 'queryImpl' vs. 'Query'

In the NewQuery function, the variable is named queryImpl, but the struct is now named Query. For consistency and clarity, consider renaming the variable to query.

Apply this diff to rename the variable:

 func NewQuery(ctx context.Context, config config.Config, connection string, db *gormio.DB, conditions *Conditions) *Query {
-    queryImpl := &Query{
+    query := &Query{
         config:     config,
         connection: connection,
         ctx:        ctx,
         instance:   db,
         queries:    make(map[string]*Query),
     }

     if conditions != nil {
-        queryImpl.conditions = *conditions
+        query.conditions = *conditions
     }

-    return queryImpl
+    return query
 }

Line range hint 108-136: Possible data race on 'err' variable within goroutine in 'Cursor' method

In the Cursor method, the err variable is shared between the main function and the goroutine without proper synchronization, which can lead to data races.

To avoid data races, consider using a channel to pass errors from the goroutine back to the main function, or handle the error within the goroutine appropriately.

For example:

 func (r *Query) Cursor() (chan contractsorm.Cursor, error) {
     with := r.conditions.with
     query := r.buildConditions()
     r.conditions.with = with

-    var err error
+    errChan := make(chan error, 1)
     cursorChan := make(chan contractsorm.Cursor)
     go func() {
         var rows *sql.Rows
-        rows, err = query.instance.Rows()
+        rows, err := query.instance.Rows()
         if err != nil {
+            errChan <- err
             close(cursorChan)
             return
         }
         defer rows.Close()

         for rows.Next() {
             val := make(map[string]any)
             err = query.instance.ScanRows(rows, val)
             if err != nil {
+                errChan <- err
                 close(cursorChan)
                 return
             }
             cursorChan <- &CursorImpl{query: r, row: val}
         }
         close(cursorChan)
     }()
-    return cursorChan, err
+    select {
+    case err := <-errChan:
+        return nil, err
+    default:
+        return cursorChan, nil
+    }
 }

Line range hint 1309-1329: Redefinition of 'err' variable may shadow previous declaration

In the refreshConnection method, the variable err is redeclared inside the if !ok block at line 1317. This shadows the outer err variable and may lead to unexpected behavior.

Remove the redundant var err error declaration inside the block to avoid shadowing:

     query, ok := r.queries[connection]
     if !ok {
-        var err error
         query, err = BuildQuery(r.ctx, r.config, connection)
         if err != nil {
             return nil, err
         }

         if r.queries == nil {
             r.queries = make(map[string]*Query)
         }
         r.queries[connection] = query
     }
database/gorm/test_utils.go (2)

Line range hint 223-244: Confirm getMockDriver usage and error handling

The getMockDriver function is now unexported. Ensure that this function is not required outside of this package. Additionally, consider handling errors without using panic, which can be disruptive.

To improve error handling, you might return the error and handle it at a higher level:

-func NewTestQuery(docker testing.DatabaseDriver, withPrefixAndSingular ...bool) *TestQuery {
+func NewTestQuery(docker testing.DatabaseDriver, withPrefixAndSingular ...bool) (*TestQuery, error) {

...

-    panic(fmt.Sprintf("connect to %s failed: %v", docker.Driver().String(), err))
+    return nil, fmt.Errorf("connect to %s failed: %w", docker.Driver().String(), err)

Line range hint 592-625: Verify SQL table creation for different drivers

In the peoples table creation functions, ensure that the SQL statements are compatible with the respective databases after changing to contractsdatabase.Driver. Check for any syntax discrepancies.

Consider parameterizing common SQL components to reduce duplication and potential errors across different driver implementations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cd17022 and 3a99442.

⛔ Files ignored due to path filters (9)
  • go.sum is excluded by !**/*.sum
  • mocks/database/Configs.go is excluded by !mocks/**
  • mocks/database/gorm/Gorm.go is excluded by !mocks/**
  • mocks/database/gorm/Initialize.go is excluded by !mocks/**
  • mocks/database/orm/Orm.go is excluded by !mocks/**
  • mocks/database/orm/Query.go is excluded by !mocks/**
  • mocks/foundation/Application.go is excluded by !mocks/**
  • mocks/testing/Database.go is excluded by !mocks/**
  • mocks/testing/DatabaseDriver.go is excluded by !mocks/**
📒 Files selected for processing (53)
  • contracts/database/config.go (1 hunks)
  • contracts/database/gorm/wire_interface.go (0 hunks)
  • contracts/database/orm/constants.go (0 hunks)
  • contracts/database/orm/orm.go (3 hunks)
  • contracts/foundation/application.go (1 hunks)
  • contracts/testing/testing.go (2 hunks)
  • database/console/migrate.go (5 hunks)
  • database/console/migrate_creator.go (2 hunks)
  • database/console/test_utils.go (1 hunks)
  • database/db/config.go (0 hunks)
  • database/db/config_test.go (0 hunks)
  • database/db/configs.go (1 hunks)
  • database/db/configs_test.go (1 hunks)
  • database/db/dsn.go (1 hunks)
  • database/db/dsn_test.go (2 hunks)
  • database/gorm/cursor.go (1 hunks)
  • database/gorm/dialector.go (1 hunks)
  • database/gorm/dialector_test.go (1 hunks)
  • database/gorm/event.go (2 hunks)
  • database/gorm/event_test.go (5 hunks)
  • database/gorm/gorm.go (5 hunks)
  • database/gorm/query.go (61 hunks)
  • database/gorm/query_test.go (11 hunks)
  • database/gorm/test_utils.go (67 hunks)
  • database/gorm/to_sql.go (1 hunks)
  • database/gorm/to_sql_test.go (2 hunks)
  • database/gorm/wire.go (0 hunks)
  • database/gorm/wire_gen.go (0 hunks)
  • database/migration/blueprint_test.go (3 hunks)
  • database/migration/schema.go (2 hunks)
  • database/migration/schema_test.go (5 hunks)
  • database/migration/sql_driver.go (2 hunks)
  • database/orm.go (5 hunks)
  • database/orm_test.go (3 hunks)
  • database/service_provider.go (2 hunks)
  • database/wire.go (0 hunks)
  • database/wire_gen.go (0 hunks)
  • database/wire_interface.go (0 hunks)
  • foundation/application_test.go (10 hunks)
  • foundation/container.go (1 hunks)
  • foundation/container_test.go (1 hunks)
  • go.mod (0 hunks)
  • support/docker/mysql.go (2 hunks)
  • support/docker/mysql_test.go (2 hunks)
  • support/docker/postgres.go (2 hunks)
  • support/docker/postgres_test.go (2 hunks)
  • support/docker/sqlite.go (2 hunks)
  • support/docker/sqlite_test.go (2 hunks)
  • support/docker/sqlserver.go (2 hunks)
  • support/docker/sqlserver_test.go (3 hunks)
  • testing/docker/database.go (3 hunks)
  • testing/docker/database_test.go (10 hunks)
  • testing/docker/docker_test.go (3 hunks)
💤 Files with no reviewable changes (10)
  • contracts/database/gorm/wire_interface.go
  • contracts/database/orm/constants.go
  • database/db/config.go
  • database/db/config_test.go
  • database/gorm/wire.go
  • database/gorm/wire_gen.go
  • database/wire.go
  • database/wire_gen.go
  • database/wire_interface.go
  • go.mod
🔇 Additional comments (125)
contracts/testing/testing.go (2)

34-34: LGTM. Verify interface implementations.

The change from Driver() orm.Driver to Driver() database.Driver is consistent with the import statement modification and aligns with the move towards a more general database abstraction.

To ensure all implementations of the DatabaseDriver interface are updated accordingly, please run the following script:

#!/bin/bash
# Description: Check for implementations of the DatabaseDriver interface

# Test: Search for struct types that implement DatabaseDriver. Expect: All implementations use database.Driver
ast-grep --lang go --pattern 'type $_ struct {
  $$$
}

func ($_ $_) Driver() $ret {
  $$$
}'

# Test: Search for any remaining references to orm.Driver. Expect: No results or only in comments
rg --type go "orm\.Driver"

Please review the results to ensure all implementations have been updated to use database.Driver.


Line range hint 1-58: LGTM. Ensure comprehensive testing.

The changes in this file successfully generalize the database interactions by moving from a specific ORM package to a more general database package. This aligns well with the PR objective of removing the "wire" component.

Given the potentially far-reaching effects of these changes, please ensure:

  1. All implementations of the DatabaseDriver interface have been updated.
  2. Any code that previously relied on specific ORM functionality has been appropriately refactored.
  3. Comprehensive tests have been added or updated to cover these changes.

Run the following script to check for any remaining references to the old ORM package:

#!/bin/bash
# Description: Check for any remaining references to the old ORM package

# Test: Search for any remaining imports of the old ORM package. Expect: No results
rg --type go 'import \((?s:.)*"github.com/goravel/framework/contracts/database/orm"(?s:.)*\)'

# Test: Search for any uses of orm package. Expect: No results or only in comments
rg --type go '\borm\.'

Review the results to ensure the refactoring is complete across the codebase.

support/docker/sqlite.go (3)

Line range hint 1-70: Clarify the relationship between these changes and removing "wire".

The changes in this file, particularly the shift from "orm" to "database", appear to be part of a larger refactoring effort. However, it's not immediately clear how these changes relate to the PR objective of removing "wire".

Could you please clarify:

  1. How do these changes in the SQLite implementation contribute to removing "wire"?
  2. Are there other files in this PR that more directly address the removal of "wire"?

To help understand the scope of the changes, let's check for "wire"-related code:

#!/bin/bash
# Description: Search for "wire"-related code and imports

# Search for "wire" imports
echo "Checking for 'wire' imports:"
rg --type go 'import \(.*"github\.com/google/wire".*\)'

# Search for "wire" function calls or annotations
echo "Checking for 'wire' function calls or annotations:"
rg --type go '(wire\.Build|\/\/\+build wireinject|\/\/go:build wireinject)'

9-9: LGTM. Verify import consistency across the codebase.

The change from orm to database import looks good and aligns with the method signature update. This suggests a refactoring of the package structure to a more general database approach.

To ensure consistency, let's verify that this import change has been applied across the codebase:


39-40: LGTM. Verify impact on dependent code.

The changes to the Driver() method signature and return value are consistent with the import path change. The functionality remains the same, with only type updates.

To ensure that this change doesn't break any dependent code, let's verify its usage across the codebase:

✅ Verification successful

Let's correct the verification scripts to properly check for usages of SqliteImpl.Driver() and ensure there are no remaining references to orm.Driver.


Let's proceed by running corrected verification scripts to ensure proper detection of SqliteImpl.Driver() usages and orm.Driver references.


Verification Successful

No usages of SqliteImpl.Driver() or orm.Driver were found in the codebase. The changes are consistent and do not affect dependent code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usages of the SqliteImpl.Driver() method

# Search for usages of SqliteImpl.Driver()
echo "Checking for SqliteImpl.Driver() usages:"
rg --type go 'SqliteImpl.*\.Driver\(\)'

# Search for any remaining type assertions or conversions involving orm.Driver
echo "Checking for remaining orm.Driver type assertions or conversions:"
rg --type go 'orm\.Driver'

Length of output: 561


Script:

#!/bin/bash
# Description: Check for usages of SqliteImpl.Driver() method and orm.Driver references

# Check for usages of SqliteImpl.Driver()
echo "Checking for SqliteImpl.Driver() usages:"
rg --type go 'SqliteImpl\..*Driver\(\)'

# Check for any remaining orm.Driver type assertions or conversions
echo "Checking for remaining orm.Driver type assertions or conversions:"
rg --type go 'orm\.Driver'

Length of output: 302


Script:

#!/bin/bash
# Description: Check for usages of SqliteImpl.Driver() method and orm.Driver references

# Check for usages of SqliteImpl.Driver()
echo "Checking for SqliteImpl.Driver() usages:"
rg --type go 'SqliteImpl\..*Driver\(\)'

# Check for any remaining orm\.Driver type assertions or conversions
echo "Checking for remaining orm.Driver type assertions or conversions:"
rg --type go 'orm\.Driver'

Length of output: 302

support/docker/sqlite_test.go (3)

8-8: LGTM: Import change aligns with PR objective

The change from importing an ORM package to the contracts/database package aligns with the PR objective of removing the "wire" component. This modification suggests a shift towards a more decoupled and flexible database interface.


74-74: LGTM: Driver constant update is consistent

The change from orm.DriverSqlite to database.DriverSqlite is consistent with the earlier import statement modification. This update maintains the test's functionality while adapting to the new package structure, further supporting the removal of the "wire" component.


Line range hint 1-85: Overall changes align with PR objective

The modifications in this file, including the import statement change and the driver constant update, are consistent with the PR objective of removing the "wire" component. These changes appear to be part of a larger refactoring effort to transition from an ORM-specific implementation to a more generic database interface.

The test functionality remains intact, which is crucial for maintaining the integrity of the codebase during this transition. However, it's important to ensure that similar changes have been applied consistently across the entire codebase.

To verify the consistency of these changes across the codebase, please run the following script:

✅ Verification successful

Verification Successful: No Remaining References to Old ORM Package

The executed scripts confirm that all references to the old ORM package and orm.DriverSqlite have been successfully removed. Additionally, the usage of database.DriverSqlite is consistent across the codebase, aligning with the PR objective of removing the "wire" component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old ORM package and inconsistent usage of database drivers.

# Test 1: Search for any remaining imports of the old ORM package
echo "Checking for remaining imports of the old ORM package:"
rg --type go 'import.*"github\.com/goravel/framework/database/orm"'

# Test 2: Search for any remaining uses of orm.DriverSqlite
echo "Checking for remaining uses of orm.DriverSqlite:"
rg --type go 'orm\.DriverSqlite'

# Test 3: Verify consistent usage of the new database.DriverSqlite
echo "Verifying consistent usage of database.DriverSqlite:"
rg --type go 'database\.DriverSqlite'

Length of output: 3802

support/docker/sqlserver_test.go (3)

16-16: LGTM! Consistent type update.

The change in the type of mockConfig from *configmocks.Config to *mocksconfig.Config is consistent with the import alias change. This update maintains the integrity of the test suite structure.


Line range hint 1-89: Summary: Changes look good and align with PR objectives.

The modifications in this file are consistent with the PR's goal of removing the "wire" component. The changes primarily involve updating import paths and their corresponding usage, reflecting a restructuring of the framework's database package. No functional changes were introduced, and the integrity of the test suite has been maintained.

Key points:

  1. Import paths have been updated to reflect the new package structure.
  2. The mock configuration import has been renamed for consistency.
  3. Type declarations and method calls have been updated to match the new import structure.

These changes contribute to streamlining the codebase without altering its core functionality. The PR objectives have been met for this file.


79-79: LGTM! Verify similar changes across the codebase.

The update from orm.DriverSqlserver to database.DriverSqlserver is consistent with the import path changes. The test's functionality remains unchanged.

To ensure similar changes have been applied consistently across the codebase, run the following script:

✅ Verification successful

Verification Successful!

All instances of orm.DriverSqlserver have been removed, and database.DriverSqlserver is consistently used across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new database driver reference across the codebase

# Test 1: Check for any remaining uses of the old driver reference
echo "Checking for old driver reference usage:"
rg --type go "orm\.DriverSqlserver"

# Test 2: Verify the usage of the new driver reference
echo "Checking new driver reference usage:"
rg --type go "database\.DriverSqlserver"

Length of output: 2671

support/docker/postgres_test.go (3)

78-78: LGTM. Consistent with import change.

The update from orm.DriverPostgres to database.DriverPostgres is consistent with the earlier import change. This modification correctly adapts the test to use the more general database contract while maintaining the original test functionality.


Line range hint 1-90: Overall changes look good. Consider broader impact.

The changes in this file are consistent and well-executed, shifting from ORM-specific to more general database contracts. This aligns with the PR objective of removing the "wire" component.

However, given the nature of these changes:

  1. Ensure that all references to orm.DriverPostgres have been updated throughout the codebase.
  2. Verify that any code depending on ORM-specific functionality has been appropriately refactored.
  3. Consider updating documentation to reflect these architectural changes.

To assist in this broader review, you can run the following script:

#!/bin/bash
# Description: Perform a broader check for potential impacts of the ORM to database contract change

# Test 1: Check for any remaining references to orm.Driver
echo "Checking for remaining references to orm.Driver:"
rg --type go "orm\.Driver"

# Test 2: Look for potential ORM-specific method calls that might need refactoring
echo "Checking for potential ORM-specific method calls:"
rg --type go "\b(Create|Update|Delete|Where|Order|Limit|Offset)\b"

# Test 3: Check for files that might need documentation updates
echo "Files that might need documentation updates:"
rg --type go --files-with-matches "database/orm"

This script will help identify areas that might need attention due to the architectural changes.


8-8: LGTM. Verify impact on codebase.

The change from contracts/database/orm to contracts/database aligns with the PR objective of removing the "wire" component. This shift to a more general database package is a good practice for flexibility.

To ensure this change doesn't introduce issues elsewhere in the codebase, please run the following script:

support/docker/mysql_test.go (2)

76-76: LGTM. Verify constant usage across the codebase.

The change from orm.DriverMysql to database.DriverMysql is consistent with the import path change and the PR objective. The functionality remains the same, only the package reference has been updated.

To ensure all occurrences of this constant have been updated, please run the following script:

#!/bin/bash
# Description: Check for any remaining occurrences of the old constant reference

# Test: Search for the old constant reference. Expect: No results.
rg --type go "orm\.DriverMysql"

# Test: Search for the new constant reference. Expect: At least one result (this file).
rg --type go "database\.DriverMysql"

Line range hint 1-86: Overall changes look good. Verify consistency across the codebase.

The changes in this file are minimal and don't affect the overall functionality of the tests. The import path and driver constant updates are consistent with the PR objective of removing the "wire" component.

To ensure these changes are applied consistently across the entire codebase:

  1. Verify that all imports of github.com/goravel/framework/contracts/database/orm have been updated to github.com/goravel/framework/contracts/database.
  2. Check that all references to orm.DriverMysql have been changed to database.DriverMysql.
  3. Run the test suite to confirm that these changes haven't introduced any regressions.

Please run the following script to perform a broader check across the codebase:

#!/bin/bash
# Description: Perform a broader check for consistency across the codebase

# Test 1: Check for any remaining old import paths
echo "Checking for old import paths:"
rg --type go "github.com/goravel/framework/contracts/database/orm"

# Test 2: Check for any remaining old constant references
echo "Checking for old constant references:"
rg --type go "orm\.DriverMysql"

# Test 3: Verify the presence of new import paths
echo "Verifying new import paths:"
rg --type go "github.com/goravel/framework/contracts/database"

# Test 4: Verify the presence of new constant references
echo "Verifying new constant references:"
rg --type go "database\.DriverMysql"

If any unexpected results are found, please review and update the affected files accordingly.

testing/docker/database.go (5)

8-8: LGTM: Import addition is consistent with code changes.

The new import for contractsorm is appropriate for the subsequent changes in the file, particularly the addition of the orm field in the Database struct.


45-49: LGTM: Function update consistent with struct changes.

The initialization of the orm field in the NewDatabase function is consistent with the changes made to the Database struct. This update properly integrates the new ORM-based approach, replacing the previous app-based initialization.


65-65: LGTM: Seed method updated consistently.

The Seed method has been updated consistently with the Build method. The receiver name change improves readability, and the use of r.artisan.Call(command) aligns with the new implementation approach, likely contributing to the removal of the "wire" component.

Also applies to: 74-74


Line range hint 1-74: Overall assessment: Changes are well-implemented and align with PR objectives.

The modifications in this file consistently implement a new ORM-based approach, likely contributing to the removal of the "wire" component as stated in the PR objectives. The refactoring improves the code structure and maintainability. All changes are logically sound and well-integrated into the existing codebase.

A few key points:

  1. The new orm field and its initialization are properly implemented.
  2. Method signatures and implementations have been updated consistently.
  3. The Build and Seed methods now use direct ORM and Artisan calls, replacing the previous approach.

These changes appear to successfully contribute to the removal of the "wire" component while maintaining the functionality of the Database struct and its methods.


20-20: LGTM: Struct change aligns with refactoring goals.

The addition of the orm field to the Database struct is consistent with the refactoring to use ORM directly. This change appears to be part of the effort to remove the "wire" component as mentioned in the PR objectives.

To ensure the complete removal of the "wire" component, please run the following script:

✅ Verification successful

Verification Successful: "wire" component has been fully removed.

All checks confirm that there are no remaining imports, usages, or related files for the "wire" component in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the removal of "wire" component from the codebase

# Test 1: Check for any remaining imports of "wire"
echo "Checking for 'wire' imports:"
rg --type go 'import.*".*wire.*"'

# Test 2: Check for any remaining uses of "wire" in the code
echo "Checking for 'wire' usage in code:"
rg --type go '\bwire\b' --iglob '!*_test.go'

# Test 3: Check for any "wire" related files
echo "Checking for 'wire' related files:"
fd -e go wire

Length of output: 1045

database/db/dsn_test.go (4)

7-9: LGTM: Import statements updated appropriately.

The import statements have been updated to reflect the new test structure. The addition of the assert package and the direct import of the database package are appropriate for the refactored tests.


20-27: LGTM: testConfig type updated correctly.

The testConfig variable type has been updated from databasecontract.Config to database.Config, which is consistent with the new import statement and aligns with the PR objective of removing the "wire" component.


82-87: LGTM: Well-structured test execution with subtests.

The test execution is well-organized using a loop and subtests. This approach provides clear separation between test cases and allows for detailed reporting of test results. The use of assert.Equal for comparing the generated DSN with the expected value is appropriate and easy to understand.


Line range hint 1-87: Overall: Excellent refactoring of the test structure.

The changes in this file significantly improve the test structure by implementing table-driven tests. This new approach is more maintainable, easier to extend, and aligns well with the PR objective of removing the "wire" component. The test cases cover a comprehensive range of scenarios, and the execution is well-organized using subtests.

A few minor suggestions were made to further enhance the code:

  1. Adding a comment to explain the purpose of the test cases.
  2. Considering an additional test case for non-default configuration values.

These changes have positively impacted the overall quality of the test file. Great job on the refactoring!

database/service_provider.go (1)

56-56: Approve the receiver name change in registerCommands.

The change of the receiver name from database to r is consistent with the changes in other methods and aligns with Go naming conventions for short receiver names.

testing/docker/docker_test.go (4)

10-10: LGTM: Import statement for mocksorm added.

The addition of the mocksorm import is consistent with the changes made in the test cases and is necessary for creating mock ORM instances.


38-38: Excellent addition of mock ORM in MySQL test case.

The creation of a mock ORM instance and its integration into the test setup enhances the test coverage and follows good unit testing practices. This change allows for better isolation of the database functionality being tested.

Also applies to: 42-42


58-58: LGTM: Consistent addition of mock ORM in PostgreSQL test case.

The changes in the PostgreSQL test case mirror those made in the MySQL test case, maintaining consistency and parity between the two database types. This ensures that both database connections are tested with the same level of mocking and isolation.

Also applies to: 62-62


Line range hint 1-70: Overall improvement in test coverage and consistency.

The changes in this file focus on enhancing the test cases for both MySQL and PostgreSQL database connections by introducing mock ORM functionality. This improvement:

  1. Increases test isolation by mocking the ORM layer.
  2. Maintains consistency between different database type tests.
  3. Aligns with the PR objective of removing "wire" by refactoring the testing approach.

These modifications improve the overall quality and reliability of the tests without changing their fundamental structure or purpose.

database/migration/schema.go (2)

Line range hint 1-90: Please clarify the relationship between these changes and the PR objective.

The changes in this file involve updating import statements and database driver constant references. However, the PR objective mentions removing the "wire" component, which is not directly addressed in these changes. Could you please provide more context on how these modifications relate to the removal of the "wire" component?

To better understand the context, let's check for any mentions of "wire" in the codebase:


7-7: LGTM! Verify usage of contractsorm.

The addition of the contractsdatabase import aligns with the changes in the getGrammar function. However, since the contractsorm import is retained, it's worth verifying its usage in the rest of the file.

Let's verify the usage of contractsorm in the file:

✅ Verification successful

Verified: The contractsorm import and its usage are appropriate and consistent with the removal of the "wire" component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of contractsorm in the file

# Test: Search for contractsorm usage in the file
rg --type go 'contractsorm' database/migration/schema.go

Length of output: 1509


Script:

#!/bin/bash
# Description: Check usage of contractsorm in the file

# Test: Search for contractsorm usage in the file
rg --type go 'contractsorm' database/migration/schema.go

Length of output: 285

database/gorm/to_sql.go (3)

12-12: Verify usage of NewToSql function across the codebase.

The parameter type in the NewToSql function has been changed from *QueryImpl to *Query. This change is consistent with the modification in the ToSql struct. However, we need to ensure that all callers of NewToSql are updated to pass a *Query instead of a *QueryImpl.

To verify the correct usage of NewToSql, run the following script:

This will help us identify all places where NewToSql is called and confirm that they are passing a *Query type argument.


Line range hint 1-124: LGTM! Suggest thorough testing of affected functionality.

The changes from *QueryImpl to *Query appear to be part of a larger refactoring effort. The rest of the file remains unchanged, which suggests that the Query type likely provides the same interface as QueryImpl. However, to ensure the integrity of the codebase:

  1. Verify that all method calls on query are still valid with the new *Query type.
  2. Conduct thorough testing of all functionalities that involve the ToSql struct and its methods.
  3. Update any relevant documentation or comments that might reference QueryImpl.

To assist in verifying the compatibility, run the following script:

This will help identify all method calls on the query field, allowing you to verify that they are all supported by the new *Query type.


8-8: Verify compatibility of *Query type with existing methods.

The type of the query field has been changed from *QueryImpl to *Query. This change suggests a refactoring of the query implementation. Please ensure that all methods using the query field are compatible with the new *Query type.

To verify the compatibility, run the following script:

This will help us confirm that the new *Query type provides all the necessary methods and fields used throughout the file.

support/docker/postgres.go (2)

73-74: LGTM. Verify impact on dependent code.

The Driver() method has been updated to return database.Driver instead of orm.Driver, which is consistent with the import statement change. The return value has also been updated accordingly.

Let's verify if this change impacts any other parts of the codebase:

#!/bin/bash
# Description: Check for any code that might be affected by the Driver() method change

# Test 1: Search for any code that uses the Driver() method of PostgresImpl
echo "Checking for usage of PostgresImpl.Driver():"
rg --type go 'PostgresImpl.*Driver\(\)'

# Test 2: Search for any code that expects orm.Driver
echo "Checking for code expecting orm.Driver:"
rg --type go 'orm\.Driver'

10-10: LGTM. Verify package usage consistency.

The import statement has been updated to use the more general database package instead of the specific orm package. This change aligns with the PR objective of removing the "wire" component.

Let's verify if this change is consistent across the codebase:

database/console/test_utils.go (3)

8-8: Function signature update looks good.

The change from contractsorm.Driver to database.Driver is consistent with the import statement modification and maintains the function's purpose while adapting to the new package structure.


4-4: Approve import change and verify its impact.

The change from "contractsorm" to "database" aligns with the PR objective of removing the "wire" component. This modification suggests a shift towards a more general database package.

To ensure this change doesn't introduce unintended consequences, please run the following script to check for any remaining usage of "contractsorm" in the codebase:


10-16: Switch-case updates are consistent and complete.

The case statements have been correctly updated to use database.Driver* instead of contractsorm.Driver*, maintaining consistency with the import and function signature changes. All database driver types are still covered.

To ensure these changes haven't affected the functionality, please verify that the existing tests still pass and consider adding new tests if necessary. Run the following command to check the test coverage for this file:

database/migration/sql_driver.go (1)

56-69: LGTM. Verify constant definitions in the new package.

The switch statement update correctly reflects the change from orm to database package. The logic for handling different database drivers remains intact, which is good.

Let's verify the constant definitions in the new package:

#!/bin/bash
# Description: Verify the constant definitions in the new database package

# Test: Check the constant definitions in the database package
echo "Checking constant definitions in the database package"
ast-grep --lang go --pattern $'const (
  $$$
  DriverPostgres $_
  DriverSqlite $_
  DriverSqlserver $_
  $$$
)' | rg 'github\.com/goravel/framework/contracts/database'

This will help ensure that the constants used in the switch statement are properly defined in the new package.

database/console/migrate_creator.go (1)

9-9: Approve import change and verify its impact.

The change from orm to database import is consistent with the PR objective. This refactoring to a more general database package is a good practice.

To ensure this change doesn't introduce issues elsewhere in the codebase, please run the following script:

database/migration/schema_test.go (4)

9-9: LGTM: Import statement updated correctly.

The addition of the contractsdatabase import is consistent with the changes in the driver type throughout the file. This aligns well with the PR objective of updating related components.


42-43: LGTM: SetupSuite method updated correctly.

The change from contractsorm.Driver to contractsdatabase.Driver in the map initialization is consistent with the struct definition update. The rest of the method remains unchanged, which is correct as the underlying logic doesn't need modification.


90-90: LGTM: initTest function signature updated correctly.

The change from contractsorm.Driver to contractsdatabase.Driver in the function signature is consistent with the overall update of the driver type in the file. The rest of the function remains unchanged, which is correct as the underlying logic doesn't need modification.


Line range hint 1-103: Overall, the changes look good with room for minor improvements.

The updates in this file consistently replace contractsorm.Driver with contractsdatabase.Driver, aligning with the PR objective of removing "wire" and updating related components. This change improves the consistency of the codebase by using more general database contracts.

To further enhance the code:

  1. Consider renaming driverToTestDB to driverToTestDatabase for improved clarity.
  2. Improve test coverage in the TestConnection method by parameterizing the connection string to test multiple database drivers.

Once these suggestions are addressed, the changes will be ready for merging.

To ensure all instances of contractsorm.Driver have been replaced, run the following script:

✅ Verification successful

All instances of contractsorm.Driver have been successfully replaced.

The executed verification script found no remaining instances of contractsorm.Driver in database/migration/schema_test.go, confirming that the replacement was completed as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all instances of contractsorm.Driver have been replaced

# Test: Search for any remaining instances of contractsorm.Driver
remaining_instances=$(rg --type go 'contractsorm\.Driver' database/migration/schema_test.go)

if [ -z "$remaining_instances" ]; then
    echo "All instances of contractsorm.Driver have been replaced successfully."
else
    echo "Found remaining instances of contractsorm.Driver:"
    echo "$remaining_instances"
fi

Length of output: 260

support/docker/mysql.go (2)

10-10: Approve import statement change and verify its impact.

The change in the import statement from github.com/goravel/framework/contracts/database/orm to github.com/goravel/framework/contracts/database aligns with the PR objective of removing the "wire" component. This modification suggests a restructuring of database-related packages in the framework.

To ensure this change is consistent across the codebase, please run the following script:

#!/bin/bash
# Description: Verify the usage of the new database import path and identify any remaining references to the old path.

# Test 1: Check for usage of the new import path
echo "Checking for usage of new import path:"
rg --type go "github.com/goravel/framework/contracts/database"

# Test 2: Check for any remaining references to the old import path
echo "Checking for remaining references to old import path:"
rg --type go "github.com/goravel/framework/contracts/database/orm"

# The results of these tests will help identify if the change has been consistently applied across the codebase.

78-79: Approve Driver method changes and verify usage.

The changes to the Driver method signature and return value are consistent with the import statement modification and align with the PR objective. The shift from orm.Driver to database.Driver suggests a move towards a more abstract database interface, which could provide greater flexibility in database implementations.

To ensure this change doesn't break existing code and is consistently applied, please run the following script:

✅ Verification successful

Driver method changes have been successfully verified.

The Driver method now returns database.Driver, and its usage is consistent throughout the codebase. Remaining orm.Driver references are limited to mock and testing files, ensuring that the main functionality remains unaffected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the Driver method and identify any remaining references to the old return type.

# Test 1: Check for usage of the new Driver method return type
echo "Checking for usage of new Driver method return type:"
rg --type go "database\.Driver"

# Test 2: Check for any remaining references to the old Driver method return type
echo "Checking for remaining references to old Driver method return type:"
rg --type go "orm\.Driver"

# Test 3: Check for any calls to the Driver method to ensure they're compatible with the new return type
echo "Checking for calls to the Driver method:"
rg --type go "\.Driver\(\)"

# The results of these tests will help identify if the change has been consistently applied and if any code needs to be updated to work with the new return type.

Length of output: 17837

foundation/container_test.go (2)

103-105: Good addition of Refresh test

The addition of this test case for the Refresh functionality is valuable. It ensures that when a singleton is refreshed, it's properly removed from the instances map. This helps maintain the integrity of the container's state management.


100-113: Improvements to TestSingleton, but unclear relation to PR objectives

The changes to the TestSingleton method improve the test coverage and robustness of the Container implementation, particularly around the Refresh functionality. This is a positive change that enhances the quality of the tests.

However, it's worth noting that these changes don't seem directly related to the stated PR objective of removing the "wire" component.

To ensure we're not missing any context, let's check for any mentions of "wire" in the codebase:

This will help us understand if there are any other changes related to removing the "wire" component that we should be aware of in the context of these test modifications.

✅ Verification successful

Verified: "wire" Removal Not Addressed in Changes

The search results indicate that "wire" is only present in the generated protobuf file grpc/test.pb.go, which pertains to protobuf parsing and is unrelated to the "wire" component targeted for removal in this PR. Therefore, the changes to the TestSingleton method enhance test coverage but do not address the removal of the "wire" dependency.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for "wire" mentions in the codebase
rg --type go "wire"

Length of output: 1496

support/docker/sqlserver.go (2)

72-73: LGTM. Method signature correctly updated.

The Driver method signature has been properly updated to return database.Driver instead of orm.Driver, which is consistent with the import changes and the PR objective.


10-10: LGTM. Verify consistent usage across the codebase.

The import statement has been correctly updated from orm to database, which aligns with the PR objective of removing the "wire" component.

To ensure consistency, let's verify if this change has been applied throughout the codebase:

database/gorm/cursor.go (1)

16-16: LGTM. Verify Query type compatibility.

The change from *QueryImpl to *Query looks good and aligns with the PR objective of removing the "wire" component. This refactoring likely simplifies or generalizes the query interface.

To ensure this change doesn't introduce any compatibility issues, please run the following verification:

These checks will help confirm that the Query type is properly defined and implements all necessary methods, and that there are no lingering references to QueryImpl in the codebase.

contracts/foundation/application.go (1)

126-127: Approve the new Refresh method with suggestions.

The addition of the Refresh method to the Application interface is a good enhancement to allow refreshing instances. However, there are a couple of points to consider:

  1. It would be beneficial to add documentation for this method to clarify its purpose and usage.
  2. This change might require updates to existing implementations of the Application interface.

Consider adding a comment to document the Refresh method, for example:

// Refresh refreshes an instance associated with the given key.
// It updates or recreates the instance in the application's container.
Refresh(key any)

To ensure all implementations of the Application interface are updated, run the following script:

This script will help identify potential implementations of the Application interface that might need updating to include the new Refresh method.

database/gorm/to_sql_test.go (16)

36-36: LGTM: Type assertion update in TestCount

The change from *QueryImpl to *Query is consistent with the refactoring effort. The test functionality remains intact.


39-39: LGTM: Consistent type assertion update in TestCount

The change from *QueryImpl to *Query is consistent with the previous update in this method. The test functionality remains unchanged.


45-45: LGTM: Type assertion update in TestCreate

The change from *QueryImpl to *Query is consistent with the ongoing refactoring. The test functionality remains intact.


48-48: LGTM: Consistent type assertion update in TestCreate

The change from *QueryImpl to *Query is consistent with the previous updates. The test functionality remains unchanged.


58-58: LGTM: Type assertion update in TestDelete

The change from *QueryImpl to *Query is consistent with the ongoing refactoring. The test functionality remains intact.


61-61: LGTM: Consistent type assertion update in TestDelete

The change from *QueryImpl to *Query is consistent with the previous updates. The test functionality remains unchanged.


64-64: LGTM: Consistent type assertion update in TestDelete

The change from *QueryImpl to *Query is consistent with the previous updates in this method and others. The test functionality remains intact.


69-69: LGTM: Consistent type assertion update in TestDelete

The change from *QueryImpl to *Query is consistent with the previous updates in this method and others. The test functionality remains unchanged.


74-74: LGTM: Consistent type assertion updates in TestFind

The changes from *QueryImpl to *Query in all instances within the TestFind method are consistent with the ongoing refactoring. The test functionalities remain intact.

Also applies to: 77-77, 80-80, 83-83


88-88: LGTM: Consistent type assertion updates in TestFirst

The changes from *QueryImpl to *Query in both instances within the TestFirst method are consistent with the ongoing refactoring. The test functionalities remain unchanged.

Also applies to: 91-91


96-96: LGTM: Consistent type assertion updates in TestForceDelete

The changes from *QueryImpl to *Query in all instances within the TestForceDelete method are consistent with the ongoing refactoring. The test functionalities remain intact.

Also applies to: 99-99, 102-102, 105-105


110-110: LGTM: Consistent type assertion updates in TestGet

The changes from *QueryImpl to *Query in both instances within the TestGet method are consistent with the ongoing refactoring. The test functionalities remain unchanged.

Also applies to: 113-113


118-118: LGTM: Consistent type assertion updates in TestPluck

The changes from *QueryImpl to *Query in both instances within the TestPluck method are consistent with the ongoing refactoring. The test functionalities remain intact.

Also applies to: 121-121


126-126: LGTM: Consistent type assertion updates in TestSave

The changes from *QueryImpl to *Query in both instances within the TestSave method are consistent with the ongoing refactoring. The test functionalities remain unchanged.

Also applies to: 129-129


136-136: LGTM: Consistent type assertion updates in TestSum and TestUpdate

The changes from *QueryImpl to *Query in all instances within the TestSum and TestUpdate methods are consistent with the ongoing refactoring throughout the file. The test functionalities remain intact.

Also applies to: 139-139, 144-144, 147-147, 152-152, 155-155, 158-158, 163-163, 170-170, 175-175


Line range hint 1-180: Summary: Consistent refactoring of type assertions

This change consistently updates all type assertions from *QueryImpl to *Query throughout the file. This refactoring appears to be part of a larger effort to standardize the query type used in the GORM package. The changes are applied systematically across all test methods, maintaining the existing functionality of the tests.

Key points:

  1. All changes are consistent and follow the same pattern.
  2. No functional changes were made to the test cases.
  3. The SQL queries generated in the tests remain unchanged.

The refactoring improves code consistency and likely aligns with changes made in the main GORM package. Overall, this is a clean and well-executed refactoring.

database/gorm/event.go (3)

23-23: LGTM. Consistent with struct change.

The NewEvent function signature update is consistent with the Event struct modification. The function body correctly remains unchanged as it's only assigning the passed query to the struct field.


20-20: LGTM. Verify impact on codebase.

The change from *QueryImpl to *Query aligns with the PR objective to remove the "wire" component. This modification suggests a move towards a more generic or interface-based approach.

To ensure this change doesn't introduce any unintended consequences, please run the following script to check for any remaining references to QueryImpl in the codebase:

#!/bin/bash
# Description: Check for remaining references to QueryImpl

# Test: Search for QueryImpl references
rg --type go 'QueryImpl'

95-95: LGTM. Verify NewQuery functionality.

The Query method update is consistent with the previous modifications, moving away from the QueryImpl type. The method now creates a new query using NewQuery with the same parameters as before, maintaining the creation of a new database session.

To ensure the NewQuery function provides the same functionality as the previous NewQueryImpl, please run the following script to locate and review the NewQuery function:

✅ Verification successful

Change Verified: NewQuery appropriately replaces NewQueryImpl.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Locate and review the NewQuery function

# Test: Search for NewQuery function definition
ast-grep --lang go --pattern $'func NewQuery($_, $_, $_, $_, $_) *Query {
  $$$
}'

Length of output: 162


Script:

#!/bin/bash
# Description: Locate and review the NewQuery function

# Test: Search for NewQuery function definition using ast-grep
ast-grep --lang go --pattern $'func NewQuery($_, $_, $_, $_, $_) *Query {\n  $$$\n}' .

Length of output: 834


Script:

#!/bin/bash
# Description: Locate and review the NewQueryImpl function

# Test: Search for NewQueryImpl function definition using ast-grep
ast-grep --lang go --pattern $'func NewQueryImpl($_, $_, $_, $_, $_) *QueryImpl {\n  $$$\n}' .

Length of output: 93

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

Line range hint 1-214: Summary: Good improvements to the ORM interface

The changes in this file are well-aligned with the PR objective of removing the "wire" component. The additions and modifications to the ORM and Query interfaces provide useful enhancements without introducing new dependencies.

Key points:

  1. The new Refresh() method in the Orm interface allows for resetting the ORM instance state.
  2. The change in the Driver() method's return type in the Query interface provides a more specific type for the database driver.

These changes should improve the flexibility and clarity of the ORM system. Ensure that all existing implementations are updated to accommodate these changes, particularly the Driver() method return type.

foundation/container.go (1)

334-336: Please provide context on how this relates to removing "wire".

The PR objective mentions removing the "wire" component, but it's not immediately clear how the addition of the Refresh method relates to this goal. Could you provide more context on how this change fits into the larger refactoring effort?

To ensure this change is properly integrated, let's verify its usage across the codebase:

This will help us understand how the new method is being used and if any additional changes or documentation might be needed.

database/migration/blueprint_test.go (4)

9-9: LGTM: Import statement updated correctly.

The addition of the database package import aligns with the PR objective and helps consolidate database-related functionality.


25-26: LGTM: TestBlueprintTestSuite function updated correctly.

The initialization of the grammars map now uses database.DriverPostgres, which is consistent with the previous changes.

To ensure this change is applied consistently across the test files, please run the following command:

#!/bin/bash
# Search for any remaining instances of orm.DriverPostgres in test files
rg --type go 'orm\.DriverPostgres' '*_test.go'

20-20: LGTM: BlueprintTestSuite struct updated correctly.

The grammars field type has been properly updated to use database.Driver instead of orm.Driver, which is consistent with the import changes.

To ensure this change is applied consistently across the codebase, please run the following command:

✅ Verification successful

Verified: No remaining instances of orm.Driver found.

All references to orm.Driver have been successfully updated to database.Driver across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of orm.Driver
rg --type go 'orm\.Driver'

Length of output: 28


358-358: LGTM: TestToSql method updated correctly.

The driver check now uses database.DriverPostgres, which is consistent with the previous changes.

To ensure this change is applied consistently across all test methods, please run the following command:

database/gorm/event_test.go (5)

Line range hint 42-49: LGTM: Consistent renaming of QueryImpl to Query

The change from QueryImpl to Query is consistent with the refactoring mentioned in the summary. The structure and initialization remain the same, ensuring that the test setup is not affected by this change.


Line range hint 88-96: LGTM: Consistent use of Query type

The change from QueryImpl to Query is consistently applied here as well. The structure and initialization of the Query type remain unchanged, ensuring that the test behavior is preserved.


Line range hint 116-124: LGTM: Consistent renaming applied to query1

The change from QueryImpl to Query is consistently applied to query1. The structure and initialization remain unchanged, maintaining the integrity of the test setup.


Line range hint 1-370: Summary: Consistent renaming with preserved test integrity

The changes in this file are limited to renaming QueryImpl to Query, which has been consistently applied throughout the test suite. The structure of the tests, including the EventTestSuite and individual test cases, remains unchanged. This renaming aligns with the PR objective of removing the "wire" component.

Given that this is a renaming change, no new tests were added, which is acceptable. However, it's crucial to ensure that these changes don't introduce any regressions in the test coverage or functionality.

To confirm that the renaming hasn't introduced any unintended side effects, please run the following commands:

#!/bin/bash
# Check if there are any remaining instances of QueryImpl in the codebase
echo "Checking for any remaining QueryImpl instances:"
rg "QueryImpl" --type go

# Run all tests in the gorm package to ensure no regressions
echo "Running all tests in the gorm package:"
go test -v ./database/gorm/...

These commands will help verify that the renaming is complete and that all tests still pass after the changes.


Line range hint 245-253: LGTM: Consistent Query usage in TestValidColumn

The change from QueryImpl to Query is consistently applied in the TestValidColumn function. Both instances of Query initialization maintain the same structure and purpose as before, preserving the test logic for different Selects and Omits configurations.

To ensure that the test coverage remains comprehensive after these changes, let's verify the test execution:

Also applies to: 258-266

foundation/application_test.go (11)

15-15: LGTM: New import added for database contracts

The addition of the contractsdatabase import is consistent with the changes made to the database configuration later in the file.


175-177: LGTM: Consistent update of mock expectations

The changes from On() to EXPECT() in the TestMakeCache function are consistent with the previous updates and maintain the test's functionality.


202-202: LGTM: Consistent update of mock expectation

The change from On() to EXPECT() in the TestMakeCrypt function maintains consistency with the previous updates and preserves the test's functionality.


247-250: LGTM: Consistent update of mock expectations

The changes from On() to EXPECT() in the TestMakeHash function maintain consistency with the previous updates and preserve the test's functionality.


265-267: LGTM: Consistent update of mock expectations

The changes from On() to EXPECT() in the TestMakeLang function maintain consistency with the previous updates and preserve the test's functionality.


378-378: LGTM: Consistent update of mock expectation

The change from On() to EXPECT() in the TestMakeSchedule function maintains consistency with the previous updates and preserves the test's functionality.


399-401: LGTM: Consistent update of mock expectations

The changes from On() to EXPECT() in the TestMakeSession function maintain consistency with the previous updates and preserve the test's functionality.


420-423: LGTM: Consistent update of mock expectations

The changes from On() to EXPECT() in the TestMakeStorage function maintain consistency with the previous updates and preserve the test's functionality.


Line range hint 1-443: Summary: Consistent updates to mock expectations and database configuration

The changes in this file primarily involve:

  1. Updating mock expectations from On() to EXPECT() throughout the test suite.
  2. Changing the database configuration from MySQL to PostgreSQL in the TestMakeOrm function.

These changes improve the consistency of the test suite and reflect a shift in the project's database strategy. However, it's important to ensure that:

  1. The new mocking approach is applied consistently across all test files in the project.
  2. The switch to PostgreSQL is reflected in the main application code and documentation.

To ensure project-wide consistency, run the following commands:

#!/bin/bash
# Check for any remaining uses of the old On() method in all test files
rg --type go 'mock.*\.On\(' .

# Verify that MySQL is no longer used as the primary database
rg --type go 'mysql' .

# Check for PostgreSQL usage across the project
rg --type go 'postgres' .

154-154: LGTM: Updated mock expectation method

The change from On() to EXPECT() is consistent with modern mocking libraries. This update improves the readability and maintainability of the test.

To ensure all mock expectations have been updated consistently, run the following command:

✅ Verification successful

Action Required: Re-verify Mock Expectations Across the Repository

The previous check failed to locate the test directory. To ensure all mock expectations have been updated consistently, please run the following command:


Verification Complete: No Remaining On() Methods in Test Files

All test files have been successfully updated to use EXPECT(), and there are no remaining instances of the old On() method outside of the mocks/ directory.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining uses of the old On() method in test files
rg --type go 'mock.*\.On\(' test

Length of output: 79


Script:

#!/bin/bash
# Check for any remaining uses of the old On() method in Go files across the repository
rg --type go 'mock.*\.On\(' .

Length of output: 149601


310-330: LGTM: Updated database configuration from MySQL to PostgreSQL

The test has been updated to use PostgreSQL instead of MySQL, which is a significant change. This update includes new mock expectations for PostgreSQL-specific configurations.

To ensure that PostgreSQL support is consistently implemented throughout the codebase, run the following commands:

database/gorm/query_test.go (1)

15-15: LGTM: Import added for database package

The addition of the database package import is appropriate and necessary for the changes made in the code, particularly for using the database driver constants.

contracts/database/config.go (2)

3-8: Constants for Database Drivers are Well-Defined

The constants for the Driver type are properly defined, providing clear and explicit values for supported database drivers.


12-14: Clarify the Necessity of the String() Method

Since Driver is a type alias for string, implementing the String() method might be redundant. However, if this is intended to satisfy interfaces like fmt.Stringer for consistency or future-proofing, it is acceptable.

Would you confirm if the String() method provides additional benefits in your use case?

database/db/dsn.go (1)

22-22: Verify the necessity of 'multi_stmts=true' in SQLite DSN

The multi_stmts=true parameter is not a recognized option for SQLite DSNs and may have no effect or could potentially cause issues. SQLite typically doesn't require this parameter.

Consider removing it if it's unnecessary:

 return fmt.Sprintf("%s?multi_stmts=true", config.Database)
+return fmt.Sprintf("%s", config.Database)

Please check the SQLite driver documentation to confirm supported DSN parameters.

database/gorm/dialector.go (1)

27-41: Verify the Completeness of Supported Drivers

Ensure that all intended drivers are supported and correctly implemented. Additionally, confirm that there are no additional drivers that need to be accommodated.

Run the following script to list all usage of driver constants and verify the supported drivers:

✅ Verification successful

Completeness of Supported Drivers Verified

All intended database drivers (mysql, postgres, sqlite, sqlserver) are supported and correctly implemented. No additional drivers are detected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: List all usages of database driver constants in the codebase.

# Search for all instances where driver constants are defined or used.
rg --type go 'Driver\w+' -A 2

Length of output: 110147

database/console/migrate.go (2)

14-16: Imports updated to use the database package

The imports have been updated to replace the orm package with the database package, which aligns with the goal of removing the "wire" component and streamlines database handling.


28-29: Ensure proper handling of database configurations

The code now retrieves write configurations using databasedb.NewConfigs(config, connection).Writes(). Verify that this method accurately captures all necessary configurations, and that any read configurations are handled appropriately elsewhere in the codebase.

database/db/configs.go (1)

81-83: Ensure Database field is set correctly

In the condition if config.Database == "", the code sets fullConfig.Database using the default configuration. Confirm that this logic aligns with the intended behavior, especially if config.Database might be intentionally left empty.

Ensure that an empty Database field in config should indeed default to the value from the main configuration. If an empty string is a valid value for Database, this logic might override intentional settings.

database/gorm/gorm.go (3)

20-23: Builder struct initialization looks good

The Builder struct is properly defined with the necessary fields config, configs, and instance, facilitating a clean and organized initialization process.


26-32: NewGorm function is correctly implemented

The NewGorm function effectively initializes a new Builder instance and invokes the Build method, streamlining the creation of the GORM database instance.


Line range hint 35-54: Build method handles configuration appropriately

The Build method correctly retrieves read and write configurations, checks for necessary configurations, initializes the database, and sets up connection pools and read-write separation. Error handling is appropriately managed.

database/orm_test.go (1)

30-31: Updated OrmSuite struct fields align with new type definitions—Looks Good

The OrmSuite struct fields have been updated to use *Orm for the orm field and map[database.Driver]*gorm.TestQuery for the testQueries field. This change aligns with the updated type definitions and ensures consistency across the codebase.

testing/docker/database_test.go (2)

54-54: Verify Correct Usage of Updated Driver Constants

The mockConfig.EXPECT().GetString() calls now return driver strings from contractsdatabase. Ensure that the driver constants like DriverMysql, DriverPostgres, etc., are correctly defined in contractsdatabase and that they match the expected values.

Also applies to: 64-64, 73-73, 83-83, 92-92, 102-102, 111-111, 121-121, 130-130, 140-140


191-193: Verify the Refresh Method Corresponds to Updated Mocks

In the TestBuild method, the call to s.mockOrm.EXPECT().Refresh().Once() might need updating if the Refresh method has moved or changed in the new contractsdatabase mocks.

Run the following script to verify the definition of the Refresh method in the updated mocks:

database/db/configs_test.go (1)

36-39: ⚠️ Potential issue

Inconsistent behavior when configurations are empty between Reads() and Writes() methods

In TestReads(), when the configurations are empty, s.configs.Reads() returns nil (line 38). However, in TestWrites(), when configurations are empty, s.configs.Writes() returns a default configuration (lines 74-83). Please verify whether this difference in behavior is intentional. If not, consider aligning the behavior of the Reads() and Writes() methods when configurations are empty.

database/gorm/query.go (1)

18-19: Imports updated to new package paths

The imports for contractsdatabase and contractsorm have been correctly updated to reflect the new package structure.

database/gorm/test_utils.go (14)

23-23: Confirm the change of TestModel to TestModelMinimum

You've set TestModel to TestModelMinimum. This reduces the number of initialized test databases, potentially affecting test coverage for MySQL and SQL Server. Please confirm that this change is intentional and aligns with your testing strategy.


82-83: Update function return types to contractsdatabase.Driver

The Queries function now returns map[contractsdatabase.Driver]*TestQuery. Ensure that all function usages and type assertions have been updated accordingly to prevent type mismatch errors.


86-87: Update QueriesOfReadWrite return type

The QueriesOfReadWrite function now returns map[contractsdatabase.Driver]map[string]orm.Query. Verify that any code utilizing this function handles the new return type correctly.


115-121: Verify driver mappings in QueriesOfReadWrite

In the returned map, only contractsdatabase.DriverPostgres and contractsdatabase.DriverSqlite are included when TestModel is TestModelMinimum. Confirm that excluding other drivers like MySQL and SQL Server is intentional.


157-173: Check driver mappings for full test model

When TestModel is not TestModelMinimum, the mappings include MySQL and SQL Server. Ensure that all necessary drivers are included and correctly configured for comprehensive testing.


181-183: Update return type in QueriesWithPrefixAndSingular

The QueriesWithPrefixAndSingular function's return type has been updated to use contractsdatabase.Driver. Verify that callers of this function handle the new type appropriately.


192-202: Consistent use of contractsdatabase.Driver in driver maps

In the queries function, the maps now use contractsdatabase.Driver as keys. Ensure that any iteration or access of these maps reflects this change to prevent key mismatches.


276-279: Ensure consistency in QueryOfReadWrite function

The QueryOfReadWrite function now uses the updated getMockDriver. Verify that it correctly initializes the mock driver and builds the query without issues.


332-335: Update mock configurations to contractsdatabase.Config

The mock read and write configurations now use []contractsdatabase.Config. Ensure that these configurations are correctly set up and that all fields required by contractsdatabase.Config are provided.


566-569: Update testTables struct and constructor

The testTables struct and its constructor now use contractsdatabase.Driver. Verify that all methods relying on driver reflect this change and function as expected.


Line range hint 804-843: Consistency in goravel_user table creation

Ensure that the goravel_user table creation scripts are updated correctly for all drivers using contractsdatabase.Driver. Verify that the table definitions are consistent across different databases.


Line range hint 918-1002: Confirm relational mappings in books and authors tables

With the driver changes, ensure that the foreign key relationships and related fields between books and authors are correctly defined and compatible with each database's requirements.

If necessary, update the SQL creation scripts to explicitly define foreign key constraints.


8-8: Ensure consistent usage of contractsdatabase package

The import statement now references contractsdatabase instead of orm. Please verify that all occurrences of orm.Driver and related types have been updated to use contractsdatabase.Driver throughout the codebase.

Here is a script to check for any remaining references to orm.Driver:

✅ Verification successful

Import Consistency Verified Successfully

All occurrences of orm.Driver have been updated to contractsdatabase.Driver throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find any remaining references to 'orm.Driver' in Go files.

rg 'orm\.Driver' --type go

Length of output: 130


Script:

#!/bin/bash
# Description: Correctly find any remaining references to 'orm.Driver' in Go files, excluding the 'database/gorm' directory.

rg 'orm\.Driver' --type go --glob '!database/gorm/*'

Length of output: 54


282-292: Impact of unexporting getMockDriver function

Changing GetMockDriver to getMockDriver unexports the function. This could affect other packages relying on it. Please confirm that this function is not used outside its package.

Here's a script to find external usages:

✅ Verification successful

Verified: getMockDriver is not used outside the gorm package.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for 'GetMockDriver' usages outside the 'gorm' package.

rg 'GetMockDriver' --type go --glob '!database/gorm/*'

Length of output: 130


Script:

#!/bin/bash
# Description: Search for 'GetMockDriver' usages outside the 'gorm' package.

rg 'GetMockDriver' --type go --glob '!database/gorm/*'

Length of output: 54

contracts/testing/testing.go Show resolved Hide resolved
support/docker/sqlserver_test.go Show resolved Hide resolved
support/docker/mysql_test.go Show resolved Hide resolved
database/service_provider.go Outdated Show resolved Hide resolved
database/service_provider.go Outdated Show resolved Hide resolved
testing/docker/database_test.go Show resolved Hide resolved
testing/docker/database_test.go Show resolved Hide resolved
database/db/configs_test.go Show resolved Hide resolved
database/gorm/query.go Show resolved Hide resolved
database/gorm/query.go Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (4)
database/orm.go (4)

15-21: LGTM: Struct changes enhance flexibility, but documentation needed

The renaming of the struct and the changes to field types improve the flexibility of the ORM implementation. The addition of the queries map allows for managing multiple queries, which is a good enhancement.

However, the purpose and usage of the refresh function are not immediately clear.

Could you add a comment explaining the purpose and usage of the refresh function?


24-35: LGTM: Constructor changes align with struct updates

The NewOrm function changes are consistent with the updates to the Orm struct. The initialization of the queries map with the default connection is a good practice.

However, consider adding error checking for the query parameter to ensure it's not nil before proceeding with the initialization.

Consider adding a nil check for the query parameter:

if query == nil {
    return nil, fmt.Errorf("query cannot be nil")
}

Line range hint 46-76: LGTM: Connection method enhances flexibility, but error handling could be improved

The updates to the Connection method improve the flexibility of the ORM by allowing dynamic creation and caching of connections. The use of the contractsorm.Orm interface as the return type is consistent with the move towards using contracts.

However, the error handling when building a new query could be improved.

Consider returning an error instead of nil when the query building fails:

queue, err := gorm.BuildQuery(r.ctx, r.config, name)
if err != nil {
    return nil, fmt.Errorf("failed to build query for connection %s: %w", name, err)
}

This would allow the caller to handle the error more effectively.


99-101: Clarify purpose and usage of Refresh method

The purpose and usage of the Refresh method are not immediately clear. Additionally, the BindingOrm constant is not defined in the visible code.

Could you please add a comment explaining:

  1. The purpose of the Refresh method
  2. When and how it should be used
  3. What the BindingOrm constant represents

Also, ensure that the BindingOrm constant is properly defined and imported.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3a99442 and aee982c.

📒 Files selected for processing (3)
  • database/gorm/test_utils.go (66 hunks)
  • database/orm.go (5 hunks)
  • database/service_provider.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • database/service_provider.go
🔇 Additional comments (26)
database/orm.go (5)

9-10: LGTM: Import changes are consistent with refactoring

The addition of the contractsorm import and the update to the gorm package import align well with the refactoring efforts to use contract interfaces for the ORM implementation.


37-44: LGTM: BuildOrm function improves code organization

The addition of the BuildOrm function is a good improvement in code organization. It encapsulates the logic for creating a new Orm instance, including the creation of the query using gorm.BuildQuery. The error handling is appropriate, providing a clear error message if the query building fails.


Line range hint 120-136: Fix potential panics in WithContext method

The WithContext method now sets the context for all queries, which is a good practice. However, the type assertions query := query.(*gorm.Query) and query := r.query.(*gorm.Query) could panic if the queries are not of type *gorm.Query. This issue was previously flagged in a past review.

To fix this, use the two-value form of type assertion:

func (r *Orm) WithContext(ctx context.Context) contractsorm.Orm {
    for key, query := range r.queries {
        if gormQuery, ok := query.(*gorm.Query); ok {
            gormQuery.SetContext(ctx)
        } else {
            // Consider logging a warning or error here
        }
    }

    if gormQuery, ok := r.query.(*gorm.Query); ok {
        gormQuery.SetContext(ctx)
    } else {
        // Consider logging a warning or error here
    }

    return &Orm{
        ctx:        ctx,
        config:     r.config,
        connection: r.connection,
        query:      r.query,
        queries:    r.queries,
    }
}

This approach safely handles the type assertions and allows for appropriate error handling or logging if the type is unexpected.


Line range hint 1-136: Summary of ORM implementation changes

The changes to the ORM implementation in database/orm.go generally improve its flexibility and functionality. Key improvements include:

  1. Use of contract interfaces for better abstraction
  2. Support for multiple queries and connections
  3. Addition of a refresh mechanism

However, there are areas that need attention:

  1. Improve error handling in the Connection method
  2. Fix potential panics due to unsafe type assertions in DB and WithContext methods
  3. Add documentation for the new Refresh method and clarify the usage of BindingOrm

Please address these issues to enhance the robustness and maintainability of the ORM implementation.


78-82: ⚠️ Potential issue

Fix potential panic in DB method

The type assertion r.Query().(*gorm.Query) could panic if r.Query() returns a type that's not *gorm.Query. This issue was previously flagged in a past review.

To fix this, use the two-value form of type assertion:

func (r *Orm) DB() (*sql.DB, error) {
    query, ok := r.Query().(*gorm.Query)
    if !ok {
        return nil, fmt.Errorf("unexpected Query type %T, expected *gorm.Query", r.Query())
    }
    return query.Instance().DB()
}
database/gorm/test_utils.go (21)

82-82: Updated return type to contractsdatabase.Driver

The Queries method now returns a map with keys of type contractsdatabase.Driver, reflecting the updated driver enumeration.


86-86: Updated return type in QueriesOfReadWrite

The QueriesOfReadWrite method's return type has been updated to use contractsdatabase.Driver as the key type. This aligns with the changes made to the driver representations.


115-122: Consistent driver types in returned map

The returned map now uses contractsdatabase.Driver as keys, which is consistent with the updated driver package.


157-173: Consistent driver types in returned map

Similar to previous changes, the map uses contractsdatabase.Driver as keys for consistency.


181-181: Updated method signature for QueriesWithPrefixAndSingular

The return type now uses contractsdatabase.Driver, aligning with the updated driver definitions.


192-193: Updated queries method and map initialization

The queries method signature and the driverToTestQuery map now use contractsdatabase.Driver, ensuring consistency across driver type usage.


195-197: Updated driver-to-docker mapping

The driverToDocker map now correctly uses contractsdatabase.Driver as keys, mapping to the corresponding testing.DatabaseDriver instances.


201-202: Conditional inclusion of MySQL and SQL Server drivers

When TestModel is not TestModelMinimum, the MySQL and SQL Server drivers are added to the driverToDocker map using contractsdatabase.Driver.


223-223: Updated function call to getMockDriver

The call to getMockDriver reflects the change in function name and encapsulation, moving from an exported to an unexported function.


237-240: Consistent use of BuildQuery function

The BuildQuery function is called consistently after updating the configuration, ensuring the query object is properly constructed with the new driver settings.


244-244: Proper error handling with informative panic message

The error handling provides a clear panic message that includes the driver name and the error encountered, aiding in debugging.


276-279: Updated QueryOfReadWrite method implementation

The method now uses getMockDriver and calls BuildQuery with the updated driver configuration, ensuring read/write configurations are correctly applied.


286-292: Updated switch cases with new driver types

The switch cases in getMockDriver now use contractsdatabase.Driver values, ensuring alignment with the updated driver definitions.


Line range hint 300-312: Updated MockMysql struct and constructor

The MockMysql struct now uses contractsdatabase.Driver, and the constructor NewMockMysql reflects this change, ensuring consistency in driver representation.


Line range hint 371-383: Updated MockPostgres struct and constructor

Similar updates are applied to the MockPostgres struct, using contractsdatabase.Driver and aligning the constructor accordingly.


Line range hint 441-450: Updated MockSqlite struct and constructor

The struct now correctly references contractsdatabase.Driver, and the constructor NewMockSqlite is updated to match.


Line range hint 498-510: Updated MockSqlserver struct and constructor

The MockSqlserver struct and its constructor now use contractsdatabase.Driver, maintaining consistency across all mock drivers.


566-569: Updated testTables struct and newTestTables function

The testTables struct now holds a contractsdatabase.Driver, and the newTestTables constructor reflects this change. This ensures that table creation functions use the correct driver type.


Line range hint 592-625: Correct use of driver types in table creation

In the peoples table creation function, the cases now use contractsdatabase.Driver constants, ensuring that the correct SQL statements are returned based on the driver.


282-292: ⚠️ Potential issue

Function GetMockDriver renamed to getMockDriver and unexported

The function has been unexported by renaming it from GetMockDriver to getMockDriver. Verify that this function is not required outside of this package and that external references have been updated accordingly.

To check for external references to GetMockDriver, run:

#!/bin/bash
# Description: Search for external references to GetMockDriver
rg 'GetMockDriver' --type go --glob '!database/gorm/*.go'

232-232: ⚠️ Potential issue

Variable declaration uses undefined type *Query

The variable query is declared as *Query, but there is no explicit import or definition shown for the Query type. Ensure that Query is properly defined or imported in the context.

To verify if the Query type is correctly defined, you can run:

database/gorm/test_utils.go Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (10)
database/gorm/dialector_test.go (1)

28-96: LGTM: Comprehensive test cases with a minor suggestion

The test cases are well-structured and cover various scenarios, including both happy and sad paths for different database types. The use of expectDialectors function for type-specific assertions is a good approach.

Consider adding a test case for an unsupported database type to ensure the getDialectors function handles unexpected inputs gracefully.

database/orm.go (5)

15-21: LGTM: Struct changes improve clarity and flexibility.

The renaming of OrmImpl to Orm simplifies the struct name, which is a good practice. The use of contractsorm.Query instead of a concrete type improves flexibility and testability.

However, the purpose of the new refresh field is not immediately clear.

Consider adding a comment to explain the purpose and usage of the refresh field:

type Orm struct {
	// ... other fields ...
	
	// refresh is a function used to update the ORM instance when needed
	refresh func(key any)
}

37-44: LGTM: BuildOrm function is a good addition.

The BuildOrm function encapsulates the query building logic, providing a convenient way to create an Orm instance with a new query. This is a good separation of concerns.

Consider wrapping the error returned from NewOrm to provide more context:

orm, err := NewOrm(ctx, config, connection, query, refresh)
if err != nil {
	return nil, fmt.Errorf("[Orm] Failed to create new Orm instance: %w", err)
}
return orm, nil

Line range hint 46-76: LGTM: Connection method changes improve immutability and flexibility.

The changes to the Connection method are well-implemented. Returning a new Orm instance instead of modifying the existing one is a good practice for immutability. The use of contractsorm.Orm as the return type improves flexibility.

Consider improving error handling when BuildQuery fails:

queue, err := gorm.BuildQuery(r.ctx, r.config, name)
if err != nil {
	color.Red().Printf("[Orm] Init %s connection error: %v\n", name, err)
	return nil
}
if queue == nil {
	color.Red().Printf("[Orm] Init %s connection error: query is nil\n", name)
	return nil
}

This separates the error cases and provides more specific error messages.


Line range hint 106-120: LGTM: Transaction method changes improve error handling.

The updates to the Transaction method, including the use of contractsorm.Query and improved error handling for rollback, are good improvements. These changes enhance the robustness of the transaction handling.

Consider using errors.Wrap for better error context:

import "github.com/pkg/errors"

// ...

if err := tx.Rollback(); err != nil {
	return errors.Wrap(err, "rollback failed")
}

This provides more context when the error is logged or displayed.


123-140: LGTM: WithContext method changes improve context handling.

The updates to the WithContext method, including setting the context for all queries and using type assertions, are good improvements. These changes ensure consistent context handling across different connections and prevent potential panics.

Consider logging a warning when a query is not of the expected type:

import "log"

// ...

for name, query := range r.queries {
	if gormQuery, ok := query.(*gorm.Query); ok {
		gormQuery.SetContext(ctx)
	} else {
		log.Printf("Warning: Query for connection %s is not of type *gorm.Query", name)
	}
}

This would help identify any unexpected query types during development or debugging.

database/gorm/gorm.go (2)

Line range hint 71-92: LGTM with suggestion: configureReadWriteSeparate method updated appropriately.

The method has been successfully updated to work with database.FullConfig and utilizes the new getDialectors function, which suggests a more modular approach. The core logic for configuring read-write separation remains intact and appropriate.

Consider extracting the error checking logic for getDialectors into a separate function to reduce repetition:

func getDialectorsWithErrorCheck(configs []database.FullConfig) ([]gormio.Dialector, error) {
    dialectors, err := getDialectors(configs)
    if err != nil {
        return nil, err
    }
    return dialectors, nil
}

This would allow you to simplify the configureReadWriteSeparate method:

readDialectors, err := getDialectorsWithErrorCheck(readConfigs)
if err != nil {
    return err
}

writeDialectors, err := getDialectorsWithErrorCheck(writeConfigs)
if err != nil {
    return err
}

Line range hint 94-134: LGTM with suggestion: init method updated appropriately.

The init method has been successfully updated to work with database.FullConfig and utilizes the new getDialectors function. The naming strategy configuration is correctly updated, and proper error handling has been added for the case of no dialectors found.

Consider moving the logger configuration into a separate method to improve readability:

func (r *Builder) configureLogger() gormlogger.Interface {
    var logLevel gormlogger.LogLevel
    if r.config.GetBool("app.debug") {
        logLevel = gormlogger.Info
    } else {
        logLevel = gormlogger.Error
    }

    logger := NewLogger(log.New(os.Stdout, "\r\n", log.LstdFlags), gormlogger.Config{
        SlowThreshold:             200 * time.Millisecond,
        LogLevel:                  gormlogger.Info,
        IgnoreRecordNotFoundError: true,
        Colorful:                  true,
    })

    return logger.LogMode(logLevel)
}

Then in the init method, you can simply call:

logger := r.configureLogger()

This would make the init method more focused and easier to read.

database/db/configs_test.go (1)

107-232: Excellent test coverage with room for minor improvement

The TestFillDefault function demonstrates a well-structured, table-driven approach to testing multiple scenarios. The test cases provide comprehensive coverage for various situations, including empty configs, configs with empty keys, and different database drivers.

To further enhance the test structure:

  1. Consider extracting the common mock setup logic into a helper function to reduce repetition across test cases.
  2. You might want to add a brief comment before each test case in the table to explain the specific scenario being tested, improving readability for future maintainers.

Overall, the test structure is clear, easy to understand, and provides excellent coverage of the fillDefault method.

database/gorm/query.go (1)

1510-1512: Ensure safe type assertion in getModelConnection function

In the getModelConnection function, the type assertion to contractsorm.ConnectionModel is performed without checking if newModel.Interface() is not nil. To prevent potential panics, consider checking if newModel.Interface() is not nil before performing the type assertion.

Apply this diff to add a nil check:

 connectionModelInterface := newModel.Interface()
+if connectionModelInterface == nil {
+    return "", nil
+}
 connectionModel, ok := connectionModelInterface.(contractsorm.ConnectionModel)
 if !ok {
     return "", nil
 }

This ensures that the function safely handles cases where the interface is nil.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between aee982c and 4bb9026.

⛔ Files ignored due to path filters (1)
  • mocks/database/ConfigBuilder.go is excluded by !mocks/**
📒 Files selected for processing (10)
  • contracts/database/config.go (1 hunks)
  • database/console/migrate.go (5 hunks)
  • database/db/configs.go (1 hunks)
  • database/db/configs_test.go (1 hunks)
  • database/gorm/dialector.go (1 hunks)
  • database/gorm/dialector_test.go (1 hunks)
  • database/gorm/gorm.go (5 hunks)
  • database/gorm/query.go (61 hunks)
  • database/orm.go (5 hunks)
  • foundation/container_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • contracts/database/config.go
  • database/console/migrate.go
  • database/db/configs.go
  • foundation/container_test.go
🔇 Additional comments (35)
database/gorm/dialector.go (6)

12-13: LGTM: Import statements are appropriate.

The new import statements are necessary for the refactored implementation and there are no unused imports.


16-16: LGTM: Function signature is well-defined.

The getDialectors function signature is appropriate for its purpose. It correctly takes a slice of database.FullConfig as input and returns a slice of gorm.Dialector along with an error. The function is not exported, which aligns with the previous suggestion to keep it as an internal function.


19-24: LGTM: Main loop implementation is correct and efficient.

The main loop correctly iterates over the configs to create dialectors. The DSN generation and error handling for empty DSN are well-implemented. The error message for empty DSN has been improved as suggested in the previous review.


44-47: LGTM: Final part of the function is correctly implemented.

The created dialector is properly appended to the slice, and the function correctly returns the slice of dialectors along with a nil error when successful.


26-42: ⚠️ Potential issue

Improve error message for unsupported database drivers.

The switch statement correctly handles the creation of dialectors for supported database drivers. However, the error message in the default case could be improved for clarity and grammar.

Apply this diff to enhance the error message:

- return nil, fmt.Errorf("err database driver: %s, only support mysql, postgres, sqlite and sqlserver", config.Driver)
+ return nil, fmt.Errorf("unsupported database driver '%s'; supported drivers are mysql, postgres, sqlite, and sqlserver", config.Driver)

Likely invalid or redundant comment.


16-47: LGTM: Excellent refactoring of the dialector creation logic.

The getDialectors function effectively replaces the previous Dialector interface and DialectorImpl struct, consolidating the logic for creating dialectors for different database types. This refactoring has simplified the code and improved maintainability while adhering to Go best practices and SOLID principles.

To ensure the changes don't have unintended consequences, please run the following script to verify the usage of the old Dialector interface and DialectorImpl struct:

✅ Verification successful

Verified: The old Dialector interface and DialectorImpl struct are no longer used in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the old Dialector interface and DialectorImpl struct are no longer used in the codebase.

# Test: Search for usage of Dialector interface
echo "Searching for Dialector interface usage:"
rg --type go "type\s+Dialector\s+interface"

# Test: Search for usage of DialectorImpl struct
echo "Searching for DialectorImpl struct usage:"
rg --type go "type\s+DialectorImpl\s+struct"

# Test: Search for NewDialectorImpl function usage
echo "Searching for NewDialectorImpl function usage:"
rg --type go "NewDialectorImpl\("

# If any of these searches return results, it may indicate that some parts of the codebase still rely on the old implementation and need to be updated.

Length of output: 415

database/gorm/dialector_test.go (4)

Line range hint 1-15: LGTM: Import statements updated appropriately

The import statements have been updated to reflect the new testing approach. The removal of the testify/suite import and the addition of testify/assert and goravel/framework/contracts/database imports are consistent with the shift from a test suite to table-driven tests.


17-27: LGTM: Well-structured table-driven tests

The new TestGetDialectors function implements a table-driven test approach, which is an excellent practice for testing multiple scenarios efficiently. This structure allows for easy addition of new test cases and improves the overall maintainability of the test suite.


99-111: LGTM: Well-implemented test execution

The test execution structure is well-implemented:

  1. Using a for loop to iterate through test cases is efficient.
  2. Running each test case as a subtest (t.Run()) provides clear and organized test output.
  3. The assertions using testify/assert are appropriate and easy to understand.
  4. The error comparison now uses assert.EqualError, addressing a previous review comment.

This implementation ensures good test isolation and clear failure messages.


Line range hint 1-111: Excellent refactoring of the test suite

The complete rewrite of this test file is a significant improvement:

  1. The shift to table-driven tests enhances maintainability and readability.
  2. Test cases are comprehensive, covering various scenarios for different database types.
  3. The new structure allows for easy addition of new test cases.
  4. Previous review comments have been addressed, particularly the use of assert.EqualError.

These changes result in a more robust and maintainable test suite. Great job on the refactoring!

database/orm.go (6)

9-10: LGTM: Import changes are appropriate.

The addition of the contractsorm import and the update to the gorm package import align well with the refactoring changes made throughout the file. These changes contribute to better separation of concerns and improved modularity.


24-35: LGTM: NewOrm function changes are consistent and well-structured.

The renaming of NewOrmImpl to NewOrm is consistent with the struct renaming. The addition of the refresh parameter and its assignment to the struct field is appropriate. The initialization of the queries map with the provided query is a good practice for maintaining the connection state.


78-85: LGTM: DB method changes improve type safety.

The addition of the type assertion and error handling in the DB method is a good improvement. It prevents potential panics that could occur if the underlying query is not of the expected type. This change enhances the robustness of the code.


87-100: LGTM: Method signature updates are consistent.

The updates to the Query, Factory, and Observe methods to use contractsorm interfaces are consistent with the overall refactoring. These changes improve the flexibility and testability of the code without altering the core logic of the methods.


102-104: Please provide more context for the Refresh method.

The purpose and usage of the Refresh method are not immediately clear. Additionally, the BindingOrm argument is not defined in this file.

Could you please provide more information about:

  1. The purpose of the Refresh method?
  2. The definition and significance of BindingOrm?
  3. When and how this method is intended to be used?

Consider adding a comment to explain these points:

// Refresh updates the ORM instance using the provided refresh function.
// It uses BindingOrm as a key to identify which binding to refresh.
func (r *Orm) Refresh() {
	r.refresh(BindingOrm)
}

Line range hint 1-140: Overall, the changes in this file are well-implemented and improve the ORM functionality.

The refactoring to use contract interfaces enhances the flexibility and testability of the code. Error handling improvements contribute to the robustness of the implementation. The new BuildOrm function and the changes to the Connection method are particularly noteworthy improvements.

However, there are a few areas that could benefit from further attention:

  1. The purpose and usage of the new Refresh method need clarification.
  2. Some methods could benefit from more detailed error handling or logging.
  3. Additional documentation for new or significantly changed methods would improve code maintainability.

These minor improvements aside, the changes represent a significant step forward in the ORM implementation.

database/gorm/gorm.go (6)

16-16: LGTM: New import aligns with restructuring.

The addition of the database contract import is consistent with the changes made to the GORM implementation structure.


20-23: LGTM: New Builder struct improves encapsulation.

The Builder struct effectively encapsulates the necessary components for constructing a GORM instance. The use of database.ConfigBuilder suggests a more flexible and maintainable approach to configuration.


26-32: LGTM: Improved NewGorm function signature and implementation.

The new NewGorm function simplifies the interface by using a ConfigBuilder and returns (*gormio.DB, error) directly, which is more idiomatic Go. The implementation is concise and clear, effectively delegating the build process to the Builder struct.


Line range hint 35-53: LGTM: Well-structured Build method.

The Build method effectively orchestrates the GORM instance creation process. It uses the configBuilder to retrieve configurations, and follows a clear step-by-step approach with appropriate error handling. The method successfully replaces the functionality of the previous Make method while improving readability and maintainability.


Line range hint 57-69: LGTM: configurePool method adapted correctly.

The configurePool method has been successfully adapted to work with the new Builder struct. The implementation remains sound, correctly configuring the connection pool using configuration values with appropriate default fallbacks.


Line range hint 1-134: Overall assessment: Significant improvements to GORM implementation structure.

The changes in this file represent a substantial improvement to the GORM implementation structure. The introduction of the Builder pattern, along with the use of database.ConfigBuilder and database.FullConfig, provides better encapsulation and flexibility. Error handling has been enhanced, and the code is generally more modular and maintainable.

The refactoring aligns well with the PR objective of removing the "wire" component, as it simplifies the initialization process and consolidates configuration handling. These changes should make the codebase more robust and easier to maintain going forward.

Great job on this refactoring! The code quality has notably improved.

database/db/configs_test.go (5)

1-18: LGTM: Proper package structure and imports

The package declaration, imports, and struct definition are well-organized and appropriate for the test suite. The necessary dependencies are correctly imported, and the ConfigTestSuite struct is properly defined with the required fields.


20-29: LGTM: Proper test suite setup

The TestConfigTestSuite function serves as a good entry point for running the test suite. The SetupTest method correctly initializes the mock config and config builder before each test, following best practices for test suite setup.


31-60: Comprehensive test cases with potential for refactoring

The TestReads function provides thorough coverage of the Reads method, testing both empty and non-empty config scenarios. The mock expectations are well-defined and cover all necessary calls.

However, as mentioned in a previous review comment, there's an opportunity to refactor the repeated mock setup code into helper functions. This would improve maintainability and reduce code duplication across multiple test methods.


62-105: Comprehensive test cases with repeated refactoring opportunity

The TestWrites function provides thorough coverage of the Writes method, testing both empty and non-empty config builder scenarios. The mock expectations are well-defined and cover all necessary calls.

As with the TestReads function, there's an opportunity to refactor the repeated mock setup code into helper functions. This would improve maintainability and reduce code duplication across multiple test methods.


1-232: Overall excellent test coverage with minor improvement suggestions

This test file provides comprehensive coverage for the ConfigBuilder functionality. The test cases are well-structured, cover various scenarios, and use appropriate testing techniques such as table-driven tests.

To further enhance the quality and maintainability of the test suite:

  1. Consider refactoring repeated mock setup code into helper functions across all test methods.
  2. Add brief comments to explain specific scenarios in table-driven tests.

These minor improvements will make the already high-quality test suite even more maintainable and easier to understand for future developers.

Great job on creating a thorough and well-structured test suite!

database/gorm/query.go (8)

18-19: Updated import statements to reflect package refactoring

The imports for contractsdatabase and contractsorm have been added, aligning with the refactoring to remove the dependency on the wire package. This ensures that the code uses the correct contracts from the updated packages.


26-32: Note on potential concurrent access to queries map

As previously mentioned, the queries map in the Query struct may not be safe for concurrent access if instances of Query are used from multiple goroutines. Ensure that appropriate synchronization mechanisms are in place to prevent data races.


35-41: Initialization of queries map in NewQuery constructor

The queries map is correctly initialized in the NewQuery constructor. This prepares the map for storing query instances associated with different connections.


51-58: Creation of BuildQuery function

The BuildQuery function provides a convenient way to build a new Query instance with the given context, configuration, and connection. This enhances the modularity and reusability of the code.


178-178: Correct implementation of Driver method

The Driver method correctly returns the database driver by casting the dialector name to contractsdatabase.Driver. This ensures compatibility with the updated contractsdatabase package.


542-551: Note on handling unsupported drivers in InRandomOrder method

As previously mentioned, consider adding a default case to handle unsupported or unknown drivers in the InRandomOrder method. This can prevent unintended behavior if a new driver is added or an unsupported driver is used.


Line range hint 1309-1327: Potential data race when accessing queries map concurrently

In the refreshConnection method, the queries map is accessed and modified. If instances of Query are used from multiple goroutines, this could lead to data races. Consider using a thread-safe data structure like sync.Map or adding synchronization mechanisms such as a mutex to protect concurrent access to the queries map.


1539-1559: Switch statement in getObserverEvent covers all event types

The getObserverEvent function includes cases for all defined EventType values, returning the corresponding observer methods. The lack of a default case is acceptable here because all possible enum values are covered. Ensure that any new event types added in the future are also handled in this switch statement.

database/gorm/query.go Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (2)
database/gorm/dialector.go (1)

22-24: Enhance error message for empty DSN

The error message for an empty DSN could be more informative. Consider including the connection name in the error message for easier debugging.

Apply this diff to improve the error message:

- return nil, fmt.Errorf("failed to generate DSN for connection: %s", config.Connection)
+ return nil, fmt.Errorf("failed to generate DSN for connection '%s'", config.Connection)
database/gorm/dialector_test.go (1)

28-96: LGTM: Comprehensive test cases with a suggestion

The test cases cover a good range of scenarios, including both error cases and successful cases for different database types. This ensures that the getDialectors function is thoroughly tested.

Consider adding a test case for an unsupported database driver to ensure the function handles unexpected inputs gracefully.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3e6bb94 and 61aa33f.

📒 Files selected for processing (2)
  • database/gorm/dialector.go (1 hunks)
  • database/gorm/dialector_test.go (1 hunks)
🔇 Additional comments (9)
database/gorm/dialector.go (4)

Line range hint 1-15: LGTM: Import statements are appropriate

The import statements have been updated to reflect the new implementation. All imports are necessary and there are no unused imports.


16-16: LGTM: Function signature is appropriate and addresses previous feedback

The getDialectors function signature is well-designed for its purpose. It takes a slice of database configurations and returns a slice of GORM dialectors along with a potential error. The function is correctly unexported, addressing the previous review comment about considering unexporting the function.


16-48: LGTM: Overall implementation is efficient and well-structured

The getDialectors function efficiently consolidates the logic for creating dialectors for different database types. It handles multiple configurations and returns a slice of dialectors, which is a good approach for supporting multiple database connections. The implementation is concise and addresses the needs of the refactoring by removing the previous Dialector interface and DialectorImpl struct.


26-42: ⚠️ Potential issue

Improve switch statement and error handling for unsupported drivers

The switch statement could benefit from a default case to handle unsupported drivers more explicitly. Additionally, the error message for unsupported drivers could be more clear and grammatically correct.

Apply this diff to improve the switch statement and error message:

 switch config.Driver {
 case database.DriverMysql:
     dialector = mysql.New(mysql.Config{
         DSN: dsn,
     })
 case database.DriverPostgres:
     dialector = postgres.New(postgres.Config{
         DSN: dsn,
     })
 case database.DriverSqlite:
     dialector = sqlite.Open(dsn)
 case database.DriverSqlserver:
     dialector = sqlserver.New(sqlserver.Config{
         DSN: dsn,
     })
 default:
-    return nil, fmt.Errorf("err database driver: %s, only support mysql, postgres, sqlite and sqlserver", config.Driver)
+    return nil, fmt.Errorf("unsupported database driver '%s'; supported drivers are mysql, postgres, sqlite, and sqlserver", config.Driver)
 }

Likely invalid or redundant comment.

database/gorm/dialector_test.go (5)

Line range hint 1-15: LGTM: Import statements are appropriate

The import statements include all necessary packages for testing and database drivers. The use of the assert package from testify is a good choice for writing clear and concise test assertions.


17-27: LGTM: Well-structured table-driven test

The TestGetDialectors function uses a table-driven test approach, which is an excellent practice for testing multiple scenarios efficiently. The structure of the test cases is clear and includes all necessary information for each test.


99-111: LGTM: Well-implemented test execution loop

The test execution loop is well-structured, using t.Run for each test case, which allows for clear separation and identification of individual test results. The assertions are appropriate for both error cases and successful dialector creation cases.


102-109: LGTM: Appropriate assertions with previous comment addressed

The assertions in the test execution loop are well-chosen:

  • assert.EqualError is correctly used for error cases, addressing the previous comment about comparing error messages.
  • assert.NoError, assert.Len, and assert.True are appropriately used for successful cases.

This ensures that both error handling and successful dialector creation are properly verified.


Line range hint 1-111: LGTM: Excellent refactoring of dialector tests

This refactoring of the dialector tests represents a significant improvement:

  1. The table-driven test approach enhances readability and maintainability.
  2. Test cases cover multiple scenarios, including error cases and different database types.
  3. Assertions are appropriate and address previous comments.
  4. The overall structure is clean and follows good testing practices.

These changes will make it easier to maintain and extend the tests in the future. Great job on improving the test quality!

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

@hwbrzzl hwbrzzl merged commit aeaf75d into master Oct 1, 2024
11 of 12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/optimize-orm-dependency branch October 1, 2024 23:59
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