登录
首页 >  Golang >  Go问答

使用 BigQuery 存储写入 API 时 golang 中的 BigQuery 可空类型

来源:stackoverflow

时间:2024-02-14 22:57:44 466浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《使用 BigQuery 存储写入 API 时 golang 中的 BigQuery 可空类型》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

按照 golang 中的以下示例,我将从旧式流 api 切换到存储写入 api: https://github.com/alexflint/bigquery-storage-api-example

在旧代码中,我使用 bigquery 的 null 类型来指示字段可以为 null:

type person struct {
    name bigquery.nullstring `bigquery:"name"`
    age  bigquery.nullint64  `bigquery:"age"`
}

var persons = []person{
    {
        name: tobigquerynullablestring(""), // this will be null in bigquery
        age:  tobigquerynullableint64("20"),
    },
    {
        name: tobigquerynullablestring("david"),
        age:  tobigquerynullableint64("60"),
    },
}

func main() {
    ctx := context.background()

    bigqueryclient, _ := bigquery.newclient(ctx, "project-id")
    
    inserter := bigqueryclient.dataset("dataset-id").table("table-id").inserter()
    err := inserter.put(ctx, persons)
    if err != nil {
        log.fatal(err)
    }
}

func tobigquerynullablestring(x string) bigquery.nullstring {
    if x == "" {
        return bigquery.nullstring{valid: false}
    }
    return bigquery.nullstring{stringval: x, valid: true}
}
func tobigquerynullableint64(x string) bigquery.nullint64 {
    if x == "" {
        return bigquery.nullint64{valid: false}
    }
    if s, err := strconv.parseint(x, 10, 64); err == nil {
        return bigquery.nullint64{int64: s, valid: true}
    }
    return bigquery.nullint64{valid: false}
}

切换到新 api 后:

var persons = []*personpb.row{
    {
        name: "",
        age: 20,
    },
    {
        name: "david",
        age: 60,
    },
}
func main() {
    ctx := context.background()

    client, _ := storage.newbigquerywriteclient(ctx)
    defer client.close()

    stream, err := client.appendrows(ctx)
    if err != nil {
        log.fatal("appendrows: ", err)
    }

    var row personpb.row
    descriptor, err := adapt.normalizedescriptor(row.protoreflect().descriptor())
    if err != nil {
        log.fatal("normalizedescriptor: ", err)
    }

    var opts proto.marshaloptions
    var data [][]byte
    for _, row := range persons {
        buf, err := opts.marshal(row)
        if err != nil {
            log.fatal("protobuf.marshal: ", err)
        }
        data = append(data, buf)
    }

    err = stream.send(&storagepb.appendrowsrequest{
        writestream: fmt.sprintf("projects/%s/datasets/%s/tables/%s/streams/_default", "project-id", "dataset-id", "table-id"),
        rows: &storagepb.appendrowsrequest_protorows{
            protorows: &storagepb.appendrowsrequest_protodata{
                writerschema: &storagepb.protoschema{
                    protodescriptor: descriptor,
                },
                rows: &storagepb.protorows{
                    serializedrows: data,
                },
            },
        },
    })
    if err != nil {
        log.fatal("appendrows.send: ", err)
    }

    _, err = stream.recv()
    if err != nil {
        log.fatal("appendrows.recv: ", err)
    }
}

使用新的 api,我需要在 .proto 文件中定义类型,因此我需要使用其他内容来定义可为 null 的字段,我尝试使用可选字段:

syntax = "proto3";

package person;

option go_package = "/personpb";

message row {
  optional string name = 1;
  int64 age = 2;
}

但在尝试流式传输时(不是在编译时)它给了我错误: bqmessage.proto:person_row.name:[proto3_optional=true]选项只能在proto3fields上设置,不能在person_row.name上设置

我尝试的另一个选择是使用 oneof,并像这样编写原型文件

syntax = "proto3";

import "google/protobuf/struct.proto";

package person;

option go_package = "/personpb";

message row {
  nullablestring name = 1;
  int64 age = 2;
}

message nullablestring {
  oneof kind {
    google.protobuf.nullvalue null = 1;
    string data = 2;
  }
}

然后像这样使用它:

var persons = []*personpb.Row{
    {
        Name: &personpb.NullableString{Kind: &personpb.NullableString_Null{
            Null: structpb.NullValue_NULL_VALUE,
        }},
        Age: 20,
    },
    {
        Name: &personpb.NullableString{Kind: &personpb.NullableString_Data{
            Data: "David",
        }},
        Age: 60,
    },
}
...

但这给了我以下错误: 无效的原型架构:bqmessage.proto:person_row.person_nullablestring.null:fielddescriptorproto.oneof_index 0超出类型“person_nullablestring”的范围。

我想因为 api 不知道如何处理 oneof 类型,所以我需要以某种方式告诉它这一点。

在使用新的存储 api 时,如何使用 bigquery.nullable 类型?任何帮助将不胜感激


正确答案


查看 this sample,了解在 go 中使用 proto2 语法文件的端到端示例。

在使用存储 API 时,proto3 仍然是一个特殊的野兽,原因如下:

  • Storage API 的当前行为为 operate using proto2 semantics
  • 目前,Storage API 不理解包装器类型,这是 proto3 用来传达可选存在(例如 BigQuery 字段中的 NULL)的原始方式。因此,它倾向于将包装器字段视为具有值字段的子消息(在 BigQuery 中,是具有单个叶字段的 STRUCT)。
  • 在其发展的后期,proto3 重新引入了 Optional 关键字作为标记存在的方式,但在内部表示中,这意味着添加另一个存在标记(您在后端错误中观察到的 proto3_Optional 警告的来源)。

看起来您已经使用了较新的胶合板,特别是 adapt.NormalizeDescriptor()。我怀疑如果您正在使用此模块,则可能使用的是该模块的旧版本,因为规范化代码已在 this PR 中更新并作为 bigquery/v1.33.0 的一部分发布。

我们正在努力改善存储 API 的体验并使整体体验更加流畅,但仍有工作要做。

理论要掌握,实操不能落!以上关于《使用 BigQuery 存储写入 API 时 golang 中的 BigQuery 可空类型》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>