MCPcopy Create free account
hub / github.com/GoogleCloudPlatform/cpp-samples / main

Function main

bigquery/write/single_threaded_write.cc:30–103  ·  view source on GitHub ↗

Writes a few rows to a (hard-coded) test table. Create the table with bq mk cpp_samples bq mk cpp_samples.hello bq update cpp_samples.hello schema.json

Source from the content-addressed store, hash-verified

28// bq mk cpp_samples.hello
29// bq update cpp_samples.hello schema.json
30int main(int argc, char* argv[]) {
31 if (argc != 2) {
32 std::cerr << "Usage: single_threaded_write <project-id>\n";
33 return 1;
34 }
35 auto const project_id = std::string{argv[1]};
36 auto client = bq::BigQueryWriteClient(bq::MakeBigQueryWriteConnection());
37
38 auto stream = client.AsyncAppendRows();
39 auto handle_broken_stream = [&stream](char const* where) {
40 auto status = stream->Finish().get();
41 std::cerr << "Unexpected streaming RPC error in " << where << ": " << status
42 << "\n";
43 return 1;
44 };
45
46 if (!stream->Start().get()) return handle_broken_stream("Start()");
47 for (int i = 0; i != 5; ++i) {
48 AppendRowsRequest request;
49 if (i == 0) {
50 // Only the first request needs to include this information.
51 request.set_write_stream(
52 std::string{"projects/"} + project_id +
53 "/datasets/cpp_samples/tables/singers/streams/_default");
54 Singers::GetDescriptor()->CopyTo(request.mutable_proto_rows()
55 ->mutable_writer_schema()
56 ->mutable_proto_descriptor());
57 }
58 *request.mutable_proto_rows()->mutable_rows() =
59 MakeSampleRows(i * kRowsPerMessage, kRowsPerMessage);
60 auto write = stream->Write(request, grpc::WriteOptions{}).get();
61 // Abort the upload if the stream is closed unexpectedly.
62 if (!write) return handle_broken_stream("Write()");
63
64 auto response = stream->Read().get();
65 // Abort the upload if the stream is closed unexpectedly.
66 if (!response.has_value()) return handle_broken_stream("Read()");
67
68 if (response->has_error()) {
69 // In this example we simply abort the write, though applications could
70 // recover, for example, using a separate stream to retry.
71 std::cerr << "Error uploading data on message " << i
72 << ". The full error is " << response->error().DebugString()
73 << "\n";
74 break;
75 }
76 if (!response->row_errors().empty()) {
77 std::cerr << "Error uploading data on message " << i
78 << ". Some rows had errors\n";
79 for (auto const& e : response->row_errors()) {
80 std::cerr << " " << e.DebugString() << "\n";
81 }
82 break;
83 }
84 if (response->has_append_result() &&
85 response->append_result().has_offset()) {
86 std::cout << "Data successfully inserted at offset "
87 << response->append_result().offset().value() << "\n";

Callers

nothing calls this directly

Calls 2

MakeSampleRowsFunction · 0.85
StartMethod · 0.45

Tested by

no test coverage detected