Join GitHub today
GitHub is home to over 36 million developers working together to host and review code, manage projects, and build software together.Sign up
[5.8] Sql Server issue with dropAllTables when foreign key constraints exist #28750
There is an issue with migrations while using a sqlsrv connection. The issue occurs in the SqlServerBuilder->dropAllTables() method when there are foreign key constraints in the database and the database will throw a foreign key constraint exception while running commands like php artisan migrate:fresh. The SqlServerGrammer class returns the following command for this method: EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"; The problem is that this sql server command only disables the constraints on INSERT and DELETE and does not work for TRUNCATE or DROP TABLE.
The only solution I have found to dropping tables with foreign key constraints in SQL Server is to first drop the foreign keys on every table.
An example of this issue can be found in the following project when configured with a sqlsrv connection. https://github.com/walliby/sql-server-drop-table-issue. Running phpunit, on the ExampleTest which uses RefreshDatabase will throw a db foreign key constraint error every other time you run the test. The reason the test fails every other time is because it will throw the error on the users table but still drop the role_user table which has the foreign keys. The second time, it will succeed, as the role_user table was deleted by the previous run.
FYI, I have only tested my proposed solution on SQL Server 2016 SP1. I used my example project with foreign key constraints: https://github.com/walliby/sql-server-drop-table-issue. The t-sql I used is fairly basic and should be correct back to at least SQL Server 2008.
@laurencei I just tested the pure sql in a SQL 2014 Azure instance and that worked fine dropping 12 foreign keys in the sample AdventureWorks database...