Skip to content

feat: [#280] Optimize the migrate:fresh command#686

Merged
hwbrzzl merged 10 commits intomasterfrom
bowen/#280-9
Oct 21, 2024
Merged

feat: [#280] Optimize the migrate:fresh command#686
hwbrzzl merged 10 commits intomasterfrom
bowen/#280-9

Conversation

@hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Oct 20, 2024

📑 Description

  1. Add db:wipe command: drop tables, drop views, and drop types;
  2. The migrate:fresh command supports two drivers;
image

Summary by CodeRabbit

  • New Features

    • Introduced a WipeCommand for dropping all database tables, views, and types.
    • Added a ConfirmToProceed function to enhance command execution safety in production environments.
    • Implemented CommonSchema and PostgresSchema types for improved schema management.
    • Added new error messages for various migration and schema operations to enhance user feedback.
  • Bug Fixes

    • Enhanced error handling in various schema and migration methods to ensure proper feedback during operations.
  • Refactor

    • Transitioned from a migration-focused to a schema-focused architecture, including renaming and restructuring of related components.
    • Updated method signatures across multiple files to return errors for better error management.
    • Removed direct console output in favor of using context methods for standardized messaging.
  • Tests

    • Added comprehensive test suites for new schema functionalities and commands, ensuring robust testing coverage.

✅ Checks

  • Added test cases for my code

Copy link

@github-actions github-actions bot left a 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: 92d09d0 Previous: 62d45f5 Ratio
Benchmark_DecryptString 5148 ns/op 1592 B/op 17 allocs/op 2020 ns/op 1592 B/op 17 allocs/op 2.55
Benchmark_DecryptString - ns/op 5148 ns/op 2020 ns/op 2.55
BenchmarkFile_ReadWrite 400788 ns/op 1800 B/op 21 allocs/op 158477 ns/op 1800 B/op 21 allocs/op 2.53
BenchmarkFile_ReadWrite - ns/op 400788 ns/op 158477 ns/op 2.53

This comment was automatically generated by workflow using github-action-benchmark.

@codecov
Copy link

codecov bot commented Oct 20, 2024

Codecov Report

Attention: Patch coverage is 62.84658% with 201 lines in your changes missing coverage. Please review.

Project coverage is 68.99%. Comparing base (62d45f5) to head (92d09d0).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
database/schema/postgres_schema.go 37.93% 52 Missing and 2 partials ⚠️
database/console/wipe_command.go 55.22% 30 Missing ⚠️
database/schema/grammars/postgres.go 74.78% 30 Missing ⚠️
database/service_provider.go 0.00% 23 Missing ⚠️
database/migration/sql_migrator.go 43.33% 15 Missing and 2 partials ⚠️
database/schema/schema.go 64.51% 11 Missing ⚠️
database/migration/default_migrator.go 62.50% 7 Missing and 2 partials ⚠️
database/schema/common_schema.go 47.05% 8 Missing and 1 partial ⚠️
...abase/console/migration/migrate_refresh_command.go 16.66% 5 Missing ⚠️
...atabase/console/migration/migrate_fresh_command.go 72.72% 3 Missing ⚠️
... and 5 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #686      +/-   ##
==========================================
- Coverage   69.30%   68.99%   -0.31%     
==========================================
  Files         189      193       +4     
  Lines       14571    14816     +245     
==========================================
+ Hits        10099    10223     +124     
- Misses       3882     4007     +125     
+ Partials      590      586       -4     

☔ 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 20, 2024 15:24
@hwbrzzl hwbrzzl requested a review from a team as a code owner October 20, 2024 15:24
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2024

Caution

Review failed

The head commit changed during the review from fc5a951 to 92d09d0.

Walkthrough

This pull request introduces significant changes to the database migration and schema management functionalities within the codebase. The migration package has been largely refactored into a schema package, with several interfaces and methods being renamed or restructured. Key changes include the removal of the Driver interface, the introduction of new methods in the Migrator interface, and the addition of a WipeCommand for database cleanup. Error handling has been enhanced across various methods, and new tests have been added to ensure the functionality of the updated schema management system.

Changes

File Path Change Summary
contracts/database/migration/driver.go Deleted file containing Driver interface and constants DriverDefault and DriverSql.
contracts/database/migration/migrator.go Added constants MigratorDefault and MigratorSql; modified Migrator interface by removing unused methods and adding Create(name string) error, Fresh() error, and Run() error.
contracts/database/migration/repository.go Updated CreateRepository and DeleteRepository methods to return error instead of void.
contracts/database/schema/blueprint.go Changed package name from migration to schema; defined Blueprint interface for schema management.
contracts/database/schema/column.go Changed package name from migration to schema; ColumnDefinition interface remains unchanged.
contracts/database/schema/grammar.go Changed package name from migration to schema; added methods for compiling SQL commands related to schema operations.
contracts/database/schema/schema.go Changed package name from migration to schema; updated Schema interface and added CommonSchema and DriverSchema interfaces; enhanced error handling in Create and DropIfExists methods.
contracts/foundation/application.go Updated MakeSchema method to return schema.Schema instead of migration.Schema.
database/console/migration/migrate_command.go Replaced driver field with migrator; updated command handling to use the new migrator interface.
database/console/migration/migrate_fresh_command.go Removed config field; added migrator field; simplified Handle method to directly call r.migrator.Fresh().
database/console/migration/migrate_make_command.go Removed config and schema fields; added migrator field; updated Handle method to use r.migrator.Create(name).
database/console/migration/migrate_reset_command_test.go Updated to utilize migrator instead of mockSchema; enhanced error handling.
database/console/migration/migrate_rollback_command_test.go Updated to utilize migrator instead of mockSchema; enhanced error handling.
database/console/migration/migrate_status_command_test.go Updated to utilize migrator instead of mockSchema; enhanced error handling.
database/console/migration/utils.go Deleted file containing GetDriver function.
database/console/migration/utils_test.go Deleted file containing tests for GetDriver function.
database/console/wipe_command.go Introduced WipeCommand struct for dropping all database tables, views, and types.
database/console/wipe_command_test.go Added tests for WipeCommand functionality.
database/migration/default_creator_test.go Updated Up and Down methods in DefaultCreatorSuite to return error.
database/migration/default_migrator.go Renamed DefaultDriver to DefaultMigrator; updated methods to reflect new struct name and include error handling.
database/migration/default_migrator_test.go Renamed test suite from DefaultDriverSuite to DefaultMigratorSuite; updated tests to reflect new struct name.
database/migration/grammars/postgres.go Deleted file containing PostgreSQL-specific migration logic.
database/migration/repository.go Updated Repository struct to use schema.Schema instead of migration.Schema; enhanced error handling in repository methods.
database/migration/repository_test.go Enhanced error handling in repository tests; updated to use new schema types.
database/migration/sql_driver_test.go Deleted file containing tests for SQL driver functionality.
database/migration/sql_migrator.go Renamed SqlDriver to SqlMigrator; added Fresh method; updated constructor and method signatures.
database/migration/sql_migrator_test.go Introduced tests for SqlMigrator functionality.
database/migration/stubs.go Updated DummyMigration methods to return error.
database/migration/test_utils.go Removed mocking capabilities; migration creation functions remain unchanged.
database/schema/common_schema.go Introduced CommonSchema struct for schema management; added methods for retrieving tables and views.
database/schema/blueprint.go Changed package name from migration to schema; updated methods to return schema.ColumnDefinition.
database/schema/blueprint_test.go Changed package name from migration to schema; updated tests to reflect new schema context.
database/schema/column.go Changed package name from migration to schema; updated methods to return schema.ColumnDefinition.
database/schema/column_test.go Changed package name from migration to schema; updated tests for ColumnDefinition.
database/schema/grammars/postgres.go Introduced Postgres struct for managing PostgreSQL schema operations.
database/schema/grammars/postgres_test.go Updated tests to reflect new schema handling for PostgreSQL.
database/schema/schema.go Changed package name from migration to schema; updated struct and method signatures to align with new schema structure.
database/schema/schema_test.go Changed package name from migration to schema; enhanced test structure and error handling.
database/schema/test_utils.go Introduced GetTestSchema function for testing schema functionality.
database/service_provider.go Updated imports and method for creating schemas and handling migrations.
errors/list.go Added new error messages related to SQL migration and schema operations.
facades/schema.go Updated return type of Schema function to schema.Schema.
foundation/container.go Updated imports and method for creating schema instances.
support/console/console.go Introduced ConfirmToProceed function for user confirmation in production environments.
support/console/console_test.go Added tests for ConfirmToProceed function.

Possibly related PRs

  • feat: [#280] Add change table feature #671: The changes in this PR involve adding and modifying columns in the users table, which relates to the main PR's focus on migration functionalities, specifically the removal of the Driver interface and constants in the migration package.
  • feat: [#280] optimize make:migration command #672: This PR optimizes the make:migration command, which is directly related to the main PR's changes in the migration package, as it also deals with migration functionalities and the structure of migration commands.

Suggested reviewers

  • devhaozi: Suggested reviewer for the changes related to migration and schema management.

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.

GetViews() ([]View, error)
}

type DriverSchema interface {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Different drivers have different logic, so separate the driver schema.

Table(table string, callback func(table Blueprint))
}

type CommonSchema interface {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The common schema can be contained by Schema and DriverSchema.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Move to database/schema/grammars/postgres.go.

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: 26

🧹 Outside diff range and nitpick comments (68)
contracts/database/migration/migrator.go (2)

3-6: LGTM! Consider adding a brief comment for clarity.

The addition of these constants aligns well with the PR objectives, supporting multiple database drivers. The naming is clear and consistent.

Consider adding a brief comment above the constant block to explain their purpose, e.g.:

// Migrator types for different database drivers
const (
	MigratorDefault = "default"
	MigratorSql     = "sql"
)

9-14: LGTM! Consider enhancing method comments.

The new method signatures in the Migrator interface align well with the PR objectives. The addition of the Fresh method is particularly noteworthy.

Consider enhancing the method comments to provide more context:

// Create generates a new migration file with the given name.
Create(name string) error

// Fresh drops all tables and re-runs all migrations.
Fresh() error

// Run executes pending migrations.
Run() error

Note: The current comment for Run mentions "paths", but this is not reflected in the method signature. If paths are relevant, consider adding them as a parameter or clarifying the comment.

database/schema/test_utils.go (1)

11-15: LGTM with suggestions: Implementation is sound but could be improved.

The implementation effectively creates a mock ORM and schema for testing purposes. However, consider the following suggestions:

  1. The expectation for mockOrm.EXPECT().Name() to be called twice might be overly specific. Consider using .AnyTimes() instead of .Twice() for more flexibility in tests.

  2. The nil parameters in the NewSchema call could benefit from a comment explaining their purpose or why they're set to nil.

Consider applying these changes:

 func GetTestSchema(t *testing.T, testQuery *gorm.TestQuery) (*Schema, *mocksorm.Orm) {
 	mockOrm := mocksorm.NewOrm(t)
-	mockOrm.EXPECT().Name().Return(testQuery.Docker().Driver().String()).Twice()
+	mockOrm.EXPECT().Name().Return(testQuery.Docker().Driver().String()).AnyTimes()
+	// TODO: Add comment explaining the purpose of nil parameters
 	schema := NewSchema(testQuery.MockConfig(), nil, mockOrm, nil)

 	return schema, mockOrm
 }
database/schema/common_schema.go (1)

20-36: LGTM: Methods are well-implemented, with a minor suggestion for improvement.

The GetTables and GetViews methods are correctly implemented, using the encapsulated dependencies and providing appropriate error handling. They are concise and focused on their specific tasks.

Consider refactoring to reduce the slight duplication in error handling logic. You could create a helper method to handle the querying and scanning, which both methods could use. For example:

func (r *CommonSchema) query(sql string, result interface{}) error {
    return r.orm.Query().Raw(sql).Scan(result)
}

func (r *CommonSchema) GetTables() ([]schema.Table, error) {
    var tables []schema.Table
    if err := r.query(r.grammar.CompileTables(""), &tables); err != nil {
        return nil, err
    }
    return tables, nil
}

func (r *CommonSchema) GetViews() ([]schema.View, error) {
    var views []schema.View
    if err := r.query(r.grammar.CompileViews(), &views); err != nil {
        return nil, err
    }
    return views, nil
}

This refactoring would make the code more DRY and easier to maintain.

database/schema/common_schema_test.go (4)

14-17: LGTM: Well-structured test suite definition.

The CommonSchemaSuite struct is well-designed for testing multiple database drivers. The driverToTestQuery map allows for easy association between drivers and their corresponding test queries.

Consider adding a comment to explain the purpose of the driverToTestQuery map for better code documentation:

 type CommonSchemaSuite struct {
 	suite.Suite
+	// driverToTestQuery maps database drivers to their corresponding test queries
 	driverToTestQuery map[database.Driver]*gorm.TestQuery
 }

19-25: LGTM: Proper test suite setup with environment consideration.

The TestCommonSchemaSuite function correctly sets up the test suite and includes a check to skip tests on Windows due to Docker incompatibility.

Consider adding a TODO comment to remind about potential future Windows support:

 func TestCommonSchemaSuite(t *testing.T) {
 	if env.IsWindows() {
 		t.Skip("Skipping tests of using docker")
 	}
+	// TODO: Consider adding Windows support for these tests in the future
 
 	suite.Run(t, &CommonSchemaSuite{})
 }

27-33: LGTM: Proper test environment setup.

The SetupTest method correctly initializes a PostgreSQL Docker instance and sets up the test query.

Consider adding error handling for the Docker setup:

 func (s *CommonSchemaSuite) SetupTest() {
 	postgresDocker := docker.Postgres()
+	if err := postgresDocker.Start(); err != nil {
+		s.T().Fatalf("Failed to start PostgreSQL Docker: %v", err)
+	}
 	postgresQuery := gorm.NewTestQuery(postgresDocker, true)
 	s.driverToTestQuery = map[database.Driver]*gorm.TestQuery{
 		database.DriverPostgres: postgresQuery,
 	}
 }

35-38: Implement TestGetViews as per TODO comment.

The TestGetViews method is currently empty with a TODO comment. Please implement this test method after the functionality for creating views is added.

Would you like assistance in creating a skeleton for the TestGetViews method or in opening a GitHub issue to track this task?

database/schema/processors/postgres.go (2)

7-12: LGTM: Struct and constructor are well-defined.

The Postgres struct and its constructor NewPostgres are appropriately defined. The empty struct suggests a stateless processor, which is fine if that's the intended design.

Consider adding a brief comment explaining the purpose of the Postgres struct and its stateless nature, if that's the case. This would improve code readability and maintainability.


1-49: Summary: Good implementation with room for improvement

Overall, this new postgres.go file introduces a well-structured processor for PostgreSQL schema types, aligning with the PR objectives. The implementation is concise and functional. However, there are a few areas for improvement:

  1. Add error handling for unknown type or category codes in the ProcessTypes method.
  2. Consider returning a new slice instead of modifying the input in ProcessTypes to avoid unexpected side effects.
  3. Enhance documentation throughout the file, especially for the Postgres struct and ProcessTypes method.
  4. Clarify the intended behavior for handling unknown codes and whether modifying the input slice is intentional.

Addressing these points will improve the robustness and maintainability of the code.

As this file is part of a larger schema management system, ensure that the behavior of this PostgreSQL processor is consistent with other database-specific processors in the system. Consider creating an interface that all database processors must implement to ensure consistency across different database types.

database/console/migration/migrate_command.go (2)

14-17: Simplified constructor improves separation of concerns

The updated NewMigrateCommand function is a good improvement. It simplifies the constructor and aligns with the new MigrateCommand struct. This change enhances the separation of concerns by removing the need for the command to handle config and schema details directly.

However, consider adding a nil check for the migrator parameter to prevent potential runtime panics:

func NewMigrateCommand(migrator migration.Migrator) *MigrateCommand {
	if migrator == nil {
		panic("migrator cannot be nil")
	}
	return &MigrateCommand{
		migrator: migrator,
	}
}

This ensures that the MigrateCommand is always initialized with a valid migrator.


39-39: Consistent update to use migrator interface

The change from r.driver.Run() to r.migrator.Run() is consistent with the earlier modifications and simplifies the migration process. The error handling remains appropriate.

Consider enhancing the error handling slightly to provide more context:

if err := r.migrator.Run(); err != nil {
	return fmt.Errorf("migration failed: %w", err)
}

This change would propagate the original error while adding context, which can be helpful for debugging or logging at higher levels.

database/schema/processors/postgres_test.go (3)

11-27: LGTM: Well-structured test function and first test case.

The test function and first test case are well-structured and follow good testing practices. The use of NewPostgres() and clear input/output definitions make the test easy to understand.

Consider adding a descriptive comment for each test case to improve readability. For example:

// Test case: Valid types should be correctly processed
input := []schema.Type{
    // ...
}

29-51: LGTM: Good coverage of edge cases.

The test cases for unknown type and unknown category are well-structured and cover important edge cases. They maintain consistency with the first test case, which is good for readability.

To improve the tests' robustness, consider adding assertions for the length of the result slice in addition to checking its content. This ensures that no unexpected elements are added. For example:

assert.Len(t, result, len(expected))
assert.Equal(t, expected, result)

53-60: LGTM: Good coverage and consistent structure.

The final test case for empty input is a valuable addition, and the overall structure of the test function is consistent and readable. The test cases cover a good range of scenarios.

To enhance the test suite, consider using table-driven tests. This approach can make it easier to add new test cases and reduce code duplication. Here's an example of how you could refactor the test:

func TestProcessTypes(t *testing.T) {
	testCases := []struct {
		name     string
		input    []schema.Type
		expected []schema.Type
	}{
		{
			name: "Valid Types",
			input: []schema.Type{
				{Type: "b", Category: "a"},
				{Type: "c", Category: "b"},
				{Type: "d", Category: "c"},
			},
			expected: []schema.Type{
				{Type: "base", Category: "array"},
				{Type: "composite", Category: "boolean"},
				{Type: "domain", Category: "composite"},
			},
		},
		// Add other test cases here
	}

	postgres := NewPostgres()
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			result := postgres.ProcessTypes(tc.input)
			assert.Equal(t, tc.expected, result)
		})
	}
}

This approach would make it easier to add new test cases in the future and improve the overall structure of the test.

database/schema/grammars/utils.go (1)

Line range hint 41-58: LGTM! Function signature updated correctly. Consider performance optimization.

The getType function has been successfully updated to use schema.Grammar and schema.ColumnDefinition. The internal logic of the function is preserved, which is appropriate as the fundamental operation remains the same.

However, it's worth noting that this function uses reflection to dynamically call methods on the grammar object. While this approach provides flexibility, it could potentially impact performance if called frequently.

Consider the following optimization if performance becomes a concern:

  1. Create a map of method names to functions at initialization time.
  2. Use this map for lookups instead of reflection at runtime.

This approach would trade some flexibility for improved performance. Here's a sketch of how this could look:

var typeMethods map[string]func(schema.Grammar, schema.ColumnDefinition) string

func init() {
    typeMethods = make(map[string]func(schema.Grammar, schema.ColumnDefinition) string)
    // Populate the map with known methods
    typeMethods["TypeString"] = func(g schema.Grammar, c schema.ColumnDefinition) string {
        return g.TypeString(c)
    }
    // Add other known types...
}

func getType(grammar schema.Grammar, column schema.ColumnDefinition) string {
    methodName := "Type" + strings.Title(column.GetType())
    if method, ok := typeMethods[methodName]; ok {
        return method(grammar, column)
    }
    return ""
}

This optimization should only be implemented if profiling indicates that the current implementation is a performance bottleneck.

database/console/migration/migrate_reset_command_test.go (1)

47-48: Approved, but consider more specific error checking.

The change to use assert.Error(t, err) is valid and simplifies the error checking process. However, to ensure that the correct type of error is being caught (i.e., a "record not found" error), consider using a more specific error check.

Consider updating the error check to be more specific:

-err = query.Where("name", "goravel").FirstOrFail(&agent)
-assert.Error(t, err)
+err = query.Where("name", "goravel").FirstOrFail(&agent)
+assert.ErrorIs(t, err, gorm.ErrRecordNotFound)

This change would ensure that the test is specifically catching a "record not found" error, which is the expected outcome after a successful migration reset.

database/console/migration/migrate_status_command_test.go (1)

34-35: LGTM: New SqlMigrator usage with proper error handling

The introduction of migration.NewSqlMigrator(mockConfig) is a positive change that aligns with the refactoring efforts. The error handling is appropriate, using require.NoError to ensure the test fails if the migrator creation fails.

As a minor suggestion, consider adding a descriptive error message to the require.NoError call for improved debugging:

require.NoError(t, err, "Failed to create new SQL migrator")

This would provide more context if the error occurs during test execution.

database/schema/postgres_schema_test.go (3)

24-30: LGTM with suggestion: Consider adding a comment explaining the Windows skip.

The TestPostgresSchemaSuite function correctly initializes and runs the test suite. The Windows check is a good practice to avoid Docker-related issues.

Consider adding a brief comment explaining why the tests are skipped on Windows, for better maintainability:

 if env.IsWindows() {
+	// Skip tests on Windows due to Docker compatibility issues
 	t.Skip("Skipping tests of using docker")
 }

40-50: LGTM with suggestion: Consider adding more test cases.

The TestGetSchema method effectively tests the getSchema function for both default and custom search path scenarios. The use of mock objects and expectations is well-implemented.

Consider adding more test cases to cover edge scenarios:

  1. Test with an empty string as the search path.
  2. Test with multiple schemas in the search path.
  3. Test with invalid schema names.

Example:

func (s *PostgresSchemaSuite) TestGetSchema() {
	testCases := []struct {
		name           string
		searchPath     string
		expectedSchema string
	}{
		{"Default", "", "public"},
		{"Custom", "goravel", "goravel"},
		{"Empty", " ", "public"},
		{"Multiple", "schema1,schema2", "schema1"},
		{"Invalid", "123invalid", "123invalid"},
	}

	for _, tc := range testCases {
		s.Run(tc.name, func() {
			s.mockOrm.EXPECT().Name().Return("postgres").Once()
			s.mockConfig.EXPECT().GetString("database.connections.postgres.search_path").Return(tc.searchPath).Once()
			s.Equal(tc.expectedSchema, s.postgresSchema.getSchema())
		})
	}
}

This approach provides more comprehensive coverage and makes it easier to add new test cases in the future.


52-55: TODO noted: Implement TestGetTypes after implementing create type.

The presence of this TODO aligns with the planned type retrieval functionality mentioned in the PR summary.

To ensure this doesn't get overlooked, would you like me to create a GitHub issue to track the implementation of the TestGetTypes method? This can help in maintaining a record of pending tasks and ensure it's addressed in future updates.

contracts/database/schema/grammar.go (1)

Line range hint 1-29: Overall assessment: Significant enhancement to schema management capabilities.

The changes to this file represent a substantial improvement in the framework's ability to manage database schemas. The transition from migration to schema package and the addition of new methods for dropping various database objects (domains, tables, types, views) and compiling queries for schema introspection align well with the PR objectives.

These enhancements provide a more comprehensive set of tools for database management, particularly beneficial for PostgreSQL databases. The new methods will allow for more flexible and powerful schema manipulation operations.

However, please address the minor issues with parameter naming in the CompileDropAllTypes and CompileDropAllViews methods to ensure consistency and clarity throughout the interface.

database/schema/column_test.go (8)

Line range hint 33-38: Consider using a setter method for change.

While the test effectively checks the GetChange functionality, it directly modifies the private change field. It would be better to use a setter method (e.g., SetChange) to modify this field, maintaining encapsulation.

Consider refactoring the test as follows:

func (s *ColumnDefinitionTestSuite) GetChange() {
	s.False(s.columnDefinition.GetChange())

	s.columnDefinition.SetChange(true) // Assuming SetChange method exists
	s.True(s.columnDefinition.GetChange())
}

Line range hint 40-45: Consider using a setter method for def.

While the test effectively checks the GetDefault functionality, it directly modifies the private def field. It would be better to use a setter method (e.g., SetDefault) to modify this field, maintaining encapsulation.

Consider refactoring the test as follows:

func (s *ColumnDefinitionTestSuite) GetDefault() {
	s.Nil(s.columnDefinition.GetDefault())

	s.columnDefinition.SetDefault("default") // Assuming SetDefault method exists
	s.Equal("default", s.columnDefinition.GetDefault())
}

Line range hint 47-52: Consider using a setter method for name.

While the test effectively checks the GetName functionality, it directly modifies the private name field. It would be better to use a setter method (e.g., SetName) to modify this field, maintaining encapsulation.

Consider refactoring the test as follows:

func (s *ColumnDefinitionTestSuite) GetName() {
	s.Empty(s.columnDefinition.GetName())

	s.columnDefinition.SetName("name") // Assuming SetName method exists
	s.Equal("name", s.columnDefinition.GetName())
}

Line range hint 54-59: Consider using a setter method for length.

While the test effectively checks the GetLength functionality, it directly modifies the private length field. It would be better to use a setter method (e.g., SetLength) to modify this field, maintaining encapsulation.

Consider refactoring the test as follows:

func (s *ColumnDefinitionTestSuite) GetLength() {
	s.Equal(0, s.columnDefinition.GetLength())

	s.columnDefinition.SetLength(255) // Assuming SetLength method exists
	s.Equal(255, s.columnDefinition.GetLength())
}

Line range hint 61-66: Consider using a setter method for nullable.

While the test effectively checks the GetNullable functionality, it directly modifies the private nullable field. It would be better to use a setter method (e.g., SetNullable) to modify this field, maintaining encapsulation.

Consider refactoring the test as follows:

func (s *ColumnDefinitionTestSuite) GetNullable() {
	s.False(s.columnDefinition.GetNullable())

	s.columnDefinition.SetNullable(true) // Assuming SetNullable method exists
	s.True(s.columnDefinition.GetNullable())
}

Line range hint 68-73: Consider using a setter method for ttype.

While the test effectively checks the GetType functionality, it directly modifies the private ttype field. It would be better to use a setter method (e.g., SetType) to modify this field, maintaining encapsulation.

Consider refactoring the test as follows:

func (s *ColumnDefinitionTestSuite) GetType() {
	s.Empty(s.columnDefinition.GetType())

	s.columnDefinition.SetType("string") // Assuming SetType method exists
	s.Equal("string", s.columnDefinition.GetType())
}

Line range hint 75-78: Consider using a getter method for unsigned.

While the test effectively checks the Unsigned functionality, it directly accesses the private unsigned field to verify the state. It would be better to use a getter method (e.g., GetUnsigned) to access this field, maintaining encapsulation.

Consider refactoring the test as follows:

func (s *ColumnDefinitionTestSuite) Unsigned() {
	s.columnDefinition.Unsigned()
	s.True(s.columnDefinition.GetUnsigned()) // Assuming GetUnsigned method exists
}

Line range hint 1-78: Overall, well-structured and comprehensive test suite with room for improvement.

The test suite for the ColumnDefinition struct is well-organized and covers the main functionalities. However, there are opportunities to improve encapsulation by using setter and getter methods instead of directly accessing private fields in most of the test methods. This change would enhance the code quality, maintainability, and align better with Go best practices.

Consider implementing and using setter methods for change, def, name, length, nullable, and ttype, and a getter method for unsigned. This will make the tests more robust and less dependent on the internal structure of the ColumnDefinition struct.

database/console/migration/migrate_rollback_command_test.go (1)

34-36: Approved: Added SQL migrator creation with error handling

The introduction of a real SQL migrator instead of a mock schema aligns with the new Migrator interface. The error handling is a good addition.

Consider using require.NoError(t, err) instead of assert.NoError(t, err) to fail the test immediately if the migrator creation fails, as the subsequent test steps depend on its success.

database/console/migration/migrate_make_command_test.go (2)

27-27: Improved test structure and naming

The updated test case structure with the expectErr field and the new "Happy path" and "Sad path" naming convention improve the clarity and robustness of the tests. This change aligns well with best practices in test design.

Consider adding a brief comment above each test case to explain the specific scenario being tested. This can further enhance the readability and maintainability of the test suite.

Also applies to: 30-30, 38-38, 44-50, 53-58


45-50: Improved test coverage with new Sad path scenarios

The addition of "Sad path" test cases for failures in asking for the migration name and creating the migration significantly improves the test coverage. The use of assert.AnError is a good practice for testing error conditions.

Consider adding more specific error checks in the future. While assert.AnError is sufficient for now, as the error handling becomes more sophisticated, it might be beneficial to check for specific error types or messages to ensure the correct errors are being returned in each scenario.

Also applies to: 53-58

support/console/console.go (1)

86-100: LGTM! Consider adding a function comment.

The ConfirmToProceed function implementation looks good and aligns well with the PR objectives. It provides a safety mechanism for running commands in a production environment.

Consider adding a function comment to explain its purpose and parameters. For example:

// ConfirmToProceed checks if the command should proceed based on the environment
// and user confirmation. It returns true if the command should proceed, false otherwise.
// Parameters:
//   - ctx: The console context
//   - env: The current environment (e.g., "production", "development")
func ConfirmToProceed(ctx console.Context, env string) bool {
    // ... (existing implementation)
}
database/migration/repository.go (3)

Line range hint 20-25: LGTM: CreateRepository method updated with improved error handling.

The method now returns an error, allowing for better error handling by callers. The use of schema.Blueprint is consistent with the overall changes.

Consider adding a specific error check before returning:

err := r.schema.Create(r.table, func(table schema.Blueprint) {
    table.ID()
    table.String("migration")
    table.Integer("batch")
})
if err != nil {
    return fmt.Errorf("failed to create repository: %w", err)
}
return nil

This would provide more context about where the error occurred.


34-35: LGTM: DeleteRepository method updated with improved error handling.

The method now returns an error, allowing for better error handling by callers. The direct return of r.schema.DropIfExists result is good for error propagation.

Consider adding a specific error check before returning:

err := r.schema.DropIfExists(r.table)
if err != nil {
    return fmt.Errorf("failed to delete repository: %w", err)
}
return nil

This would provide more context about where the error occurred.


Line range hint 1-103: Overall assessment: Changes align well with PR objectives and improve code quality.

The modifications to this file successfully transition from the migration package to the schema package, aligning with the PR's goal of optimizing the migrate commands. The changes consistently use schema.Schema instead of migration.Schema, and improve error handling in key methods.

To further enhance the code:

  1. Consider adding more detailed error messages in CreateRepository and DeleteRepository methods as suggested.
  2. Ensure that all callers of these methods are updated to handle the new error returns.
  3. Consider adding unit tests for the new error scenarios if not already covered.
database/migration/default_creator_test.go (3)

48-50: Approve change with minor suggestion.

The update to the Up method signature to return an error is correct and aligns with the PR objectives. This change enhances error handling capabilities in migration methods.

Consider adding a comment explaining that this is a stub implementation for testing purposes, to improve code clarity:

 // Up Run the migrations.
 func (r *M202410131203CreateUsersTable) Up() error {
+    // Stub implementation for testing
     return nil
 }

53-55: Approve change with minor suggestion.

The update to the Down method signature to return an error is correct and consistent with the changes made to the Up method. This change enhances error handling capabilities in migration methods.

Consider adding a comment explaining that this is a stub implementation for testing purposes, to improve code clarity:

 // Down Reverse the migrations.
 func (r *M202410131203CreateUsersTable) Down() error {
+    // Stub implementation for testing
     return nil
 }

76-84: Approve changes with suggestions for improved error handling.

The updates to both Up and Down method signatures to return an error are correct and consistent with the previous changes. However, the current implementations don't handle potential errors from the schema operations.

Consider updating the implementations to handle and return potential errors:

 // Up Run the migrations.
 func (r *M202410131203CreateUsersTable) Up() error {
-    facades.Schema.Create("users", func(table migration.Blueprint) {
+    return facades.Schema.Create("users", func(table migration.Blueprint) {
         table.BigIncrements("id")
         table.Timestamps()
     })
 }

 // Down Reverse the migrations.
 func (r *M202410131203CreateUsersTable) Down() error {
-    facades.Schema.DropIfExists("users")
+    return facades.Schema.DropIfExists("users")
 }

This change ensures that any errors from the schema operations are properly propagated.

database/console/migration/migrate_refresh_command_test.go (1)

34-36: LGTM: New SqlMigrator instantiation with proper error handling.

The addition of the SqlMigrator instantiation is good, and the error handling is appropriate. However, consider adding a more descriptive error message to provide context in case of failure.

You could improve the error handling slightly by adding more context:

 migrator, err := migration.NewSqlMigrator(mockConfig)
-require.NoError(t, err)
+require.NoError(t, err, "Failed to create SQL migrator")
database/migration/repository_test.go (3)

45-45: LGTM: Improved error handling and transaction mocking.

The addition of error checking for CreateRepository and DeleteRepository calls enhances the test's robustness. The use of mockTransaction before these operations is a good practice for setting up the necessary mocking.

Consider adding a comment explaining the purpose of mockTransaction for better code readability.

Also applies to: 53-53


154-157: LGTM: Improved schema initialization in tests.

The changes in the initRepository function are good improvements:

  1. Renaming schema to testSchema avoids shadowing the package name, enhancing clarity.
  2. Using schema.GetTestSchema() centralizes test schema creation, which can improve maintainability.

Consider adding a brief comment explaining what GetTestSchema does, especially if it's not immediately obvious from its name.


159-162: LGTM: Useful helper function for mocking transactions.

The new mockTransaction function is a valuable addition:

  1. It encapsulates the logic for mocking transactions, reducing code duplication in tests.
  2. The use of mock.Anything and RunAndReturn provides flexibility in handling various transaction scenarios.

Consider adding a brief documentation comment explaining the purpose and usage of this function. This would help other developers understand how to use it in their tests.

database/migration/stubs.go (3)

18-24: LGTM! Consider adding a comment about the empty implementation.

The changes to return error in the Up and Down methods are good. This allows for better error handling in the migration process.

Consider adding a comment in the empty method bodies to explain why they're empty. For example:

func (r *DummyMigration) Up() error {
    // This is a stub implementation. Actual migration code should be added here.
    return nil
}

func (r *DummyMigration) Down() error {
    // This is a stub implementation. Actual rollback code should be added here.
    return nil
}

This would make the intention clearer for developers using these stubs.


43-53: LGTM! Consider handling potential errors from Schema operations.

The changes to return error in the Up and Down methods are good and consistent with the previous changes.

Consider handling potential errors from the Schema.Create and Schema.DropIfExists operations. For example:

func (r *DummyMigration) Up() error {
    return facades.Schema.Create("DummyTable", func(table migration.Blueprint) {
        table.BigIncrements("id")
        table.Timestamps()
    })
}

func (r *DummyMigration) Down() error {
    return facades.Schema.DropIfExists("DummyTable")
}

This way, any errors occurring during the schema operations will be properly propagated.


71-80: LGTM! Consider error handling and documenting the empty Down method.

The changes to return error in the Up and Down methods are good and consistent with the previous changes.

  1. Consider handling potential errors from the Schema.Table operation in the Up method:
func (r *DummyMigration) Up() error {
    return facades.Schema.Table("DummyTable", func(table migration.Blueprint) {
        // Add your table modifications here
    })
}
  1. For the Down method, if it's intentionally left empty because the update can't be easily reversed, consider adding a comment explaining this:
func (r *DummyMigration) Down() error {
    // This update cannot be automatically reversed.
    // Manual intervention might be required to undo these changes.
    return nil
}

These changes would improve error handling and make the intentions clearer for developers using these stubs.

support/console/console_test.go (1)

137-194: Well-structured test function with good coverage.

The TestConfirmToProceed function is well-organized and covers various scenarios for the ConfirmToProceed function. The use of table-driven tests allows for easy addition of new test cases.

Consider the following improvements:

  1. Use more descriptive names for test cases. For example:

    {
      name: "Should proceed when environment is not production",
      // ...
    },
    {
      name: "Should proceed when force option is true in production",
      // ...
    },
  2. Add a test case for when the confirmation returns false but no error:

    {
      name: "Should not proceed when confirmation returns false",
      env:  "production",
      setup: func() {
        mockCtx.EXPECT().OptionBool("force").Return(false).Once()
        mockCtx.EXPECT().Confirm("Are you sure you want to run this command?").Return(false, nil).Once()
      },
      expectResult: false,
    },
  3. Consider expanding the error case to test different error scenarios, such as specific error types that might be returned by the Confirm method.

These improvements will enhance the test coverage and make the test cases more descriptive and easier to understand.

contracts/foundation/application.go (1)

Line range hint 1-124: Summary: Changes align with schema management transition.

The modifications in this file, including the updated import statement and the MakeSchema() method signature, are consistent with the transition from migration to schema management as described in the PR objectives. These changes are part of a larger refactoring effort and appear to be correctly implemented within this file.

To ensure a smooth transition:

  1. Verify that all usages of MakeSchema() across the codebase have been updated to expect schema.Schema as the return type.
  2. Check for any other occurrences of migration.Schema that might need to be updated to schema.Schema.
  3. Ensure that the new schema package provides all the necessary functionality that was previously available in the migration package.

Consider adding a brief comment above the MakeSchema() method to explain its purpose and the recent change from migration to schema management. This will help future developers understand the context of this method.

database/console/wipe_command_test.go (4)

13-24: LGTM: Well-structured test function with a suggestion.

The test function is well-organized using a table-driven approach, which is excellent for covering multiple scenarios. The beforeEach function ensures consistent setup for each test case.

Consider adding a t.Parallel() call at the beginning of the test function to allow for parallel test execution, which can improve test performance:

 func TestWipeCommand(t *testing.T) {
+	t.Parallel()
 	var (
 		mockContext *mocksconsole.Context
 		mockConfig  *mocksconfig.Config
 		mockSchema  *mocksschema.Schema
 	)
 	// ... rest of the function
 }

Also applies to: 140-149


26-88: LGTM: Comprehensive happy path test cases with a suggestion.

The happy path test cases cover a good range of scenarios, including local and production environments, with and without force options. The mock expectations are set up correctly for each case.

Consider adding a test case for a scenario where the database option is not provided or is empty. This would help ensure the command handles default database connections correctly:

{
	name: "Happy path - default database connection",
	setup: func() {
		mockConfig.EXPECT().GetString("app.env").Return("local").Once()
		mockContext.EXPECT().Option("database").Return("").Once()
		// Expect the default connection to be used
		mockSchema.EXPECT().Connection("").Return(mockSchema).Once()
		mockContext.EXPECT().OptionBool("drop-views").Return(false).Once()
		mockSchema.EXPECT().DropAllTables().Return(nil).Once()
		mockContext.EXPECT().OptionBool("drop-types").Return(false).Once()
	},
},

89-137: LGTM: Thorough sad path test cases with a suggestion.

The sad path test cases cover important failure scenarios, including confirmation denial and failures in dropping views, tables, and types. The mock expectations are set up correctly for each case.

Consider adding a test case for a scenario where an invalid database connection is provided. This would help ensure the command handles invalid database connections gracefully:

{
	name: "Sad path - invalid database connection",
	setup: func() {
		mockConfig.EXPECT().GetString("app.env").Return("local").Once()
		mockContext.EXPECT().Option("database").Return("invalid_db").Once()
		mockSchema.EXPECT().Connection("invalid_db").Return(nil).Once()
	},
},

1-149: LGTM: Well-structured and comprehensive test suite with a suggestion for improvement.

The test suite for the WipeCommand is well-structured using a table-driven approach, which allows for easy addition of new test cases. The use of mocks effectively isolates the WipeCommand behavior from external dependencies, and the test cases cover a wide range of scenarios, including both happy and sad paths.

To improve test isolation and make the tests more robust, consider using a separate mock setup for each test case instead of relying on a shared beforeEach function. This can prevent potential interference between test cases:

func TestWipeCommand(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name  string
		setup func() (*mocksconsole.Context, *mocksconfig.Config, *mocksschema.Schema)
	}{
		{
			name: "Happy path - local",
			setup: func() (*mocksconsole.Context, *mocksconfig.Config, *mocksschema.Schema) {
				mockContext := mocksconsole.NewContext(t)
				mockConfig := mocksconfig.NewConfig(t)
				mockSchema := mocksschema.NewSchema(t)
				
				// Set up expectations here
				
				return mockContext, mockConfig, mockSchema
			},
		},
		// ... other test cases
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mockContext, mockConfig, mockSchema := tt.setup()
			command := NewWipeCommand(mockConfig, mockSchema)
			assert.NoError(t, command.Handle(mockContext))
		})
	}
}

