com.google.cloud.spanner.ResultSet Java Examples

The following examples show how to use com.google.cloud.spanner.ResultSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpannerTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void existsByIdEmbeddedKeyTest() {
	ResultSet results = mock(ResultSet.class);
	when(results.next()).thenReturn(false);

	when(this.readContext.read(any(), any(), any(), any())).thenReturn(results);
	when(this.databaseClient.singleUse(any())).thenReturn(this.readContext);

	Key key = Key.of("key");
	KeySet keySet = KeySet.singleKey(key);
	assertThat(this.spannerTemplate.existsById(TestEntityEmbeddedPK.class, key)).isFalse();

	verify(this.databaseClient, times(1)).singleUse();
	verify(this.readContext, times(1))
			.read(eq("test_table_embedded_pk"), eq(keySet), eq(Collections.singleton("stringId")));
}
 
Example #2
Source File: XATransaction.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private static void cleanupPrepared(TransactionContext transaction, String xid) {
  boolean foundRecords = false;
  KeySet.Builder builder = KeySet.newBuilder();
  try (ResultSet rs = transaction.executeQuery(getPreparedMutationsStatement(xid))) {
    while (rs.next()) {
      foundRecords = true;
      long number = rs.getLong(0);
      builder.addKey(Key.of(xid, number));
    }
  }
  if (foundRecords) {
    Mutation delete =
        Mutation.delete(CloudSpannerXAConnection.XA_PREPARED_MUTATIONS_TABLE, builder.build());
    transaction.buffer(delete);
  }
}
 
Example #3
Source File: BatchClientSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
void partitionReadUsingIndex() {
  // [START partition_read_using_index]
  final BatchReadOnlyTransaction txn =
      batchClient.batchReadOnlyTransaction(TimestampBound.strong());
  List<Partition> partitions =
      txn.partitionReadUsingIndex(
          PartitionOptions.getDefaultInstance(),
          "Singers",
          "SingerId",
          KeySet.all(),
          Arrays.asList("SingerId", "FirstName", "LastName"));

  for (Partition p : partitions) {
    try (ResultSet results = txn.execute(p)) {
      while (results.next()) {
        long singerId = results.getLong(0);
        String firstName = results.getString(1);
        String lastName = results.getString(2);
        System.out.println("[" + singerId + "] " + firstName + " " + lastName);
      }
    }
  }
  // [END partition_read_using_index]
}
 
Example #4
Source File: App.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void query(DatabaseClient dbClient, int timespan) {
  Statement statement =
      Statement
          .newBuilder(
            "SELECT p.PlayerId, p.PlayerName, s.Score, s.Timestamp "
            + "FROM Players p "
            + "JOIN Scores s ON p.PlayerId = s.PlayerId "
            + "WHERE s.Timestamp > "
            + "TIMESTAMP_SUB(CURRENT_TIMESTAMP(), "
            + "    INTERVAL @Timespan HOUR) "
            + "ORDER BY s.Score DESC LIMIT 10")
          .bind("Timespan")
          .to(timespan)
          .build();
  ResultSet resultSet = dbClient.singleUse().executeQuery(statement);
  while (resultSet.next()) {
    String scoreDate = String.valueOf(resultSet.getTimestamp("Timestamp"));
    String score = String.format("%,d", resultSet.getLong("Score"));
    System.out.printf(
        "PlayerId: %d  PlayerName: %s  Score: %s  Timestamp: %s\n",
        resultSet.getLong("PlayerId"), resultSet.getString("PlayerName"), score,
        scoreDate.substring(0,10));
  }
}
 
Example #5
Source File: BatchClientSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
void partitionRead() {
  // [START partition_read]
  final BatchReadOnlyTransaction txn =
      batchClient.batchReadOnlyTransaction(TimestampBound.strong());
  List<Partition> partitions =
      txn.partitionRead(
          PartitionOptions.getDefaultInstance(),
          "Singers",
          KeySet.all(),
          Arrays.asList("SingerId", "FirstName", "LastName"));
  for (final Partition p : partitions) {
    try (ResultSet results = txn.execute(p)) {
      while (results.next()) {
        long singerId = results.getLong(0);
        String firstName = results.getString(1);
        String lastName = results.getString(2);
        System.out.println("[" + singerId + "] " + firstName + " " + lastName);
      }
    }
  }
  // [END partition_read]
}
 
