@@ -366,3 +366,59 @@ func TestNonTransactionalWithCheckConstraint(t *testing.T) {
366
366
err = tk .ExecToErr ("batch limit 1 insert into t select * from (select 1, 2) tmp" )
367
367
require .EqualError (t , err , "Non-transactional DML, table name not found in join" )
368
368
}
369
+
370
+ func TestNonTransactionalDMLWorkWithForeignKey (t * testing.T ) {
371
+ store := testkit .CreateMockStore (t )
372
+ tk := testkit .NewTestKit (t , store )
373
+
374
+ // t1 is the parent table, t2 is the child table, t3 is a helper table.
375
+ tk .MustExec ("use test" )
376
+ tk .MustExec ("drop table if exists t1, t2, t3" )
377
+ tk .MustExec ("create table t1(a int, b int, key(a), key(b))" )
378
+ tk .MustExec ("create table t2(a int, b int, foreign key (a) references t1(a), key(b))" )
379
+ tk .MustExec ("create table t3(a int, b int, key(a))" )
380
+
381
+ cleanFn := func () {
382
+ tk .MustExec ("truncate t3" )
383
+ tk .MustExec ("truncate t2" )
384
+ // Cannot truncate t1 because it is the parent table
385
+ tk .MustExec ("delete from t1" )
386
+ }
387
+
388
+ // The check should work for INSERT
389
+ for i := 0 ; i < 100 ; i ++ {
390
+ tk .MustExec (fmt .Sprintf ("insert into t1 values (%d, %d)" , i , i ))
391
+ tk .MustExec (fmt .Sprintf ("insert into t3 values (%d, %d)" , i , i ))
392
+ }
393
+ tk .MustExec ("DELETE FROM t1 WHERE a = 55" )
394
+ tk .MustContainErrMsg ("BATCH ON a LIMIT 10 INSERT INTO t2 SELECT * FROM t3" , "Cannot add or update a child row: a foreign key constraint fails" )
395
+ // Though it failed, some data is still inserted
396
+ tk .MustQuery ("select count(*) from t2" ).Check (testkit .Rows ("50" ))
397
+ cleanFn ()
398
+
399
+ // The check should work for UPDATE
400
+ for i := 0 ; i < 100 ; i ++ {
401
+ tk .MustExec (fmt .Sprintf ("insert into t1 values (%d, %d)" , i , i ))
402
+ }
403
+ tk .MustExec ("DELETE FROM t1 WHERE a = 55" )
404
+ for i := 0 ; i < 100 ; i ++ {
405
+ if i != 55 {
406
+ tk .MustExec (fmt .Sprintf ("insert into t2 values (%d, %d)" , i , i ))
407
+ }
408
+ }
409
+ tk .MustContainErrMsg ("BATCH ON b LIMIT 10 UPDATE t2 SET a = a + 1" , "Cannot add or update a child row: a foreign key constraint fails" )
410
+ tk .MustQuery ("select min(a) from t2" ).Check (testkit .Rows ("1" ))
411
+ cleanFn ()
412
+
413
+ // The check should work for DELETE
414
+ for i := 0 ; i < 100 ; i ++ {
415
+ tk .MustExec (fmt .Sprintf ("insert into t1 values (%d, %d)" , i , i ))
416
+ }
417
+ tk .MustExec ("DELETE FROM t1 WHERE a = 55" )
418
+ for i := 56 ; i < 100 ; i ++ {
419
+ tk .MustExec (fmt .Sprintf ("insert into t2 values (%d, %d)" , i , i ))
420
+ }
421
+ tk .MustContainErrMsg ("BATCH ON b LIMIT 10 DELETE FROM t1" , "Cannot delete or update a parent row: a foreign key constraint fails" )
422
+ tk .MustQuery ("select count(*) from t1" ).Check (testkit .Rows ("49" ))
423
+ cleanFn ()
424
+ }
0 commit comments