This approach ensures that each test case has its own set of mock objects, preventing any potential state leakage between tests.

foundation/container.go (1)

Line range hint 292-301: LGTM: Method updated to use new schema binding.

The MakeSchema method has been correctly updated to use database.BindingSchema instead of database.BindingMigration, which is consistent with the package restructuring.

However, for better naming consistency, consider updating the return type from contractsmigration.Schema to contractsschema.Schema if such an interface exists in the new package structure.

database/migration/default_migrator.go (1)

45-45: Address the TODO to remove the Fresh method

There is a TODO comment indicating that the Fresh method should be removed and its logic moved to the migrate:fresh command when the SQL migrator is removed. To maintain code cleanliness and prevent technical debt, it's important to track and address this task.

Would you like assistance in refactoring this logic now, or should I open a GitHub issue to ensure this task is tracked for future updates?

database/console/wipe_command.go (2)

24-32: Minor typos in comment descriptions

There are minor typos in the comments for Signature, Description, and Extend methods. The word "The" is capitalized unnecessarily, and "extend" should be "extension" or rephrased for clarity.

Consider updating the comments:

// Signature The name and signature of the console command.
+// Signature returns the name and signature of the console command.

// Description The console command description.
+// Description returns the console command description.

// Extend The console command extend.
+// Extend provides additional options for the console command.

