Skip to content
This repository was archived by the owner on Sep 27, 2023. It is now read-only.

Commit 35552a6

Browse files
author
Praful Makani
authored
docs(samples): add create scheduled query with service account (#322)
1 parent b62ee9d commit 35552a6

File tree

2 files changed

+204
-0
lines changed

2 files changed

+204
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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.bigquerydatatransfer;
18+
19+
// [START bigquerydatatransfer_create_scheduled_query_with_service_account]
20+
import com.google.api.gax.rpc.ApiException;
21+
import com.google.cloud.bigquery.datatransfer.v1.CreateTransferConfigRequest;
22+
import com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient;
23+
import com.google.cloud.bigquery.datatransfer.v1.ProjectName;
24+
import com.google.cloud.bigquery.datatransfer.v1.TransferConfig;
25+
import com.google.protobuf.Struct;
26+
import com.google.protobuf.Value;
27+
import java.io.IOException;
28+
import java.util.HashMap;
29+
import java.util.Map;
30+
31+
// Sample to create a scheduled query with service account
32+
public class CreateScheduledQueryWithServiceAccount {
33+
34+
public static void main(String[] args) throws IOException {
35+
// TODO(developer): Replace these variables before running the sample.
36+
final String projectId = "MY_PROJECT_ID";
37+
final String datasetId = "MY_DATASET_ID";
38+
final String serviceAccount = "MY_SERVICE_ACCOUNT";
39+
final String query =
40+
"SELECT CURRENT_TIMESTAMP() as current_time, @run_time as intended_run_time, "
41+
+ "@run_date as intended_run_date, 17 as some_integer";
42+
Map<String, Value> params = new HashMap<>();
43+
params.put("query", Value.newBuilder().setStringValue(query).build());
44+
params.put(
45+
"destination_table_name_template",
46+
Value.newBuilder().setStringValue("my_destination_table_{run_date}").build());
47+
params.put("write_disposition", Value.newBuilder().setStringValue("WRITE_TRUNCATE").build());
48+
params.put("partitioning_field", Value.newBuilder().build());
49+
TransferConfig transferConfig =
50+
TransferConfig.newBuilder()
51+
.setDestinationDatasetId(datasetId)
52+
.setDisplayName("Your Scheduled Query Name")
53+
.setDataSourceId("scheduled_query")
54+
.setParams(Struct.newBuilder().putAllFields(params).build())
55+
.setSchedule("every 24 hours")
56+
.build();
57+
createScheduledQueryWithServiceAccount(projectId, transferConfig, serviceAccount);
58+
}
59+
60+
public static void createScheduledQueryWithServiceAccount(
61+
String projectId, TransferConfig transferConfig, String serviceAccount) throws IOException {
62+
try (DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.create()) {
63+
ProjectName parent = ProjectName.of(projectId);
64+
CreateTransferConfigRequest request =
65+
CreateTransferConfigRequest.newBuilder()
66+
.setParent(parent.toString())
67+
.setTransferConfig(transferConfig)
68+
.setServiceAccountName(serviceAccount)
69+
.build();
70+
TransferConfig config = dataTransferServiceClient.createTransferConfig(request);
71+
System.out.println(
72+
"\nScheduled query with service account created successfully :" + config.getName());
73+
} catch (ApiException ex) {
74+
System.out.print("\nScheduled query with service account was not created." + ex.toString());
75+
}
76+
}
77+
}
78+
// [END bigquerydatatransfer_create_scheduled_query_with_service_account]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
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.bigquerydatatransfer;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static junit.framework.TestCase.assertNotNull;
21+
22+
import com.google.auth.oauth2.ServiceAccountCredentials;
23+
import com.google.cloud.bigquery.BigQuery;
24+
import com.google.cloud.bigquery.BigQueryOptions;
25+
import com.google.cloud.bigquery.DatasetInfo;
26+
import com.google.cloud.bigquery.datatransfer.v1.TransferConfig;
27+
import com.google.cloud.bigquery.datatransfer.v1.TransferState;
28+
import com.google.protobuf.Struct;
29+
import com.google.protobuf.Value;
30+
import java.io.ByteArrayOutputStream;
31+
import java.io.IOException;
32+
import java.io.PrintStream;
33+
import java.util.HashMap;
34+
import java.util.Map;
35+
import java.util.UUID;
36+
import java.util.logging.Level;
37+
import java.util.logging.Logger;
38+
import org.junit.After;
39+
import org.junit.Before;
40+
import org.junit.BeforeClass;
41+
import org.junit.Test;
42+
43+
public class CreateScheduledQueryWithServiceAccountIT {
44+
45+
private final Logger log = Logger.getLogger(this.getClass().getName());
46+
private BigQuery bigquery;
47+
private ByteArrayOutputStream bout;
48+
private String name;
49+
private String displayName;
50+
private String datasetName;
51+
private PrintStream out;
52+
private PrintStream originalPrintStream;
53+
54+
private static final String PROJECT_ID = requireEnvVar("GOOGLE_CLOUD_PROJECT");
55+
56+
private static String requireEnvVar(String varName) {
57+
String value = System.getenv(varName);
58+
assertNotNull(
59+
"Environment variable " + varName + " is required to perform these tests.",
60+
System.getenv(varName));
61+
return value;
62+
}
63+
64+
@BeforeClass
65+
public static void checkRequirements() {
66+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
67+
}
68+
69+
@Before
70+
public void setUp() {
71+
displayName = "MY_SCHEDULE_NAME_TEST_" + UUID.randomUUID().toString().substring(0, 8);
72+
datasetName = "MY_DATASET_NAME_TEST_" + UUID.randomUUID().toString().substring(0, 8);
73+
// create a temporary dataset
74+
bigquery = BigQueryOptions.getDefaultInstance().getService();
75+
bigquery.create(DatasetInfo.of(datasetName));
76+
77+
bout = new ByteArrayOutputStream();
78+
out = new PrintStream(bout);
79+
originalPrintStream = System.out;
80+
System.setOut(out);
81+
}
82+
83+
@After
84+
public void tearDown() throws IOException {
85+
// Clean up
86+
DeleteScheduledQuery.deleteScheduledQuery(name);
87+
// delete a temporary dataset
88+
bigquery.delete(datasetName, BigQuery.DatasetDeleteOption.deleteContents());
89+
// restores print statements in the original method
90+
System.out.flush();
91+
System.setOut(originalPrintStream);
92+
log.log(Level.INFO, bout.toString());
93+
}
94+
95+
@Test
96+
public void testCreateScheduledQueryWithServiceAccount() throws IOException {
97+
String query =
98+
"SELECT CURRENT_TIMESTAMP() as current_time, @run_time as intended_run_time, "
99+
+ "@run_date as intended_run_date, 17 as some_integer";
100+
String destinationTableName =
101+
"MY_DESTINATION_TABLE_" + UUID.randomUUID().toString().substring(0, 8) + "_{run_date}";
102+
Map<String, Value> params = new HashMap<>();
103+
params.put("query", Value.newBuilder().setStringValue(query).build());
104+
params.put(
105+
"destination_table_name_template",
106+
Value.newBuilder().setStringValue(destinationTableName).build());
107+
params.put("write_disposition", Value.newBuilder().setStringValue("WRITE_TRUNCATE").build());
108+
params.put("partitioning_field", Value.newBuilder().setStringValue("").build());
109+
TransferConfig transferConfig =
110+
TransferConfig.newBuilder()
111+
.setDestinationDatasetId(datasetName)
112+
.setDisplayName(displayName)
113+
.setDataSourceId("scheduled_query")
114+
.setParams(Struct.newBuilder().putAllFields(params).build())
115+
.setSchedule("every 24 hours")
116+
.setState(TransferState.CANCELLED)
117+
.build();
118+
ServiceAccountCredentials credentials =
119+
(ServiceAccountCredentials) ServiceAccountCredentials.getApplicationDefault();
120+
CreateScheduledQueryWithServiceAccount.createScheduledQueryWithServiceAccount(
121+
PROJECT_ID, transferConfig, credentials.getClientEmail());
122+
String result = bout.toString();
123+
name = result.substring(result.indexOf(":") + 1, result.length() - 1);
124+
assertThat(result).contains("Scheduled query with service account created successfully");
125+
}
126+
}

0 commit comments

Comments
 (0)