Skip to content

Allow Prisma to work with foreign key that uses different (native) types on each side #5289

Open

Description

@divyenduz

Bug description

prisma introspect with native types produces invalid schema.

How to reproduce

  1. Deploy the following SQL
CREATE TABLE public.grading_periods (
    id bigint NOT NULL,
    grading_period_group_id integer NOT NULL
);

ALTER TABLE ONLY public.grading_periods
    ADD CONSTRAINT grading_periods_pkey PRIMARY KEY (id);

CREATE TABLE public.grading_period_groups (
    id bigint NOT NULL
);

ALTER TABLE ONLY public.grading_period_groups
    ADD CONSTRAINT grading_period_groups_pkey PRIMARY KEY (id);

ALTER TABLE ONLY public.grading_periods
    ADD CONSTRAINT fk_rails_9cc118401a FOREIGN KEY (grading_period_group_id) REFERENCES public.grading_period_groups(id);
  1. prisma introspect (with nativeTypes flag) produces
model grading_period_groups {
  id              BigInt            @id @db.BigInt
  grading_periods grading_periods[]
}

model grading_periods {
  id                      BigInt                @id @db.BigInt
  grading_period_group_id Int                   @db.Integer
  grading_period_groups   grading_period_groups @relation(fields: [grading_period_group_id], references: [id])
}
  1. prisma validate returns
(base) divyendusingh [prisma-explicit-panic]$ yarn prisma validate
yarn run v1.22.4
$ /Users/divyendusingh/Documents/prisma/triage/prisma-explicit-panic/node_modules/.bin/prisma validate
Prisma schema loaded from schema.prisma
Error: Schema parsing
error: Error parsing attribute "@relation": The type of the field `grading_period_group_id` in the model `grading_periods` is not matching the type of the referenced field `id` in model `grading_period_groups`.
  -->  schema.prisma:19
   | 
18 |   grading_period_group_id Int                   @db.Integer
19 |   grading_period_groups   grading_period_groups @relation(fields: [grading_period_group_id], references: [id])
20 | }
   | 

Prisma information