4-10: Organize imports for readability

For better readability, organize the import statements by grouping standard library imports and third-party imports separately, and ordering them alphabetically within their groups.

Example:

import (
+   "fmt"

	"github.com/goravel/framework/contracts/config"
	"github.com/goravel/framework/contracts/console"
	"github.com/goravel/framework/contracts/console/command"
	"github.com/goravel/framework/contracts/database/schema"
	"github.com/goravel/framework/support/color"
	supportconsole "github.com/goravel/framework/support/console"
)
database/schema/postgres_schema.go (2)

122-128: Ensure default schema aligns with PostgreSQL configurations

In the getSchema() method, when the schema variable is empty, it defaults to "public". Please verify that this default schema aligns with your PostgreSQL database configurations. If the application uses multiple schemas or a different default, consider making the default schema configurable or adding a warning.


130-137: Provide additional context in error handling

When an error occurs during Scan in the GetTypes() method, the returned error could be more descriptive. Wrapping the error with additional context can aid in debugging and understanding the failure point.

Suggested change:

if err := r.orm.Query().Raw(r.grammar.CompileTypes()).Scan(&types); err != nil {
-    return nil, err
+    return nil, fmt.Errorf("failed to scan types in GetTypes: %w", err)
}
database/schema/schema.go (3)

Line range hint 91-107: Update HasTable method due to removal of GetTables

The HasTable method relies on r.GetTables(), but according to the AI-generated summary, the GetTables method has been removed. This will result in a compilation error. Please update the HasTable method to work without GetTables, possibly by implementing an alternative approach to check for table existence.

Consider refactoring the HasTable method to directly query the database for the table's existence.

Would you like assistance in refactoring the HasTable method to ensure it functions correctly without GetTables?


Line range hint 131-135: Avoid using log.Fatalf in the Sql method

The Sql method uses log.Fatalf to handle errors, which will terminate the application on failure. To allow for better error management and flexibility, consider returning the error instead, so that the caller can handle it appropriately.

Apply this diff to modify the method to return an error:

