Cloudflare で D1 の環境を構築

概要

Cloudflare で D1 の開発環境を構築したので備忘録。

環境

developers.cloudflare.com

npm install wrangler 

確認。

% npx wrangler dev

 ⛅️ wrangler 3.64.0 (update available 3.65.1)
-------------------------------------------------------

セットアップ

npm create cloudflare@latest -- d1-tutorial

データベースの作成

cd d1-tutorial
npx wrangler d1 create prod-d1-tutorial

wrang.tomlに下記を追記。

[[d1_databases]]
binding = "DB"
database_name = "prod-d1-tutorial"
database_id = "生成されたデータベースのID"

DDLの実行

schema.sqlに下記を追記。

DROP TABLE IF EXISTS Customers;
CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT);
INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name');

下記のコマンドを実行。

npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql

結果の確認

%npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT * FROM Customers"

🌀 Executing on local database prod-d1-tutorial (127f7041-9006-4d9c-a614-3ac70a312fdd) from .wrangler/state/v3/d1:
🌀 To execute on your remote database, add a --remote flag to your wrangler command.
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName         │ ContactName       │
├────────────┼─────────────────────┼───────────────────┤
│ 1          │ Alfreds Futterkiste │ Maria Anders      │
├────────────┼─────────────────────┼───────────────────┤
│ 4          │ Around the Horn     │ Thomas Hardy      │
├────────────┼─────────────────────┼───────────────────┤
│ 11         │ Bs Beverages        │ Victoria Ashworth │
├────────────┼─────────────────────┼───────────────────┤
│ 13         │ Bs Beverages        │ Random Name       │
└────────────┴─────────────────────┴───────────────────┘