SQL Server auto-increment PK in Prisma

kkbh8khc  于 2023-03-07  发布在  SQL Server
关注(0)|答案(1)|浏览(137)

I used Prisma to introspect my existing SQL Server db. I have a Note table with a PK defined like this in the .sql table file:

[NOTE_ID] NUMERIC(8) NOT NULL IDENTITY (10000000, 1),

The Prisma introspection generated this in the schema.prisma file for this field:

NOTE_ID DECIMAL @id(map: "PK_NOTE") @db.Decimal(8, 0)

When I tried to create a new note with a function like this, it's expecting me to be passing in the NOTE_ID value (even though in my non-Prisma app where I just submit a vanilla INSERT SQL query it doesn't require it, and creates it while providing its own "next number" PK value).

prisma.note.create({
    data: {
      NOTE_TYPE: 'Note', // can be 'Note' or other note types, etc.
      NOTE_VALUE: 'blah',
    },
  });

Anyone know how to get Prisma to play nice with how SQL Server wants to do its own auto-increment identifier PK values? I'd like to be able to run the Prisma introspection and not have to go manually update the generated schema each time for all PK fields (I have quite a few tables).

Edit: some additional info that may help narrow the scope of the question.

The db is an existing one that I'm not able to modify schema of directly. I'm doing a proof-of-concept to see how Prisma would work, but can't go making changes to the db. I have to rely on the existing db behavior of doing an insert without providing the PK, allowing it to provide it internally. It seems like Prisma is geared towards returning the PK of the inserted record, and I'd want to preserve that behavior as well.

g6ll5ycj

g6ll5ycj1#

I don't really know sql server, but with prisma you can describe your default value, and you could rely on you Db to generate it.

NOTE_ID DECIMAL @id(map: "PK_NOTE") @db.Decimal(8, 0) @default(autoincrement())

or

NOTE_ID DECIMAL @id(map: "PK_NOTE") @db.Decimal(8, 0) @default(dbgenerated("<INSERT TRANSACT SQL HERE>"))

for example, with postgresql and a sequence

noteId Int @id @default(dbgenerated("nextval('my_sequence')"))

Once you modified your prisma.schema you should be able to sync with the db and good to go.

Nevertheless, the docs points at the fact that you might need to re-create your table if prisma considers that you are adding this autoincrement constraint.

相关问题