(base) divyendusingh [prisma-explicit-panic]$ yarn prisma --version                                                                                                                  130 ↵
yarn run v1.22.4
$ /Users/divyendusingh/Documents/prisma/triage/prisma-explicit-panic/node_modules/.bin/prisma --version
@prisma/cli          : 2.16.0-dev.17
@prisma/client       : 2.16.0-dev.17
Current platform     : darwin
Query Engine         : query-engine d621d9b01ebb4c8fcd3adeaf3421e0149c676c58 (at node_modules/@prisma/engines/query-engine-darwin)
Migration Engine     : migration-engine-cli d621d9b01ebb4c8fcd3adeaf3421e0149c676c58 (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine : introspection-core d621d9b01ebb4c8fcd3adeaf3421e0149c676c58 (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary        : prisma-fmt d621d9b01ebb4c8fcd3adeaf3421e0149c676c58 (at node_modules/@prisma/engines/prisma-fmt-darwin)
Studio               : 0.343.0
Preview Features     : nativeTypes
✨  Done in 1.75s.

Activity

  1. changed the title [-]Error parsing attribute "@relation": The type of the field `<field>` in the model `<model>` is not matching the type of the referenced field `id` in model `<model2>>`.[/-] [+]Error parsing attribute "@relation": The type of the field `<field>` in the model `<model>` is not matching the type of the referenced field `id` in model `<model2>`.[/+] on Jan 26, 2021
  2. do4gr commented on Feb 2, 2021

    @do4gr
    Member

    Yeah, we could make the validation there more lenient. Although I wonder whether the db would reject the inverted case. You seem to be constraining a bigint column to values from an int column. That should always work, but the other way around could fail

  3. added this to the 2.17.0 milestone on Feb 3, 2021
  4. 4 remaining items

  5. removed
    bug/2-confirmed
    on Feb 25, 2021
  6. carchrae commented on Feb 28, 2021

    @carchrae

    thanks for reporting. i think the validation is great and in the db i am working with i absolutely agree that the types should be consistent. i have a similar issue to OP here, poor db design mixed references to bigint with int.

    however - as you know, tech debt cannot always be paid off immediately. i would very much like to continue with these as warnings instead of it stopping. much like how the earlier versions comments out models when there are problems

    image

    is it possible to get prisma to skip the validation check on a particular line? along the lines of /* eslint-disable no-eval */

    i guess at the moment, the quick solution is to rollback a version. i know the best/correct solution is for me to fix the columns in this db. i realise these checks are all so you can make sane migrations. and if the underlying database has these sloppy type mistakes, it might make it harder/impossible for the code that generates migrations.

    if i can dream a bit, it would be amazing if prisma could generate a migration to fixes these type incompatibilities (:pray:) by changing the columns to the same type (eg, upgrade int columns to bigint).

  7. carchrae commented on Feb 28, 2021

    @carchrae

    answering my own question

    is it possible to get prisma to skip the validation check on a particular line? along the lines of /* eslint-disable no-eval */

    i just commented out the lines in question. obviously, this means i cannot use prisma to access any of these values, however, it means that i can fix them as i need to. (i am slowly porting a legacy code base over to prisma)

  8. removed
    kind/bug
    on Mar 1, 2021
  9. do4gr commented on Mar 22, 2021

    @do4gr
    Member

    Hey @carchrae, thanks for providing your input. As you figured out, commenting out the offending fields is currently the only solution. I think you could even comment out just the relationfield and then still write to the underlying scalar fields directly. Just mentioning it in case you are commenting out both.

    model User {
      id              BigInt   @id @db.BigInt
      // Posts       []
    }
    
    model Posts {
      id             BigInt   @id @db.BigInt
      user_id   Int         @db.Integer
      // user        User     @relation(fields: [user_id], references: [id])
    }
    

    I like your idea of a cleanup helper to find Sql schema smells and offer a migration to clean them up. I'll open a separate issue about this. #6205

  10. removed their assignment
    on Mar 22, 2021
  11. carchrae commented on Mar 22, 2021

    @carchrae

    thanks @do4gr. yes, i've been learning how to overcome these different errors and warnings. a lack of valid unique ids is the other main curse, in particular, compound ids that can be made up of nullable values (but are still unique). sometimes i need to go into the woods and shout a bit.

    hmm - i just realised that maybe views can help in some of these cases https://www.prisma.io/docs/guides/general-guides/database-workflows/sql-views-postgres - yes, kind of ugly, but maybe functional. eg, in a view, null becomes 0, or you can cast a column type. yes, you can't update views, but queries with prisma could then work.

    i do appreciate you taking up the migration fix idea, but i do have a 'developer relations' recommendation, which is that instead of errors, introspect should continue to comment out models (or fields) that have issues. when i ran introspect using 2.16 it gave me a working, but incomplete, schema. when checking out if a tool is going to work with your project or not, that was a far more rewarding developer experience than lots of errors - each of which take some searching and research to resolve. being able to see it work asap in 2.16 gave me some proof it was worth investing more time using prisma and the commented out errors shown in the schema comments were clear. ymmv - but on a bigger team, proving something works well is required to invest more time (or even consider running migrations to allow the tool to work)

  12. janpio commented on Jun 14, 2021

    @janpio
    Contributor

    An alternative workaround here might be to lie to Prisma. Instead of trying to generate a client with two non matching columns in the relation, change the bigger one to actually have the type of the smaller one. This will not reflect reality, but e.g. for Int and BigInt this should be fine assuming your data confirms to that and does not include BigInts. Then the error should go away, you should be able to use the full API of Prisma on your models.

    (Although a discussion happens here, this is in the end "just" a feature request to enable this behavior. If we want to keep guidance for users around how to handle this specific case, we should put it into our documentation as a workaround for a limitation ("Prisma does not support foreign keys with different data types - this is what you can do to work with that database in Prisma anyway").

  13. added
    kind/feature
    and removed on Jun 14, 2021
  14. changed the title [-]Error parsing attribute "@relation": The type of the field `<field>` in the model `<model>` is not matching the type of the referenced field `id` in model `<model2>`.[/-] [+]Introspection produces invalid schema when foreign key uses different (native) types on both sides[/+] on Jan 29, 2024
  15. changed the title [-]Introspection produces invalid schema when foreign key uses different (native) types on both sides[/-] [+]Allow Prisma to work with foreign key that uses different (native) types on each side[/+] on Jan 29, 2024
  16. JasperSui commented on May 14, 2024

    @JasperSui

    We looked into the issue and had a discussion about this. The databases to some degree allow differing types between the underlying and the referenced column in foreign keys. However not all the combinations where they do not error out are also safe. On Postgres for example you can reference a Text column into a Char(10) column. This can of course fail at run time.

    Since we currently don't know of a use case where you would need the ability for differing types we're going to stay with the strict validation. We think this will protect the user from accidentally creating migrations that are valid SQL schemas, but might later fail at runtime.

    Our proposal for this case would be to align the types in the original database which migrate should be able to do.

    I'm leaving this issue open for others who might run into this. If you have a specific use case where you need to be able to have different types please let us know and we might reconsider. For now we're not going to change the validation.

    Hi @do4gr, we are facing the exact same issue. Here's the scenario, we've got an application which is in charge of database migration e.g. Rails, after many years, it develope two tables like:

    CREATE TABLE author (
        id bigint NOT NULL
    );
    
    CREATE TABLE book (
        id bigint NOT NULL
        author_id int NOT NULL
    )

    The type of author.id was INT, and it's migrated to BIGINT successfully, but the book.author_id wasn't.

    As you can see, the original application doesn't complain about this, and we are trying to use Nest.js with Prisma to read the existing database schema only, so Rails does the actual migration, and we use the prisma db pull to do the one-way sync-up here.

    Hope we can find a way to ignore this validation error without commenting out the relation line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions