Documentação

Adicionar uma nova tabela

Tutorial passo a passo — crie um schema Drizzle, exporte, gere uma migration, aplique e escreva queries no Motoko Base.

Abrir emChatGPT (abre em uma nova aba)Claude (abre em uma nova aba)Cursor (abre em uma nova aba)Tutorial passo a passo — crie um schema Drizzle, exporte, gere uma migration, aplique e escreva queries no Motoko Base.

Este walkthrough adiciona uma tabela notes — um recurso simples de propriedade do usuário, semelhante ao Link Manager. Adapte os mesmos passos para qualquer feature nova.

Objetivo: cada usuário pode guardar notas com título e corpo. Somente o dono pode ler ou mutar suas linhas.

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

Crie 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)],
);

Pontos-chave:

  • userId — coluna de ownership com cascade delete (quando um usuário é excluído, as notas dele também vão embora)
  • Text primary key — gere IDs no código da aplicação (p. ex. crypto.randomUUID()), alinhado às tabelas existentes
  • Index on user_id — necessário para queries list-by-owner

Step 2 — Export schema

Adicione o export em 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

O Drizzle Kit só enxerga tabelas exportadas deste barrel.


Step 3 — Generate migration

Garanta que DATABASE_URL esteja definida em .env e então rode:

pnpm db:generate

O Drizzle Kit cria uma nova pasta em drizzle/migrations/ com SQL semelhante 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");

Revise o SQL gerado antes de aplicar. Se algo parecer errado, corrija o arquivo de schema, delete a pasta de migration não aplicada e rode db:generate de novo.

O Motoko Base habilita RLS em todas as tabelas públicas. Após gerar a migration, adicione statements RLS ao mesmo migration.sql (ou a uma migration de acompanhamento):

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

Isso segue o padrão em drizzle/migrations/20260822044000_enable_rls/migration.sql. O app Next.js conecta pelo role do pooler e ignora RLS; os roles de API Supabase anon/authenticated não conseguem ler linhas.


Step 4 — Apply migration

pnpm db:migrate

Verifique com o Drizzle Studio:

pnpm db:studio

Abra a tabela notes e confirme que as colunas batem com o schema.

Se o migrate falhar pelo pooler do Supabase, troque temporariamente DATABASE_URL para a conexão direct (porta 5432), rode o migrate e volte. Veja Migrations.


Step 5 — Create queries

Crie as queries da feature em src/features/notes/queries.ts. Leituras e escritas ficam na pasta da feature — não em componentes de rota.

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

Siga o mesmo padrão do Link Manager:

  1. Zod schemas — src/features/notes/schemas.ts para validação de entrada das actions
  2. Server Actions — src/features/notes/actions.ts com "use server", checagem de sessão, parse Zod, chamadas a queries
  3. UI — src/features/notes/components/notes-page.tsx
  4. Route — src/app/dashboard/notes/page.tsx busca via queries e renderiza o componente
  5. Navigation — adicione um item em src/features/dashboard/config/nav.ts

Sempre derive userId da sessão — nunca confie em IDs de usuário enviados pelo 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 — Referência de comandos e resolução de problemas.

Database — Arquitetura, convenções e onde os arquivos ficam.

Project structure — Layout de pastas de feature e regras práticas.