errors) {
28 | super(String.format("job %s failed with error: %s", id, errors));
29 | this.id = id;
30 | this.errors = errors;
31 | }
32 |
33 | /** The ID for the failed job. */
34 | public JobId getId() {
35 | return id;
36 | }
37 |
38 | /**
39 | * The errors reported by the job.
40 | *
41 | * The list is immutable.
42 | */
43 | public List getErrors() {
44 | return errors;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/.cloudbuild/samples_build.yaml:
--------------------------------------------------------------------------------
1 | steps:
2 | - name: gcr.io/cloud-devrel-public-resources/java8
3 | entrypoint: ls
4 | args: [
5 | '-alt',
6 | ]
7 | - name: gcr.io/cloud-devrel-public-resources/java8
8 | entrypoint: curl
9 | args: [
10 | '--header',
11 | 'Metadata-Flavor: Google',
12 | 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email'
13 | ]
14 | - name: gcr.io/cloud-devrel-public-resources/java8
15 | entrypoint: pwd
16 | - name: gcr.io/cloud-devrel-public-resources/java8
17 | entrypoint: bash
18 | args: [
19 | '.kokoro/build.sh'
20 | ]
21 | env:
22 | - 'JOB_TYPE=samples'
23 | - 'BIGQUERY_PROJECT_ID=cloud-java-ci-sample'
24 | - 'GOOGLE_CLOUD_PROJECT=cloud-java-ci-sample'
25 | - 'GCS_BUCKET=java-samples-bigquery'
26 | - 'BIGQUERY_TEST_TABLE=test_table'
27 | - 'BIGQUERY_MODEL_NAME=natality_model'
28 | - 'BIGQUERY_MODEL_TEST_PROJECT_ID=bigquery-public-data'
29 | - 'OMNI_PROJECT_ID=sunlit-ace-276222'
30 | - 'OMNI_EXTERNAL_TABLE_NAME=devrel_test_table'
31 | - 'BIGQUERY_TABLE2=table2'
32 | - 'BIGQUERY_TABLE1=table1'
33 | - 'BIGTABLE_TESTING_INSTANCE=bigquery-samples-instance'
34 | - 'BIGQUERY_DATASET_NAME=bigquery_test_dataset'
35 | - 'KOKORO_GFILE_DIR=/workspace'
36 | # This key is not available yet
37 | - 'BIGQUERY_KMS_KEY_NAME=projects/cloud-java-ci-sample/locations/us/keyRings/bq-kms-key/cryptoKeys/bq-kms-key'
38 | - name: gcr.io/cloud-devrel-public-resources/java8
39 | entrypoint: echo
40 | args: [
41 | 'Sample job succeeded',
42 | ]
43 | timeout: 3600s
44 | options:
45 | defaultLogsBucketBehavior: REGIONAL_USER_OWNED_BUCKET
46 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryBaseService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.cloud.bigquery;
17 |
18 | import com.google.cloud.BaseService;
19 | import com.google.cloud.ExceptionHandler;
20 | import com.google.cloud.ServiceOptions;
21 |
22 | abstract class BigQueryBaseService>
23 | extends BaseService {
24 |
25 | protected BigQueryBaseService(ServiceOptions options) {
26 | super(options);
27 | }
28 |
29 | public static final ExceptionHandler DEFAULT_BIGQUERY_EXCEPTION_HANDLER =
30 | ExceptionHandler.newBuilder()
31 | .abortOn(RuntimeException.class)
32 | .retryOn(java.net.ConnectException.class) // retry on Connection Exception
33 | .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException
34 | .retryOn(java.net.SocketException.class) // retry on SocketException
35 | .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR)
36 | .build();
37 | }
38 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryDryRunResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import com.google.api.core.BetaApi;
20 | import java.util.List;
21 |
22 | public interface BigQueryDryRunResult {
23 |
24 | /** Returns the schema of the results. Null if the schema is not supplied. */
25 | @BetaApi
26 | Schema getSchema() throws BigQuerySQLException;
27 |
28 | /**
29 | * Returns query parameters for standard SQL queries by extracting undeclare query parameters from
30 | * the dry run job. See more information:
31 | * https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/java/latest/com/google/api/services/bigquery/model/JobStatistics2.html#getUndeclaredQueryParameters--
32 | */
33 | @BetaApi
34 | List getQueryParameters() throws BigQuerySQLException;
35 |
36 | /** Returns some processing statistics */
37 | @BetaApi
38 | BigQueryResultStats getStatistics() throws BigQuerySQLException;
39 | }
40 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryDryRunResultImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import java.util.List;
20 |
21 | public class BigQueryDryRunResultImpl implements BigQueryDryRunResult {
22 | private Schema schema;
23 | private List queryParameters;
24 | private BigQueryResultStats stats;
25 |
26 | BigQueryDryRunResultImpl(
27 | Schema schema,
28 | List queryParameters,
29 | BigQueryResultStats stats) { // Package-Private access
30 | this.schema = schema;
31 | this.queryParameters = queryParameters;
32 | this.stats = stats;
33 | }
34 |
35 | @Override
36 | public Schema getSchema() throws BigQuerySQLException {
37 | return schema;
38 | }
39 |
40 | @Override
41 | public List getQueryParameters() throws BigQuerySQLException {
42 | return queryParameters;
43 | }
44 |
45 | @Override
46 | public BigQueryResultStats getStatistics() throws BigQuerySQLException {
47 | return stats;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * A client for BigQuery – A fully managed, petabyte scale, low cost enterprise data warehouse for
19 | * analytics.
20 | *
21 | * A simple usage example showing how to create a table in Bigquery. For the complete source code
22 | * see
24 | * CreateTable.java.
25 | *
26 | *
{@code
27 | * BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); *
28 | * TableId tableId = TableId.of(datasetName, tableName);
29 | * TableDefinition tableDefinition = StandardTableDefinition.of(schema);
30 | * TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build(); *
31 | * bigquery.create(tableInfo);
32 | * System.out.println("Table created successfully");
33 | * }
34 | *
35 | * @see Google Cloud BigQuery
36 | */
37 | package com.google.cloud.bigquery;
38 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExecuteSelectResponse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import com.google.auto.value.AutoValue;
20 | import java.io.Serializable;
21 | import javax.annotation.Nullable;
22 |
23 | @AutoValue
24 | public abstract class ExecuteSelectResponse implements Serializable {
25 | @Nullable
26 | public abstract BigQueryResult getResultSet();
27 |
28 | public abstract boolean getIsSuccessful();
29 |
30 | @Nullable
31 | public abstract BigQuerySQLException getBigQuerySQLException();
32 |
33 | public static Builder newBuilder() {
34 | return new AutoValue_ExecuteSelectResponse.Builder();
35 | }
36 |
37 | @AutoValue.Builder
38 | public abstract static class Builder {
39 | public abstract ExecuteSelectResponse build();
40 |
41 | public abstract Builder setResultSet(BigQueryResult bigQueryResult);
42 |
43 | public abstract Builder setIsSuccessful(boolean isSuccessful);
44 |
45 | public abstract Builder setBigQuerySQLException(BigQuerySQLException bigQuerySQLException);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * A testing helper for Google BigQuery.
19 | *
20 | * A simple usage example: 1. Create a test Google Cloud project.
21 | *
22 | *
2. Download a JSON service account credentials file from the Google Developer's Console.
23 | *
24 | *
3. Create a RemoteBigQueryHelper object using your project ID and JSON key. Here is an example
25 | * that uses the RemoteBigQueryHelper to create a dataset.
26 | *
27 | *
4. Run tests.
28 | *
29 | *
Before the test:
30 | *
31 | *
{@code
32 | * RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create();
33 | * BigQuery bigquery = bigqueryHelper.getOptions().getService();
34 | * String dataset = RemoteBigQueryHelper.generateDatasetName();
35 | * bigquery.create(DatasetInfo.newBuilder(dataset).build());
36 | * }
37 | *
38 | * After the test:
39 | *
40 | *
{@code
41 | * RemoteBigQueryHelper.forceDelete(bigquery, DATASET);
42 | * }
43 | */
44 | package com.google.cloud.bigquery.testing;
45 |
--------------------------------------------------------------------------------
/.kokoro/populate-secrets.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Copyright 2020 Google LLC.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | set -eo pipefail
17 |
18 | function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;}
19 | function msg { println "$*" >&2 ;}
20 | function println { printf '%s\n' "$(now) $*" ;}
21 |
22 |
23 | # Populates requested secrets set in SECRET_MANAGER_KEYS from service account:
24 | # kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com
25 | SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager"
26 | msg "Creating folder on disk for secrets: ${SECRET_LOCATION}"
27 | mkdir -p ${SECRET_LOCATION}
28 | for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g")
29 | do
30 | msg "Retrieving secret ${key}"
31 | docker run --entrypoint=gcloud \
32 | --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \
33 | gcr.io/google.com/cloudsdktool/cloud-sdk \
34 | secrets versions access latest \
35 | --project cloud-devrel-kokoro-resources \
36 | --secret ${key} > \
37 | "${SECRET_LOCATION}/${key}"
38 | if [[ $? == 0 ]]; then
39 | msg "Secret written to ${SECRET_LOCATION}/${key}"
40 | else
41 | msg "Error retrieving secret ${key}"
42 | fi
43 | done
44 |
--------------------------------------------------------------------------------
/.kokoro/readme.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Copyright 2020 Google LLC
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | set -eo pipefail
17 |
18 | cd ${KOKORO_ARTIFACTS_DIR}/github/java-bigquery
19 |
20 | # Disable buffering, so that the logs stream through.
21 | export PYTHONUNBUFFERED=1
22 |
23 | # Kokoro exposes this as a file, but the scripts expect just a plain variable.
24 | export GITHUB_TOKEN=$(cat ${KOKORO_KEYSTORE_DIR}/73713_yoshi-automation-github-key)
25 |
26 | # Setup git credentials
27 | echo "https://${GITHUB_TOKEN}:@github.com" >> ~/.git-credentials
28 | git config --global credential.helper 'store --file ~/.git-credentials'
29 |
30 | python3.6 -m pip install git+https://github.com/googleapis/synthtool.git#egg=gcp-synthtool
31 |
32 | set +e
33 | python3.6 -m autosynth.synth \
34 | --repository=googleapis/java-bigquery \
35 | --synth-file-name=.github/readme/synth.py \
36 | --metadata-path=.github/readme/synth.metadata \
37 | --pr-title="chore: regenerate README" \
38 | --branch-suffix="readme"
39 |
40 | # autosynth returns 28 to signal there are no changes
41 | RETURN_CODE=$?
42 | if [[ ${RETURN_CODE} -ne 0 && ${RETURN_CODE} -ne 28 ]]
43 | then
44 | exit ${RETURN_CODE}
45 | fi
46 |
--------------------------------------------------------------------------------
/.kokoro/common.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Copyright 2020 Google LLC
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | function retry_with_backoff {
17 | attempts_left=$1
18 | sleep_seconds=$2
19 | shift 2
20 | command=$@
21 |
22 |
23 | # store current flag state
24 | flags=$-
25 |
26 | # allow a failures to continue
27 | set +e
28 | ${command}
29 | exit_code=$?
30 |
31 | # restore "e" flag
32 | if [[ ${flags} =~ e ]]
33 | then set -e
34 | else set +e
35 | fi
36 |
37 | if [[ $exit_code == 0 ]]
38 | then
39 | return 0
40 | fi
41 |
42 | # failure
43 | if [[ ${attempts_left} > 0 ]]
44 | then
45 | echo "failure (${exit_code}), sleeping ${sleep_seconds}..."
46 | sleep ${sleep_seconds}
47 | new_attempts=$((${attempts_left} - 1))
48 | new_sleep=$((${sleep_seconds} * 2))
49 | retry_with_backoff ${new_attempts} ${new_sleep} ${command}
50 | fi
51 |
52 | return $exit_code
53 | }
54 |
55 | ## Helper functionss
56 | function now() { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n'; }
57 | function msg() { println "$*" >&2; }
58 | function println() { printf '%s\n' "$(now) $*"; }
59 |
60 | ## Helper comment to trigger updated repo dependency release
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResponse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import com.google.api.core.InternalApi;
20 | import com.google.auto.value.AutoValue;
21 | import com.google.common.collect.ImmutableList;
22 | import javax.annotation.Nullable;
23 |
24 | @InternalApi
25 | @AutoValue
26 | public abstract class QueryResponse {
27 | QueryResponse() {
28 | // Package private so users can't subclass it but AutoValue can.
29 | }
30 |
31 | // Only null if the job fails.
32 | @Nullable
33 | abstract Schema getSchema();
34 |
35 | abstract boolean getCompleted();
36 |
37 | abstract long getTotalRows();
38 |
39 | abstract ImmutableList getErrors();
40 |
41 | static Builder newBuilder() {
42 | return new AutoValue_QueryResponse.Builder();
43 | }
44 |
45 | @AutoValue.Builder
46 | abstract static class Builder {
47 | abstract Builder setSchema(Schema val);
48 |
49 | abstract Builder setCompleted(boolean val);
50 |
51 | abstract Builder setTotalRows(long val);
52 |
53 | abstract Builder setErrors(ImmutableList val);
54 |
55 | abstract QueryResponse build();
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/GetJob.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_get_job]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Job;
24 | import com.google.cloud.bigquery.JobId;
25 |
26 | // Sample to get a job
27 | public class GetJob {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String jobName = "MY_JOB_NAME";
32 | getJob(jobName);
33 | }
34 |
35 | public static void getJob(String jobName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | JobId jobId = JobId.of(jobName);
42 | Job job = bigquery.getJob(jobId);
43 | System.out.println("Job retrieved successfully");
44 | } catch (BigQueryException e) {
45 | System.out.println("Job not retrieved. \n" + e.toString());
46 | }
47 | }
48 | }
49 | // [END bigquery_get_job]
50 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/QuickstartSample.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Google Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_quickstart]
20 | // Imports the Google Cloud client library
21 | import com.google.cloud.bigquery.BigQuery;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 | import com.google.cloud.bigquery.DatasetInfo;
25 |
26 | public class QuickstartSample {
27 | public static void main(String... args) throws Exception {
28 | // Instantiate a client. If you don't specify credentials when constructing a client, the
29 | // client library will look for credentials in the environment, such as the
30 | // GOOGLE_APPLICATION_CREDENTIALS environment variable.
31 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
32 |
33 | // The name for the new dataset
34 | String datasetName = "my_new_dataset";
35 |
36 | // Prepares a new dataset
37 | Dataset dataset = null;
38 | DatasetInfo datasetInfo = DatasetInfo.newBuilder(datasetName).build();
39 |
40 | // Creates the dataset
41 | dataset = bigquery.create(datasetInfo);
42 |
43 | System.out.printf("Dataset %s created.%n", dataset.getDatasetId().getDataset());
44 | }
45 | }
46 | // [END bigquery_quickstart]
47 |
--------------------------------------------------------------------------------
/samples/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with BigQuery Samples
2 |
3 | ## Running a sample using Cloud Shell
4 |
5 | The Google Cloud Shell has application default credentials from its compute instance which will allow you to run an integration test without having to obtain `GOOGLE_APPLICATION_CREDENTIALS`. Go to [BigQuery Client Readme](https://github.com/googleapis/java-bigquery#samples) to run each sample in the Cloud Shell.
6 |
7 | ## Running a sample using command line
8 |
9 | First set up `GOOGLE_APPLICATION_CREDENTIALS` and `GOOGLE_CLOUD_PROJECT` environment variables before running any samples.
10 |
11 | To run a sample:
12 | 1. `cd samples/snippets` - all samples are located in `java-bigquery/samples/snippets` directory.
13 | 2. `mvn compile exec:java -Dexec.mainClass=com.example.bigquery.SimpleQuery` - this runs the [SimpleQuery sample](https://github.com/googleapis/java-bigquery/blob/master/samples/snippets/src/main/java/com/example/bigquery/SimpleQuery.java) which runs the BigQuery query method. You can update the developer's `TODO` section in the snippet if you wish to run a different query.
14 |
15 | ## Running a sample integration test using command line
16 |
17 | Note that some samples require environment variables to be set. For instance, in `CreateDatasetIT.java`:
18 |
19 | `private static final String GOOGLE_CLOUD_PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT");` - this sample integration test requires you to specific the [Google Cloud Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects) you would like to run the test in.
20 |
21 | Make sure to set environment variables, if necessary, before running the sample, or else you will get an error asking you to set it.
22 |
23 | To run a samples integration tests:
24 |
25 | 1. `cd samples/snippets` - all samples are located in `java-bigquery/samples/snippets` directory.
26 | 2. `mvn -Dtest=GetTableIT test` - this runs the integration test of `GetTable.java` sample.
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/RunLegacyQueryIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class RunLegacyQueryIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testRunLegacyQuery() {
54 | RunLegacyQuery.runLegacyQuery();
55 | assertThat(bout.toString()).contains("Legacy query ran successfully");
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/.kokoro/run_samples_resource_cleanup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Copyright 2020 Google Inc.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # `-e` enables the script to automatically fail when a command fails
17 | # `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero``
18 | set -eo pipefail
19 |
20 | echo "********** MAVEN INFO ***********"
21 | mvn -v
22 |
23 | # Get the directory of the build script
24 | scriptDir=$(realpath $(dirname "${BASH_SOURCE[0]}"))
25 | ## cd to the parent directory, i.e. the root of the git repo
26 | cd ${scriptDir}/..
27 |
28 | # include common functions
29 | source ${scriptDir}/common.sh
30 |
31 | # Setup required env variables
32 | source ${KOKORO_GFILE_DIR}/secret_manager/java-bigquery-samples-secrets
33 | # if GOOGLE_APPLICATION_CREDENTIALS is specified as a relative path, prepend Kokoro root directory onto it
34 | if [[ ! -z "${GOOGLE_APPLICATION_CREDENTIALS}" && "${GOOGLE_APPLICATION_CREDENTIALS}" != /* ]]; then
35 | export GOOGLE_APPLICATION_CREDENTIALS=$(realpath ${KOKORO_GFILE_DIR}/${GOOGLE_APPLICATION_CREDENTIALS})
36 | fi
37 | echo "********** Successfully Set All Environment Variables **********"
38 |
39 | # Move into the samples directory
40 | cd samples/snippets
41 |
42 | echo -e "\n******************** NIGHTLY RESOURCE CLEAN UP ********************"
43 |
44 | mvn compile exec:java -Dexec.mainClass=com.example.bigquery.ResourceCleanUp
45 |
--------------------------------------------------------------------------------
/.kokoro/dependencies.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Copyright 2019 Google LLC
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | set -eo pipefail
17 | shopt -s nullglob
18 |
19 | ## Get the directory of the build script
20 | scriptDir=$(realpath $(dirname "${BASH_SOURCE[0]}"))
21 | ## cd to the parent directory, i.e. the root of the git repo
22 | cd ${scriptDir}/..
23 |
24 | # include common functions
25 | source ${scriptDir}/common.sh
26 |
27 | # Print out Java
28 | java -version
29 | echo $JOB_TYPE
30 |
31 | function determineMavenOpts() {
32 | local javaVersion=$(
33 | # filter down to the version line, then pull out the version between quotes,
34 | # then trim the version number down to its minimal number (removing any
35 | # update or suffix number).
36 | java -version 2>&1 | grep "version" \
37 | | sed -E 's/^.*"(.*?)".*$/\1/g' \
38 | | sed -E 's/^(1\.[0-9]\.0).*$/\1/g'
39 | )
40 |
41 | if [[ $javaVersion == 17* ]]
42 | then
43 | # MaxPermSize is no longer supported as of jdk 17
44 | echo -n "-Xmx1024m"
45 | else
46 | echo -n "-Xmx1024m -XX:MaxPermSize=128m"
47 | fi
48 | }
49 |
50 | export MAVEN_OPTS=$(determineMavenOpts)
51 |
52 | # this should run maven enforcer
53 | retry_with_backoff 3 10 \
54 | mvn install -B -V -ntp \
55 | -DskipTests=true \
56 | -Dmaven.javadoc.skip=true \
57 | -Dclirr.skip=true
58 |
59 | mvn -B dependency:analyze -DfailOnWarning=true
60 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/ListJobs.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_list_jobs]
20 | import com.google.api.gax.paging.Page;
21 | import com.google.cloud.bigquery.BigQuery;
22 | import com.google.cloud.bigquery.BigQueryException;
23 | import com.google.cloud.bigquery.BigQueryOptions;
24 | import com.google.cloud.bigquery.Job;
25 |
26 | // Sample to get list of jobs
27 | public class ListJobs {
28 |
29 | public static void main(String[] args) {
30 | listJobs();
31 | }
32 |
33 | public static void listJobs() {
34 | try {
35 | // Initialize client that will be used to send requests. This client only needs to be created
36 | // once, and can be reused for multiple requests.
37 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
38 |
39 | Page jobs = bigquery.listJobs(BigQuery.JobListOption.pageSize(10));
40 | if (jobs == null) {
41 | System.out.println("Dataset does not contain any jobs.");
42 | return;
43 | }
44 | jobs.getValues().forEach(job -> System.out.printf("Success! Job ID: %s", job.getJobId()));
45 | } catch (BigQueryException e) {
46 | System.out.println("Jobs not listed in dataset due to error: \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_list_jobs]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/AuthDriveScopeIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.IOException;
23 | import java.io.PrintStream;
24 | import java.util.logging.Level;
25 | import java.util.logging.Logger;
26 | import org.junit.After;
27 | import org.junit.Before;
28 | import org.junit.Test;
29 |
30 | public class AuthDriveScopeIT {
31 |
32 | private final Logger log = Logger.getLogger(this.getClass().getName());
33 | private ByteArrayOutputStream bout;
34 | private PrintStream out;
35 | private PrintStream originalPrintStream;
36 |
37 | @Before
38 | public void setUp() {
39 | bout = new ByteArrayOutputStream();
40 | out = new PrintStream(bout);
41 | originalPrintStream = System.out;
42 | System.setOut(out);
43 | }
44 |
45 | @After
46 | public void tearDown() {
47 | // restores print statements in the original method
48 | System.out.flush();
49 | System.setOut(originalPrintStream);
50 | log.log(Level.INFO, "\n" + bout.toString());
51 | }
52 |
53 | @Test
54 | public void setAuthDriveScope() throws IOException {
55 | AuthDriveScope.setAuthDriveScope();
56 | assertThat(bout.toString()).contains("Auth succeeded with multiple scopes.");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/GetDatasetLabels.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_get_dataset_labels]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 |
25 | // Sample to get dataset labels
26 | public class GetDatasetLabels {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | getDatasetLabels(datasetName);
32 | }
33 |
34 | public static void getDatasetLabels(String datasetName) {
35 | try {
36 | // Initialize client that will be used to send requests. This client only needs to be created
37 | // once, and can be reused for multiple requests.
38 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
39 |
40 | Dataset dataset = bigquery.getDataset(datasetName);
41 | dataset
42 | .getLabels()
43 | .forEach((key, value) -> System.out.println("Retrieved labels successfully"));
44 | } catch (BigQueryException e) {
45 | System.out.println("Label was not found. \n" + e.toString());
46 | }
47 | }
48 | }
49 | // [END bigquery_get_dataset_labels]
50 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryWithNamedParametersIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryWithNamedParametersIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryWithNamedParameters() {
54 | QueryWithNamedParameters.queryWithNamedParameters();
55 | assertThat(bout.toString()).contains("Query with named parameters performed successfully.");
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/ListDatasetsIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class ListDatasetsIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() throws Exception {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testListDatasets() {
54 | // List datasets in bigquery-public-data project
55 | ListDatasets.listDatasets("bigquery-public-data");
56 | assertThat(bout.toString()).contains("Success! Dataset ID");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryWithStructsParametersIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryWithStructsParametersIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryWithNamedParameters() {
54 | QueryWithStructsParameters.queryWithStructsParameters();
55 | assertThat(bout.toString()).contains("Query with struct parameter performed successfully.");
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/CancelJobIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class CancelJobIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testCreateJob() {
54 | String query = "SELECT country_name from `bigquery-public-data.utility_us.country_code_iso`";
55 |
56 | CancelJob.cancelJob(query);
57 | assertThat(bout.toString()).contains("Job canceled successfully");
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/CreateDatasetWithRegionalEndpointIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class CreateDatasetWithRegionalEndpointIT {
30 | private final Logger log = Logger.getLogger(this.getClass().getName());
31 | private ByteArrayOutputStream bout;
32 | private PrintStream out;
33 | private PrintStream originalPrintStream;
34 |
35 | @Before
36 | public void setUp() {
37 | bout = new ByteArrayOutputStream();
38 | out = new PrintStream(bout);
39 | originalPrintStream = System.out;
40 | System.setOut(out);
41 | }
42 |
43 | @After
44 | public void tearDown() {
45 | // restores print statements in the original method
46 | System.out.flush();
47 | System.setOut(originalPrintStream);
48 | log.log(Level.INFO, "\n" + bout.toString());
49 | }
50 |
51 | @Test
52 | public void testCreateDatasetWithRegionalEndpoint() {
53 | CreateDatasetWithRegionalEndpoint.createDatasetWithRegionalEndpoint();
54 | assertThat(bout.toString().contains("Region of dataset: us-east4"));
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/CreateJobIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class CreateJobIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testCreateJob() {
54 | String query = "SELECT country_name from `bigquery-public-data.utility_us.country_code_iso`";
55 |
56 | CreateJob.createJob(query);
57 | assertThat(bout.toString()).contains("Job created successfully");
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/GetTableIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class GetTableIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() throws Exception {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testGetTable() {
54 | // Get shakespeare table from bigquery-public-data:samples dataset
55 | GetTable.getTable("bigquery-public-data", "samples", "shakespeare");
56 | assertThat(bout.toString()).contains("Table info:");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/ListTablesIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class ListTablesIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() throws Exception {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testListTables() {
54 | // List tables in bigquery-public-data:samples dataset
55 | ListTables.listTables("bigquery-public-data", "samples");
56 | assertThat(bout.toString()).contains("Tables listed successfully.");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryWithTimestampParametersIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryWithTimestampParametersIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryWithTimestampParameters() {
54 | QueryWithTimestampParameters.queryWithTimestampParameters();
55 | assertThat(bout.toString()).contains("Query with timestamp parameter performed successfully.");
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldElementTypeTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2024 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.cloud.bigquery;
17 |
18 | import static org.junit.Assert.assertEquals;
19 |
20 | import com.google.api.services.bigquery.model.QueryParameterType;
21 | import org.junit.Test;
22 |
23 | public class FieldElementTypeTest {
24 | private static final FieldElementType FIELD_ELEMENT_TYPE =
25 | FieldElementType.newBuilder().setType("DATE").build();
26 |
27 | @Test
28 | public void testToBuilder() {
29 | compareFieldElementType(FIELD_ELEMENT_TYPE, FIELD_ELEMENT_TYPE.toBuilder().build());
30 | }
31 |
32 | @Test
33 | public void testBuilder() {
34 | assertEquals("DATE", FIELD_ELEMENT_TYPE.getType());
35 | }
36 |
37 | @Test
38 | public void testFromAndPb() {
39 | assertEquals(FIELD_ELEMENT_TYPE, FieldElementType.fromPb(FIELD_ELEMENT_TYPE.toPb()));
40 | assertEquals(
41 | FIELD_ELEMENT_TYPE,
42 | FieldElementType.fromPb(
43 | new QueryParameterType()
44 | .setRangeElementType(new QueryParameterType().setType("DATE"))));
45 | }
46 |
47 | private void compareFieldElementType(FieldElementType expected, FieldElementType value) {
48 | assertEquals(expected.getType(), value.getType());
49 | assertEquals(expected.hashCode(), value.hashCode());
50 | assertEquals(expected.toString(), value.toString());
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryBatchIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryBatchIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryBatch() {
54 | String query = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus";
55 |
56 | QueryBatch.queryBatch(query);
57 | assertThat(bout.toString()).contains("Query batch performed successfully.");
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryWithPositionalParametersIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryWithPositionalParametersIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryWithPositionalParameters() {
54 | QueryWithPositionalParameters.queryWithPositionalParameters();
55 | assertThat(bout.toString())
56 | .contains("Query with positional parameters performed successfully.");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/GetView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_get_view]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Table;
24 | import com.google.cloud.bigquery.TableId;
25 |
26 | // Sample to get a view
27 | public class GetView {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | String viewName = "MY_VIEW_NAME";
33 | getView(datasetName, viewName);
34 | }
35 |
36 | public static void getView(String datasetName, String viewName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | TableId tableId = TableId.of(datasetName, viewName);
43 | Table view = bigquery.getTable(tableId);
44 | System.out.println("View retrieved successfully" + view.getDescription());
45 | } catch (BigQueryException e) {
46 | System.out.println("View not retrieved. \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_get_view]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/DeleteTable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_delete_table]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.TableId;
24 |
25 | public class DeleteTable {
26 |
27 | public static void main(String[] args) {
28 | // TODO(developer): Replace these variables before running the sample.
29 | String datasetName = "MY_DATASET_NAME";
30 | String tableName = "MY_TABLE_NAME";
31 | deleteTable(datasetName, tableName);
32 | }
33 |
34 | public static void deleteTable(String datasetName, String tableName) {
35 | try {
36 | // Initialize client that will be used to send requests. This client only needs to be created
37 | // once, and can be reused for multiple requests.
38 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
39 | boolean success = bigquery.delete(TableId.of(datasetName, tableName));
40 | if (success) {
41 | System.out.println("Table deleted successfully");
42 | } else {
43 | System.out.println("Table was not found");
44 | }
45 | } catch (BigQueryException e) {
46 | System.out.println("Table was not deleted. \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_delete_table]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryDisableCacheIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryDisableCacheIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryDisableCache() {
54 | String query = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;";
55 | QueryDisableCache.queryDisableCache(query);
56 | assertThat(bout.toString()).contains("Query disable cache performed successfully.");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/GetModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_get_model]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Model;
24 | import com.google.cloud.bigquery.ModelId;
25 |
26 | public class GetModel {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | String modelName = "MY_MODEL_ID";
32 | getModel(datasetName, modelName);
33 | }
34 |
35 | public static void getModel(String datasetName, String modelName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | ModelId modelId = ModelId.of(datasetName, modelName);
42 | Model model = bigquery.getModel(modelId);
43 | System.out.println("Model: " + model.getDescription());
44 |
45 | System.out.println("Successfully retrieved model");
46 | } catch (BigQueryException e) {
47 | System.out.println("Cannot retrieve model \n" + e.toString());
48 | }
49 | }
50 | }
51 | // [END bigquery_get_model]
52 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryWithArrayOfStructsNamedParametersIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryWithArrayOfStructsNamedParametersIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryWithNamedParameters() {
54 | QueryWithArrayOfStructsNamedParameters.queryWithArrayOfStructsNamedParameters();
55 | assertThat(bout.toString())
56 | .contains("Query with Array of struct parameters performed successfully.");
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/DatasetExists.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_dataset_exists]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 | import com.google.cloud.bigquery.DatasetId;
25 |
26 | // Sample to check dataset exist
27 | public class DatasetExists {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | datasetExists(datasetName);
33 | }
34 |
35 | public static void datasetExists(String datasetName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | Dataset dataset = bigquery.getDataset(DatasetId.of(datasetName));
42 | if (dataset != null) {
43 | System.out.println("Dataset already exists.");
44 | } else {
45 | System.out.println("Dataset not found.");
46 | }
47 | } catch (BigQueryException e) {
48 | System.out.println("Something went wrong. \n" + e.toString());
49 | }
50 | }
51 | }
52 | // [END bigquery_dataset_exists]
53 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/SimpleQueryIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class SimpleQueryIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testSimpleQuery() {
54 | String query =
55 | "SELECT corpus, count(*) as corpus_count "
56 | + "FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;";
57 |
58 | SimpleQuery.simpleQuery(query);
59 | assertThat(bout.toString()).contains("Query ran successfully");
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/DeleteModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_delete_model]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.ModelId;
24 |
25 | // Sample to delete a model
26 | public class DeleteModel {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | String modelName = "MY_MODEL_NAME";
32 | deleteModel(datasetName, modelName);
33 | }
34 |
35 | public static void deleteModel(String datasetName, String modelName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 | boolean success = bigquery.delete(ModelId.of(datasetName, modelName));
41 | if (success) {
42 | System.out.println("Model deleted successfully");
43 | } else {
44 | System.out.println("Model was not found");
45 | }
46 | } catch (BigQueryException e) {
47 | System.out.println("Model was not deleted. \n" + e.toString());
48 | }
49 | }
50 | }
51 | // [END bigquery_delete_model]
52 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/GetTable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_get_table]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Table;
24 | import com.google.cloud.bigquery.TableId;
25 |
26 | public class GetTable {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String projectId = "bigquery_public_data";
31 | String datasetName = "samples";
32 | String tableName = "shakespeare";
33 | getTable(projectId, datasetName, tableName);
34 | }
35 |
36 | public static void getTable(String projectId, String datasetName, String tableName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | TableId tableId = TableId.of(projectId, datasetName, tableName);
43 | Table table = bigquery.getTable(tableId);
44 | System.out.println("Table info: " + table.getDescription());
45 | } catch (BigQueryException e) {
46 | System.out.println("Table not retrieved. \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_get_table]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/QueryTotalRows.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_query_total_rows]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.QueryJobConfiguration;
24 | import com.google.cloud.bigquery.TableResult;
25 |
26 | // Sample to run query total rows
27 | public class QueryTotalRows {
28 |
29 | public static void main(String[] args) {
30 | String query =
31 | "SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013`"
32 | + " WHERE state = \"TX\""
33 | + " LIMIT 100";
34 | queryTotalRows(query);
35 | }
36 |
37 | public static void queryTotalRows(String query) {
38 | try {
39 | // Initialize client that will be used to send requests. This client only needs to be created
40 | // once, and can be reused for multiple requests.
41 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
42 |
43 | TableResult results = bigquery.query(QueryJobConfiguration.of(query));
44 |
45 | System.out.println("Query total rows performed successfully." + results.getTotalRows());
46 | } catch (BigQueryException | InterruptedException e) {
47 | System.out.println("Query not performed \n" + e.toString());
48 | }
49 | }
50 | }
51 | // [END bigquery_query_total_rows]
52 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/GetRoutine.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_get_routine]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Routine;
24 | import com.google.cloud.bigquery.RoutineId;
25 |
26 | // Sample to get a routine
27 | public class GetRoutine {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | String routineName = "MY_ROUTINE_NAME";
33 | getRoutine(datasetName, routineName);
34 | }
35 |
36 | public static void getRoutine(String datasetName, String routineName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | RoutineId routineId = RoutineId.of(datasetName, routineName);
43 | Routine routine = bigquery.getRoutine(routineId);
44 | System.out.println("Routine retrieved successfully" + routine.getDescription());
45 | } catch (BigQueryException e) {
46 | System.out.println("Routine not retrieved. \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_get_routine]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/CreateDatasetWithRegionalEndpoint.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_create_dataset_with_regional_endpoint]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 | import com.google.cloud.bigquery.DatasetInfo;
25 |
26 | public class CreateDatasetWithRegionalEndpoint {
27 | public static void createDatasetWithRegionalEndpoint() {
28 | BigQuery bigquery;
29 | try {
30 | // Initialize client that will be used to send requests. This client only needs to be created
31 | // once, and can be reused for multiple requests.
32 | bigquery =
33 | BigQueryOptions.newBuilder()
34 | .setHost("https://us-east4-bigquery.googleapis.com/")
35 | .build()
36 | .getService();
37 | String datasetName = "MyRegionalDataset";
38 |
39 | DatasetInfo datasetInfo = DatasetInfo.newBuilder(datasetName).build();
40 |
41 | Dataset newDataset = bigquery.create(datasetInfo);
42 | System.out.println("Region of dataset: " + newDataset.getLocation());
43 | bigquery.delete("MyRegionalDataset");
44 | } catch (BigQueryException e) {
45 | System.out.println("Dataset was not created. \n" + e);
46 | }
47 | }
48 | }
49 | // [END bigquery_create_dataset_with_regional_endpoint]
50 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/DeleteRoutine.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_delete_routine]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.RoutineId;
24 |
25 | // Sample to delete a routine
26 | public class DeleteRoutine {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | String routineName = "MY_ROUTINE_NAME";
32 | deleteRoutine(datasetName, routineName);
33 | }
34 |
35 | public static void deleteRoutine(String datasetName, String routineName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 | boolean success = bigquery.delete(RoutineId.of(datasetName, routineName));
41 | if (success) {
42 | System.out.println("Routine deleted successfully");
43 | } else {
44 | System.out.println("Routine was not found");
45 | }
46 | } catch (BigQueryException e) {
47 | System.out.println("Routine was not deleted. \n" + e.toString());
48 | }
49 | }
50 | }
51 | // [END bigquery_delete_routine]
52 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/UpdateRoutine.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_update_routine]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Routine;
24 | import com.google.cloud.bigquery.RoutineId;
25 |
26 | // Sample to update routine
27 | public class UpdateRoutine {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | String routineName = "MY_ROUTINE_NAME";
33 | updateRoutine(datasetName, routineName);
34 | }
35 |
36 | public static void updateRoutine(String datasetName, String routineName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | Routine routine = bigquery.getRoutine(RoutineId.of(datasetName, routineName));
43 | routine.toBuilder().setBody("x * 4").build().update();
44 | System.out.println("Routine updated successfully");
45 | } catch (BigQueryException e) {
46 | System.out.println("Routine was not updated. \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_update_routine]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryTotalRowsIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryTotalRowsIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryTotalRows() {
54 | String query =
55 | "SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013`"
56 | + " WHERE state = \"TX\""
57 | + " LIMIT 100";
58 | QueryTotalRows.queryTotalRows(query);
59 | assertThat(bout.toString()).contains("Query total rows performed successfully.");
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/CreateDataset.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_create_dataset]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 | import com.google.cloud.bigquery.DatasetInfo;
25 |
26 | public class CreateDataset {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | createDataset(datasetName);
32 | }
33 |
34 | public static void createDataset(String datasetName) {
35 | try {
36 | // Initialize client that will be used to send requests. This client only needs to be created
37 | // once, and can be reused for multiple requests.
38 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
39 |
40 | String location = "US";
41 |
42 | DatasetInfo datasetInfo = DatasetInfo.newBuilder(datasetName).setLocation(location).build();
43 |
44 | Dataset newDataset = bigquery.create(datasetInfo);
45 | String newDatasetName = newDataset.getDatasetId().getDataset();
46 | System.out.println(newDatasetName + " created successfully");
47 | } catch (BigQueryException e) {
48 | System.out.println("Dataset was not created. \n" + e.toString());
49 | }
50 | }
51 | }
52 | // [END bigquery_create_dataset]
53 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryJobOptionalIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryJobOptionalIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryBatch() {
54 | String query =
55 | "SELECT name, gender, SUM(number) AS total FROM "
56 | + "bigquery-public-data.usa_names.usa_1910_2013 GROUP BY "
57 | + "name, gender ORDER BY total DESC LIMIT 10";
58 |
59 | QueryJobOptional.queryJobOptional(query);
60 | assertThat(bout.toString()).contains("Query was run");
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryDryRunIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class QueryDryRunIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testQueryDryRun() {
54 | String query =
55 | "SELECT name, COUNT(*) as name_count "
56 | + "FROM `bigquery-public-data.usa_names.usa_1910_2013` "
57 | + "WHERE state = 'WA' "
58 | + "GROUP BY name";
59 |
60 | QueryDryRun.queryDryRun(query);
61 | assertThat(bout.toString()).contains("Query dry run performed successfully.");
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/AuthSnippetsIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Google Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 | import org.junit.runner.RunWith;
29 | import org.junit.runners.JUnit4;
30 |
31 | /** Tests for auth samples. */
32 | @RunWith(JUnit4.class)
33 | @SuppressWarnings("checkstyle:abbreviationaswordinname")
34 | public class AuthSnippetsIT {
35 |
36 | private final Logger log = Logger.getLogger(this.getClass().getName());
37 | private ByteArrayOutputStream bout;
38 | private PrintStream out;
39 | private PrintStream originalPrintStream;
40 |
41 | @Before
42 | public void setUp() {
43 | bout = new ByteArrayOutputStream();
44 | out = new PrintStream(bout);
45 | originalPrintStream = System.out;
46 | System.setOut(out);
47 | }
48 |
49 | @After
50 | public void tearDown() {
51 | // restores print statements in the original method
52 | System.out.flush();
53 | System.setOut(originalPrintStream);
54 | log.log(Level.INFO, "\n" + bout.toString());
55 | }
56 |
57 | @Test
58 | public void testAuthSnippetsImplicit() throws Exception {
59 | AuthSnippets.main(new String[] {"implicit"});
60 | String got = bout.toString();
61 | assertThat(got).contains("Datasets:");
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/SimpleQueryConnectionReadApiIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2024 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class SimpleQueryConnectionReadApiIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 | }
43 |
44 | @After
45 | public void tearDown() {
46 | // restores print statements in the original method
47 | System.out.flush();
48 | System.setOut(originalPrintStream);
49 | log.log(Level.INFO, "\n" + bout.toString());
50 | }
51 |
52 | @Test
53 | public void testSimpleQueryConnectionReadApi() {
54 | String query =
55 | "SELECT corpus, count(*) as corpus_count "
56 | + "FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;";
57 |
58 | SimpleQueryConnectionReadApi.simpleQueryConnectionReadApi(query);
59 | assertThat(bout.toString()).contains("Query ran successfully");
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import static org.junit.Assert.assertEquals;
20 |
21 | import org.junit.Test;
22 |
23 | public class JobIdTest {
24 |
25 | private static final JobId JOB = JobId.of("job");
26 | private static final JobId JOB_COMPLETE = JobId.of("project", "job");
27 |
28 | @Test
29 | public void testOf() {
30 | assertEquals(null, JOB.getProject());
31 | assertEquals("job", JOB.getJob());
32 | assertEquals("project", JOB_COMPLETE.getProject());
33 | assertEquals("job", JOB_COMPLETE.getJob());
34 | }
35 |
36 | @Test
37 | public void testEquals() {
38 | compareJobs(JOB, JobId.of("job"));
39 | compareJobs(JOB_COMPLETE, JobId.of("project", "job"));
40 | }
41 |
42 | @Test
43 | public void testToPbAndFromPb() {
44 | compareJobs(JOB, JobId.fromPb(JOB.toPb()));
45 | compareJobs(JOB_COMPLETE, JobId.fromPb(JOB_COMPLETE.toPb()));
46 | }
47 |
48 | @Test
49 | public void testSetProjectId() {
50 | assertEquals(JOB_COMPLETE, JOB.setProjectId("project"));
51 | }
52 |
53 | private void compareJobs(JobId expected, JobId value) {
54 | assertEquals(expected, value);
55 | assertEquals(expected.hashCode(), value.hashCode());
56 | assertEquals(expected.toString(), value.toString());
57 | assertEquals(expected.getProject(), value.getProject());
58 | assertEquals(expected.getJob(), value.getJob());
59 | assertEquals(expected.hashCode(), value.hashCode());
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/UpdateDatasetDescription.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_update_dataset_description]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 |
25 | public class UpdateDatasetDescription {
26 |
27 | public static void main(String[] args) {
28 | // TODO(developer): Replace these variables before running the sample.
29 | String datasetName = "MY_DATASET_NAME";
30 | String newDescription = "this is the new dataset description";
31 | updateDatasetDescription(datasetName, newDescription);
32 | }
33 |
34 | public static void updateDatasetDescription(String datasetName, String newDescription) {
35 | try {
36 | // Initialize client that will be used to send requests. This client only needs to be created
37 | // once, and can be reused for multiple requests.
38 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
39 |
40 | Dataset dataset = bigquery.getDataset(datasetName);
41 | bigquery.update(dataset.toBuilder().setDescription(newDescription).build());
42 | System.out.println("Dataset description updated successfully to " + newDescription);
43 | } catch (BigQueryException e) {
44 | System.out.println("Dataset description was not updated \n" + e.toString());
45 | }
46 | }
47 | }
48 | // [END bigquery_update_dataset_description]
49 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/GetJobIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class GetJobIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private String jobName;
33 | private ByteArrayOutputStream bout;
34 | private PrintStream out;
35 | private PrintStream originalPrintStream;
36 |
37 | @Before
38 | public void setUp() {
39 | bout = new ByteArrayOutputStream();
40 | out = new PrintStream(bout);
41 | originalPrintStream = System.out;
42 | System.setOut(out);
43 |
44 | String query = "SELECT country_name from `bigquery-public-data.utility_us.country_code_iso`";
45 | CreateJob.createJob(query);
46 | String result = bout.toString();
47 | jobName = result.substring(result.lastIndexOf(".") + 1);
48 | }
49 |
50 | @After
51 | public void tearDown() {
52 | // restores print statements in the original method
53 | System.out.flush();
54 | System.setOut(originalPrintStream);
55 | log.log(Level.INFO, "\n" + bout.toString());
56 | }
57 |
58 | @Test
59 | public void testGetJob() {
60 | GetJob.getJob(jobName);
61 | assertThat(bout.toString()).contains("Job retrieved successfully");
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/ListJobsIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 |
29 | public class ListJobsIT {
30 |
31 | private final Logger log = Logger.getLogger(this.getClass().getName());
32 | private ByteArrayOutputStream bout;
33 | private PrintStream out;
34 | private PrintStream originalPrintStream;
35 |
36 | @Before
37 | public void setUp() {
38 | bout = new ByteArrayOutputStream();
39 | out = new PrintStream(bout);
40 | originalPrintStream = System.out;
41 | System.setOut(out);
42 |
43 | // Create a new job
44 | String query =
45 | "SELECT name"
46 | + " FROM `bigquery-public-data.usa_names.usa_1910_2013`"
47 | + " WHERE state = 'TX'"
48 | + " LIMIT 100;";
49 | CreateJob.createJob(query);
50 | }
51 |
52 | @After
53 | public void tearDown() {
54 | // Clean up
55 | // restores print statements in the original method
56 | System.out.flush();
57 | System.setOut(originalPrintStream);
58 | log.log(Level.INFO, "\n" + bout.toString());
59 | }
60 |
61 | @Test
62 | public void testListJobs() {
63 | ListJobs.listJobs();
64 | assertThat(bout.toString()).contains("Success! Job ID");
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Option.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import static com.google.common.base.Preconditions.checkNotNull;
20 |
21 | import com.google.cloud.bigquery.spi.v2.BigQueryRpc;
22 | import com.google.common.base.MoreObjects;
23 | import java.io.Serializable;
24 | import java.util.Objects;
25 |
26 | /** Base class for BigQuery operation option. */
27 | abstract class Option implements Serializable {
28 |
29 | private static final long serialVersionUID = -6647817677804099207L;
30 |
31 | private final BigQueryRpc.Option rpcOption;
32 | private final Object value;
33 |
34 | Option(BigQueryRpc.Option rpcOption, Object value) {
35 | this.rpcOption = checkNotNull(rpcOption);
36 | this.value = value;
37 | }
38 |
39 | BigQueryRpc.Option getRpcOption() {
40 | return rpcOption;
41 | }
42 |
43 | Object getValue() {
44 | return value;
45 | }
46 |
47 | @Override
48 | public boolean equals(Object obj) {
49 | if (!(obj instanceof Option)) {
50 | return false;
51 | }
52 | Option other = (Option) obj;
53 | return Objects.equals(rpcOption, other.rpcOption) && Objects.equals(value, other.value);
54 | }
55 |
56 | @Override
57 | public int hashCode() {
58 | return Objects.hash(rpcOption, value);
59 | }
60 |
61 | @Override
62 | public String toString() {
63 | return MoreObjects.toStringHelper(this)
64 | .add("name", rpcOption.value())
65 | .add("value", value)
66 | .toString();
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/GetTableLabels.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_get_table_labels]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Table;
24 | import com.google.cloud.bigquery.TableId;
25 |
26 | // Sample to get table labels
27 | public class GetTableLabels {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | String tableName = "MY_TABLE_NAME";
33 | getTableLabels(datasetName, tableName);
34 | }
35 |
36 | public static void getTableLabels(String datasetName, String tableName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | // This example table starts with existing label { color: 'green' }
43 | Table table = bigquery.getTable(TableId.of(datasetName, tableName));
44 | table
45 | .getLabels()
46 | .forEach((key, value) -> System.out.println("Retrieved labels successfully"));
47 | } catch (BigQueryException e) {
48 | System.out.println("Label was not deleted. \n" + e.toString());
49 | }
50 | }
51 | }
52 | // [END bigquery_get_table_labels]
53 |
--------------------------------------------------------------------------------
/samples/snippets/src/test/java/com/example/bigquery/QueryClusteredTableIT.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.PrintStream;
23 | import java.util.logging.Level;
24 | import java.util.logging.Logger;
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Ignore;
28 | import org.junit.Test;
29 |
30 | @Ignore
31 | public class QueryClusteredTableIT {
32 |
33 | private final Logger log = Logger.getLogger(this.getClass().getName());
34 | private ByteArrayOutputStream bout;
35 | private PrintStream out;
36 | private PrintStream originalPrintStream;
37 |
38 | @Before
39 | public void setUp() {
40 | bout = new ByteArrayOutputStream();
41 | out = new PrintStream(bout);
42 | originalPrintStream = System.out;
43 | System.setOut(out);
44 | }
45 |
46 | @After
47 | public void tearDown() {
48 | // restores print statements in the original method
49 | System.out.flush();
50 | System.setOut(originalPrintStream);
51 | log.log(Level.INFO, "\n" + bout.toString());
52 | }
53 |
54 | @Test
55 | public void queryClusteredTable() {
56 | String projectId = "java-docs-samples-testing";
57 | String datasetName = "bigquery_test_dataset";
58 | String tableName = "clustered_shakespeare";
59 |
60 | QueryClusteredTable.queryClusteredTable(projectId, datasetName, tableName);
61 | assertThat(bout.toString()).contains("Query clustered table performed successfully.");
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/spi/v2/HttpBigQueryRpcTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.cloud.bigquery.spi.v2;
17 |
18 | import static com.google.common.truth.Truth.assertThat;
19 |
20 | import com.google.api.services.bigquery.model.Dataset;
21 | import com.google.api.services.bigquery.model.DatasetList;
22 | import com.google.api.services.bigquery.model.DatasetReference;
23 | import java.util.Collections;
24 | import org.junit.Test;
25 |
26 | public class HttpBigQueryRpcTest {
27 | @Test
28 | public void testListToDataset() {
29 | DatasetReference datasetRef =
30 | new DatasetReference().setDatasetId("dataset-id").setProjectId("project-id");
31 |
32 | DatasetList.Datasets listDataSet =
33 | new DatasetList.Datasets()
34 | .setDatasetReference(datasetRef)
35 | .setId("project-id:dataset-id")
36 | .setFriendlyName("friendly")
37 | .setKind("bigquery#dataset")
38 | .setLabels(Collections.singletonMap("foo", "bar"))
39 | .setLocation("test-region-1");
40 | Dataset dataset = HttpBigQueryRpc.LIST_TO_DATASET.apply(listDataSet);
41 |
42 | assertThat(dataset.getKind()).isEqualTo("bigquery#dataset");
43 | assertThat(dataset.getId()).isEqualTo("project-id:dataset-id");
44 | assertThat(dataset.getFriendlyName()).isEqualTo("friendly");
45 | assertThat(dataset.getDatasetReference()).isEqualTo(datasetRef);
46 | assertThat(dataset.getLabels()).containsExactly("foo", "bar");
47 | assertThat(dataset.getLocation()).isEqualTo("test-region-1");
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import static org.junit.Assert.assertEquals;
20 |
21 | import org.junit.Test;
22 |
23 | public class DatasetIdTest {
24 |
25 | private static final DatasetId DATASET = DatasetId.of("dataset");
26 | private static final DatasetId DATASET_COMPLETE = DatasetId.of("project", "dataset");
27 |
28 | @Test
29 | public void testOf() {
30 | assertEquals(null, DATASET.getProject());
31 | assertEquals("dataset", DATASET.getDataset());
32 | assertEquals("project", DATASET_COMPLETE.getProject());
33 | assertEquals("dataset", DATASET_COMPLETE.getDataset());
34 | }
35 |
36 | @Test
37 | public void testEquals() {
38 | compareDatasetIds(DATASET, DatasetId.of("dataset"));
39 | compareDatasetIds(DATASET_COMPLETE, DatasetId.of("project", "dataset"));
40 | }
41 |
42 | @Test
43 | public void testToPbAndFromPb() {
44 | compareDatasetIds(DATASET, DatasetId.fromPb(DATASET.toPb()));
45 | compareDatasetIds(DATASET_COMPLETE, DatasetId.fromPb(DATASET_COMPLETE.toPb()));
46 | }
47 |
48 | @Test
49 | public void testSetProjectId() {
50 | assertEquals(DATASET_COMPLETE, DATASET.setProjectId("project"));
51 | }
52 |
53 | private void compareDatasetIds(DatasetId expected, DatasetId value) {
54 | assertEquals(expected, value);
55 | assertEquals(expected.getProject(), value.getProject());
56 | assertEquals(expected.getDataset(), value.getDataset());
57 | assertEquals(expected.hashCode(), value.hashCode());
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/ListModels.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_list_models]
20 | import com.google.api.gax.paging.Page;
21 | import com.google.cloud.bigquery.BigQuery;
22 | import com.google.cloud.bigquery.BigQuery.ModelListOption;
23 | import com.google.cloud.bigquery.BigQueryException;
24 | import com.google.cloud.bigquery.BigQueryOptions;
25 | import com.google.cloud.bigquery.Model;
26 |
27 | public class ListModels {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | listModels(datasetName);
33 | }
34 |
35 | public static void listModels(String datasetName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | Page models = bigquery.listModels(datasetName, ModelListOption.pageSize(100));
42 | if (models == null) {
43 | System.out.println("Dataset does not contain any models.");
44 | return;
45 | }
46 | models
47 | .iterateAll()
48 | .forEach(model -> System.out.printf("Success! Model ID: %s", model.getModelId()));
49 | } catch (BigQueryException e) {
50 | System.out.println("Models not listed in dataset due to error: \n" + e.toString());
51 | }
52 | }
53 | }
54 | // [END bigquery_list_models]
55 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Clustering.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.google.cloud.bigquery;
17 |
18 | import com.google.auto.value.AutoValue;
19 | import com.google.common.collect.ImmutableList;
20 | import java.io.Serializable;
21 | import java.util.List;
22 | import javax.annotation.Nullable;
23 |
24 | @AutoValue
25 | public abstract class Clustering implements Serializable {
26 |
27 | private static final long serialVersionUID = 1L;
28 |
29 | @Nullable
30 | abstract ImmutableList getFieldsImmut();
31 |
32 | public List getFields() {
33 | return getFieldsImmut();
34 | }
35 |
36 | public abstract Builder toBuilder();
37 |
38 | @AutoValue.Builder
39 | public abstract static class Builder {
40 |
41 | abstract Builder setFieldsImmut(ImmutableList fieldsImmut);
42 |
43 | public Builder setFields(List fields) {
44 | return setFieldsImmut(ImmutableList.copyOf(fields));
45 | }
46 |
47 | public abstract Clustering build();
48 | }
49 |
50 | public static Builder newBuilder() {
51 | return new AutoValue_Clustering.Builder();
52 | }
53 |
54 | com.google.api.services.bigquery.model.Clustering toPb() {
55 | com.google.api.services.bigquery.model.Clustering clusterPb =
56 | new com.google.api.services.bigquery.model.Clustering();
57 | clusterPb.setFields(getFields());
58 | return clusterPb;
59 | }
60 |
61 | static Clustering fromPb(com.google.api.services.bigquery.model.Clustering clusterPb) {
62 | return newBuilder().setFields(clusterPb.getFields()).build();
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/DeleteDataset.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_delete_dataset]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQuery.DatasetDeleteOption;
22 | import com.google.cloud.bigquery.BigQueryException;
23 | import com.google.cloud.bigquery.BigQueryOptions;
24 | import com.google.cloud.bigquery.DatasetId;
25 |
26 | public class DeleteDataset {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String projectId = "MY_PROJECT_ID";
31 | String datasetName = "MY_DATASET_NAME";
32 | deleteDataset(projectId, datasetName);
33 | }
34 |
35 | public static void deleteDataset(String projectId, String datasetName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | DatasetId datasetId = DatasetId.of(projectId, datasetName);
42 | boolean success = bigquery.delete(datasetId, DatasetDeleteOption.deleteContents());
43 | if (success) {
44 | System.out.println("Dataset deleted successfully");
45 | } else {
46 | System.out.println("Dataset was not found");
47 | }
48 | } catch (BigQueryException e) {
49 | System.out.println("Dataset was not deleted. \n" + e.toString());
50 | }
51 | }
52 | }
53 | // [END bigquery_delete_dataset]
54 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DmlStatsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import static org.junit.Assert.assertEquals;
20 |
21 | import org.junit.Test;
22 |
23 | public class DmlStatsTest {
24 |
25 | private static final Long DELETED_ROW_COUNT = 10L;
26 | private static final Long INSERTED_ROW_COUNT = 20L;
27 | private static final Long UPDATED_ROW_COUNT = 30L;
28 | private static final DmlStats DML_STATS =
29 | DmlStats.newBuilder()
30 | .setDeletedRowCount(DELETED_ROW_COUNT)
31 | .setInsertedRowCount(INSERTED_ROW_COUNT)
32 | .setUpdatedRowCount(UPDATED_ROW_COUNT)
33 | .build();
34 |
35 | @Test
36 | public void testBuilder() {
37 | assertEquals(DELETED_ROW_COUNT, DML_STATS.getDeletedRowCount());
38 | assertEquals(UPDATED_ROW_COUNT, DML_STATS.getUpdatedRowCount());
39 | assertEquals(INSERTED_ROW_COUNT, DML_STATS.getInsertedRowCount());
40 | }
41 |
42 | @Test
43 | public void testToPbAndFromPb() {
44 | compareDmlStats(DML_STATS, DmlStats.fromPb(DML_STATS.toPb()));
45 | }
46 |
47 | private void compareDmlStats(DmlStats expected, DmlStats actual) {
48 | assertEquals(expected, actual);
49 | assertEquals(expected.hashCode(), actual.hashCode());
50 | assertEquals(expected.toString(), actual.toString());
51 | assertEquals(expected.getDeletedRowCount(), actual.getDeletedRowCount());
52 | assertEquals(expected.getInsertedRowCount(), actual.getInsertedRowCount());
53 | assertEquals(expected.getUpdatedRowCount(), actual.getUpdatedRowCount());
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/LabelDataset.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_label_dataset]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 | import java.util.HashMap;
25 | import java.util.Map;
26 |
27 | // Sample to updates a label on dataset
28 | public class LabelDataset {
29 |
30 | public static void main(String[] args) {
31 | // TODO(developer): Replace these variables before running the sample.
32 | String datasetName = "MY_DATASET_NAME";
33 | labelDataset(datasetName);
34 | }
35 |
36 | public static void labelDataset(String datasetName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | // This example dataset starts with existing label { color: 'green' }
43 | Dataset dataset = bigquery.getDataset(datasetName);
44 | // Add label to dataset
45 | Map labels = new HashMap<>();
46 | labels.put("color", "green");
47 |
48 | dataset.toBuilder().setLabels(labels).build().update();
49 | System.out.println("Label added successfully");
50 | } catch (BigQueryException e) {
51 | System.out.println("Label was not added. \n" + e.toString());
52 | }
53 | }
54 | }
55 | // [END bigquery_label_dataset]
56 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/PrimaryKeyTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import static org.junit.Assert.assertEquals;
20 | import static org.junit.Assert.assertTrue;
21 |
22 | import java.util.Arrays;
23 | import java.util.List;
24 | import org.junit.Test;
25 |
26 | public class PrimaryKeyTest {
27 | private static final List COLUMNS = Arrays.asList("column1", "column2");
28 | private static final PrimaryKey PRIMARY_KEY = PrimaryKey.newBuilder().setColumns(COLUMNS).build();
29 |
30 | @Test
31 | public void testToBuilder() {
32 | comparePrimaryKeyDefinition(PRIMARY_KEY, PRIMARY_KEY.toBuilder().build());
33 | PrimaryKey primaryKey =
34 | PRIMARY_KEY.toBuilder().setColumns(Arrays.asList("col1", "col2", "col3")).build();
35 | assertEquals(Arrays.asList("col1", "col2", "col3"), primaryKey.getColumns());
36 | }
37 |
38 | @Test
39 | public void testBuilder() {
40 | assertEquals(COLUMNS, PRIMARY_KEY.getColumns());
41 | PrimaryKey primaryKey = PRIMARY_KEY.newBuilder().setColumns(COLUMNS).build();
42 | assertEquals(PRIMARY_KEY, primaryKey);
43 | }
44 |
45 | @Test
46 | public void testToAndFromPb() {
47 | PrimaryKey primaryKey = PRIMARY_KEY.toBuilder().build();
48 | assertTrue(PrimaryKey.fromPb(primaryKey.toPb()) instanceof PrimaryKey);
49 | comparePrimaryKeyDefinition(primaryKey, PrimaryKey.fromPb(primaryKey.toPb()));
50 | }
51 |
52 | private void comparePrimaryKeyDefinition(PrimaryKey expected, PrimaryKey value) {
53 | assertEquals(expected.getColumns(), value.getColumns());
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/UpdateTableDescription.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_update_table_description]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Table;
24 |
25 | public class UpdateTableDescription {
26 |
27 | public static void main(String[] args) {
28 | // TODO(developer): Replace these variables before running the sample.
29 | String datasetName = "MY_DATASET_NAME";
30 | String tableName = "MY_TABLE_NAME";
31 | String newDescription = "this is the new table description";
32 | updateTableDescription(datasetName, tableName, newDescription);
33 | }
34 |
35 | public static void updateTableDescription(
36 | String datasetName, String tableName, String newDescription) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | Table table = bigquery.getTable(datasetName, tableName);
43 | bigquery.update(table.toBuilder().setDescription(newDescription).build());
44 | System.out.println("Table description updated successfully to " + newDescription);
45 | } catch (BigQueryException e) {
46 | System.out.println("Table description was not updated \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_update_table_description]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/ListDatasets.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_list_datasets]
20 | import com.google.api.gax.paging.Page;
21 | import com.google.cloud.bigquery.BigQuery;
22 | import com.google.cloud.bigquery.BigQuery.DatasetListOption;
23 | import com.google.cloud.bigquery.BigQueryException;
24 | import com.google.cloud.bigquery.BigQueryOptions;
25 | import com.google.cloud.bigquery.Dataset;
26 |
27 | public class ListDatasets {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String projectId = "MY_PROJECT_ID";
32 | listDatasets(projectId);
33 | }
34 |
35 | public static void listDatasets(String projectId) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | Page datasets = bigquery.listDatasets(projectId, DatasetListOption.pageSize(100));
42 | if (datasets == null) {
43 | System.out.println("Dataset does not contain any models");
44 | return;
45 | }
46 | datasets
47 | .iterateAll()
48 | .forEach(
49 | dataset -> System.out.printf("Success! Dataset ID: %s ", dataset.getDatasetId()));
50 | } catch (BigQueryException e) {
51 | System.out.println("Project does not contain any datasets \n" + e.toString());
52 | }
53 | }
54 | }
55 | // [END bigquery_list_datasets]
56 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/ListRoutines.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_list_routines]
20 | import com.google.api.gax.paging.Page;
21 | import com.google.cloud.bigquery.BigQuery;
22 | import com.google.cloud.bigquery.BigQueryException;
23 | import com.google.cloud.bigquery.BigQueryOptions;
24 | import com.google.cloud.bigquery.Routine;
25 |
26 | // Sample to get list of routines
27 | public class ListRoutines {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | listRoutines(datasetName);
33 | }
34 |
35 | public static void listRoutines(String datasetName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | Page routines =
42 | bigquery.listRoutines(datasetName, BigQuery.RoutineListOption.pageSize(100));
43 | if (routines == null) {
44 | System.out.println("Dataset does not contain any routines.");
45 | return;
46 | }
47 | routines
48 | .iterateAll()
49 | .forEach(routine -> System.out.printf("Success! Routine ID: %s", routine.getRoutineId()));
50 | } catch (BigQueryException e) {
51 | System.out.println("Routines not listed in dataset due to error: \n" + e.toString());
52 | }
53 | }
54 | }
55 | // [END bigquery_list_routines]
56 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/UpdateDatasetExpiration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_update_dataset_expiration]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 | import java.util.concurrent.TimeUnit;
25 |
26 | public class UpdateDatasetExpiration {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | // Update dataset expiration to one day
32 | Long newExpiration = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);
33 | updateDatasetExpiration(datasetName, newExpiration);
34 | }
35 |
36 | public static void updateDatasetExpiration(String datasetName, Long newExpiration) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | Dataset dataset = bigquery.getDataset(datasetName);
43 | bigquery.update(dataset.toBuilder().setDefaultTableLifetime(newExpiration).build());
44 | System.out.println("Dataset description updated successfully to " + newExpiration);
45 | } catch (BigQueryException e) {
46 | System.out.println("Dataset expiration was not updated \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_update_dataset_expiration]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/TableExists.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_table_exists]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Table;
24 | import com.google.cloud.bigquery.TableId;
25 |
26 | // Sample to check table exist
27 | public class TableExists {
28 |
29 | public static void main(String[] args) {
30 | // TODO(developer): Replace these variables before running the sample.
31 | String datasetName = "MY_DATASET_NAME";
32 | String tableName = "MY_TABLE_NAME";
33 | tableExists(datasetName, tableName);
34 | }
35 |
36 | public static void tableExists(String datasetName, String tableName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | Table table = bigquery.getTable(TableId.of(datasetName, tableName));
43 | if (table != null
44 | && table
45 | .exists()) { // table will be null if it is not found and setThrowNotFound is not set
46 | // to `true`
47 | System.out.println("Table already exist");
48 | } else {
49 | System.out.println("Table not found");
50 | }
51 | } catch (BigQueryException e) {
52 | System.out.println("Table not found. \n" + e.toString());
53 | }
54 | }
55 | }
56 | // [END bigquery_table_exists]
57 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/UpdateTableRequirePartitionFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_update_table_require_partition_filter]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Table;
24 |
25 | // Sample to update require partition filter on a table.
26 | public class UpdateTableRequirePartitionFilter {
27 |
28 | public static void runUpdateTableRequirePartitionFilter() {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | String tableName = "MY_TABLE_NAME";
32 | updateTableRequirePartitionFilter(datasetName, tableName);
33 | }
34 |
35 | public static void updateTableRequirePartitionFilter(String datasetName, String tableName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | Table table = bigquery.getTable(datasetName, tableName);
42 | table.toBuilder().setRequirePartitionFilter(true).build().update();
43 |
44 | System.out.println("Table require partition filter updated successfully");
45 | } catch (BigQueryException e) {
46 | System.out.println("Table require partition filter was not updated \n" + e.toString());
47 | }
48 | }
49 | }
50 | // [END bigquery_update_table_require_partition_filter]
51 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/DeleteLabelDataset.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_delete_label_dataset]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.Dataset;
24 | import java.util.HashMap;
25 | import java.util.Map;
26 |
27 | // Sample tp deletes a label on a dataset.
28 | public class DeleteLabelDataset {
29 |
30 | public static void main(String[] args) {
31 | // TODO(developer): Replace these variables before running the sample.
32 | String datasetName = "MY_DATASET_NAME";
33 | deleteLabelDataset(datasetName);
34 | }
35 |
36 | public static void deleteLabelDataset(String datasetName) {
37 | try {
38 | // Initialize client that will be used to send requests. This client only needs to be created
39 | // once, and can be reused for multiple requests.
40 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
41 |
42 | // This example dataset starts with existing label { color: 'green' }
43 | Dataset dataset = bigquery.getDataset(datasetName);
44 | // Add label to dataset
45 | Map labels = new HashMap<>();
46 | labels.put("color", null);
47 |
48 | dataset.toBuilder().setLabels(labels).build().update();
49 | System.out.println("Dataset label deleted successfully");
50 | } catch (BigQueryException e) {
51 | System.out.println("Dataset label was not deleted. \n" + e.toString());
52 | }
53 | }
54 | }
55 | // [END bigquery_delete_label_dataset]
56 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/ListTables.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_list_tables]
20 | import com.google.api.gax.paging.Page;
21 | import com.google.cloud.bigquery.BigQuery;
22 | import com.google.cloud.bigquery.BigQuery.TableListOption;
23 | import com.google.cloud.bigquery.BigQueryException;
24 | import com.google.cloud.bigquery.BigQueryOptions;
25 | import com.google.cloud.bigquery.DatasetId;
26 | import com.google.cloud.bigquery.Table;
27 |
28 | public class ListTables {
29 |
30 | public static void main(String[] args) {
31 | // TODO(developer): Replace these variables before running the sample.
32 | String projectId = "bigquery-public-data";
33 | String datasetName = "samples";
34 | listTables(projectId, datasetName);
35 | }
36 |
37 | public static void listTables(String projectId, String datasetName) {
38 | try {
39 | // Initialize client that will be used to send requests. This client only needs to be created
40 | // once, and can be reused for multiple requests.
41 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
42 |
43 | DatasetId datasetId = DatasetId.of(projectId, datasetName);
44 | Page tables = bigquery.listTables(datasetId, TableListOption.pageSize(100));
45 | tables.iterateAll().forEach(table -> System.out.print(table.getTableId().getTable() + "\n"));
46 |
47 | System.out.println("Tables listed successfully.");
48 | } catch (BigQueryException e) {
49 | System.out.println("Tables were not listed. Error occurred: " + e.toString());
50 | }
51 | }
52 | }
53 | // [END bigquery_list_tables]
54 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/DeleteMaterializedView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_delete_materialized_view]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.TableId;
24 |
25 | // Sample to delete materialized view
26 | public class DeleteMaterializedView {
27 |
28 | public static void main(String[] args) {
29 | // TODO(developer): Replace these variables before running the sample.
30 | String datasetName = "MY_DATASET_NAME";
31 | String materializedViewName = "MY_MATERIALIZED_VIEW_NAME";
32 | deleteMaterializedView(datasetName, materializedViewName);
33 | }
34 |
35 | public static void deleteMaterializedView(String datasetName, String materializedViewName) {
36 | try {
37 | // Initialize client that will be used to send requests. This client only needs to be created
38 | // once, and can be reused for multiple requests.
39 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
40 |
41 | TableId tableId = TableId.of(datasetName, materializedViewName);
42 |
43 | boolean success = bigquery.delete(tableId);
44 | if (success) {
45 | System.out.println("Materialized view deleted successfully");
46 | } else {
47 | System.out.println("Materialized view was not found");
48 | }
49 | } catch (BigQueryException e) {
50 | System.out.println("Materialized view was not found. \n" + e.toString());
51 | }
52 | }
53 | }
54 | // [END bigquery_delete_materialized_view]
55 |
--------------------------------------------------------------------------------
/samples/snippets/src/main/java/com/example/bigquery/RunLegacyQuery.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.bigquery;
18 |
19 | // [START bigquery_query_legacy]
20 | import com.google.cloud.bigquery.BigQuery;
21 | import com.google.cloud.bigquery.BigQueryException;
22 | import com.google.cloud.bigquery.BigQueryOptions;
23 | import com.google.cloud.bigquery.QueryJobConfiguration;
24 | import com.google.cloud.bigquery.TableResult;
25 |
26 | public class RunLegacyQuery {
27 |
28 | public static void main(String[] args) {
29 | runLegacyQuery();
30 | }
31 |
32 | public static void runLegacyQuery() {
33 | try {
34 | // Initialize client that will be used to send requests. This client only needs to be created
35 | // once, and can be reused for multiple requests.
36 | BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
37 |
38 | // To use legacy SQL syntax, set useLegacySql to true.
39 | String query =
40 | "SELECT corpus FROM [bigquery-public-data:samples.shakespeare] GROUP BY corpus;";
41 | QueryJobConfiguration queryConfig =
42 | QueryJobConfiguration.newBuilder(query).setUseLegacySql(true).build();
43 |
44 | // Execute the query.
45 | TableResult result = bigquery.query(queryConfig);
46 |
47 | // Print the results.
48 | result.iterateAll().forEach(rows -> rows.forEach(row -> System.out.println(row.getValue())));
49 |
50 | System.out.println("Legacy query ran successfully");
51 | } catch (BigQueryException | InterruptedException e) {
52 | System.out.println("Legacy query did not run \n" + e.toString());
53 | }
54 | }
55 | }
56 | // [END bigquery_query_legacy]
57 |
--------------------------------------------------------------------------------
/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/AvroOptionsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.google.cloud.bigquery;
18 |
19 | import static org.junit.Assert.assertEquals;
20 |
21 | import org.junit.Test;
22 |
23 | public class AvroOptionsTest {
24 |
25 | private static final Boolean USE_AVRO_LOGICAL_TYPES = true;
26 | private static final AvroOptions AVRO_OPTIONS =
27 | AvroOptions.newBuilder().setUseAvroLogicalTypes(USE_AVRO_LOGICAL_TYPES).build();
28 |
29 | @Test
30 | public void testToBuilder() {
31 | compareAvroOptions(AVRO_OPTIONS, AVRO_OPTIONS.toBuilder().build());
32 | AvroOptions avroOptions = AVRO_OPTIONS.toBuilder().setUseAvroLogicalTypes(false).build();
33 | assertEquals(false, avroOptions.useAvroLogicalTypes());
34 | avroOptions = avroOptions.toBuilder().setUseAvroLogicalTypes(true).build();
35 | compareAvroOptions(AVRO_OPTIONS, avroOptions);
36 | }
37 |
38 | @Test
39 | public void testBuilder() {
40 | assertEquals(FormatOptions.AVRO, AVRO_OPTIONS.getType());
41 | assertEquals(USE_AVRO_LOGICAL_TYPES, AVRO_OPTIONS.useAvroLogicalTypes());
42 | }
43 |
44 | @Test
45 | public void testToAndFromPb() {
46 | compareAvroOptions(AVRO_OPTIONS, AvroOptions.fromPb(AVRO_OPTIONS.toPb()));
47 | AvroOptions avroOptions =
48 | AvroOptions.newBuilder().setUseAvroLogicalTypes(USE_AVRO_LOGICAL_TYPES).build();
49 | compareAvroOptions(avroOptions, AvroOptions.fromPb(avroOptions.toPb()));
50 | }
51 |
52 | private void compareAvroOptions(AvroOptions expected, AvroOptions value) {
53 | assertEquals(expected, value);
54 | assertEquals(expected.useAvroLogicalTypes(), value.useAvroLogicalTypes());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------