如何在sqlc golang中将pgtype.text更改为string?

hfwmuf9z  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(93)

我有给定查询生成的代码

INSERT INTO "users" (
    username,
    name,
    surname,
    email,
    hashed_password,
    role
) VALUES (
    $1, $2, $3, $4, $5, $6
) RETURNING "id", "username";

看起来像这样

type CreateUserParams struct {
    Username       string      `json:"username"`
    Name           pgtype.Text `json:"name"`
    Surname        pgtype.Text `json:"surname"`
    Email          string      `json:"email"`
    HashedPassword string      `json:"hashed_password"`
    Role           UserRole    `json:"role"`
}

如何将Name pgtype.Text转换为golang字符串?目前我的sqlc.yaml文件看起来像以下

version: "2"
sql:
  - schema: "db/migrations/users"
    queries: "db/queries"
    engine: "postgresql"
    gen:
      go:
        package: "internal"
        out: "db/internal/"
        sql_package: "pgx/v5"
        output_files_suffix: "_gen"
        emit_json_tags: true
        emit_interface: true
        emit_empty_slices: true
        overrides:
          - db_type: "timestamptz"
            go_type: "time.Time"
          - db_type: "uuid"
            go_type: "github.com/google/uuid.UUID"
          - db_type: "text"
            go_type:
              type: "string"

我的模式如下所示

CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    username VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100),
    surname VARCHAR(100),
    email VARCHAR(150) UNIQUE NOT NULL CHECK (email ~* '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$'),
    hashed_password VARCHAR(1024) NOT NULL,
    role user_role NOT NULL DEFAULT 'USER',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

这里,namesurname可以是基于模式的NULL。现在正如@kozmo指出的,因为这些列可以为空,所以它生成的是pgtype.Text而不是string。但我想在每一个场景中创建字符串。我怎么能这么做呢?

ctehm74n

ctehm74n1#

我猜,您的“用户”模式文件看起来像

create table users
(
    id              uuid,
    username        text,
    name            text,
);

a sqlc generate

type User struct {
    ID       pgtype.UUID `json:"id"`
    Username pgtype.Text `json:"username"`
    Name     pgtype.Text `json:"name"`
}

如果添加约束not null

create table users
(
    id              uuid,
    username        text,
    name            text not null --- 👈🏻
);

生成的代码看起来像

type User struct {
    ID       pgtype.UUID `json:"id"`
    Username pgtype.Text `json:"username"`
    Name     string      `json:"name"`
}

相关问题