// === file: server/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
check,
index,
integer,
pgTable,
text,
timestamp,
unique,
uuid,
} from "drizzle-orm/pg-core";
// Better Auth owns identity; we only reference its `user` table by id.
import { user } from "./auth-schema";
export type OrderStatus = "pending" | "paid" | "shipped" | "cancelled";
/** Catalog product — the marketing/display unit. Money + stock live on the
* variant below, never here, so a product can have many priced SKUs. */
export const products = pgTable(
"products",
{
id: uuid("id").primaryKey().defaultRandom(),
slug: text("slug").notNull().unique(),
name: text("name").notNull(),
description: text("description"),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(t) => [index("idx_product_slug").on(t.slug)],
);
/** A buyable SKU under a product. Price (integer cents) and inventory live here
* because that's what a customer actually adds to a cart and pays for. */
export const productVariants = pgTable(
"product_variants",
{
id: uuid("id").primaryKey().defaultRandom(),
productId: uuid("product_id")
.notNull()
.references(() => products.id, { onDelete: "cascade" }),
sku: text("sku").notNull().unique(),
name: text("name").notNull(), // e.g. "Large / Black"
// Money as integer cents — no float money in the catalog.
priceCents: integer("price_cents").notNull().default(0),
inventoryQty: integer("inventory_qty").notNull().default(0),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(t) => [index("idx_variant_product").on(t.productId)],
);
/** One open cart per shopper. userId is nullable so guests can shop before they
* authenticate; on login the app reassigns the guest cart to user.id. */
export const carts = pgTable(
"carts",
{
id: uuid("id").primaryKey().defaultRandom(),
// Better Auth's user.id is text — match it, don't recast. Nullable: a guest
// cart has no user yet.
userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(t) => [index("idx_cart_user").on(t.userId)],
);
/** A variant + quantity in a cart. The composite unique keeps one row per
* variant per cart (the app bumps quantity instead of inserting duplicates). */
export const cartItems = pgTable(
"cart_items",
{
id: uuid("id").primaryKey().defaultRandom(),
cartId: uuid("cart_id")
.notNull()
.references(() => carts.id, { onDelete: "cascade" }),
variantId: uuid("variant_id")
.notNull()
.references(() => productVariants.id, { onDelete: "cascade" }),
quantity: integer("quantity").notNull().default(1),
},
(t) => [
unique("cart_items_cart_variant_unique").on(t.cartId, t.variantId),
index("idx_cart_item_cart").on(t.cartId),
],
);
/** A placed order. totalCents is the captured total at checkout; status walks
* the fulfilment states. userId is nullable to allow guest checkout. */
export const orders = pgTable(
"orders",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id").references(() => user.id, { onDelete: "set null" }),
status: text("status").$type<OrderStatus>().notNull().default("pending"),
totalCents: integer("total_cents").notNull().default(0),
// ponytail: opaque payment-provider id (Stripe/etc.) — no provider FK needed.
providerPaymentId: text("provider_payment_id"),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(t) => [
index("idx_order_user").on(t.userId),
index("idx_order_status").on(t.status),
check(
"orders_status_check",
sql`${t.status} in ('pending','paid','shipped','cancelled')`,
),
],
);
/** Order line item. Snapshots unitPriceCents (and the SKU string) at purchase
* time so re-pricing or deleting a variant never rewrites order history — the
* variant FK is set null on delete, the snapshot stays. */
export const orderItems = pgTable(
"order_items",
{
id: uuid("id").primaryKey().defaultRandom(),
orderId: uuid("order_id")
.notNull()
.references(() => orders.id, { onDelete: "cascade" }),
// Keep the line even if the catalog variant is later removed.
variantId: uuid("variant_id").references(() => productVariants.id, {
onDelete: "set null",
}),
// Frozen at checkout — the SKU and price as they were when bought.
sku: text("sku").notNull(),
unitPriceCents: integer("unit_price_cents").notNull(),
quantity: integer("quantity").notNull().default(1),
},
(t) => [
// Drives the "line items for this order" lookup.
index("idx_order_item_order").on(t.orderId),
],
);
export const productsRelations = relations(products, ({ many }) => ({
variants: many(productVariants),
}));
export const productVariantsRelations = relations(
productVariants,
({ one, many }) => ({
product: one(products, {
fields: [productVariants.productId],
references: [products.id],
}),
cartItems: many(cartItems),
orderItems: many(orderItems),
}),
);
export const cartsRelations = relations(carts, ({ one, many }) => ({
user: one(user, { fields: [carts.userId], references: [user.id] }),
items: many(cartItems),
}));
export const cartItemsRelations = relations(cartItems, ({ one }) => ({
cart: one(carts, { fields: [cartItems.cartId], references: [carts.id] }),
variant: one(productVariants, {
fields: [cartItems.variantId],
references: [productVariants.id],
}),
}));
export const ordersRelations = relations(orders, ({ one, many }) => ({
user: one(user, { fields: [orders.userId], references: [user.id] }),
items: many(orderItems),
}));
export const orderItemsRelations = relations(orderItems, ({ one }) => ({
order: one(orders, { fields: [orderItems.orderId], references: [orders.id] }),
variant: one(productVariants, {
fields: [orderItems.variantId],
references: [productVariants.id],
}),
}));