Skip to content

Commit

Permalink
docs(sample): relocate native image sample from old repo (#1758)
Browse files Browse the repository at this point in the history
* docs(sample): relocate native image sample from old repo
  • Loading branch information
mpeddada1 committed Jun 2, 2022
1 parent b6aed28 commit ef187f4
Show file tree
Hide file tree
Showing 8 changed files with 517 additions and 2 deletions.
7 changes: 5 additions & 2 deletions README.md
Expand Up @@ -56,13 +56,13 @@ implementation 'com.google.cloud:google-cloud-spanner'
If you are using Gradle without BOM, add this to your dependencies

```Groovy
implementation 'com.google.cloud:google-cloud-spanner:6.25.4'
implementation 'com.google.cloud:google-cloud-spanner:6.25.5'
```

If you are using SBT, add this to your dependencies

```Scala
libraryDependencies += "com.google.cloud" % "google-cloud-spanner" % "6.25.4"
libraryDependencies += "com.google.cloud" % "google-cloud-spanner" % "6.25.5"
```

## Authentication
Expand Down Expand Up @@ -240,6 +240,9 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-spanner/tree/

| Sample | Source Code | Try it |
| --------------------------- | --------------------------------- | ------ |
| Database Operations | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/native-image/src/main/java/com/example/spanner/DatabaseOperations.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/native-image/src/main/java/com/example/spanner/DatabaseOperations.java) |
| Instance Operations | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/native-image/src/main/java/com/example/spanner/InstanceOperations.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/native-image/src/main/java/com/example/spanner/InstanceOperations.java) |
| Native Image Spanner Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/native-image/src/main/java/com/example/spanner/NativeImageSpannerSample.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/native-image/src/main/java/com/example/spanner/NativeImageSpannerSample.java) |
| Add Json Column Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/AddJsonColumnSample.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/AddJsonColumnSample.java) |
| Add Numeric Column Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/AddNumericColumnSample.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/AddNumericColumnSample.java) |
| Async Dml Example | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/AsyncDmlExample.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/AsyncDmlExample.java) |
Expand Down
92 changes: 92 additions & 0 deletions samples/native-image/README.md
@@ -0,0 +1,92 @@
# Spanner Sample Application with Native Image

This is a sample application which uses the Cloud Spanner client libraries and demonstrates compatibility with Native Image compilation.

The application creates a new Spanner instance and database, and it runs basic operations including queries and Spanner mutations.

## Setup Instructions

You will need to follow these prerequisite steps in order to run these samples:

1. If you have not already, [create a Google Cloud Platform Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project).

