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

Added uploadTypedRows to BigQuery client #5218

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
3 changes: 2 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -814,9 +814,10 @@ lazy val `scio-google-cloud-platform` = project
"org.apache.beam" % "beam-sdks-java-extensions-google-cloud-platform-core" % beamVersion,
"org.apache.beam" % "beam-sdks-java-io-google-cloud-platform" % beamVersion,
"org.apache.beam" % "beam-vendor-guava-32_1_2-jre" % beamVendorVersion,
"org.apache.commons" % "commons-lang3" % commonsLang3Version,
"org.slf4j" % "slf4j-api" % slf4jVersion,
"com.google.cloud" % "google-cloud-storage" % googleCloudStorageVersion,
// test
"com.google.cloud" % "google-cloud-storage" % googleCloudStorageVersion % Test,
"com.spotify" %% "magnolify-cats" % magnolifyVersion % Test,
"com.spotify" %% "magnolify-scalacheck" % magnolifyVersion % Test,
"org.hamcrest" % "hamcrest" % hamcrestVersion % Test,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import com.google.auth.http.HttpCredentialsAdapter
import com.google.auth.oauth2.{GoogleCredentials, ImpersonatedCredentials}
import com.google.cloud.bigquery.storage.v1beta1.{BigQueryStorageClient, BigQueryStorageSettings}
import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer
import com.google.cloud.storage.{Storage, StorageOptions}
import com.spotify.scio.bigquery.{Table => STable}
import com.spotify.scio.bigquery.client.BigQuery.Client
import com.spotify.scio.bigquery.client.BigQueryConfig.ImpersonationInfo
Expand Down Expand Up @@ -331,5 +332,8 @@ object BigQuery {
.build()
BigQueryStorageClient.create(settings)
}

lazy val blobStorage: Storage =
StorageOptions.newBuilder.setProjectId(project).setCredentials(_credentials).build.getService
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,22 @@
package com.spotify.scio.bigquery.client

import com.google.api.services.bigquery.model._
import com.google.cloud.storage.{BlobId, BlobInfo, Storage}
import com.spotify.scio.bigquery.client.BigQuery.Client
import com.spotify.scio.bigquery.{BigQueryUtil, CREATE_IF_NEEDED, WRITE_APPEND}
import com.spotify.scio.bigquery.types.BigQueryType.HasAnnotation
import com.spotify.scio.bigquery.{BigQueryType, BigQueryUtil, CREATE_IF_NEEDED, WRITE_APPEND}
import org.apache.avro.file.DataFileWriter
import org.apache.avro.generic.{GenericDatumWriter, GenericRecord}
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.{CreateDisposition, WriteDisposition}
import org.apache.beam.sdk.io.gcp.{bigquery => bq}
import org.apache.commons.lang3.RandomStringUtils
import org.slf4j.LoggerFactory

import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import scala.annotation.nowarn
import scala.jdk.CollectionConverters._
import scala.util.Try
import scala.reflect.runtime.universe.TypeTag

private[client] object LoadOps {
private val Logger = LoggerFactory.getLogger(this.getClass)
Expand Down Expand Up @@ -119,6 +126,56 @@ final private[client] class LoadOps(client: Client, jobService: JobOps) {
location = location
)

/**
* Upload List of rows to Cloud Storage as Avro file and load to BigQuery table. Note that element
* type `T` must be annotated with [[BigQueryType]].
*/
def uploadTypedRows[T <: HasAnnotation: TypeTag](
Copy link
Contributor

Choose a reason for hiding this comment

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

IMHO this naming can be simplified. Other APIs here do not have the upload prefix.
Usage will be from BigQuery with bq.load.uploadTypeRows.

I think this should be named

Suggested change
def uploadTypedRows[T <: HasAnnotation: TypeTag](
def typedRows[T <: HasAnnotation: TypeTag](

tableSpec: String,
rows: List[T],
tempLocation: String,
Copy link
Contributor

Choose a reason for hiding this comment

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

Since this is temp, shouldn't we clean if afterward ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was thinking about bucket retention policy, but yeah, deleting it would be more optimal

Copy link
Contributor Author

Choose a reason for hiding this comment

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

on the other hand if I do:

  avro(
        List(blobId.toGsUtilUri),
        tableSpec,
        schema = Some(bqt.schema),
        createDisposition = createDisposition,
        writeDisposition = writeDisposition
  )

  storage.delete(blobId)

I am not confident that avro is fully synchronous and BQ doesn't read that file on the background

Copy link
Contributor

Choose a reason for hiding this comment

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

execute contains jobService.waitForJobs(loadJob) so I think this is fine.

I'm wondering also if we should create a SaveOps to allow saving some file formats (avro/json)

writeDisposition: WriteDisposition = WriteDisposition.WRITE_APPEND,
createDisposition: CreateDisposition = CreateDisposition.CREATE_IF_NEEDED
): Try[TableReference] = {
val bqt = BigQueryType[T]

Try {
val out = new ByteArrayOutputStream()
val datumWriter = new GenericDatumWriter[GenericRecord]()
val dataFileWriter = new DataFileWriter[GenericRecord](datumWriter)
try {
dataFileWriter.create(bqt.avroSchema, out)
rows.foreach { row =>
dataFileWriter.append(bqt.toAvro(row))
}
} finally {
dataFileWriter.close()
}

val blobId =
BlobId.fromGsUtilUri(
s"${tempLocation.stripSuffix("/")}/upload_${RandomStringUtils.randomAlphanumeric(10)}.avro"
)
val blobInfo = BlobInfo.newBuilder(blobId).build
client.blobStorage.createFrom(
blobInfo,
new ByteArrayInputStream(out.toByteArray),
Storage.BlobWriteOption.doesNotExist(),
Storage.BlobWriteOption.crc32cMatch()
clairemcginty marked this conversation as resolved.
Show resolved Hide resolved
)

blobId
}.flatMap { blobId =>
avro(
List(blobId.toGsUtilUri),
tableSpec,
schema = Some(bqt.schema),
createDisposition = createDisposition,
writeDisposition = writeDisposition
)
}
}

@nowarn("msg=private default argument in class LoadOps is never used")
private def execute(
sources: List[String],
Expand Down
Loading