Created
June 14, 2016 20:05
-
-
Save wrunk/f5d4d5d648e41292f24be4c9b678edd8 to your computer and use it in GitHub Desktop.
Golang xorm jsonb struct field issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/go-xorm/xorm" | |
_ "github.com/lib/pq" | |
"math/rand" | |
"time" | |
) | |
const ( | |
DB_USER = "" | |
DB_NAME = "" | |
DB_PW = "" | |
DB_HOST = "127.0.0.1" | |
DB_SSLMODE = "disable" | |
) | |
type Address struct { | |
Street string `json:"street"` | |
City string `json:"city"` | |
} | |
// Using card with address like this doesnt seem to work with json b | |
type CardS struct { | |
Addr Address `xorm:"jsonb notnull 'addr'" json:"addr"` | |
Id string `xorm:"pk notnull 'id'" json:"id"` | |
IsDefault bool `xorm:"'is_default'" json:"isDefault"` | |
Nickname string `xorm:"text notnull 'nickname'" json:"nickname"` | |
NumberLast4 string `xorm:"text notnull 'number_last_4'" json:"numberLast4"` | |
} | |
// Works fine with jsonb... | |
type CardM struct { | |
Addr map[string]interface{} `xorm:"jsonb notnull 'addr'" json:"addr"` | |
Id string `xorm:"pk notnull 'id'" json:"id"` | |
Nickname string `xorm:"text notnull 'nickname'" json:"nickname"` | |
NumberLast4 string `xorm:"text notnull 'number_last_4'" json:"numberLast4"` | |
} | |
func init() { | |
rand.Seed(time.Now().UTC().UnixNano()) | |
} | |
func main() { | |
xormEngine, err := xorm.NewEngine( | |
"postgres", | |
fmt.Sprintf("user=%v dbname=%v sslmode=%v password=%v host=%v", DB_USER, DB_NAME, DB_SSLMODE, DB_PW, DB_HOST)) | |
if err != nil { | |
panic(err) | |
} | |
cardS := &CardS{} | |
cardM := &CardM{} | |
err = xormEngine.Sync2(cardS, cardM) | |
if err != nil { | |
panic(err) | |
} | |
cardM.Addr = map[string]interface{}{"street": "1778 Main st", "city": "Los Angeles"} | |
cardM.Id = fmt.Sprintf("something%d", rand.Intn(100000000)) | |
cardM.Nickname = "test" | |
cardM.NumberLast4 = "1111" | |
// Using the jsonb field as struct will succeed... | |
affected, err := xormEngine.InsertOne(cardM) | |
if affected != 1 || err != nil { | |
panic(fmt.Sprintf("Failed to insert cardM, got (%d) row affected and/or error (%s)", affected, err)) | |
} else { | |
fmt.Println("****** Success, inserted (%d) rows", affected) | |
} | |
// This will fail... "no primary key for col addr" | |
cardS.Addr = Address{"1778 Main st", "Los Angeles"} | |
cardS.Id = fmt.Sprintf("something%d", rand.Intn(100000000)) | |
cardS.Nickname = "test" | |
cardS.NumberLast4 = "1111" | |
affected, err = xormEngine.InsertOne(cardS) | |
if affected != 1 || err != nil { | |
panic(fmt.Sprintf("Failed to insert cardS, got (%d) row affected and/or error (%s)", affected, err)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment