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

DDL: add unique key example #4

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion db.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,17 @@ func RunMigrations() {
}
return nil
},
}})
}, {
// alter name column as unique key
ID: "202307262210",
Migrate: func(db *gorm.DB) error {
if err := db.Exec("ALTER TABLE `users` ADD UNIQUE (name(32))").Error; err != nil {
return err
}
return nil
},
},
})

if err = m.Migrate(); err != nil {
log.Fatalf("Migration failed: %v", err)
Expand Down
20 changes: 19 additions & 1 deletion main_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"github.com/google/uuid"
"testing"
)

Expand All @@ -9,7 +10,7 @@ import (
// TEST_DRIVERS: sqlite, mysql, postgres, sqlserver, tidb

func TestGORM(t *testing.T) {
user := User{Name: "jinzhu"}
user := User{Name: uuid.NewString()}

DB.Create(&user)

Expand All @@ -18,3 +19,20 @@ func TestGORM(t *testing.T) {
t.Errorf("Failed, got error: %v", err)
}
}

func TestUniqueKey(t *testing.T) {

name := uuid.NewString()
user := User{Name: name}
if err := DB.Create(&user).Error; err != nil {
t.Errorf("Failed, got error: %v", err)
}
if err := DB.Create(&user).Error; err == nil {
t.Error("Should return error because of the same name")
}

var result User
if err := DB.First(&result, user.ID).Error; err != nil {
t.Errorf("Failed, got error: %v", err)
}
}
2 changes: 1 addition & 1 deletion tidbcloud.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
github:
branch:
allowList:
- "ci_example"
- "uk_example"
Loading