Задать вопрос
ShadowOfCasper
@ShadowOfCasper
Middle User Interface Web Developer

Как задать стандартную expire дату в postgresql при создании строки в таблице?

Здравствуйте.
У меня возникает проблема с созданием схемы для таблицы verification.
Хочу сделать так, чтоб при регистрации аккаунта в таблицу verification устанавливалась строка с колонкой expires_at с неделей от даты создания.
ОРМка создаёт такой вот запрос:
CREATE TABLE "verification" (
	"id" serial PRIMARY KEY NOT NULL,
	"user_id" text NOT NULL,
	"identifier" text NOT NULL,
	"value" boolean DEFAULT false,
	"expires_at" timestamp DEFAULT dateadd(day, 7, getdate()) NOT NULL,
	"created_at" timestamp DEFAULT now() NOT NULL,
	"updated_at" timestamp DEFAULT now() NOT NULL
);

А постгрес на него жалуется ошибкой
applying migrations...error: cannot use column reference in DEFAULT expression

Как правильно установить DEFAULT?
  • Вопрос задан
  • 39 просмотров
Подписаться 1 Простой 2 комментария
Пригласить эксперта
Ответы на вопрос 1
ShadowOfCasper
@ShadowOfCasper Автор вопроса
Middle User Interface Web Developer
Отработал такой вариант
CREATE TABLE "verification" (
	"id" text PRIMARY KEY NOT NULL,
	"user_id" text NOT NULL,
	"identifier" text NOT NULL,
	"value" boolean DEFAULT false,
	"expires_at" timestamp DEFAULT now() + INTERVAL '+ 7 days' NOT NULL,
	"created_at" timestamp DEFAULT now() NOT NULL,
	"updated_at" timestamp DEFAULT now() NOT NULL
);

Запрос в моём случае генерился ормкой drizzle
Исходник схемы:
import { createId } from "@paralleldrive/cuid2";
import { sql } from "drizzle-orm";
import { boolean, pgTable, text, timestamp } from "drizzle-orm/pg-core";
import { user } from "./user";

export const verification = pgTable("verification", {
  id: text()
    .$defaultFn(() => createId())
    .primaryKey(),
  userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
  identifier: text('identifier').notNull(),
  value: boolean('value').default(false),
  expiresAt: timestamp('expires_at')
    .default(
      sql`now() + INTERVAL '+ 7 days'`
    )
    .notNull(),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull()
});

Исходник ДТО (лишнее убрано):
//...
export const verificationDto = {
  //...
  createVerification: async (userId: string) => {
    const newVerification = await db
      .insert(table.verification)
      .values({
        userId,
        identifier: createId()
      })
      .returning()
    return newVerification[0]
  }
  //...
}

Исходник контроллера (лишнее убрано):
//...
export const auth = new Elysia({ name: 'auth' })
  //...
  .post("/signup", async ({ body, jwtAuth, error }) => {
    //...
    const newUser = await userDTO.createUser({
      role: body.role,
      email: body.email,
      password: await Bun.password.hash(body.password)
    });
    const token = await jwtAuth.sign({ id: newUser.id });
    const { password, ...user } = newUser
    await verificationDto.createVerification(user.id);
    //...
    return {
      token,
      user,
      //...
    }
  }, { body: registerBody })
//...

Результат:
67d4753bb71d5369542344.png
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы