Skip to content

[5.8] Sql Server issue with dropAllTables when foreign key constraints exist #28750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,22 @@ public function compileDisableForeignKeyConstraints()
return 'EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all";';
}

/**
* Compile the command to drop all foreign keys.
*
* @return string
*/
public function compileDropAllForeignKeys()
{
return "DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += 'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to specify the database name?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@staudenmeir I dont believe so because it's being called the same was as compileDropAllTables using $this->connection.

$this->connection->statement($this->grammar->compileDropAllForeignKeys());
$this->connection->statement($this->grammar->compileDropAllTables());

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I ran this code, it only removed the foreign keys on the one database (I checked the other one on the same server, and it's foreign keys are still intact).

+ '.' + QUOTENAME(OBJECT_NAME(parent_object_id)) +
' DROP CONSTRAINT ' + QUOTENAME(name) + ';'
FROM sys.foreign_keys;

EXEC sp_executesql @sql;";
}

/**
* Create the column definition for a char type.
*
Expand Down
4 changes: 1 addition & 3 deletions src/Illuminate/Database/Schema/SqlServerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ class SqlServerBuilder extends Builder
*/
public function dropAllTables()
{
$this->disableForeignKeyConstraints();
$this->connection->statement($this->grammar->compileDropAllForeignKeys());

$this->connection->statement($this->grammar->compileDropAllTables());

$this->enableForeignKeyConstraints();
}
}