import { createId as cuid } from "@paralleldrive/cuid2"; import { relations, sql } from "drizzle-orm"; import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; export const users = sqliteTable("users", { id: text("id") .notNull() .primaryKey() .$defaultFn(() => cuid()), name: text("name").notNull(), username: text("username").notNull().unique(), email: text("email").notNull().unique(), dob: integer("dob", { mode: "timestamp" }).notNull(), image: text("image"), createdAt: integer("createdAt", { mode: "timestamp" }) .notNull() .default(sql`DATE('now')`), updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(), }); export const verification = sqliteTable( "verification", { id: text("id") .notNull() .primaryKey() .$defaultFn(() => cuid()), target: text("target").notNull(), type: text("type", { enum: ["onboarding", "reset-password"] }).notNull(), charSet: text("charSet").notNull(), secret: text("secret").notNull(), algorithm: text("algorithm").notNull(), digits: integer("digits").notNull(), period: integer("period").notNull(), createdAt: integer("createdAt", { mode: "timestamp" }) .notNull() .default(sql`DATE('now')`), expiresAt: integer("expiresAt", { mode: "timestamp" }).notNull(), }, (verification) => [uniqueIndex("verification_target_type_key").on(verification.target, verification.type)], ); export const password = sqliteTable("password", { hash: text("hash").notNull(), userId: text("userId") .notNull() .unique() .references(() => users.id, { onDelete: "cascade", onUpdate: "cascade" }), }); export const sessions = sqliteTable( "sessions", { id: text("id") .notNull() .primaryKey() .$defaultFn(() => cuid()), userId: text("userId") .notNull() .references(() => users.id, { onDelete: "cascade" }), createdAt: integer("createdAt", { mode: "timestamp" }) .notNull() .default(sql`DATE('now')`), updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(), expiresAt: integer("expiresAt", { mode: "timestamp" }).notNull(), }, (session) => [index("session_userId_idx").on(session.userId)], ); export const usersRelations = relations(users, ({ many, one }) => ({ password: one(password), sessions: many(sessions), })); export const passwordRelations = relations(password, ({ one }) => ({ user: one(users, { relationName: "PasswordToUser", fields: [password.userId], references: [users.id], }), })); export const SessionRelations = relations(sessions, ({ one }) => ({ user: one(users, { relationName: "SessionToUser", fields: [sessions.userId], references: [users.id], }), }));