Skip to main content

risingwave_connector/sink/
big_query.rs

1// Copyright 2023 RisingWave Labs
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//     http://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
15use core::pin::Pin;
16use core::time::Duration;
17use std::collections::{BTreeMap, HashMap, VecDeque};
18use std::time::{SystemTime, UNIX_EPOCH};
19
20use anyhow::{Context, anyhow};
21use async_trait::async_trait;
22use base64::Engine;
23use base64::prelude::BASE64_STANDARD;
24use either::Either;
25use futures::future::pending;
26use futures::prelude::Future;
27use futures::{Stream, StreamExt};
28use futures_async_stream::try_stream;
29use gcloud_bigquery::client::google_cloud_auth;
30use gcloud_bigquery::client::google_cloud_auth::credentials::CredentialsFile;
31use gcloud_bigquery::grpc::apiv1::conn_pool::ConnectionManager;
32use gcloud_gax::conn::{ConnectionOptions, Environment};
33use gcloud_gax::grpc::{Request, Response, Status};
34use gcloud_googleapis::cloud::bigquery::storage::v1::append_rows_request::{
35    MissingValueInterpretation, ProtoData, Rows as AppendRowsRequestRows,
36};
37use gcloud_googleapis::cloud::bigquery::storage::v1::{
38    AppendRowsRequest, AppendRowsResponse, ProtoRows, ProtoSchema,
39};
40use gcp_bigquery_client::Client;
41use gcp_bigquery_client::error::BQError;
42use gcp_bigquery_client::model::query_request::QueryRequest;
43use gcp_bigquery_client::model::query_response::ResultSet;
44use gcp_bigquery_client::model::table::Table;
45use gcp_bigquery_client::model::table_field_schema::TableFieldSchema;
46use gcp_bigquery_client::model::table_schema::TableSchema;
47use parking_lot::Mutex;
48use phf::{Set, phf_set};
49use prost_reflect::{FieldDescriptor, MessageDescriptor};
50use prost_types::{
51    DescriptorProto, FieldDescriptorProto, FileDescriptorProto, FileDescriptorSet,
52    field_descriptor_proto,
53};
54use risingwave_common::array::{Op, StreamChunk};
55use risingwave_common::catalog::{Field, Schema};
56use risingwave_common::types::DataType;
57use risingwave_common::util::iter_util::ZipEqDebug;
58use serde::Deserialize;
59use serde_with::{DisplayFromStr, serde_as};
60use simd_json::prelude::ArrayTrait;
61use tokio::sync::mpsc;
62use url::Url;
63use uuid::Uuid;
64use with_options::WithOptions;
65use yup_oauth2::ServiceAccountKey;
66
67use super::encoder::{ProtoEncoder, ProtoHeader, RowEncoder, SerTo};
68use super::log_store::{LogStoreReadItem, TruncateOffset};
69use super::{
70    LogSinker, SINK_TYPE_APPEND_ONLY, SINK_TYPE_OPTION, SINK_TYPE_UPSERT, SinkError, SinkLogReader,
71};
72use crate::aws_utils::load_file_descriptor_from_s3;
73use crate::connector_common::AwsAuthProps;
74use crate::enforce_secret::EnforceSecret;
75use crate::sink::{Result, Sink, SinkParam, SinkWriterParam};
76
77pub const BIGQUERY_SINK: &str = "bigquery";
78pub const CHANGE_TYPE: &str = "_CHANGE_TYPE";
79pub const CHANGE_SEQUENCE_NUMBER: &str = "_CHANGE_SEQUENCE_NUMBER";
80const DEFAULT_GRPC_CHANNEL_NUMS: usize = 4;
81const CONNECT_TIMEOUT: Option<Duration> = Some(Duration::from_secs(30));
82const CONNECTION_TIMEOUT: Option<Duration> = None;
83const BIGQUERY_SEND_FUTURE_BUFFER_MAX_SIZE: usize = 65536;
84// < 10MB, we set 8MB
85const MAX_ROW_SIZE: usize = 8 * 1024 * 1024;
86
87#[serde_as]
88#[derive(Deserialize, Debug, Clone, WithOptions)]
89pub struct BigQueryCommon {
90    #[serde(rename = "bigquery.local.path")]
91    pub local_path: Option<String>,
92    #[serde(rename = "bigquery.s3.path")]
93    pub s3_path: Option<String>,
94    #[serde(rename = "bigquery.project")]
95    pub project: String,
96    #[serde(rename = "bigquery.dataset")]
97    pub dataset: String,
98    #[serde(rename = "bigquery.table")]
99    pub table: String,
100    #[serde(default, alias = "create_table_if_not_exists")] // default false
101    #[serde_as(as = "DisplayFromStr")]
102    pub auto_create: bool,
103    #[serde(rename = "bigquery.credentials")]
104    pub credentials: Option<String>,
105}
106
107impl EnforceSecret for BigQueryCommon {
108    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
109        "bigquery.credentials",
110    };
111}
112
113struct BigQueryFutureManager {
114    // `offset_queue` holds the Some corresponding to each future.
115    // When TruncateOffset is barrier, the num is 0, we don't need to wait for the return of `resp_stream`.
116    // When TruncateOffset is chunk:
117    // 1. chunk has no rows. we didn't send, the num is 0, we don't need to wait for the return of `resp_stream`.
118    // 2. chunk is less than `MAX_ROW_SIZE`, we only sent once, the num is 1 and we only have to wait once for `resp_stream`.
119    // 3. chunk is less than `MAX_ROW_SIZE`, we only sent n, the num is n and we need to wait n times for r.
120    offset_queue: VecDeque<(TruncateOffset, usize)>,
121    resp_stream: Pin<Box<dyn Stream<Item = Result<()>> + Send>>,
122}
123impl BigQueryFutureManager {
124    pub fn new(
125        max_future_num: usize,
126        resp_stream: impl Stream<Item = Result<()>> + Send + 'static,
127    ) -> Self {
128        let offset_queue = VecDeque::with_capacity(max_future_num);
129        Self {
130            offset_queue,
131            resp_stream: Box::pin(resp_stream),
132        }
133    }
134
135    pub fn add_offset(&mut self, offset: TruncateOffset, resp_num: usize) {
136        self.offset_queue.push_back((offset, resp_num));
137    }
138
139    pub async fn next_offset(&mut self) -> Result<TruncateOffset> {
140        if let Some((_offset, remaining_resp_num)) = self.offset_queue.front_mut() {
141            if *remaining_resp_num == 0 {
142                return Ok(self.offset_queue.pop_front().unwrap().0);
143            }
144            while *remaining_resp_num > 0 {
145                self.resp_stream
146                    .next()
147                    .await
148                    .ok_or_else(|| SinkError::BigQuery(anyhow::anyhow!("end of stream")))??;
149                *remaining_resp_num -= 1;
150            }
151            Ok(self.offset_queue.pop_front().unwrap().0)
152        } else {
153            pending().await
154        }
155    }
156}
157pub struct BigQueryLogSinker {
158    writer: BigQuerySinkWriter,
159    bigquery_future_manager: BigQueryFutureManager,
160    future_num: usize,
161}
162impl BigQueryLogSinker {
163    pub fn new(
164        writer: BigQuerySinkWriter,
165        resp_stream: impl Stream<Item = Result<()>> + Send + 'static,
166        future_num: usize,
167    ) -> Self {
168        Self {
169            writer,
170            bigquery_future_manager: BigQueryFutureManager::new(future_num, resp_stream),
171            future_num,
172        }
173    }
174}
175
176#[async_trait]
177impl LogSinker for BigQueryLogSinker {
178    async fn consume_log_and_sink(mut self, mut log_reader: impl SinkLogReader) -> Result<!> {
179        log_reader.start_from(None).await?;
180        loop {
181            tokio::select!(
182                offset = self.bigquery_future_manager.next_offset() => {
183                        log_reader.truncate(offset?)?;
184                }
185                item_result = log_reader.next_item(), if self.bigquery_future_manager.offset_queue.len() <= self.future_num => {
186                    let (epoch, item) = item_result?;
187                    match item {
188                        LogStoreReadItem::StreamChunk { chunk_id, chunk } => {
189                            let resp_num = self.writer.write_chunk(chunk)?;
190                            self.bigquery_future_manager
191                                .add_offset(TruncateOffset::Chunk { epoch, chunk_id },resp_num);
192                        }
193                        LogStoreReadItem::Barrier { .. } => {
194                            self.bigquery_future_manager
195                                .add_offset(TruncateOffset::Barrier { epoch },0);
196                        }
197                    }
198                }
199            )
200        }
201    }
202}
203
204impl BigQueryCommon {
205    async fn build_client(&self, aws_auth_props: &AwsAuthProps) -> Result<Client> {
206        let auth_json = self.get_auth_json_from_path(aws_auth_props).await?;
207
208        let service_account =
209            if let Ok(auth_json_from_base64) = BASE64_STANDARD.decode(auth_json.clone()) {
210                serde_json::from_slice::<ServiceAccountKey>(&auth_json_from_base64)
211            } else {
212                serde_json::from_str::<ServiceAccountKey>(&auth_json)
213            }
214            .map_err(|e| SinkError::BigQuery(e.into()))?;
215
216        let client: Client = Client::from_service_account_key(service_account, false)
217            .await
218            .map_err(|err| SinkError::BigQuery(anyhow::anyhow!(err)))?;
219        Ok(client)
220    }
221
222    async fn build_writer_client(
223        &self,
224        aws_auth_props: &AwsAuthProps,
225    ) -> Result<(StorageWriterClient, impl Stream<Item = Result<()>> + use<>)> {
226        let auth_json = self.get_auth_json_from_path(aws_auth_props).await?;
227
228        let credentials_file =
229            if let Ok(auth_json_from_base64) = BASE64_STANDARD.decode(auth_json.clone()) {
230                serde_json::from_slice::<CredentialsFile>(&auth_json_from_base64)
231            } else {
232                serde_json::from_str::<CredentialsFile>(&auth_json)
233            }
234            .map_err(|e| SinkError::BigQuery(e.into()))?;
235
236        StorageWriterClient::new(credentials_file).await
237    }
238
239    async fn get_auth_json_from_path(&self, aws_auth_props: &AwsAuthProps) -> Result<String> {
240        if let Some(credentials) = &self.credentials {
241            Ok(credentials.clone())
242        } else if let Some(local_path) = &self.local_path {
243            std::fs::read_to_string(local_path)
244                .map_err(|err| SinkError::BigQuery(anyhow::anyhow!(err)))
245        } else if let Some(s3_path) = &self.s3_path {
246            let url =
247                Url::parse(s3_path).map_err(|err| SinkError::BigQuery(anyhow::anyhow!(err)))?;
248            let auth_vec = load_file_descriptor_from_s3(&url, aws_auth_props)
249                .await
250                .map_err(|err| SinkError::BigQuery(anyhow::anyhow!(err)))?;
251            Ok(String::from_utf8(auth_vec).map_err(|e| SinkError::BigQuery(e.into()))?)
252        } else {
253            Err(SinkError::BigQuery(anyhow::anyhow!(
254                "`bigquery.local.path` and `bigquery.s3.path` set at least one, configure as needed."
255            )))
256        }
257    }
258}
259
260#[serde_as]
261#[derive(Clone, Debug, Deserialize, WithOptions)]
262pub struct BigQueryConfig {
263    #[serde(flatten)]
264    pub common: BigQueryCommon,
265    #[serde(flatten)]
266    pub aws_auth_props: AwsAuthProps,
267    pub r#type: String, // accept "append-only" or "upsert"
268
269    /// Write `_CHANGE_SEQUENCE_NUMBER` on upsert rows, so that `BigQuery` applies the changes of
270    /// each key in the order they are sent. Once a table has rows written with it, turning it off
271    /// makes `BigQuery` ignore later changes to those rows.
272    #[serde(rename = "bigquery.change_sequence_number", default)]
273    #[serde_as(as = "DisplayFromStr")]
274    #[with_option(allow_alter_on_fly)]
275    pub change_sequence_number: bool,
276
277    #[serde(flatten)]
278    pub unknown_fields: std::collections::HashMap<String, String>,
279}
280
281crate::impl_sink_unknown_fields!(BigQueryConfig);
282
283impl EnforceSecret for BigQueryConfig {
284    fn enforce_one(prop: &str) -> crate::error::ConnectorResult<()> {
285        BigQueryCommon::enforce_one(prop)?;
286        AwsAuthProps::enforce_one(prop)?;
287        Ok(())
288    }
289}
290
291impl BigQueryConfig {
292    pub fn from_btreemap(properties: BTreeMap<String, String>) -> Result<Self> {
293        let config =
294            serde_json::from_value::<BigQueryConfig>(serde_json::to_value(properties).unwrap())
295                .map_err(|e| SinkError::Config(anyhow!(e)))?;
296        if config.r#type != SINK_TYPE_APPEND_ONLY && config.r#type != SINK_TYPE_UPSERT {
297            return Err(SinkError::Config(anyhow!(
298                "`{}` must be {}, or {}",
299                SINK_TYPE_OPTION,
300                SINK_TYPE_APPEND_ONLY,
301                SINK_TYPE_UPSERT
302            )));
303        }
304        Ok(config)
305    }
306}
307
308#[derive(Debug)]
309pub struct BigQuerySink {
310    pub config: BigQueryConfig,
311    schema: Schema,
312    pk_indices: Vec<usize>,
313    is_append_only: bool,
314}
315
316impl EnforceSecret for BigQuerySink {
317    fn enforce_secret<'a>(
318        prop_iter: impl Iterator<Item = &'a str>,
319    ) -> crate::error::ConnectorResult<()> {
320        for prop in prop_iter {
321            BigQueryConfig::enforce_one(prop)?;
322        }
323        Ok(())
324    }
325}
326
327impl BigQuerySink {
328    pub fn new(
329        config: BigQueryConfig,
330        schema: Schema,
331        pk_indices: Vec<usize>,
332        is_append_only: bool,
333    ) -> Result<Self> {
334        Ok(Self {
335            config,
336            schema,
337            pk_indices,
338            is_append_only,
339        })
340    }
341}
342
343impl BigQuerySink {
344    fn is_decimal_type_compatible(bigquery_type: &str) -> bool {
345        // BigQuery INFORMATION_SCHEMA reports parameterized decimal columns as
346        // `NUMERIC(p, s)` or `BIGNUMERIC(p, s)`. RisingWave `Decimal` does not
347        // carry typmod, so schema validation accepts the BigQuery decimal type
348        // family instead of requiring exact string equality.
349        let normalized = bigquery_type.trim().to_ascii_uppercase();
350        matches!(
351            normalized
352                .split_once('(')
353                .map_or(normalized.as_str(), |(prefix, _)| prefix),
354            "NUMERIC" | "BIGNUMERIC"
355        )
356    }
357
358    fn is_data_type_compatible(rw_data_type: &DataType, bigquery_type: &str) -> Result<bool> {
359        if matches!(rw_data_type, DataType::Decimal) {
360            return Ok(Self::is_decimal_type_compatible(bigquery_type));
361        }
362
363        Ok(Self::get_string_and_check_support_from_datatype(rw_data_type)? == bigquery_type)
364    }
365
366    fn check_column_name_and_type(
367        &self,
368        big_query_columns_desc: HashMap<String, String>,
369    ) -> Result<()> {
370        let rw_fields_name = self.schema.fields();
371        if big_query_columns_desc.is_empty() {
372            return Err(SinkError::BigQuery(anyhow::anyhow!(
373                "Cannot find table in bigquery"
374            )));
375        }
376        if rw_fields_name.len().ne(&big_query_columns_desc.len()) {
377            return Err(SinkError::BigQuery(anyhow::anyhow!(
378                "The length of the RisingWave column {} must be equal to the length of the bigquery column {}",
379                rw_fields_name.len(),
380                big_query_columns_desc.len()
381            )));
382        }
383
384        for i in rw_fields_name {
385            let value = big_query_columns_desc.get(&i.name).ok_or_else(|| {
386                SinkError::BigQuery(anyhow::anyhow!(
387                    "Column `{:?}` on RisingWave side is not found on BigQuery side.",
388                    i.name
389                ))
390            })?;
391            let data_type_string = Self::get_string_and_check_support_from_datatype(&i.data_type)?;
392            if !Self::is_data_type_compatible(&i.data_type, value)? {
393                return Err(SinkError::BigQuery(anyhow::anyhow!(
394                    "Data type mismatch for column `{:?}`. BigQuery side: `{:?}`, RisingWave side: `{:?}`. ",
395                    i.name,
396                    value,
397                    data_type_string
398                )));
399            };
400        }
401        Ok(())
402    }
403
404    fn get_string_and_check_support_from_datatype(rw_data_type: &DataType) -> Result<String> {
405        match rw_data_type {
406            DataType::Boolean => Ok("BOOL".to_owned()),
407            DataType::Int16 => Ok("INT64".to_owned()),
408            DataType::Int32 => Ok("INT64".to_owned()),
409            DataType::Int64 => Ok("INT64".to_owned()),
410            DataType::Float32 => Err(SinkError::BigQuery(anyhow::anyhow!(
411                "REAL is not supported for BigQuery sink. Please convert to FLOAT64 or other supported types."
412            ))),
413            DataType::Float64 => Ok("FLOAT64".to_owned()),
414            DataType::Decimal => Ok("NUMERIC".to_owned()),
415            DataType::Date => Ok("DATE".to_owned()),
416            DataType::Varchar => Ok("STRING".to_owned()),
417            DataType::Time => Ok("TIME".to_owned()),
418            DataType::Timestamp => Ok("DATETIME".to_owned()),
419            DataType::Timestamptz => Ok("TIMESTAMP".to_owned()),
420            DataType::Interval => Ok("INTERVAL".to_owned()),
421            DataType::Struct(structs) => {
422                let mut elements_vec = vec![];
423                for (name, datatype) in structs.iter() {
424                    let element_string =
425                        Self::get_string_and_check_support_from_datatype(datatype)?;
426                    elements_vec.push(format!("{} {}", name, element_string));
427                }
428                Ok(format!("STRUCT<{}>", elements_vec.join(", ")))
429            }
430            DataType::List(l) => {
431                let element_string = Self::get_string_and_check_support_from_datatype(l.elem())?;
432                Ok(format!("ARRAY<{}>", element_string))
433            }
434            DataType::Bytea => Ok("BYTES".to_owned()),
435            DataType::Jsonb => Ok("JSON".to_owned()),
436            DataType::Variant => Err(SinkError::BigQuery(anyhow::anyhow!(
437                "VARIANT is not supported for BigQuery sink."
438            ))),
439            DataType::Serial => Ok("INT64".to_owned()),
440            DataType::Int256 => Err(SinkError::BigQuery(anyhow::anyhow!(
441                "INT256 is not supported for BigQuery sink."
442            ))),
443            DataType::Map(_) => Err(SinkError::BigQuery(anyhow::anyhow!(
444                "MAP is not supported for BigQuery sink."
445            ))),
446            DataType::Vector(_) => Err(SinkError::BigQuery(anyhow::anyhow!(
447                "VECTOR is not supported for BigQuery sink."
448            ))),
449        }
450    }
451
452    fn map_field(rw_field: &Field) -> Result<TableFieldSchema> {
453        let tfs = match &rw_field.data_type {
454            DataType::Boolean => TableFieldSchema::bool(&rw_field.name),
455            DataType::Int16 | DataType::Int32 | DataType::Int64 | DataType::Serial => {
456                TableFieldSchema::integer(&rw_field.name)
457            }
458            DataType::Float32 => {
459                return Err(SinkError::BigQuery(anyhow::anyhow!(
460                    "REAL is not supported for BigQuery sink. Please convert to FLOAT64 or other supported types."
461                )));
462            }
463            DataType::Float64 => TableFieldSchema::float(&rw_field.name),
464            DataType::Decimal => TableFieldSchema::numeric(&rw_field.name),
465            DataType::Date => TableFieldSchema::date(&rw_field.name),
466            DataType::Varchar => TableFieldSchema::string(&rw_field.name),
467            DataType::Time => TableFieldSchema::time(&rw_field.name),
468            DataType::Timestamp => TableFieldSchema::date_time(&rw_field.name),
469            DataType::Timestamptz => TableFieldSchema::timestamp(&rw_field.name),
470            DataType::Interval => {
471                return Err(SinkError::BigQuery(anyhow::anyhow!(
472                    "INTERVAL is not supported for BigQuery sink. Please convert to VARCHAR or other supported types."
473                )));
474            }
475            DataType::Struct(st) => {
476                let mut sub_fields = Vec::with_capacity(st.len());
477                for (name, dt) in st.iter() {
478                    let rw_field = Field::with_name(dt.clone(), name);
479                    let field = Self::map_field(&rw_field)?;
480                    sub_fields.push(field);
481                }
482                TableFieldSchema::record(&rw_field.name, sub_fields)
483            }
484            DataType::List(lt) => {
485                let inner_field =
486                    Self::map_field(&Field::with_name(lt.elem().clone(), &rw_field.name))?;
487                TableFieldSchema {
488                    mode: Some("REPEATED".to_owned()),
489                    ..inner_field
490                }
491            }
492
493            DataType::Bytea => TableFieldSchema::bytes(&rw_field.name),
494            DataType::Jsonb => TableFieldSchema::json(&rw_field.name),
495            DataType::Variant => {
496                return Err(SinkError::BigQuery(anyhow::anyhow!(
497                    "VARIANT is not supported for BigQuery sink."
498                )));
499            }
500            DataType::Int256 => {
501                return Err(SinkError::BigQuery(anyhow::anyhow!(
502                    "INT256 is not supported for BigQuery sink."
503                )));
504            }
505            DataType::Map(_) => {
506                return Err(SinkError::BigQuery(anyhow::anyhow!(
507                    "MAP is not supported for BigQuery sink."
508                )));
509            }
510            DataType::Vector(_) => {
511                return Err(SinkError::BigQuery(anyhow::anyhow!(
512                    "VECTOR is not supported for BigQuery sink."
513                )));
514            }
515        };
516        Ok(tfs)
517    }
518
519    async fn create_table(
520        &self,
521        client: &Client,
522        project_id: &str,
523        dataset_id: &str,
524        table_id: &str,
525        fields: &Vec<Field>,
526    ) -> Result<Table> {
527        let dataset = client
528            .dataset()
529            .get(project_id, dataset_id)
530            .await
531            .map_err(|e| SinkError::BigQuery(e.into()))?;
532        let fields: Vec<_> = fields.iter().map(Self::map_field).collect::<Result<_>>()?;
533        let table = Table::from_dataset(&dataset, table_id, TableSchema::new(fields));
534
535        client
536            .table()
537            .create(table)
538            .await
539            .map_err(|e| SinkError::BigQuery(e.into()))
540    }
541}
542
543impl Sink for BigQuerySink {
544    type LogSinker = BigQueryLogSinker;
545
546    const SINK_NAME: &'static str = BIGQUERY_SINK;
547
548    crate::impl_validate_sink_unknown_fields!();
549
550    fn validate_alter_config(config: &BTreeMap<String, String>) -> Result<()> {
551        BigQueryConfig::from_btreemap(config.clone())?;
552        Ok(())
553    }
554
555    async fn new_log_sinker(&self, _writer_param: SinkWriterParam) -> Result<Self::LogSinker> {
556        let (writer, resp_stream) = BigQuerySinkWriter::new(
557            self.config.clone(),
558            self.schema.clone(),
559            self.pk_indices.clone(),
560            self.is_append_only,
561        )
562        .await?;
563        Ok(BigQueryLogSinker::new(
564            writer,
565            resp_stream,
566            BIGQUERY_SEND_FUTURE_BUFFER_MAX_SIZE,
567        ))
568    }
569
570    async fn validate(&self) -> Result<()> {
571        risingwave_common::license::Feature::BigQuerySink
572            .check_available()
573            .map_err(|e| anyhow::anyhow!(e))?;
574        if !self.is_append_only && self.pk_indices.is_empty() {
575            return Err(SinkError::Config(anyhow!(
576                "Primary key not defined for upsert bigquery sink (please define in `primary_key` field)"
577            )));
578        }
579        let client = self
580            .config
581            .common
582            .build_client(&self.config.aws_auth_props)
583            .await?;
584        let BigQueryCommon {
585            project: project_id,
586            dataset: dataset_id,
587            table: table_id,
588            ..
589        } = &self.config.common;
590
591        if self.config.common.auto_create {
592            match client
593                .table()
594                .get(project_id, dataset_id, table_id, None)
595                .await
596            {
597                Err(BQError::ResponseError { error }) if error.error.code == 404 => {
598                    // early return: no need to query schema to check column and type
599                    return self
600                        .create_table(
601                            &client,
602                            project_id,
603                            dataset_id,
604                            table_id,
605                            &self.schema.fields,
606                        )
607                        .await
608                        .map(|_| ());
609                }
610                Err(e) => return Err(SinkError::BigQuery(e.into())),
611                _ => {}
612            }
613        }
614
615        let rs = client
616            .job()
617            .query(
618                &self.config.common.project,
619                QueryRequest::new(format!(
620                    "SELECT column_name, data_type FROM `{}.{}.INFORMATION_SCHEMA.COLUMNS` WHERE table_name = '{}'",
621                    project_id, dataset_id, table_id,
622                )),
623            ).await.map_err(|e| SinkError::BigQuery(e.into()))?;
624        let mut rs = ResultSet::new_from_query_response(rs);
625
626        let mut big_query_schema = HashMap::default();
627        while rs.next_row() {
628            big_query_schema.insert(
629                rs.get_string_by_name("column_name")
630                    .map_err(|e| SinkError::BigQuery(e.into()))?
631                    .ok_or_else(|| {
632                        SinkError::BigQuery(anyhow::anyhow!("Cannot find column_name"))
633                    })?,
634                rs.get_string_by_name("data_type")
635                    .map_err(|e| SinkError::BigQuery(e.into()))?
636                    .ok_or_else(|| {
637                        SinkError::BigQuery(anyhow::anyhow!("Cannot find column_name"))
638                    })?,
639            );
640        }
641
642        self.check_column_name_and_type(big_query_schema)?;
643        Ok(())
644    }
645}
646
647pub struct BigQuerySinkWriter {
648    pub config: BigQueryConfig,
649    #[expect(dead_code)]
650    schema: Schema,
651    #[expect(dead_code)]
652    pk_indices: Vec<usize>,
653    client: StorageWriterClient,
654    is_append_only: bool,
655    row_encoder: ProtoEncoder,
656    writer_pb_schema: ProtoSchema,
657    #[expect(dead_code)]
658    message_descriptor: MessageDescriptor,
659    write_stream: String,
660    proto_field: Option<FieldDescriptor>,
661    change_sequence_number_field: Option<FieldDescriptor>,
662}
663
664impl TryFrom<SinkParam> for BigQuerySink {
665    type Error = SinkError;
666
667    fn try_from(param: SinkParam) -> std::result::Result<Self, Self::Error> {
668        let schema = param.schema();
669        let pk_indices = param.downstream_pk_or_empty();
670        let config = BigQueryConfig::from_btreemap(param.properties)?;
671        BigQuerySink::new(config, schema, pk_indices, param.sink_type.is_append_only())
672    }
673}
674
675impl BigQuerySinkWriter {
676    pub async fn new(
677        config: BigQueryConfig,
678        schema: Schema,
679        pk_indices: Vec<usize>,
680        is_append_only: bool,
681    ) -> Result<(Self, impl Stream<Item = Result<()>>)> {
682        let (client, resp_stream) = config
683            .common
684            .build_writer_client(&config.aws_auth_props)
685            .await?;
686        let writer = Self::with_client(config, schema, pk_indices, is_append_only, client)?;
687        Ok((writer, resp_stream))
688    }
689
690    fn with_client(
691        config: BigQueryConfig,
692        schema: Schema,
693        pk_indices: Vec<usize>,
694        is_append_only: bool,
695        client: StorageWriterClient,
696    ) -> Result<Self> {
697        let mut descriptor_proto = build_protobuf_schema(
698            schema
699                .fields()
700                .iter()
701                .map(|f| (f.name.as_str(), &f.data_type)),
702            config.common.table.clone(),
703        )?;
704
705        if !is_append_only {
706            let field = FieldDescriptorProto {
707                name: Some(CHANGE_TYPE.to_owned()),
708                number: Some((schema.len() + 1) as i32),
709                r#type: Some(field_descriptor_proto::Type::String.into()),
710                ..Default::default()
711            };
712            descriptor_proto.field.push(field);
713            if config.change_sequence_number {
714                let field = FieldDescriptorProto {
715                    name: Some(CHANGE_SEQUENCE_NUMBER.to_owned()),
716                    number: Some((schema.len() + 2) as i32),
717                    r#type: Some(field_descriptor_proto::Type::String.into()),
718                    ..Default::default()
719                };
720                descriptor_proto.field.push(field);
721            }
722        }
723
724        let descriptor_pool = build_protobuf_descriptor_pool(&descriptor_proto)?;
725        let message_descriptor = descriptor_pool
726            .get_message_by_name(&config.common.table)
727            .ok_or_else(|| {
728                SinkError::BigQuery(anyhow::anyhow!(
729                    "Can't find message proto {}",
730                    config.common.table
731                ))
732            })?;
733        let proto_field = if !is_append_only {
734            let proto_field = message_descriptor
735                .get_field_by_name(CHANGE_TYPE)
736                .ok_or_else(|| {
737                    SinkError::BigQuery(anyhow::anyhow!("Can't find {}", CHANGE_TYPE))
738                })?;
739            Some(proto_field)
740        } else {
741            None
742        };
743        let change_sequence_number_field = if !is_append_only && config.change_sequence_number {
744            let field = message_descriptor
745                .get_field_by_name(CHANGE_SEQUENCE_NUMBER)
746                .ok_or_else(|| {
747                    SinkError::BigQuery(anyhow::anyhow!("Can't find {}", CHANGE_SEQUENCE_NUMBER))
748                })?;
749            Some(field)
750        } else {
751            None
752        };
753        let row_encoder = ProtoEncoder::new(
754            schema.clone(),
755            None,
756            message_descriptor.clone(),
757            ProtoHeader::None,
758        )?;
759        Ok(Self {
760            write_stream: format!(
761                "projects/{}/datasets/{}/tables/{}/streams/_default",
762                config.common.project, config.common.dataset, config.common.table
763            ),
764            config,
765            schema,
766            pk_indices,
767            client,
768            is_append_only,
769            row_encoder,
770            message_descriptor,
771            proto_field,
772            change_sequence_number_field,
773            writer_pb_schema: ProtoSchema {
774                proto_descriptor: Some(descriptor_proto.clone()),
775            },
776        })
777    }
778
779    fn append_only(&mut self, chunk: StreamChunk) -> Result<Vec<Vec<u8>>> {
780        let mut serialized_rows: Vec<Vec<u8>> = Vec::with_capacity(chunk.capacity());
781        for (op, row) in chunk.rows() {
782            if op != Op::Insert {
783                continue;
784            }
785            serialized_rows.push(self.row_encoder.encode(row)?.ser_to()?)
786        }
787        Ok(serialized_rows)
788    }
789
790    fn upsert(&mut self, chunk: StreamChunk) -> Result<Vec<Vec<u8>>> {
791        let sequence_numbers = if self.change_sequence_number_field.is_some() {
792            Either::Left(CHANGE_SEQUENCE_CLOCK.reserve(chunk.cardinality()).map(Some))
793        } else {
794            Either::Right(std::iter::repeat_n(None, chunk.cardinality()))
795        };
796        let mut serialized_rows: Vec<Vec<u8>> = Vec::with_capacity(chunk.capacity());
797        for ((op, row), sequence_number) in chunk.rows().zip_eq_debug(sequence_numbers) {
798            if op == Op::UpdateDelete {
799                continue;
800            }
801            let mut pb_row = self.row_encoder.encode(row)?;
802            match op {
803                Op::Insert => pb_row
804                    .message
805                    .try_set_field(
806                        self.proto_field.as_ref().unwrap(),
807                        prost_reflect::Value::String("UPSERT".to_owned()),
808                    )
809                    .map_err(|e| SinkError::BigQuery(e.into()))?,
810                Op::Delete => pb_row
811                    .message
812                    .try_set_field(
813                        self.proto_field.as_ref().unwrap(),
814                        prost_reflect::Value::String("DELETE".to_owned()),
815                    )
816                    .map_err(|e| SinkError::BigQuery(e.into()))?,
817                Op::UpdateDelete => continue,
818                Op::UpdateInsert => pb_row
819                    .message
820                    .try_set_field(
821                        self.proto_field.as_ref().unwrap(),
822                        prost_reflect::Value::String("UPSERT".to_owned()),
823                    )
824                    .map_err(|e| SinkError::BigQuery(e.into()))?,
825            };
826            if let Some(sequence_number) = sequence_number {
827                pb_row
828                    .message
829                    .try_set_field(
830                        self.change_sequence_number_field.as_ref().unwrap(),
831                        prost_reflect::Value::String(sequence_number),
832                    )
833                    .map_err(|e| SinkError::BigQuery(e.into()))?;
834            }
835
836            serialized_rows.push(pb_row.ser_to()?)
837        }
838        Ok(serialized_rows)
839    }
840
841    fn write_chunk(&mut self, chunk: StreamChunk) -> Result<usize> {
842        let serialized_rows = if self.is_append_only {
843            self.append_only(chunk)?
844        } else {
845            self.upsert(chunk)?
846        };
847        if serialized_rows.is_empty() {
848            return Ok(0);
849        }
850        let mut batches = Vec::new();
851        let mut batch = Vec::new();
852        let mut batch_size = 0;
853        for row in serialized_rows {
854            if !batch.is_empty() && batch_size + row.len() > MAX_ROW_SIZE {
855                batches.push(std::mem::take(&mut batch));
856                batch_size = 0;
857            }
858            batch_size += row.len();
859            batch.push(row);
860        }
861        if !batch.is_empty() {
862            batches.push(batch);
863        }
864        let len = batches.len();
865        for serialized_rows in batches {
866            let rows = AppendRowsRequestRows::ProtoRows(ProtoData {
867                writer_schema: Some(self.writer_pb_schema.clone()),
868                rows: Some(ProtoRows { serialized_rows }),
869            });
870            self.client.append_rows(rows, self.write_stream.clone())?;
871        }
872        Ok(len)
873    }
874}
875
876/// Hands out `_CHANGE_SEQUENCE_NUMBER`s as `{physical:X}/{logical:X}`, with the wall clock in
877/// microseconds as `physical`. Each number is greater than any reserved before from the same clock,
878/// even if the wall clock moves back.
879///
880/// The change with the largest number wins for each key, so numbering rows in send order is
881/// enough: the sinker sends the changes of a key in log order, and every replay (rewind, recovery,
882/// rescale) resends all changes after the truncated offset, so the last change sent for a key is
883/// its latest one.
884struct ChangeSequenceClock {
885    /// The physical time of the last reserved numbers and the next logical number after them.
886    next: Mutex<(u64, u64)>,
887}
888
889impl ChangeSequenceClock {
890    const fn new() -> Self {
891        Self {
892            next: Mutex::new((0, 0)),
893        }
894    }
895
896    /// Reserves `count` numbers at the current wall clock.
897    fn reserve(&self, count: usize) -> impl Iterator<Item = String> + use<> {
898        let now = SystemTime::now()
899            .duration_since(UNIX_EPOCH)
900            .map_or(0, |since_epoch| since_epoch.as_micros() as u64);
901        let count = count as u64;
902        let (physical, start) = self.reserve_at(now, count);
903        (start..start + count).map(move |logical| format!("{physical:X}/{logical:X}"))
904    }
905
906    /// Reserves `count` logical numbers at physical time `now`, or after the last reserved ones if
907    /// `now` has not moved past their physical time. Returns the physical time and the first
908    /// logical number.
909    fn reserve_at(&self, now: u64, count: u64) -> (u64, u64) {
910        let mut next = self.next.lock();
911        let (physical, logical) = if now > next.0 { (now, 0) } else { *next };
912        *next = (physical, logical + count);
913        (physical, logical)
914    }
915}
916
917/// Shared by all writers in the process, so that the numbers keep increasing when a writer is
918/// rebuilt or a key moves to another actor in the process.
919static CHANGE_SEQUENCE_CLOCK: ChangeSequenceClock = ChangeSequenceClock::new();
920
921#[try_stream(ok = (), error = SinkError)]
922pub async fn resp_to_stream(
923    resp_stream: impl Future<
924        Output = std::result::Result<
925            Response<gcloud_gax::grpc::Streaming<AppendRowsResponse>>,
926            Status,
927        >,
928    >
929    + 'static
930    + Send,
931) {
932    let mut resp_stream = resp_stream
933        .await
934        .map_err(|e| SinkError::BigQuery(e.into()))?
935        .into_inner();
936    loop {
937        match resp_stream
938            .message()
939            .await
940            .map_err(|e| SinkError::BigQuery(e.into()))?
941        {
942            Some(append_rows_response) => {
943                if !append_rows_response.row_errors.is_empty() {
944                    return Err(SinkError::BigQuery(anyhow::anyhow!(
945                        "bigquery insert error {:?}",
946                        append_rows_response.row_errors
947                    )));
948                }
949                if let Some(gcloud_googleapis::cloud::bigquery::storage::v1::append_rows_response::Response::Error(status)) = append_rows_response.response{
950                            return Err(SinkError::BigQuery(anyhow::anyhow!(
951                                "bigquery insert error {:?}",
952                                status
953                            )));
954                        }
955                yield ();
956            }
957            None => {
958                return Err(SinkError::BigQuery(anyhow::anyhow!(
959                    "bigquery insert error: end of resp stream",
960                )));
961            }
962        }
963    }
964}
965
966struct StorageWriterClient {
967    #[expect(dead_code)]
968    environment: Environment,
969    request_sender: mpsc::UnboundedSender<AppendRowsRequest>,
970}
971impl StorageWriterClient {
972    pub async fn new(
973        credentials: CredentialsFile,
974    ) -> Result<(Self, impl Stream<Item = Result<()>>)> {
975        let ts_grpc = google_cloud_auth::token::DefaultTokenSourceProvider::new_with_credentials(
976            Self::bigquery_grpc_auth_config(),
977            Box::new(credentials),
978        )
979        .await
980        .map_err(|e| SinkError::BigQuery(e.into()))?;
981        let conn_options = ConnectionOptions {
982            connect_timeout: CONNECT_TIMEOUT,
983            timeout: CONNECTION_TIMEOUT,
984            ..Default::default()
985        };
986        let environment = Environment::GoogleCloud(Box::new(ts_grpc));
987        let conn = ConnectionManager::new(DEFAULT_GRPC_CHANNEL_NUMS, &environment, &conn_options)
988            .await
989            .map_err(|e| SinkError::BigQuery(e.into()))?;
990        let mut client = conn.writer();
991
992        let (tx, rx) = mpsc::unbounded_channel();
993        let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
994
995        let resp = async move { client.append_rows(Request::new(stream)).await };
996        let resp_stream = resp_to_stream(resp);
997
998        Ok((
999            StorageWriterClient {
1000                environment,
1001                request_sender: tx,
1002            },
1003            resp_stream,
1004        ))
1005    }
1006
1007    pub fn append_rows(&mut self, row: AppendRowsRequestRows, write_stream: String) -> Result<()> {
1008        let append_req = AppendRowsRequest {
1009            write_stream,
1010            offset: None,
1011            trace_id: Uuid::new_v4().hyphenated().to_string(),
1012            missing_value_interpretations: HashMap::default(),
1013            rows: Some(row),
1014            default_missing_value_interpretation: MissingValueInterpretation::DefaultValue as i32,
1015        };
1016        self.request_sender
1017            .send(append_req)
1018            .map_err(|e| SinkError::BigQuery(e.into()))?;
1019        Ok(())
1020    }
1021
1022    fn bigquery_grpc_auth_config() -> google_cloud_auth::project::Config<'static> {
1023        let mut auth_config = google_cloud_auth::project::Config::default();
1024        auth_config = auth_config.with_audience(gcloud_bigquery::grpc::apiv1::conn_pool::AUDIENCE);
1025        auth_config = auth_config.with_scopes(&gcloud_bigquery::grpc::apiv1::conn_pool::SCOPES);
1026        auth_config
1027    }
1028}
1029
1030fn build_protobuf_descriptor_pool(desc: &DescriptorProto) -> Result<prost_reflect::DescriptorPool> {
1031    let file_descriptor = FileDescriptorProto {
1032        message_type: vec![desc.clone()],
1033        name: Some("bigquery".to_owned()),
1034        ..Default::default()
1035    };
1036
1037    prost_reflect::DescriptorPool::from_file_descriptor_set(FileDescriptorSet {
1038        file: vec![file_descriptor],
1039    })
1040    .context("failed to build descriptor pool")
1041    .map_err(SinkError::BigQuery)
1042}
1043
1044fn build_protobuf_schema<'a>(
1045    fields: impl Iterator<Item = (&'a str, &'a DataType)>,
1046    name: String,
1047) -> Result<DescriptorProto> {
1048    let mut proto = DescriptorProto {
1049        name: Some(name),
1050        ..Default::default()
1051    };
1052    let mut struct_vec = vec![];
1053    let field_vec = fields
1054        .enumerate()
1055        .map(|(index, (name, data_type))| {
1056            let (field, des_proto) =
1057                build_protobuf_field(data_type, (index + 1) as i32, name.to_owned())?;
1058            if let Some(sv) = des_proto {
1059                struct_vec.push(sv);
1060            }
1061            Ok(field)
1062        })
1063        .collect::<Result<Vec<_>>>()?;
1064    proto.field = field_vec;
1065    proto.nested_type = struct_vec;
1066    Ok(proto)
1067}
1068
1069fn build_protobuf_field(
1070    data_type: &DataType,
1071    index: i32,
1072    name: String,
1073) -> Result<(FieldDescriptorProto, Option<DescriptorProto>)> {
1074    let mut field = FieldDescriptorProto {
1075        name: Some(name.clone()),
1076        number: Some(index),
1077        ..Default::default()
1078    };
1079    match data_type {
1080        DataType::Boolean => field.r#type = Some(field_descriptor_proto::Type::Bool.into()),
1081        DataType::Int32 => field.r#type = Some(field_descriptor_proto::Type::Int32.into()),
1082        DataType::Int16 | DataType::Int64 => {
1083            field.r#type = Some(field_descriptor_proto::Type::Int64.into())
1084        }
1085        DataType::Float64 => field.r#type = Some(field_descriptor_proto::Type::Double.into()),
1086        DataType::Decimal => field.r#type = Some(field_descriptor_proto::Type::String.into()),
1087        DataType::Date => field.r#type = Some(field_descriptor_proto::Type::Int32.into()),
1088        DataType::Varchar => field.r#type = Some(field_descriptor_proto::Type::String.into()),
1089        DataType::Time => field.r#type = Some(field_descriptor_proto::Type::String.into()),
1090        DataType::Timestamp => field.r#type = Some(field_descriptor_proto::Type::String.into()),
1091        DataType::Timestamptz => field.r#type = Some(field_descriptor_proto::Type::String.into()),
1092        DataType::Interval => field.r#type = Some(field_descriptor_proto::Type::String.into()),
1093        DataType::Struct(s) => {
1094            field.r#type = Some(field_descriptor_proto::Type::Message.into());
1095            let name = format!("Struct{}", name);
1096            let sub_proto = build_protobuf_schema(s.iter(), name.clone())?;
1097            field.type_name = Some(name);
1098            return Ok((field, Some(sub_proto)));
1099        }
1100        DataType::List(l) => {
1101            let (mut field, proto) = build_protobuf_field(l.elem(), index, name)?;
1102            field.label = Some(field_descriptor_proto::Label::Repeated.into());
1103            return Ok((field, proto));
1104        }
1105        DataType::Bytea => field.r#type = Some(field_descriptor_proto::Type::Bytes.into()),
1106        DataType::Jsonb => field.r#type = Some(field_descriptor_proto::Type::String.into()),
1107        DataType::Variant => {
1108            return Err(SinkError::BigQuery(anyhow::anyhow!(
1109                "Don't support Variant"
1110            )));
1111        }
1112        DataType::Serial => field.r#type = Some(field_descriptor_proto::Type::Int64.into()),
1113        DataType::Float32 | DataType::Int256 => {
1114            return Err(SinkError::BigQuery(anyhow::anyhow!(
1115                "Don't support Float32 and Int256"
1116            )));
1117        }
1118        DataType::Map(_) => return Err(SinkError::BigQuery(anyhow::anyhow!("Don't support Map"))),
1119        DataType::Vector(_) => {
1120            return Err(SinkError::BigQuery(anyhow::anyhow!("Don't support Vector")));
1121        }
1122    }
1123    Ok((field, None))
1124}
1125
1126#[cfg(test)]
1127mod test {
1128
1129    use std::assert_matches;
1130    use std::collections::{BTreeMap, HashMap};
1131
1132    use gcloud_gax::conn::Environment;
1133    use gcloud_googleapis::cloud::bigquery::storage::v1::append_rows_request::{
1134        ProtoData, Rows as AppendRowsRequestRows,
1135    };
1136    use prost_reflect::{DynamicMessage, ReflectMessage};
1137    use risingwave_common::array::StreamChunk;
1138    use risingwave_common::array::stream_chunk::StreamChunkTestExt as _;
1139    use risingwave_common::catalog::{Field, Schema};
1140    use risingwave_common::types::{DataType, StructType};
1141    use tokio::sync::mpsc;
1142
1143    use crate::allow_alter_on_fly_fields::check_sink_allow_alter_on_fly_fields;
1144    use crate::connector_common::AwsAuthProps;
1145    use crate::sink::big_query::{
1146        BIGQUERY_SINK, BigQueryCommon, BigQueryConfig, BigQuerySink, BigQuerySinkWriter,
1147        CHANGE_SEQUENCE_NUMBER, CHANGE_TYPE, ChangeSequenceClock, StorageWriterClient,
1148        build_protobuf_descriptor_pool, build_protobuf_schema,
1149    };
1150    use crate::sink::{SINK_TYPE_APPEND_ONLY, Sink, validate_sink_unknown_fields};
1151
1152    #[tokio::test]
1153    async fn test_type_check() {
1154        let big_query_type_string = "ARRAY<STRUCT<v1 ARRAY<INT64>, v2 STRUCT<v1 INT64, v2 INT64>>>";
1155        let rw_datatype = DataType::list(DataType::Struct(StructType::new(vec![
1156            ("v1".to_owned(), DataType::Int64.list()),
1157            (
1158                "v2".to_owned(),
1159                DataType::Struct(StructType::new(vec![
1160                    ("v1".to_owned(), DataType::Int64),
1161                    ("v2".to_owned(), DataType::Int64),
1162                ])),
1163            ),
1164        ])));
1165        assert_eq!(
1166            BigQuerySink::get_string_and_check_support_from_datatype(&rw_datatype).unwrap(),
1167            big_query_type_string
1168        );
1169    }
1170
1171    #[tokio::test]
1172    async fn test_schema_check() {
1173        let schema = Schema {
1174            fields: vec![
1175                Field::with_name(DataType::Int64, "v1"),
1176                Field::with_name(DataType::Float64, "v2"),
1177                Field::with_name(
1178                    DataType::list(DataType::Struct(StructType::new(vec![
1179                        ("v1".to_owned(), DataType::Int64.list()),
1180                        (
1181                            "v3".to_owned(),
1182                            DataType::Struct(StructType::new(vec![
1183                                ("v1".to_owned(), DataType::Int64),
1184                                ("v2".to_owned(), DataType::Int64),
1185                            ])),
1186                        ),
1187                    ]))),
1188                    "v3",
1189                ),
1190            ],
1191        };
1192        let fields = schema
1193            .fields()
1194            .iter()
1195            .map(|f| (f.name.as_str(), &f.data_type));
1196        let desc = build_protobuf_schema(fields, "t1".to_owned()).unwrap();
1197        let pool = build_protobuf_descriptor_pool(&desc).unwrap();
1198        let t1_message = pool.get_message_by_name("t1").unwrap();
1199        assert_matches!(
1200            t1_message.get_field_by_name("v1").unwrap().kind(),
1201            prost_reflect::Kind::Int64
1202        );
1203        assert_matches!(
1204            t1_message.get_field_by_name("v2").unwrap().kind(),
1205            prost_reflect::Kind::Double
1206        );
1207        assert_matches!(
1208            t1_message.get_field_by_name("v3").unwrap().kind(),
1209            prost_reflect::Kind::Message(_)
1210        );
1211
1212        let v3_message = pool.get_message_by_name("t1.Structv3").unwrap();
1213        assert_matches!(
1214            v3_message.get_field_by_name("v1").unwrap().kind(),
1215            prost_reflect::Kind::Int64
1216        );
1217        assert!(v3_message.get_field_by_name("v1").unwrap().is_list());
1218
1219        let v3_v3_message = pool.get_message_by_name("t1.Structv3.Structv3").unwrap();
1220        assert_matches!(
1221            v3_v3_message.get_field_by_name("v1").unwrap().kind(),
1222            prost_reflect::Kind::Int64
1223        );
1224        assert_matches!(
1225            v3_v3_message.get_field_by_name("v2").unwrap().kind(),
1226            prost_reflect::Kind::Int64
1227        );
1228    }
1229
1230    #[test]
1231    fn test_decimal_type_family_compatibility() {
1232        assert!(BigQuerySink::is_decimal_type_compatible("NUMERIC"));
1233        assert!(BigQuerySink::is_decimal_type_compatible("numeric(31, 2)"));
1234        assert!(BigQuerySink::is_decimal_type_compatible("BIGNUMERIC"));
1235        assert!(BigQuerySink::is_decimal_type_compatible(
1236            "bignumeric(35, 12)"
1237        ));
1238        assert!(!BigQuerySink::is_decimal_type_compatible("STRING"));
1239    }
1240
1241    #[test]
1242    fn test_decimal_schema_check_accepts_parameterized_numeric_types() {
1243        let sink = BigQuerySink {
1244            config: BigQueryConfig {
1245                common: BigQueryCommon {
1246                    local_path: None,
1247                    s3_path: None,
1248                    project: "project".to_owned(),
1249                    dataset: "dataset".to_owned(),
1250                    table: "table".to_owned(),
1251                    auto_create: false,
1252                    credentials: None,
1253                },
1254                aws_auth_props: AwsAuthProps {
1255                    region: None,
1256                    endpoint: None,
1257                    access_key: None,
1258                    secret_key: None,
1259                    session_token: None,
1260                    arn: None,
1261                    external_id: None,
1262                    profile: None,
1263                    msk_signer_timeout_sec: None,
1264                },
1265                r#type: "append-only".to_owned(),
1266                change_sequence_number: false,
1267                unknown_fields: Default::default(),
1268            },
1269            schema: Schema {
1270                fields: vec![Field::with_name(DataType::Decimal, "capitalizedcost")],
1271            },
1272            pk_indices: vec![],
1273            is_append_only: true,
1274        };
1275
1276        sink.check_column_name_and_type(HashMap::from([(
1277            "capitalizedcost".to_owned(),
1278            "NUMERIC(31, 2)".to_owned(),
1279        )]))
1280        .unwrap();
1281
1282        sink.check_column_name_and_type(HashMap::from([(
1283            "capitalizedcost".to_owned(),
1284            "BIGNUMERIC(35, 12)".to_owned(),
1285        )]))
1286        .unwrap();
1287    }
1288
1289    fn sink_properties(sink_type: &str, extra: &[(&str, &str)]) -> BTreeMap<String, String> {
1290        [
1291            ("bigquery.project", "project"),
1292            ("bigquery.dataset", "dataset"),
1293            ("bigquery.table", "table"),
1294            ("type", sink_type),
1295        ]
1296        .iter()
1297        .chain(extra)
1298        .map(|&(k, v)| (k.to_owned(), v.to_owned()))
1299        .collect()
1300    }
1301
1302    fn sink_config(sink_type: &str, extra: &[(&str, &str)]) -> BigQueryConfig {
1303        BigQueryConfig::from_btreemap(sink_properties(sink_type, extra)).unwrap()
1304    }
1305
1306    #[test]
1307    fn test_change_sequence_number_option() {
1308        // `ALTER SINK` passes the merged properties and the altered ones.
1309        let alter = |value: &str| {
1310            let alter_props = BTreeMap::from([(
1311                "bigquery.change_sequence_number".to_owned(),
1312                value.to_owned(),
1313            )]);
1314            BigQuerySink::validate_alter_config_change(
1315                &sink_properties("upsert", &[("bigquery.change_sequence_number", value)]),
1316                &alter_props,
1317            )
1318        };
1319        assert!(!sink_config("upsert", &[]).change_sequence_number);
1320        for (value, expected) in [("true", true), ("false", false)] {
1321            let config = sink_config("upsert", &[("bigquery.change_sequence_number", value)]);
1322            assert_eq!(config.change_sequence_number, expected);
1323            validate_sink_unknown_fields(&config).unwrap();
1324            alter(value).unwrap();
1325        }
1326        alter("yes").unwrap_err();
1327        check_sink_allow_alter_on_fly_fields(
1328            BIGQUERY_SINK,
1329            &["bigquery.change_sequence_number".to_owned()],
1330        )
1331        .unwrap();
1332    }
1333
1334    /// Writes `chunks` in order and decodes the rows of the sent requests.
1335    fn write_and_decode(config: BigQueryConfig, chunks: Vec<StreamChunk>) -> Vec<DynamicMessage> {
1336        let schema = Schema {
1337            fields: vec![
1338                Field::with_name(DataType::Int64, "id"),
1339                Field::with_name(DataType::Varchar, "v"),
1340            ],
1341        };
1342        let (request_sender, mut request_rx) = mpsc::unbounded_channel();
1343        let client = StorageWriterClient {
1344            environment: Environment::Emulator(String::new()),
1345            request_sender,
1346        };
1347        let is_append_only = config.r#type == SINK_TYPE_APPEND_ONLY;
1348        let mut writer =
1349            BigQuerySinkWriter::with_client(config, schema, vec![0], is_append_only, client)
1350                .unwrap();
1351        for chunk in chunks {
1352            writer.write_chunk(chunk).unwrap();
1353        }
1354
1355        let mut rows = vec![];
1356        while let Ok(request) = request_rx.try_recv() {
1357            let Some(AppendRowsRequestRows::ProtoRows(ProtoData {
1358                writer_schema: Some(writer_schema),
1359                rows: Some(proto_rows),
1360            })) = request.rows
1361            else {
1362                panic!("expected proto rows");
1363            };
1364            let pool =
1365                build_protobuf_descriptor_pool(&writer_schema.proto_descriptor.unwrap()).unwrap();
1366            let message = pool.get_message_by_name("table").unwrap();
1367            rows.extend(
1368                proto_rows
1369                    .serialized_rows
1370                    .iter()
1371                    .map(|row| DynamicMessage::decode(message.clone(), row.as_slice()).unwrap()),
1372            );
1373        }
1374        rows
1375    }
1376
1377    #[test]
1378    fn test_oversized_first_row_not_sent_as_empty_batch() {
1379        let schema = Schema {
1380            fields: vec![
1381                Field::with_name(DataType::Int64, "id"),
1382                Field::with_name(DataType::Varchar, "v"),
1383            ],
1384        };
1385        let (request_sender, mut request_rx) = mpsc::unbounded_channel();
1386        let client = StorageWriterClient {
1387            environment: Environment::Emulator(String::new()),
1388            request_sender,
1389        };
1390        let mut writer = BigQuerySinkWriter::with_client(
1391            sink_config("upsert", &[]),
1392            schema,
1393            vec![0],
1394            false,
1395            client,
1396        )
1397        .unwrap();
1398
1399        let big = "x".repeat(9 * 1024 * 1024);
1400        let small = "x".repeat(4 * 1024 * 1024 + 512 * 1024);
1401        let chunk = StreamChunk::from_pretty(&format!(
1402            " I T
1403            + 1 {big}
1404            + 2 {small}
1405            + 3 {small}"
1406        ));
1407        let batch_num = writer.write_chunk(chunk).unwrap();
1408
1409        let mut batch_row_counts = vec![];
1410        while let Ok(request) = request_rx.try_recv() {
1411            let Some(AppendRowsRequestRows::ProtoRows(ProtoData {
1412                rows: Some(proto_rows),
1413                ..
1414            })) = request.rows
1415            else {
1416                panic!("expected proto rows");
1417            };
1418            batch_row_counts.push(proto_rows.serialized_rows.len());
1419        }
1420        assert_eq!(batch_num, 3);
1421        assert_eq!(batch_row_counts, vec![1, 1, 1]);
1422    }
1423
1424    #[test]
1425    fn test_change_sequence_clock() {
1426        let clock = ChangeSequenceClock::new();
1427        assert_eq!(clock.reserve_at(100, 3), (100, 0));
1428        // The clock has not moved past the last physical time, or has moved back.
1429        assert_eq!(clock.reserve_at(100, 2), (100, 3));
1430        assert_eq!(clock.reserve_at(90, 1), (100, 5));
1431        assert_eq!(clock.reserve_at(101, 1), (101, 0));
1432    }
1433
1434    #[test]
1435    fn test_write_change_sequence_number() {
1436        let chunks = || {
1437            vec![
1438                StreamChunk::from_pretty(
1439                    "  I T
1440                    +  1 a
1441                    U- 1 a
1442                    U+ 1 b",
1443                ),
1444                StreamChunk::from_pretty(
1445                    " I T
1446                    - 1 b",
1447                ),
1448            ]
1449        };
1450        let field = |row: &DynamicMessage, name: &str| {
1451            row.get_field_by_name(name)
1452                .unwrap()
1453                .as_str()
1454                .unwrap()
1455                .to_owned()
1456        };
1457
1458        let rows = write_and_decode(
1459            sink_config("upsert", &[("bigquery.change_sequence_number", "true")]),
1460            chunks(),
1461        );
1462        let change_types: Vec<_> = rows.iter().map(|row| field(row, CHANGE_TYPE)).collect();
1463        assert_eq!(change_types, ["UPSERT", "UPSERT", "DELETE"]);
1464        let sequence_numbers: Vec<_> = rows
1465            .iter()
1466            .map(|row| {
1467                let sequence_number = field(row, CHANGE_SEQUENCE_NUMBER);
1468                let (physical, logical) = sequence_number.split_once('/').unwrap();
1469                (
1470                    u64::from_str_radix(physical, 16).unwrap(),
1471                    u64::from_str_radix(logical, 16).unwrap(),
1472                )
1473            })
1474            .collect();
1475        assert!(
1476            sequence_numbers.windows(2).all(|pair| pair[0] < pair[1]),
1477            "{sequence_numbers:?}"
1478        );
1479
1480        // Off by default: upsert rows carry only the change type.
1481        let rows = write_and_decode(sink_config("upsert", &[]), chunks());
1482        let change_types: Vec<_> = rows.iter().map(|row| field(row, CHANGE_TYPE)).collect();
1483        assert_eq!(change_types, ["UPSERT", "UPSERT", "DELETE"]);
1484        assert!(
1485            rows[0]
1486                .descriptor()
1487                .get_field_by_name(CHANGE_SEQUENCE_NUMBER)
1488                .is_none()
1489        );
1490
1491        let rows = write_and_decode(
1492            sink_config(
1493                "append-only",
1494                &[("bigquery.change_sequence_number", "true")],
1495            ),
1496            chunks(),
1497        );
1498        for name in [CHANGE_TYPE, CHANGE_SEQUENCE_NUMBER] {
1499            assert!(rows[0].descriptor().get_field_by_name(name).is_none());
1500        }
1501    }
1502}