Example #6
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryWithParameter(DatabaseClient dbClient) {
  Statement statement =
      Statement.newBuilder(
              "SELECT SingerId, FirstName, LastName "
                  + "FROM Singers "
                  + "WHERE LastName = @lastName")
          .bind("lastName")
          .to("Garcia")
          .build();
  try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %s %s\n",
          resultSet.getLong("SingerId"),
          resultSet.getString("FirstName"),
          resultSet.getString("LastName"));
    }
  }
}
 
Example #7
Source File: App.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void query(DatabaseClient dbClient, int timespan) {
  Statement statement =
      Statement
          .newBuilder(
            "SELECT p.PlayerId, p.PlayerName, s.Score, s.Timestamp "
            + "FROM Players p "
            + "JOIN Scores s ON p.PlayerId = s.PlayerId "
            + "WHERE s.Timestamp > "
            + "TIMESTAMP_SUB(CURRENT_TIMESTAMP(), "
            + "    INTERVAL @Timespan HOUR) "
            + "ORDER BY s.Score DESC LIMIT 10")
          .bind("Timespan")
          .to(timespan)
          .build();
  ResultSet resultSet = dbClient.singleUse().executeQuery(statement);
  while (resultSet.next()) {
    String scoreDate = String.valueOf(resultSet.getTimestamp("Timestamp"));
    String score = String.format("%,d", resultSet.getLong("Score"));
    System.out.printf(
        "PlayerId: %d  PlayerName: %s  Score: %s  Timestamp: %s\n",
        resultSet.getLong("PlayerId"), resultSet.getString("PlayerName"), score,
        scoreDate.substring(0,10));
  }
}
 
Example #8
Source File: InformationSchemaScanner.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
private void listColumns(Ddl.Builder builder) {
  ResultSet resultSet =
      context.executeQuery(
          Statement.newBuilder(
                  "SELECT c.table_name, c.column_name,"
                      + " c.ordinal_position, c.spanner_type, c.is_nullable"
                      + " FROM information_schema.columns as c"
                      + " WHERE c.table_catalog = '' AND c.table_schema = '' "
                      + " ORDER BY c.table_name, c.ordinal_position")
              .build());
  while (resultSet.next()) {
    String tableName = resultSet.getString(0);
    String columnName = resultSet.getString(1);
    String spannerType = resultSet.getString(3);
    boolean nullable = resultSet.getString(4).equalsIgnoreCase("YES");
    builder
        .createTable(tableName)
        .column(columnName)
        .parseType(spannerType)
        .notNull(!nullable)
        .endColumn()
        .endTable();
  }
}
 
Example #9
Source File: CloudSpannerResultSetMetaData.java    From spanner-jdbc with MIT License 6 votes vote down vote up
@Override
public int isNullable(int column) throws SQLException {
  Column col = getColumn(column);
  if (col != null && col.getTable() != null) {
    String schema = Strings.isNullOrEmpty(col.getTable().getSchemaName()) ? ""
        : CloudSpannerDriver.unquoteIdentifier(col.getTable().getSchemaName());
    String tableName = CloudSpannerDriver.unquoteIdentifier(col.getTable().getName());
    String colName = CloudSpannerDriver.unquoteIdentifier(col.getColumnName());
    try (java.sql.ResultSet rs =
        statement.getConnection().getMetaData().getColumns("", schema, tableName, colName)) {
      if (rs.next()) {
        return rs.getInt("NULLABLE");
      }
    }
  }
  return columnNullableUnknown;
}
 
Example #10
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryWithTimestampParameter(DatabaseClient dbClient) {
  Instant exampleTimestamp = Instant.now();
  Statement statement =
      Statement.newBuilder(
              "SELECT VenueId, VenueName, LastUpdateTime FROM Venues "
                  + "WHERE LastUpdateTime < @lastUpdateTime")
          .bind("lastUpdateTime")
          .to(exampleTimestamp.toString())
          .build();
  try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %s %s\n",
          resultSet.getLong("VenueId"),
          resultSet.getString("VenueName"),
          resultSet.getTimestamp("LastUpdateTime"));
    }
  }
}
 
Example #11
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryWithBytes(DatabaseClient dbClient) {
  ByteArray exampleBytes =
      ByteArray.fromBase64(BaseEncoding.base64().encode("Hello World 1".getBytes()));
  Statement statement =
      Statement.newBuilder(
              "SELECT VenueId, VenueName FROM Venues " + "WHERE VenueInfo = @venueInfo")
          .bind("venueInfo")
          .to(exampleBytes)
          .build();
  try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %s\n", resultSet.getLong("VenueId"), resultSet.getString("VenueName"));
    }
  }
}
 
Example #12
Source File: SpannerTemplate.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
public ResultSet executeQuery(Statement statement, SpannerQueryOptions options) {

		long startTime = LOGGER.isDebugEnabled() ? System.currentTimeMillis() : 0;

		ResultSet resultSet = performQuery(statement, options);
		if (LOGGER.isDebugEnabled()) {
			String message;
			if (options == null) {
				message = "Executing query without additional options: " + statement;
			}
			else {
				message = getQueryLogMessageWithOptions(statement, options);
			}
			LOGGER.debug(message);
			LOGGER.debug("Query elapsed milliseconds: " + (System.currentTimeMillis() - startTime));
		}
		return resultSet;
	}
 
Example #13
Source File: SpannerTemplate.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private ResultSet executeRead(String tableName, KeySet keys, Iterable<String> columns,
		SpannerReadOptions options) {

	long startTime = LOGGER.isDebugEnabled() ? System.currentTimeMillis() : 0;

	ReadContext readContext = (options != null && options.getTimestampBound() != null)
			? getReadContext(options.getTimestampBound())
			: getReadContext();

	final ResultSet resultSet = options != null && options.getIndex() != null
			? readContext.readUsingIndex(tableName, options.getIndex(), keys, columns, options.getOptions())
			: readContext.read(tableName, keys, columns, options == null ? ArrayUtils.toArray() : options.getOptions());

	if (LOGGER.isDebugEnabled()) {
		StringBuilder logs = logColumns(tableName, keys, columns);
		logReadOptions(options, logs);
		LOGGER.debug(logs.toString());

		LOGGER.debug("Read elapsed milliseconds: " + (System.currentTimeMillis() - startTime));
	}

	return resultSet;
}
 
Example #14
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryWithFloat(DatabaseClient dbClient) {
  float exampleFloat = 0.8f;
  Statement statement =
      Statement.newBuilder(
              "SELECT VenueId, VenueName, PopularityScore FROM Venues "
                  + "WHERE PopularityScore > @popularityScore")
          .bind("popularityScore")
          .to(exampleFloat)
          .build();
  try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %s %f\n",
          resultSet.getLong("VenueId"),
          resultSet.getString("VenueName"),
          resultSet.getDouble("PopularityScore"));
    }
  }
}
 
Example #15
Source File: SpannerTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void existsByIdTest() {
	ResultSet results = mock(ResultSet.class);
	when(results.next()).thenReturn(true);

	when(this.readContext.read(any(), any(), any(), any())).thenReturn(results);
	when(this.databaseClient.singleUse(any())).thenReturn(this.readContext);

	Key key = Key.of("key");
	KeySet keySet = KeySet.singleKey(key);
	assertThat(this.spannerTemplate.existsById(TestEntity.class, key)).isTrue();

	verify(this.databaseClient, times(1)).singleUse();
	verify(this.readContext, times(1))
			.read(eq("custom_test_table"), eq(keySet), eq(Collections.singleton("id")));
}
 
Example #16
Source File: ConverterAwareMappingSpannerEntityProcessor.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Override
public <T> List<T> mapToList(ResultSet resultSet, Class<T> entityClass,
		Set<String> includeColumns, boolean allowMissingColumns) {
	ArrayList<T> result = new ArrayList<>();
	try {
		while (resultSet.next()) {
			result.add(this.entityReader.read(entityClass,
					resultSet.getCurrentRowAsStruct(),
					includeColumns,
					allowMissingColumns));
		}
	}
	finally {
		resultSet.close();
	}
	return result;
}
 
Example #17
Source File: SpannerTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void findMultipleKeysTest() {
	ResultSet results = mock(ResultSet.class);
	ReadOption readOption = mock(ReadOption.class);
	SpannerReadOptions options = new SpannerReadOptions().addReadOption(readOption)
			.setTimestampBound(TimestampBound.ofMinReadTimestamp(Timestamp.ofTimeMicroseconds(333L)));
	KeySet keySet = KeySet.singleKey(Key.of("key"));
	when(this.readContext.read(any(), any(), any(), any())).thenReturn(results);
	when(this.databaseClient.singleUse(eq(TimestampBound.ofMinReadTimestamp(Timestamp.ofTimeMicroseconds(333L)))))
			.thenReturn(this.readContext);

	verifyAfterEvents(new AfterReadEvent(Collections.emptyList(), keySet, options),
			() -> this.spannerTemplate.read(TestEntity.class, keySet, options), x -> {
				verify(this.objectMapper, times(1)).mapToList(same(results),
						eq(TestEntity.class), isNull(), eq(false));
				verify(this.readContext, times(1)).read(eq("custom_test_table"), same(keySet),
						any(), same(readOption));
			});
	verify(this.databaseClient, times(1))
			.singleUse(TimestampBound.ofMinReadTimestamp(Timestamp.ofTimeMicroseconds(333L)));
}
 
Example #18
Source File: ReadSpannerSchema.java    From beam with Apache License 2.0 6 votes vote down vote up
private ResultSet readTableInfo(ReadOnlyTransaction tx) {
  // retrieve schema information for all tables, as well as aggregating the
  // number of indexes that cover each column. this will be used to estimate
  // the number of cells (table column plus indexes) mutated in an upsert operation
  // in order to stay below the 20k threshold
  return tx.executeQuery(
      Statement.of(
          "SELECT"
              + "    c.table_name"
              + "  , c.column_name"
              + "  , c.spanner_type"
              + "  , (1 + COALESCE(t.indices, 0)) AS cells_mutated"
              + "  FROM ("
              + "    SELECT c.table_name, c.column_name, c.spanner_type, c.ordinal_position"
              + "     FROM information_schema.columns as c"
              + "     WHERE c.table_catalog = '' AND c.table_schema = '') AS c"
              + "  LEFT OUTER JOIN ("
              + "    SELECT t.table_name, t.column_name, COUNT(*) AS indices"
              + "      FROM information_schema.index_columns AS t "
              + "      WHERE t.index_name != 'PRIMARY_KEY' AND t.table_catalog = ''"
              + "      AND t.table_schema = ''"
              + "      GROUP BY t.table_name, t.column_name) AS t"
              + "  USING (table_name, column_name)"
              + "  ORDER BY c.table_name, c.ordinal_position"));
}
 
Example #19
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryWithInt(DatabaseClient dbClient) {
  long exampleInt = 3000;
  Statement statement =
      Statement.newBuilder(
              "SELECT VenueId, VenueName, Capacity FROM Venues " + "WHERE Capacity >= @capacity")
          .bind("capacity")
          .to(exampleInt)
          .build();
  try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %s %d\n",
          resultSet.getLong("VenueId"),
          resultSet.getString("VenueName"),
          resultSet.getLong("Capacity"));
    }
  }
}
 
