Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

sort columns before generation #1223

Open
trim21 opened this issue Oct 5, 2024 · 1 comment
Open

sort columns before generation #1223

trim21 opened this issue Oct 5, 2024 · 1 comment

Comments

@trim21
Copy link
Contributor

trim21 commented Oct 5, 2024

is it possible to generate stable struct fields ordering based on column name instead of definition order?

for example, generate same result for create table ( a int, b int ) and create table ( b int, a int )

I can send a pr for this to add a new option

diff --git a/internal/generate/table.go b/internal/generate/table.go
index e5222c1..37a5758 100644
--- a/internal/generate/table.go
+++ b/internal/generate/table.go
@@ -3,6 +3,7 @@ package generate
 import (
 	"context"
 	"errors"
+	"sort"
 
 	"gorm.io/gorm"
 
@@ -48,6 +49,11 @@ func getTableColumns(db *gorm.DB, schemaName string, tableName string, indexTag
 	if err != nil {
 		return nil, err
 	}
+
+	sort.Slice(result, func(i, j int) bool {
+		return result[i].Name() < result[j].Name()
+	})
+
 	if !indexTag || len(result) == 0 {
 		return result, nil
 	}
@@ -64,7 +70,12 @@ func getTableColumns(db *gorm.DB, schemaName string, tableName string, indexTag
 	im := model.GroupByColumn(index)
 	for _, c := range result {
 		c.Indexes = im[c.Name()]
+
+		sort.Slice(c.Indexes, func(i, j int) bool {
+			return c.Indexes[i].Name() < c.Indexes[j].Name()
+		})
 	}
+
 	return result, nil
 }
 
@qqxhb
Copy link
Member

qqxhb commented Oct 19, 2024

Adjusting the field order in table definitions, could it be a better solution?

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

No branches or pull requests

2 participants