Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sink): add config auto_create for BigQuery #17393

Merged
merged 7 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 121 additions & 10 deletions src/connector/src/sink/big_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ use std::sync::Arc;

use anyhow::anyhow;
use async_trait::async_trait;
use gcp_bigquery_client::error::BQError;
use gcp_bigquery_client::model::query_request::QueryRequest;
use gcp_bigquery_client::model::table::Table;
use gcp_bigquery_client::model::table_field_schema::TableFieldSchema;
use gcp_bigquery_client::model::table_schema::TableSchema;
use gcp_bigquery_client::Client;
use google_cloud_bigquery::grpc::apiv1::bigquery_client::StreamingWriteClient;
use google_cloud_bigquery::grpc::apiv1::conn_pool::{WriteConnectionManager, DOMAIN};
Expand All @@ -39,10 +43,11 @@ use prost_types::{
};
use risingwave_common::array::{Op, StreamChunk};
use risingwave_common::buffer::Bitmap;
use risingwave_common::catalog::Schema;
use risingwave_common::catalog::{Field, Schema};
use risingwave_common::types::DataType;
use serde_derive::Deserialize;
use serde_with::{serde_as, DisplayFromStr};
use simd_json::prelude::ArrayTrait;
use url::Url;
use uuid::Uuid;
use with_options::WithOptions;
Expand Down Expand Up @@ -83,6 +88,8 @@ pub struct BigQueryCommon {
#[serde(rename = "bigquery.retry_times", default = "default_retry_times")]
#[serde_as(as = "DisplayFromStr")]
pub retry_times: usize,
#[serde(rename = "bigquery.auto_create_table", default)] // default false
pub auto_create_table: bool,
jetjinser marked this conversation as resolved.
Show resolved Hide resolved
}

fn default_max_batch_rows() -> usize {
Expand Down Expand Up @@ -255,6 +262,79 @@ impl BigQuerySink {
))),
}
}

fn map_field(rw_field: &Field) -> Result<TableFieldSchema> {
let tfs = match &rw_field.data_type {
DataType::Boolean => TableFieldSchema::bool(&rw_field.name),
DataType::Int16 | DataType::Int32 | DataType::Int64 | DataType::Serial => {
TableFieldSchema::integer(&rw_field.name)
}
DataType::Float32 => {
return Err(SinkError::BigQuery(anyhow::anyhow!(
"Bigquery cannot support real"
)))
}
DataType::Float64 => TableFieldSchema::float(&rw_field.name),
DataType::Decimal => TableFieldSchema::numeric(&rw_field.name),
DataType::Date => TableFieldSchema::date(&rw_field.name),
DataType::Varchar => TableFieldSchema::string(&rw_field.name),
DataType::Time => TableFieldSchema::time(&rw_field.name),
DataType::Timestamp => TableFieldSchema::date_time(&rw_field.name),
DataType::Timestamptz => TableFieldSchema::timestamp(&rw_field.name),
DataType::Interval => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems to be supported, If it is not possible, please also set what is written below as not supported

Copy link
Contributor Author

@jetjinser jetjinser Jun 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should indeed be unsupported for now: https://cloud.google.com/bigquery/docs/schemas#standard_sql_data_types. (no interval here, in pre-ga)
What needs to be added in the error message?

Copy link
Contributor

@xxhZs xxhZs Jun 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested it before and it works, you can retest it, if it doesn't work, please disable interval in the code elsewhere
doc is in https://cloud.google.com/bigquery/docs/write-api?hl=zh-cn

Copy link
Contributor Author

@jetjinser jetjinser Jun 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does support it, but it is not a stable feature yet.
In addition, the sdk FieldType have no Interval. It's used to construct Table that table().create() would use.
I think we can let it keep the unsupported error? Panic when validate failed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to change it in get_string_and_check_support_from_datatype?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

About Interval?
Unlike the case of map_field, which is used to create a BigQuery table, we can avoid actively using unstable type Interval; the return value of get_string_and_check_support_from_datatype is used to validate types of BigQuery table columns. If a column is indeed an Interval type, I don't think we have any reason to refuse?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it, thanks for the explanation. Would you mind adding the explanations here into the code comment?

return Err(SinkError::BigQuery(anyhow::anyhow!(
"Bigquery cannot support Interval"
)))
}
DataType::Struct(_) => {
let mut sub_fields = Vec::with_capacity(rw_field.sub_fields.len());
for rw_field in &rw_field.sub_fields {
let field = Self::map_field(rw_field)?;
sub_fields.push(field)
}
TableFieldSchema::record(&rw_field.name, sub_fields)
}
DataType::List(dt) => {
let inner_field = Self::map_field(&Field::with_name(*dt.clone(), &rw_field.name))?;
TableFieldSchema {
mode: Some("REPEATED".to_string()),
..inner_field
}
}

DataType::Bytea => TableFieldSchema::bytes(&rw_field.name),
DataType::Jsonb => TableFieldSchema::json(&rw_field.name),
DataType::Int256 => {
return Err(SinkError::BigQuery(anyhow::anyhow!(
"Bigquery cannot support Int256"
)))
}
};
Ok(tfs)
}

