我正在学习使用 sqlc(与 pgx)
我的sqlc.yaml
version: "2"
sql:
- engine: "postgresql"
queries: "query.sql"
schema: "schema.sql"
gen:
go:
package: "database"
out: "../../pkg/database"
sql_package: "pgx/v5"
架构.sql
CREATE TABLE users (
ulid varchar(26) PRIMARY KEY,
email varchar(50) NOT NULL,
password varchar NOT NULL,
name varchar(50) NOT NULL,
superuser boolean DEFAULT false,
UNIQUE (email)
);
查询.sql
-- name: CreateUser :one
INSERT INTO users (email, password, name, ulid, superuser) VALUES ($1, $2, $3, $4, $5) RETURNING *;
生成的go代码
type CreateUserParams struct {
Email string
Password string
Name string
Ulid string
Superuser pgtype.Bool
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) {
row := q.db.QueryRow(ctx, createUser,
arg.Email,
arg.Password,
arg.Name,
arg.Ulid,
arg.Superuser,
)
var i User
err := row.Scan(
&i.Ulid,
&i.Email,
&i.Password,
&i.Name,
&i.Superuser,
)
return i, err
}
我尝试实施
func CreateUser(ctx context.Context, email, password, name string, superuser bool) (database.User, error) {
conn, err := MakeDbConn(ctx)
if err != nil {
return database.User{}, err
}
defer conn.Close(ctx)
queries := database.New(conn)
hashedPassword, err := utils.HashPassword(password)
if err != nil {
return database.User{}, err
}
user, err := queries.CreateUser(ctx, database.CreateUserParams{
Email: email,
Password: hashedPassword,
Name: name,
Ulid: utils.MakeUlid(),
Superuser: superuser,
})
if err != nil {
return database.User{}, err
}
fmt.Println("new user: ", user)
return user, nil
}
但是 vscode 说:“不能使用超级用户(bool 类型的变量)作为结构文字中的 pgtype.Bool 值”对于 CreateUserParams.Superuser
请告诉我如何在 sqlc 中正确使用 bool
编辑: 从@gavin和@brits得到帮助,我将代码更改为
user, err := queries.CreateUser(ctx, database.CreateUserParams{
Email: email,
Password: hashedPassword,
Name: name,
Ulid: utils.MakeUlid(),
Superuser: pgtype.Bool{Bool: superuser, Valid: true},
})
解决了
一个更方便但不太安全的替代解决方案是在
pgtype.Bool
yaml 配置中将 bool
映射到原生 sqlc
(相关文档):
version: "2"
sql:
- engine: postgresql
queries: ...
schema: ...
gen:
go:
package: sqlc
out: ../pkg/db/sqlc
sql_package: pgx/v5
overrides:
- db_type: bool
go_type:
import: ""
type: bool
- db_type: bool
go_type:
import: ""
type: bool
pointer: true
nullable: true
请注意,这里我覆盖了可为空和不可为空的
bool
。在您的情况下, superuser
字段可以为空,因此它将在 go 中表示为 *bool
。
有关使用
pgtype
类型并在 此 StackOverflow 线程中覆盖它们的更多讨论。