我有一个具有此架构的 BigQuery 表:
name STRING NULLABLE
age INTEGER NULLABLE
amount INTEGER NULLABLE
还有这两行:
1 Batgirl 23 123
2 Batman 22 null
我想做的是在这张表上从 Go 中进行选择,它工作得很好:
ctx := context.Background()
client, err := bigquery.NewClient(ctx, projectID)
q := client.Query("SELECT * FROM test.user_test LIMIT 1000")
it, err := q.Read(ctx)
if err != nil {
log.Fatal(err)
}
for {
var values []bigquery.Value
err := it.Next(&values)
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(values)
}
上面的代码就像一个魅力,它获得了选择并像这样打印两行:
[Batman 22 <nil>]
[Batgirl 23 123]
bat 侠显示为零值。当我尝试使用以下代码将这些行存储在结构中时,问题就来了:
type test struct {
Name string
Age int
Amount int `nullable`
}
q := client.Query("SELECT * FROM test.test_user LIMIT 1000")
if err != nil {
log.Fatal(err)
}
it, err := q.Read(ctx)
if err != nil {
log.Fatal(err)
}
for {
var c test
err := it.Next(&c)
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(c)
}
上面的代码迭代了结果查询,并将这两个值存储在一个我可以稍后操作的结构中。当没有任何空列时它工作正常(现在不是我的情况,因为我在 bat 侠上有一个空数量),所以我得到下一个错误:
bigquery: NULL values cannot be read into structs
我试图解决这个问题的方法是像这样使结构字段可以为空:
type test struct {
Name string
Age int
Amount int `bigquery:",nullable"`
}
但这基本上什么都不做。我开始学习 Go,但我真的不明白为什么我不能在结构中使用 nil 值或如何解决这个问题,所以这是我的两个问题:
如何存储具有空值的行结果?
为什么 google 决定不能在结构字段上设置 nil 值?
最佳答案
您可以使用您可以看到的任何 bigquery.Null 类型 in this link :
STRING NullString
BOOL NullBool
INTEGER NullInt64
FLOAT NullFloat64
TIMESTAMP NullTimestamp
DATE NullDate
TIME NullTime
DATETIME NullDateTime
在你的情况下,你将不得不改变你的线路
Amount int `nullable`
到:
Amount bigquery.NullInt64
在same link它指出:
It is an error to attempt to read a BigQuery NULL value into a struct field, unless the field is of type []byte or is one of the special Null types: NullInt64, NullFloat64, NullBool, NullString, NullTimestamp, NullDate, NullTime or NullDateTime.
关于go - 将带有 null 的 bigquery 行映射到结构后出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51040470/