Prisma db push error when removing column that has a default value - prisma

After removing a column from schema.prisma, and running npm prisma db push, I'm getting the error...
Error: The object 'users_role_df' is dependent on column 'role'.
I'm using Prisma 3.3.0 with the sqlserver connection.
The model looks like this...
model User {
id ....
name ...
role String #default("USER")
}
I see the initial push created the CONSTRAINT users_role_df but now when I remove it from the model, and run push, it's not handling removing the constraint first and then the column.
How can I fix this?

You could try running the command npx prisma migrate dev --create-only to see what the generated SQL looks like for the migration.
You could manually add a DROP CONSTRAINT users_role_df; inside the generated migration or change the order of the SQL commands (if such a command already exists in the generated migration).
It is fine for you to make changes to the migration file as long as you do it before applying the migration to your database.

Related

how can make a changes prisma.schema model fields, without losing data after mgration?

How can make a change to the database with Prisma.js without having to reset the whole thing?
When I changed prisma.schema and run:
npx prisma migrate dev --name change-name
My database lost all data. Can I run another command which doesn't remove my data? What is best for me in this situation?
You would need to Baseline your database in order to not reset your database.
For the cases which contains data that must be maintained (like production), which means that the database cannot be reset, In those cases Baselining tells Prisma Migrate to assume that one or more migrations have already been applied. This prevents generated migrations from failing when they try to create tables and fields that already exist.

How to run Prisma schema update without erasing the PostgreSQL data?

I have a PostgreSQL db that is used by a Nest.Js / Prisma app.
We changed the name of a field in the Prisma schema and added a new field.
Now, when we want to update the PostreSQL structure, I'm running, as suggested by Prisma, the following commands:
npx prisma generate
and then
npx prisma migrate dev --name textSettings-added --create-only
The idea is to use the --create-only flag to review the migration before it is actually made.
However, when I run it I get a list of the changes to be made to the DB and the following message:
We need to reset the PostgreSQL database "my_database" at "my_db_name#cluster.us-east-1.rds.amazonaws.com:5432".
Do you want to continue? All data will be lost.
Of course I choose not to continue, because I don't want to lose the data. Upon inspection I see that the migration file actually contains DROP TABLE for the tables that I simply wanted to modify. How to avoid that?
So how do I run the update without affecting the data?
UPDATE:
I saw that running with --create-only creates a migration which can then be implemented on the DB level using prisma migrate dev, however, in that migration file there are still some commands that drop my previous tables because of some new parameters inside. How can I run prisma migration without deleting my PostgreSQL data?
UPDATE 2:
I don't want Prisma to drop my tables when I just updated them. The migration file generated, however, drops them and then alters them. Do you know what's the best procedure to avoid this drop? I saw somewhere I could first manually update the DB with the new options and then run the migration, so Prisma can find a way to update it, but that seems too manual to me... Maybe some other ideas?
For some cases like renaming tables or columns, Prisma's generated migration files need to be updated if they already contain data.
If that applies to your use case, Prisma's docs suggest to:
Make updates to the prisma schema
Create migration file without applying it (--create-only flag)
Update the migration script to remove the drops and instead write your custom query (e.g. RENAME <table_name> TO <new_name>)
Save and apply the migration (npx prisma migrate dev)
Note that those changes can lead to downtime (renaming a field or model), for which they have outlined the expand and contract pattern.
It might be a Prisma bug: https://github.com/prisma/prisma/issues/8053
I also recently had this situation. It probably should not try to run migration if you only want to create migration file.
But overall it is expected with Prisma to recreate your db sometimes. If you migration is breaking then it will be required to reset the data anyway when you apply it.
I suggest you to create some seeding script so you could consistently re-create the database state, it's very useful for your development environment.
More info

How do you make prisma redeploy to a database after you've removed all the tables from the database

I used prisma to generate the schema to a database, but due to changing an id column started getting errors. I deleted the tables and was going to redeploy the schema but I can't find a way to do that.
I've already tried doing things like prisma deploy, but it tells me I'm already sync'd up which isn't true. I need it to redeploy as if the schema was new and it seems to not want to do that.
TL;DR: Try prisma delete then prisma deploy.
Prisma create a database for management where it will hold all migration related data. Even if you deleted the tables manually, you didn't change the migration data about your service. Therefore, Prisma think everything is up-to-date.
Instead of manually deleting the tables, you should use prisma delete to let Prisma do a clean deleting of your tables. Then, you can re-run prisma deploy to rebuild the tables again.
Give this a try: "prisma deploy --force"
According to the documentation you have to accept data loss caused by schema changes with --force. But the tables are already deleted in your case, so I think it is ok to try it.
Prisma doc

