データデータベース
最初のクエリ
テーブルを作成し、データを保存してから取得するまでの基本的な流れを説明します。
データベースを追加する
runlot.json に "database": true を書いてデプロイします。デプロイが PostgreSQL データベースを作ります。
{ "database": true }runlot deployテーブルを作成する
migrations/0001_init.sql ファイルを作成します。
create table posts (
id bigserial primary key,
title text not null,
created_at timestamptz not null default now()
);マイグレーションを適用します。
runlot pg migrateワーカーからデータを使う
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/posts") {
const { title } = (await request.json()) as { title: string };
const rows = await env.db.exec(
"insert into posts (title) values ($1) returning id, title",
[title],
);
return Response.json(rows[0], { status: 201 });
}
const rows = await env.db.exec(
"select id, title, created_at from posts order by id desc limit 20",
);
return Response.json(rows);
},
};runlot deploy動作を確認する
curl -X POST https://my-app.me.runlot.app/posts \
-H 'content-type: application/json' \
-d '{"title":"hello"}'
curl https://my-app.me.runlot.app/postsCLI から直接確認することもできます。
runlot pg execute -c "select count(*) from posts"次のステップ
- SQLSTATE に応じてエラーを処理するには、tryExec を参照してください。
- node-postgres に近い API が必要な場合は、@runlot/pg を使用してください。
- ORM を使用する場合は、ORM を参照してください。