Prisma 模型:可以使用 autoincrement() 从 0 开始吗?

huangapple go评论128阅读模式
英文:

Prisma Models: can autoincrement() start at 0?

问题

有没有可能使用 @id @default(autoincrement()) 并使 id 从0开始自动增长,而不是从1开始?

与此相关:https://stackoverflow.com/questions/66415593/start-ids-at-an-arbitrary-number-in-prisma-data-model(该问题也未收到任何答案)

我想知道在特定情况下(特别是在postgresql中)是否可能。

Prisma 生成相应的 SQL :

CREATE TABLE "Message" (
    "id" SERIAL NOT NULL,
    "from" TEXT NOT NULL,
    "content" TEXT NOT NULL,
    "discussionId" INTEGER NOT NULL,

    CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
);

NOT NULL 是否是问题?移除它是否可以?

那个 Stack Overflow 的回答至少表明可能性:https://stackoverflow.com/a/32728273/10469162

如果可能,Prisma 为什么不暴露这个功能呢?

英文:

Is it possible to have @id @default(autoincrement()) with auto-incrementation starting the ids from 0 instead of 1 ?

In relation to : https://stackoverflow.com/questions/66415593/start-ids-at-an-arbitrary-number-in-prisma-data-model
(which did not receive any answer either)

I am interested to see if it is possible with postgresql in particular.

Prisma generates the corresponding SQL :

CREATE TABLE "Message" (
    "id" SERIAL NOT NULL,
    "from" TEXT NOT NULL,
    "content" TEXT NOT NULL,
    "discussionId" INTEGER NOT NULL,

    CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
);

Is the NOT NULL the issue ? Would it be ok to remove it ?

That SO answer seems to at least suggest that it would be possible : https://stackoverflow.com/a/32728273/10469162

And if it's possible, is there a reason for Prisma not to expose it ?

答案1

得分: 3

有两个可用选项。首选的是始终生成为身份标识。仅适用于版本10及以上。

create table message (
      id integer generated always as identity 
                 (minvalue 0  start with 0)
    , _from text not null
    , content text not null
    , discussionid integer not null
    , constraint message_pkey primary key (id)
);

另一个选项(适用于版本10之前的版本)是不将id列定义为serial,而是手动执行serial的操作。虽然serial在ddl中占据数据类型的位置,但它不是数据类型;实际上,它是以下操作的简写:

  1. 创建序列,
  2. 创建数据类型为integer的列,
  3. 将序列设置为列的默认值。

所以:

create sequence message_id_seq
                minvalue 0
                start with 0;
            
create table message (
    id integer default nextval('message_id_seq')
    , _from text not null
    , content text not null
    , discussionid integer not null
    , constraint message_pkey primary key (id)
);

参见demo。抱歉,我无法将其翻译成你的混淆语言(Prisma),因为我对它不够熟悉。

英文:

There are a couple options available. The first and preferred is generated always as identity. Available only in versions 10 and above.

create table message (
      id integer generated always as identity 
                 (minvalue 0  start with 0)
    , _from text not null
    , content text not null
    , discussionid integer not null
    , constraint message_pkey primary key (id)
);

The other (and required for versions prior to 10) is not define the id column as serial, but manually do what serial does. Although serial occupies the place of data type in the ddl it is not a data type; it is actually a short for:

  1. create a sequence,
  2. create column of data type integer,
  3. set the sequence as default for column. <br/>

So:

create sequence message_id_seq
                minvalue 0
                start with 0;
            
create table message (
    id integer default nextval(&#39;message_id_seq&#39;)
    , _from text not null
    , content text not null
    , discussionid integer not null
    , constraint message_pkey primary key (id)
    );

See demo. Sorry, but I am unable to translate into your obscurification language (Prisma) as I am not familiar enough with it.

答案2

得分: 1

这不可能直接从模式中实现,但你可以修改迁移文件以实现此目的。此示例使用了Postgres数据库。

假设我们必须从0开始任务ID。为此,在schema.prisma文件中添加模型

model Task {
  id        Int   @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String?
}

然后运行以下命令

npx prisma migrate dev --create-only

它将在prisma/migrations文件夹中添加迁移文件。然后打开migration.sql文件并添加以下代码

ALTER SEQUENCE "Task_id_seq" MINVALUE 0 START 0 RESTART 0;

然后运行以下命令以在数据库中应用更改

npx prisma migrate dev

然后你应该看到如下输出
Prisma 模型:可以使用 autoincrement() 从 0 开始吗?

从这里,你可以继续创建记录。例如

const res = await prisma.task.create({
  data: {
    title: "testing",
    updatedAt: new Date()
  }
 })

将结果记录到控制台,你应该看到ID从0开始

{
  id: 0,
  createdAt: 2023-03-09T02:35:53.587Z,
  updatedAt: 2023-03-09T02:35:53.532Z,
  title: 'testing'
}

这个响应是由GitHub上的ludralph制作的,并在此处以通知他的方式复制,目的是分享知识。
这是答案的原始链接:https://github.com/prisma/prisma/discussions/18246

英文:

It's not possible from the schema directly but you can modify the migration file to achieve this. This example uses a Postgres database.

Let's assume that we have to start the Task id from 0. To do that, Add the model in schema.prisma file

model Task {
  id        Int   @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String?
}

Then run the below command

 npx prisma  migrate dev --create-only

It will add the migration file in the prisma/migrations folder. Then open the migration.sql file and add the following code

ALTER SEQUENCE &quot;Task_id_seq&quot; MINVALUE 0 START 0 RESTART 0;

Then run the following command to apply in the database

 npx prisma  migrate dev

Then you should see the output like below
Prisma 模型:可以使用 autoincrement() 从 0 开始吗?
From here, you can then proceed to create records. For example

const res = await prisma.task.create({
  data: {
    title: &quot;testing&quot;,
    updatedAt: new Date()
  }
 })

Logging the result to the console, you should see the id starting at 0

{
  id: 0,
  createdAt: 2023-03-09T02:35:53.587Z,
  updatedAt: 2023-03-09T02:35:53.532Z,
  title: &#39;testing&#39;
}

This response was crafted by ludralph over at github and reproduced here with him being notified about it for the purpose of sharing knowledge.
Here is the original link of the answer: https://github.com/prisma/prisma/discussions/18246

huangapple
  • 本文由 发表于 2023年3月7日 23:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定