Skip to content

Commit e832298

Browse files
docs: add samples for PostgresSQL (#1781)
* Added samples for PG dialect databases * docs: add samples for postgresql * docs: samples tag fixes * docs: samples tag fixes * docs: samples tag violation fixes * docs: samples imports and indent fixes * docs: samples checkstyle fixes * docs: add samples for postgresql * docs: samples tag fixes * docs: pg samples pr comments fixes * docs: pg samples checkstyle fixes * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 2471d91 commit e832298

12 files changed

+2766
-2
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,10 +265,15 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-spanner/tree/
265265
| Get Instance Config Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/GetInstanceConfigSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/GetInstanceConfigSample.java) |
266266
| List Databases Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/ListDatabasesSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/ListDatabasesSample.java) |
267267
| List Instance Configs Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/ListInstanceConfigsSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/ListInstanceConfigsSample.java) |
268+
| Pg Async Query To List Async Example | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgAsyncQueryToListAsyncExample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgAsyncQueryToListAsyncExample.java) |
269+
| Pg Async Runner Example | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgAsyncRunnerExample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgAsyncRunnerExample.java) |
270+
| Pg Async Transaction Manager Example | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgAsyncTransactionManagerExample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgAsyncTransactionManagerExample.java) |
268271
| Pg Batch Dml Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgBatchDmlSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgBatchDmlSample.java) |
269272
| Pg Case Sensitivity Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgCaseSensitivitySample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgCaseSensitivitySample.java) |
270273
| Pg Interleaved Table Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgInterleavedTableSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgInterleavedTableSample.java) |
271274
| Pg Partitioned Dml Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgPartitionedDmlSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgPartitionedDmlSample.java) |
275+
| Pg Query With Numeric Parameter Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgQueryWithNumericParameterSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgQueryWithNumericParameterSample.java) |
276+
| Pg Spanner Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/PgSpannerSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/PgSpannerSample.java) |
272277
| Query Information Schema Database Options Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/QueryInformationSchemaDatabaseOptionsSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/QueryInformationSchemaDatabaseOptionsSample.java) |
273278
| Query With Json Parameter Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/QueryWithJsonParameterSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/QueryWithJsonParameterSample.java) |
274279
| Query With Numeric Parameter Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/QueryWithNumericParameterSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/QueryWithNumericParameterSample.java) |

samples/snippets/src/main/java/com/example/spanner/AsyncQueryToListAsyncExample.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
import java.util.concurrent.TimeUnit;
3232
import java.util.concurrent.TimeoutException;
3333

