-
Notifications
You must be signed in to change notification settings - Fork 105
feat: [#280] Manage migrations table #664
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
Conversation
WalkthroughThe pull request introduces several enhancements across multiple files in the migration package. Key changes include the addition of new methods and structs, updates to existing method signatures to include error handling, and the removal of certain fields to streamline functionality. Notably, a new Changes
Possibly related PRs
Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
⚠️ Performance Alert ⚠️
Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.
| Benchmark suite | Current: f77315b | Previous: aeaf75d | Ratio |
|---|---|---|---|
Benchmark_Panic |
0.001043 ns/op 0 B/op 0 allocs/op |
0.0006658 ns/op 0 B/op 0 allocs/op |
1.57 |
Benchmark_Panic - ns/op |
0.001043 ns/op |
0.0006658 ns/op |
1.57 |
This comment was automatically generated by workflow using github-action-benchmark.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 13
🧹 Outside diff range and nitpick comments (4)
contracts/database/migration/grammar.go (1)
12-13: LGTM! Consider enhancing the comment for clarity.The new
CompileTablesmethod is a great addition to theGrammarinterface. It fits well with the existing methods and follows consistent naming conventions.To improve clarity, consider expanding the comment slightly:
- // CompileTables Compile the query to determine the tables. + // CompileTables Compile the query to determine the tables in the specified database. + // Returns a string representing the compiled SQL query.This enhancement provides more context about the method's behavior and the nature of the returned string.
contracts/database/migration/repository.go (1)
10-29: Excellent updates to theRepositoryinterface.The changes to the
Repositoryinterface significantly improve its clarity and robustness:
- All methods now have explicit return types, including proper error handling.
- The use of the
Filestruct in return types provides a clear structure for migration data.- The
Logmethod's batch parameter is now anint, which is more appropriate for representing batch numbers.These updates align well with the PR objectives of improving migration management.
Consider adding godoc comments for the
Filestruct and its fields to improve documentation.database/migration/blueprint.go (1)
Line range hint
91-94: LGTM: GetTableName method updated to usetablefield.The
GetTableNamemethod has been correctly updated to user.tableinstead ofr.schema, which is consistent with the previous changes. This ensures that the table name is correctly generated.There's a TODO comment about adding schema support for Postgres. Would you like me to create a GitHub issue to track this task for future implementation?
database/migration/repository_test.go (1)
22-22: Improve the skip message for clarityThe message
"Skipping tests of using docker"can be rephrased for better readability.Consider updating the message as follows:
- t.Skip("Skipping tests of using docker") + t.Skip("Skipping tests that use Docker")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (5)
mocks/database/migration/Connection.gois excluded by!mocks/**mocks/database/migration/Grammar.gois excluded by!mocks/**mocks/database/migration/Migration.gois excluded by!mocks/**mocks/database/migration/Repository.gois excluded by!mocks/**mocks/database/migration/Schema.gois excluded by!mocks/**
📒 Files selected for processing (11)
- contracts/database/migration/grammar.go (1 hunks)
- contracts/database/migration/repository.go (1 hunks)
- contracts/database/migration/schema.go (3 hunks)
- database/migration/blueprint.go (1 hunks)
- database/migration/grammars/postgres.go (1 hunks)
- database/migration/repository.go (1 hunks)
- database/migration/repository_test.go (1 hunks)
- database/migration/respository.go (0 hunks)
- database/migration/schema.go (2 hunks)
- database/migration/schema_test.go (2 hunks)
- database/service_provider.go (1 hunks)
💤 Files with no reviewable changes (1)
- database/migration/respository.go
🔇 Additional comments (27)
contracts/database/migration/repository.go (2)
3-7: LGTM: Well-structuredFilestruct for migration entries.The
Filestruct is well-designed with appropriate fields and types for representing migration entries. Its exported status allows for use in other packages, which is suitable for this context.
1-29: Well-structured and consistent file.The overall file structure is clean and well-organized. The changes maintain consistency with the existing code style, and there are no apparent issues with imports or package-level declarations.
database/service_provider.go (2)
Line range hint
1-73: Consider documenting the migration system changesThe simplification of the schema initialization in this file appears to be part of a larger refactoring effort in the migration system. While this change looks good, it's important to ensure that it doesn't inadvertently break any existing functionality.
Consider updating the package documentation or README to reflect these changes in the migration system, explaining the new approach to schema initialization.
Ensure that all related tests have been updated to reflect this new initialization method.
If this change is part of a breaking change or significant update, consider mentioning it in the CHANGELOG or upgrade guide for the framework.
Let's check for any related test files that might need updating:
#!/bin/bash # Description: Find test files related to schema initialization # Test: Search for test files that might be affected by this change rg --type go -l 'TestNewSchema|TestSchemaInitialization'This will help ensure that all relevant tests are updated to match the new implementation.
39-39: Approve change with verification requestThe simplification of the
NewSchemafunction call looks good. It aligns with the PR objective of improving migration management. However, we should verify that this change is compatible with themigrationpackage implementation.
- Please add a comment explaining the reason for this change, e.g.:
// Simplified schema initialization by passing config directly instead of creating a blueprint return migration.NewSchema(config, connection, log, orm), nil
- Let's verify the
NewSchemafunction signature in themigrationpackage:This will help ensure that the change is consistent with the
migrationpackage implementation.✅ Verification successful
Change Verified Successfully
The updated
NewSchemafunction call indatabase/service_provider.goaligns with the current implementation in themigrationpackage. The removal of theblueprintparameter is consistent with theNewSchemafunction signature.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the NewSchema function signature in the migration package # Test: Check the NewSchema function signature ast-grep --lang go --pattern 'func NewSchema($config, $connection, $log, $orm) $_ { $$$ }'Length of output: 216
Script:
#!/bin/bash # Description: Verify the NewSchema function signature in the migration package # Test: Check the NewSchema function signature ast-grep --lang go --pattern 'func NewSchema($config, $connection, $log, $orm) $_ { $$$ }'Length of output: 94
Script:
#!/bin/bash # Description: List all NewSchema function definitions in the migration package rg --type go 'func NewSchema' -A2Length of output: 566
database/migration/blueprint.go (3)
27-31: LGTM: NewBlueprint function updated to usetableparameter.The
NewBlueprintfunction has been correctly updated to usetableinstead ofschema, which is consistent with the changes in theBlueprintstruct. This modification ensures that thetablefield is properly initialized.To ensure all calls to
NewBlueprinthave been updated, please run the following script:#!/bin/bash # Search for all calls to NewBlueprint in the codebase rg --type go 'NewBlueprint\('Review the results to confirm that all calls to
NewBlueprinthave been updated to provide the correct arguments (prefix and table).
Line range hint
1-265: Overall LGTM: Blueprint implementation updated to usetableinstead ofschema.The changes in this file are consistent and align well with the PR objectives. The
Blueprintstruct,NewBlueprintfunction, andGetTableNamemethod have all been updated to usetableinstead ofschema, which simplifies the table name handling process.To ensure these changes don't introduce any regressions:
- Run the existing test suite, paying special attention to any tests related to migrations or table creation.
- Consider adding new test cases that specifically verify the behavior of the updated
Blueprintimplementation with various table names.- Perform integration tests to ensure that the migration process works correctly with these changes.
#!/bin/bash # Run the test suite go test ./...If all tests pass and the suggested verifications are successful, this change is ready for merge.
Line range hint
19-24: LGTM: Blueprint struct updated to usetableinstead ofschema.The change from
schematotablein theBlueprintstruct aligns with the PR objectives for managing the migrations table. This modification simplifies the table name handling process.To ensure this change doesn't break existing functionality, please run the following script to check for any remaining references to the
schemafield in the codebase:If the script returns any results, those occurrences should be reviewed and updated accordingly.
contracts/database/migration/schema.go (3)
9-9:⚠️ Potential issueEnsure implementations of
DropIfExistsare updated due to signature changeThe
DropIfExistsmethod now returns anerror, modifying theSchemainterface and potentially breaking existing implementations. All implementations must be updated to include theerrorreturn value to satisfy the interface.Run the following script to find implementations of
DropIfExiststhat may not have been updated:#!/bin/bash # Description: Find implementations of the Schema interface with the old DropIfExists method signature. # Search for structs that implement Schema interface rg --type go 'type (\w+) struct' -o -r '$1' | while read -r struct_name; do # Find files where the DropIfExists method is defined for the struct rg --type go "func \(\*${struct_name}\) DropIfExists\(.*\)" -l | while read -r file; do # Check if the DropIfExists method returns an error if ! rg "func \(\*${struct_name}\) DropIfExists\(.*\) error" "$file" -q; then echo "DropIfExists method in $file may not return error" fi done done
11-13:⚠️ Potential issueAdding methods to an interface can introduce breaking changes
The addition of
GetTables()andHasTable(table string) boolmethods to theSchemainterface changes the interface's contract. Existing implementations will not satisfy the interface unless they implement these new methods, which can lead to compilation errors.Consider whether these methods should be added to a new interface or ensure that all existing implementations are updated to include these methods.
Run the following script to identify implementations missing these methods:
#!/bin/bash # Description: Find implementations of the Schema interface missing new methods. # Search for structs that implement Schema interface rg --type go 'type (\w+) struct' -o -r '$1' | while read -r struct_name; do file=$(rg --files-with-matches "type ${struct_name} struct") missing_methods=() # Check for GetTables method if ! rg "func \(\*${struct_name}\) GetTables\(\)" "$file" -q; then missing_methods+=("GetTables") fi # Check for HasTable method if ! rg "func \(\*${struct_name}\) HasTable\(table string\)" "$file" -q; then missing_methods+=("HasTable") fi if [ ${#missing_methods[@]} -ne 0 ]; then echo "Struct ${struct_name} in $file is missing methods: ${missing_methods[*]}" fi done
5-5:⚠️ Potential issueBe cautious of breaking changes due to method signature alteration
Changing the
Createmethod to return anerrormodifies theSchemainterface and introduces a breaking change. Existing implementations of theSchemainterface will no longer satisfy the interface unless they are updated to include theerrorreturn value. Please ensure that all implementations are updated accordingly, and consider the impact on any external users who may implement this interface.Run the following script to identify implementations of the
Schemainterface that may not have updated theCreatemethod signature:database/migration/schema_test.go (7)
8-12: Imports are appropriate and necessaryThe imported packages, including
dockerandenv, are relevant for the new testing approach and support the test suite effectively.
18-18: Effective mapping withdriverToTestQueryDefining
driverToTestQueryas a map ofdatabase.Driverto*gorm.TestQueryenhances flexibility and prepares the test suite for multiple database drivers.
38-40: Good structure for scalable testingIterating over
driverToTestQuerywiths.Runfacilitates the addition of more database drivers in the future, making the test suite easily extensible.
45-49: Verify mock expectations forQuerymethodThe expectation
mockOrm.EXPECT().Query().Return(testQuery.Query()).Twice()assumes that theQuerymethod will be called twice withinschema.DropIfExistsandschema.Create. Ensure that these methods indeed callQuerytwice to match the expectation; otherwise, the test may fail due to unmet expectations.
51-52: Appropriate assertion withHasTableUsing
s.True(schema.HasTable(table))correctly verifies that the table has been created successfully.
54-56: Consistency in setting mock expectations forConnectionYou have set
mockOrm.EXPECT().Connection(schema.connection).Return(mockOrm).Once(). Ensure that this matches the actual number of timesConnectionis called withinschema.DropIfExists. IfConnectionis called more than once, adjust the expectation accordingly to prevent test failures.
64-68: Initialization ofSchemawith mock configurationsThe
initSchemafunction properly initializes theSchemausingtestQuery.MockConfig()and the driver string, ensuring that the schema is set up with the correct configurations for testing.database/migration/repository.go (8)
8-12: Struct fields are appropriately defined.The
Repositorystruct fields are clearly defined and suitable for managing migrations.
14-20: Constructor function correctly initializes Repository.The
NewRepositoryfunction properly initializes theRepositorystruct with the provided parameters.
30-34: Proper error handling in Delete method.The
Deletemethod correctly handles errors by returning any encountered error.
40-47: Verify handling of zero batch numbers in GetLast method.In the
GetLastmethod, when there are no migrations,getLastBatchNumber()returns0, causing the query to filter withbatch = 0. Please verify if batch number0is valid in your context or adjust the logic to handle cases when no batches exist.You can check if batches start from
1and modify the method accordingly. For example:func (r *Repository) getLastBatchNumber() int { var batch int if err := r.query.Table(r.table).OrderByDesc("batch").Limit(1).Pluck("batch", &batch); err != nil { - return 0 + return 0 // Or possibly return -1 to indicate no batches exist } return batch }
71-78: Consistent ordering in GetRan method.The
GetRanmethod orders migrations bybatchandmigration, which provides a consistent execution order.
80-85: Logging method is correctly implemented.The
Logmethod correctly inserts a new migration record into the migration table with the appropriate fields.
87-89: RepositoryExists method properly checks for table existence.The
RepositoryExistsmethod accurately checks if the migration table exists usingschema.HasTable.
49-56:⚠️ Potential issueEnsure GetMigrations retrieves complete batches as per steps.
The
GetMigrationsmethod usesLimit(steps), which may not retrieve all migrations in the laststepsbatches if multiple migrations exist per batch. Consider fetching all migrations from the laststepsbatches to ensure consistency.You might adjust the query to:
func (r *Repository) GetMigrations(steps int) ([]migration.File, error) { var files []migration.File + lastBatchNumber := r.getLastBatchNumber() + targetBatchNumber := lastBatchNumber - steps + 1 if err := r.query.Table(r.table). - Where("batch >= 1"). + Where("batch >= ?", targetBatchNumber). OrderByDesc("batch"). OrderByDesc("migration"). - Limit(steps). Get(&files); err != nil { return nil, err } return files, nil }This adjustment ensures you retrieve all migrations from the last
stepsbatches.database/migration/schema.go (1)
99-101: Verify error propagation in thebuildmethodThe
buildmethod returns an error fromblueprint.Build(...). Ensure that any errors returned by this method are appropriately handled by the calling functions to prevent unhandled exceptions during the migration process.database/migration/repository_test.go (1)
71-76: Ensure repository existence check is reliableThe condition
if !repository.RepositoryExists()might lead to flaky tests if the repository state is not properly cleaned up between tests. Ensure that the repository state is consistent at the start of each test.Consider resetting the repository or ensuring isolation between tests. You can verify the repository state with the following script:
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #664 +/- ##
==========================================
+ Coverage 70.27% 70.44% +0.16%
==========================================
Files 187 187
Lines 11896 11944 +48
==========================================
+ Hits 8360 8414 +54
+ Misses 2963 2948 -15
- Partials 573 582 +9 ☔ View full report in Codecov by Sentry. |
There was a problem hiding this 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 (3)
database/migration/repository_test.go (3)
15-26: LGTM: Test suite structure is well-defined.The
RepositoryTestSuiteandTestRepositoryTestSuiteare correctly set up. Skipping tests on Windows due to Docker limitations is a good practice.Consider adding a comment explaining why tests are skipped on Windows for better clarity:
if env.IsWindows() { t.Skip("Skipping tests that use Docker due to limitations on Windows") }
64-129: LGTM: TestRecord method is comprehensive and well-implemented.This test method thoroughly covers various repository operations, including logging migrations, retrieving batch numbers, and managing migration records. The structure allows for testing with multiple database drivers, and proper error checking is implemented throughout.
Consider adding a test case for the scenario where
GetMigrationsis called with a limit greater than the total number of migrations to ensure it handles this edge case correctly.
1-135: Overall, the test file is well-structured and provides good coverage.The test suite effectively covers the main repository operations and uses appropriate mocking techniques to isolate the repository from the actual database. The structure allows for easy extension to multiple database drivers in the future.
To further improve the test file:
- Extend coverage to include more database drivers (MySQL, SQLite) as previously suggested.
- Implement error handling for the
initSchemafunction ininitRepository.- Consider adding edge cases, such as testing
GetMigrationswith a limit exceeding the total number of migrations.- Add comments explaining the purpose of each test method for better readability.
These improvements will enhance the robustness and maintainability of the test suite.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (5)
mocks/database/migration/Connection.gois excluded by!mocks/**mocks/database/migration/Grammar.gois excluded by!mocks/**mocks/database/migration/Migration.gois excluded by!mocks/**mocks/database/migration/Repository.gois excluded by!mocks/**mocks/database/migration/Schema.gois excluded by!mocks/**
📒 Files selected for processing (11)
- contracts/database/migration/grammar.go (1 hunks)
- contracts/database/migration/repository.go (1 hunks)
- contracts/database/migration/schema.go (3 hunks)
- database/migration/blueprint.go (1 hunks)
- database/migration/grammars/postgres.go (1 hunks)
- database/migration/repository.go (1 hunks)
- database/migration/repository_test.go (1 hunks)
- database/migration/respository.go (0 hunks)
- database/migration/schema.go (2 hunks)
- database/migration/schema_test.go (2 hunks)
- database/service_provider.go (1 hunks)
💤 Files with no reviewable changes (1)
- database/migration/respository.go
🚧 Files skipped from review as they are similar to previous changes (6)
- contracts/database/migration/grammar.go
- contracts/database/migration/repository.go
- database/migration/blueprint.go
- database/migration/grammars/postgres.go
- database/migration/repository.go
- database/service_provider.go
🔇 Additional comments (19)
contracts/database/migration/schema.go (5)
5-5: LGTM: Improved error handling in Create methodThe addition of an error return to the
Createmethod is a good improvement. It allows for better error handling and follows Go's idiomatic approach to dealing with potential failures in operations.
9-9: LGTM: Consistent error handling in DropIfExists methodThe addition of an error return to the
DropIfExistsmethod is consistent with theCreatemethod change and improves error handling capabilities. This change enhances the robustness of the schema operations.
10-11: LGTM: New GetTables method enhances schema functionalityThe addition of the
GetTablesmethod is a valuable enhancement to theSchemainterface. It provides a way to retrieve all tables in the database, returning a slice ofTablestructs along with an error for proper error handling. This method will be useful for migration management as mentioned in the PR objectives.
12-13: 🛠️ Refactor suggestionConsider returning an error along with the boolean in
HasTableWhile the addition of the
HasTablemethod is beneficial, it's worth reconsidering its signature. As mentioned in a previous review, database operations can fail due to various issues (e.g., connectivity problems). Returning an error along with the boolean can help handle such cases more gracefully.Consider changing the method signature to
HasTable(table string) (bool, error).
31-34: 🛠️ Refactor suggestionConsider renaming
Connectioninterface andTablestruct to avoid potential naming conflictsWhile the addition of the
Connectioninterface andTablestruct enhances the migration functionality, their names might lead to potential conflicts:
The
Connectioninterface might conflict with other packages or standard library types using the same name. Consider a more specific name likeMigrationConnectionorSchemaConnection.The
Tablestruct might conflict with other types namedTablein the codebase or imported packages. Consider renaming it to something more specific likeSchemaTableorMigrationTable.These renamings would improve clarity and reduce the risk of naming collisions.
Also applies to: 51-55
database/migration/schema.go (7)
23-23: LGTM: Schema struct modificationThe removal of the
blueprintfield and addition of theprefixfield appear to be part of a refactoring to improve the handling of table prefixes. This change aligns well with the overall modifications in the file.
26-37: LGTM: NewSchema function updateThe changes to the
NewSchemafunction are consistent with theSchemastruct modifications. Retrieving theprefixfrom the configuration provides more flexibility and centralizes the prefix management.
42-42: LGTM: Connection method simplificationThe
Connectionmethod has been simplified to align with the updatedNewSchemafunction signature. This change maintains consistency across the codebase.
62-70: LGTM: Well-implementedGetTablesmethodThe
GetTablesmethod is well-implemented with proper error handling. It uses the ORM to execute a raw SQL query generated by the grammar'sCompileTablesmethod, which allows for database-specific SQL generation. This approach is flexible and maintainable.
45-52:⚠️ Potential issueImplement error handling and rollback in the
CreatemethodThe
Createmethod has been updated to return an error, which is a good practice. However, the TODO comment indicates that error handling and rollback functionality are not yet implemented. To ensure data integrity during migrations, it's crucial to implement proper error handling and transaction management.Consider implementing the following:
- Wrap the operations in a transaction.
- If an error occurs during the build process, rollback the transaction.
- If successful, commit the transaction.
This will help prevent partial migrations in case of failures.
Would you like assistance in implementing the error handling and rollback logic?
54-60:⚠️ Potential issueImplement error handling in the
DropIfExistsmethodThe
DropIfExistsmethod has been added with a structure similar to theCreatemethod. However, the TODO comment indicates that error handling is not yet implemented. To maintain database consistency, it's important to implement proper error handling for this operation as well.Consider implementing the following:
- Wrap the operation in a transaction.
- If an error occurs during the build process, rollback the transaction.
- If successful, commit the transaction.
This will help handle potential failures during the drop operation and maintain database consistency.
Would you like assistance in implementing the error handling logic?
71-87: 🛠️ Refactor suggestionConsider propagating errors in the
HasTablemethodCurrently, if
GetTables()returns an error, theHasTablemethod logs the error and returnsfalse. This approach may mask underlying issues and lead to incorrect assumptions about the existence of tables. Consider modifying the method to return an error along with the boolean result. This will allow calling functions to handle errors appropriately.Apply this diff to adjust the method signature and error handling:
-func (r *Schema) HasTable(name string) bool { +func (r *Schema) HasTable(name string) (bool, error) { blueprint := r.createBlueprint(name) tableName := blueprint.GetTableName() tables, err := r.GetTables() if err != nil { - r.log.Errorf("failed to get %s tables: %v", r.connection, err) - return false + return false, fmt.Errorf("failed to get %s tables: %w", r.connection, err) } for _, table := range tables { if table.Name == tableName { - return true + return true, nil } } - return false + return false, nil }database/migration/repository_test.go (4)
1-13: LGTM: Package declaration and imports are appropriate.The package name and imports are correctly set up for testing the migration repository. All imported packages are used in the test file.
28-34: LGTM: SetupTest method is correctly implemented for PostgreSQL.The
SetupTestmethod properly initializes a PostgreSQL Docker instance and test query.As previously suggested, consider extending test coverage to include more database drivers like MySQL and SQLite to enhance the test suite's comprehensiveness.
36-62: LGTM: TestCreate_Delete_Exists method is comprehensive and well-structured.This test method effectively covers the creation, existence check, and deletion operations of the repository. The use of mock expectations for the ORM ensures proper verification of interactions. The structure allows for easy extension to multiple database drivers in the future.
131-135:⚠️ Potential issueHandle potential errors from
initSchemafunction.The
initRepositorymethod correctly initializes a repository instance and its mock ORM. However, as previously noted, the error returned byinitSchemais not being handled.Modify the function to handle errors appropriately:
-func (s *RepositoryTestSuite) initRepository(testQuery *gorm.TestQuery) (*Repository, *mocksorm.Orm) { - schema, mockOrm := initSchema(s.T(), testQuery) +func (s *RepositoryTestSuite) initRepository(testQuery *gorm.TestQuery) (*Repository, *mocksorm.Orm, error) { + schema, mockOrm, err := initSchema(s.T(), testQuery) + if err != nil { + return nil, nil, err + } - return NewRepository(testQuery.Query(), schema, "migrations"), mockOrm + return NewRepository(testQuery.Query(), schema, "migrations"), mockOrm, nil }Remember to update the calls to
initRepositoryin the test methods to handle the returned error.database/migration/schema_test.go (3)
Line range hint
18-34: Well-structured refactoring of test initializationThe shift from
driverToTestDBtodriverToTestQueryin theSchemaSuitestruct simplifies the test setup and enhances clarity. Initializing the test queries inSetupTestprovides a more streamlined and maintainable approach.
38-59: Comprehensive testing ofDropIfExistsandHasTablemethodsThe updated
TestDropIfExistsmethod effectively tests the creation, existence, and deletion of tables using theschemaobject. Iterating over thedriverToTestQuerymap ensures that the tests are prepared to accommodate multiple database drivers.
64-68: Proper initialization of theSchemaobjectThe
initSchemafunction correctly initializes theSchemaobject with the appropriate configurations and mock ORM. PassingtestQuery.MockConfig()andtestQuery.Docker().Driver().String()ensures that the schema is set up with the correct settings for the tests.
kkumar-gcc
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
📑 Description
goravel/goravel#280
GetTablesandHasTable;Summary by CodeRabbit
New Features
CompileTables,GetTables, andHasTable.CreateandDropIfExists.Fileadded to enhance migration functionality.BlueprintandSchemastructures for improved clarity.Bug Fixes
Tests
Chores
✅ Checks