-func (r *Schema) Sql(sql string) {
+func (r *Schema) Sql(sql string) error {
   if _, err := r.orm.Query().Exec(sql); err != nil {
-    r.log.Fatalf("failed to execute sql: %v", err)
+    return fmt.Errorf("failed to execute sql: %v", err)
   }
+  return nil
 }

Line range hint 137-142: Modify Table method to return an error instead of exiting

The Table method currently calls log.Fatalf when an error occurs, which will exit the application. Returning an error allows callers to handle failures gracefully without terminating the entire application.

Apply this diff to change the method signature and error handling:

-func (r *Schema) Table(table string, callback func(table schema.Blueprint)) {
+func (r *Schema) Table(table string, callback func(table schema.Blueprint)) error {
   blueprint := r.createBlueprint(table)
   callback(blueprint)

   if err := r.build(blueprint); err != nil {
-    r.log.Fatalf("failed to modify %s table: %v", table, err)
+    return fmt.Errorf("failed to modify %s table: %v", table, err)
   }
+  return nil
 }

Please ensure that callers of the Table method handle the returned error appropriately.

database/migration/sql_migrator.go (1)

Line range hint 92-158: Consider refactoring to reduce code duplication in driver initialization.

The switch-case statements for initializing database drivers contain duplicated code patterns for opening database connections and creating driver instances. Refactoring this logic can enhance maintainability and readability.

You could abstract the common patterns into helper functions. Here's an example of how you might refactor the driver initialization:

func initializeDB(writeConfig databasedb.WriteConfig, dsn string) (*sql.DB, string, error) {
    databaseName := writeConfig.Driver.String()
    db, err := sql.Open(databaseName, dsn)
    if err != nil {
        return nil, "", err
    }
    return db, databaseName, nil
}

func getDatabaseDriver(db *sql.DB, driverName database.Driver, table string) (migratedatabase.Driver, error) {
    switch driverName {
    case database.DriverMysql:
        return mysql.WithInstance(db, &mysql.Config{
            MigrationsTable: table,
        })
    case database.DriverPostgres:
        return postgres.WithInstance(db, &postgres.Config{
            MigrationsTable: table,
        })
    case database.DriverSqlite:
        return driver.WithInstance(db, &driver.Config{
            MigrationsTable: table,
        })
    case database.DriverSqlserver:
        return sqlserver.WithInstance(db, &sqlserver.Config{
            MigrationsTable: table,
        })
    default:
        return nil, errors.OrmDriverNotSupported.Args(driverName.String())
    }
}

Then, modify the getMigrator function to utilize these helper functions:

db, databaseName, err := initializeDB(writeConfig, dsn)
if err != nil {
    return nil, err
}

dbDriver, err := getDatabaseDriver(db, writeConfig.Driver, table)
if err != nil {
    return nil, err
}

This refactoring reduces repetition and centralizes the initialization logic.

database/schema/blueprint.go (1)

Line range hint 145-159: Missing handling of commandComment in ToSql method

In the ToSql method, the switch statement does not handle the commandComment case. This could result in comment commands not being processed, potentially causing schema comments to be ignored during migrations.

Apply this diff to handle commandComment:

 func (r *Blueprint) ToSql(query ormcontract.Query, grammar schema.Grammar) []string {
 	r.addImpliedCommands(grammar)

 	var statements []string
 	for _, command := range r.commands {
 		switch command.Name {
 		case commandAdd:
 			statements = append(statements, grammar.CompileAdd(r))
 		case commandChange:
 			statements = append(statements, grammar.CompileChange(r))
 		case commandCreate:
 			statements = append(statements, grammar.CompileCreate(r, query))
 		case commandDropIfExists:
 			statements = append(statements, grammar.CompileDropIfExists(r))
+		case commandComment:
+			statements = append(statements, grammar.CompileComment(r))
 		}
 	}

 	return statements
 }

Ensure that the schema.Grammar interface includes a CompileComment method to handle the commandComment command.

database/schema/schema_test.go (3)

96-100: Implement the TestDropAllTypes test method

The TestDropAllTypes method is currently empty and marked with a TODO comment. Would you like assistance in implementing this test?

Would you like me to help implement the TestDropAllTypes method or open a GitHub issue to track this task?


101-104: Implement the TestDropAllViews test method

The TestDropAllViews method is currently empty and marked with a TODO comment. Would you like assistance in implementing this test?

Would you like me to help implement the TestDropAllViews method or open a GitHub issue to track this task?


175-179: Implement the TestGetViews test method

The TestGetViews method is currently empty and marked with a TODO comment. Would you like assistance in implementing this test?

Would you like me to help implement the TestGetViews method or open a GitHub issue to track this task?

database/schema/blueprint_test.go (1)

Line range hint 237-239: Address the TODO: Implement the Comment method

There is a TODO comment indicating the need to implement the Comment method:

// TODO Add below when implementing the comment method
// s.blueprint.String("name").Comment("comment")
// s.blueprint.Comment("comment")

Implementing this method will enhance the schema building capabilities by allowing comments to be added to columns and tables as needed.

Would you like assistance in implementing the Comment method or opening a GitHub issue to track this task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 62d45f5 and ed5b5a1.

⛔ Files ignored due to path filters (14)
  • mocks/database/migration/Driver.go is excluded by !mocks/**
  • mocks/database/migration/Grammar.go is excluded by !mocks/**
  • mocks/database/migration/Migrator.go is excluded by !mocks/**
  • mocks/database/migration/Repository.go is excluded by !mocks/**
  • mocks/database/schema/Blueprint.go is excluded by !mocks/**
  • mocks/database/schema/ColumnDefinition.go is excluded by !mocks/**
  • mocks/database/schema/CommonSchema.go is excluded by !mocks/**
  • mocks/database/schema/Connection.go is excluded by !mocks/**
  • mocks/database/schema/DriverSchema.go is excluded by !mocks/**
  • mocks/database/schema/Grammar.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 (55)
  • contracts/database/migration/driver.go (0 hunks)
  • contracts/database/migration/migrator.go (1 hunks)
  • contracts/database/migration/repository.go (1 hunks)
  • contracts/database/schema/blueprint.go (1 hunks)
  • contracts/database/schema/column.go (1 hunks)
  • contracts/database/schema/grammar.go (2 hunks)
  • contracts/database/schema/schema.go (3 hunks)
  • contracts/foundation/application.go (2 hunks)
  • database/console/migration/migrate_command.go (2 hunks)
  • database/console/migration/migrate_fresh_command.go (3 hunks)
  • database/console/migration/migrate_fresh_command_test.go (1 hunks)
  • database/console/migration/migrate_make_command.go (2 hunks)
  • database/console/migration/migrate_make_command_test.go (2 hunks)
  • database/console/migration/migrate_refresh_command_test.go (2 hunks)
  • database/console/migration/migrate_reset_command_test.go (1 hunks)
  • database/console/migration/migrate_rollback_command_test.go (1 hunks)
  • database/console/migration/migrate_status_command_test.go (1 hunks)
  • database/console/migration/utils.go (0 hunks)
  • database/console/migration/utils_test.go (0 hunks)
  • database/console/wipe_command.go (1 hunks)
  • database/console/wipe_command_test.go (1 hunks)
  • database/migration/default_creator_test.go (3 hunks)
  • database/migration/default_migrator.go (5 hunks)
  • database/migration/default_migrator_test.go (12 hunks)
  • database/migration/grammars/postgres.go (0 hunks)
  • database/migration/repository.go (2 hunks)
  • database/migration/repository_test.go (4 hunks)
  • database/migration/sql_driver_test.go (0 hunks)
  • database/migration/sql_migrator.go (6 hunks)
  • database/migration/sql_migrator_test.go (1 hunks)
  • database/migration/stubs.go (3 hunks)
  • database/migration/test_utils.go (0 hunks)
  • database/schema/blueprint.go (11 hunks)
  • database/schema/blueprint_test.go (12 hunks)
  • database/schema/column.go (3 hunks)
  • database/schema/column_test.go (1 hunks)
  • database/schema/common_schema.go (1 hunks)
  • database/schema/common_schema_test.go (1 hunks)
  • database/schema/grammars/postgres.go (1 hunks)
  • database/schema/grammars/postgres_test.go (9 hunks)
  • database/schema/grammars/utils.go (2 hunks)
  • database/schema/grammars/utils_test.go (2 hunks)
  • database/schema/postgres_schema.go (1 hunks)
  • database/schema/postgres_schema_test.go (1 hunks)
  • database/schema/processors/postgres.go (1 hunks)
  • database/schema/processors/postgres_test.go (1 hunks)
  • database/schema/schema.go (5 hunks)
  • database/schema/schema_test.go (4 hunks)
  • database/schema/test_utils.go (1 hunks)
  • database/service_provider.go (3 hunks)
  • errors/list.go (2 hunks)
  • facades/schema.go (1 hunks)
  • foundation/container.go (1 hunks)
  • support/console/console.go (1 hunks)
  • support/console/console_test.go (1 hunks)
💤 Files with no reviewable changes (6)
  • contracts/database/migration/driver.go
  • database/console/migration/utils.go
  • database/console/migration/utils_test.go
  • database/migration/grammars/postgres.go
  • database/migration/sql_driver_test.go
  • database/migration/test_utils.go
✅ Files skipped from review due to trivial changes (2)
  • contracts/database/schema/blueprint.go
  • contracts/database/schema/column.go
🧰 Additional context used
🔇 Additional comments (150)
facades/schema.go (1)

4-9: LGTM! Verify the App().MakeSchema() method.

The changes in this file look good and are consistent with the PR objectives. The import statement and function signature have been updated to use the new schema package instead of migration, which aligns with the broader refactoring of the codebase.

To ensure full compatibility, please verify that the App().MakeSchema() method has been updated to return the new schema.Schema type. Run the following script to check the implementation:

✅ Verification successful

Verified: The App().MakeSchema() method returns schema.Schema as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the App().MakeSchema() method implementation

# Search for the MakeSchema method implementation
rg -p "func.*MakeSchema.*schema\.Schema" --type go

Length of output: 356

contracts/database/migration/migrator.go (1)

1-14: Overall, the changes look good and align well with the PR objectives.

The modifications to this file enhance the migration functionality and support multiple database drivers as intended. The new constants and updated Migrator interface provide a solid foundation for the improvements described in the PR.

A few minor suggestions for documentation have been made, but these are not critical. The overall structure and implementation are sound and follow Go best practices.

database/schema/test_utils.go (3)

1-8: LGTM: Package declaration and imports are appropriate.

The package name schema aligns with the file's location, and the imports are relevant to the function's purpose. No unused imports are present.


10-10: LGTM: Function signature is well-defined and purpose-driven.

The GetTestSchema function has a clear name, appropriate parameters for testing, and return types that align with its purpose of providing a test schema and mock ORM.


1-16: Overall assessment: Well-structured test utility with minor improvement opportunities.

This new file introduces a valuable test utility function that aligns with the PR's objectives of enhancing database-related functionalities. It supports the transition from the migration to schema package and provides a convenient way to set up mock schemas and ORMs for testing.

The implementation is generally sound, with only minor suggestions for improvement as noted in the previous comments. These changes would enhance the flexibility and clarity of the code without altering its core functionality.

Great job on adding this test utility to support the new schema management approach!

database/schema/common_schema.go (4)

1-6: LGTM: Package declaration and imports are appropriate.

The package name schema aligns well with the file's location and purpose. The imports are relevant to the functionality provided in this file, importing necessary contracts for ORM and schema operations.


8-11: LGTM: Well-designed struct with appropriate dependencies.

The CommonSchema struct is well-designed, encapsulating the necessary dependencies (grammar and orm) for schema operations. Using interface types for these fields allows for flexibility in implementation and easier testing.


13-18: LGTM: Constructor is properly implemented.

The NewCommonSchema constructor is correctly implemented. It takes the necessary dependencies as parameters and returns a pointer to a new CommonSchema instance, which is a common practice in Go for structs.


1-36: Summary: New file aligns well with PR objectives and follows best practices.

This new file, common_schema.go, introduces the CommonSchema type and associated methods, which align well with the PR's objective of enhancing schema management capabilities. The code is well-structured, follows Go best practices, and provides a solid foundation for the new db:wipe command mentioned in the PR objectives.

The file introduces abstractions that should make it easier to implement and maintain database schema operations across different database drivers, which is in line with the PR's goal of supporting multiple database drivers in the migrate:fresh command.

Overall, this file is a valuable addition to the codebase and contributes significantly to the goals outlined in the PR objectives.

contracts/database/migration/repository.go (3)

11-11: Improved error handling for CreateRepository method

The change to return an error from CreateRepository() is a good improvement. This allows for better error handling and aligns with Go's idiomatic approach to error management. Callers can now check for and handle potential errors during repository creation.


15-15: Improved error handling for DeleteRepository method

The modification to return an error from DeleteRepository() is a positive change. This enhancement allows for better error handling and is consistent with Go's idiomatic approach to error management. It also maintains consistency with the CreateRepository() method, improving the overall interface design.


11-15: Verify implementations of the updated Repository interface

The changes to CreateRepository() and DeleteRepository() improve the consistency and error handling capabilities of the Repository interface. This aligns well with the PR objectives of optimizing migration commands.

To ensure a smooth transition:

  1. Update all implementations of the Repository interface to return appropriate errors for these methods.
  2. Review and update any code that calls these methods to handle the potential errors.

Run the following script to find all implementations of the Repository interface:

This will help identify the structs that need to be updated to match the new interface.

database/schema/common_schema_test.go (1)

1-12: LGTM: Package declaration and imports are appropriate.

The package name "schema" aligns with the file's purpose, and the imports cover necessary testing libraries, database contracts, and support packages required for the test suite.

database/schema/processors/postgres.go (2)

1-5: LGTM: Package declaration and imports are appropriate.

The package name processors aligns with the file's location, and the import of the schema package is relevant for the file's purpose.


14-49: ⚠️ Potential issue

Suggestions for improving the ProcessTypes method.

The ProcessTypes method effectively translates short codes to full type and category names for PostgreSQL. However, there are a few areas that could be improved:

  1. Error Handling: The method doesn't handle cases where a type or category code is not found in the maps. Consider adding error handling for unknown codes.

  2. Input Modification: The method modifies the input slice directly. This might lead to unexpected behavior if the caller doesn't expect the input to be changed. Consider creating a new slice instead.

  3. Documentation: Adding comments explaining the purpose of the method and the meaning of the short codes would improve readability.

Here's a suggested improvement:

// ProcessTypes translates PostgreSQL type and category codes to their full names.
// It returns a new slice with processed types and any errors encountered.
func (r Postgres) ProcessTypes(types []schema.Type) ([]schema.Type, error) {
	processedTypes := make([]schema.Type, len(types))
	copy(processedTypes, types)

	for i, t := range processedTypes {
		if fullType, ok := processType[t.Type]; ok {
			processedTypes[i].Type = fullType
		} else {
			return nil, fmt.Errorf("unknown type code: %s", t.Type)
		}

		if fullCategory, ok := processCategory[t.Category]; ok {
			processedTypes[i].Category = fullCategory
		} else {
			return nil, fmt.Errorf("unknown category code: %s", t.Category)
		}
	}

	return processedTypes, nil
}

Could you clarify if there's a specific reason for modifying the input slice directly instead of returning a new slice? Also, how should unknown type or category codes be handled?

database/console/migration/migrate_command.go (2)

11-11: Excellent refactoring to use migration.Migrator

The change from driver migration.Driver to migrator migration.Migrator is a positive improvement. This abstraction allows for greater flexibility in supporting multiple database drivers, aligning well with the PR objectives. It also simplifies the MigrateCommand struct by removing the need for driver-specific logic.


Line range hint 1-46: Overall excellent refactoring of the MigrateCommand

The changes in this file successfully transition the MigrateCommand from a driver-based approach to a migrator-based approach. This refactoring aligns well with the PR objectives and improves the flexibility of the migration system. The code is now more abstract, allowing for easier support of multiple database drivers.

Key improvements:

  1. Simplified MigrateCommand struct
  2. More flexible and abstract NewMigrateCommand constructor
  3. Consistent update in the Handle method

These changes contribute to a more maintainable and extensible codebase. Great job on this refactoring!

database/schema/processors/postgres_test.go (1)

1-9: LGTM: Package declaration and imports are appropriate.

The package declaration and imports are correct and suitable for a test file. The use of the assert package from gookit/goutil is a good practice for writing clear and concise test assertions.

database/schema/grammars/utils.go (2)

13-19: LGTM! Function signature updated correctly.

The addModify function has been successfully updated to use schema.Blueprint and schema.ColumnDefinition. The logic within the function remains unchanged, which is appropriate as the fundamental operation is still the same.


Line range hint 21-30: LGTM! Function signature updated correctly.

The getColumns function has been successfully updated to use schema.Grammar and schema.Blueprint. The internal logic of the function is preserved, which is appropriate as the fundamental operation of building a list of column SQL definitions remains the same.

database/schema/column.go (5)

1-1: LGTM: Package name change is appropriate.

The change from package migration to package schema aligns with the overall refactoring effort to enhance schema management capabilities. This modification is consistent with the changes observed in other files mentioned in the AI summary.


4-4: LGTM: Import statement updated correctly.

The import statement has been appropriately updated to include the new schema package. This change is necessary to support the package name change and the updated method signatures. The new import path suggests that schema-related contracts have been moved to a separate package, which is consistent with the overall refactoring effort.


20-20: LGTM: Method signatures updated consistently.

The method signatures for AutoIncrement and Nullable have been correctly updated to return schema.ColumnDefinition instead of migration.ColumnDefinition. These changes are consistent with the package name change and the overall refactoring effort. The method bodies remain unchanged, preserving the original functionality.

Also applies to: 82-82


88-88: LGTM: Method signature updated consistently.

The method signature for Unsigned has been correctly updated to return schema.ColumnDefinition instead of migration.ColumnDefinition. This change is consistent with the package name change and the overall refactoring effort. The method body remains unchanged, preserving the original functionality.


Line range hint 1-92: Summary: Consistent refactoring from migration to schema package.

The changes in this file are part of a larger refactoring effort to transition from a migration package to a schema package. The modifications include:

  1. Updating the package name
  2. Adjusting the import statement
  3. Modifying method signatures to return schema.ColumnDefinition

These changes are consistent throughout the file and align with the overall refactoring effort described in the AI summary. The functionality of the methods remains unchanged, ensuring that existing behavior is preserved while improving the organization of the codebase.

database/console/migration/migrate_make_command.go (4)

12-12: Approve: Simplified struct design

The replacement of config and schema fields with a single migrator field of type migration.Migrator is a good design choice. This change aligns well with the PR objectives and the broader refactoring efforts, leading to a more focused and cohesive structure for handling migrations.


15-16: Approve: Consistent constructor update

The NewMigrateMakeCommand function has been appropriately updated to reflect the changes in the struct. The simplified signature, now accepting a single migration.Migrator parameter, improves consistency and makes the dependency more explicit. The implementation correctly initializes the struct with the provided migrator.


58-58: Approve: Streamlined migration creation

The modification in the Handle method to directly use r.migrator.Create(name) is a good improvement. This change simplifies the migration creation process by eliminating the need for an intermediary driver retrieval step. It aligns well with the PR objectives of optimizing migration commands and the overall refactoring efforts. The error handling remains appropriate, ensuring that any issues during migration creation are properly reported.


Line range hint 1-64: Summary: Effective refactoring of MigrateMakeCommand

The changes made to this file effectively refactor the MigrateMakeCommand to use a migration.Migrator interface. This refactoring simplifies the command's structure, improves consistency, and streamlines the migration creation process. These modifications align well with the PR objectives of optimizing database-related commands and contribute to the broader refactoring efforts in the codebase.

Key improvements:

  1. Simplified MigrateMakeCommand struct with a single migrator field.
  2. Updated constructor function with a more focused signature.
  3. Streamlined Handle method implementation for direct migration creation.

These changes should lead to more maintainable and efficient code for handling migration creation.

database/console/migration/migrate_reset_command_test.go (3)

29-29: LGTM: Updated migration driver type aligns with codebase changes.

The change from contractsmigration.DriverSql to contractsmigration.MigratorSql is consistent with the broader refactoring of the migration system. This update ensures that the test setup correctly reflects the new migration handling approach.


34-36: LGTM: Improved test setup with migrator initialization and error handling.

The addition of migrator initialization using migration.NewSqlMigrator(mockConfig) and the subsequent error check enhance the test setup. This change:

  1. Aligns the test with the new migration system architecture.
  2. Improves error handling by ensuring the migrator is properly initialized before proceeding with the test.

These modifications contribute to more robust and reliable tests.


39-39: LGTM: Updated MigrateCommand initialization aligns with new architecture.

The change to NewMigrateCommand(migrator) reflects the shift from using a mock schema to a real migrator instance. This update:

  1. Ensures consistency with changes in other command files.
  2. Provides a more accurate representation of the actual migration process in the test environment.

This modification contributes to more realistic and effective testing of the migration command.

database/console/migration/migrate_status_command_test.go (3)

29-29: LGTM: Updated mock expectation aligns with refactoring

The change from contractsmigration.DriverSql to contractsmigration.MigratorSql is consistent with the overall refactoring of the migration package. This update reflects the shift from a Driver-based approach to a Migrator-based approach, which should provide more flexibility and modularity in handling database migrations.


39-39: LGTM: Simplified MigrateCommand creation

The update to NewMigrateCommand(migrator) is a positive change that simplifies the command creation process. By using the concrete Migrator instance instead of separate config and schema mocks, this modification:

  1. Reduces the number of dependencies for the MigrateCommand.
  2. Improves testability by using a real Migrator implementation.
  3. Aligns with the overall refactoring effort to make the migration system more modular.

This change should lead to more maintainable and easier to understand test code.


Line range hint 1-55: Overall assessment: Successful implementation of migration package refactoring

The changes in this file successfully implement the refactoring of the migration package as outlined in the PR objectives and AI summary. The test has been updated to use the new Migrator-based approach, maintaining good error handling and test structure. These modifications contribute to a more modular and flexible migration system.

A few key points:

  1. The transition from Driver to Migrator is consistently applied.
  2. The introduction of a concrete SqlMigrator improves testability.
  3. The simplification of the MigrateCommand creation reduces dependencies.

These changes should lead to more maintainable and easier to understand code, both in the production code and the tests.

database/schema/postgres_schema_test.go (4)

3-14: LGTM: Import statements are well-organized and relevant.

The import statements are properly structured, including necessary packages for testing, mocking, and database operations. The use of mock packages suggests good test isolation practices.


16-22: LGTM: PostgresSchemaSuite struct is well-defined.

The PostgresSchemaSuite struct is properly structured with embedded suite.Suite and necessary fields for mocking and database interaction. This setup allows for both unit testing with mocks and integration testing with a real database connection.


32-38: LGTM: SetupTest method is comprehensive and well-structured.

The SetupTest method effectively initializes all necessary components for testing, including:

  1. Setting up a PostgreSQL Docker instance
  2. Initializing a test query
  3. Creating mock objects for configuration and ORM

This setup ensures a clean, isolated test environment and allows for both integration testing with a real database and unit testing with mocks.


1-55: Overall assessment: Well-structured test suite with room for minor improvements.

This new test file for PostgreSQL schema functionality demonstrates good testing practices:

  1. Proper use of test suites and mocking.
  2. Integration with Docker for realistic database testing.
  3. Coverage of main scenarios in the implemented tests.

Areas for potential improvement:

  1. Adding more comprehensive test cases for TestGetSchema.
  2. Implementing the TestGetTypes method as noted in the TODO.
  3. Adding brief comments to explain the purpose of each test method.

These improvements will enhance the overall quality and maintainability of the test suite.

contracts/database/schema/grammar.go (5)

1-1: LGTM: Package name change is appropriate.

The change from package migration to package schema accurately reflects the broader focus on schema management rather than just migrations. This aligns well with the overall restructuring of the codebase.


14-15: LGTM: New method CompileDropAllDomains enhances schema management capabilities.

The addition of CompileDropAllDomains method is a valuable enhancement to the Grammar interface. It provides the ability to compile SQL for dropping multiple domains, which is particularly useful for PostgreSQL database management.


16-17: LGTM: New method CompileDropAllTables adds bulk table drop functionality.

The addition of CompileDropAllTables method is a useful enhancement to the Grammar interface. It allows for compiling SQL to drop multiple tables at once, which can be particularly helpful for database cleanup or reset operations.


26-27: LGTM: New method CompileTypes enhances schema introspection capabilities.

The addition of the CompileTypes method is a valuable enhancement to the Grammar interface. It provides the ability to compile a query for determining the types in the database, which is crucial for schema introspection and management.


28-29: LGTM: New method CompileViews further enhances schema introspection capabilities.

The addition of the CompileViews method is another valuable enhancement to the Grammar interface. It provides the ability to compile a query for determining the views in the database, which complements the CompileTypes method and further improves the schema introspection and management capabilities.

database/schema/column_test.go (4)

Line range hint 1-9: LGTM: Package name change aligns with refactoring.

The change from package migration to package schema is consistent with the broader refactoring mentioned in the PR summary. The imports are appropriate for a test file.


Line range hint 11-20: LGTM: Well-structured test suite.

The ColumnDefinitionTestSuite struct and the TestColumnDefinitionTestSuite function are well-defined, following best practices for using the testify package in Go tests.


Line range hint 22-24: LGTM: Proper test setup.

The SetupTest method correctly initializes a new ColumnDefinition for each test, ensuring a clean state for each test case.


Line range hint 26-31: LGTM: Comprehensive auto-increment test.

The GetAutoIncrement test method effectively checks both the initial state and the state after invoking AutoIncrement, ensuring the functionality works as expected.

database/console/migration/migrate_rollback_command_test.go (3)

29-29: Approved: Updated mock configuration to use MigratorSql

This change reflects the transition from using the Driver interface to the Migrator interface for handling migrations. It aligns with the broader refactoring of the migration system mentioned in the PR summary.


Line range hint 1-58: Summary: Significant updates to migration system testing

The changes in this file reflect a broader refactoring of the migration system, transitioning from a Driver interface to a Migrator interface. Key points:

  1. Updated mock configuration to use MigratorSql instead of DriverSql.
  2. Introduced a real SQL migrator instance instead of using a mock schema.
  3. Updated the MigrateCommand instantiation to use the new migrator.

These changes should provide more accurate and reliable test results by using actual components instead of mocks. However, it's important to ensure that these modifications haven't negatively impacted the test coverage or introduced any new edge cases that aren't being tested.

To ensure the changes haven't introduced any regressions, please run the full test suite for the migration package and verify that all tests pass:


40-40: Approved: Updated MigrateCommand instantiation

The migrateCommand is now correctly instantiated with the new SQL migrator, which is consistent with the previous changes and reflects a more direct approach in testing the migration command.

To ensure this change doesn't negatively impact test coverage, please run the following command and verify that the test coverage for the MigrateCommand remains the same or has improved:

database/console/migration/migrate_make_command_test.go (4)

15-16: LGTM: Improved imports and introduced mockMigrator

The removal of unused imports and the introduction of mockMigrator align well with the PR's objectives. These changes contribute to code cleanliness and reflect the shift towards using a migrator interface for migration operations.

Also applies to: 21-21


33-34: LGTM: Updated mock expectations for Happy path scenarios

The mock expectations for the "Happy path" scenarios have been effectively updated to use the new mockMigrator object. This change accurately reflects the expected behavior of the MigrateMakeCommand and aligns with the PR's objective of updating the migration command functionality.

Also applies to: 41-41


67-67: LGTM: Improved test execution and assertion

The updated NewMigrateMakeCommand function call and the simplified assertion improve the test's clarity and align with the PR's objectives. The use of mockMigrator and the expectErr flag in the assertion provide a clear and maintainable way to verify the command's behavior in various scenarios.

Also applies to: 70-70


Line range hint 1-73: Overall assessment: Significant improvements to test structure and coverage

The changes made to this test file are comprehensive and align well with the PR's objectives. The introduction of the mockMigrator, improved test case structure, and additional error scenario coverage enhance the overall quality of the tests. The modifications reflect a shift towards using a migrator interface for migration operations, which is consistent with the broader changes in the PR.

Key improvements:

  1. Cleaner import statements
  2. Introduction of mockMigrator
  3. Better test case naming and structure
  4. Improved coverage with new "Sad path" scenarios
  5. Simplified and more maintainable assertions

These changes contribute positively to the codebase's quality and testability. The minor suggestions provided for future improvements (adding brief comments for test cases and considering more specific error checks) can be addressed in subsequent iterations to further enhance the test suite.

database/schema/grammars/utils_test.go (4)

8-9: LGTM: Import statements updated correctly.

The import statements have been properly updated to reflect the package restructuring from migration to schema. This change aligns with the PR objectives and ensures consistency with the new schema management approach.


50-50: LGTM: TestGetType function updated correctly.

The TestGetType function has been properly updated to use the new mocksschema package for creating mock objects. These changes are consistent with the updates made throughout the file and maintain the original test logic.

Also applies to: 53-53, 59-59, 62-62


Line range hint 1-74: Overall changes look good and maintain test integrity.

The updates in this file successfully transition the test suite from using the migration package to the new schema package. All necessary changes have been made consistently, including import statements and mock object creations. The original test logic and coverage appear to be maintained, ensuring that the refactoring doesn't introduce any regressions in test functionality.


13-13: LGTM: TestGetColumns function updated consistently.

The TestGetColumns function has been successfully updated to use the new schema package and mocksschema mocks. All references to the old migration package have been correctly replaced, maintaining the original logic of the test.

To ensure all references have been updated, run the following command:

Also applies to: 17-17, 21-22, 26-27

database/migration/repository.go (3)

5-5: LGTM: Import statement updated correctly.

The new import for the schema package aligns with the changes in the file, supporting the transition from migration.Schema to schema.Schema.


9-9: LGTM: Repository struct updated correctly.

The schema field type has been updated from migration.Schema to schema.Schema, which is consistent with the import changes and aligns with the PR's objective of restructuring the migration system.


13-13: LGTM: NewRepository function signature updated correctly.

The NewRepository function now accepts schema.Schema instead of migration.Schema, which is consistent with the changes made to the Repository struct and aligns with the overall restructuring of the migration system.

database/migration/default_creator_test.go (1)

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

The modifications to the DefaultCreatorSuite test cases consistently update the Up and Down method signatures to return errors, which aligns with the PR objectives to enhance error handling in migration methods. The changes are applied uniformly across all test cases, maintaining consistency throughout the file.

A few minor suggestions have been made to improve code clarity and error handling:

  1. Adding comments to explain stub implementations in test cases.
  2. Updating the "Create stub" test case to properly handle and return potential errors from schema operations.

These suggestions, if implemented, would further enhance the quality and robustness of the test suite.

database/console/migration/migrate_refresh_command_test.go (4)

29-29: LGTM: Updated mock configuration to use new MigratorSql constant.

This change aligns with the transition from a Driver interface to a Migrator interface in the migration system. It ensures that the test is using the correct constant for the new implementation.


41-41: LGTM: Updated MigrateCommand instantiation to use new Migrator.

This change aligns with the broader refactoring of the migration system. By passing the migrator directly to NewMigrateCommand, we're adhering to the new design where the Migrator encapsulates configuration and schema operations. This should lead to better separation of concerns and easier testing.


51-51: LGTM: Reused err variable for database query.

This is a minor change that reuses the err variable instead of redeclaring it. It's a common practice in Go and doesn't affect functionality. It slightly reduces the number of variables in the scope, which can improve readability.


Line range hint 1-89: Overall assessment: Well-implemented refactoring of migration system tests.

The changes in this file successfully adapt the tests to the new Migrator-based approach in the migration system. Key improvements include:

  1. Updated mock configurations to use the new MigratorSql constant.
  2. Proper instantiation and error handling for the new SqlMigrator.
  3. Updated MigrateCommand instantiation to use the new Migrator.
  4. Minor code style improvements like reusing the err variable.

These changes align well with the broader refactoring of the migration system and should provide a solid foundation for testing the new implementation.

database/migration/repository_test.go (3)

6-6: LGTM: New imports are correctly added.

The new import statements are necessary and correctly added to support the changes in the test file. They enable mocking, contract definitions, and schema management, which are used in the updated and new functions.

Also applies to: 10-10, 12-12


72-72: LGTM: Consistent error handling added.

The addition of error checking for the CreateRepository call in the TestRecord function is consistent with the changes made in TestCreate_Delete_Exists. This improvement ensures that any errors during repository creation are properly caught and reported in the test.


Line range hint 1-162: Overall, excellent improvements to the repository tests.

The changes in this file consistently enhance the quality of the tests:

  1. Improved error handling for repository operations.
  2. Introduction of a helper function for mocking transactions.
  3. Better schema initialization in tests.
  4. Consistent use of mocking throughout the test cases.

These improvements align well with the PR objectives of optimizing database-related commands by ensuring robust testing of the underlying repository operations.

Great job on these enhancements! The test suite is now more robust and maintainable.

database/migration/stubs.go (1)

Line range hint 1-214: Overall, the changes improve error handling in migration stubs.

The modifications to the Up and Down methods in the DummyMigration struct are consistent and align with the PR objectives. These changes enhance error handling capabilities for migration processes.

Consider applying similar error handling improvements to the database-specific stubs (MySQL, Postgres, SQLite, SQLServer) if they are used in actual migrations. This would ensure consistent error handling across all migration types.

To ensure consistency across the codebase, let's verify if similar changes have been made in other migration-related files:

This will help identify any other files that might benefit from similar error handling improvements.

✅ Verification successful

Verified: The error handling improvements in database/migration/stubs.go are consistent and no additional updates are required in the identified mock or test migration files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other migration-related files that might need similar updates
echo "Files that might need similar updates:"
rg -l "func.*Up\(\s*\)" --type go | grep -v "stubs.go"
rg -l "func.*Down\(\s*\)" --type go | grep -v "stubs.go"

Length of output: 518


Script:

#!/bin/bash
# Extract Up and Down methods from identified migration-related files to verify error handling

files=(
  "mocks/database/schema/Migration.go"
  "mocks/database/migration/Migration.go"
  "database/migration/default_creator_test.go"
  "database/migration/default_migrator_test.go"
)

for file in "${files[@]}"; do
  echo "Analyzing file: $file"

  # Extract Up method
  echo "Up method in $file:"
  ast-grep --pattern 'func (.*) Up() error' "$file" | sed -n '/func .* Up() error/,/^}/p'
  
  # Extract Down method
  echo "Down method in $file:"
  ast-grep --pattern 'func (.*) Down() error' "$file" | sed -n '/func .* Down() error/,/^}/p'
  
  echo ""
done

Length of output: 2761

contracts/foundation/application.go (1)

13-13: LGTM: Import statement updated correctly.

The import statement has been updated from "migration" to "schema", which aligns with the overall restructuring of the codebase from migration to schema management.

database/console/wipe_command_test.go (1)

1-11: LGTM: Package declaration and imports are well-structured.

The package declaration and imports are correctly set up. The use of aliased imports for mocks improves code readability.

errors/list.go (5)

69-69: LGTM: New error message for SQL migrator initialization.

The addition of MigrationSqlMigratorInit error is well-defined and consistent with the existing error naming conventions. It provides a clear message for SQL migration driver initialization failures, which aligns with the PR's objective of enhancing the migrate command.


99-99: LGTM: New error message for unsupported schema drivers.

The addition of SchemaDriverNotSupported error is well-defined and consistent with the existing error naming conventions. It provides a clear message for unsupported schema drivers, which is important for proper error handling in the schema management system.


100-101: LGTM: New error messages for table creation and deletion failures.

The additions of SchemaFailedToCreateTable and SchemaFailedToDropTable errors are well-defined and consistent with the existing error naming conventions. They provide clear messages for failures in creating and dropping tables, which are crucial for proper error handling in schema operations. These additions align well with the PR's objective of enhancing the schema management system.


102-102: LGTM: Retention of error message for failure to get tables.

The retention of the SchemaFailedToGetTables error is appropriate. It maintains consistency with the newly added schema-related errors and continues to provide clear error messaging for failures in retrieving tables. This retention aligns well with the PR's objective of enhancing the schema management system.


Line range hint 69-102: Overall assessment: Excellent additions to error handling for migration and schema operations.

The changes in this file consistently improve error handling for migration and schema operations. The new error messages are well-defined, follow existing naming conventions, and provide clear, actionable information. These enhancements align perfectly with the PR's objectives of optimizing the migrate command and supporting multiple database drivers.

Great job on maintaining code quality and improving the robustness of the error handling system!

foundation/container.go (2)

19-19: LGTM: Import statement updated to reflect package restructuring.

The change from migration to schema in the import statement aligns with the PR objective of updating database-related functionalities. This modification is consistent with the broader restructuring of the migration package into a schema package.


Line range hint 1-385: Overall assessment: Changes are minimal and align with PR objectives.

The modifications to this file are limited to updating the import statement and the MakeSchema method, both of which are consistent with the broader restructuring of database-related packages mentioned in the PR objectives. The rest of the file remains unchanged, maintaining the existing functionality of the Container struct and its methods.

database/schema/grammars/postgres_test.go (10)

8-9: LGTM: Import statements updated to reflect package refactoring.

The changes to the import statements correctly align with the transition from the migration package to the schema package. This update ensures consistency with the new architecture of the database schema management system.


27-29: LGTM: Mock declarations updated to use new schema package.

The changes to the mock declarations are consistent with the updated import statements. The test logic remains intact, ensuring that the functionality is still properly tested with the new schema package.


92-94: LGTM: Mock setup in TestCompileCreate updated to use schema package.

The changes to the mock setup in TestCompileCreate are consistent with the overall refactoring to the schema package. The test logic remains unchanged, ensuring that the CompileCreate functionality is still properly tested.


142-142: LGTM: Mock declaration in TestCompileDropIfExists updated.

The change to the mock declaration in TestCompileDropIfExists is consistent with the transition to the schema package. The test logic remains intact, ensuring that the CompileDropIfExists functionality is still properly tested.


150-151: LGTM: Mock declarations in TestModifyDefault updated to use schema package.

The changes to the mock declarations in TestModifyDefault are consistent with the transition to the schema package. The test structure and logic remain unchanged, ensuring that the ModifyDefault functionality is still properly tested.


203-204: LGTM: Mock instantiations in TestModifyDefault updated.

The changes to the mock instantiations within the test loop of TestModifyDefault are consistent with the transition to the schema package. The test setup remains logically equivalent, ensuring that each test case for ModifyDefault is still properly configured.


216-216: LGTM: Mock setup in TestModifyNullable updated to use schema package.

The changes to the mock setup in TestModifyNullable are consistent with the transition to the schema package. The test logic remains intact, ensuring that the ModifyNullable functionality is still properly tested across various scenarios.

Also applies to: 218-218


241-241: LGTM: Mock setup in TestModifyIncrement updated to use schema package.

The changes to the mock setup in TestModifyIncrement are consistent with the transition to the schema package. The test structure and assertions remain unchanged, ensuring that the ModifyIncrement functionality is still properly tested.

Also applies to: 243-243


257-257: LGTM: Mock setups in type-specific tests updated to use schema package.

The changes to the mock setups in TestTypeBigInteger, TestTypeInteger, and TestTypeString are consistent with the transition to the schema package. The test logic in each function remains intact, ensuring that the type-specific functionalities are still properly tested.

Also applies to: 262-262, 269-269, 274-274, 281-281, 286-286


Line range hint 1-290: Overall assessment: Successful refactoring to schema package

The changes in this file consistently update the mock package references from migration to schema across all test functions. This refactoring aligns well with the broader architectural changes described in the PR objectives and AI summary. The preservation of test logic throughout these changes suggests that the functionality should remain intact, reducing the risk of introducing new bugs during this refactoring process.

A few key points to note:

  1. The import statements have been correctly updated to reflect the new package structure.
  2. All mock declarations and instantiations now use the mocksschema package instead of mocksmigration.
  3. The underlying test logic, expectations, and assertions remain unchanged, ensuring continued coverage of the PostgreSQL grammar functionality.

These changes contribute to improved modularity and clarity in the database schema management system while maintaining the integrity of the existing tests.

database/console/migration/migrate_fresh_command_test.go (2)

13-17: Variable declarations are appropriate.

The mock variables are correctly declared and will be used in the tests.


19-23: Good use of beforeEach function for test setup.

Encapsulating the setup logic into a beforeEach function improves code readability and avoids duplication in your tests.

database/console/migration/migrate_fresh_command.go (4)

13-14: Addition of 'migrator' field improves modularity

Introducing the migrator field to the MigrateFreshCommand struct enhances dependency injection and aligns with the application's architecture, promoting better modularity and testability.


17-20: Constructor updated for cleaner dependency management

Updating NewMigrateFreshCommand to accept the migrator parameter simplifies dependency management and makes the codebase more maintainable by injecting required dependencies explicitly.


25-35: Consistent receiver naming enhances readability

Changing the receiver from receiver to r across all methods provides consistency and improves code readability, adhering to Go's conventions for receiver names.


65-65: ⚠️ Potential issue

Validate seeder names to prevent command injection

Concatenating user-provided input into command strings can lead to command injection vulnerabilities. Ensure that the seeder inputs are properly validated before use.

[security]

To verify that seeder names are safe, consider adding validation or sanitization. Here's a script to help identify any unsafe seeder names:

Consider implementing input validation before using seederFlag:

 // Seed the database if the "seed" flag is provided
 if ctx.OptionBool("seed") {
     seeders := ctx.OptionSlice("seeder")
+    // Validate seeder names
+    for _, seeder := range seeders {
+        if !isValidSeederName(seeder) {
+            color.Red().Println("Invalid seeder name:", seeder)
+            return nil
+        }
+    }
     seederFlag := ""
     if len(seeders) > 0 {
         seederFlag = " --seeder " + strings.Join(seeders, ",")
     }
     r.artisan.Call("db:seed" + seederFlag)
 }

And define the validation function:

func isValidSeederName(name string) bool {
    // Add your validation logic here
    // For example, allow only letters, numbers, and underscores
    validName := regexp.MustCompile(`^[a-zA-Z0-9_]+$`)
    return validName.MatchString(name)
}
✅ Verification successful

Seeder names are properly validated, preventing command injection vulnerabilities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for unsafe characters in seeder names.

# Get all seeder names used in the codebase
rg 'OptionSlice\("seeder"\)' -A 5 | grep -oP '(?<=OptionSlice\("seeder"\)).*' | tr -d '[],"' | tr ' ' '\n' | while read -r seeder; do
  if [[ $seeder =~ [^a-zA-Z0-9_,] ]]; then
    echo "Unsafe seeder name detected: $seeder"
  fi
done

Length of output: 886


Script:

#!/bin/bash
# Description: Accurately extract seeder names and check for unsafe characters using ast-grep.

# Use ast-grep to find string literals passed to OptionSlice("seeder")
ast-grep --pattern 'OptionSlice("seeder")($$)' --go \
  | grep -oP '(?<=")[a-zA-Z0-9_,]+(?=")' \
  | while read -r seeder; do
    if [[ ! "$seeder" =~ ^[a-zA-Z0-9_,]+$ ]]; then
      echo "Unsafe seeder name detected: $seeder"
    fi
  done

Length of output: 333


Script:

#!/bin/bash
# Description: Accurately extract seeder names and check for unsafe characters using ast-grep.

# Use ast-grep to find string literals passed to OptionSlice("seeder") in Go files
ast-grep --pattern 'OptionSlice("seeder")("$_")' --globs "*.go" \
  | grep -oP '(?<=")[a-zA-Z0-9_,]+(?=")' \
  | while read -r seeder; do
    if [[ ! "$seeder" =~ ^[a-zA-Z0-9_,]+$ ]]; then
      echo "Unsafe seeder name detected: $seeder"
    fi
  done

Length of output: 121

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

8-9: Embedding CommonSchema and DriverSchema into Schema interface

Embedding the CommonSchema and DriverSchema interfaces into the Schema interface enhances modularity and allows for a clear separation of common and driver-specific schema operations.


34-39: Introduction of CommonSchema interface enhances modularity

The addition of the CommonSchema interface separates common schema operations, improving modularity and facilitating better code organization.


41-50: Addition of DriverSchema interface improves driver-specific schema management

Introducing the DriverSchema interface allows for driver-specific schema operations, enhancing flexibility and maintainability by segregating driver-dependent functionalities.


84-84: Added Schema field to Table struct

Including the Schema field in the Table struct enhances the ability to manage tables within specific schemas, providing better support for databases that use schemas.


88-95: Introduction of Type struct for database types management

The new Type struct facilitates handling of database types, enabling operations like retrieving and dropping custom types, which is especially useful for databases like PostgreSQL.


96-100: Added View struct to represent database views

The addition of the View struct allows for better management of database views within the schema package, providing capabilities to retrieve and manipulate views.


56-56: ⚠️ Potential issue

Ensure error handling for updated Migration interface methods Up and Down

The Up and Down methods in the Migration interface now return an error. Please ensure that all implementations of the Migration interface and all invocations of these methods are updated to handle the returned errors to maintain robust error propagation during migrations.

To verify that all implementations and calls to Up and Down methods handle errors appropriately, run the following script:

#!/bin/bash
# Description: Find all implementations and usages of Up and Down methods that need error handling.

# Find all implementations of the Migration interface's Up method not returning error
rg -A 1 'func (\w+) Up\(' -g '*.go' | rg -L 'error'

# Find all usages of Up method without error handling
rg '\.Up\(' -g '*.go' | rg -v 'if err' | rg -v 'err :='

# Find all implementations of Down method not returning error
rg -A 1 'func (\w+) Down\(' -g '*.go' | rg -L 'error'

# Find all usages of Down method without error handling
rg '\.Down\(' -g '*.go' | rg -v 'if err' | rg -v 'err :='

Also applies to: 58-58

database/service_provider.go (8)

7-7: Approved: Added necessary import for contractsmigration package.

The import statement correctly includes the contractsmigration package needed for migration handling.


12-12: Approved: Added necessary import for schema package.

The import statement correctly includes the schema package required for schema management.


60-60: Approved: Updated schema initialization to use new schema package.

The return statement now uses schema.NewSchema, aligning with the updated schema management approach.


74-77: Approved: Initialized log, schema, and seeder dependencies.

The added initializations ensure that all necessary dependencies are available before proceeding with command registration.


78-78: Approved: Added nil checks for all essential components.

The conditional check verifies that artisan, config, log, schema, and seeder are not nil, preventing potential nil pointer dereferences.


81-95: Approved: Properly initialized migrator with enhanced error handling.

The code correctly initializes the migrator based on the database.migrations.driver configuration, handling different driver options and logging errors appropriately if an unsupported driver is provided.


97-102: Approved: Updated migration commands to utilize the new migrator.

The migration commands now use the migrator variable, ensuring they operate with the correct migration system and configurations.


109-109: Approved: Added new WipeCommand for database cleanup.

The console.NewWipeCommand(config, schema) enhances the console commands by adding the ability to wipe the database, improving database management capabilities.

database/schema/postgres_schema.go (1)

34-61: Verify the implementation of GetTables method

The DropAllTables() function relies on r.GetTables(), but the implementation of GetTables() is not provided. Ensure that GetTables() is correctly implemented and returns the expected list of tables to avoid runtime errors.

database/schema/schema.go (2)

81-89: Verify error handling for the DropIfExists method

Similar to the Create method, DropIfExists now returns an error. Please ensure that all places where DropIfExists is called are updated to handle the error to maintain robustness.

Use this script to find and review all calls to DropIfExists:

#!/bin/bash
# Description: Find all calls to the DropIfExists method and check for error handling.

# Test: Search for usages of 'DropIfExists(' and check if the returned error is handled.
rg -t go 'DropIfExists\(' -A 2 -B 2 | grep -E 'err\s*:='

69-78: Ensure consistent error handling in the Create method

The Create method now returns an error, which is a good practice for error propagation. Please verify that all callers of this method are updated to handle the returned error appropriately to prevent unhandled errors.

Run the following script to identify usages of the Create method and ensure error handling is in place:

✅ Verification successful

All callers of the Create method are handling errors appropriately.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to the Create method and check for error handling.

# Test: Search for usages of 'Create(' and check if the returned error is handled.
rg -t go 'Create\(' -A 2 -B 2 | grep -E 'err\s*:='

Length of output: 128


Script:

#!/bin/bash
# Description: Find all calls to the Create method and check if the returned error is handled.

# Search for usages of 'Create(' and check if the returned error is handled with error handling.
rg -t go 'Create\(' -A 2 -B 2 | grep -E 'err\s*:='

Length of output: 6866

database/migration/sql_migrator.go (4)

24-27: Renaming to SqlMigrator enhances clarity.

Changing the struct name from SqlDriver to SqlMigrator better reflects its purpose and improves code readability. The addition of the migrator field integrates the *migrate.Migrate instance directly into the struct, which streamlines the migration operations.


31-47: Constructor error handling is appropriate, but verify table configuration.

The NewSqlMigrator function correctly initializes the SqlMigrator instance and handles errors from getMigrator. However, it's important to ensure that the table retrieved from the configuration is not empty to prevent unexpected behavior during migrations.

Please verify that the table variable is properly set in the configuration. You might consider adding a check like:

if table == "" {
    return nil, fmt.Errorf("migrations table name is not configured")
}

68-82: Fresh method implementation is correct and efficient.

The Fresh method effectively resets the migrations by dropping all tables and rerunning the migrations. Reassigning the migrator after recreating ensures that the migrator instance is up-to-date.


84-87: Proper error handling in Run method.

The Run method correctly handles the case where there are no new migrations to apply by checking against migrate.ErrNoChange, ensuring that it doesn't return an error unnecessarily.

database/schema/schema_test.go (10)

1-1: Package name change to schema is appropriate

The package name has been changed from migration to schema, which accurately reflects the functionality within this file.


6-11: Import statements have been correctly updated

The import statements have been updated to reflect the new package structure. This ensures that dependencies are correctly referenced.


42-42: Updated schema initialization to use GetTestSchema

Replaced initSchema with GetTestSchema for initializing the schema in tests. This change aligns with the refactored schema management approach.


46-46: Added error handling with s.NoError

Including s.NoError for schema.DropIfExists strengthens the test by verifying that the operation completes without errors.


50-52: Ensured error-free table creation with s.NoError

Wrapping schema.Create with s.NoError enhances test robustness by checking for errors during table creation.


60-60: Added error handling for dropping table

Consistent use of s.NoError for schema.DropIfExists ensures that any errors are caught during the drop operation.


68-94: Added new test method TestDropAllTables

The TestDropAllTables method effectively tests the DropAllTables functionality. The test setup and assertions are comprehensive and well-structured.


109-114: Initialized schema with GetTestSchema and added error handling

The test TestTable_GetTables has been updated to use GetTestSchema and includes error handling with s.NoError, improving test reliability.


183-188: Added error handling in TestSql

Including s.NoError when creating the table in TestSql enhances the test by ensuring that the table creation is successful.


203-206: Added mockTransaction helper function for transaction mocking

The mockTransaction function simplifies setting up transaction mocks in tests, improving code reusability and test clarity.

database/schema/grammars/postgres.go (2)

47-47: Undefined Functions 'getColumns' and 'prefixArray'

This issue is similar to the one mentioned earlier. The functions getColumns and prefixArray are used but not defined or imported.


58-58: Undefined Functions 'getColumns' and 'prefixArray'

As previously noted, getColumns and prefixArray are used here without being defined or imported. This needs to be addressed to avoid compilation errors.

database/migration/default_migrator_test.go (13)

11-14: Imports are correctly updated to reflect new package structure.

The imports include the new schema contract and mock implementations, aligning with the refactored architecture. This ensures the tests utilize the correct interfaces and mock objects.


19-25: Struct DefaultMigratorSuite updated with necessary mock dependencies.

The DefaultMigratorSuite struct now includes mockArtisan, mockRepository, and mockSchema, along with the updated driver field of type *DefaultMigrator. This properly sets up the test suite with all required dependencies for the new migrator implementation.


28-29: Test suite initialization correctly reflects the migrator changes.

The test suite function TestDefaultMigratorSuite is appropriately renamed and initializes the suite with &DefaultMigratorSuite{}. This ensures that the tests are organized under the correct suite name, matching the updated migrator.


32-39: SetupTest initializes mock objects and driver correctly.

The SetupTest method now initializes mockArtisan, mockRepository, mockSchema, and assigns a new DefaultMigrator to s.driver, injecting the necessary mocks. This setup is crucial for the tests to run accurately with the new migrator functionalities.


Line range hint 46-66: TestCreate function accurately tests migration file creation with proper teardown.

The test simulates the creation of a migration file, verifies its existence, and ensures cleanup after execution. It uses carbon.SetTestNow for consistent timestamping, which is essential for predictable test results.


Line range hint 74-143: TestRun method effectively covers multiple scenarios including error handling.

The test cases within TestRun cover both successful execution and various error paths, such as errors from Log and GetNextBatchNumber. This comprehensive coverage ensures the migrator behaves correctly under different conditions.


Line range hint 144-157: TestPendingMigrations correctly identifies and returns pending migrations.

The test verifies that the pendingMigrations function accurately filters out migrations that have already been run, ensuring only pending ones are returned. This is crucial for the migrator to apply only necessary migrations.


158-166: TestPrepareDatabase properly tests repository existence and creation.

The test checks both scenarios where the repository exists and where it does not, ensuring that CreateRepository is called appropriately. This guarantees that the migrator can prepare the database correctly for migrations.


Line range hint 167-225: TestRunPending method comprehensively tests the execution of pending migrations.

Multiple test cases simulate different conditions, including no pending migrations and errors from GetNextBatchNumber and runUp. This thorough testing strengthens the reliability of the migrator's pending migrations execution.


Line range hint 226-245: TestRunUp verifies migration execution and connection handling.

The test ensures that migrations are applied correctly and that the schema connection is appropriately managed when a migration specifies a different connection. This is important for multi-database setups.


253-257: TestMigration.Up method correctly updated to return an error.

The Up method now returns an error, aligning with Go's standard practices and the updated interface requirements. This change allows for proper error propagation during migrations.


259-260: TestMigration.Down method updated to return an error.

Similarly, the Down method now returns an error, ensuring consistency and enabling proper error handling during rollback operations.


275-279: TestConnectionMigration.Up correctly implements the new method signature and logic.

The method returns an error and increments the suite's value, adhering to the updated interface and fulfilling the intended test behavior.

database/schema/blueprint_test.go (7)

Line range hint 1-13: Code refactoring from 'migration' to 'schema' is correctly implemented

The changes in the package declaration and imports from migration to schema are consistent and correctly reflect the restructuring of the codebase.


20-25: Update of grammars field and initialization is accurate

The grammars field in the BlueprintTestSuite struct has been updated to use schema.Grammar, and its initialization in TestBlueprintTestSuite correctly reflects this change.


Line range hint 37-47: Mocks and expected commands updated to use schema package

The replacement of mocksmigration.Grammar with mocksschema.Grammar and updating expectCommands to []*schema.Command ensures that the tests align with the new schema package.


Line range hint 68-88: Test cases in TestAddAttributeCommands are properly adjusted

Test cases now correctly use schema.Command and are set up to test the new schema commands appropriately.


91-99: Mocks in TestAddImpliedCommands are correctly updated

The mock grammar in TestAddImpliedCommands is appropriately changed to use mocksschema.Grammar, ensuring consistency in the test setup.


Line range hint 116-167: Adjustment of test expectations aligns with schema changes

The expected commands in the test cases reflect the changes to the schema.Command type, and the logic within the tests accurately accommodates the new schema definitions.


Line range hint 179-188: Initialization of mock grammar is correctly implemented

The instantiation of mockGrammar using mocksschema.NewGrammar(s.T()) ensures that the tests use the correct mock objects from the updated schema package.

krishankumar01
krishankumar01 previously approved these changes Oct 21, 2024
Copy link
Member

@krishankumar01 krishankumar01 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 Oct 21, 2024
@hwbrzzl hwbrzzl reopened this Oct 21, 2024
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: 14

🧹 Outside diff range and nitpick comments (21)
database/console/migration/migrate_command.go (1)

39-44: LGTM: Improved Handle method with better error handling and output

The changes to the Handle method are well-implemented and consistent with the overall refactoring:

  1. Migration execution now uses r.migrator.Run(), aligning with previous changes.
  2. Error handling has been improved, using a structured approach with errors.MigrationMigrateFailed.
  3. Output now uses ctx.Error() and ctx.Info(), which is more idiomatic for console commands.

These changes enhance error reporting and maintain consistency with the new Migrator interface.

Consider returning the error instead of nil when migration fails:

 if err := r.migrator.Run(); err != nil {
 	ctx.Error(errors.MigrationMigrateFailed.Args(err).Error())
-	return nil
+	return err
 }

This allows callers to handle the error if needed.

database/console/migration/migrate_status_command.go (2)

49-49: Improved error handling for empty database config.

The use of a predefined error and the context's Error method is a good improvement. It standardizes error handling and improves consistency across the codebase.

Consider adding a return statement after the error to explicitly exit the function:

 ctx.Error(errors.ConsoleEmptyDatabaseConfig.Error())
-return nil
+return errors.ConsoleEmptyDatabaseConfig

This would propagate the error up the call stack, allowing for better error handling at higher levels.


55-55: Enhanced error reporting for migration status retrieval.

The use of a predefined error with arguments and the context's Error method is a good improvement. It provides more detailed error information and maintains consistency with the new error handling approach.

Consider returning the error instead of nil:

 ctx.Error(errors.MigrationGetStatusFailed.Args(err).Error())
-return nil
+return errors.MigrationGetStatusFailed.Args(err)

This would allow for proper error propagation and handling at higher levels of the application.

database/console/migration/migrate_make_command.go (1)

59-63: Simplified migration creation and improved output handling

The changes in the Handle method effectively utilize the new migrator field, simplifying the migration creation process. The use of ctx.Info for output is a good practice for consistency across the framework.

However, consider enhancing the error handling:

 if err := r.migrator.Create(name); err != nil {
-    return err
+    return fmt.Errorf("failed to create migration %s: %w", name, err)
 }

 ctx.Info(fmt.Sprintf("Created Migration: %s", name))

This change would provide more context in case of an error, making debugging easier.

database/console/migration/migrate_rollback_command.go (2)

65-65: Consistent error handling with improved context

The change to ctx.Error() with errors.MigrationRollbackFailed.Args(err) is a good improvement. It maintains consistency with the new error handling approach and provides more detailed error information.

Consider adding a comment explaining what type of error err represents here, to provide more context for future maintainers. For example:

// err here represents a parsing error for the 'step' argument
ctx.Error(errors.MigrationRollbackFailed.Args(err).Error())

75-75: Standardized output messaging

The changes to use ctx.Error() and ctx.Info() instead of color-specific print functions are excellent improvements. They complete the standardization of output messaging in this file, making it more maintainable and consistent.

To ensure consistency across the entire codebase, consider creating constants for common messages like "Migration rollback success". This would allow for easier updates and translations in the future. For example:

const (
    MigrationRollbackSuccessMsg = "Migration rollback success"
)

// Then use it like this:
ctx.Info(MigrationRollbackSuccessMsg)

You might want to place these constants in a separate file that can be imported by all migration-related commands.

Also applies to: 81-81

database/console/migration/migrate_refresh_command.go (2)

75-76: LGTM: Consistent error handling with room for improvement

The use of ctx.Error with errors.MigrationRefreshFailed.Args(err) is a good improvement for consistent error handling.

Consider adding more context to the error message, such as including the step value that caused the failure. This could help with debugging:

ctx.Error(errors.MigrationRefreshFailed.Args(err).WithContext("step", step).Error())

92-93: LGTM: Consistent error handling for migration operations

The use of ctx.Error for both the migration down and up operations maintains consistency in error handling. This is a good improvement.

Consider refactoring the error handling into a separate function to reduce code duplication:

func handleMigrationError(ctx console.Context, err error) {
    if err != nil && !errors.Is(err, migrate.ErrNoChange) {
        ctx.Error(errors.MigrationRefreshFailed.Args(err).Error())
    }
}

Then you can use it like this:

if err = m.Down(); err != nil {
    handleMigrationError(ctx, err)
    return nil
}

if err = m.Up(); err != nil {
    handleMigrationError(ctx, err)
    return nil
}

This would make the code more DRY and easier to maintain.

Also applies to: 99-100

support/console/console_test.go (1)

137-195: Well-structured test function with comprehensive coverage.

The TestConfirmToProceed function is well-organized and covers the main scenarios for the ConfirmToProceed function. The table-driven approach allows for easy addition of new test cases.

However, there are a few suggestions for improvement:

  1. Consider using the env field consistently across all test cases for clarity.
  2. In the "confirm returns err" case, consider adding an explicit check for the returned error.
  3. Add verification of mock expectations after each test case.

Here's a suggested improvement for the test function:

 func TestConfirmToProceed(t *testing.T) {
 	var (
 		mockCtx *consolemocks.Context
 	)
 
 	beforeEach := func() {
 		mockCtx = &consolemocks.Context{}
 	}
 
 	tests := []struct {
 		name         string
 		env          string
 		setup        func()
 		expectResult bool
+		expectErr    error
 	}{
 		{
 			name:         "env is not production",
+			env:          "development",
 			setup:        func() {},
 			expectResult: true,
 		},
 		{
 			name: "the force option is true",
 			env:  "production",
 			setup: func() {
 				mockCtx.EXPECT().OptionBool("force").Return(true).Once()
 			},
 			expectResult: true,
 		},
 		{
 			name: "confirm returns err",
 			env:  "production",
 			setup: func() {
 				mockCtx.EXPECT().OptionBool("force").Return(false).Once()
 				mockCtx.EXPECT().Confirm("Are you sure you want to run this command?").Return(false, assert.AnError).Once()
 				mockCtx.EXPECT().Error(errors.ConsoleFailedToConfirm.Args(assert.AnError).Error()).Once()
 			},
 			expectResult: false,
+			expectErr:    errors.ConsoleFailedToConfirm.Args(assert.AnError),
 		},
 		{
 			name: "confirm returns true",
 			env:  "production",
 			setup: func() {
 				mockCtx.EXPECT().OptionBool("force").Return(false).Once()
 				mockCtx.EXPECT().Confirm("Are you sure you want to run this command?").Return(true, nil).Once()
 			},
 			expectResult: true,
 		},
 	}
 
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			beforeEach()
 			tt.setup()
-			result := ConfirmToProceed(mockCtx, tt.env)
+			result, err := ConfirmToProceed(mockCtx, tt.env)
 
 			assert.Equal(t, tt.expectResult, result)
+			if tt.expectErr != nil {
+				assert.Equal(t, tt.expectErr, err)
+			} else {
+				assert.NoError(t, err)
+			}
+			mockCtx.AssertExpectations(t)
 		})
 	}
 }

These changes ensure consistent usage of the env field, add explicit error checking, and verify mock expectations after each test case.

database/console/driver/sqlite.go (1)

Line range hint 145-190: Suggestion: Improve error handling and query building

While the current implementation is functional, consider the following improvements:

  1. Error Handling: The error handling in this method is repetitive. Consider creating a helper function to wrap errors consistently.

  2. Query Building: Instead of using string concatenation for SQL queries, consider using prepared statements or a query builder. This would make the code more resistant to SQL injection (even though it's not a current issue) and easier to maintain.

Example of a helper function for error handling:

func (m *Sqlite) dbError(err error, query string) error {
    return &database.Error{OrigErr: err, Query: []byte(query)}
}

Then you could simplify error handling like this:

if err = tables.Err(); err != nil {
    return m.dbError(err, query)
}

For query building, consider using a library like squirrel or creating simple helpers to build your queries.

errors/list.go (5)

70-72: LGTM: New migration-related errors are well-defined.

The new error variables for migration operations are consistent and provide specific error messages. They also include placeholders for additional error details, which is helpful for debugging.

Consider adding SetModule(ModuleMigration) to these errors for consistency with other module-specific errors in the file.


74-77: LGTM: Additional migration-related errors are well-defined.

The new error variables for migration operations are consistent and provide specific error messages. They also include placeholders for additional error details, which is helpful for debugging.

Consider adding SetModule(ModuleMigration) to these errors for consistency with other module-specific errors in the file.


107-107: LGTM: New schema-related error is well-defined.

The new error variable SchemaDriverNotSupported is consistent with the existing error style and provides a specific error message for unsupported schema drivers.

Consider adding SetModule(ModuleSchema) to this error for consistency with other module-specific errors in the file.


108-110: LGTM: Additional schema-related errors are well-defined.

The new error variables for schema operations are consistent and provide specific error messages. They also include placeholders for additional error details, which is helpful for debugging.

Consider adding SetModule(ModuleSchema) to these errors for consistency with other module-specific errors in the file.


Line range hint 1-134: Overall, the changes to errors/list.go are well-implemented and consistent.

The new error variables introduced for console operations, migrations, and schema management are well-defined and follow the existing patterns in the file. They provide clear and specific error messages that will be helpful for debugging and user feedback.

For consistency, consider adding the appropriate SetModule() calls to all new error variables, similar to how it's done for console-related errors (e.g., SetModule(ModuleMigration) for migration errors and SetModule(ModuleSchema) for schema errors).

database/schema/schema.go (1)

Line range hint 137-142: Consider returning an error instead of exiting on failure in Table method

Currently, the Table method terminates the program using r.log.Fatalf when r.build(blueprint) returns an error. To improve error handling and maintain consistency with methods like Create and DropIfExists, consider modifying Table to return an error instead of exiting. This change allows caller functions to handle errors appropriately.

Apply this diff to update the method:

-func (r *Schema) Table(table string, callback func(table schema.Blueprint)) {
+func (r *Schema) Table(table string, callback func(table schema.Blueprint)) error {
	blueprint := r.createBlueprint(table)
	callback(blueprint)

	if err := r.build(blueprint); err != nil {
-		r.log.Fatalf("failed to modify %s table: %v", table, err)
+		return fmt.Errorf("failed to modify %s table: %w", table, err)
	}
+	return nil
}
database/schema/schema_test.go (5)

96-100: Reminder: Address the TODO comment in TestDropAllTypes.

The TestDropAllTypes function is currently empty and marked with a TODO. Implement this test after adding the create type functionality to ensure comprehensive test coverage.

Would you like assistance in drafting this test method or opening a GitHub issue to track this task?


101-105: Reminder: Address the TODO comment in TestDropAllViews.

The TestDropAllViews function is empty and has a TODO comment. Please implement this test once the create view feature is available to validate the view-related schema operations.

Would you like help in creating this test method or opening a GitHub issue to track its implementation?


Line range hint 109-177: Consider removing or clarifying the commented-out code in TestTable_GetTables.

There's a substantial block of commented-out code within the TestTable_GetTables method. This can reduce code readability and may cause confusion for future contributors.

If this code is intended for future use, consider adding comments to explain its purpose or tracking the pending work in an issue tracker. Otherwise, if it's no longer needed, it would be better to remove it to keep the codebase clean.


Line range hint 178-196: Handle errors returned by schema.Sql in TestSql.

In the TestSql method, the call to schema.Sql does not check for returned errors. For robust test practices, it's important to handle potential errors from this operation.

Apply this diff to incorporate error handling:

 func (s *SchemaSuite) TestSql() {
 	for driver, testQuery := range s.driverToTestQuery {
 		s.Run(driver.String(), func() {
 			schema, mockOrm := GetTestSchema(s.T(), testQuery)
 			mockTransaction(mockOrm, testQuery)

-			s.NoError(schema.Create("sql", func(table contractsschema.Blueprint) {
+			err := schema.Create("sql", func(table contractsschema.Blueprint) {
 				table.String("name")
 			}))
+			s.NoError(err)

 			mockOrm.EXPECT().Query().Return(testQuery.Query()).Once()

-			schema.Sql("insert into goravel_sql (name) values ('goravel');")
+			err = schema.Sql("insert into goravel_sql (name) values ('goravel');")
+			s.NoError(err)

 			var count int64
 			err = testQuery.Query().Table("sql").Where("name", "goravel").Count(&count)

 			s.NoError(err)
 			s.Equal(int64(1), count)
 		})
 	}
 }

198-201: Add documentation to mockTransaction for improved clarity.

The mockTransaction helper function lacks comments explaining its purpose. Adding a brief description will enhance code readability and assist future developers.

Include a comment above the function to describe its role in mocking transaction behavior in tests.

+// mockTransaction simulates a database transaction for testing purposes.
 func mockTransaction(mockOrm *mocksorm.Orm, testQuery *gorm.TestQuery) {
 	mockOrm.EXPECT().Transaction(mock.Anything).RunAndReturn(func(txFunc func(contractsorm.Query) error) error {
 		return txFunc(testQuery.Query())
 	}).Once()
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ed5b5a1 and 9364860.

⛔ Files ignored due to path filters (1)
  • mocks/database/schema/Grammar.go is excluded by !mocks/**
📒 Files selected for processing (20)
  • contracts/database/schema/grammar.go (2 hunks)
  • database/console/driver/sqlite.go (1 hunks)
  • database/console/migration/migrate_command.go (2 hunks)
  • database/console/migration/migrate_fresh_command.go (3 hunks)
  • database/console/migration/migrate_make_command.go (2 hunks)
  • database/console/migration/migrate_refresh_command.go (4 hunks)
  • database/console/migration/migrate_reset_command.go (1 hunks)
  • database/console/migration/migrate_rollback_command.go (2 hunks)
  • database/console/migration/migrate_status_command.go (2 hunks)
  • database/migration/default_creator_test.go (3 hunks)
  • database/migration/sql_migrator_test.go (1 hunks)
  • database/migration/stubs.go (3 hunks)
  • database/schema/grammars/postgres.go (1 hunks)
  • database/schema/grammars/postgres_test.go (9 hunks)
  • database/schema/postgres_schema.go (1 hunks)
  • database/schema/schema.go (5 hunks)
  • database/schema/schema_test.go (4 hunks)
  • errors/list.go (3 hunks)
  • support/console/console.go (1 hunks)
  • support/console/console_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • database/migration/default_creator_test.go
  • database/migration/stubs.go
  • database/schema/postgres_schema.go
🧰 Additional context used
🔇 Additional comments (48)
database/console/migration/migrate_command.go (3)

7-7: LGTM: Import of errors package

The addition of the errors package import is consistent with the improved error handling in the Handle method. This change enhances the overall error management in the command.


11-11: LGTM: Migrator field replacement

The replacement of the driver field with a migrator field of type migration.Migrator aligns well with the PR objectives. This change reflects a more focused approach to migration operations and is consistent with the broader refactoring of the migration system.


14-16: LGTM: Simplified constructor with improved dependency injection

The changes to the NewMigrateCommand constructor are well-implemented:

  1. The function now accepts a migration.Migrator, aligning with the struct field change.
  2. This simplifies the constructor by removing the need for driver retrieval and error handling.
  3. It improves separation of concerns by depending on a higher-level Migrator interface.

These changes contribute to a more maintainable and flexible design.

database/console/migration/migrate_reset_command.go (4)

46-46: Improved error handling for empty database configuration

The change from color.Yellow().Println() to ctx.Error() with a specific error type enhances error reporting consistency and aligns with the framework's conventions. This modification improves the overall robustness of the command.


53-53: Consistent improvement in error handling for migration reset failure

This change follows the same pattern as the previous one, using ctx.Error() with a specific error type. The use of Args(err) ensures that the original error details are preserved, which is crucial for debugging. This consistent approach to error handling across the file is commendable.


58-58: Standardized success message output

The change to ctx.Info() for the success message completes the standardization of output in this file. This consistent approach to both error and success messaging improves the overall coherence of the command's output handling. The message is clear and effectively communicates the operation's success.


46-58: Overall improvement in error handling and messaging

The changes in this file consistently enhance error handling and messaging by leveraging the context's methods (ctx.Error() and ctx.Info()). This standardization improves the robustness and maintainability of the migrate:reset command, aligning well with the PR objectives.

To ensure consistency across the codebase, let's verify if similar changes have been applied to related migration command files:

This will help confirm that the standardization has been applied uniformly across all migration commands.

✅ Verification successful

Consistent usage of ctx.Error() and ctx.Info() across migration command files

Verified that all migration command files consistently utilize ctx.Error() and ctx.Info() methods, ensuring standardized error handling and messaging throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent use of ctx.Error() and ctx.Info() in migration command files

# Test: Search for ctx.Error() and ctx.Info() usage in migration command files
rg -U 'ctx\.(Error|Info)\(' database/console/migration/*_command.go

Length of output: 2719

database/console/migration/migrate_status_command.go (4)

4-5: LGTM: Import changes are consistent with code modifications.

The addition of "fmt" and "errors" imports, along with the removal of the "color" package, aligns well with the changes in error handling and output formatting in the Handle method.

Also applies to: 12-12


61-63: LGTM: Improved consistency in status output.

The use of ctx.Warning and ctx.Info for outputting the migration status (dirty/clean) is a good improvement. It maintains consistency with the new approach of using context methods for output and allows for better control of the output format at a higher level.


66-66: LGTM: Consistent approach for version output.

The use of ctx.Info with fmt.Sprintf for outputting the migration version is a good improvement. It aligns with the new standardized approach of using context methods for output, enhancing consistency across the codebase.


Line range hint 1-69: Overall assessment: Improved error handling and output consistency.

The changes in this file significantly enhance error handling and output consistency. The use of predefined errors and context methods for output aligns well with similar modifications in other files, as mentioned in the AI summary. These improvements contribute to better maintainability and readability of the migration functionality.

A few minor suggestions have been made to further improve error propagation, but overall, the changes are well-implemented and achieve the intended goals of the PR.

database/console/migration/migrate_make_command.go (3)

13-13: Improved struct design with focused migration handling

The removal of config and schema fields in favor of a single migrator field of type migration.Migrator simplifies the struct and improves its focus on migration operations. This change aligns well with the PR's objective of optimizing migration commands.


16-17: Consistent update to constructor function

The NewMigrateMakeCommand function has been appropriately updated to reflect the changes in the struct. The simplified signature, now accepting only a migration.Migrator, is consistent with the struct modifications and reduces unnecessary dependencies.


Line range hint 1-67: Overall improvement in code structure and migration handling

The changes in this file significantly improve the MigrateMakeCommand by:

  1. Simplifying the struct and its dependencies
  2. Focusing the command on migration operations through the use of the migrator field
  3. Streamlining the migration creation process in the Handle method

These modifications align well with the PR's objective of optimizing migration commands and should lead to more maintainable and focused code.

database/console/migration/migrate_fresh_command.go (6)

8-8: LGTM: Import addition is appropriate.

The new import for the migration package is correctly added and aligns with the subsequent changes in the file.


13-14: LGTM: Struct field addition is appropriate.

The addition of the migrator field of type migration.Migrator is in line with the PR objectives and the overall refactoring of the migration package. This change enhances the command's functionality by providing direct access to migration operations.


17-20: LGTM: Constructor updates are consistent.

The changes to the constructor signature and body correctly reflect the addition of the migrator field to the struct. This ensures proper initialization of the MigrateFreshCommand with the necessary dependencies.


25-25: LGTM: Consistent receiver variable naming.

The change from receiver to r in method signatures improves code consistency and readability. This stylistic update is a good practice for maintaining clean and uniform code.

Also applies to: 30-30, 35-35, 52-52


53-54: LGTM: Handle method refactored effectively.

The Handle method has been significantly simplified while maintaining its core functionality:

  1. The use of r.migrator.Fresh() aligns with the PR objectives and the overall refactoring of the migration package.
  2. Error handling has been improved, addressing the previous review comment about exposing internal error details. The new approach using ctx.Error provides a more secure way of reporting errors.
  3. The seeding logic is retained, ensuring that existing functionality is preserved.

These changes enhance the method's clarity and maintainability while addressing previous concerns.

Also applies to: 65-65, 68-68


Line range hint 1-71: Overall: Excellent refactoring of the MigrateFreshCommand

The changes in this file successfully implement the PR objectives:

  1. The command now uses the new migration.Migrator interface, aligning with the broader refactoring of the migration package.
  2. Error handling has been improved, addressing previous concerns about exposing internal details.
  3. Code consistency and readability have been enhanced through uniform naming conventions.

The refactoring maintains existing functionality while simplifying the implementation, resulting in more maintainable and robust code.

contracts/database/schema/grammar.go (8)

14-15: LGTM: New method CompileDropAllDomains added.

The addition of CompileDropAllDomains method enhances the Grammar interface by providing functionality to compile SQL for dropping multiple domains. The method signature is clear and consistent with its intended purpose.


16-17: LGTM: New method CompileDropAllTables added.

The addition of CompileDropAllTables method enhances the Grammar interface by providing functionality to compile SQL for dropping multiple tables. The method signature is clear and consistent with its intended purpose.


18-19: LGTM: New method CompileDropAllTypes added with correct parameter name.

The addition of CompileDropAllTypes method enhances the Grammar interface by providing functionality to compile SQL for dropping multiple types. The method signature is correct and consistent with its intended purpose. The previously raised issue about the parameter name has been addressed.


20-21: LGTM: New method CompileDropAllViews added with correct parameter name.

The addition of CompileDropAllViews method enhances the Grammar interface by providing functionality to compile SQL for dropping multiple views. The method signature is correct and consistent with its intended purpose. The previously raised issue about the parameter name has been addressed.


26-27: LGTM: New method CompileTypes added.

The addition of CompileTypes method enhances the Grammar interface by providing functionality to compile a query for determining types. The method signature is clear and consistent with its intended purpose.


28-29: LGTM: New method CompileViews added.

The addition of CompileViews method enhances the Grammar interface by providing functionality to compile a query for determining views. The method signature is clear and consistent with its intended purpose.


1-1: Package name changed from migration to schema.

The package name has been updated from migration to schema, which better reflects the broader scope of database schema management functionalities provided by this package.


Line range hint 1-29: Overall enhancement of the Grammar interface.

The changes to the Grammar interface significantly enhance its capabilities for managing database schemas. New methods have been added to support dropping various database objects (domains, tables, types, views) and compiling queries to determine types and views. These additions provide a more comprehensive set of tools for database schema management.

database/console/migration/migrate_rollback_command.go (2)

57-57: Improved error handling and consistency

The change from color.Yellow().Println() to ctx.Error() is a good improvement. It standardizes error reporting through the context and removes the direct dependency on the color package. Using a predefined error (ConsoleEmptyDatabaseConfig) also enhances consistency and maintainability across the codebase.


Line range hint 1-84: Overall assessment: Improved error handling and consistency

The changes in this file significantly enhance error handling and output messaging consistency. By standardizing the use of ctx.Error() and ctx.Info(), the code becomes more maintainable and aligns well with Go best practices. These modifications support the PR objectives by improving the migrate:rollback command's robustness and user feedback.

The removal of direct color formatting in favor of context-based messaging is a positive step towards a more flexible and consistent codebase. This approach will make it easier to implement potential future enhancements, such as localization or custom formatting of console output.

These changes, combined with the suggested minor improvements, contribute to a more robust and maintainable codebase, which is crucial for the ongoing development and optimization of the framework's database migration capabilities.

support/console/console.go (1)

86-101: Excellent implementation of the ConfirmToProceed function!

The function is well-structured and addresses the concerns raised in the previous review. Notable improvements include:

  1. Proper environment and force option checks.
  2. Enhanced error handling for the confirmation prompt.
  3. Appropriate use of the ctx.Error method for logging errors.

The implementation provides a robust mechanism for confirming potentially destructive operations, especially in production environments.

database/console/migration/migrate_refresh_command.go (4)

66-67: LGTM: Consistent error handling

The change to use ctx.Error for reporting the empty database configuration error is a good improvement. It aligns with the standardized approach to error handling across the codebase.


85-86: LGTM: Consistent error handling in switch statement

The use of ctx.Error here maintains consistency with the error handling approach throughout the file. It's correctly placed in the default case of the switch statement to handle unexpected errors.


113-113: LGTM: Consistent success message handling

The use of ctx.Info for the success message is a good change. It maintains consistency with the new approach of using console.Context methods for output and clearly indicates the successful completion of the migration refresh operation.


Line range hint 1-115: Overall assessment: Improved consistency and error handling

The changes made to this file significantly improve the consistency of error handling and output messaging. By transitioning to the use of console.Context methods (ctx.Error and ctx.Info), the code now aligns better with the broader changes made across the codebase. This approach enhances maintainability and provides a more uniform user experience when interacting with the command-line interface.

While the changes are generally positive, there are a few minor suggestions for further improvement:

  1. Consider adding more context to error messages where applicable.
  2. Explore opportunities to refactor common error handling patterns into separate functions to reduce code duplication.

These suggestions aside, the modifications effectively achieve the goal of standardizing error handling and output messaging in the MigrateRefreshCommand.

database/console/driver/sqlite.go (1)

145-145: Approve: Improved slice initialization

This change from tableNames := make([]string, 0) to var tableNames []string is a good optimization. It's more idiomatic Go code, slightly more efficient (as it doesn't allocate any initial capacity), and doesn't change the functionality. This approach is preferred when the initial size of the slice is unknown and you're going to append to it.

errors/list.go (1)

16-19: LGTM: New console-related errors are well-defined.

The new error variables ConsoleEmptyDatabaseConfig and ConsoleFailedToConfirm are consistent with the existing error style and use the appropriate module setting. The messages are clear and descriptive, which will help with debugging and user feedback.

database/schema/grammars/postgres_test.go (8)

8-9: LGTM: Import statements updated correctly.

The import statements have been appropriately updated to reflect the shift from migration-centric to schema-centric approach. This change is consistent with the overall refactoring mentioned in the summary.


27-29: LGTM: Mock types updated consistently.

The mock variable types have been correctly updated to use the new mocksschema package instead of mocksmigration. This change is consistent with the import statement updates and the overall refactoring approach.


92-94: LGTM: Mock initializations updated correctly.

The mock variable initializations have been properly updated to use the new mocksschema package. This change is consistent with the previous updates to import statements and mock types.


142-142: LGTM: Mock initialization updated consistently.

The mock variable initialization for mockBlueprint has been correctly updated to use mocksschema.NewBlueprint. This change is consistent with the previous updates in the file.


148-163: LGTM: New TestEscapeNames function added.

The new TestEscapeNames function is a valuable addition to the test suite. It covers important scenarios for name escaping in PostgreSQL, including single names, multiple names with dot notation, and empty input. This test enhances the coverage of the EscapeNames method in the Postgres grammar.


167-168: LGTM: Mock types updated consistently in TestModifyDefault.

The mock variable types in the TestModifyDefault function have been correctly updated to use mocksschema.Blueprint and mocksschema.ColumnDefinition. These changes are consistent with the previous updates in the file.


220-221: LGTM: Consistent updates across all remaining test functions.

All remaining test functions (TestModifyDefault, TestModifyNullable, TestModifyIncrement, TestTypeBigInteger, TestTypeInteger, and TestTypeString) have been consistently updated to use the new mocksschema package for mock initializations. These changes align with the overall refactoring from a migration-centric to a schema-centric approach.

The consistency of these changes across the entire file demonstrates a thorough and systematic update of the test suite. The core logic and expectations of the tests remain unchanged, preserving the integrity of the test cases while adapting to the new schema-based structure.

Also applies to: 233-233, 235-235, 258-258, 260-260, 274-274, 279-279, 286-286, 291-291, 298-298, 303-303


Line range hint 1-305: Overall assessment: Comprehensive and consistent refactoring.

The changes in this file demonstrate a thorough and consistent refactoring from a migration-centric to a schema-centric approach. Key points:

  1. All import statements and mock initializations have been updated to use the new schema and mocksschema packages.
  2. The core logic and expectations of existing tests remain unchanged, preserving the integrity of the test suite.
  3. A new TestEscapeNames function has been added, improving the coverage of the Postgres grammar's name escaping functionality.

These changes align well with the larger refactoring effort described in the AI summary. The updates maintain the existing test coverage while adapting to the new schema-based structure, ensuring that the PostgreSQL schema handling remains thoroughly tested after the refactoring.

database/migration/sql_migrator_test.go (2)

96-97: Verify idempotency when running migrations multiple times

Running migrator.Run() multiple times should not cause errors or alter the database state unexpectedly. Ensure that the migrator handles redundant executions gracefully.

Consider adding assertions to confirm that the database state remains consistent after consecutive runs.


33-35: Confirm all supported drivers are included in tests

Ensure that s.driverToTestQuery in SetupSuite includes all the database drivers you intend to support.

Run the following script to list all drivers included in the tests:

database/schema/grammars/postgres.go (1)

164-170: Verify the logic for primary key assignment in ModifyIncrement

In the ModifyIncrement method, the condition checks for !blueprint.HasCommand("primary") before assigning primary key to an auto-incrementing column. This logic might introduce issues if the table already has a primary key or if multiple columns are set to auto-increment.

Please verify that this logic aligns with the intended schema design. If multiple columns could be auto-incrementing or if the primary key is defined elsewhere, this condition may need adjustment.

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 (3)
database/console/migration/migrate_reset_command_test.go (1)

50-51: LGTM. Improved error handling, but consider using require.Error.

The reassignment of err and the use of assert.Error improve the error handling in this test. This change enhances the test's ability to catch and verify errors.

However, consider using require.Error instead of assert.Error. If this assertion fails, it might be more appropriate to stop the test execution immediately.

Here's a suggested improvement:

-		err = query.Where("name", "goravel").FirstOrFail(&agent)
-		assert.Error(t, err)
+		err = query.Where("name", "goravel").FirstOrFail(&agent)
+		require.Error(t, err)
database/console/migration/migrate_make_command_test.go (2)

26-59: LGTM: Improved test coverage with explicit happy and sad path scenarios.

The updated test structure now covers both successful and error scenarios, which is a significant improvement. The use of mockMigrator is consistent with the new command implementation.

Consider adding a constant for the test migration name (e.g., "create_users_table") to improve maintainability and reduce duplication across test cases.


72-72: LGTM: Simplified error assertion.

The change to assert.NoError simplifies the error checking and assumes proper error handling within the command. This is consistent with the improved error handling mentioned in the PR objectives.

Consider adding specific error checks for the sad path test cases to ensure that the expected errors are being returned and handled correctly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9364860 and f219719.

📒 Files selected for processing (10)
  • database/console/migration/migrate_fresh_command_test.go (1 hunks)
  • database/console/migration/migrate_make_command.go (2 hunks)
  • database/console/migration/migrate_make_command_test.go (2 hunks)
  • database/console/migration/migrate_refresh_command_test.go (2 hunks)
  • database/console/migration/migrate_reset_command_test.go (1 hunks)
  • database/console/migration/migrate_rollback_command_test.go (1 hunks)
  • database/console/migration/migrate_status_command_test.go (1 hunks)
  • database/console/wipe_command.go (1 hunks)
  • database/console/wipe_command_test.go (1 hunks)
  • errors/list.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • database/console/migration/migrate_fresh_command_test.go
  • database/console/migration/migrate_make_command.go
  • database/console/migration/migrate_rollback_command_test.go
  • database/console/migration/migrate_status_command_test.go
  • database/console/wipe_command_test.go
🧰 Additional context used
🔇 Additional comments (26)
database/console/migration/migrate_reset_command_test.go (4)

34-36: LGTM. Improved migrator initialization with error handling.

The introduction of NewSqlMigrator and the associated error handling enhances the test setup. This change aligns with the broader refactoring of the migration system and improves the robustness of the test.


40-40: LGTM. Updated command initialization to use migrator.

The change to use the migrator instance in NewMigrateCommand is consistent with the updated migration logic. This modification ensures that the test accurately reflects the new structure of the migration system.


44-45: LGTM. Enhanced test expectations and improved readability.

The addition of the expectation for the "Migration reset success" message strengthens the test by verifying the correct output. The empty line improves code readability.


29-29: LGTM. Verify consistent usage of MigratorSql.

The change from DriverSql to MigratorSql aligns with the updated migration handling approach. This looks good, but it's important to ensure this change is consistent across the codebase.

Let's verify the consistent usage of MigratorSql:

✅ Verification successful

Consistent usage of MigratorSql confirmed.

All instances of MigratorSql are appropriately used in migration contexts, and DriverSql remains correctly utilized for general database configurations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instances of DriverSql and verify MigratorSql usage

# Search for any remaining instances of DriverSql
echo "Checking for any remaining DriverSql instances:"
rg "DriverSql"

# Verify MigratorSql usage
echo "Verifying MigratorSql usage:"
rg "MigratorSql"

Length of output: 6972

database/console/migration/migrate_make_command_test.go (3)

9-11: LGTM: Import changes reflect improved error handling and mock updates.

The new imports align with the refactoring of the migration package and the introduction of more robust error handling. These changes are consistent with the overall improvements described in the PR objectives.


16-17: LGTM: Test setup refactored to use mockMigrator.

The change from using separate mockConfig and mockSchema to a single mockMigrator aligns with the broader refactoring of the migration system. This simplifies the test setup and better reflects the new structure of the migration commands.

Also applies to: 22-22


69-69: LGTM: Command initialization updated to use mockMigrator.

The change in NewMigrateMakeCommand initialization is consistent with the updated method signature and reflects the shift to using a single migrator interface for migration operations. This simplifies the command's dependencies and aligns with the overall refactoring of the migration system.

database/console/wipe_command.go (5)

1-11: LGTM: Package declaration and imports are appropriate.

The package declaration and imports are well-organized and include all necessary dependencies for the WipeCommand implementation.


12-22: LGTM: WipeCommand struct and constructor are well-implemented.

The WipeCommand struct and its constructor are correctly defined, following good practices for dependency injection and initialization.


24-61: LGTM: Command metadata methods are well-defined.

The Signature, Description, and Extend methods provide clear and comprehensive information about the db:wipe command, including appropriate flags for customization.


100-110: LGTM: Helper methods are well-implemented.

The dropAllTables, dropAllViews, and dropAllTypes methods are concise, focused, and provide a clean abstraction for the main Handle method. They follow the single responsibility principle and make the code more maintainable.


1-110: Overall assessment: Well-implemented with minor improvement suggested.

The WipeCommand implementation is generally well-structured and follows good practices. It provides useful functionality for database management within the Goravel framework. The command's structure, metadata, and helper methods are all well-implemented.

The main area for improvement is in the error handling within the Handle method. Addressing this will enhance the robustness of the command and improve its integration with the rest of the system.

Great job on this new feature! Once the error handling is adjusted, this will be a valuable addition to the framework's database management capabilities.

database/console/migration/migrate_refresh_command_test.go (7)

29-29: LGTM: Updated migration driver expectation.

The change from DriverSql to MigratorSql is consistent with the overall migration system refactoring described in the PR objectives. This update aligns the test with the new migration architecture.


34-36: LGTM: Introduced new SqlMigrator with proper error handling.

The addition of NewSqlMigrator and the accompanying error check enhances the test's robustness. This change aligns with the PR's goal of updating the migration system and improves error handling.


42-42: LGTM: Updated MigrateCommand creation to use new migrator.

The change in how the MigrateCommand is created reflects the updated function signature and is consistent with the new migration system architecture. This modification ensures that the test uses the newly introduced migrator.


48-49: LGTM: Added expectation for success message.

The addition of the expectation for the "Migration refresh success" message enhances the test coverage by verifying that the command provides appropriate feedback upon successful execution.


54-56: LGTM: Improved variable reuse.

The reuse of the err variable instead of redeclaration improves code consistency. This change doesn't affect the test's functionality but enhances its readability and adheres to good coding practices.


61-63: LGTM: Consistent updates to expectations and command creation.

The addition of the "Migration success" message expectation and the updated MigrateCommand creation are consistent with earlier changes in the file. These modifications maintain the improved test coverage and alignment with the new migration system.


70-72: LGTM: Enhanced test coverage for seeding scenarios.

The additions of expectations for the "Migration refresh success" message and the seed command calls significantly improve the test coverage. These changes verify the correct behavior of the refresh command under different seeding conditions (with and without specific seeders), ensuring a more comprehensive test suite.

Also applies to: 83-85

errors/list.go (7)

32-38: LGTM: New console-related error variables are well-defined.

The new error variables for console operations are clear, follow the existing naming convention, and use proper formatting for variable insertion. They cover important scenarios such as failing to drop tables, types, or views, empty database configurations, and confirmation failures.


39-40: LGTM: ConsoleRunInProduction error variable is well-defined.

The new error variable for running commands in production environments is clear and provides helpful guidance on using the --force option. It follows the existing naming convention and addresses an important safety concern for production environments.


49-53: LGTM: New Docker-related error variables are well-defined.

The new error variables for Docker operations are clear, follow a consistent naming convention (Docker prefix), and use proper formatting for variable insertion. They cover important scenarios such as unknown container types, insufficient database containers, zero container count, and missing container IDs.


74-82: LGTM: New migration-related error variables are well-defined.

The new error variables for migration operations are clear, follow the existing naming convention (Migration prefix), and use proper formatting for variable insertion. They cover a comprehensive range of migration scenarios, including creation, fresh migration, status retrieval, migration execution, refresh, reset, rollback, and SQL migrator initialization.


112-115: LGTM: New and updated schema-related error variables are well-defined.

The new error variables for schema operations (SchemaDriverNotSupported, SchemaFailedToCreateTable, SchemaFailedToDropTable) are clear, follow the existing naming convention (Schema prefix), and use proper formatting for variable insertion. The minor update to SchemaFailedToGetTables maintains consistency with the new error variables.


Line range hint 1-134: LGTM: File structure and consistency are maintained.

The new error variables have been added in appropriate sections, maintaining the file's organization by functionality. The additions are consistent with the existing style and naming conventions, preserving the overall readability and structure of the file.


Line range hint 1-134: Verification: Changes align with PR objectives and AI-generated summary.

The new error variables introduced in this file align well with the PR objectives and the AI-generated summary:

  1. Error variables for dropping tables, types, and views (e.g., ConsoleDropAllTablesFailed) support the new db:wipe command.
  2. New migration-related errors (e.g., MigrationFreshFailed) support the updated migrate:fresh command.
  3. The addition of schema-related errors (e.g., SchemaFailedToCreateTable) aligns with the refactoring of the migration package into a schema package mentioned in the AI-generated summary.

These changes enhance error handling across various methods, as noted in the summary.

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 21, 2024
@hwbrzzl hwbrzzl merged commit 3796cbd into master Oct 21, 2024
@hwbrzzl hwbrzzl deleted the bowen/#280-9 branch October 21, 2024 06:46
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