@@ -105,6 +105,9 @@ func (p *CreateForeignKey) String() string {
105
105
return pr .String ()
106
106
}
107
107
108
+ // ValidateForeignKeyDefinition checks that the foreign key definition is valid for creation
109
+ var ValidateForeignKeyDefinition = validateForeignKeyDefinition
110
+
108
111
// ResolveForeignKey verifies the foreign key definition and resolves the foreign key, creating indexes and validating
109
112
// data as necessary.
110
113
// 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
171
174
}
172
175
173
176
// 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
184
180
}
185
181
186
182
// 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
324
320
}
325
321
}
326
322
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
+
327
339
type DropForeignKey struct {
328
340
// In the cases where we have multiple ALTER statements, we need to resolve the table at execution time rather than
329
341
// during analysis. Otherwise, you could add a foreign key in the preceding alter and we may have analyzed to a
0 commit comments