34+
/**
35+
* Example code for using Async query on Cloud Spanner and convert it to list.
36+
*/
3437
class AsyncQueryToListAsyncExample {
3538
static class Album {
3639
final long singerId;

samples/snippets/src/main/java/com/example/spanner/CustomTimeoutAndRetrySettingsExample.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ static void executeSqlWithCustomTimeoutAndRetrySettings(
8080
.readWriteTransaction()
8181
.run(transaction -> {
8282
String sql =
83-
"INSERT Singers (SingerId, FirstName, LastName)\n"
83+
"INSERT INTO Singers (SingerId, FirstName, LastName)\n"
8484
+ "VALUES (20, 'George', 'Washington')";
8585
long rowCount = transaction.executeUpdate(Statement.of(sql));
8686
System.out.printf("%d record inserted.%n", rowCount);
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Copyright 2022 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.spanner;
18+
19+
// [START spanner_postgresql_async_query_to_list]
20+
import com.google.api.core.ApiFuture;
21+
import com.google.cloud.spanner.AsyncResultSet;
22+
import com.google.cloud.spanner.DatabaseClient;
23+
import com.google.cloud.spanner.DatabaseId;
24+
import com.google.cloud.spanner.Spanner;
25+
import com.google.cloud.spanner.SpannerOptions;
26+
import com.google.cloud.spanner.Statement;
27+
import java.util.List;
28+
import java.util.concurrent.ExecutionException;
29+
import java.util.concurrent.ExecutorService;
30+
import java.util.concurrent.Executors;
31+
import java.util.concurrent.TimeUnit;
32+
import java.util.concurrent.TimeoutException;
33+
34+
public class PgAsyncQueryToListAsyncExample {
35+
static class Album {
36+
final long singerId;
37+
final long albumId;
38+
final String albumTitle;
39+
40+
Album(long singerId, long albumId, String albumTitle) {
41+
this.singerId = singerId;
42+
this.albumId = albumId;
43+
this.albumTitle = albumTitle;
44+
}
45+
}
46+
47+
static void asyncQueryToList() throws InterruptedException, ExecutionException, TimeoutException {
48+
// TODO(developer): Replace these variables before running the sample.
49+
String projectId = "my-project";
50+
String instanceId = "my-instance";
51+
String databaseId = "my-database";
52+
53+
try (Spanner spanner =
54+
SpannerOptions.newBuilder().setProjectId(projectId).build().getService()) {
55+
DatabaseClient client =
56+
spanner.getDatabaseClient(DatabaseId.of(projectId, instanceId, databaseId));
57+
asyncQueryToList(client);
58+
}
59+
}
60+
61+
// Execute a query asynchronously and transform the result to a list.
62+
static void asyncQueryToList(DatabaseClient client)
63+
throws InterruptedException, ExecutionException, TimeoutException {
64+
ExecutorService executor = Executors.newSingleThreadExecutor();
65+
ApiFuture<? extends List<Album>> albums;
66+
try (AsyncResultSet resultSet =
67+
client
68+
.singleUse()
69+
.executeQueryAsync(Statement.of("SELECT singerid as \"SingerId\", "
70+
+ "albumid as \"AlbumId\", albumtitle as \"AlbumTitle\" "
71+
+ "FROM Albums"))) {
72+
// Convert the result set to a list of Albums asynchronously.
73+
albums =
74+
resultSet.toListAsync(
75+
reader -> {
76+
return new Album(
77+
reader.getLong("SingerId"),
78+
reader.getLong("AlbumId"),
79+
reader.getString("AlbumTitle"));
80+
},
81+
executor);
82+
}
83+
84+
for (Album album : albums.get(30L, TimeUnit.SECONDS)) {
85+
System.out.printf("%d %d %s%n", album.singerId, album.albumId, album.albumTitle);
86+
}
87+
executor.shutdown();
88+
}
89+
}
90+
//[END spanner_postgresql_async_query_to_list]
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*
2+
* Copyright 2022 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.spanner;
18+
19+
//[START spanner_postgresql_async_read_write_transaction]
20+
import com.google.api.core.ApiFuture;
21+
import com.google.api.core.ApiFutures;
22+
import com.google.cloud.spanner.AsyncRunner;
23+
import com.google.cloud.spanner.DatabaseClient;
24+
import com.google.cloud.spanner.DatabaseId;
25+
import com.google.cloud.spanner.Key;
26+
import com.google.cloud.spanner.Spanner;
27+
import com.google.cloud.spanner.SpannerExceptionFactory;
28+
import com.google.cloud.spanner.SpannerOptions;
29+
import com.google.cloud.spanner.Statement;
30+
import com.google.cloud.spanner.Struct;
31+
import com.google.common.collect.ImmutableList;
32+
import com.google.common.util.concurrent.MoreExecutors;
33+
import java.util.Arrays;
34+
import java.util.concurrent.ExecutionException;
35+
import java.util.concurrent.ExecutorService;
36+
import java.util.concurrent.Executors;
37+
import java.util.concurrent.TimeUnit;
38+
import java.util.concurrent.TimeoutException;
39+
40+
class PgAsyncRunnerExample {
41+
42+
static void asyncRunner() throws InterruptedException, ExecutionException, TimeoutException {
43+
// TODO(developer): Replace these variables before running the sample.
44+
String projectId = "my-project";
45+
String instanceId = "my-instance";
46+
String databaseId = "my-database";
47+
48+
try (Spanner spanner =
49+
SpannerOptions.newBuilder().setProjectId(projectId).build().getService()) {
50+
DatabaseClient client =
51+
spanner.getDatabaseClient(DatabaseId.of(projectId, instanceId, databaseId));
52+
asyncRunner(client);
53+
}
54+
}
55+
56+
// Execute a read/write transaction asynchronously.
57+
static void asyncRunner(DatabaseClient client)
58+
throws InterruptedException, ExecutionException, TimeoutException {
59+
ExecutorService executor = Executors.newSingleThreadExecutor();
60+
61+
// Create an async transaction runner.
62+
AsyncRunner runner = client.runAsync();
63+
// The transaction returns the total number of rows that were updated as a future array of
64+
// longs.
65+
ApiFuture<long[]> rowCounts =
66+
runner.runAsync(
67+
txn -> {
68+
// Transfer marketing budget from one album to another. We do it in a
69+
// transaction to ensure that the transfer is atomic.
70+
ApiFuture<Struct> album1BudgetFut =
71+
txn.readRowAsync("Albums", Key.of(1, 1), ImmutableList.of("MarketingBudget"));
72+
ApiFuture<Struct> album2BudgetFut =
73+
txn.readRowAsync("Albums", Key.of(2, 2), ImmutableList.of("MarketingBudget"));
74+
75+
try {
76+
// Transaction will only be committed if this condition still holds at the
77+
// time of commit. Otherwise it will be aborted and the AsyncWork will be
78+
// rerun by the client library.
79+
long transfer = 200_000;
80+
if (album2BudgetFut.get().getLong(0) >= transfer) {
81+
long album1Budget = album1BudgetFut.get().getLong(0);
82+
long album2Budget = album2BudgetFut.get().getLong(0);
83+
84+
album1Budget += transfer;
85+
album2Budget -= transfer;
86+
Statement updateStatement1 =
87+
Statement.newBuilder(
88+
"UPDATE Albums "
89+
+ "SET MarketingBudget = $1 "
90+
+ "WHERE SingerId = 1 and AlbumId = 1")
91+
.bind("p1")
92+
.to(album1Budget)
93+
.build();
94+
Statement updateStatement2 =
95+
Statement.newBuilder(
96+
"UPDATE Albums "
97+
+ "SET MarketingBudget = $1 "
98+
+ "WHERE SingerId = 2 and AlbumId = 2")
99+
.bind("p1")
100+
.to(album2Budget)
101+
.build();
102+
return txn.batchUpdateAsync(
103+
ImmutableList.of(updateStatement1, updateStatement2));
104+
} else {
105+
return ApiFutures.immediateFuture(new long[] {0L, 0L});
106+
}
107+
} catch (ExecutionException e) {
108+
throw SpannerExceptionFactory.newSpannerException(e.getCause());
109+
} catch (InterruptedException e) {
110+
throw SpannerExceptionFactory.propagateInterrupt(e);
111+
}
112+
},
113+
executor);
114+
115+
ApiFuture<Long> totalUpdateCount =
116+
ApiFutures.transform(
117+
rowCounts,
118+
input -> Arrays.stream(input).sum(),
119+
MoreExecutors.directExecutor());
120+
System.out.printf("%d records updated.%n", totalUpdateCount.get(30L, TimeUnit.SECONDS));
121+
executor.shutdown();
122+
}
123+
}
124+
//[END spanner_postgresql_async_read_write_transaction]

0 commit comments

Comments
 (0)