question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Dummy foreign keys changes for every generated migration sql

See original GitHub issue

Bug description

When I run prisma migrate dev to create an apply a new migration for e.g. adding new field, the generated SQL every time contains DROP CONSTRAINT and ADD FOREIGN KEY statements, e.g.:

/*
  Warnings:

  - Added the required column `test` to the `User` table without a default value. This is not possible if the table is not empty.

*/
-- DropForeignKey
ALTER TABLE "_CreatorToProblem" DROP CONSTRAINT "_CreatorToProblem_A_fkey";

-- DropForeignKey
ALTER TABLE "_CreatorToProblem" DROP CONSTRAINT "_CreatorToProblem_B_fkey";

-- AlterTable
ALTER TABLE "User" ADD COLUMN     "test" BOOLEAN NOT NULL;

-- AddForeignKey
ALTER TABLE "_CreatorToProblem" ADD FOREIGN KEY ("A") REFERENCES "Creator"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_CreatorToProblem" ADD FOREIGN KEY ("B") REFERENCES "Problem"("id") ON DELETE CASCADE ON UPDATE CASCADE;

How to reproduce

  1. prisma migrate reset
  2. Add a new field to schema
  3. prisma migrate dev
  4. See the dummy sql statements
  5. Add a new field to schema
  6. prisma migrate dev
  7. See the dummy sql statements again …

Expected behavior

Expect to not emit ghost changes every time.

Prisma information

