@@ -5,6 +5,21 @@ const {escapeId} = require('mysql/lib/protocol/SqlString');
5
5
6
6
const referenceOptions = [ 'RESTRICT' , 'CASCADE' , 'SET NULL' , 'NO ACTION' ] ;
7
7
8
+ function sanitizeReferenceOption ( option ) {
9
+ const refOption = option . toUpperCase ( ) ;
10
+ if ( referenceOptions . indexOf ( refOption ) === - 1 ) {
11
+ throw new Error ( 'Invalid foreign key reference option: ' + option ) ;
12
+ }
13
+
14
+ // NO ACTION is the same as RESTRICT in MySQL 8
15
+ // https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-key-referential-actions
16
+ if ( refOption === 'NO ACTION' ) {
17
+ return 'RESTRICT' ;
18
+ }
19
+
20
+ return refOption ;
21
+ }
22
+
8
23
class ForeignKeyDefinition {
9
24
constructor ( columns ) {
10
25
this . $columns = columns ;
@@ -24,20 +39,12 @@ class ForeignKeyDefinition {
24
39
}
25
40
26
41
onDelete ( option ) {
27
- const refOption = option . toUpperCase ( ) ;
28
- if ( referenceOptions . indexOf ( refOption ) === - 1 ) {
29
- throw new Error ( 'Invalid foreign key reference option: ' + option ) ;
30
- }
31
- this . _onDelete = refOption ;
42
+ this . _onDelete = sanitizeReferenceOption ( option ) ;
32
43
return this ;
33
44
}
34
45
35
46
onUpdate ( option ) {
36
- const refOption = option . toUpperCase ( ) ;
37
- if ( referenceOptions . indexOf ( refOption ) === - 1 ) {
38
- throw new Error ( 'Invalid foreign key reference option: ' + option ) ;
39
- }
40
- this . _onUpdate = refOption ;
47
+ this . _onUpdate = sanitizeReferenceOption ( option ) ;
41
48
return this ;
42
49
}
43
50
@@ -77,6 +84,9 @@ class ForeignKeyDefinition {
77
84
`CONSTRAINT ${ escapeId ( this . $name ) } \n FOREIGN KEY (${ escapeId ( this . $columns ) } ) ` +
78
85
`REFERENCES ${ escapeId ( this . _referenceTable ) } (${ escapeId ( this . _referenceColumns ) } )` ;
79
86
87
+ // RESTRICT and NO ACTION are equivalent to omitting the clause:
88
+ // https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-key-referential-actions
89
+ // (NO ACTION is transformed into RESTRICT above because it's basically an alias in MySQL 8)
80
90
if ( this . _onDelete !== 'RESTRICT' ) {
81
91
sql += ' ON DELETE ' + this . _onDelete ;
82
92
}
0 commit comments