Skip to content

Commit

Permalink
dialect/sql/schema: skip creating unique key for primary keys (#2425)
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m committed Mar 24, 2022
1 parent c00b4ec commit 6c30ca7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion dialect/sql/schema/atlas.go
Expand Up @@ -490,7 +490,7 @@ func (m *Migrate) aColumns(b atBuilder, t1 *Table, t2 *schema.Table) error {
}
c2.SetDefault(&schema.RawExpr{X: x})
}
if c1.Unique {
if c1.Unique && (len(t1.PrimaryKey) != 1 || t1.PrimaryKey[0] != c1) {
b.atUniqueC(t1, c1, t2, c2)
}
if c1.Increment {
Expand Down
21 changes: 19 additions & 2 deletions entc/integration/customid/customid_test.go
Expand Up @@ -13,7 +13,6 @@ import (
"testing"

"entgo.io/ent/dialect"

entsql "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/integration/customid/ent"
Expand All @@ -25,6 +24,7 @@ import (
"entgo.io/ent/entc/integration/customid/sid"
"entgo.io/ent/schema/field"

atlas "ariga.io/atlas/sql/schema"
"github.com/go-sql-driver/mysql"
"github.com/google/uuid"
_ "github.com/lib/pq"
Expand Down Expand Up @@ -74,7 +74,7 @@ func TestPostgres(t *testing.T) {
defer db.Exec("DROP SCHEMA custom_id CASCADE")

client := ent.NewClient(ent.Driver(entsql.OpenDB(dialect.Postgres, db)))
err = client.Schema.Create(context.Background(), schema.WithAtlas(true))
err = client.Schema.Create(context.Background(), schema.WithAtlas(true), schema.WithDiffHook(expectOnePetsIndex))
require.NoError(t, err)
CustomID(t, client)
BytesID(t, client)
Expand Down Expand Up @@ -263,3 +263,20 @@ func skipBytesID(c schema.Creator) schema.Creator {
return c.Create(ctx, t...)
})
}

// expectOnePetsIndex expects that pets table contains only one index.
func expectOnePetsIndex(next schema.Differ) schema.Differ {
return schema.DiffFunc(func(current, desired *atlas.Schema) ([]atlas.Change, error) {
changes, err := next.Diff(current, desired)
for _, c := range changes {
addT, ok := c.(*atlas.AddTable)
if !ok || addT.T.Name != pet.Table {
continue
}
if n := len(addT.T.Indexes); n != 1 {
return nil, fmt.Errorf("expect only one index, but got: %d", n)
}
}
return changes, err
})
}

0 comments on commit 6c30ca7

Please sign in to comment.