LoginSignup
0
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

CloudFlareにデプロイするためのRemixプロジェクトでフレッシュマイグレーション + seed実行の仕組みを作ってみる

Last updated at Posted at 2024-06-13

概要

Remix + Prisma + CloudFlareのD1という構成だとフレッシュマイグレーション + seed実行のようなコマンドは用意されていないため自前で用意してみる。

前提

    • CloudFlare上のD1データベース名は「todo-cloudflare-d1」とする。よってwrangler.tomlでdatabase_nameがtodo-cloudflare-d1と指定されている
  • 下記の内容が完了している

方法

  1. フレッシュマイグレーションの流れは「テーブル削除」 → 「マイグレーション実行」のためその流れを作成

  2. 下記を実行してseedsディレクトリ直下にdrop_tables.sqlを作成

    touch seeds/drop_tables.sql
    
  3. seeds/drop_tables.sqlを下記のように記載

    seeds/drop_tables.sql
    -- DropTable
    -- マイグレーション管理テーブルリセット
    DELETE FROM d1_migrations;
    -- NOTE: テーブルを追加したらこちらにも忘れず追記
    DROP TABLE IF EXISTS tasks;
    DROP TABLE IF EXISTS task_category_masters;
    DROP TABLE IF EXISTS users;
    
  4. 下記を実行してテーブルが削除されることを確認

    npx wrangler d1 execute todo-cloudflare-d1 --local --file ./seeds/drop_tables.sql
    
  5. テーブルが一部削除されていることを確認

  6. 下記を実行してマイグレーションが通ることを確認

    npm run migrate
    
  7. 下記を実行してseedを流しデータが入ることを確認

    npm run seed
    
  8. ここまでが無事通ったら実装は問題ない

一発でマイグレーションリセット(テーブル削除していちからマイグレーション実行)できるコマンドを用意

  1. 下記をpackage.jsonのscriptsに記載

    package.json
    {
      "scripts": {
        "local-migrate-fresh": "npx wrangler d1 execute todo-cloudflare-d1 --local --file ./seeds/drop_tables.sql"
      }
    }
    
  2. これで下記を実行することでマイグレーションフレッシュする事が可能

    npm run local-migrate-fresh
    
  3. 下記をpackage.jsonのscriptsに記載

    package.json
    {
      "scripts": {
        "local-migrate-reset": "npm run local-migrate-fresh && npm run local-migrate"
      }
    }
    
  4. これで下記を実行することでマイグレーションリセットをする事が可能

    npm run local-migrate-reset
    

更に便利になりそうなコマンドを追加

コマンドを入れ子実行するようにして便利なコマンドを作っておいた。

package.json
"scripts": {
  "build": "remix vite:build",
  "deploy": "npm run build && wrangler pages deploy",
  "dev": "remix vite:dev",
  "lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
  "start": "wrangler pages dev ./build/client",
  "typecheck": "tsc",
  "typegen": "wrangler types",
  "preview": "npm run build && wrangler pages dev",
  "cf-typegen": "wrangler types",
  "local-seed": "./execute_seeds.sh",
  "local-migrate": "npx wrangler d1 migrations apply todo-cloudflare-d1 --local",
  "local-migrate-fresh": "npx wrangler d1 execute todo-cloudflare-d1 --local --file ./seeds/drop_tables.sql",
  "local-migrate-reset": "npm run local-migrate-fresh && npm run local-migrate",
  "local-migrate-reset-and-seed": "npm run local-migrate-reset && npm run local-seed",
  "remote-migrate": "npx wrangler d1 migrations apply todo-cloudflare-d1 --remote"
},
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0