Documentación

Añadir una tabla nueva

Tutorial paso a paso — crea un esquema Drizzle, expórtalo, genera una migración, aplícala y escribe consultas en Motoko Base.

Abrir enChatGPT (se abre en una pestaña nueva)Claude (se abre en una pestaña nueva)Cursor (se abre en una pestaña nueva)Tutorial paso a paso — crea un esquema Drizzle, expórtalo, genera una migración, aplícala y escribe consultas en Motoko Base.

Este recorrido añade una tabla notes — un recurso simple propiedad del usuario, similar a Link Manager. Adapta los mismos pasos a cualquier feature nueva.

Objetivo: cada usuario puede guardar notas con título y cuerpo. Solo el propietario puede leer o mutar sus filas.

Overview

1. Create schema     →  src/lib/db/schema/notes.ts
2. Export schema     →  src/lib/db/schema/schema.ts
3. Generate migration →  pnpm db:generate
4. Apply migration   →  pnpm db:migrate
5. Create queries    →  src/features/notes/queries.ts

Step 1 — Create schema

Crea src/lib/db/schema/notes.ts:

import { index, pgTable, text, timestamp } from "drizzle-orm/pg-core";

import { user } from "./auth";

export const notes = pgTable(
  "notes",
  {
    id: text("id").primaryKey(),
    userId: text("user_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    title: text("title").notNull(),
    body: text("body").notNull().default(""),
    createdAt: timestamp("created_at").defaultNow().notNull(),
    updatedAt: timestamp("updated_at")
      .defaultNow()
      .$onUpdate(() => new Date())
      .notNull(),
  },
  (table) => [index("notes_userId_idx").on(table.userId)],
);

Puntos clave:

  • userId — columna de ownership con cascade delete (al borrar un usuario, sus notas también se borran)
  • Text primary key — genera IDs en el código de la aplicación (p. ej. crypto.randomUUID()), igual que las tablas existentes
  • Index on user_id — necesario para consultas list-by-owner

Step 2 — Export schema

Añade el export a src/lib/db/schema/schema.ts:

export * from "./auth";
export * from "./links";
export * from "./files";
export * from "./user-preferences";
export * from "./notes";   // add this line

Drizzle Kit solo ve las tablas exportadas desde este barrel.


Step 3 — Generate migration

Asegúrate de que DATABASE_URL esté definida en .env, luego ejecuta:

pnpm db:generate

Drizzle Kit crea una carpeta nueva bajo drizzle/migrations/ con SQL similar a:

CREATE TABLE "notes" (
  "id" text PRIMARY KEY NOT NULL,
  "user_id" text NOT NULL,
  "title" text NOT NULL,
  "body" text DEFAULT '' NOT NULL,
  "created_at" timestamp DEFAULT now() NOT NULL,
  "updated_at" timestamp DEFAULT now() NOT NULL
);

ALTER TABLE "notes" ADD CONSTRAINT "notes_user_id_user_id_fk"
  FOREIGN KEY ("user_id") REFERENCES "public"."user"("id")
  ON DELETE cascade ON UPDATE no action;

CREATE INDEX "notes_userId_idx" ON "notes" USING btree ("user_id");

Revisa el SQL generado antes de aplicar. Si algo parece incorrecto, corrige el archivo de esquema, borra la carpeta de migración no aplicada y vuelve a ejecutar db:generate.

Motoko Base habilita RLS en todas las tablas públicas. Tras generar la migración, añade sentencias RLS al mismo migration.sql (o a una migración de seguimiento):

ALTER TABLE "notes" ENABLE ROW LEVEL SECURITY;
REVOKE ALL ON TABLE "notes" FROM anon, authenticated;

Esto coincide con el patrón en drizzle/migrations/20260822044000_enable_rls/migration.sql. La app Next.js se conecta vía el rol del pooler y omite RLS; los roles de API Supabase anon/authenticated no pueden leer filas.


Step 4 — Apply migration

pnpm db:migrate

Verifica con Drizzle Studio:

pnpm db:studio

Abre la tabla notes y confirma que las columnas coinciden con tu esquema.

Si migrate falla a través del pooler de Supabase, cambia temporalmente DATABASE_URL a la conexión direct (puerto 5432), ejecuta migrate y vuelve. Consulta Migrations.


Step 5 — Create queries

Crea las consultas de feature en src/features/notes/queries.ts. Las lecturas y escrituras permanecen en la carpeta de feature — no en componentes de ruta.

import { and, desc, eq } from "drizzle-orm";

import { db } from "@/lib/db";
import { notes } from "@/lib/db/schema/notes";

export type NoteItem = {
  id: string;
  title: string;
  body: string;
  createdAt: Date;
};

function toNoteItem(row: typeof notes.$inferSelect): NoteItem {
  return {
    id: row.id,
    title: row.title,
    body: row.body,
    createdAt: row.createdAt,
  };
}

export async function listNotesForUser(userId: string): Promise<NoteItem[]> {
  const rows = await db
    .select()
    .from(notes)
    .where(eq(notes.userId, userId))
    .orderBy(desc(notes.createdAt));

  return rows.map(toNoteItem);
}

export async function findOwnedNote(userId: string, id: string) {
  const [row] = await db
    .select()
    .from(notes)
    .where(and(eq(notes.id, id), eq(notes.userId, userId)))
    .limit(1);

  return row ?? null;
}

export async function insertNote(input: {
  id: string;
  userId: string;
  title: string;
  body: string;
}) {
  const [row] = await db
    .insert(notes)
    .values({
      id: input.id,
      userId: input.userId,
      title: input.title,
      body: input.body,
    })
    .returning();

  return row;
}

export async function deleteOwnedNote(userId: string, id: string) {
  const [row] = await db
    .delete(notes)
    .where(and(eq(notes.id, id), eq(notes.userId, userId)))
    .returning({ id: notes.id });

  return row ?? null;
}

Wire it into the app

Sigue el mismo patrón que Link Manager:

  1. Zod schemas — src/features/notes/schemas.ts para validar la entrada de las actions
  2. Server Actions — src/features/notes/actions.ts con "use server", comprobación de sesión, parse Zod, llamadas a queries
  3. UI — src/features/notes/components/notes-page.tsx
  4. Route — src/app/dashboard/notes/page.tsx obtiene datos vía queries y renderiza el componente
  5. Navigation — añade un ítem en src/features/dashboard/config/nav.ts

Deriva siempre userId de la sesión — nunca confíes en IDs de usuario enviados por el cliente:

const session = await getCachedSession();
if (!session?.user?.id) {
  return { ok: false, error: "You must be signed in." };
}
const userId = session.user.id;

Checklist

  • Schema file in src/lib/db/schema/
  • Exported from schema.ts
  • pnpm db:generate — migration SQL reviewed
  • RLS + REVOKE added for Supabase (if using Supabase)
  • pnpm db:migrate — applied successfully
  • Queries in src/features/<name>/queries.ts
  • Ownership filter on every mutation (id + userId)
  • Migration folder committed to git

Next steps

Migrations — Referencia de comandos y resolución de problemas.

Database — Arquitectura, convenciones y dónde viven los archivos.

Project structure — Diseño de carpetas de feature y reglas prácticas.