sqlc将 SQL 编译为类型安全的 Go
sqlc 从 SQL 生成完全类型安全的成语 Go 代码。下面是它的工作原理:
- 你使用 SQL 编写查询。
- 你运行 sqlc 以生成具有这些查询的类型安全接口的代码。
- 你编写调用生成代码的应用程序代码。
sqlc 可以使用这个 SQL:
CREATE TABLE authors ( id BIGSERIAL PRIMARY KEY, name text NOT NULL, bio text ); -- name: GetAuthor :one SELECT * FROM authors WHERE id = $1 LIMIT 1;
并自动生成以下 Go 代码:
package db
import (
"context"
"database/sql"
)
type Author struct {
ID int64
Name string
Bio sql.NullString
}
const getAuthor = `-- name: GetAuthor :one
SELECT id, name, bio FROM authors
WHERE id = $1 LIMIT 1
`
type Queries struct {
db *sql.DB
}
func (q *Queries) GetAuthor(ctx context.Context, id int64) (Author, error) {
row := q.db.QueryRowContext(ctx, getAuthor, id)
var i Author
err := row.Scan(&i.ID, &i.Name, &i.Bio)
return i, err
}
sqlc 的灵感来自 PugSQL 和 HugSQL。
评论
