Next.js 14でTodoアプリを作る – 4.D1を新規作成
投稿日:2024年03月11日
更新日:2024年03月19日
データベースを作成
https://developers.cloudflare.com/d1/get-started/#3-create-a-database
まずはデータベースを作成します。
以下のコマンドを実行します。
データベース名はtodo-app-d1とします。
npx wrangler d1 create todo-app-d1ファイルwrangler.tomlを作成
https://developers.cloudflare.com/d1/get-started/#4-bind-your-worker-to-your-d1-database
ファイルwrangler.tomlを作成します。
ファイルwrangler.tomlにd1_databasesの設定を追加します。d1_databasesの設定はデータベースを作成したときに表示されたものをそのままコピペしてください。
[[d1_databases]]
binding = "DB"
database_name = "todo-app-d1"
database_id = "<unique-ID-for-your-database>"テーブルを作成
データベースtodo-app-d1にテーブルを作成します。
まずはファイルschema.sqlを作成します。
ファイルschema.sqlに以下のSQLを追加します。
-- テーブルの存在確認
DROP TABLE IF EXISTS todos;
-- テーブル作成
CREATE TABLE todos (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL
);
-- テストデータ挿入
INSERT INTO todos (title, content) VALUES
('タスク1', 'これはタスク1です'),
('タスク2', 'これはタスク2です'),
('タスク3', 'これはタスク3です');
次にファイルschema.sqlを使って、データベースtodo-app-d1にテーブルtodosを作成します。
今回はローカル環境にデータベースを作成します。
本番環境にはAPIの機能を追加した後に作成します。
以下のコマンドを実行します。
オプションでlocalを指定しています。
これがローカル環境で作成されます。
npx wrangler d1 execute todo-app-d1 --local --file=./schema.sqlテーブルtodosが作成されたかどう確認します。
以下のコマンドを実行します。
npx wrangler d1 execute todo-app-d1 --local --command='SELECT * FROM todos'