Skip to content

Commit

Permalink
sort models by name when using standalone mode (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
ronenlu authored Apr 16, 2024
1 parent cb8b534 commit e5d6dbf
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,9 @@ package models

import "gorm.io/gorm"

type User struct {
gorm.Model
Name string
Pets []Pet
}

type Pet struct {
gorm.Model
Name string
User User
UserID uint
}

type Toy struct {
ID uint
Name string
}
6 changes: 6 additions & 0 deletions internal/testdata/models/toy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package models

type Toy struct {
ID uint
Name string
}
9 changes: 9 additions & 0 deletions internal/testdata/models/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package models

import "gorm.io/gorm"

type User struct {
gorm.Model
Name string
Pets []Pet
}
5 changes: 5 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os"
"os/exec"
"reflect"
"sort"
"strings"
"text/template"
"time"
Expand Down Expand Up @@ -156,6 +157,10 @@ func gatherModels(pkgs []*packages.Package) []model {
}
}
}
// Return models in deterministic order.
sort.Slice(models, func(i, j int) bool {
return models[i].Name < models[j].Name
})
return models
}

Expand Down
17 changes: 17 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,20 @@ func TestLoad(t *testing.T) {
})
}
}

func TestDeterministicOutput(t *testing.T) {
expected := "CREATE TABLE `users` (`id` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,`name` text,PRIMARY KEY (`id`));\n" +
"CREATE INDEX `idx_users_deleted_at` ON `users`(`deleted_at`);\n" +
"CREATE TABLE `pets` (`id` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,`name` text,`user_id` integer,PRIMARY KEY (`id`),CONSTRAINT `fk_users_pets` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`));\nCREATE INDEX `idx_pets_deleted_at` ON `pets`(`deleted_at`);\n\n"
cmd := &LoadCmd{
Path: "./internal/testdata/models",
Dialect: "sqlite",
}
for i := 0; i < 10; i++ {
var buf bytes.Buffer
cmd.out = &buf
err := cmd.Run()
require.NoError(t, err)
require.Equal(t, expected, buf.String())
}
}

0 comments on commit e5d6dbf

Please sign in to comment.