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을 참고하세요.

이 페이지의 목차