Gopkg.in/pg.v4 insert problem

I am using “gopkg.in/pg.v4” package and have defined below struct

Postgres table structure (name text default null, amount integer default null)

type Example1 struct {
TableName struct{} sql:"example_table"
Name string sql:"name"
Amount int sql:"amount"
}

type Example2 struct {
TableName struct{} sql:"example_table"
Name string sql:"name"
}

Now when I create row using Example1 without passing any amount for a row then in postgres db it automatically fills amount as 0, but when I use Example2 - amount column remains NULL.

I want to use Example1 and fill amount as NULL if I don’t pass any value. I don’t want it to fill 0 for amount column automatically.

Checkout the sql.Null____ types in the database/sql package (e.g. sql.NullInt64).

type Example1 struct {
    TableName struct{}   `sql:"example_table"`
    Name sql.NullString  `sql:"name"`
    Amount sql.NullInt64 `sql:"amount"`
}

I saw this solution but when I assign a integer value in Amount it says cannot use type int as sql.NullInt64

You can’t just say:

e1 := Example1{Name: "test", Amount: 1}

I made Name and Amount’s types sql.NullString and sql.NullInt64, respectively. If you check the documentation of these types, you’ll see that they’re structs. Because they’re structs, you have to either assign structs to them:

e1 := Example1{
    Name: sql.NullString{String: "test", Valid: true},
    Amount: sql.NullInt64{Int64: 1, Valid: true},
}

Yeah Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.