NestJs with TypeORM migrations fail - postgresql

I use this boilerplate app to learn NestJs GITHUB LINK. The template is amazing but there was one thing that I can't fix migrations. When I try to add a new entity or use an existing one with npm run migrate:create Init migration was successful
Migration D:/src/database/migrations/1657796180301-init.ts
has been generated successfully.
but without any updating on the migration file or database. Only If I use synchronize: true and start the app the database was updated.

try to run migration:generate to generate new migrate file.

You have to run migration:run to apply migrations. This process is not done automatically because some migrations will cause you to loose data (dropping a column for example), so this gives you a chance to validate migration file before applying it.

Related

How to automatically create migration files when using sequelize?

Is it possible to automatically create migration files when using sequelize?
For example if I change my model, is there a way to automatically create a migration file that reflects those changes and run the migration to effect those changes in the database. Or do I have to manually create migration files myself?
I am using PostgreSQL.
There is a package for that
Sequelize-mig
its maintained and documented.
Install it with:
npm install sequelize-mig -g / yarn global add sequelize-mig
then use it like this
sequelize-mig migration:make -n <migration name>
and it will generate the migration file
I highly recommend Sequelize-mig, as referenced by MRVMV. I have 25 years of experience in creating my own ORM, and for my most recent project I decided to finally use an existing ORM. I chose Sequelize and as I got going with it, I was sorely disappointed that it does not have the ability to automatically genereate migration files by inspecting model files. This issue landed me here in this SO thread, and so I tried sequelize-mig. I read the docs and tried it out for about 4 hours and I find it to be working very well.
Using it, you can just create/modify your models .js files, then call "npx sequelize-mig migration:make --preview" to see what it will do. Carefully inspect all the preview code and make changes until you love the result. Then call "npx sequelize-mig migration:make -n <>" and it will populate the migration files. Carefully inspect those and when you love them, then use sequelize to migrate to your dev database by calling "npx sequelize-cli db:migrate" and that's it.
Next up, I will decide upon the best way for moving these migrations to production. But that decision doesn't have anything to do with sequelize-mig - it is the same decision you have to make for sequelize itself, just that now you get automatic generation of your migration files, thanks to sequelize-mig.
Highly recommend sequelize-mig!

Resetting Entity Framework Migrations then synchronizing schemas from previous migrations

I am using Entity Framework 6.1.3 Data migrations along with code first.
I am in the process of resetting the migrations. I have deleted the migrations history table and created a new baseline snapshot of the current state of the db. Everything works fine on a new install with the following intializer:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<T>, Migrations.Configuration>(true));
However, how should one deploy this reset to our customers who have an existing database? This fails locally when i have an existing db with the error:
There is already an object named '*****' in the database.
Does anyone have a better approach when needing to reset migrations and synchronizing schemas of existing databases?
I set out thinking I needed to reset my migrations because previous developers on my team were not using the Add-Migrations script correctly. This was causing the following error:
However, I wasn't sure how that would work out for existing customers. I didn't realize that I was able to re-scaffold my migrations. After much SO searching and trial and error, I was able to save my migrations. I first migrated to a migrations that was in a good state.
It was important to use the fully qualified name given. After trial and error I found a stable migration. I verified this by running the following:
It would succeed if EF could fully reconcile. I also had to exclude from VS project, all the migrations following the recently targeted migration. Simple shift select, right click and exclude from project.
Then I added the next migration back to the project after i updated the database. I also used the fluent API to exclude all the model changes following the currently targeted migration.
Then I incrementally re-scaffold all the broken migrations.
Then at the very end I created an idempotent script of my schema up to this point. Using the following:
My migrations are now not complaining about model mismatch and I am happy.

EF 6 Code First Migration - Controlling the sequence in which Migration scripts execute and DB schema gets created