async fn create_table(
&self,
client: &Client,
project_id: &str,
dataset_id: &str,
table_id: &str,
fields: &Vec<Field>,
) -> Result<Table> {
let dataset = client
.dataset()
.get(project_id, dataset_id)
.await
.map_err(|e| SinkError::BigQuery(e.into()))?;
let fields: Vec<_> = fields.iter().map(Self::map_field).collect::<Result<_>>()?;
let table = Table::from_dataset(&dataset, table_id, TableSchema::new(fields));

client
.table()
.create(table)
.await
.map_err(|e| SinkError::BigQuery(e.into()))
}
}

impl Sink for BigQuerySink {
Expand Down Expand Up @@ -284,16 +364,47 @@ impl Sink for BigQuerySink {
.common
.build_client(&self.config.aws_auth_props)
.await?;
let BigQueryCommon {
project: project_id,
dataset: dataset_id,
table: table_id,
..
} = &self.config.common;

if self.config.common.auto_create_table {
match client
.table()
.get(project_id, dataset_id, table_id, None)
.await
{
Err(BQError::ResponseError { error: _ }) => {
// early return: no need to query schema to check column and type
return self
.create_table(
&client,
project_id,
dataset_id,
table_id,
&self.schema.fields,
)
.await
.map(|_| ());
}
Err(e) => return Err(SinkError::BigQuery(e.into())),
_ => {}
}
}

let mut rs = client
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When auto_create_table=true, it seems that there is no need to query the schema again

.job()
.query(
&self.config.common.project,
QueryRequest::new(format!(
"SELECT column_name, data_type FROM `{}.{}.INFORMATION_SCHEMA.COLUMNS` WHERE table_name = '{}'"
,self.config.common.project,self.config.common.dataset,self.config.common.table,
)),
)
.await.map_err(|e| SinkError::BigQuery(e.into()))?;
.job()
.query(
&self.config.common.project,
QueryRequest::new(format!(
"SELECT column_name, data_type FROM `{}.{}.INFORMATION_SCHEMA.COLUMNS` WHERE table_name = '{}'",
project_id, dataset_id, table_id,
)),
).await.map_err(|e| SinkError::BigQuery(e.into()))?;

let mut big_query_schema = HashMap::default();
while rs.next_row() {
big_query_schema.insert(
Expand Down
4 changes: 4 additions & 0 deletions src/connector/with_options_sink.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ BigQueryConfig:
field_type: usize
required: false
default: '5'
- name: bigquery.auto_create_table
field_type: bool
required: false
default: Default::default
- name: aws.region
field_type: String
required: false
Expand Down
Loading