Repository navigation
Description
I have encountered a problem with idempotent migration scripts that make them fail in our continous integration system. The reason is that some migration scripts are parsed even though they are not going to be executed.
This issue is much like issue #10717. This issue can be reproduced by manipulating EF types i a sequence of migrations.
In example I have these two migrations, the first is adding a unique index for a nullable column, the second is removing the column:
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20180519095519_AddIndexToMyTable')
BEGIN
CREATE UNIQUE INDEX [NameIndex] ON [MyTable] ([Name]) WHERE [Name] IS NOT NULL;
END;
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20180720070812_RemoveNameFromMyTable')
BEGIN
DROP INDEX [NameIndex] ON [MyTable];
END;
GO
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20180720070812_RemoveNameFromMyTable')
BEGIN
DECLARE @var19 sysname;
SELECT @var19 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[MyTable]') AND [c].[name] = N'Name');
IF @var19 IS NOT NULL EXEC(N'ALTER TABLE [MyTable] DROP CONSTRAINT [' + @var19 + '];');
ALTER TABLE [MyTable] DROP COLUMN [Name];
END;
GO
This will work fine in the first execution, just as #10717
The second time this in run in our CI system, MyTable will no longer have the column "Name" and will fail in the execution of
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20180519095519_AddIndexToMyTable')
BEGIN
CREATE UNIQUE INDEX [NameIndex] ON [MyTable] ([Name]) WHERE [Name] IS NOT NULL;
END;
The SQL error message is
Invalid column name 'Name'.
This happens even though the migration "AddIndexToMyTable" has been installed and the "If not exists.." statement should avoid execution of the script, but as i happens it is parsed anyways, making it fail!
Steps to reproduce
- Create a entity type with a nullable field with a unique index using fluent API
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<MyTable>().HasIndex(c => c.Name).IsUnique();
}
- Make a new migration
- Remove the field Name from MyTable and remove the unique index in OnModelCreating
- Make a new migration
- Create an idempotent migration script with
dotnet ef migrations script -o migrationscript.sql --startup-project MyProject.csproj --configuration release --idempotent
- execute migrationscript.sql twice on the database making it fail
Proposal for a solution
This problem only occurs because the script section is parsed in the sql server even though it is not going to be executed. If this could be avoided the problem would not occur. It could be solved by using dynamic a sql script, as:
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20180519095519_AddIndexToMyTable')
BEGIN
EXEC('CREATE UNIQUE INDEX [NameIndex] ON [MyTable] ([Name]) WHERE [Name] IS NOT NULL;')
END;
As it is i'm adding the exec to the migration script with powershell in CI, but I believe that everyone would be happier if we could rely on the script produced by EFCore :-)
Further technical details
EF Core version: 2.1.1
Activity
ajcvickers commentedon Aug 10, 2018
Note for triage: I was able to reproduce this both in SQL Management Studio and when running the commands directly from ADO.NET:
ADO.NET repro code:
ajcvickers commentedon Aug 28, 2018
Triage: for 3.0, we will investigate the minimal set of places where we have to wrap in an exec call to avoid the SQL Server parsing issue. Worst case, we will have to do it everywhere. Note that this should only be done when generating idempotent scripts.
tonven commentedon Sep 21, 2018
@christianholsen can you paste a gist with a powershell script that you use to prepare migration file?
Thanks in advance.
christianholsen commentedon Oct 4, 2018
Yep. As a wrote above the only problem I found was the specific scenario specific where I have created an index for a nullable column and later remove it. The problem arises when the CREATE UNIQUE INDEX statement is evaluated even though it is not executed. So I have chosen to wrap all CREATE UNIQUE INDEX statements in the SQL in EXEC blocks. This has the effect that the script is dynamic and will only be evaluated when it actually is executed - fixing the immediate problem.
I use Team City as my build tools. You should be able to use this approach with any build tool.
I have a build step where I create the idempotent SQL file as mentioned in my first post. This step is executed as a command line step using the dotnet cli : dotnet ef migration script...etc (see my first post) This creates the idempotent script 'migrationscript.sql'
Next I have a powershell script step where I replace CREATE UNIQUE INDEX using regular expressions.
The code is here:
As I understand it this problem will be fixed at some point in EF CORE, so this is working fine for me for now. :-)
Hope this helps,
/Christian
tonven commentedon Oct 4, 2018
@christianholsen Thanks for response. I found different solution. I am producing all migrations separately and in Octopus Deploy run only those migrations, that were not applied. So I am waiting as well when this will be fixed, so I can switch back to migrations.sql. :)
Kukkimonsuta commentedon Oct 10, 2018
We are experiencing the same issue with hand written updates after column was removed/renamed:
migrationBuilder.Sql(@"UPDATE [Foo] SET [Bar] = 15 WHERE [Bar] = 10");- it would be great if this was also wrapped when generating a script.mitchelsellers commentedon Nov 6, 2018
We are also experiencing this issue. The workaround that @christianholsen used seems to have gotten us past this, as we are using Azure DevOps for deployments we were able to patch the script before we release.
acarrau commentedon Nov 9, 2018
The same is occurring to us with Idempotent Script Generation. In our case it is not happening with an INDEX creation, but with an IDENTITY INSERT.
Shtong commentedon Feb 27, 2019
Another project where this problem occurs (without involving indexes) is the current version of the Contoso University sample app (available here https://github.com/aspnet/Docs/tree/0ee6b101d9d4b4022add3583ed25f0d89674b87b/aspnetcore/data/ef-mvc/intro/samples/cu-final). The
Inheritancemigration creates a temporary column (OldID) that is created and immediately removed in the same migration ; and after the first run, the database rejects the itempotent migration script because the column does not exist.Unfortunately in this case, wrapping the instructions in an
EXECcall with a simple regex replace won't be enough, as we would need to escape the quotes inside theEXECargument, like in that case:adria3a3 commentedon May 13, 2019
I'm having the same problem with the migrations. When the idempotent flag is set not all statements are wrapped with a
EXECstatement and the migration fails.It there an ETA know for this issue to be resolved?
bricelam commentedon May 13, 2019
We still hope to address this issue before the final 3.0.0 release (this September).
69 remaining items
VidSankar commentedon Mar 14, 2021
bricelam commentedon Mar 19, 2021
@derigel23 Can you create a new issue with more details about the issue you're encountering?
derigel23 commentedon May 3, 2021
@bricelam I've found out that errors are rising from my custom SQL statements in migration builder.
Should I escape them manually in EXEC or is there some better way?
bricelam commentedon May 3, 2021
Escape them manually. Users are responsible for ensuring their custom SQL statements work with the idempotent script. (Since we generally avoid trying to parse SQL in EF)
jasonbert commentedon May 31, 2022
Super useful, great idea, we're building the idempotent script and publishing as an artifact. At the time of build we can't determine which migrations have been applied, just when we're running the release. Should resolve the problem described in this issue about the invalid column name, which we're experiencing 👍.
Worth noting that this only happens when we're running the release through Azure DevOps pipelines. It works fine If I take the script and run it through MSSMS.
ChristopherHaws commentedon May 31, 2022
We have been using this extension method in place of
migrationBuilder.Sql("...")for years now and it has worked great for us.sgabler-solytic commentedon Sep 6, 2022
@ChristopherHaws thanks for that, it solved our problem 👍
We had issues at first, because the generated SQL script didn't properly close the ' (single quotes) correctly. After some digging, we found out that our raw SQL scripts sometimes contained
GOcommands.Example
Apparently EF Core splits the scripts based on
GOcommands. So the above example would create two steps in the generated SQL script, but the first one would have a missing ' (single quote).The workaround for us was to extend your method a bit:
alexandis commentedon Feb 19, 2023
Isn't it possible to use
DbCommandInterceptorto eliminate this issue? We use it for the site, but I am not sure if it's possible to use it for migrations, insideIDesignTimeDbContextFactoryimplementationa-witkowski commentedon Jun 13, 2023
@bricelam,
dotnet ef migrations script --idempotentversion 7.0.7 still producesIF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20230523085552_init')BEGIN/****** Object: Schema [reporting] Script Date: 2023-05-17 17:27:00 ******/CREATE SCHEMA [reporting]END;GObricelam commentedon Jun 14, 2023
@a-witkowski Can you file a new issue?
brentlyjdavid commentedon Aug 17, 2023
I wonder if this could just be added to the framework. We are adding this to our projects and going to start exclusively using it too because of dropped columns in a similar situation. Getting frustrated it keeps randomly popping up in different circumstances.
Is there a security risk or something to not have the
.Sql(...)command just automatically run it/create it like that by default? rather than have an extension method?patrickklaeren commentedon Aug 25, 2023
The payload of that is specific to SQL Server. I don't think there's particularly high overhead to putting that into a project yourself, personally.
It's less of a security concern and more of a behavioural quirk, I'd say mainly because this is largely dependent on the engine you're targeting.