Skip to content

Commit

Permalink
refactor: sort relationships map to have a deterministic SQL output
Browse files Browse the repository at this point in the history
  • Loading branch information
luantranminh committed Apr 22, 2024
1 parent 0836bcb commit 498be9c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
14 changes: 13 additions & 1 deletion gormschema/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"database/sql/driver"
"errors"
"fmt"
"sort"

"ariga.io/atlas-go-sdk/recordriver"
"gorm.io/driver/mysql"
Expand Down Expand Up @@ -147,7 +148,18 @@ func (m *migrator) HasTable(dst any) bool {
func (m *migrator) CreateConstraints(models []any) error {
for _, model := range m.ReorderModels(models, true) {
err := m.Migrator.RunWithValue(model, func(stmt *gorm.Statement) error {
for _, rel := range stmt.Schema.Relationships.Relations {

relationNames := make([]string, 0, len(stmt.Schema.Relationships.Relations))
for name := range stmt.Schema.Relationships.Relations {
relationNames = append(relationNames, name)
}
// since Relations is a map, the order of the keys is not guaranteed
// so we sort the keys to make the sql output deterministic
sort.Strings(relationNames)

for _, name := range relationNames {
rel := stmt.Schema.Relationships.Relations[name]

if rel.Field.IgnoreMigration {
continue
}
Expand Down
2 changes: 1 addition & 1 deletion gormschema/testdata/mysql_custom_join_table
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
CREATE TABLE `addresses` (`id` bigint AUTO_INCREMENT,`name` longtext,PRIMARY KEY (`id`));
CREATE TABLE `people` (`id` bigint AUTO_INCREMENT,`name` longtext,PRIMARY KEY (`id`));
CREATE TABLE `person_addresses` (`person_id` bigint,`address_id` bigint,`created_at` datetime(3) NULL,`deleted_at` datetime(3) NULL,PRIMARY KEY (`person_id`,`address_id`));
ALTER TABLE `person_addresses` ADD CONSTRAINT `fk_person_addresses_person` FOREIGN KEY (`person_id`) REFERENCES `people`(`id`);
ALTER TABLE `person_addresses` ADD CONSTRAINT `fk_person_addresses_address` FOREIGN KEY (`address_id`) REFERENCES `addresses`(`id`);
ALTER TABLE `person_addresses` ADD CONSTRAINT `fk_person_addresses_person` FOREIGN KEY (`person_id`) REFERENCES `people`(`id`);

0 comments on commit 498be9c

Please sign in to comment.