Forcing a failed mvn flyway:migrate to skip failed schema migration, and try executing next schema

I was trying to run flyway:migrate on my projects postgres database. I have made the changes to a table manually and because of that the schema migration using flyway is failing, which is blocking next schema migration execution.
table : foo
required_change : ALTER TABLE foo ALTER COLUMN id DROP NOT NULL
current_schema_version : 2
next_schema_version : 3
Error:
[ERROR] com.googlecode.flyway.core.api.FlywayException: Migration of schema "public" to version 3 failed! Changes successfully rolled back.
How could I skip failing schema and make flyway:migrate execute next schema defined?
It might be simplest to undo the manual change so that Flyway can run successfully. For example, if you dropped the column then add it back in, then run the Flyway script to drop it.
So I found one possible solution to this problem, which goes as follows:
(1). In mysql database there is a table schema_version, which maintains the migration version number , it's status and other related information.
for ex.
mysql> desc schema_version;
version_rank
installed_rank
version
description
type
script
checksum
installed_by
installed_on
execution_time
success
for a failed migration the success field values stores 0, to override that and execute the next flyway:migration you can manually set the value to 1 (this would make sure, you don't lose the data stored on the table you created manually , when migration failed.
(2). Adding following on your pom.xml while running flyway:migration temporarily (while testing) also helps.
<validateOnMigrate>false</validateOnMigrate>

EF 7 Migration to Existing Database

I am working on a web project using ASP.Net 5 and EF7.
I have imported all the tables from existing database onto my models in my project. However, I am having problems in regards with migrations.
I have created the initial migration, made some changes on particular entity, create another migration following the changes I have made and now want to apply the changes on the database.
After running this command below:
dnx ef database update [Migration]
the dnx is trying to apply the 'initial' migration with all the entities which are already in database and this causes an error as below:
{ There is already an object named ['EntityName'] in the database. }
Can you please advise on how to do the migration on the existing database?
Thanks
Saeed
In EF6 you would run a migration with the -IgnoreChanges flag and it would take a snapshot of the model without any Up() code. This is missing from EF 7(EF Core) as indicated here.
The workaround for now is delete or comment out the code for existing database objects from the Up() code of the migration and then update-database. Subsequent migrations will then include only the changes.
After 2 days I found a way for EFCore that is not in google and internet!
How My steps works?
When you have a database with 10 table and you have data in tabales that you don't want to clear's data.and after this you will create new models in your code first and runnig to existing database and you will get error "Invalid object name 'tableName'." for query to new tables and you want to create migrations and do update it to existing database but first migration will create all queries for old and new tables if you run update-database you will get "There is already an object named ['EntityName'] in the database." for your initial migration.
How fix it?
Delete all migrations and snapshot in you database project
Delete __EFMigrationsHistory table in your existing database (if exist)
Run in Package manager console:
Note before run: This code will create new context and models of your existing database to Data folder so don't forgot to check you have not Data folder in your project.
Scaffold-DbContext "your connection string"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data
Run in Package manager console:
Note before run: Create first migration for initial database with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Add-Migration initial -Context OldDataBaseContext
Delete all code in Up method inside of created initial migaration in step 3
Run in Package manager console:
Note before run: Update databse with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Update-Database -Context OldDataBaseContext
Delete data folder that created in Step 2
Go to snapshot and initial migration classes and change the deleted context from Data folder to main context that is exist in your database project (just fix it for build)
Run:
Note before run: Add migration for main context that have new database changes
Add-Migration newUpdate
Run:
Update-Database
I Hope this help someone.
If you are strongly believe, that new (EF7) database schema will match your old database schema (including index and key names) - you may run 'Initial' migration to empty (temporary) database and then copy __EFMigrationHistory table from there to your real database.
Otherwise, I recommend you create empty database using migration and use sql insert into ... select commands to copy data from your old database. Without this, you will receive exceptions when upgrading database later - for example changing index will lead to DropIndex and CreateIndex migration commands, and DropIndex will fail because there is no index with this name (index exist with other, pre-EF7 name).
In my projects - old (from EF6) and new database schemes are different, and I used second option.