Skip to content

Commit

Permalink
test: namer identifier lenght (#6872)
Browse files Browse the repository at this point in the history
  • Loading branch information
a631807682 committed Mar 9, 2024
1 parent f17a752 commit 9efae65
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions tests/table_test.go
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

0 comments on commit 9efae65

Please sign in to comment.