Skip to content

feat: [#635] Optimize the process of generating migration and model (#2)#1049

Merged
krishankumar01 merged 54 commits intomasterfrom
kkumar-gcc/#635-2
Dec 3, 2025
Merged

feat: [#635] Optimize the process of generating migration and model (#2)#1049
krishankumar01 merged 54 commits intomasterfrom
kkumar-gcc/#635-2

Conversation

@krishankumar01
Copy link
Member

@krishankumar01 krishankumar01 commented May 26, 2025

📑 Description

Closes goravel/goravel#635

This PR adds a new flag -m/--model to the make:migration command. It will try to resolve the provided model and generate a migration file based on that model. This feature mostly relies on gorm tags to support custom behavior.

Below is how you can use this feature:

// Register your model to the schema facade so that it can be discovered at runtime

func (receiver *DatabaseServiceProvider) Boot(app foundation.Application) {
	facades.Schema().Extend(schema.Extension{
		Models: []any{models.AllFeatures{}},
	})
}
// Define model
type AllFeatures struct {
	orm.Model
	SKU        string         `gorm:"column:sku_code;size:100;unique;not null;default:'SKU-001';comment:'Stock Keeping Unit'"`
	Price      uint           `gorm:"type:decimal(10,2);unsigned;index"`
	Status     string         `gorm:"type:enum('pending','active','inactive');default:'pending'"`
	Metadata   []byte         `gorm:"type:json"`
	OtherData  map[string]any `gorm:"type:json"`
	Ignored    string         `gorm:"-"`
	Relation   User           `gorm:"foreignKey:UserID"` // will be ignored as it is a relation
	Categories []User         // will be ignored as it is a relation
}

Note

The model registration (discovery) can be optimized further. Currently, it registers model instances, but this can be improved. Looking for more suggestions on how to make this process cleaner and more efficient.

Call make:migration command to generate:

go run . artisan make:migration -m AllFeatures 

Below is the generated migration file:

func (r *M20251130103337AllFeatures) Up() error {
	return facades.Schema().Table("comprehensive_test_models", func(table schema.Blueprint) {
		table.TimestampTz("created_at").Nullable()
		table.TimestampTz("updated_at").Nullable()
		table.BigIncrements("id")
		table.String("sku_code", 100).Default("SKU-001").Comment("Stock Keeping Unit")
		table.Decimal("price").Unsigned().Nullable()
		table.Enum("status", []any{"pending", "active", "inactive"}).Nullable().Default("pending")
		table.Json("metadata").Nullable()
		table.Json("other_data").Nullable()

		table.Index("price")
		table.Unique("sku_code")
	})
}

✅ Checks

  • Added test cases for my code

@krishankumar01 krishankumar01 requested a review from a team as a code owner May 26, 2025 17:46
@codecov
Copy link

codecov bot commented May 27, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.56%. Comparing base (2b4df4c) to head (b9081b5).
⚠️ Report is 3 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1049      +/-   ##
==========================================
+ Coverage   68.42%   68.56%   +0.14%     
==========================================
  Files         264      264              
  Lines       15484    15566      +82     
==========================================
+ Hits        10595    10673      +78     
- Misses       4425     4430       +5     
+ Partials      464      463       -1     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@krishankumar01 krishankumar01 marked this pull request as draft May 28, 2025 09:56
@krishankumar01 krishankumar01 marked this pull request as ready for review June 28, 2025 11:28
@krishankumar01 krishankumar01 marked this pull request as draft June 28, 2025 11:28
@hwbrzzl
Copy link
Contributor

hwbrzzl commented Jul 9, 2025

Hi @kkumar-gcc Thanks for your great PR, and FYI, v1.16 is going to be released in about one/two weeks. It would be great if it can be merged before that. Or v1.17 is fine as well.

@hwbrzzl hwbrzzl mentioned this pull request Jul 18, 2025
1 task
@krishankumar01 krishankumar01 marked this pull request as ready for review October 26, 2025 19:19
Copilot AI review requested due to automatic review settings October 26, 2025 19:19
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR optimizes the migration and model generation process by introducing a new structmeta package for struct introspection and a model mapper that automatically generates migration schema from Go struct models. The changes enable automatic migration generation from model definitions with GORM tags, streamlining the development workflow.

Key changes:

  • Added structmeta package for runtime struct metadata extraction including fields, methods, and tags
  • Implemented automatic migration schema generation from Go models with GORM tag parsing
  • Extended Schema to support model registration and retrieval
  • Updated migration command to accept a --model flag for automatic schema generation

Reviewed Changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
support/structmeta/type.go Defines metadata structures for struct introspection (fields, methods, tags)
support/structmeta/structmeta_test.go Test coverage for struct walking and tag parsing functionality
support/structmeta/structmeta.go Core implementation for walking structs and extracting metadata
database/migration/model_mapper.go Maps Go struct models to migration schema lines with GORM tag support
database/migration/model_mapper_test.go Comprehensive tests for model-to-migration conversion
database/migration/stubs.go Updated migration templates to use template variables and support dynamic schema fields
database/migration/migrator.go Enhanced to generate migrations from models using templates and formatting
database/migration/migrator_test.go Updated test to pass empty model name parameter
database/schema/schema.go Added model storage, retrieval, and name extraction functionality
database/schema/schema_test.go Tests for model extension and retrieval
database/console/migration/migrate_make_command.go Added --model flag support for automatic migration generation
contracts/database/schema/schema.go Added Model type and GetModel method to Schema interface
contracts/database/migration/migrator.go Updated Create signature to include modelName parameter
mocks/database/schema/Schema.go Generated mock for new GetModel method
mocks/database/migration/Migrator.go Updated mock for Create with modelName parameter

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

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

Thanks, amazing PR. I successfully generated the migration. Left a few questions.

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

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

Great PR 👍

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated 8 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

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

Thanks, almost there. Please check the Copilot comments as well, optimize them if necessary.

@hwbrzzl
Copy link
Contributor

hwbrzzl commented Dec 2, 2025

Found an issue when running locally:

image

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@krishankumar01
Copy link
Member Author

krishankumar01 commented Dec 2, 2025

Found an issue when running locally:
image

Fixed! For gorm.DeletedAt, the field is now correctly marked as .Nullable().
Regarding the serializer:json tag: it won't automatically make the column a JSON type. GORM uses this tag only for Go-side serialization/deserialization, but stores the data as TEXT or VARCHAR in the database. If you want it to map to Json than you can use gorm:"migration:Json" tag.

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

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

Awesome, we were finally here. 💯

@krishankumar01 krishankumar01 merged commit 30a694c into master Dec 3, 2025
14 checks passed
@krishankumar01 krishankumar01 deleted the kkumar-gcc/#635-2 branch December 3, 2025 05:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize the process of generating migration and model

3 participants