Documentation
Database
How Motoko Base connects to PostgreSQL through Drizzle ORM — schema, queries, migrations, and Supabase.
Motoko Base uses PostgreSQL as the database, Drizzle ORM for type-safe schemas and queries, and Supabase as the recommended hosted Postgres provider. The Next.js app talks to the database only on the server — never from the browser.
Architecture
Next.js (Server Components, Server Actions, Route Handlers)
↓
Drizzle ORM (src/lib/db/)
↓
postgres.js client (prepare: false, connection pool)
↓
PostgreSQL (Supabase or local Postgres)| Layer | Location | Role |
|---|---|---|
| Next.js | src/app/, src/features/ | Routes and features call queries/actions on the server |
| Drizzle | src/lib/db/ | Schema definitions, typed queries, migrations |
| postgres.js | src/lib/db/index.ts | Low-level Postgres driver with pooling |
| PostgreSQL | Supabase / local | Persistent storage |
There is no separate database service or ORM microservice. Import db from @/lib/db in server code and run queries directly.
Supabase is optional — any Postgres instance works as long as DATABASE_URL is set. Supabase is recommended because it provides managed Postgres, a transaction pooler for serverless, and a familiar dashboard.
Connection
The database client lives in src/lib/db/index.ts:
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
const client = postgres(process.env.DATABASE_URL!, {
prepare: false, // required for Supabase transaction pooler
max: 10,
idle_timeout: 20,
connect_timeout: 10,
});
export const db = drizzle({ client });Set DATABASE_URL in .env (server-only — never NEXT_PUBLIC_*).
| Use case | Connection URL | Notes |
|---|---|---|
| App runtime | Supabase transaction pooler (often port 6543) | Use for pnpm dev, production, and all Next.js queries |
| Migrations | Direct connection (often port 5432) | Use when pnpm db:migrate fails through the pooler |
The pooler does not support prepared statements — prepare: false is required. If DDL fails during migrate, temporarily point DATABASE_URL at the direct connection, run migrate, then switch back.
See src/lib/db/README.md for RLS, indexes, and monitoring notes.
Schema
Table definitions live in src/lib/db/schema/ — one file per domain area:
| File | Tables |
|---|---|
auth.ts | user, session, account, verification (Better Auth) |
links.ts | links |
files.ts | files |
user-preferences.ts | user_preferences |
All tables are re-exported from the barrel file src/lib/db/schema/schema.ts:
export * from "./auth";
export * from "./links";
export * from "./files";
export * from "./user-preferences";Drizzle Kit reads this barrel when generating migrations (drizzle.config.ts → schema: "./src/lib/db/schema/schema.ts").
Conventions
- Table names — plural snake_case in Postgres (
links,user_preferences) - Column names — snake_case in the database, camelCase in TypeScript (
userId→user_id) - Primary keys — text IDs generated in application code (not auto-increment serials)
- Ownership — user-scoped tables include
userIdreferencinguser.idwithonDelete: "cascade" - Indexes — index foreign keys (
user_id) and columns used inWHERE/ORDER BY
Example from src/lib/db/schema/links.ts:
export const links = pgTable(
"links",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
slug: text("slug").notNull(),
destinationUrl: text("destination_url").notNull(),
clicks: integer("clicks").default(0).notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => new Date())
.notNull(),
},
(table) => [
uniqueIndex("links_slug_uidx").on(table.slug),
index("links_userId_idx").on(table.userId),
],
);Infer row types from the schema:
type LinkRow = typeof links.$inferSelect;
type NewLink = typeof links.$inferInsert;Queries
Database reads and writes live in feature query files, not in route components. Each feature under src/features/<name>/ typically has:
queries.ts— database reads and writesactions.ts— Server Actions that validate with Zod, call queries, and revalidateschemas.ts— Zod input validation
Example pattern from src/features/links/queries.ts:
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { links } from "@/lib/db/schema/links";
export async function findOwnedLink(userId: string, id: string) {
const [row] = await db
.select()
.from(links)
.where(and(eq(links.id, id), eq(links.userId, userId)))
.limit(1);
return row ?? null;
}Rules of thumb:
- Server-only — import
dbonly in server components, server actions, and route handlers - Ownership — always filter mutations with
id + userId(deriveuserIdfrom session, never from client input alone) - Thin routes — pages fetch data via queries and pass results to feature components
// src/app/dashboard/links/page.tsx
const session = await getCachedSession();
const result = await listLinksForUser(session!.user!.id);
return <LinksPage initialLinks={result.items} />;Better Auth uses the same schema through the Drizzle adapter (src/lib/auth/auth.ts).
Migrations
Schema changes are version-controlled SQL files under drizzle/migrations/. Drizzle Kit compares your TypeScript schema to the database and generates migration files.
| Command | Purpose |
|---|---|
pnpm db:generate | Generate a new migration from schema changes |
pnpm db:migrate | Apply pending migrations to the database |
pnpm db:studio | Open Drizzle Studio to browse tables |
Workflow after changing a schema file:
pnpm db:generate # creates SQL in drizzle/migrations/
pnpm db:migrate # applies it to your databaseSee Migrations for when to use each command and troubleshooting.
Row Level Security (Supabase)
All public tables have RLS enabled with no policies for anon / authenticated, and those roles are revoked. This blocks Supabase Data API access while the Next.js app continues to work through the pooler role (which bypasses RLS).
Motoko Base uses Better Auth, not Supabase Auth — do not add auth.uid() policies unless you integrate Supabase Auth JWTs later.
When you add a new table, include it in the RLS migration pattern (see Adding a New Table).
Where do I change this?
| What | Where |
|---|---|
| Database client / pool settings | src/lib/db/index.ts |
| Table definitions | src/lib/db/schema/*.ts |
| Schema barrel export | src/lib/db/schema/schema.ts |
| Drizzle Kit config | drizzle.config.ts |
| Generated migrations | drizzle/migrations/ |
| Feature queries | src/features/<name>/queries.ts |
| Deep-dive notes (RLS, indexes) | src/lib/db/README.md |
Env var: DATABASE_URL — see Environment Variables.
Next steps
Migrations — db:generate, db:migrate, and db:studio in detail.
Adding a New Table — Step-by-step tutorial from schema to queries.