I have a simple Prisma schema (I'm only using the relevant part):
enum ApprovalStatus {
APPROVED
DENIED
PENDING
}
model Attendee {
user User #relation(fields: [user_id], references: [id])
user_id BigInt
event Event #relation(fields: [event_id], references: [id])
event_id BigInt
status ApprovalStatus #default(APPROVED)
created_at DateTime #default(now())
updated_at DateTime? #updatedAt
deleted_at DateTime?
##id([user_id, event_id])
##unique([user_id, event_id])
##map("attendees")
}
After saving the schema I run npx prisma migrate dev, and it creates the migration and successfully migrates. A quick peek in postgres shows that the table is created and a \dT+ shows that the new type and the 3 entries, have been added as well.
Then I noticed that subsequent runs of migration started adding some weird alter table lines for the attendees table, for no reason. I checked the migration and there was no reason for it. Here's the migration of the attendee table, and as you can see status column is quite clearly defined:
-- CreateTable
CREATE TABLE "attendees" (
"user_id" BIGINT NOT NULL,
"event_id" BIGINT NOT NULL,
"status" "ApprovalStatus" NOT NULL DEFAULT 'APPROVED',
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
"deleted_at" TIMESTAMP(3),
CONSTRAINT "attendees_pkey" PRIMARY KEY ("user_id","event_id")
);
And now, even if there were no changes to anything in the schema, and all previous migrations were properly applied, running npx prisma migrate dev (with or without --create-only) will always generate a migration with following:
/*
Warnings:
- The `status` column on the `attendees` table would be dropped and recreated. This will lead to data loss if there is data in the column.
*/
-- AlterTable
ALTER TABLE "attendees" DROP COLUMN "status",
ADD COLUMN "status" "ApprovalStatus" NOT NULL DEFAULT 'APPROVED';
It's acting as if the type or name of the column has changed, even though there were no changes to the model or even entire schema for that matter. If I run the generate command more times, it will create this same migration each time with the exact same content. I thought it might have something to do with migration order, but unless it's doing migrations randomly, ApprovalStatus migration comes before attendees does. I really see no reason for it to behave this way, but I'm uncertain how to proceed. Any advice would be welcome.
EDIT: Additional info
"prisma": "^4.6.0"
"express": "^4.17.2"
"typescript": "^4.8.4"
psql (15.0, server 12.13 (Debian 12.13-1.pgdg110+1))
There was a regression introduced in Prisma v4.6.0 where Prisma drops and recreates an enum field as can be seen in this issue. This was fixed in Prisma v4.6.1. Kindly update to the latest version and you should not experience this issue with Prisma migrate.
Related
I did some manual modifications to my database table, so now Prisma won't let me run migrate dev. I want to undo my changes, so I'm back in sync with what Prisma want me to have.
I had a lot of changes that I've managed to fix. But there's still one left that I don't know how to handle.
[*] Changed the `Product` table
[*] Altered column `id` (sequence changed)
This is a Prostgres database. How do I reset the sequence to whatever value Prisma wants it to be? How do I know what value Prisma wants?
The problem was that the id column had been re-created with an INTEGER type. The original table had a SERIAL type. After fixing that I could successfully run my migration.
The correct types to use was found in my very first migration.sql file in the migrations folder.
-- CreateTable
CREATE TABLE "Product" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"desc" TEXT,
"longDesc" TEXT,
"price" INTEGER,
"imgUrl" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ("id")
);
I want to create column with the following definition
updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE now(),
But when I type in schema.prisma
updated_at DateTime #updatedAt #db.DateTime(0)
Then I obtains table with column:
`updated_at` datetime NOT NULL,
How to add ON UPDATE now() to this column using prisma? I use MySQL/MariaDB.
References:
Connected problem
https://github.com/prisma/prisma/issues/5799#issuecomment-894631317
Article about ON UPDATE
https://medium.com/#bengarvey/use-an-updated-at-column-in-your-mysql-table-and-make-it-update-automatically-6bf010873e6a
Based on the client reference it seems that the client itself is responsible for providing the updated at DATETIME value instead of the way you're wanting it (to be done in the DB server).
If you really need the table/column definition to be exactly as you want, I would suggest creating or modifying the table directly in SQL and then using introspect to import the definition in your schema.
You could even add the definitions to your prisma migration files as these are just plain sql files. How to do this can be found in the Customizing Migrations article
I'm not really sure what I've done wrong. But this caused the other services to mess up the other db migration stuff.
Hoping someone will help me with the cause.
Thank you!
We have a db migration script that creates a table
V6__add_subscription_tables.sql
CREATE TABLE plan_subscription (
id bigint NOT NULL,
version bigint NOT NULL,
team_id bigint NOT NULL,
plan_id bigint NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (plan_id) REFERENCES plan (id),
UNIQUE (team_id)
);
Added another script that would add to dev environment a plan_subscription
But in my current task, the migration will fail if it's a fresh database so I deleted the insertion
V5002__add_test_data.sql
//There are other test data here
/* THIS IS THE DATA THAT I DELETED
INSERT INTO plan_subscription VALUES (nextval('plan_subscription_sequence'), 0, 3, currval('plan_sequence'));
*/
And since I have to alter the table and add a column with constraint, I moved the adding of test data in the new db migration script but.
There seems to be no error but it messed up something that I'm not sure what's the cause.
V5004__add_date_occurred_in_plan_subscription.sql
ALTER TABLE plan_subscription ADD
date_occurred TIMESTAMP WITHOUT TIME ZONE NOT NULL;
INSERT INTO plan_subscription VALUES (nextval('plan_subscription_sequence'), 0, 3, currval('plan_sequence'), current_date);
So what I did, I just removed the NOT NULL constraint and reverted the deletion of the old test data.
I know this is kinda long and weird but I'm hoping someone would know the reason.
Thank you!
I got a table of the following form in Postgres:
CREATE TABLE contract (
id serial NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
price float8 NOT NULL,
CONSTRAINT contract_pkey PRIMARY KEY (id)
);
In Microsoft Powerapps, I create a EditForm to update the table above. For other databases, like MS SQL, I didn't need to supply the id, since it's auto increment. But for some reason, PowerApps keeps demanding to fill in the id for this table, even though it's auto increment and shouldn't be supplied to Postgres.
Anyone with the same experience with Powerapps in combination with Postgres? Struggling with it for hours...
I have installed a blog engine to refinerycms which is working perfectly.
Now I have generated a migration with some table fields changes (of course not refinerycms or blog tables), but I'm getting an error:
== CreateBlogStructure: migrating ============================================
-- create_table("refinery_blog_posts", {:id=>true})
NOTICE: CREATE TABLE will create implicit sequence "refinery_blog_posts_id_seq1" for serial column "refinery_blog_posts.id"
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::Error: ERROR: relation "refinery_blog_posts" already exists
: CREATE TABLE "refinery_blog_posts" ("id" serial primary key, "title" character varying(255), "body" text, "draft" boolean, "published_at" timestamp, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Check your db/schema.rb
You most likely have the same table being created there in addition to a migration in db/migrate/[timestamp]your_migration
You can delete the db/migrate/[timestamp]your_migration if it is a duplicate of the one found in the schema and it should work.
PG::Error: ERROR: relation “refinery_blog_posts” already exists
Pg is a Rails gem, the piece of code that allows communication between Rails and PostgreSQL. It relates your migrations to SQL tables, thus a relation error. So, what the error is saying is:
I'm trying to create table X, based on migration X, but table X
already exists in the database.
Possible solutions:
Create migrations that drop those, probably old, tables.
Change the migration's name.
Login to PostgreSQL and drop the table. Something like:
$ psql -U username databasename
then
database_name=# drop table table-name;
The exact commands might be a little different though.
Adding as this is an obvious but easy to overlook cause of this error (and this is the first post search engines bring up).
If you accidentally defined the same relationship twice in the same migration this is the error that shows up.
def change
create_table :books do |t|
t.belongs_to :author
t.belongs_to :author # Duplicated column definition
end
end
Seems obvious but easy to overlook. To fix just remove the duplicated reference.