@@ -105,6 +105,9 @@ func (p *CreateForeignKey) String() string {
105105 return pr .String ()
106106}
107107
108+ // ValidateForeignKeyDefinition checks that the foreign key definition is valid for creation
109+ var ValidateForeignKeyDefinition = validateForeignKeyDefinition
110+
108111// ResolveForeignKey verifies the foreign key definition and resolves the foreign key, creating indexes and validating
109112// data as necessary.
110113// fkChecks - whether to check the foreign key against the data in the table
@@ -171,16 +174,9 @@ func ResolveForeignKey(ctx *sql.Context, tbl sql.ForeignKeyTable, refTbl sql.For
171174 }
172175
173176 // Check that the types align and are valid
174- for i := range fkDef .Columns {
175- col := cols [strings .ToLower (fkDef .Columns [i ])]
176- parentCol := parentCols [strings .ToLower (fkDef .ParentColumns [i ])]
177- if ! foreignKeyComparableTypes (ctx , col .Type , parentCol .Type ) {
178- return sql .ErrForeignKeyColumnTypeMismatch .New (fkDef .Columns [i ], fkDef .ParentColumns [i ])
179- }
180- sqlParserType := col .Type .Type ()
181- if sqlParserType == sqltypes .Text || sqlParserType == sqltypes .Blob {
182- return sql .ErrForeignKeyTextBlob .New ()
183- }
177+ err := ValidateForeignKeyDefinition (ctx , fkDef , cols , parentCols )
178+ if err != nil {
179+ return err
184180 }
185181
186182 // Ensure that a suitable index exists on the referenced table, and check the declaring table for a suitable index.
@@ -324,6 +320,22 @@ func ResolveForeignKey(ctx *sql.Context, tbl sql.ForeignKeyTable, refTbl sql.For
324320 }
325321}
326322
323+ // validateForeignKeyDefinition checks that the foreign key definition is valid for creation
324+ func validateForeignKeyDefinition (ctx * sql.Context , fkDef sql.ForeignKeyConstraint , cols map [string ]* sql.Column , parentCols map [string ]* sql.Column ) error {
325+ for i := range fkDef .Columns {
326+ col := cols [strings .ToLower (fkDef .Columns [i ])]
327+ parentCol := parentCols [strings .ToLower (fkDef .ParentColumns [i ])]
328+ if ! foreignKeyComparableTypes (ctx , col .Type , parentCol .Type ) {
329+ return sql .ErrForeignKeyColumnTypeMismatch .New (fkDef .Columns [i ], fkDef .ParentColumns [i ])
330+ }
331+ sqlParserType := col .Type .Type ()
332+ if sqlParserType == sqltypes .Text || sqlParserType == sqltypes .Blob {
333+ return sql .ErrForeignKeyTextBlob .New ()
334+ }
335+ }
336+ return nil
337+ }
338+
327339type DropForeignKey struct {
328340 // In the cases where we have multiple ALTER statements, we need to resolve the table at execution time rather than
329341 // during analysis. Otherwise, you could add a foreign key in the preceding alter and we may have analyzed to a
0 commit comments