I see the related question already there. FluentMigrator Failed Migrations Don't Rollback? and Rollback to a specfic Migration in FluentMigrator. But unfortunately i can't solve my rollback issue with this solution. I am using FluentMigrator to versioning database.
My migration code :
using FluentMigrator;
namespace WebCruiter.Candidate.DBMigration.Migrations.R2016_6
{
[Migration(20160908000908, "USERSTORY")]
public class Migration20160908000908 : AutoReversingMigration
{
public override void Up()
{
Create.Column("TestUrl").OnTable("JobApplication").AsString(500).Nullable();
}
}
}
And my attempt to rollback this version(20160908000908) from command line:
migrate.exe -c "server=(LocalDB)\MSSQLLocalDB;Initial Catalog=Candidate;Integrated Security=True" -db sqlserver2014 -a ".\..\..\..\WebCruiter.Candidate.DBMigration\bin\Debug\FluentMigrator.dll" -t rollback:20160908000908
Without rollback column TestUrl from JobApplication it shows :
Can anybody help me out where i made a mistake ?
Because you need to give the runner the number of the migration before the one you want to rollback to. So say you have migrations 1, 2, and 3. And you want to rollback 3, you would give the runner 2
What you are giving the runner at the moment is not that, give it the migration before '20160908000908'.
This is basically what was written in Rollback to a specfic Migration in FluentMigrator, You write the number of the migration you want as your last one, not the number of migration you want to rollback to.
Related
I have successfully configured spring boot with a new project to work
with flyway
Migrated with the Postgres database from the version 0001.0 to 0008.0
I have made manually alter the script in local but
flyway migration getting failed.
Sample Error message:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'flywayInitializer' defined in class path
resource
[org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]:
Invocation of init method failed; nested exception is
org.flywaydb.core.api.FlywayException: Validate failed: Migration
checksum mismatch for migration version 0006.0
How to alter the database tables without affecting flyway script from the flyway_schema_history?
For example, I need to change the table name using alter command but executing the flyway migration script without failed.
Any suggestions, Kindly appreciated.
Note:- I don't want to remove the script entries from the table flyway_schema_history.
There are a few ways to do this:-
1) Create a new script file with incremented version. Put your DDL commands to alter the table in this file. Then run migration.
2) If you don't want to delete the entry from the schema_version table, you can change the checksum value in that table. To calculate checksum, use the following method copied from org.flywaydb.core.internal.resolver.sql.SqlMigrationResolver. You can pass null for resource parameter:-
/**
* Calculates the checksum of this string.
*
* #param str The string to calculate the checksum for.
* #return The crc-32 checksum of the bytes.
*/
/* private -> for testing */
static int calculateChecksum(Resource resource, String str) {
final CRC32 crc32 = new CRC32();
BufferedReader bufferedReader = new BufferedReader(new StringReader(str));
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
crc32.update(line.getBytes("UTF-8"));
}
} catch (IOException e) {
String message = "Unable to calculate checksum";
if (resource != null) {
message += " for " + resource.getLocation() + " (" + resource.getLocationOnDisk() + ")";
}
throw new FlywayException(message, e);
}
return (int) crc32.getValue();
}
3) If you are using Flyway Pro version 5+, you can rollback the migration https://flywaydb.org/getstarted/undo.
The answers here are outdated but can still help you.
It sounds like you might be in one of two situations:
You want to re-run a versioned migration. This isn't really how flyway works, as Kartik has suggested, create a new versioned migration to alter the table.
A migration file has been modified and you want to leave it that way and run new ones (eg 0009.0). In this situation you can try:
Run repair. Which will recalculate the checksums (among other things).
Turn off the validateOnMigrate option which will not fail a migration if there are modified migration files.
To solve this error locally without dropping your whole db:
Fix the migration error which caused the root problem
Disconnect your db server
Open the table "flyway_schema_history" which would be created automatically
Delete the rows with the versions that are causing the mismatch problem
Open the tables that have columns depending on the conflict migrations and drop those columns (if needed)
Run again your db server with the new migrations
I am trying to revert a PostgreSQL database with with the Vapor command:
vapor run prepare --revert -y
I get this out put:
Running mist...
Are you sure you want to revert the database?
y/n>yes
Reverting Post
Reverted Post
Removing metadata
Reversion complete
In case you are wondering, I have tried doing this multiple times, so the Post class gets prepared, but the others don't.
This command reverts that tables for all the models, except one (There are four total).
For some reason the 'pages' table will not revert.
And when I try running the app after reverting the database, I get this error:
invalidSQL("ERROR: relation \"pages\" already exists\n")
Here is the database preparation code for the model:
extension Page: Preparation {
static func prepare(_ database: Database) throws {
try database.create("pages", closure: { post in
post.id()
post.string("content", length: 10000)
post.string("name")
post.string("link")
})
}
static func revert(_ database: Database) throws {
try database.delete("pages")
}
}
I managed to fix this by deleting the old DB:
dropdb `whoami`
Then creating a new one:
createdb `whoami`
Problem solved!
I am currently experiencing a SQL Timeout when running a SQL() command inside of an EF Migration.
Situation:
I am replacing a bunch (>50) tables with one table, and need to convert the data from those tables I'm about to drop into the new table. I've organized the Migration the following way:
1.Create the new table.
In the same Migration, use the SQL() function to run a sql script that migrates the data.
3.Drop all the old tables.
Currently, the migration gives the following error:
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
The error is happening in an environment where I give them an installer, and they run it without me involved, so I can't manually run individual migrations, and pause in the middle to run the SQL script.
Is there any way to change the timeout for a connection, or get around this issue?
Environment:
EF 6.0 Code First
SQL Server 2012
See this answer.
Use Configuration.cs file to set custom time out:
internal sealed class Configuration :
DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "YourDbContext";
// New timeout in seconds
this.CommandTimeout = 60 * 5;
}
}
With this method, you can change the timeout only for migration and not everyone using your default connection string.
You should be able to set the connection timeout in the connection string, something like:
Connection Timeout=180;
We have an issue with slick 3.0 and a postgres database (9.5) on AWS, where slick opens a transaction but does not seem to commit it, leaving an open connection "idle in transaction" and the futures never complete.
We are just calling db.run(saveRow(row).transactionally.asTry), where
private def saveRow(row: Row): DBIO[Int] = {
val getExistingRow: DBIO[Option[Row]] = table.filter(_.id === row.id).result.headOption
getExistingRow.flatMap((existingRow: Option[Row]) =>
existingRow match {
case None => table += row
case Some(row) =>
table.filter(_.id === row.id).map(_.propety).update(row.property)
}
)
}
Now the first select statement created from getExistingRow already does not complete. It works locally, but when running it in production on AWS, all prepared statements are never commited. Logs from slick.backend just show
#1: Start transaction
#2: StreamingInvokerAction$HeadOptionAction [select ...]
We would expect to get the following further logs from slick.backend (we see them locally), but we don't see them.
#3: SingleInsertAction [insert into ...]
#4: Commit
Is there some configuration setting I need to provide for this to work on the side of Slick, HikariCP or the postgres database that could fix this? Any other ideas on how to fix this issue?
It was actually caused by using the play execution context. When switching to the scala default execution context it worked fine.
Code related info:
Refer to Entity Framework 6.13 by NuGet under Visual Studio 2013
Use database-first mode, that is, create .edmx file with Visual Studio template ADO.NET Entity Data Model -> EF Designer from database
My DbContext code:
public partial class MySampleEntities : DbContext
{
public MySampleEntities ()
{
}
public MySampleEntities (string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
...
}
One method to modify model with below sample code:
using (var dbContext = GetDbContext())
{
...
dbContext.Entry(blobItem).State = EntityState.Modified;
await dbContext.SaveChangesAsync();
}
Unit Test Cases info:
Use NUnit and Moq
Some Unit Test code:
var mockContext = new Mock<MySampleEntities>();
Test passed with initial database schema, after some database table column names changed, and execute Visual Studio "Update Model from Database..." command on .edmx diagram, update all corresponding model properties, build code, and finally failed to run unit test on code dbContext.Entry(blobItem).State = EntityState.Modified with this exception:
The model backing the 'MySampleEntities' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Solutions tried:
Use Database.SetInitializer(null) in constructors of MySampleEntities
Failed to execute NuGet Package Manager commands like Enable-Migrations, Update-Database etc with below exception, seems it is for code-first mode:
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly.
My questions:
How to resolve such issue to make unit test case run successfully?