데이터데이터베이스
첫 쿼리
표 하나를 만들고, 넣고, 읽는 데까지.
켜기
runlot add pgrunlot.json 에 "database": true 가 적히고, 프로젝트에 PostgreSQL 한 벌이 붙습니다.
표 만들기
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"다음
- 오류를 코드로 분기하려면 tryExec
- 익숙한
pg모양이 좋으시면 @runlot/pg - ORM 을 쓰시려면 ORM