Home > Software engineering >  SQLC Override Bool Type PostgreSQL
SQLC Override Bool Type PostgreSQL

Time:12-29

I am using SQLC and my YAML config file contains the following type overrides for postgresql:

gen:
  go:
    emit_json_tags: true
    package: "hmdb"
    out: "hmdb"
    overrides:
    - db_type: "hstore"
      nullable: true
      go_type: "github.com/jackc/pgtype.Hstore"
    - db_type: "text"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "String"
    - db_type: "timestamptz"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "Time"

Everything here works, but if I add:

    - db_type: "bool"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "Bool"

I do not get the expected result. I have also tried boolean and bit to no avail, both with and without nullable.

I have an update query defined here:

-- name: SetUser :one
UPDATE users SET 
    username = coalesce(sqlc.narg(username), username),
    email = coalesce(sqlc.narg('email'), email),
    phone = coalesce(sqlc.narg('phone'), phone),
    password = coalesce(sqlc.narg('password'), password),
    mfatoken = coalesce(sqlc.narg('mfatoken'), mfatoken),
    active = coalesce(sqlc.narg('active'), active)
    WHERE id = $1 RETURNING *;

But the generated struct looks like:

type SetUserParams struct {
    ID       uuid.UUID    `json:"id"`
    Username null.String  `json:"username"`
    Email    null.String  `json:"email"`
    Phone    null.String  `json:"phone"`
    Password null.String  `json:"password"`
    MFAToken null.String  `json:"mfatoken"`
    Active   sql.NullBool `json:"active"`
}

I want to use null.Bool instead of sql.NullBool, is this possible?

CodePudding user response:

Create your schema.yaml like this:

CREATE TABLE users (
    ...
    active pg_catalog.bool
)

In sqlc.yaml the entry should look something like this:

   - db_type: "pg_catalog.bool"
     nullable: true
     go_type:
       import: "gopkg.in/guregu/null.v4"
       package: "null"
       type: "Bool"

Then after sqlc generate it would look like this:

type SetUserParams struct {
    ...
    Active   null.Bool   `json:"active"`
}

So it uses null.Bool instead of sql.NullBool.

  • Related