2. Install the [Google Cloud SDK](https://cloud.google.com/sdk/) which will allow you to run the sample with your project's credentials.

Once installed, log in with Application Default Credentials using the following command:

```
gcloud auth application-default login
```

**Note:** Authenticating with Application Default Credentials is convenient to use during development, but we recommend [alternate methods of authentication](https://cloud.google.com/docs/authentication/production) during production use.

3. Install the GraalVM compiler.

You can follow the [official installation instructions](https://www.graalvm.org/docs/getting-started-with-graalvm/#install-graalvm) from the GraalVM website.
After following the instructions, ensure that you install the Native Image extension installed by running:

```
gu install native-image
```

Once you finish following the instructions, verify that the default version of Java is set to the GraalVM version by running `java -version` in a terminal.

You will see something similar to the below output:

```
$ java -version
openjdk version "11.0.15" 2022-04-19
OpenJDK Runtime Environment GraalVM CE 22.1.0 (build 11.0.15+10-jvmci-22.1-b06)
OpenJDK 64-Bit Server VM GraalVM CE 22.1.0 (build 11.0.15+10-jvmci-22.1-b06, mixed mode, sharing)
```
## Run with Native Image Compilation

1. **(Optional)** If you wish to run the application against the [Spanner emulator](https://cloud.google.com/spanner/docs/emulator), make sure that you have the [Google Cloud SDK](https://cloud.google.com/sdk) installed.

In a new terminal window, start the emulator via `gcloud`:

```
gcloud beta emulators spanner start
```

You may leave the emulator running for now.
In the next section, we will run the sample application against the Spanner emulator instsance.

2. Navigate to this directory and compile the application with the Native Image compiler.

```
mvn package -P native -DskipTests
```

3. **(Optional)** If you're using the emulator, export the `SPANNER_EMULATOR_HOST` as an environment variable in your terminal.

```
export SPANNER_EMULATOR_HOST=localhost:9010
```

The Spanner Client Libraries will detect this environment variable and will automatically connect to the emulator instance if this variable is set.

4. Run the application.

```
./target/native-image
```

5. The application will run through some basic Spanner operations and log some output statements.

```
Running the Spanner Sample.
Singers Registered in Spanner:
Bob Loblaw
Virginia Watson
```

## Sample Integration test with Native Image Support

In order to run the sample integration test as a native image, call the following command:

```
mvn test -Pnative
```
164 changes: 164 additions & 0 deletions samples/native-image/pom.xml
@@ -0,0 +1,164 @@
<?xml version='1.0' encoding='UTF-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.cloud</groupId>
<artifactId>native-image</artifactId>
<name>Native Image Sample</name>
<url>https://github.com/googleapis/java-spanner</url>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
-->
<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.2.0</version>
</parent>

<properties>
<!-- Java 8 because the Kokoro Sample test uses that Java version -->
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>25.2.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner</artifactId>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.1.3</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<!-- This plugin enables building the application to a JAR *not* using Native Image -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>dependency-jars/</classpathPrefix>
<mainClass>com.example.spanner.NativeImageSpannerSample</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/dependency-jars/
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

<!-- Native Profile-->
<profiles>
<profile>
<id>native</id>

<dependencies>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>junit-platform-native</artifactId>
<version>0.9.10</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin
</artifactId> <!-- Must use older version of surefire plugin for native-image testing. -->
<version>2.22.2</version>
<configuration>
<includes>
<include>**/*IT</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.9.9</version>
<extensions>true</extensions>
<configuration>
<mainClass>com.example.spanner.NativeImageSpannerSample</mainClass>
<buildArgs>
<buildArg>--no-fallback</buildArg>
<buildArg>--no-server</buildArg>
</buildArgs>
</configuration>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>build</goal>
<goal>test</goal>
</goals>
<phase>package</phase>
</execution>
<execution>
<id>test-native</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
@@ -0,0 +1,92 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.spanner;

import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Statement;
import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.List;

/** Helper methods to manage Spanner Databases. */
public class DatabaseOperations {

private static final List<String> DDL_STATEMENTS =
ImmutableList.of(
"CREATE TABLE Singers (SingerId INT64 NOT NULL, FirstName "
+ "STRING(1024), LastName STRING(1024)) PRIMARY KEY (SingerId)");

static void createDatabase(
DatabaseAdminClient databaseAdminClient, String instanceId, String databaseId) {

if (databaseExists(databaseAdminClient, instanceId, databaseId)) {
databaseAdminClient.dropDatabase(instanceId, databaseId);
}
databaseAdminClient.createDatabase(instanceId, databaseId, DDL_STATEMENTS);
}

static boolean databaseExists(
DatabaseAdminClient databaseAdminClient, String instanceId, String databaseId) {

for (Database database : databaseAdminClient.listDatabases(instanceId).iterateAll()) {
if (databaseId.equals(database.getId().getDatabase())) {
return true;
}
}
return false;
}

static void insertUsingDml(DatabaseClient dbClient) {
dbClient
.readWriteTransaction()
.run(
transaction -> {
String sql =
"INSERT INTO Singers (SingerId, FirstName, LastName) "
+ " VALUES (10, 'Virginia', 'Watson')";
transaction.executeUpdate(Statement.of(sql));
return null;
});
}

static void insertUsingMutation(DatabaseClient dbClient) {
Mutation mutation =
Mutation.newInsertBuilder("Singers")
.set("SingerId")
.to(12)
.set("FirstName")
.to("Bob")
.set("LastName")
.to("Loblaw")
.build();
dbClient.write(Collections.singletonList(mutation));
}

static ResultSet performRead(DatabaseClient dbClient) {
return dbClient.singleUse().executeQuery(Statement.of("SELECT * FROM Singers"));
}

static void deleteDatabase(DatabaseClient dbClient) {
dbClient.write(Collections.singletonList(Mutation.delete("Singers", KeySet.all())));
System.out.println("Records deleted.");
}
}

0 comments on commit ef187f4

Please sign in to comment.