jackc / pgtype

MIT License
318 stars 112 forks source link

Is it possible to omit undefined values? #188

Open lesovsky opened 2 years ago

lesovsky commented 2 years ago

I have struct with optional field. This optional field is not used sometimes and in such cases marshalling fails with error. Is it possible to omit such fields transparently?

type Person struct {
    Name       pgtype.Text `db:"name" json:"name"`
    Registered pgtype.Bool `db:"registered" json:"registered,omitempty"`
}

func TestExample(t *testing.T) {
    c, err := pgx.Connect(context.Background(), "host=127.0.0.1 user=postgres dbname=postgres")
    assert.NoError(t, err)

    var name pgtype.Text
    err = c.QueryRow(context.Background(), "SELECT 'vasya' AS name").Scan(&name)
    assert.NoError(t, err)

    p := Person{
        Name: name,
    }

    // Here we can define something to 'Registered' field, but it could be unfair or wrong accordingly to "buisiness" logic.

    b, err := json.Marshal(&p)
    assert.NoError(t, err)
    fmt.Println(string(b))
}

omitempty tag not working and test returns:

json: error calling MarshalJSON for type pgtype.Bool: cannot encode status undefined

I would like that could working like with native types:

type Person struct {
    Name       string `db:"name" json:"name"`
    Registered bool   `db:"registered" json:"registered,omitempty"`
}

func TestExample(t *testing.T) {
    c, err := pgx.Connect(context.Background(), "host=127.0.0.1 user=postgres dbname=postgres")
    assert.NoError(t, err)

    var name string
    err = c.QueryRow(context.Background(), "SELECT 'vasya' AS name").Scan(&name)
    assert.NoError(t, err)

    p := Person{
        Name: name,
    }

    b, err := json.Marshal(&p)
    assert.NoError(t, err)
    fmt.Println(string(b))
}

which returns normally with no error and prints {"name":"vasya"} with ommited optional field.

jackc commented 2 years ago

That seems reasonable, but I don't think it is possible. The MarshalJSON() method defined on the pgtype doesn't have access to the struct tags. And a quick look at the json package docs seems to indicate that omitempty has a hard-coded list of zero values.