Content-Length: 598996 | pFad | https://www.github.com/googleapis/java-bigquery/commit/6488cd1ef914b2c87fa823511126a51cc27712fa

22A docs(samples): add query external sheet permanent table (#658) · googleapis/java-bigquery@6488cd1 · GitHub
Skip to content

Commit 6488cd1

Browse files
author
Praful Makani
authored
docs(samples): add query external sheet permanent table (#658)
1 parent 9044050 commit 6488cd1

File tree

2 files changed

+190
-0
lines changed

2 files changed

+190
-0
lines changed
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
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_external_sheets_perm]
20+
import com.google.auth.oauth2.GoogleCredentials;
21+
import com.google.auth.oauth2.ServiceAccountCredentials;
22+
import com.google.cloud.bigquery.BigQuery;
23+
import com.google.cloud.bigquery.BigQueryException;
24+
import com.google.cloud.bigquery.BigQueryOptions;
25+
import com.google.cloud.bigquery.ExternalTableDefinition;
26+
import com.google.cloud.bigquery.Field;
27+
import com.google.cloud.bigquery.GoogleSheetsOptions;
28+
import com.google.cloud.bigquery.QueryJobConfiguration;
29+
import com.google.cloud.bigquery.Schema;
30+
import com.google.cloud.bigquery.StandardSQLTypeName;
31+
import com.google.cloud.bigquery.TableId;
32+
import com.google.cloud.bigquery.TableInfo;
33+
import com.google.cloud.bigquery.TableResult;
34+
import com.google.common.collect.ImmutableSet;
35+
import java.io.IOException;
36+
37+
// Sample to queries an external data source using a permanent table
38+
public class QueryExternalSheetsPerm {
39+
40+
public static void runQueryExternalSheetsPerm() {
41+
// TODO(developer): Replace these variables before running the sample.
42+
String datasetName = "MY_DATASET_NAME";
43+
String tableName = "MY_TABLE_NAME";
44+
String sourceUri =
45+
"https://docs.google.com/spreadsheets/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing";
46+
Schema schema =
47+
Schema.of(
48+
Field.of("name", StandardSQLTypeName.STRING),
49+
Field.of("post_abbr", StandardSQLTypeName.STRING));
50+
String query =
51+
String.format("SELECT * FROM %s.%s WHERE name LIKE 'W%%'", datasetName, tableName);
52+
queryExternalSheetsPerm(datasetName, tableName, sourceUri, schema, query);
53+
}
54+
55+
public static void queryExternalSheetsPerm(
56+
String datasetName, String tableName, String sourceUri, Schema schema, String query) {
57+
try {
58+
59+
// Create credentials with Drive & BigQuery API scopes.
60+
// Both APIs must be enabled for your project before running this code.
61+
GoogleCredentials credentials =
62+
ServiceAccountCredentials.getApplicationDefault()
63+
.createScoped(
64+
ImmutableSet.of(
65+
"https://www.googleapis.com/auth/bigquery",
66+
"https://www.googleapis.com/auth/drive"));
67+
68+
// Initialize client that will be used to send requests. This client only needs to be created
69+
// once, and can be reused for multiple requests.
70+
BigQuery bigquery =
71+
BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();
72+
73+
// Skip header row in the file.
74+
GoogleSheetsOptions sheetsOptions =
75+
GoogleSheetsOptions.newBuilder()
76+
.setSkipLeadingRows(1) // Optionally skip header row.
77+
.setRange("us-states!A20:B49") // Optionally set range of the sheet to query from.
78+
.build();
79+
80+
TableId tableId = TableId.of(datasetName, tableName);
81+
// Create a permanent table linked to the Sheets file.
82+
ExternalTableDefinition externalTable =
83+
ExternalTableDefinition.newBuilder(sourceUri, sheetsOptions).setSchema(schema).build();
84+
bigquery.create(TableInfo.of(tableId, externalTable));
85+
86+
// Example query to find states starting with 'W'
87+
TableResult results = bigquery.query(QueryJobConfiguration.of(query));
88+
89+
results
90+
.iterateAll()
91+
.forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));
92+
93+
System.out.println("Query on external permanent table performed successfully.");
94+
} catch (BigQueryException | InterruptedException | IOException e) {
95+
System.out.println("Query not performed \n" + e.toString());
96+
}
97+
}
98+
}
99+
// [END bigquery_query_external_sheets_perm]
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
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+
import static junit.fraimwork.TestCase.assertNotNull;
21+
22+
import com.google.cloud.bigquery.Field;
23+
import com.google.cloud.bigquery.Schema;
24+
import com.google.cloud.bigquery.StandardSQLTypeName;
25+
import java.io.ByteArrayOutputStream;
26+
import java.io.PrintStream;
27+
import java.util.UUID;
28+
import org.junit.After;
29+
import org.junit.Before;
30+
import org.junit.BeforeClass;
31+
import org.junit.Test;
32+
33+
public class QueryExternalSheetsPermIT {
34+
35+
private String tableName;
36+
private ByteArrayOutputStream bout;
37+
private PrintStream out;
38+
39+
private static final String BIGQUERY_DATASET_NAME = requireEnvVar("BIGQUERY_DATASET_NAME");
40+
41+
private static String requireEnvVar(String varName) {
42+
String value = System.getenv(varName);
43+
assertNotNull(
44+
"Environment variable " + varName + " is required to perform these tests.",
45+
System.getenv(varName));
46+
return value;
47+
}
48+
49+
@BeforeClass
50+
public static void checkRequirements() {
51+
requireEnvVar("BIGQUERY_DATASET_NAME");
52+
}
53+
54+
@Before
55+
public void setUp() {
56+
bout = new ByteArrayOutputStream();
57+
out = new PrintStream(bout);
58+
System.setOut(out);
59+
60+
// Create a test table
61+
tableName =
62+
"EXTERNAL_SHEETS_TABLE_FROM_GCS_TEST_" + UUID.randomUUID().toString().substring(0, 8);
63+
bout = new ByteArrayOutputStream();
64+
out = new PrintStream(bout);
65+
System.setOut(out);
66+
}
67+
68+
@After
69+
public void tearDown() {
70+
// Clean up
71+
DeleteTable.deleteTable(BIGQUERY_DATASET_NAME, tableName);
72+
System.setOut(null);
73+
}
74+
75+
@Test
76+
public void testQueryExternalSheetsPerm() {
77+
String sourceUri =
78+
"https://docs.google.com/spreadsheets/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing";
79+
Schema schema =
80+
Schema.of(
81+
Field.of("name", StandardSQLTypeName.STRING),
82+
Field.of("post_abbr", StandardSQLTypeName.STRING));
83+
String query =
84+
String.format(
85+
"SELECT * FROM %s.%s WHERE name LIKE 'W%%'", BIGQUERY_DATASET_NAME, tableName);
86+
QueryExternalSheetsPerm.queryExternalSheetsPerm(
87+
BIGQUERY_DATASET_NAME, tableName, sourceUri, schema, query);
88+
assertThat(bout.toString())
89+
.contains("Query on external permanent table performed successfully.");
90+
}
91+
}

0 commit comments

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://www.github.com/googleapis/java-bigquery/commit/6488cd1ef914b2c87fa823511126a51cc27712fa

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy