mcpField
S
supabase

supabase

github.com/alinaqiデータ・データベース710644 回インストール2 週間前に更新
リポジトリ

supabase について

supabase は、Supabase プロジェクト向けの開発ガイドです。CLI の使い方やデータベースの運用、各サービスを扱い、ローカル開発とバージョン管理されたマイグレーション、CI/CD によるデプロイを重視します。

主な機能

  1. 01Supabase CLI の設定とローカル開発
  2. 02データベースマイグレーションとリモートデプロイ
  3. 03PostgreSQL と RLS ポリシー
  4. 04Edge Functions と Storage
  5. 05CI/CD と環境変数の管理

活用シーン

  1. 01ローカル Supabase 環境で開発
  2. 02マイグレーションによるスキーマ変更管理
  3. 03Edge Functions のデプロイと Storage ポリシー設定

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/alinaqi/maggy --skill supabase

インストール後、Claude Code で/supabaseを入力して読み込まれたか確認します。

詳細

Supabase コアスキル

すべての Supabase プロジェクトに共通するコアコンセプト、CLI ワークフロー、パターンです。

参照元: Supabase ドキュメント | Supabase CLI


コア原則

ローカルファーストで、マイグレーションをバージョン管理し、本番環境には直接変更を加えないでください。

Supabase CLI を使ってローカルで開発し、すべての変更をマイグレーションとして記録して、CI/CD を通じてデプロイします。


Supabase スタック

サービス用途
DatabasePostgreSQL と拡張機能
Authユーザー認証、OAuth プロバイダー
StorageRLS によるファイルストレージ
Edge Functionsサーバーレスの Deno 関数
RealtimeWebSocket サブスクリプション
VectorAI 埋め込み(pgvector)

CLI のセットアップ

インストールとログイン
# macOS
brew install supabase/tap/supabase

# npm (alternative)
npm install -g supabase

# Login
supabase login
プロジェクトの初期化
# In your project directory
supabase init

# Creates:
# supabase/
# ├── config.toml      # Local config
# ├── seed.sql         # Seed data
# └── migrations/      # SQL migrations
リモートとのリンク
# Get project ref from dashboard URL: https://supabase.com/dashboard/project/<ref>
supabase link --project-ref <project-id>

# Pull existing schema
supabase db pull
ローカルスタックの起動
supabase start

# Output:
# API URL: http://localhost:54321
# GraphQL URL: http://localhost:54321/graphql/v1
# DB URL: postgresql://postgres:postgres@localhost:54322/postgres
# Studio URL: http://localhost:54323
# Anon key: eyJ...
# Service role key: eyJ...

マイグレーションのワークフロー

オプション 1:ダッシュボードと差分(迅速なプロトタイピング)
# 1. Make changes in local Studio (localhost:54323)
# 2. Generate migration from diff
supabase db diff -f <migration_name>

# 3. Review generated SQL
cat supabase/migrations/*_<migration_name>.sql

# 4. Reset to test
supabase db reset
オプション 2:マイグレーションを直接記述(推奨)
# 1. Create empty migration
supabase migration new create_users_table

# 2. Edit the migration file
# supabase/migrations/<timestamp>_create_users_table.sql

# 3. Apply locally
supabase db reset
オプション 3:ORM マイグレーション(最良の開発者体験)

Drizzle(TypeScript)または SQLAlchemy(Python)を使用してください。フレームワーク固有のスキルを参照してください。

マイグレーションのデプロイ
# Push to remote (staging/production)
supabase db push

# Check migration status
supabase migration list

データベースのパターン

すべてのテーブルで RLS を有効化
-- Always enable RLS
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;

-- Default deny - must create policies
CREATE POLICY "Users can view own profile"
  ON public.profiles
  FOR SELECT
  USING (auth.uid() = id);
一般的な RLS ポリシー
-- Public read
CREATE POLICY "Public read access"
  ON public.posts FOR SELECT
  USING (true);

-- Authenticated users only
CREATE POLICY "Authenticated users can insert"
  ON public.posts FOR INSERT
  WITH CHECK (auth.role() = 'authenticated');

-- Owner access
CREATE POLICY "Users can update own records"
  ON public.posts FOR UPDATE
  USING (auth.uid() = user_id);

-- Admin access (using custom claim)
CREATE POLICY "Admins have full access"
  ON public.posts FOR ALL
  USING (auth.jwt() ->> 'role' = 'admin');
auth.users へのリンク
-- Profile table linked to auth
CREATE TABLE public.profiles (
  id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
  username TEXT UNIQUE NOT NULL,
  avatar_url TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Auto-create profile on signup
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO public.profiles (id, username)
  VALUES (NEW.id, NEW.email);
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

CREATE TRIGGER on_auth_user_created
  AFTER INSERT ON auth.users
  FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();

シードデータ

supabase/seed.sql
-- Runs on `supabase db reset`
-- Use ON CONFLICT for idempotency

INSERT INTO public.profiles (id, username, avatar_url)
VALUES
  ('d0e1f2a3-b4c5-6d7e-8f9a-0b1c2d3e4f5a', 'testuser', null),
  ('a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d', 'admin', null)
ON CONFLICT (id) DO NOTHING;

環境変数

必須の変数
# Public (safe for client-side)
SUPABASE_URL=https://xxxxx.supabase.co
SUPABASE_ANON_KEY=eyJ...

# Private (server-side only - NEVER expose)
SUPABASE_SERVICE_ROLE_KEY=eyJ...
DATABASE_URL=postgresql://postgres.[ref]:[password]@aws-0-region.pooler.supabase.com:6543/postgres
ローカル環境と本番環境
# .env.local (local development)
SUPABASE_URL=http://localhost:54321
SUPABASE_ANON_KEY=<from supabase start>
DATABASE_URL=postgresql://postgres:postgres@localhost:54322/postgres

# .env.production (remote)
SUPABASE_URL=https://xxxxx.supabase.co
SUPABASE_ANON_KEY=<from dashboard>
DATABASE_URL=<connection pooler URL>
コネクションプーリング
# Transaction mode (recommended for serverless)
# Add ?pgbouncer=true to URL
DATABASE_URL=postgresql://[email protected]:6543/postgres?pgbouncer=true

# Session mode (for migrations, long transactions)
DATABASE_URL=postgresql://[email protected]:5432/postgres

Edge Functions

関数の作成
supabase functions new hello-world
基本構造
// supabase/functions/hello-world/index.ts
import { serve } from 'https://deno.land/[email protected]/http/server.ts';

serve(async (req) => {
  const { name } = await req.json();

  return new Response(
    JSON.stringify({ message: `Hello ${name}!` }),
    { headers: { 'Content-Type': 'application/json' } }
  );
});
認証コンテキストを使用
import { serve } from 'https://deno.land/[email protected]/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';

serve(async (req) => {
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_ANON_KEY') ?? '',
    {
      global: {
        headers: { Authorization: req.headers.get('Authorization')! },
      },
    }
  );

  const { data: { user } } = await supabase.auth.getUser();

  if (!user) {
    return new Response('Unauthorized', { status: 401 });
  }

  return new Response(JSON.stringify({ user_id: user.id }));
});
デプロイ
# Serve locally
supabase functions serve

# Deploy single function
supabase functions deploy hello-world

# Deploy all
supabase functions deploy

Storage

バケットの作成(マイグレーション内)
INSERT INTO storage.buckets (id, name, public)
VALUES ('avatars', 'avatars', true);

-- Storage policies
CREATE POLICY "Avatar images are publicly accessible"
  ON storage.objects FOR SELECT
  USING (bucket_id = 'avatars');

CREATE POLICY "Users can upload own avatar"
  ON storage.objects FOR INSERT
  WITH CHECK (
    bucket_id = 'avatars' AND
    auth.uid()::text = (storage.foldername(name))[1]
  );

CLI クイックリファレンス

# Lifecycle
supabase start                   # Start local stack
supabase stop                    # Stop local stack
supabase status                  # Show status & credentials

# Database
supabase db reset                # Reset + migrations + seed
supabase db push                 # Push to remote
supabase db pull                 # Pull remote schema
supabase db diff -f <name>       # Generate migration from diff
supabase db lint                 # Check for issues

# Migrations
supabase migration new <name>    # Create migration
supabase migration list          # List migrations
supabase migration up            # Apply pending (remote)

# Functions
supabase functions new <name>    # Create function
supabase functions serve         # Local dev
supabase functions deploy        # Deploy all

# Types
supabase gen types typescript --local > types/database.ts

# Project
supabase link --project-ref <id> # Link to remote
supabase projects list           # List projects

CI/CD テンプレート

# .github/workflows/supabase.yml
name: Supabase CI/CD

on:
  push:
    branches: [main]
  pull_request:

env:
  SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
  SUPABASE_DB_PASSWORD: ${{ secrets.SUPABASE_DB_PASSWORD }}
  SUPABASE_PROJECT_ID: ${{ secrets.SUPABASE_PROJECT_ID }}

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: supabase/setup-cli@v1

      - name: Start Supabase
        run: supabase start

      - name: Run migrations
        run: supabase db reset

      - name: Lint database
        run: supabase db lint

  deploy:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: supabase/setup-cli@v1

      - name: Link project
        run: supabase link --project-ref $SUPABASE_PROJECT_ID

      - name: Push migrations
        run: supabase db push

      - name: Deploy functions
        run: supabase functions deploy

アンチパターン

  • 本番環境への直接変更 - 常にマイグレーションを使用してください
  • RLS の無効化 - ユーザーデータを含むすべてのテーブルで有効にしてください
  • クライアントでのサービスキーの使用 - サービスロールキーを決して公開しないでください
  • コネクションプーリングなし - サーバーレスではプーラーを使用してください
  • .env のコミット - .gitignore に追加してください
  • マイグレーションレビューの省略 - 生成された SQL を必ず確認してください
  • シードデータなし - 一貫したローカル開発のために seed.sql を使用してください

コメント