Skip to main content

google_cloud_bigquery/
lib.rs

1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Google Cloud Client Libraries for Rust - BigQuery
16//!
17//! **NOTE:** While the version is still `0.x`, we believe the APIs to be stable.
18//! We plan to release a `1.0` version of this crate in the following release.
19//!
20//! We welcome feedback about the APIs, documentation, missing features, bugs, etc.
21//!
22//! This crate contains traits, types, and functions to interact with
23//! [Google Cloud BigQuery][bigquery]. Most applications will use the structs
24//! defined in the [client] module.
25//!
26//! For executing queries and managing jobs:
27//! * [BigQuery][client::BigQuery]
28//!
29//! For reading query results efficiently:
30//! * [Read][client::Read]
31//!
32//! For streaming data to BigQuery:
33//! * [Write][client::Write]
34//!
35//! [bigquery]: https://cloud.google.com/bigquery
36//!
37//! # Example: Executing a Query
38//!
39//! ```
40//! # use google_cloud_bigquery::client::BigQuery;
41//! # async fn sample() -> anyhow::Result<()> {
42//! // Create a client configured with a default project ID.
43//! let client = BigQuery::builder()
44//!     .with_project_id("my-project-id")
45//!     .build()
46//!     .await?;
47//!
48//! // Configure, run, and read query results.
49//! let mut rows = client
50//!     .query("SELECT 'hello world' AS greeting")
51//!     .until_done()
52//!     .await?
53//!     .read();
54//!
55//! while let Some(row) = rows.next().await.transpose()? {
56//!     let greeting: String = row.get("greeting")?;
57//!     println!("Greeting: {greeting}");
58//! }
59//! # Ok(())
60//! # }
61//! ```
62//!
63//! # Example: Mapping Rows to Rust Structs
64//!
65//! Define typed Rust structs with `#[derive(FromRow)]` to convert rows
66//! directly into domain types using `TryFrom<Row>`:
67//!
68//! ```
69//! # use google_cloud_bigquery::client::BigQuery;
70//! # use google_cloud_bigquery::query::FromRow;
71//! #[derive(FromRow, Debug)]
72//! struct UserStats {
73//!     name: String,
74//!     number: i64,
75//! }
76//!
77//! # async fn sample(client: BigQuery) -> anyhow::Result<()> {
78//! let mut rows = client
79//!     .query("SELECT name, number FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = 'WA' LIMIT 5")
80//!     .until_done()
81//!     .await?
82//!     .read();
83//!
84//! while let Some(row) = rows.next().await.transpose()? {
85//!     let user: UserStats = row.try_into()?;
86//!     println!("{} has count {}", user.name, user.number);
87//! }
88//! # Ok(())
89//! # }
90//! ```
91//!
92//! # Example: Reading from BigQuery
93//!
94//! ```
95//! use google_cloud_bigquery::client::Read;
96//! use google_cloud_bigquery::model::{DataFormat, ReadSession};
97//! # async fn sample() -> anyhow::Result<()> {
98//! let client = Read::builder().build().await?;
99//!
100//! let session = client
101//!     .create_read_session()
102//!     .set_parent("projects/my-project")
103//!     .set_read_session(
104//!         ReadSession::new()
105//!             .set_data_format(DataFormat::Arrow)
106//!             .set_table("projects/my-project/datasets/my-dataset/tables/my-table"),
107//!     )
108//!     .set_max_stream_count(1)
109//!     .send()
110//!     .await?;
111//!
112//! for stream in &session.streams {
113//!     let mut rows = client
114//!         .read_rows()
115//!         .set_read_stream(&stream.name)
116//!         .send()
117//!         .await?;
118//!
119//!     while let Some(response) = rows.next().await.transpose()? {
120//!         println!("Read {} rows", response.row_count);
121//!     }
122//! }
123//! # Ok(())
124//! # }
125//! ```
126//!
127//! # Example: Writing to BigQuery
128//!
129//! ```
130//! use google_cloud_bigquery::client::Write;
131//! use google_cloud_bigquery::model::{ArrowSchema, ArrowRecordBatch};
132//! # async fn sample() -> anyhow::Result<()> {
133//! let client = Write::builder().build().await?;
134//! let writer = client
135//!     .open_default_stream("projects/my-project/datasets/my-dataset/tables/my-table")
136//!     .build_arrow(schema())
137//!     .await?;
138//!
139//! let f1 = writer.append(rows()).send();
140//! let f2 = writer.append(rows()).send();
141//!
142//! let _ = f1.await?;
143//! let _ = f2.await?;
144//! # Ok(()) }
145//!
146//! fn schema() -> ArrowSchema {
147//!     todo!("Define your table's schema...")
148//! }
149//! fn rows() -> ArrowRecordBatch {
150//!     todo!("Serialize your rows...")
151//! }
152//! ```
153
154pub use google_cloud_gax::Result;
155pub use google_cloud_gax::error::Error;
156
157pub(crate) mod generated;
158
159/// Clients to interact with Google Cloud BigQuery.
160pub mod client {
161    pub use crate::query::client::BigQuery;
162    pub use crate::write::client::Write;
163    pub use crate::write::generated::gapic_storage::client::Read;
164    // TODO(#6152) - add Write admin client
165}
166
167pub use crate::write::generated::gapic_storage::model;
168
169/// Extends [crate::model].
170///
171/// Note that there is no real distinction between the types in `model` and
172/// `model_ext`. The two modules are separate for library maintenance reasons.
173pub mod model_ext {
174    pub use crate::generated::{CompleteQueryMetadata, QueryMetadata, QueryRequest};
175    pub use crate::write::append_response::AppendResponse;
176}
177
178/// Request and client builders.
179pub mod builder {
180    /// Request and client builders for the [BigQuery][crate::client::BigQuery] client.
181    pub mod bigquery {
182        pub use crate::generated::QueryRequest;
183        pub use crate::query::builder::Query;
184        pub use crate::query::client_builder::ClientBuilder;
185    }
186    /// Request and client builders for the [Write][crate::client::Write] client.
187    pub mod write {
188        pub use crate::write::builder::{Append, AppendWithOffset};
189        pub use crate::write::client_builder::ClientBuilder;
190        pub use crate::write::writer_builder::WriterBuilder;
191    }
192    pub use crate::write::generated::gapic_storage::builder::read;
193}
194
195/// Traits to mock the clients in this library.
196pub mod stub {
197    pub use crate::write::generated::gapic_storage::stub::Read;
198}
199
200/// Custom errors for the BigQuery clients.
201pub mod error;
202
203/// Types related to querying with a [BigQuery][crate::client::BigQuery] client.
204pub mod query;
205
206/// Types related to writing with a [Write][crate::client::Write] client.
207pub mod write;
208
209pub mod datatypes;
210
211pub(crate) use google_cloud_gax::client_builder::internal::{
212    ClientFactory, new_builder as new_client_builder,
213};
214pub(crate) use google_cloud_gax::client_builder::{ClientBuilder, Result as ClientBuilderResult};
215pub(crate) use google_cloud_gax::options::RequestOptions;
216pub(crate) use google_cloud_gax::options::internal::RequestBuilder;
217pub(crate) use google_cloud_gax::response::Response;
218
219#[allow(dead_code)]
220pub(crate) mod google {
221    pub mod api {
222        include!("write/generated/protos/storage/google.api.rs");
223    }
224    pub mod cloud {
225        pub mod bigquery {
226            pub mod storage {
227                pub mod v1 {
228                    #![allow(deprecated)]
229                    include!("write/generated/protos/storage/google.cloud.bigquery.storage.v1.rs");
230                    include!("write/generated/convert/storage/convert.rs");
231                }
232            }
233        }
234    }
235    pub mod rpc {
236        include!("write/generated/protos/storage/google.rpc.rs");
237    }
238}