test: namer identifier lenght (#6872)

This commit is contained in:
Cr 2024-03-09 17:31:28 +08:00 committed by GitHub
parent f17a75242e
commit 9efae659cb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 87 additions and 0 deletions

View File

@ -2,8 +2,10 @@ package tests_test
import (
"regexp"
"sync"
"testing"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"gorm.io/gorm/utils/tests"
@ -172,3 +174,88 @@ func TestTableWithNamer(t *testing.T) {
t.Errorf("Table with namer, got %v", sql)
}
}
func TestPostgresTableWithIdentifierLength(t *testing.T) {
if DB.Dialector.Name() != "postgres" {
return
}
type LongString struct {
ThisIsAVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString string `gorm:"unique"`
}
t.Run("default", func(t *testing.T) {
db, _ := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{})
user, err := schema.Parse(&LongString{}, &sync.Map{}, db.Config.NamingStrategy)
if err != nil {
t.Fatalf("failed to parse user unique, got error %v", err)
}
constraints := user.ParseUniqueConstraints()
if len(constraints) != 1 {
t.Fatalf("failed to find unique constraint, got %v", constraints)
}
for key := range constraints {
if len(key) != 63 {
t.Errorf("failed to find unique constraint, got %v", constraints)
}
}
})
t.Run("naming strategy", func(t *testing.T) {
db, _ := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{
NamingStrategy: schema.NamingStrategy{},
})
user, err := schema.Parse(&LongString{}, &sync.Map{}, db.Config.NamingStrategy)
if err != nil {
t.Fatalf("failed to parse user unique, got error %v", err)
}
constraints := user.ParseUniqueConstraints()
if len(constraints) != 1 {
t.Fatalf("failed to find unique constraint, got %v", constraints)
}
for key := range constraints {
if len(key) != 63 {
t.Errorf("failed to find unique constraint, got %v", constraints)
}
}
})
t.Run("namer", func(t *testing.T) {
uname := "custom_unique_name"
db, _ := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{
NamingStrategy: mockUniqueNamingStrategy{
UName: uname,
},
})
user, err := schema.Parse(&LongString{}, &sync.Map{}, db.Config.NamingStrategy)
if err != nil {
t.Fatalf("failed to parse user unique, got error %v", err)
}
constraints := user.ParseUniqueConstraints()
if len(constraints) != 1 {
t.Fatalf("failed to find unique constraint, got %v", constraints)
}
for key := range constraints {
if key != uname {
t.Errorf("failed to find unique constraint, got %v", constraints)
}
}
})
}
type mockUniqueNamingStrategy struct {
UName string
schema.NamingStrategy
}
func (a mockUniqueNamingStrategy) UniqueName(table, column string) string {
return a.UName
}