Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [#280] Refactor database migrate - optimize make:migration command #606

Merged
merged 6 commits into from
Aug 21, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Aug 21, 2024

📑 Description

Issue: goravel/goravel#280

  1. Optimize the make:migration command, supports two drivers: default and sql.
  2. Add facades.Schema().
  3. The new migration file will be:
// 20240817105351_create_users_table.go
package migrations

type M20240817105351CreateUsersTable struct {
}

// Signature The unique signature for the migration.
func (r *M20240817105351CreateUsersTable) Signature() string {
	return "20240817105351_create_users_table"
}

// Connection The database connection that should be used by the migration.
func (r *M20240817105351CreateUsersTable) Connection() string {
	return ""
}

// Up Run the migrations.
func (r *M20240817105351CreateUsersTable) Up() {

}

// Down Reverse the migrations.
func (r *M20240817105351CreateUsersTable) Down() {

}

Summary by CodeRabbit

  • New Features

    • Introduced a migration package for managing database drivers, enhancing extensibility.
    • Added a Schema interface for structured management of database schemas and migrations.
    • Implemented a DefaultDriver for dynamic creation of migration files.
    • Introduced SqlDriver for managing SQL migrations with specific templates for various databases.
    • Enhanced the MigrateMakeCommand with a driver-based approach for migration creation.
  • Bug Fixes

    • Enhanced error handling in the migration creation logic to ensure robustness.
  • Documentation

    • New test suites added for DefaultDriver, SqlDriver, and MigrateMakeCommand, ensuring correct functionality and file generation.
  • Chores

    • Refactored service provider to support schema management through dependency injection.
    • Restructured tests for improved organization and maintainability.

✅ Checks

  • Added test cases for my code

@hwbrzzl hwbrzzl requested a review from a team as a code owner August 21, 2024 10:48
Copy link
Contributor

coderabbitai bot commented Aug 21, 2024

Walkthrough

The recent changes enhance the migration framework by introducing a comprehensive package for managing database schemas and drivers. Key improvements include the establishment of interfaces for schema and migration management, the implementation of default and SQL drivers, and schema functionalities integrated into the service provider. Additionally, new test suites validate functionality, contributing to a robust architecture for effectively handling database migrations.

Changes

Files Change Summary
contracts/database/migration/..., contracts/database/schema/... Introduced migration and schema packages with interfaces for managing database drivers and schemas, promoting extensibility and modularity in handling database operations.
contracts/foundation/container.go Added the MakeSchema method to the Container interface for resolving instances of schema.Schema, enhancing schema management capabilities.
database/console/migrate_creator.go, database/console/migrate_make_command.go Modified receiver types to pointer receivers in MigrateCreator methods for state modification; improved migration file creation logic using a driver-based approach, enhancing clarity and maintainability.
database/migration/default_driver.go, database/migration/sql_driver.go Implemented DefaultDriver and SqlDriver types for managing migration file creation with structured methods for populating and managing SQL commands.
database/migration/default_driver_test.go, database/migration/sql_driver_test.go Added comprehensive test suites for DefaultDriver and SqlDriver, ensuring proper functionality and validation of migration file creation across various database systems.
database/migration/stubs.go, database/migration/table_guesser.go, database/migration/schema.go Restructured stub management and table guessing functionality, enhancing the migration process with a clear architecture for future development.
database/service_provider.go Introduced a new singleton binding for schema management, allowing the service provider to manage database schemas alongside ORM and seeder functionalities.
facades/schema.go Added a facade for simplified access to schema functionalities, promoting modularity and clean organization within the codebase.
database/console/migrate_make_command_test.go Enhanced the test setup in TestMigrateMakeCommand with organized structures for test cases, improving clarity and maintainability while ensuring comprehensive coverage of migration scenarios.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

devhaozi
devhaozi previously approved these changes Aug 21, 2024
Copy link
Member

@devhaozi devhaozi left a comment

Choose a reason for hiding this comment

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

LGTM

@hwbrzzl hwbrzzl closed this Aug 21, 2024
@hwbrzzl hwbrzzl reopened this Aug 21, 2024
@hwbrzzl hwbrzzl enabled auto-merge (squash) August 21, 2024 10:57
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: 6

Outside diff range, codebase verification and nitpick comments (1)
database/migration/default_driver.go (1)

66-68: Consider error handling for os.Getwd.

Currently, the error from os.Getwd is ignored. Consider handling it to avoid potential issues.

Use this diff to handle the error:

- pwd, _ := os.Getwd()
+ pwd, err := os.Getwd()
+ if err != nil {
+     return ""
+ }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 93a3ea5 and fde45bb.

Files ignored due to path filters (6)
  • mocks/database/migration/Driver.go is excluded by !mocks/**
  • mocks/database/schema/Blueprint.go is excluded by !mocks/**
  • mocks/database/schema/Migration.go is excluded by !mocks/**
  • mocks/database/schema/Schema.go is excluded by !mocks/**
  • mocks/foundation/Application.go is excluded by !mocks/**
  • mocks/foundation/Container.go is excluded by !mocks/**
Files selected for processing (17)
  • contracts/database/migration/migration.go (1 hunks)
  • contracts/database/schema/blueprint.go (1 hunks)
  • contracts/database/schema/schema.go (1 hunks)
  • contracts/foundation/container.go (2 hunks)
  • database/console/migrate_creator.go (5 hunks)
  • database/console/migrate_make_command.go (2 hunks)
  • database/migration/default_driver.go (1 hunks)
  • database/migration/default_driver_test.go (1 hunks)
  • database/migration/schema.go (1 hunks)
  • database/migration/sql_driver.go (1 hunks)
  • database/migration/sql_driver_test.go (1 hunks)
  • database/migration/stubs.go (1 hunks)
  • database/migration/table_guesser.go (1 hunks)
  • database/migration/table_guesser_test.go (1 hunks)
  • database/service_provider.go (2 hunks)
  • facades/schema.go (1 hunks)
  • foundation/container.go (2 hunks)
Files skipped from review due to trivial changes (4)
  • contracts/database/migration/migration.go
  • contracts/database/schema/blueprint.go
  • database/migration/table_guesser.go
  • database/migration/table_guesser_test.go
Additional comments not posted (22)
facades/schema.go (1)

7-9: LGTM!

The Schema function correctly retrieves a schema instance using dependency injection.

contracts/database/schema/schema.go (2)

3-16: Interfaces are well-defined.

The Schema interface provides a clear contract for schema operations. Consider implementing or removing commented-out methods if not needed.


18-27: Interfaces are well-defined.

The Migration interface provides a clear contract for migration operations.

database/service_provider.go (2)

14-14: LGTM!

The addition of BindingSchema enhances the service provider's capabilities by allowing schema management.


32-34: LGTM!

The registration of the schema singleton is correctly implemented.

database/migration/default_driver.go (2)

21-41: LGTM!

The Create method is well-structured, handling file creation and template population.


71-73: LGTM!

The getFileName method correctly formats the file name with a timestamp.

database/console/migrate_make_command.go (2)

62-72: Ensure all migration drivers are covered.

The switch statement handles DriverDefault and DriverSql. Ensure that all necessary drivers are covered and consider logging unsupported drivers for better debugging.

Consider adding logging for unsupported drivers:

default:
	fmt.Printf("Unsupported migration driver: %s\n", driver)
	return fmt.Errorf("unsupported migration driver: %s", driver)

75-75: Check error handling for migration creation.

Ensure that the error returned by migrationDriver.Create(name) is properly logged or handled to aid in debugging.

Consider adding logging for errors:

if err := migrationDriver.Create(name); err != nil {
	fmt.Printf("Error creating migration: %s\n", err)
	return err
}
database/console/migrate_creator.go (4)

Line range hint 26-42: Appropriate use of pointer receiver.

Using a pointer receiver allows the method to modify the receiver's state, which is appropriate for this method.


Line range hint 46-76: Clear and correct stub retrieval logic.

The method correctly references the migration package for stub retrieval, improving clarity and maintainability.


Line range hint 81-89: Correct and efficient placeholder population.

The method efficiently populates placeholders in the stub, ensuring correct configuration values are used.


Line range hint 92-99: Correct path construction logic.

The method constructs the migration file path correctly, using the current working directory and formatted timestamps.

database/migration/sql_driver.go (4)

25-47: Ensure robust error handling in Create method.

The Create method should handle errors robustly, especially when dealing with file operations.

Consider adding logging for errors:

if err := file.Create(r.getPath(name, "up"), r.populateStub(upStub, table)); err != nil {
	fmt.Printf("Error creating up.sql: %s\n", err)
	return err
}

if err := file.Create(r.getPath(name, "down"), r.populateStub(downStub, table)); err != nil {
	fmt.Printf("Error creating down.sql: %s\n", err)
	return err
}

49-82: Correct stub retrieval logic.

The method correctly retrieves stubs based on the database driver and operation type, ensuring accurate migration templates.


84-93: Efficient placeholder population in populateStub.

The method efficiently replaces placeholders in the stub with configuration values, ensuring correct migration scripts.


95-100: Correct path construction in getPath.

The method constructs the migration file path correctly, using the current working directory and formatted timestamps.

database/migration/default_driver_test.go (1)

14-127: Comprehensive test coverage for DefaultDriverCreate.

The test cases comprehensively cover various migration scenarios, ensuring the Create method functions as expected.

contracts/foundation/container.go (1)

74-75: Appropriate addition of MakeSchema method.

The MakeSchema method aligns with the Container interface's purpose, enhancing its functionality by managing schema-related operations.

database/migration/stubs.go (1)

1-90: LGTM!

The restructuring of the codebase and the introduction of the Stubs type with methods for migration templates are well-structured and improve maintainability.

database/migration/sql_driver_test.go (1)

1-209: LGTM!

The test cases are comprehensive and well-structured, providing thorough coverage for different database types and scenarios.

foundation/container.go (1)

259-267: LGTM!

The addition of the MakeSchema method is well-implemented and aligns with the existing design pattern for instance creation.

Comment on lines +13 to +16
func (r *Schema) Create(table string, callback func(table schema.Blueprint)) error {
//TODO implement me
panic("implement me")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Implement the Create method.

The method is currently a placeholder with a TODO comment and a panic statement.

Would you like assistance in implementing this method?

Comment on lines +18 to +21
func (r *Schema) Connection() schema.Schema {
//TODO implement me
panic("implement me")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Implement the Connection method.

The method is currently a placeholder with a TODO comment and a panic statement.

Would you like assistance in implementing this method?

Comment on lines +23 to +26
func (r *Schema) Register(migrations []schema.Migration) {
//TODO implement me
panic("implement me")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Implement the Register method.

The method is currently a placeholder with a TODO comment and a panic statement.

Would you like assistance in implementing this method?

Comment on lines +28 to +31
func (r *Schema) Table(table string, callback func(table schema.Blueprint)) error {
//TODO implement me
panic("implement me")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Implement the Table method.

The method is currently a placeholder with a TODO comment and a panic statement.

Would you like assistance in implementing this method?

`
}

// TODO add the facades.Schema().Create() method
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Implement facades.Schema().Create() method.

The TODO comment indicates that this method needs to be added to complete the functionality.

Do you want me to generate a stub for this method or open a GitHub issue to track this task?

`
}

// TODO add the facades.Schema().Table() method
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Implement facades.Schema().Table() method.

The TODO comment indicates that this method needs to be added to complete the functionality.

Do you want me to generate a stub for this method or open a GitHub issue to track this task?

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fde45bb and 532064a.

Files selected for processing (1)
  • database/console/migrate_make_command_test.go (1 hunks)
Additional comments not posted (8)
database/console/migrate_make_command_test.go (8)

26-29: Good practice: Use of beforeEach function.

The beforeEach function effectively initializes mock objects, reducing redundancy and improving test readability.


31-34: Good practice: Use of afterEach function.

The afterEach function ensures that all expectations on mock objects are verified, which is crucial for maintaining test integrity.


36-41: Well-structured test case definition.

The use of a structured slice of structs for test cases enhances readability and maintainability, making it easier to add or modify tests.


42-50: Comprehensive test for empty migration name.

The test correctly handles the scenario where the migration name is empty, ensuring that the appropriate error is returned.


51-61: Thorough test for default driver scenario.

The test case for the default driver ensures that the migration file is created as expected, verifying the integration with the file system.


63-78: Comprehensive test for SQL driver scenario.

The test case for the SQL driver covers multiple configuration settings and checks for both up and down migration files, ensuring robust coverage.


82-94: Efficient test execution loop.

The loop over test cases is efficiently handled, with clear separation of setup, execution, and assertion phases.


96-96: Clean-up operation with file.Remove.

The use of file.Remove to clean up after tests is a good practice to ensure no residual files affect subsequent tests.

Copy link

codecov bot commented Aug 21, 2024

Codecov Report

Attention: Patch coverage is 70.37037% with 40 lines in your changes missing coverage. Please review.

Project coverage is 70.07%. Comparing base (93a3ea5) to head (532064a).
Report is 1 commits behind head on master.

Files Patch % Lines
database/migration/schema.go 0.00% 10 Missing ⚠️
database/console/migrate_creator.go 41.66% 7 Missing ⚠️
database/migration/sql_driver.go 82.50% 5 Missing and 2 partials ⚠️
foundation/container.go 0.00% 6 Missing ⚠️
database/migration/default_driver.go 83.33% 3 Missing and 1 partial ⚠️
database/console/migrate_make_command.go 70.00% 2 Missing and 1 partial ⚠️
database/service_provider.go 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #606      +/-   ##
==========================================
+ Coverage   69.53%   70.07%   +0.53%     
==========================================
  Files         181      184       +3     
  Lines       11121    11241     +120     
==========================================
+ Hits         7733     7877     +144     
+ Misses       2811     2784      -27     
- Partials      577      580       +3     

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

@hwbrzzl hwbrzzl merged commit 99d173a into master Aug 21, 2024
10 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#280-1 branch August 21, 2024 13:38
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