Skip to content

Commit 3902ba1

Browse files
docs(samples): add update table using dml query sample (#424)
Fixes #413
1 parent 9ca2064 commit 3902ba1

File tree

5 files changed

+235
-0
lines changed

5 files changed

+235
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{"id":"2ad525d6-c832-4c3d-b7fe-59d104885519","user_id":"38","login_time":"1.47766087E9","logout_time":"1.477661109E9","ip_address":"192.0.2.12"}
2+
{"id":"53d65e20-6ea9-4650-98d9-a2111fbd1122","user_id":"88","login_time":"1.47707544E9","logout_time":"1.477075519E9","ip_address":"192.0.2.88"}
3+
{"id":"5e6c3021-d5e7-4ccd-84b2-adfa9176d13d","user_id":"39","login_time":"1.474022869E9","logout_time":"1.474022961E9","ip_address":"203.0.113.52"}
4+
{"id":"6196eefa-1498-4567-8ef0-498845b888d9","user_id":"52","login_time":"1.478604612E9","logout_time":"1.478604691E9","ip_address":"203.0.113.169"}
5+
{"id":"70656dc5-7e0f-49cf-9e00-f06ed93c1f5b","user_id":"46","login_time":"1.474089924E9","logout_time":"1.474090227E9","ip_address":"192.0.2.10"}
6+
{"id":"aafa5eef-ad49-49a7-9a0f-fbc7fd639bd3","user_id":"40","login_time":"1.478031161E9","logout_time":"1.478031388E9","ip_address":"203.0.113.18"}
7+
{"id":"d2792fc2-24dd-4260-9456-3fbe6cdfdd90","user_id":"5","login_time":"1.481259081E9","logout_time":"1.481259247E9","ip_address":"192.0.2.140"}
8+
{"id":"d835dc49-32f9-4790-b4eb-dddee62e0dcc","user_id":"62","login_time":"1.478892977E9","logout_time":"1.478893219E9","ip_address":"203.0.113.83"}
9+
{"id":"f4a0d3c7-351f-471c-8e11-e093e7a6ce75","user_id":"89","login_time":"1.459031555E9","logout_time":"1.459031831E9","ip_address":"203.0.113.233"}
10+
{"id":"f6e9f526-5b22-4679-9c3e-56a636e815bb","user_id":"97","login_time":"1.482426034E9","logout_time":"1.482426415E9","ip_address":"203.0.113.167"}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{"id":"2ad525d6-c832-4c3d-b7fe-59d104885519","user_id":"38","login_time":"1.47766087E9","logout_time":"1.477661109E9","ip_address":"192.0.2.12"}
2+
{"id":"53d65e20-6ea9-4650-98d9-a2111fbd1122","user_id":"88","login_time":"1.47707544E9","logout_time":"1.477075519E9","ip_address":"192.0.2.88"}
3+
{"id":"5e6c3021-d5e7-4ccd-84b2-adfa9176d13d","user_id":"39","login_time":"1.474022869E9","logout_time":"1.474022961E9","ip_address":"203.0.113.52"}
4+
{"id":"6196eefa-1498-4567-8ef0-498845b888d9","user_id":"52","login_time":"1.478604612E9","logout_time":"1.478604691E9","ip_address":"203.0.113.169"}
5+
{"id":"70656dc5-7e0f-49cf-9e00-f06ed93c1f5b","user_id":"46","login_time":"1.474089924E9","logout_time":"1.474090227E9","ip_address":"192.0.2.10"}
6+
{"id":"aafa5eef-ad49-49a7-9a0f-fbc7fd639bd3","user_id":"40","login_time":"1.478031161E9","logout_time":"1.478031388E9","ip_address":"203.0.113.18"}
7+
{"id":"d2792fc2-24dd-4260-9456-3fbe6cdfdd90","user_id":"5","login_time":"1.481259081E9","logout_time":"1.481259247E9","ip_address":"192.0.2.140"}
8+
{"id":"d835dc49-32f9-4790-b4eb-dddee62e0dcc","user_id":"62","login_time":"1.478892977E9","logout_time":"1.478893219E9","ip_address":"203.0.113.83"}
9+
{"id":"f4a0d3c7-351f-471c-8e11-e093e7a6ce75","user_id":"89","login_time":"1.459031555E9","logout_time":"1.459031831E9","ip_address":"203.0.113.233"}
10+
{"id":"f6e9f526-5b22-4679-9c3e-56a636e815bb","user_id":"97","login_time":"1.482426034E9","logout_time":"1.482426415E9","ip_address":"203.0.113.167"}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
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_with_dml]
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.FormatOptions;
24+
import com.google.cloud.bigquery.Job;
25+
import com.google.cloud.bigquery.JobId;
26+
import com.google.cloud.bigquery.QueryJobConfiguration;
27+
import com.google.cloud.bigquery.QueryParameterValue;
28+
import com.google.cloud.bigquery.TableDataWriteChannel;
29+
import com.google.cloud.bigquery.TableId;
30+
import com.google.cloud.bigquery.TableResult;
31+
import com.google.cloud.bigquery.WriteChannelConfiguration;
32+
import java.io.IOException;
33+
import java.io.OutputStream;
34+
import java.nio.channels.Channels;
35+
import java.nio.file.FileSystems;
36+
import java.nio.file.Files;
37+
import java.nio.file.Path;
38+
import java.util.UUID;
39+
40+
// Sample to update data in BigQuery tables using DML query
41+
public class UpdateTableDML {
42+
43+
public static void runUpdateTableDML() throws IOException, InterruptedException {
44+
// TODO(developer): Replace these variables before running the sample.
45+
String datasetName = "MY_DATASET_NAME";
46+
String tableName = "MY_TABLE_NAME";
47+
updateTableDML(datasetName, tableName);
48+
}
49+
50+
public static void updateTableDML(String datasetName, String tableName)
51+
throws IOException, InterruptedException {
52+
try {
53+
// Initialize client that will be used to send requests. This client only needs to be created
54+
// once, and can be reused for multiple requests.
55+
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
56+
57+
// Load JSON file into UserSessions table
58+
TableId tableId = TableId.of(datasetName, tableName);
59+
60+
WriteChannelConfiguration writeChannelConfiguration =
61+
WriteChannelConfiguration.newBuilder(tableId)
62+
.setFormatOptions(FormatOptions.json())
63+
.build();
64+
65+
// Imports a local JSON file into a table.
66+
Path jsonPath = FileSystems.getDefault().getPath("src/test/resources", "userSessionsData.json");
67+
68+
// The location and JobName must be specified; other fields can be auto-detected.
69+
String jobName = "jobId_" + UUID.randomUUID().toString();
70+
JobId jobId = JobId.newBuilder().setLocation("us").setJob(jobName).build();
71+
72+
try (TableDataWriteChannel writer = bigquery.writer(jobId, writeChannelConfiguration);
73+
OutputStream stream = Channels.newOutputStream(writer)) {
74+
Files.copy(jsonPath, stream);
75+
}
76+
77+
// Get the Job created by the TableDataWriteChannel and wait for it to complete.
78+
Job job = bigquery.getJob(jobId);
79+
Job completedJob = job.waitFor();
80+
if (completedJob == null) {
81+
System.out.println("Job not executed since it no longer exists.");
82+
return;
83+
} else if (completedJob.getStatus().getError() != null) {
84+
System.out.println(
85+
"BigQuery was unable to load local file to the table due to an error: \n"
86+
+ job.getStatus().getError());
87+
return;
88+
}
89+
90+
System.out.println(job.getStatistics().toString() + " userSessionsData json uploaded successfully");
91+
92+
// Write a DML query to modify UserSessions table
93+
// To create DML query job to mask the last octet in every row's ip_address column
94+
String dmlQuery = String.format("UPDATE `%s.%s` \n"
95+
+ "SET ip_address = REGEXP_REPLACE(ip_address, r\"(\\.[0-9]+)$\", \".0\")\n"
96+
+ "WHERE TRUE", datasetName, tableName);
97+
98+
QueryJobConfiguration dmlQueryConfig =
99+
QueryJobConfiguration.newBuilder(dmlQuery).build();
100+
101+
// Execute the query.
102+
TableResult result = bigquery.query(dmlQueryConfig);
103+
104+
// Print the results.
105+
result.iterateAll().forEach(rows -> rows.forEach(row -> System.out.println(row.getValue())));
106+
107+
System.out.println("Table updated successfully using DML");
108+
} catch (BigQueryException e) {
109+
System.out.println("Table update failed \n" + e.toString());
110+
}
111+
}
112+
}
113+
// [END bigquery_update_with_dml]
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
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.framework.TestCase.assertNotNull;
21+
22+
import com.google.cloud.bigquery.Field;
23+
import com.google.cloud.bigquery.LegacySQLTypeName;
24+
import com.google.cloud.bigquery.Schema;
25+
import java.io.ByteArrayOutputStream;
26+
import java.io.IOException;
27+
import java.io.PrintStream;
28+
import java.nio.file.FileSystems;
29+
import java.nio.file.Path;
30+
import java.util.UUID;
31+
import org.junit.After;
32+
import org.junit.Before;
33+
import org.junit.BeforeClass;
34+
import org.junit.Test;
35+
36+
public class UpdateTableDMLIT {
37+
38+
private String tableName;
39+
private ByteArrayOutputStream bout;
40+
private PrintStream out;
41+
42+
private static final String BIGQUERY_DATASET_NAME = requireEnvVar("BIGQUERY_DATASET_NAME");
43+
44+
private static String requireEnvVar(String varName) {
45+
String value = System.getenv(varName);
46+
assertNotNull(
47+
"Environment variable " + varName + " is required to perform these tests.",
48+
System.getenv(varName));
49+
return value;
50+
}
51+
52+
@BeforeClass
53+
public static void checkRequirements() {
54+
requireEnvVar("BIGQUERY_DATASET_NAME");
55+
}
56+
57+
@Before
58+
public void setUp() {
59+
bout = new ByteArrayOutputStream();
60+
out = new PrintStream(bout);
61+
System.setOut(out);
62+
63+
// Create a test table
64+
tableName = "UserSessions_TEST_" + UUID.randomUUID().toString().replace('-', '_');
65+
Schema schema =
66+
Schema.of(
67+
Field.of("id", LegacySQLTypeName.STRING),
68+
Field.of("user_id", LegacySQLTypeName.STRING),
69+
Field.of("login_time", LegacySQLTypeName.STRING),
70+
Field.of("logout_time", LegacySQLTypeName.STRING),
71+
Field.of("ip_address", LegacySQLTypeName.STRING));
72+
73+
CreateTable.createTable(BIGQUERY_DATASET_NAME, tableName, schema);
74+
75+
bout = new ByteArrayOutputStream();
76+
out = new PrintStream(bout);
77+
System.setOut(out);
78+
}
79+
80+
@After
81+
public void tearDown() {
82+
// Clean up
83+
DeleteTable.deleteTable(BIGQUERY_DATASET_NAME, tableName);
84+
System.setOut(null);
85+
}
86+
87+
@Test
88+
public void testUpdateTableDML() throws IOException, InterruptedException {
89+
UpdateTableDML.updateTableDML(BIGQUERY_DATASET_NAME, tableName);
90+
assertThat(bout.toString()).contains("Table updated successfully using DML");
91+
}
92+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{"id":"2ad525d6-c832-4c3d-b7fe-59d104885519","user_id":"38","login_time":"1.47766087E9","logout_time":"1.477661109E9","ip_address":"192.0.2.12"}
2+
{"id":"53d65e20-6ea9-4650-98d9-a2111fbd1122","user_id":"88","login_time":"1.47707544E9","logout_time":"1.477075519E9","ip_address":"192.0.2.88"}
3+
{"id":"5e6c3021-d5e7-4ccd-84b2-adfa9176d13d","user_id":"39","login_time":"1.474022869E9","logout_time":"1.474022961E9","ip_address":"203.0.113.52"}
4+
{"id":"6196eefa-1498-4567-8ef0-498845b888d9","user_id":"52","login_time":"1.478604612E9","logout_time":"1.478604691E9","ip_address":"203.0.113.169"}
5+
{"id":"70656dc5-7e0f-49cf-9e00-f06ed93c1f5b","user_id":"46","login_time":"1.474089924E9","logout_time":"1.474090227E9","ip_address":"192.0.2.10"}
6+
{"id":"aafa5eef-ad49-49a7-9a0f-fbc7fd639bd3","user_id":"40","login_time":"1.478031161E9","logout_time":"1.478031388E9","ip_address":"203.0.113.18"}
7+
{"id":"d2792fc2-24dd-4260-9456-3fbe6cdfdd90","user_id":"5","login_time":"1.481259081E9","logout_time":"1.481259247E9","ip_address":"192.0.2.140"}
8+
{"id":"d835dc49-32f9-4790-b4eb-dddee62e0dcc","user_id":"62","login_time":"1.478892977E9","logout_time":"1.478893219E9","ip_address":"203.0.113.83"}
9+
{"id":"f4a0d3c7-351f-471c-8e11-e093e7a6ce75","user_id":"89","login_time":"1.459031555E9","logout_time":"1.459031831E9","ip_address":"203.0.113.233"}
10+
{"id":"f6e9f526-5b22-4679-9c3e-56a636e815bb","user_id":"97","login_time":"1.482426034E9","logout_time":"1.482426415E9","ip_address":"203.0.113.167"}

0 commit comments

Comments
 (0)