max identifier length changed to 63

This commit is contained in:
mohammad ali ashraf 2023-05-21 01:46:27 +05:00
parent f5837deef3
commit 563d9b588a
4 changed files with 17 additions and 12 deletions

View File

@ -146,7 +146,7 @@ func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
}
if config.NamingStrategy == nil {
config.NamingStrategy = schema.NamingStrategy{}
config.NamingStrategy = schema.NamingStrategy{IdentifierMaxLength: 63}
}
if config.Logger == nil {

View File

@ -28,10 +28,11 @@ type Replacer interface {
// NamingStrategy tables, columns naming strategy
type NamingStrategy struct {
TablePrefix string
SingularTable bool
NameReplacer Replacer
NoLowerCase bool
TablePrefix string
SingularTable bool
NameReplacer Replacer
NoLowerCase bool
IdentifierMaxLength int
}
// TableName convert string to table name
@ -89,12 +90,16 @@ func (ns NamingStrategy) formatName(prefix, table, name string) string {
prefix, table, name,
}, "_"), ".", "_")
if utf8.RuneCountInString(formattedName) > 64 {
if ns.IdentifierMaxLength == 0 {
ns.IdentifierMaxLength = 63
}
if utf8.RuneCountInString(formattedName) > ns.IdentifierMaxLength {
h := sha1.New()
h.Write([]byte(formattedName))
bs := h.Sum(nil)
formattedName = formattedName[0:56] + hex.EncodeToString(bs)[:8]
formattedName = formattedName[0:ns.IdentifierMaxLength-8] + hex.EncodeToString(bs)[:8]
}
return formattedName
}

View File

@ -189,11 +189,11 @@ func TestCustomReplacerWithNoLowerCase(t *testing.T) {
}
}
func TestFormatNameWithStringLongerThan64Characters(t *testing.T) {
ns := NamingStrategy{}
func TestFormatNameWithStringLongerThan63Characters(t *testing.T) {
ns := NamingStrategy{IdentifierMaxLength: 63}
formattedName := ns.formatName("prefix", "table", "thisIsAVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString")
if formattedName != "prefix_table_thisIsAVeryVeryVeryVeryVeryVeryVeryVeryVery180f2c67" {
if formattedName != "prefix_table_thisIsAVeryVeryVeryVeryVeryVeryVeryVeryVer180f2c67" {
t.Errorf("invalid formatted name generated, got %v", formattedName)
}
}

View File

@ -768,13 +768,13 @@ func TestParseConstraintNameWithSchemaQualifiedLongTableName(t *testing.T) {
s, err := schema.Parse(
&Book{},
&sync.Map{},
schema.NamingStrategy{},
schema.NamingStrategy{IdentifierMaxLength: 63},
)
if err != nil {
t.Fatalf("Failed to parse schema")
}
expectedConstraintName := "fk_my_schema_a_very_very_very_very_very_very_very_very_l4db13eec"
expectedConstraintName := "fk_my_schema_a_very_very_very_very_very_very_very_very_4db13eec"
constraint := s.Relationships.Relations["Author"].ParseConstraint()
if constraint.Name != expectedConstraintName {