sqlc 简单试用

以前简单介绍过sqlc的功能,以下是一个简单试用

环境准备

  • docker-compose

提供db支持

services:
  pgmq:
      image: tembo.docker.scarf.sh/tembo/pg17-pgmq:latest
      ports:
        - "5432:5432"
      environment:
      - POSTGRES_PASSWORD=postgres

项目代码

  • sqlc.yaml

定义schema 以及query sql 以及一些db 信息, 插件使用了ts 的

version: '2'
servers:
- engine: postgresql
  uri: "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable"
plugins:
- name: ts
  wasm:
    url: https://downloads.sqlc.dev/plugin/sqlc-gen-typescript_0.1.3.wasm
    sha256: 287df8f6cc06377d67ad5ba02c9e0f00c585509881434d15ea8bd9fc751a9368
sql:
- schema: "schema.sql"
  queries: "query.sql"
  engine: postgresql
  database:
    managed: true
    uri: postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable
  rules:
  - sqlc/db-prepare
  codegen:
  - out: src/authors
    plugin: ts
    options:
      runtime: node
      driver: postgres
  • schema.sql 主要定义table 的schema 信息,对于managed模式会基于此创建db 以及tables
CREATE TABLE authors (
  id   BIGSERIAL PRIMARY KEY,
  name text      NOT NULL,
  bio  text
);
  • query.sql

定义sql 操作,会基于此生成代码

-- name: GetAuthor :one
SELECT * FROM authors
WHERE id = $1 LIMIT 1;

-- name: ListAuthors :many
SELECT * FROM authors
ORDER BY name;

-- name: CreateAuthor :one
INSERT INTO authors (
  name, bio
) VALUES (
  $1, $2
)
RETURNING *;

-- name: UpdateAuthor :exec
UPDATE authors
  set name = $2,
  bio = $3
WHERE id = $1;

-- name: DeleteAuthor :exec
DELETE FROM authors
WHERE id = $1;

生成代码

  • 命令
sqlc generate   
  • 效果

  • 代码集成

基于typescript, 使用bun 运行

import postgres from "postgres"

import {createAuthor,listAuthors} from "./authors/query_sql"

let  sql = postgres("postgres://postgres:postgres@localhost:5432/sqlc_managed_c3dcc55a7b3e6d52?sslmode=disable");

(async () => {
    let inserted = await createAuthor(sql, {name: "Alice", bio: "Alice's bio"})
    console.log(inserted)
    let authors = await listAuthors(sql)
    console.log(authors)
})()

  • 运行效果

说明

以上只是简单试用,sqlc 还支持类型映射等功能,同时官方对于sql 生成代码的处理也提供了内部处理介绍,方便了解内部机制,完整示例代码我已经放github 上了

参考资料

https://www.npmjs.com/package/postgres

https://github.com/sqlc-dev/sqlc-gen-typescript

https://docs.sqlc.dev/en/stable/howto/select.html

https://github.com/inngest/inngest/tree/main/pkg/cqrs/base_cqrs/sqlc/postgres

https://docs.sqlc.dev/en/stable/tutorials/getting-started-postgresql.html

https://github.com/rongfengliang/sqlc-typescript-learning

posted on 2025-05-20 08:00  荣锋亮  阅读(38)  评论(0)    收藏  举报

导航