Documentation

Database

How Motoko Base connects to PostgreSQL through Drizzle ORM — schema, queries, migrations, and Supabase.

Open inChatGPT (opens in a new tab)Claude (opens in a new tab)Cursor (opens in a new tab)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)
LayerLocationRole
Next.jssrc/app/, src/features/Routes and features call queries/actions on the server
Drizzlesrc/lib/db/Schema definitions, typed queries, migrations
postgres.jssrc/lib/db/index.tsLow-level Postgres driver with pooling
PostgreSQLSupabase / localPersistent 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 caseConnection URLNotes
App runtimeSupabase transaction pooler (often port 6543)Use for pnpm dev, production, and all Next.js queries
MigrationsDirect 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:

FileTables
auth.tsuser, session, account, verification (Better Auth)
links.tslinks
files.tsfiles
user-preferences.tsuser_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 userId referencing user.id with onDelete: "cascade"
  • Indexes — index foreign keys (user_id) and columns used in WHERE / 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 writes
  • actions.ts — Server Actions that validate with Zod, call queries, and revalidate
  • schemas.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 db only in server components, server actions, and route handlers
  • Ownership — always filter mutations with id + userId (derive userId from 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.

CommandPurpose
pnpm db:generateGenerate a new migration from schema changes
pnpm db:migrateApply pending migrations to the database
pnpm db:studioOpen 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 database

See 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?

WhatWhere
Database client / pool settingssrc/lib/db/index.ts
Table definitionssrc/lib/db/schema/*.ts
Schema barrel exportsrc/lib/db/schema/schema.ts
Drizzle Kit configdrizzle.config.ts
Generated migrationsdrizzle/migrations/
Feature queriessrc/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.