You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Schema builder: Dropping a column with a default value constraint #4402
I'm using Laravel 4.1 with the sqlsrv database driver and I'm running in a problem with the default value constraints in the migration scripts.
When I add a column to a table with a default value constraint the name of the constraint is randomly generated (e.g. DF__foo__bar__322242A7). The problem occurs now in the rollback method because it is not possible to drop the column as long as the default constraint exists and it is not possible to drop the constraint because its name is randomly generated by the sql server.
I think that it would be good if the Laravel framework would generate the names of default value constraints like id does it for the primary, the foreign and the unique constraints.
I've stumbled upon the same issue today. Creating a column with a default value on SQL Server creates a constraint that stops the ability to drop the column.
any update on this? it's happening on laravel 5.1 and mssql. it's fine if you use Schema::drop() but the error occurs when you use $table->dropColumn().
$tableName = 'myTable';
if ('sqlsrv' == DB::connection()->getDriverName()) {
$defaultContraint = DB::selectOne("SELECT OBJECT_NAME([default_object_id]) AS name FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID('[dbo].[$tableName]') AND [name] = 'myField'");
DB::statement("ALTER TABLE [dbo].[$tableName] DROP CONSTRAINT $defaultContraint->name");
}
Schema::table($tableName, function (Blueprint $table) {
$table->dropColumn('myField');
});
But more complete solution is to assign explicit name to default contraint as described in #8827 (this requires developing a pull request - anyone please?).
Reacted by Ilya Savinkov, César, ppoffice, Jeff Puckett, Martín Granados García, Elanor, Lee Hicks, Max, Leonardo de Albuquerque Gouveia, Goran Hrženjak and 5 more
I just ran into this problem as well. Why was this issue closed?
Otherwise a notice for the default modifier, that SQL Server can't rollback automatically, would be nice.
Edit: I just did some research and found this piece of code which fetches all constraints for a list of columns.
SELECT OBJECT_NAME([default_object_id])
FROMSYS.COLUMNSWHERE [object_id] = OBJECT_ID('[tableSchema].[tableSchema]') AND [name] IN ('column1', 'column2', 'column3');
This can be used in conjunction with Illuminate\Database\Schema\Grammars\SqlServerGrammar::compileDropColumn() to drop the constraints before the columns.
This is sadly still an issue, and I hope it will be addressed in the future. Illuminate\Foundation\Testing\RefreshDatabase for testing will not work either, of course.
But good news is i managed to fix your code. This version works for me. WARNING! I fixed misspelled 'dropDefaultConstraint', so make sure that you change invocations if you copied it from previous version, and I added $databaseConnectionName that you get from your database config file.
$databaseConnectionName = 'my-mssql-connection';
Blueprint::macro('dropDefaultConstraint', function (string$column) use ($databaseConnectionName) {
$connection = Schema::connection($databaseConnectionName)->getConnection();
if ($connection->getDriverName() === 'sqlsrv') {
$query = sprintf(
'SELECT OBJECT_NAME([default_object_id]) AS name ' .
'FROM SYS.COLUMNS ' .
"WHERE [object_id] = OBJECT_ID('[dbo].[%s]') AND [name] = '%s'",
$this->getTable(),
$column
);
$result = $connection->selectOne($query);
$constraint = newIndex($result->name, [$column]);
$tableName = $this->getTable();
$keyName = $constraint->getName();
$sql = "ALTER TABLE {$tableName} DROP CONSTRAINT {$keyName}";
$connection->statement($sql);
//$connection->getDoctrineSchemaManager()->dropConstraint($constraint, $this->getTable());
}
});
Here you have a better fix, it works as long as you only use one drop column statement with array notation: $table->dropColumn(['column_a','column_b']); since @sql can only be declared once in T-SQL otherwise it will probably throw errors.
@yaroslavmo see my comment for quick fix for now, until hopefully they will actually approve one of my PR's (upto now all my Pr's have been instantly denied/closed).
Thank you. I used the workaround @rafis suggested (only on the local machine). I will wait till they review your PR. I strongly believe this kind of thing should be the same for all four DB connectors Laravel supports and should be fixed on the framework level. For now, it is hard to use sqlsrv as a database.
P.S. if they deny your PR, I will have to use your fix tho 😃
Hi @joelharkes . Your PR did not work for one of my migrations.
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpgradeCors extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('cors_config', function (Blueprint $table) {
$table->string('description')->nullable()->after('path');
$table->text('exposed_header')->nullable()->after('header');
$table->boolean('supports_credentials')->default(0)->after('max_age');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('cors_config', function (Blueprint $table) {
$table->dropColumn(['description', 'exposed_header', 'supports_credentials']);
});
}
}
It gives this error:
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The object 'DF__cors_conf__suppo__44428990' is dependent on column 'supports_credentials'. (SQL: DECLARE @SQL NVARCHAR(MAX) = ''
;SELECT @SQL += 'ALTER TABLE [dbo].[cors_config] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID('[dbo].[cors_config]') AND [name] in ('descr
iption','exposed_header','supports_credentials');EXEC(@SQL);alter table "cors_config" drop column "description", "exposed_header", "supports_credentials")
I tried to debug it myself but I am not that familiar with SQL Server and it is super unclear to me why created default object is called 'DF__cors_conf__suppo__44428990' and not 'DF__cors_conf__supports_credentials__44428990'
DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE [dbo].[cors_config] DROP
CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM SYS.COLUMNS WHERE
[object_id] = OBJECT_ID('[dbo][cors_config]') AND [name] in ('description', 'exposed_header',
'supports_credentials'); EXEC(@sql);
alter table 'cors_config' drop column 'description', 'exposed_header', 'supports_creadentials'
Which fails with the same error when I run it in SQL Server Management Studio.
While this query will work just fine:
DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE [dbo].[cors_config] DROP
CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM SYS.COLUMNS WHERE
[object_id] = OBJECT_ID('[dbo][cors_config]') AND [name] = 'supports_credentials'; EXEC(@sql);
alter table 'cors_config' drop column 'description', 'exposed_header', 'supports_creadentials'
This will also work if I just add "not equals": AND [name] in('description', 'exposed_header', 'supports_credentials') AND [default_object_id] <> 0; EXEC(@sql);
So I believe something wrong with IN statement. @joelharkes What do you think?
Activity
taylorotwell commentedon May 23, 2014
I'm not that familiar with SQL Server. If you want to submit a pull request to fix this behavior please feel free.
joestrong commentedon Jun 11, 2014
I've stumbled upon the same issue today. Creating a column with a default value on SQL Server creates a constraint that stops the ability to drop the column.
cowabunga1 commentedon Jul 25, 2014
Column name change also generates an error...
sherwinmartin commentedon Jul 14, 2015
any update on this? it's happening on laravel 5.1 and mssql. it's fine if you use Schema::drop() but the error occurs when you use $table->dropColumn().
rafis commentedon Sep 22, 2016
Temporary solution:
But more complete solution is to assign explicit name to default contraint as described in #8827 (this requires developing a pull request - anyone please?).
FrittenKeeZ commentedon Jul 12, 2017
I just ran into this problem as well. Why was this issue closed?
Otherwise a notice for the default modifier, that SQL Server can't rollback automatically, would be nice.
Edit: I just did some research and found this piece of code which fetches all constraints for a list of columns.
This can be used in conjunction with
Illuminate\Database\Schema\Grammars\SqlServerGrammar::compileDropColumn()to drop the constraints before the columns.It just doesn't seem like the right place to put it, but I don't know where else it could be placed.
@taylorotwell what are your thoughts on this?
oranges13 commentedon Oct 6, 2017
Just another note to say I just had this issue with Sql Server and the solution in @rafis comment fixed it, but it does seem somewhat janky.
phattarachai commentedon Jun 29, 2018
Hi, today I run into this problem as well, I wish to have this functionality work from Laravel just like with other database driver.
zrm-eeifler commentedon Dec 5, 2018
This is sadly still an issue, and I hope it will be addressed in the future. Illuminate\Foundation\Testing\RefreshDatabase for testing will not work either, of course.
FrittenKeeZ commentedon Apr 4, 2019
Inspired by @holystix solution in their referenced fix, I made a Blueprint macro to drop the default constraint without polluting the migration files.
Just put it in
AppServiceProvider::boot()and call it like any other drop statement$table->dropDefaultConstraint('active');dominik-stypula-polcode commentedon Dec 12, 2019
This macro throws an exception.
dominik-stypula-polcode commentedon Dec 12, 2019
But good news is i managed to fix your code. This version works for me.
WARNING! I fixed misspelled 'dropDefaultConstraint', so make sure that you change invocations if you copied it from previous version, and I added $databaseConnectionName that you get from your database config file.
joelharkes commentedon Jan 17, 2020
Why is this not in the default? should be checked when drop column happens in laravel.
This issue shouldn't be closed, its still an issue to date.
joelharkes commentedon Jan 20, 2020
Here you have a better fix, it works as long as you only use one drop column statement with array notation:
$table->dropColumn(['column_a','column_b']);since@sqlcan only be declared once in T-SQL otherwise it will probably throw errors.IN DatabaseServiceProvider.php
yaroslavmo commentedon Jan 27, 2020
I am confused. I am using Laravel 6.0.4 and facing this 6 years old issue. Any updates when it will be fixed?
oranges13 commentedon Jan 27, 2020
It looks like there is a PR proposed in #31229
joelharkes commentedon Jan 27, 2020
@yaroslavmo see my comment for quick fix for now, until hopefully they will actually approve one of my PR's (upto now all my Pr's have been instantly denied/closed).
yaroslavmo commentedon Jan 27, 2020
Thank you. I used the workaround @rafis suggested (only on the local machine). I will wait till they review your PR. I strongly believe this kind of thing should be the same for all four DB connectors Laravel supports and should be fixed on the framework level. For now, it is hard to use sqlsrv as a database.
P.S. if they deny your PR, I will have to use your fix tho 😃
joelharkes commentedon Jan 29, 2020
It has been merged. will probably be release in next laravel version
yaroslavmo commentedon Feb 3, 2020
Hi @joelharkes . Your PR did not work for one of my migrations.
It gives this error:
I tried to debug it myself but I am not that familiar with SQL Server and it is super unclear to me why created default object is called 'DF__cors_conf__suppo__44428990' and not 'DF__cors_conf__supports_credentials__44428990'
yaroslavmo commentedon Feb 3, 2020
This is the SQL query generated by your PR:
Which fails with the same error when I run it in SQL Server Management Studio.
While this query will work just fine:
This will also work if I just add "not equals":
AND [name] in('description', 'exposed_header', 'supports_credentials') AND [default_object_id] <> 0; EXEC(@sql);So I believe something wrong with IN statement. @joelharkes What do you think?
joelharkes commentedon Feb 3, 2020
Weird let me check if I can reproduce it tomorrow.