From 449ae7e940b0e8920a4a3013397a5d9ef02e0236 Mon Sep 17 00:00:00 2001 From: Anthony Lazzaro <93217007+ant-laz@users.noreply.github.com> Date: Wed, 26 Feb 2025 11:03:01 +0000 Subject: [PATCH 1/3] Adds an example of writing to spanner via JDBC from Apache Spark on Dataproc This commits adds an example of using Apache Spark (on Cloud Dataproc) to write to Cloud Spanner via JDBC in Scala. There is no other public documentation or examples of how to do this. As a result, this example will help customers. --- examples/dataproc-spanner/jdbc/LICENCE | 175 ++++++++++++++++ examples/dataproc-spanner/jdbc/README.md | 198 ++++++++++++++++++ .../dataproc-spanner/jdbc/build.properties | 1 + examples/dataproc-spanner/jdbc/build.sbt | 22 ++ .../jdbc/project/build.properties | 1 + .../jdbc/src/main/META-INF/MANIFEST.MF | 2 + .../jdbc/src/main/scala/Main.scala | 61 ++++++ .../jdbc/src/main/scala/Pipeline.scala | 83 ++++++++ .../src/main/scala/SpannerJdbcDialect.scala | 75 +++++++ 9 files changed, 618 insertions(+) create mode 100644 examples/dataproc-spanner/jdbc/LICENCE create mode 100644 examples/dataproc-spanner/jdbc/README.md create mode 100644 examples/dataproc-spanner/jdbc/build.properties create mode 100644 examples/dataproc-spanner/jdbc/build.sbt create mode 100644 examples/dataproc-spanner/jdbc/project/build.properties create mode 100644 examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF create mode 100644 examples/dataproc-spanner/jdbc/src/main/scala/Main.scala create mode 100644 examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala create mode 100644 examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala diff --git a/examples/dataproc-spanner/jdbc/LICENCE b/examples/dataproc-spanner/jdbc/LICENCE new file mode 100644 index 0000000000..19dc35b243 --- /dev/null +++ b/examples/dataproc-spanner/jdbc/LICENCE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/examples/dataproc-spanner/jdbc/README.md b/examples/dataproc-spanner/jdbc/README.md new file mode 100644 index 0000000000..d664f57325 --- /dev/null +++ b/examples/dataproc-spanner/jdbc/README.md @@ -0,0 +1,198 @@ +## BigQuery to Spanner using Apache Spark in Scala + +### Why create this repo ? + + * Google Cloud customers need to move data from BigQuery to Spanner using Apache Spark in Scala + * Dataproc [templates](https://github.com/GoogleCloudPlatform/dataproc-templates) cannot help as they are written in Python & Java + * The Apache Spark SQL [connector](https://github.com/GoogleCloudDataproc/spark-spanner-connector) for Google Cloud Spanner only supports reads not writes + +### Why is this a hard problem ? + +**1. data type mapping** + +The [spark-bigquery-connector](https://github.com/GoogleCloudDataproc/spark-bigquery-connector?tab=readme-ov-file#data-types) reads from BigQuery and converts BigQuery Google SQL Types into SparkSQL Types. + +Apahce Spark JDBC is used to write to spanner, converting SparkSQL types into Spanner GoogleSQL types. + +For some BigQuery GoogleSQL types, there is not equivalent in SparkSQL & Spanner GoogleSQL. + +| BigQuery GoogleSQL Type | SparkSQL Type | Spanner GoogleSQL Type |Notes | +|----------|---------------|--------------|--------------| +| [INT64](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#integer_types) | LongType | [INT64](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#integer_types) | | +| [FLOAT64](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#floating_point_types) | DoubleType | [FLOAT64](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#floating_point_types) | | +| [NUMERIC](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#decimal_types) | DecimalType | [NUMERIC](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#decimal_types) | | +| [BIGNUMERIC](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#decimal_types) | DecimalType | [NUMERIC](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#decimal_types) | Spark & Spanner have no Big Numeric support | +| [BOOL](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#boolean_type) | BooleanType | [BOOL](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#boolean_type) | | +| [STRING](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#string_type) | StringType | [STRING(MAX)](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#string_type) | | +| [DATE](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#date_type) | DateType |[DATE](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#date_type) | | +| [DATETIME](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#datetime_type) | StringType | [STRING(MAX)](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#string_type) | Spark & Spanner have no DATETIME type| +| [TIME](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#time_type) | LongType | [INT64](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#integer_types) | Spark & Spanner have no TIME type| +| [TIMESTAMP](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#timestamp_type) | TimestampType |[TIMESTAMP](https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#timestamp_type) | | + +**2. no jdbc dialect for spanner** + +When using Apache Spark JDBC in Scala, there are pre-built SQL [dialects](https://github.com/apache/spark/tree/071feabbd4325504332679dfa620bc5ee4359370/sql/core/src/main/scala/org/apache/spark/sql/jdbc) for known databases: + +* Teradata +* Postgres +* Oracle +* MySQL +* MsSqlServer +* H2 +* DB2 + +However, there is no pre-built SQL dialect for Spanner. + +When using Apache Spark JDBC in Scala to read or write with Spanner, the default JDBC SQL dialect is used which is incompatible with Spanner. + +For this reason a new custom SQL dialect had to be written for Spanner, for use with Apache Spark JDBC in Scala. + +### How to build this code & use this template ? + +1. [Dataproc2.2](https://cloud.google.com/dataproc/docs/concepts/versioning/dataproc-release-2.2) images are the target execution environment +2. Given dataproc image, need Java JDK 11 +3. Given dataproc image, need Scala 2.12.18 +4. Also need sbt +5. Build a JAR of this code by running ```sbt package``` from root of this repo. We call this the ```APP_JAR``` +6. upload JAR of this code to Google Cloud Storage +7. upload a JAR of the Spanner JDBC [driver](https://cloud.google.com/spanner/docs/jdbc-drivers) to Google Cloud Storage. We call this the ```SPANNER_JDBC_JAR``` +8. If it does not exist, create a Spanner table with schema equal to source BigQuery table +9. Sumit a job to your dataproc cluster to move data from BigQuery to Spanner + +```shell +gcloud dataproc jobs submit spark --cluster ${CLUSTER_NAME} \ + --region=us-central1 \ + --jar=${GCS_BUCKET_JARS}/${APP_JAR_NAME} \ + --jars=${GCS_BUCKET_JARS}/${SPANNER_JDBC_JAR} \ + -- ${BQ_PROJECT_ID} ${BQ_DATASET} ${BQ_TABLE} ${BQ_TABLE_PK} ${SPANNER_PROJECT_ID} ${SPANNER_INSTANCE} ${NUM_SPANNER_NODES} ${SPANNER_DB} ${SPANNER_TABLE} ${JDBC_BATCH_SIZE} +``` + +Where the arguments have this meaning + +| cmd line arg | meaning | example | +|----------|---------------|--------------| +| CLUSTER_NAME | The name of your Dataproc cluster | my_cluster | +| GCS_BUCKET_JARS | The Google Cloud Storage bucket for JARs | gs://my-jar-bucket | +| APP_JAR_NAME | As above, the JAR of this template code | spark-bigquery-spanner.jar | +| SPANNER_JDBC_JAR | As above, the JAR of Spanner JDBC driver | google-cloud-spanner-jdbc-2.17.1-single-jar-with-dependencies.jar | +| BQ_PROJECT_ID | The ID of the GCP project with BigQuery source data | ```gcloud config list core/project --format="value(core.project)"``` | +| BQ_DATASET | The BigQuery dataset with source data | my_bq_dataset | +| BQ_TABLE | The BigQuery table with source data | my_bq_table | +| BQ_TABLE_PK | Primary key column name of the BigQuery table | my_pk_column_name | +| SPANNER_PROJECT_ID | The ID of the GCP project with Spanner target | ```BQ_PROJECT_ID=$(gcloud config list core/project --format="value(core.project)")``` | +| SPANNER_INSTANCE | The Spanner instance with target table | my_spanner_instance | +| NUM_SPANNER_NODES | The number of nodes the spanner instance has | ```gcloud spanner instances describe ${SPANNER_INSTANCE} --format="value(nodeCount)"``` | +| SPANNER_DB | The Spanner database with target table | my_spanner_db | +| SPANNER_TABLE | The target table in Spanner | my_spanner_table | +| JDBC_BATCH_SIZE | The number of rows to bundle into a single write to Spanner | 200 | + +### Example of using this template + +#### Example - part 1 of 4 - environment variables + setup + +```shell +export PROJECT_ID=$(gcloud config list core/project --format="value(core.project)") +export PROJECT_NUM=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)") +export GEO_REGION="US" +export GCS_BUCKET="gs://${PROJECT_ID}-sparkbigqueryspanner" +export GCS_BUCKET_JARS="${GCS_BUCKET}/jars" +export BQ_PROJECT_ID="bigquery-public-data" +export BQ_DATASET="austin_311" +export BQ_TABLE="311_service_requests" +export BQ_TABLE_PK="unique_key" +export SPANNER_INSTANCE="sparkbigqueryspanner-demo-instance" +export SPANNER_DB="sparkbigqueryspanner-demo--db" +export SPANNER_TABLE="service_requests_copy" +export JDBC_BATCH_SIZE="200" +export CLUSTER_NAME="sparkbigqueryspanner-demo-cluster" +export APP_JAR_NAME="spark-bigquery-spanner_2.12-0.1.0-SNAPSHOT.jar" +export SPANNER_JDBC_JAR="google-cloud-spanner-jdbc-2.17.1-single-jar-with-dependencies.jar" +``` + +#### Example - part 2 of 4 - BigQuery table (source) + +we will use the public table + +```shell +bigquery-public-data.austin_311.311_service_requests +``` + +It has 1,860,505 rows + +#### Example - part 3 of 4 - Spanner table (sink) + +create a spanner instance + +```shell +gcloud spanner instances create ${SPANNER_INSTANCE} \ + --project=${PROJECT_ID} \ + --config=regional-us-central1 \ + --description="Demo replication from BigQuery" \ + --nodes=1 +``` + +create environmental variable to record num nodes for later usage in template +```shell +export NUM_SPANNER_NODES=$(gcloud spanner instances describe ${SPANNER_INSTANCE} --format="value(nodeCount)") +``` + +create a database within the spanner instance (with dialect GoogleSQL) + +```shell +gcloud spanner databases create ${SPANNER_DB} \ + --instance=${SPANNER_INSTANCE} +``` + +create a table in our Spanner DB: + * column names matching BigQuery table names + * column types as per mapping table above + + +```shell +gcloud spanner databases ddl update ${SPANNER_DB} \ +--instance=${SPANNER_INSTANCE} \ +--ddl='CREATE TABLE service_requests_copy ( unique_key STRING(MAX), complaint_description STRING(MAX), source STRING(MAX), status STRING(MAX), status_change_date TIMESTAMP, created_date TIMESTAMP, last_update_date TIMESTAMP, close_date TIMESTAMP, incident_address STRING(MAX), street_number STRING(MAX), street_name STRING(MAX), city STRING(MAX), incident_zip INT64, county STRING(MAX), state_plane_x_coordinate STRING(MAX), state_plane_y_coordinate FLOAT64, latitude FLOAT64, longitude FLOAT64, location STRING(MAX), council_district_code INT64, map_page STRING(MAX), map_tile STRING(MAX)) PRIMARY KEY (unique_key)' +``` + +#### Example - part 4 of 4 - Run Scala Spark Job on Dataproc + +create a dataproc cluster + +```shell +gcloud dataproc clusters create ${CLUSTER_NAME} \ + --region us-central1 \ + --no-address \ + --master-machine-type n2-standard-4 \ + --master-boot-disk-type pd-balanced \ + --master-boot-disk-size 500 \ + --num-workers 2 \ + --worker-machine-type n2-standard-4 \ + --worker-boot-disk-type pd-balanced \ + --worker-boot-disk-size 500 \ + --image-version 2.2-debian12 \ + --project ${PROJECT_ID} +``` + +create a bucket to hold JARs + +```shell +gcloud storage buckets create ${GCS_BUCKET} \ + --project=${PROJECT_ID} \ + --location=${GEO_REGION} \ + --uniform-bucket-level-access +``` + +Upload required JARs to Google Cloud Storage bucket + + * ```APP_JAR```, the JAR of this code by running ```sbt package``` from root of this repo + * ```SPANNER_JDBC_JAR```, the JAR of the Spanner JDBC [driver](https://cloud.google.com/spanner/docs/jdbc-drivers) + +launch Scala Apache Spark job on Dataproc cluster + +```shell +gcloud dataproc jobs submit spark --cluster ${CLUSTER_NAME} \ + --region=us-central1 \ + --jar=${GCS_BUCKET_JARS}/${APP_JAR_NAME} \ + --jars=${GCS_BUCKET_JARS}/${SPANNER_JDBC_JAR} \ + -- ${BQ_PROJECT_ID} ${BQ_DATASET} ${BQ_TABLE} ${BQ_TABLE_PK} ${PROJECT_ID} ${SPANNER_INSTANCE} ${NUM_SPANNER_NODES} ${SPANNER_DB} ${SPANNER_TABLE} ${JDBC_BATCH_SIZE} +``` \ No newline at end of file diff --git a/examples/dataproc-spanner/jdbc/build.properties b/examples/dataproc-spanner/jdbc/build.properties new file mode 100644 index 0000000000..04267b14af --- /dev/null +++ b/examples/dataproc-spanner/jdbc/build.properties @@ -0,0 +1 @@ +sbt.version=1.9.9 diff --git a/examples/dataproc-spanner/jdbc/build.sbt b/examples/dataproc-spanner/jdbc/build.sbt new file mode 100644 index 0000000000..263ba68e21 --- /dev/null +++ b/examples/dataproc-spanner/jdbc/build.sbt @@ -0,0 +1,22 @@ +//do not use "bare style" for build.sbt +//instead use "multi project" for our build.sbt +lazy val root = (project in file(".")).settings( + inThisBuild( + List( + organization := "org.tonz.com", + // version of scala compatible with latest dataproc images + scalaVersion := "2.12.18" + ) + ), + name := "spark-bigquery-spanner" +) + +// we need to use spark & spanner jdbc in this project +val sparkVersion = "3.5.0" +val sparkJDBC = "2.17.1" + +libraryDependencies ++= Seq( + "org.apache.spark" %% "spark-core" % sparkVersion, + "org.apache.spark" %% "spark-sql" % sparkVersion, + "com.google.cloud" % "google-cloud-spanner-jdbc" % sparkJDBC +) diff --git a/examples/dataproc-spanner/jdbc/project/build.properties b/examples/dataproc-spanner/jdbc/project/build.properties new file mode 100644 index 0000000000..04267b14af --- /dev/null +++ b/examples/dataproc-spanner/jdbc/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.9.9 diff --git a/examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF b/examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..b125915e20 --- /dev/null +++ b/examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Main-Class: org.tonyz.com.Main diff --git a/examples/dataproc-spanner/jdbc/src/main/scala/Main.scala b/examples/dataproc-spanner/jdbc/src/main/scala/Main.scala new file mode 100644 index 0000000000..14fdc13d63 --- /dev/null +++ b/examples/dataproc-spanner/jdbc/src/main/scala/Main.scala @@ -0,0 +1,61 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.tonyz.com + +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.jdbc.JdbcDialects + +object Main { + def main(args: Array[String]): Unit = { + + // ---------PARSE COMMAND LINE ARGUMENTS------------------------------------- + val numArgs = 10 + if (args.length != numArgs) { + throw new IllegalArgumentException( + s"Exactly $numArgs arguments are required" + ) + } + + // source :: BigQuery Dataset & Table + val bqProject = args(0) + val bqDataset = args(1) + val bqTable = args(2) + val bqPk = args(3) + // sink :: Spanner instance, database & table + val spanProject = args(4) + val inst = args(5) + val numSpannerNodes = args(6) + val db = args(7) + val tbl = args(8) + val batchSize = args(9) + + // ---------Launch pipeline------------------------------------- + val pipeline = + new Pipeline( + bqProject, + bqDataset, + bqTable, + bqPk, + spanProject, + inst, + numSpannerNodes, + db, + tbl, + batchSize + ) + + pipeline.exe_pipeline() + } +} diff --git a/examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala b/examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala new file mode 100644 index 0000000000..eac06ab901 --- /dev/null +++ b/examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala @@ -0,0 +1,83 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.tonyz.com + +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.jdbc.JdbcDialects + +class Pipeline( + var bqProject: String, + var bqDataset: String, + var bqTable: String, + var bqPk: String, + var spanProject: String, + var inst: String, + var numSpannerNodes: String, + var db: String, + var tbl: String, + var batchSize: String +) { + + def exe_pipeline(): Unit = { + // ---------CREATE SPARK SESSION--------------------------------------------- + val spark = SparkSession + .builder() + .appName("bigquery-spanner-template") + .getOrCreate() + + // ---------READ SOURCE DATA FROM BIGQUERY----------------------------------- + val inputDF = spark.read + .format("bigquery") + .load(s"$bqProject.$bqDataset.$bqTable") + + // ---------REPARTITION BY PRIMARY KEY----------------------------------- + // How many partitions ? + // Let N be the number of nodes in our spanner instance + // There should be 10*N partitions in our dataset + // How to partition? + // Partitioning should be done on the primary key + // So that rows are written sequentially by primary key. E.g. not in random order. + // This is all per Spanner best pratices + // https://cloud.google.com/spanner/docs/bulk-loading#partition-by-key) + val numPartitions = 10 * numSpannerNodes.toInt + val inputDFRepartitioned = + inputDF.repartition(numPartitions, inputDF(s"$bqPk")) + + // ---------TELL SPARK TO USE OUR CUSTOM SQL DIALECT FOR SPANNER------------- + JdbcDialects.registerDialect(SpannerJdbcDialect) + + // ---------WRITE DATA FROM BIGQUERY TO SPANNER------------------------------ + val url = + s"jdbc:cloudspanner:/projects/$spanProject/instances/$inst/databases/$db" + val driver = "com.google.cloud.spanner.jdbc.JdbcDriver" + val fmt = "jdbc" + inputDFRepartitioned.write + .format(fmt) + .option("url", url) + .option("driver", driver) + .option("dbtable", tbl) + // We do not need transaction isolation are we are doing a large batch of writes + // As per transaction documentation + // https://cloud.google.com/spanner/docs/transactions#introduction + .option("isolationLevel", "NONE") + // Each write to Spanner should contain hundreds of rows at a maximum. + // How many hundreds ? + // As Many as can fit into 1MB as per best practices + // https://cloud.google.com/spanner/docs/bulk-loading#commit-size + .option("batchsize", batchSize.toInt) + .mode("append") + .save() + } +} diff --git a/examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala b/examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala new file mode 100644 index 0000000000..b958161844 --- /dev/null +++ b/examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala @@ -0,0 +1,75 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.tonyz.com + +import org.apache.spark.sql.jdbc.{JdbcDialect, JdbcType} +import org.apache.spark.sql.types._ + +object SpannerJdbcDialect extends JdbcDialect { + + /* + JdbcDialect is an abstract class + We need to override methods of this abstract class + */ + + /* + Checks if this dialect instance can handle a certain jdbc url. + We override this to indicate that this dialect can handle Spanner specific jdbc urls. + */ + override def canHandle(url: String): Boolean = + url.toLowerCase.startsWith("jdbc:cloudspanner:") + + /* + When reading from Spanner w/ JDBC need to map Spanner GoogleSQL type to SparkSQL type. + Default behaviour, JdbcUtils.getCatalystType maps JDBC type to Spark Catalyst type. + We overwrite this type mapping to make it work for Spanner + */ + override def getCatalystType( + sqlType: Int, + typeName: String, + size: Int, + md: MetadataBuilder + ): Option[DataType] = + if (sqlType == java.sql.Types.NUMERIC) Some(DecimalType(38, 9)) else None + + /* + When writing to Spanner w/ JDBC need to map SparkSQL type to Spanner GoogleSQL type. + Default behaviour, org.apache.spark.jdbc.JdbcUtils ==> getCommonJDBCType + We override this to make sure all data types for writing are supported by Spanner. + */ + override def getJDBCType(dt: DataType): Option[JdbcType] = dt match { + case IntegerType => Some(JdbcType("INT64", java.sql.Types.INTEGER)) + case LongType => Some(JdbcType("INT64", java.sql.Types.BIGINT)) + case DoubleType => Some(JdbcType("FLOAT64", java.sql.Types.DOUBLE)) + case FloatType => Some(JdbcType("FLOAT64", java.sql.Types.FLOAT)) + case ShortType => Some(JdbcType("INT64", java.sql.Types.SMALLINT)) + case ByteType => Some(JdbcType("BYTES(1)", java.sql.Types.TINYINT)) + case BooleanType => Some(JdbcType("BOOL", java.sql.Types.BOOLEAN)) + case StringType => Some(JdbcType("STRING(MAX)", java.sql.Types.VARCHAR)) + case BinaryType => Some(JdbcType("BYTES(MAX)", java.sql.Types.VARBINARY)) + case TimestampType => Some(JdbcType("TIMESTAMP", java.sql.Types.TIMESTAMP)) + case DateType => Some(JdbcType("DATE", java.sql.Types.DATE)) + case _: DecimalType => Some(JdbcType("NUMERIC", java.sql.Types.NUMERIC)) + case _ => None + } + + /* + Change default behaviour around quoting identifiers. + This is used to put quotes around the identifier in case the column name. + We override this default behaviour to make it compatible with Spanner. + */ + override def quoteIdentifier(colName: String): String = s"`$colName`" + +} From 266f53db606c570aa268da6b8547a84b8204de49 Mon Sep 17 00:00:00 2001 From: Anthony Lazzaro <93217007+ant-laz@users.noreply.github.com> Date: Wed, 26 Feb 2025 11:06:31 +0000 Subject: [PATCH 2/3] Deletes LICENSE --- examples/dataproc-spanner/jdbc/LICENCE | 175 ------------------------- 1 file changed, 175 deletions(-) delete mode 100644 examples/dataproc-spanner/jdbc/LICENCE diff --git a/examples/dataproc-spanner/jdbc/LICENCE b/examples/dataproc-spanner/jdbc/LICENCE deleted file mode 100644 index 19dc35b243..0000000000 --- a/examples/dataproc-spanner/jdbc/LICENCE +++ /dev/null @@ -1,175 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. \ No newline at end of file From f413c12ed3f0bdf1f2d1b8791ab24b93fb3e3cb1 Mon Sep 17 00:00:00 2001 From: Anthony Lazzaro <93217007+ant-laz@users.noreply.github.com> Date: Wed, 26 Feb 2025 12:18:32 +0000 Subject: [PATCH 3/3] updated copyright to 2025 & use pso package name --- examples/dataproc-spanner/jdbc/build.sbt | 2 +- examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF | 2 +- examples/dataproc-spanner/jdbc/src/main/scala/Main.scala | 4 ++-- examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala | 4 ++-- .../jdbc/src/main/scala/SpannerJdbcDialect.scala | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/dataproc-spanner/jdbc/build.sbt b/examples/dataproc-spanner/jdbc/build.sbt index 263ba68e21..c0c06a05eb 100644 --- a/examples/dataproc-spanner/jdbc/build.sbt +++ b/examples/dataproc-spanner/jdbc/build.sbt @@ -3,7 +3,7 @@ lazy val root = (project in file(".")).settings( inThisBuild( List( - organization := "org.tonz.com", + organization := "com.google.cloud.pso", // version of scala compatible with latest dataproc images scalaVersion := "2.12.18" ) diff --git a/examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF b/examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF index b125915e20..632ed3855d 100644 --- a/examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF +++ b/examples/dataproc-spanner/jdbc/src/main/META-INF/MANIFEST.MF @@ -1,2 +1,2 @@ Manifest-Version: 1.0 -Main-Class: org.tonyz.com.Main +Main-Class: com.google.cloud.pso.Main diff --git a/examples/dataproc-spanner/jdbc/src/main/scala/Main.scala b/examples/dataproc-spanner/jdbc/src/main/scala/Main.scala index 14fdc13d63..9a3673262c 100644 --- a/examples/dataproc-spanner/jdbc/src/main/scala/Main.scala +++ b/examples/dataproc-spanner/jdbc/src/main/scala/Main.scala @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package org.tonyz.com +package com.google.cloud.pso import org.apache.spark.sql.SparkSession import org.apache.spark.sql.jdbc.JdbcDialects diff --git a/examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala b/examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala index eac06ab901..450111bbd2 100644 --- a/examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala +++ b/examples/dataproc-spanner/jdbc/src/main/scala/Pipeline.scala @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package org.tonyz.com +package com.google.cloud.pso import org.apache.spark.sql.SparkSession import org.apache.spark.sql.jdbc.JdbcDialects diff --git a/examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala b/examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala index b958161844..420d2127b1 100644 --- a/examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala +++ b/examples/dataproc-spanner/jdbc/src/main/scala/SpannerJdbcDialect.scala @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package org.tonyz.com +package com.google.cloud.pso import org.apache.spark.sql.jdbc.{JdbcDialect, JdbcType} import org.apache.spark.sql.types._