datasource postgres {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

type Numeric = Float

generator client {
  provider        = "prisma-client-js"
  binaryTargets   = ["windows", "debian-openssl-1.1.x"]
  output          = "../prisma/generated/client"
  previewFeatures = ["orderByRelation", "nApi", "selectRelationCount", "orderByAggregateGroup", "referentialActions", "filterJson", "namedConstraints", "fullTextSearch"]
}

generator typegraphql {
  provider                 = "node ../src/cli/dev.ts"
  output                   = "../prisma/generated/type-graphql"
  emitDMMF                 = true
  simpleResolvers          = false
  useUncheckedScalarInputs = false
  emitIdAsIDType           = true
}

// Role enum comment
/// Role enum doc
enum Role {
  USER
  ADMIN
}

// User model comment
/// User model doc
/// @@TypeGraphQL.type(name: "MainUser")
model User {
  // User model field comment
  /// User model field doc
  id          Int      @id @default(autoincrement())
  email       String   @unique
  /// renamed field doc
  /// @TypeGraphQL.field(name: "firstName")
  name        String?
  age         Int
  /// @TypeGraphQL.field(name: "accountBalance")
  balance     Numeric
  amount      Float
  /// @TypeGraphQL.field(name: "clientPosts")
  posts       post[]   @relation("posts")
  role        Role
  test        Boolean
  /// @TypeGraphQL.omit(output: true)
  editorPosts post[]   @relation("editorPosts")
  grades      Int[]
  aliases     String[]
}

enum PostKind {
  BLOG
  ADVERT
}

model post {
  uuid      String    @id @default(uuid())
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
  published Boolean
  title     String
  /// @TypeGraphQL.omit(output: true)
  subtitle  String
  content   String?
  author    User      @relation(fields: [authorId], references: [id], name: "posts", onDelete: Cascade)
  authorId  Int
  /// @TypeGraphQL.omit(output: true)
  editor    User?     @relation(fields: [editorId], references: [id], name: "editorPosts", onDelete: Cascade)
  /// @TypeGraphQL.omit(output: true)
  editorId  Int?
  kind      PostKind?
  metadata  Json
}

model Category {
  name   String
  slug   String
  number Int

  @@unique([slug, number], name: "categoryCompoundUnique")
}

model Patient {
  firstName String
  lastName  String
  email     String

  @@id([firstName, lastName])
}

model Movie {
  directorFirstName String
  directorLastName  String
  director          Director @relation(fields: [directorFirstName, directorLastName], references: [firstName, lastName], onDelete: Cascade)
  title             String

  @@id([directorFirstName, directorLastName, title], name: "movieCompoundId")
}

model Director {
  firstName String
  lastName  String
  movies    Movie[]

  @@id([firstName, lastName])
}

model Problem {
  id          Int       @id @default(autoincrement())
  problemText String
  likedBy     Creator[]
  creator     Creator?  @relation(name: "creator", fields: [creatorId], references: [id], onDelete: Cascade)
  creatorId   Int?
}

model Creator {
  id       Int       @id @default(autoincrement())
  name     String
  likes    Problem[]
  problems Problem[] @relation("creator")
}

model NativeTypeModel {
  id      Int      @id @default(autoincrement()) @postgres.Integer
  bigInt  BigInt?  @postgres.BigInt
  byteA   Bytes?   @postgres.ByteA
  decimal Decimal? @postgres.Decimal
}

Environment & setup

  • OS: Ubuntu 20.04
  • Database: PostgreSQL
  • Node.js version: v16.4.0

Prisma Version

prisma                : 2.30.0
@prisma/client        : 2.30.0
Current platform      : debian-openssl-1.1.x
Query Engine (Binary) : query-engine 60b19f4a1de4fe95741da371b4c44a92f4d1adcb (at node_modules/@prisma/engines/query-engine-debian-openssl-1.1.x)
Migration Engine      : migration-engine-cli 60b19f4a1de4fe95741da371b4c44a92f4d1adcb (at node_modules/@prisma/engines/migration-engine-debian-openssl-1.1.x)
Introspection Engine  : introspection-core 60b19f4a1de4fe95741da371b4c44a92f4d1adcb (at node_modules/@prisma/engines/introspection-engine-debian-openssl-1.1.x)
Format Binary         : prisma-fmt 60b19f4a1de4fe95741da371b4c44a92f4d1adcb (at node_modules/@prisma/engines/prisma-fmt-debian-openssl-1.1.x)
Default Engines Hash  : 60b19f4a1de4fe95741da371b4c44a92f4d1adcb
Studio                : 0.422.0
Preview Features      : orderByRelation, nApi, selectRelationCount, orderByAggregateGroup, referentialActions, filterJson, namedConstraints, fullTextSearch

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:3
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
MichalLytekcommented, Aug 28, 2021
  • new project
  • prisma db pull to create schema from database
  • prisma migrate dev to reset database, generate migration and apply it
  • in sql for that migration I see on the bottom the statements (only create, no drop):
-- AddForeignKey
ALTER TABLE "_CreatorToProblem" ADD FOREIGN KEY ("A") REFERENCES "Creator"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_CreatorToProblem" ADD FOREIGN KEY ("B") REFERENCES "Problem"("id") ON DELETE CASCADE ON UPDATE CASCADE;

When I then add new field, I still have dummy changes:

/*
  Warnings:

  - Added the required column `test3` to the `User` table without a default value. This is not possible if the table is not empty.

*/
-- DropForeignKey
ALTER TABLE "_CreatorToProblem" DROP CONSTRAINT "_CreatorToProblem_A_fkey";

-- DropForeignKey
ALTER TABLE "_CreatorToProblem" DROP CONSTRAINT "_CreatorToProblem_B_fkey";

-- AlterTable
ALTER TABLE "User" ADD COLUMN     "test3" BOOLEAN NOT NULL;

-- AddForeignKey
ALTER TABLE "_CreatorToProblem" ADD FOREIGN KEY ("A") REFERENCES "Creator"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_CreatorToProblem" ADD FOREIGN KEY ("B") REFERENCES "Problem"("id") ON DELETE CASCADE ON UPDATE CASCADE;
1reaction
janpiocommented, Sep 1, 2021

Yep, something along those lines: We recently added the namedContraints preview feature flag, which might have unfortunately changed the existing behavior as well unexpectedly. That is right up that ballpark, constraint name, special case for implicit m:n relations tables and so on.

Thanks for the digging!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Loose foreign keys - GitLab Docs
The tool ensures that all aspects of swapping a foreign key are covered. This includes: Creating a migration to remove a foreign key....
Read more >
laravel - Migration: Cannot add foreign key constraint
The solution was to rename the file with the foreign key to an earlier time ... In my case I just change the...
Read more >
3 common foreign key mistakes (and how to avoid them)
Foreign key constraints are important to any SQL database, but they can also cause problems if they're not implemented correctly.
Read more >
How to Add Multiple Foreign Keys to Same Table and Not Get ...
Let's now execute the SQL Script that creates the described database. Start by creating tables without any foreign keys. If you try to...
Read more >
How to copy migrate data to new tables with identity column ...
Copy all child rows of those rows into new tables without foreign keys to the parent table. Note: We'll refer to the above...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found