"Fix "foreign key too long" bug for any identifier"
I use SHA1 to generate a unique hash using the identifier. I ignore the underscores. Then I use the hash rather than the identifier
This commit is contained in:
		
							parent
							
								
									e1df3994fb
								
							
						
					
					
						commit
						7b6cd38e58
					
				@ -1,6 +1,7 @@
 | 
				
			|||||||
package gorm
 | 
					package gorm
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"crypto/sha1"
 | 
				
			||||||
	"database/sql"
 | 
						"database/sql"
 | 
				
			||||||
	"database/sql/driver"
 | 
						"database/sql/driver"
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
@ -619,10 +620,21 @@ func (scope *Scope) addIndex(unique bool, indexName string, column ...string) {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) {
 | 
					func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) {
 | 
				
			||||||
	var keyName = fmt.Sprintf("%s_%s_%s_foreign", scope.TableName(), field, dest)
 | 
						getHash := func(rawKey string) string {
 | 
				
			||||||
	keyName = regexp.MustCompile("(_*[^a-zA-Z]+_*|_+)").ReplaceAllString(keyName, "_")
 | 
							h := sha1.New()
 | 
				
			||||||
	var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;`
 | 
							h.Write([]byte(rawKey))
 | 
				
			||||||
	scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.QuoteIfPossible(keyName), scope.QuoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
 | 
							bs := h.Sum(nil)
 | 
				
			||||||
 | 
							return fmt.Sprintf("%x", bs)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						keyName := scope.TableName() + field + dest
 | 
				
			||||||
 | 
						hash := getHash(keyName)
 | 
				
			||||||
 | 
						query := `ALTER TABLE ` + scope.QuotedTableName() +
 | 
				
			||||||
 | 
							` ADD CONSTRAINT ` + "`" + hash + "`" +
 | 
				
			||||||
 | 
							` FOREIGN KEY (` + scope.QuoteIfPossible(field) + `)` +
 | 
				
			||||||
 | 
							` REFERENCES ` + dest +
 | 
				
			||||||
 | 
							` ON DELETE ` + onDelete +
 | 
				
			||||||
 | 
							` ON UPDATE ` + onUpdate + `;`
 | 
				
			||||||
 | 
						scope.Raw(query).Exec()
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (scope *Scope) removeIndex(indexName string) {
 | 
					func (scope *Scope) removeIndex(indexName string) {
 | 
				
			||||||
 | 
				
			|||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user