Example #20
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryWithStruct(DatabaseClient dbClient) {
  // [START spanner_create_struct_with_data]
  Struct name =
      Struct.newBuilder().set("FirstName").to("Elena").set("LastName").to("Campbell").build();
  // [END spanner_create_struct_with_data]

  // [START spanner_query_data_with_struct]
  Statement s =
      Statement.newBuilder(
              "SELECT SingerId FROM Singers "
                  + "WHERE STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName) "
                  + "= @name")
          .bind("name")
          .to(name)
          .build();
  try (ResultSet resultSet = dbClient.singleUse().executeQuery(s)) {
    while (resultSet.next()) {
      System.out.printf("%d\n", resultSet.getLong("SingerId"));
    }
  }
  // [END spanner_query_data_with_struct]
}
 
Example #21
Source File: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void queryUsingIndex(PrintWriter pw) {
  ResultSet resultSet =
      SpannerClient.getDatabaseClient()
          .singleUse()
          .executeQuery(
              // We use FORCE_INDEX hint to specify which index to use. For more details see
              // https://cloud.google.com/spanner/docs/query-syntax#from-clause
              Statement.of(
                  "SELECT AlbumId, AlbumTitle, MarketingBudget\n"
                      + "FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle}\n"
                      + "WHERE AlbumTitle >= 'Aardvark' AND AlbumTitle < 'Goo'"));
  while (resultSet.next()) {
    pw.printf(
        "%d %s %s\n",
        resultSet.getLong("AlbumId"),
        resultSet.getString("AlbumTitle"),
        resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
  }
}
 
Example #22
Source File: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void readOnlyTransaction(PrintWriter pw) {
  // ReadOnlyTransaction must be closed by calling close() on it to release resources held by it.
  // We use a try-with-resource block to automatically do so.
  try (ReadOnlyTransaction transaction =
      SpannerClient.getDatabaseClient().readOnlyTransaction()) {
    ResultSet queryResultSet =
        transaction.executeQuery(
            Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"));
    while (queryResultSet.next()) {
      pw.printf(
          "%d %d %s\n",
          queryResultSet.getLong(0), queryResultSet.getLong(1), queryResultSet.getString(2));
    }
    ResultSet readResultSet =
        transaction.read(
            "Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "AlbumTitle"));
    while (readResultSet.next()) {
      pw.printf(
          "%d %d %s\n",
          readResultSet.getLong(0), readResultSet.getLong(1), readResultSet.getString(2));
    }
  }
}
 
Example #23
Source File: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void queryMarketingBudget(PrintWriter pw) {
  // Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
  // null.
  ResultSet resultSet =
      SpannerClient.getDatabaseClient()
          .singleUse()
          .executeQuery(Statement.of("SELECT SingerId, AlbumId, MarketingBudget FROM Albums"));
  while (resultSet.next()) {
    pw.printf(
        "%d %d %s\n",
        resultSet.getLong("SingerId"),
        resultSet.getLong("AlbumId"),
        // We check that the value is non null. ResultSet getters can only be used to retrieve
        // non null values.
        resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
  }
}
 
Example #24
Source File: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void queryUsingIndex(PrintWriter pw) {
  ResultSet resultSet =
      SpannerClient.getDatabaseClient()
          .singleUse()
          .executeQuery(
              // We use FORCE_INDEX hint to specify which index to use. For more details see
              // https://cloud.google.com/spanner/docs/query-syntax#from-clause
              Statement.of(
                  "SELECT AlbumId, AlbumTitle, MarketingBudget\n"
                      + "FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle}\n"
                      + "WHERE AlbumTitle >= 'Aardvark' AND AlbumTitle < 'Goo'"));
  while (resultSet.next()) {
    pw.printf(
        "%d %s %s\n",
        resultSet.getLong("AlbumId"),
        resultSet.getString("AlbumTitle"),
        resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
  }
}
 
Example #25
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryMarketingBudgetWithTimestamp(DatabaseClient dbClient) {
  // Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
  // null. A try-with-resource block is used to automatically release resources held by
  // ResultSet.
  try (ResultSet resultSet =
      dbClient
          .singleUse()
          .executeQuery(
              Statement.of(
                  "SELECT SingerId, AlbumId, MarketingBudget, LastUpdateTime FROM Albums"
                      + " ORDER BY LastUpdateTime DESC"))) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %d %s %s\n",
          resultSet.getLong("SingerId"),
          resultSet.getLong("AlbumId"),
          // We check that the value is non null. ResultSet getters can only be used to retrieve
          // non null values.
          resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"),
          resultSet.isNull("LastUpdateTime") ? "NULL" : resultSet.getTimestamp("LastUpdateTime"));
    }
  }
}
 
Example #26
Source File: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void readStoringIndex(PrintWriter pw) {
  // We can read MarketingBudget also from the index since it stores a copy of MarketingBudget.
  ResultSet resultSet =
      SpannerClient.getDatabaseClient()
          .singleUse()
          .readUsingIndex(
              "Albums",
              "AlbumsByAlbumTitle2",
              KeySet.all(),
              Arrays.asList("AlbumId", "AlbumTitle", "MarketingBudget"));
  while (resultSet.next()) {
    pw.printf(
        "%d %s %s\n",
        resultSet.getLong(0),
        resultSet.getString(1),
        resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
  }
}
 
Example #27
Source File: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void readOnlyTransaction(PrintWriter pw) {
  // ReadOnlyTransaction must be closed by calling close() on it to release resources held by it.
  // We use a try-with-resource block to automatically do so.
  try (ReadOnlyTransaction transaction =
      SpannerClient.getDatabaseClient().readOnlyTransaction()) {
    ResultSet queryResultSet =
        transaction.executeQuery(
            Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"));
    while (queryResultSet.next()) {
      pw.printf(
          "%d %d %s\n",
          queryResultSet.getLong(0), queryResultSet.getLong(1), queryResultSet.getString(2));
    }
    ResultSet readResultSet =
        transaction.read(
            "Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "AlbumTitle"));
    while (readResultSet.next()) {
      pw.printf(
          "%d %d %s\n",
          readResultSet.getLong(0), readResultSet.getLong(1), readResultSet.getString(2));
    }
  }
}
 
Example #28
Source File: HelloSpanner.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
  var writer = new PrintWriter(response.getWriter());
  try {
    DatabaseClient client = getClient();
    try (ResultSet rs =
        client
            .singleUse()
            .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) {
      writer.printf("Albums:%n");
      while (rs.next()) {
        writer.printf(
            "%d %d %s%n",
            rs.getLong("SingerId"), rs.getLong("AlbumId"), rs.getString("AlbumTitle"));
      }
    } catch (SpannerException e) {
      writer.printf("Error querying database: %s%n", e.getMessage());
      response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e.getMessage());
    }
  } catch (Throwable t) {
    logger.log(Level.SEVERE, "Spanner example failed", t);
    writer.printf("Error setting up Spanner: %s%n", t.getMessage());
    response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, t.getMessage());
  }
}
 
Example #29
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryWithArray(DatabaseClient dbClient) {
  Value exampleArray =
      Value.dateArray(Arrays.asList(Date.parseDate("2020-10-01"), Date.parseDate("2020-11-01")));

  Statement statement =
      Statement.newBuilder(
              "SELECT VenueId, VenueName, AvailableDate FROM Venues v, "
                  + "UNNEST(v.AvailableDates) as AvailableDate "
                  + "WHERE AvailableDate in UNNEST(@availableDates)")
          .bind("availableDates")
          .to(exampleArray)
          .build();
  try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %s %s\n",
          resultSet.getLong("VenueId"),
          resultSet.getString("VenueName"),
          resultSet.getDate("AvailableDate"));
    }
  }
}
 
Example #30
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void queryMarketingBudget(DatabaseClient dbClient) {
  // Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
  // null. A try-with-resource block is used to automatically release resources held by
  // ResultSet.
  try (ResultSet resultSet =
      dbClient
          .singleUse()
          .executeQuery(Statement.of("SELECT SingerId, AlbumId, MarketingBudget FROM Albums"))) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %d %s\n",
          resultSet.getLong("SingerId"),
          resultSet.getLong("AlbumId"),
          // We check that the value is non null. ResultSet getters can only be used to retrieve
          // non null values.
          resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
    }
  }
}