// src/server/db/schema.ts
import { relations, sql } from "drizzle-orm";
import {
boolean,
index,
integer,
pgEnum,
pgTableCreator,
primaryKey,
serial,
text,
timestamp,
varchar,
} from "drizzle-orm/pg-core";
const createTable = pgTableCreator((name) => `${env.DB_PREFIX}_${name}`);
export const users = createTable("user", {
id: varchar("id", { length: 255 })
.notNull()
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
name: varchar("name", { length: 255 }),
email: varchar("email", { length: 255 }).notNull(),
emailVerified: timestamp("email_verified", {
mode: "date",
withTimezone: true,
}).default(sql`CURRENT_TIMESTAMP`),
image: varchar("image", { length: 255 }),
password: varchar("password", { length: 255 }),
role: varchar("role", { length: 50 }).default("user").notNull(),
createdAt: timestamp("created_at", { withTimezone: true })
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate(
() => new Date(),
),
});
export const accounts = createTable(
"account",
{
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
type: text("type").notNull(),
provider: text("provider").notNull(),
providerAccountId: text("providerAccountId").notNull(),
refresh_token: text("refresh_token"),
access_token: text("access_token"),
expires_at: integer("expires_at"),
token_type: text("token_type"),
scope: text("scope"),
id_token: text("id_token"),
session_state: text("session_state"),
},
(account) => ({
compoundKey: primaryKey({
columns: [account.provider, account.providerAccountId],
}),
userIdIdx: index("account_user_id_idx").on(account.userId),
}),
);
export const sessions = createTable("session", {
sessionToken: text("sessionToken").primaryKey(),
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
expires: timestamp("expires", { mode: "date" }).notNull(),
});
export const posts = createTable(
"post",
{
id: serial("id").primaryKey(),
name: varchar("name", { length: 256 }),
createdById: varchar("created_by", { length: 255 })
.notNull()
.references(() => users.id),
createdAt: timestamp("created_at", { withTimezone: true })
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate(
() => new Date(),
),
},
(example) => ({
createdByIdIdx: index("created_by_idx").on(example.createdById),
nameIndex: index("name_idx").on(example.name),
}),
);