runlot

最初のクエリ

テーブルを作成し、データを保存してから取得するまでの基本的な流れを説明します。

データベースを追加する

runlot.json"database": true を書いてデプロイします。デプロイが PostgreSQL データベースを作ります。

runlot.json
{ "database": true }
runlot deploy

テーブルを作成する

migrations/0001_init.sql ファイルを作成します。

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

ワーカーからデータを使う

src/index.ts
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/posts

CLI から直接確認することもできます。

runlot pg execute -c "select count(*) from posts"

次のステップ

  • SQLSTATE に応じてエラーを処理するには、tryExec を参照してください。
  • node-postgres に近い API が必要な場合は、@runlot/pg を使用してください。
  • ORM を使用する場合は、ORM を参照してください。

このページの目次