This is my first question in SO, though i have been referring to questions posted for quite some time.
I was recently doing a code first migration for an existing database to migrate it to the latest version. My DB initializer was using the default strategy "CreateDatabaseIfNotExists" and I'm using SQL server 2012 express.
The following were the steps used to do the migration:
1. Enabled migrations with the older database v1 and corresponding code version cv1. Generated initial migration script with -IgnoreChanges option. Updated the database with this migration.
2. With the latest code version cv2, used the older database v1. Added migration to generate the actual migration script for the schema changes and updated database
This worked perfectly for an existing database and it got successfully migrated to the latest version.
But for a new database, the database gets created, but seeding was not happening. On debugging, I could notice that the migration scripts are getting executed first even before DB schema was created.
The migration scripts are failing since the tables being migrated have not even been added yet.
Note:
I have turned OFF AutomaticMigrationsEnabled for migrations.
Please note, a similar approach to the above was working fine for the earlier version of EF - 4.3 which i was using.
This is the code in App_Start:
Database.SetInitializer(new DBLayer.Models.MyDBInitializer());
using (MyDBContext db = new MyDBContext())
{
db.Database.Initialize(false);
if (!db.Database.Exists())
{
((IObjectContextAdapter)db).ObjectContext.CreateDatabase();
}
//Initializing membership APIs
MembershipInitializer.InstallServices();
In the above code, after db.Database.Initialize, migration scripts are executing where as tables are not yet added and hence error gets thrown.
On disabling migrations and creating a new database, things work fine again.
My questions are:
How can you control this sequence for executing migration scripts to first add the tables before executing migration scripts. What am I missing here?
When automatic migration is turned OFF which are the migration scripts getting executed first place?
Please advise. Please let me know if you need any more info.

Entity Framework 6 - Does not create tables when enabling Migrations

In my application I enable Code First Migrations with some migrations, Also I use SQL Server Compact for integration test.
When I run my tests, Entity Framework create an empty database and tries to run migration on that empty database and thrown The specified table does not exist.
Based on this report I think usage of Migration in Entity Framework 6 has changed.
I test all Database Initializer with Context.Database.Create(); but in all case tabale's never created.
I don't know that this is EntityFramework's bug or not, but when I made rename the namespace of Migration Configuration class from default (Projectname/Migrations) to any none default name, migration works well.
Context.Database.Create() will not execute migrations! It only creates empty db. To Update database from code to latest version you need to use DbMigrator.Update method:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
Alternatively you might use MigrateDatabaseToLatestVersion
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());
It is described in details here: http://msdn.microsoft.com/en-us/data/jj591621.aspx#initializer
In case someone still struggles to fix the issue.
The code that follows works for me: add-migration MyFirstMigration
Meanwhile add-migration "MyFirstMigration" with the migration name ramped in quote doesn't work.
There may be previous migration files which the ide may be referring to mostly likely due to caching.
Drop backup and drop target database if it exists, and drop the migration folder.
Now add the migration and you will be good to go.
It does happens when adding model and running add-migration command.
Here is the simplest cause of this issue:
Add a newly added model property into IdentityDbContex class.
Here are the steps:
create model
add property into IdentityDbContex class
run add-migration
update-database

How to Manage EF Migrations Between Development and Production Databases?

Before anyone marks this as a duplicate, none of the questions similar to this addressed any of my concerns or answered any of my questions.
I am currently developing all the POCOs and data contexts in a library project, and running migrations from within this project. The database I'm updating is the development database.
What do I do if I want to create the current schema to a fresh, new database? I figure that all I have to do is to change the connection string in web.config and run Update-Database, correct?
While the live/production database is up and running, I want to add new columns and new tables to the schema, and test it out in development. So I switch back the connection string to the development database's connection string, and run Update-Database.
Going back and forth between two databases seems like I'll get conflicts between _MigrationHistory tables and the auto-generated migration scripts.
Is it safe to manually delete the _MigrationHistory tables in both databases, and/or delete the migration files in /Migrations (so I'll run Add-Migration again)? How do we manage this?
What do I do if I want to create the current schema to a fresh, new database?
- Yes, to create fresh database to the current migration level you simply modify the connection string to point to a database that does not yet exist and run update-database. It will run all the migrations in order.
As far as migrating to the Production database, I am running the update-database command with the -script switch to acquire the raw sql and then applying that script to the production database manually. This is helpful if you need to keep a record of sql commands run against the database as well. Additionally, you can generate the script explicitly from a specific migration to another specific migration via some of the other update-database switches.
Alternatively, you can create an Idempotent script that works from any migration by using the–SourceMigration $InitialDatabase switch and optionally specify an end migration with –TargetMigration
If you delete the _MigrationHistory tables you will have issues where the generated script will be trying to add columns that already exist and such.
You may find the following link helpful:
Microsoft Entity Framework Migrations
I would suggest having a separate trunk in your source code repository - one pointing to production and one to development to avoid risks of switching between the two in visual studio.
Me also had the same problem, even when using one and the same database - due to some merges in the repository, and the mix of automatic/manual migrations. For some reason the EF was not taking into account the target database, and calculating what scripts need to me executed, based on what is already in the database.
To fix this, I go to the [__MigrationHistory] table on the target database and get the latest migration name. This will help EF to determinate the state of the DB, and will execute just the scripts needed.
then the following script is run:
update-database -script -sourcemigration {latest migration name}
This creates update script that is specific to the target database (the connection string should be correct, as discussed in the other comments)
you can also use -force parameter if needed
this way you can update any database to latest version, no mater in what version you found it, if it has MigrationHistory table.
Hope this helps
My production and my developmental database went out of synch and it gave me endless problems. I solved it using a tool from Red-Gate to match up the databases. After using the tool, the databases were exactly the same but my migration was not working and I started to get odd errors i.e. trying to add tables/ columns that already existed etc. I solved that. I just deleted the migration folder on the local, recreated it, added the initial migration, updated the database and then matched the data of this migration file (local) to the one on the host (delete all the data in the migration file on the host, and add the same data that is on the local into the host). A more detailed explanation is at:
migration synch developmental and production databases