com.google.cloud.spanner.Value Java Examples

The following examples show how to use com.google.cloud.spanner.Value. 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: 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 #2
Source File: RandomValueGenerator.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
private Value generate(Column column) {
  Type type = column.type();

  if (type.getCode() != Type.Code.ARRAY) {
    return generateScalar(column);
  }

  switch (type.getArrayElementType().getCode()) {
    case BOOL:
      return Value.boolArray(generateList(random::nextBoolean));
    case INT64:
      return Value.int64Array(generateList(random::nextLong));
    case FLOAT64:
      return Value.float64Array(generateList(random::nextDouble));
    case BYTES:
      return Value.bytesArray(generateList(() -> randomByteArray(column.size())));
    case STRING:
      return Value.stringArray(generateList(() -> randomString(column.size())));
    case DATE:
      return Value.dateArray(generateList(this::randomDate));
    case TIMESTAMP:
      return Value.timestampArray(generateList(this::randomTimestamp));
  }
  throw new IllegalArgumentException("Unexpected type " + type);
}
 
Example #3
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void readSingularArrayMismatchTest() {
	this.expectedEx.expect(SpannerDataException.class);
	this.expectedEx.expectMessage("The value in column with name innerLengths could not be converted " +
			"to the corresponding property in the entity. The property's type is class java.lang.Integer.");

	Struct colStruct = Struct.newBuilder().set("string_col").to(Value.string("value"))
			.build();
	Struct rowStruct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("innerLengths")
			.toStructArray(Type.struct(StructField.of("string_col", Type.string())),
					Arrays.asList(colStruct))
			.build();

	new ConverterAwareMappingSpannerEntityReader(new SpannerMappingContext(),
			new SpannerReadConverter(Arrays.asList(new Converter<Struct, Integer>() {
				@Nullable
				@Override
				public Integer convert(Struct source) {
					return source.getString("string_col").length();
				}
			}))).read(OuterTestEntityFlatFaulty.class, rowStruct);
}
 
Example #4
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void readConvertedNestedStructTest() {
	Struct colStruct = Struct.newBuilder().set("string_col").to(Value.string("value"))
			.build();
	Struct rowStruct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("innerLengths")
			.toStructArray(Type.struct(StructField.of("string_col", Type.string())),
					Arrays.asList(colStruct))
			.build();

	OuterTestEntityFlat result = new ConverterAwareMappingSpannerEntityReader(
			new SpannerMappingContext(),
			new SpannerReadConverter(Arrays.asList(new Converter<Struct, Integer>() {
				@Nullable
				@Override
				public Integer convert(Struct source) {
					return source.getString("string_col").length();
				}
			}))).read(OuterTestEntityFlat.class, rowStruct);
	assertThat(result.id).isEqualTo("key1");
	assertThat(result.innerLengths).hasSize(1);
	assertThat(result.innerLengths.get(0)).isEqualTo(5);
}
 
Example #5
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void readNotFoundColumnTest() {
	this.expectedEx.expect(SpannerDataException.class);
	this.expectedEx.expectMessage("Unable to read column from Cloud Spanner results: id4");
	Struct struct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("custom_col").to(Value.string("string1")).set("booleanField")
			.to(Value.bool(true)).set("longField").to(Value.int64(3L))
			.set("doubleArray")
			.to(Value.float64Array(new double[] { 3.33, 3.33, 3.33 }))
			.set("dateField").to(Value.date(Date.fromYearMonthDay(2018, 11, 22)))
			.set("timestampField")
			.to(Value.timestamp(Timestamp.ofTimeMicroseconds(333))).set("bytes")
			.to(Value.bytes(ByteArray.copyFrom("string1"))).build();

	this.spannerEntityReader.read(TestEntity.class, struct);
}
 
Example #6
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void readUnconvertableValueTest() {
	this.expectedEx.expect(ConversionFailedException.class);
	this.expectedEx.expectMessage("Failed to convert from type [java.lang.String] to type " +
			"[java.lang.Double] for value 'UNCONVERTABLE VALUE'; nested exception is " +
			"java.lang.NumberFormatException: For input string: \"UNCONVERTABLEVALUE\"");
	Struct struct = Struct.newBuilder().set("id").to(Value.string("key1")).set("id2")
			.to(Value.string("key2")).set("id3").to(Value.string("key3")).set("id4")
			.to(Value.string("key4")).set("intField2").to(Value.int64(333L))
			.set("custom_col").to(Value.string("WHITE")).set("booleanField")
			.to(Value.bool(true)).set("longField").to(Value.int64(3L))
			.set("doubleField").to(Value.string("UNCONVERTABLE VALUE"))
			.set("doubleArray")
			.to(Value.float64Array(new double[] { 3.33, 3.33, 3.33 }))
			.set("dateField").to(Value.date(Date.fromYearMonthDay(2018, 11, 22)))
			.set("timestampField")
			.to(Value.timestamp(Timestamp.ofTimeMicroseconds(333))).set("bytes")
			.to(Value.bytes(ByteArray.copyFrom("string1"))).build();

	this.spannerEntityReader.read(TestEntity.class, struct);
}
 
Example #7
Source File: RandomValueGenerator.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
private Value generateScalar(Column column) {
  Type type = column.type();
  switch (type.getCode()) {
    case BOOL:
      return Value.bool(random.nextBoolean());
    case INT64:
      return Value.int64(random.nextLong());
    case FLOAT64:
      return Value.float64(random.nextDouble());
    case BYTES: {
      return Value.bytes(randomByteArray(column.size()));
    }
    case STRING: {
      return Value.string(randomString(column.size()));
    }
    case DATE: {
      return Value.date(randomDate());
    }
    case TIMESTAMP: {
      return Value.timestamp(randomTimestamp());
    }
  }
  throw new IllegalArgumentException("Unexpected type " + type);
}
 
Example #8
Source File: RandomInsertMutationGenerator.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
private LinkedList<Mutation> generate(
    Table r, Map<String, Value> overrides, Map<String, TableSupplier> suppliers, int num) {
  LinkedList<Mutation> result = new LinkedList<>();
  for (int i = 0; i < num; i++) {
    TableSupplier tableSupplier = suppliers.get(r.name());

    Mutation mutation = tableSupplier.generateMutation(overrides);
    Map<String, Value> mutationMap = mutation.asMap();

    Map<String, Value> pkMap = new HashMap<>();
    for (IndexColumn pk : r.primaryKeys()) {
      Value value = mutationMap.get(pk.name());
      pkMap.put(pk.name(), value);
    }

    result.add(mutation);
    for (Table c : ddl.childTables(r.name())) {
      LinkedList<Mutation> children = generate(c, pkMap, suppliers, rand.nextInt(3));
      result.addAll(children);
    }
  }
  return result;
}
 
Example #9
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void readNestedStructWithConstructor() {
	Struct innerStruct = Struct.newBuilder().set("value").to(Value.string("value"))
			.build();
	Struct outerStruct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("innerTestEntities")
			.toStructArray(Type.struct(StructField.of("value", Type.string())),
					Arrays.asList(innerStruct))
			.build();

	TestEntities.OuterTestEntityWithConstructor result = this.spannerEntityReader
			.read(TestEntities.OuterTestEntityWithConstructor.class, outerStruct, null, true);
	assertThat(result.id).isEqualTo("key1");
	assertThat(result.innerTestEntities).hasSize(1);
	assertThat(result.innerTestEntities.get(0).value).isEqualTo("value");
}
 
Example #10
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void readNestedStructsAsStructsTest() {
	Struct innerStruct = Struct.newBuilder().set("value")
			.to(Value.string("inner-value")).build();
	Struct outerStruct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("innerStructs")
			.toStructArray(Type.struct(StructField.of("value", Type.string())),
					Arrays.asList(innerStruct))
			.build();

	OuterTestHoldingStructsEntity result = this.spannerEntityReader
			.read(OuterTestHoldingStructsEntity.class, outerStruct);
	assertThat(result.id).isEqualTo("key1");
	assertThat(result.innerStructs).hasSize(1);
	assertThat(result.innerStructs.get(0).getString("value")).isEqualTo("inner-value");
}
 
Example #11
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void readNestedStructTest() {
	Struct innerStruct = Struct.newBuilder().set("value")
			.to(Value.string("inner-value")).build();
	Struct outerStruct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("innerTestEntities")
			.toStructArray(Type.struct(StructField.of("value", Type.string())),
					Arrays.asList(innerStruct))
			.build();

	OuterTestEntity result = this.spannerEntityReader.read(OuterTestEntity.class,
			outerStruct, null, true);
	assertThat(result.id).isEqualTo("key1");
	assertThat(result.innerTestEntities).hasSize(1);
	assertThat(result.innerTestEntities.get(0).value).isEqualTo("inner-value");
	assertThat(result.innerTestEntities.get(0).missingColumnValue).isNull();
}
 
Example #12
Source File: MutationSizeEstimator.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Estimates a size of mutation in bytes. */
static long sizeOf(Mutation m) {
  if (m.getOperation() == Mutation.Op.DELETE) {
    return sizeOf(m.getKeySet());
  }
  long result = 0;
  for (Value v : m.getValues()) {
    switch (v.getType().getCode()) {
      case ARRAY:
        result += estimateArrayValue(v);
        break;
      case STRUCT:
        throw new IllegalArgumentException("Structs are not supported in mutation.");
      default:
        result += estimatePrimitiveValue(v);
    }
  }
  return result;
}
 
Example #13
Source File: MutationSizeEstimator.java    From beam with Apache License 2.0 6 votes vote down vote up
private static long estimatePrimitiveValue(Value v) {
  switch (v.getType().getCode()) {
    case BOOL:
      return 1;
    case INT64:
    case FLOAT64:
      return 8;
    case DATE:
    case TIMESTAMP:
      return 12;
    case STRING:
      return v.isNull() ? 0 : v.getString().length();
    case BYTES:
      return v.isNull() ? 0 : v.getBytes().length();
    default:
      throw new IllegalArgumentException("Unsupported type " + v.getType());
  }
}
 
Example #14
Source File: ConverterAwareMappingSpannerEntityWriterTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommitTimestampsType() {
	CommitTimestamps entity = new CommitTimestamps();

	doWithFields(CommitTimestamps.class,
			f -> setField(f, entity, CommitTimestamp.of(f.getType())),
			ff -> !ff.isSynthetic() && Objects.isNull(ff.getAnnotation(PrimaryKey.class)));

	WriteBuilder writeBuilder = Mutation.newInsertBuilder("commit_timestamps_table");
	this.spannerEntityWriter.write(entity, writeBuilder::set);
	Mutation mutation = writeBuilder.build();
	assertThat(mutation.asMap().entrySet().stream()
			.filter(e -> !"id".equals(e.getKey()))
			.map(Map.Entry::getValue)
			.collect(Collectors.toList())).allMatch(Value::isCommitTimestamp);
}
 
Example #15
Source File: Queue.java    From spanner-event-exporter with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a QueueMessage to the spanner queue table
 *
 * <p>Example of sending data to a queue.
 *
 * <pre>{@code
 * MyProto myProto = MyProto.newBuilder().setMessage("My-Message").build();
 *
 * try {
 *   Queue.send(dbClient, queueName, "myKey", ByteArray.copyFrom(myProto.toByteArray()));
 * } catch (SpannerException e) {
 *   log.error("Could not write message to Queue", e);
 * }
 * }</pre>
 *
 * @param dbClient the Spanner database client
 * @param queueName the name of the queue to be polled
 * @param key the name used to partition the passed value for storage and lookup
 * @param value the message payload
 * @return Timestamp the timestamp that the message was written
 */
public static Timestamp send(DatabaseClient dbClient, String queueName, String key, byte[] value)
    throws SpannerException {
  Preconditions.checkNotNull(dbClient);
  Preconditions.checkNotNull(queueName);
  Preconditions.checkNotNull(key);
  Preconditions.checkNotNull(value);

  final List<Mutation> mutations = new ArrayList<>();
  mutations.add(
      Mutation.newInsertBuilder(queueName)
          .set("MessageId")
          .to(UUID.randomUUID().toString())
          .set("Key")
          .to(key)
          .set("Payload")
          .to(ByteArray.copyFrom(value))
          .set("Ack")
          .to(false)
          .set("Timestamp")
          .to(Value.COMMIT_TIMESTAMP)
          .build());

  return dbClient.write(mutations);
}
 
Example #16
Source File: RunningOperationsStore.java    From spanner-jdbc with MIT License 6 votes vote down vote up
/**
 * 
 * @return A result set of all DDL operations that have been issued on this connection since the
 *         last clear operation.
 * @throws SQLException If a database error occurs
 */
ResultSet getOperations(CloudSpannerStatement statement) throws SQLException {
  List<Struct> rows = new ArrayList<>(operations.size());
  for (DdlOperation op : operations) {
    op.operation = op.operation.reload();
    String exception = null;
    try {
      op.operation.getResult();
    } catch (Exception e) {
      exception = e.getMessage();
    }
    for (String ddl : op.sql) {
      rows.add(Struct.newBuilder().set("NAME").to(Value.string(op.operation.getName()))
          .set("TIME_STARTED").to(Value.timestamp(op.timeStarted)).set("STATEMENT")
          .to(Value.string(ddl)).set("DONE").to(Value.bool(op.operation.isDone()))
          .set("EXCEPTION").to(Value.string(exception)).build());
    }
  }
  com.google.cloud.spanner.ResultSet rs =
      ResultSets.forRows(Type.struct(StructField.of("NAME", Type.string()),
          StructField.of("TIME_STARTED", Type.timestamp()),
          StructField.of("STATEMENT", Type.string()), StructField.of("DONE", Type.bool()),
          StructField.of("EXCEPTION", Type.string())), rows);
  return new CloudSpannerResultSet(statement, rs, null);
}
 
Example #17
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
Venue(
    long venueId,
    String venueName,
    String venueInfo,
    long capacity,
    Value availableDates,
    String lastContactDate,
    boolean outdoorVenue,
    float popularityScore) {
  this.venueId = venueId;
  this.venueName = venueName;
  this.venueInfo = venueInfo;
  this.capacity = capacity;
  this.availableDates = availableDates;
  this.lastContactDate = lastContactDate;
  this.outdoorVenue = outdoorVenue;
  this.popularityScore = popularityScore;
}
 
Example #18
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void writeExampleDataWithTimestamp(DatabaseClient dbClient) {
  List<Mutation> mutations = new ArrayList<>();
  for (Performance performance : PERFORMANCES) {
    mutations.add(
        Mutation.newInsertBuilder("Performances")
            .set("SingerId")
            .to(performance.singerId)
            .set("VenueId")
            .to(performance.venueId)
            .set("EventDate")
            .to(performance.eventDate)
            .set("Revenue")
            .to(performance.revenue)
            .set("LastUpdateTime")
            .to(Value.COMMIT_TIMESTAMP)
            .build());
  }
  dbClient.write(mutations);
}
 
Example #19
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testPartialConstructor() {
	Struct struct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("custom_col").to(Value.string("string1")).set("booleanField")
			.to(Value.bool(true)).set("longField").to(Value.int64(3L))
			.set("doubleField").to(Value.float64(3.14)).build();

	this.spannerEntityReader.read(TestEntities.PartialConstructor.class, struct);
}
 
Example #20
Source File: MutationSizeEstimator.java    From beam with Apache License 2.0 5 votes vote down vote up
private static long estimateArrayValue(Value v) {
  if (v.isNull()) {
    return 0;
  }
  switch (v.getType().getArrayElementType().getCode()) {
    case BOOL:
      return v.getBoolArray().size();
    case INT64:
      return 8L * v.getInt64Array().size();
    case FLOAT64:
      return 8L * v.getFloat64Array().size();
    case STRING:
      long totalLength = 0;
      for (String s : v.getStringArray()) {
        if (s == null) {
          continue;
        }
        totalLength += s.length();
      }
      return totalLength;
    case BYTES:
      totalLength = 0;
      for (ByteArray bytes : v.getBytesArray()) {
        if (bytes == null) {
          continue;
        }
        totalLength += bytes.length();
      }
      return totalLength;
    case DATE:
      return 12L * v.getDateArray().size();
    case TIMESTAMP:
      return 12L * v.getTimestampArray().size();
    default:
      throw new IllegalArgumentException("Unsupported type " + v.getType());
  }
}
 
Example #21
Source File: MutationKeyEncoder.java    From beam with Apache License 2.0 5 votes vote down vote up
private void encodeKey(OrderedCode orderedCode, Mutation m) {
  Map<String, Value> mutationMap = mutationAsMap(m);
  for (SpannerSchema.KeyPart part : schema.getKeyParts(m.getTable())) {
    Value val = mutationMap.get(part.getField());
    if (val == null || val.isNull()) {
      if (part.isDesc()) {
        orderedCode.writeInfinityDecreasing();
      } else {
        orderedCode.writeInfinity();
      }
    } else {
      Type.Code code = val.getType().getCode();
      switch (code) {
        case BOOL:
          writeNumber(orderedCode, part, (long) (val.getBool() ? 0 : 1));
          break;
        case INT64:
          writeNumber(orderedCode, part, val.getInt64());
          break;
        case FLOAT64:
          writeNumber(orderedCode, part, Double.doubleToLongBits(val.getFloat64()));
          break;
        case STRING:
          writeString(orderedCode, part, val.getString());
          break;
        case BYTES:
          writeBytes(orderedCode, part, val.getBytes());
          break;
        case TIMESTAMP:
          writeTimestamp(orderedCode, part, val.getTimestamp());
          break;
        case DATE:
          writeNumber(orderedCode, part, encodeDate(val.getDate()));
          break;
        default:
          throw new IllegalArgumentException("Unknown type " + val.getType());
      }
    }
  }
}
 
Example #22
Source File: MutationKeyEncoder.java    From beam with Apache License 2.0 5 votes vote down vote up
private static Map<String, Value> mutationAsMap(Mutation m) {
  Map<String, Value> result = new HashMap<>();
  Iterator<String> coli = m.getColumns().iterator();
  Iterator<Value> vali = m.getValues().iterator();
  while (coli.hasNext()) {
    String column = coli.next();
    Value val = vali.next();
    result.put(column.toLowerCase(), val);
  }
  return result;
}
 
Example #23
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void updateWithTimestamp(DatabaseClient dbClient) {
  // Mutation can be used to update/insert/delete a single row in a table. Here we use
  // newUpdateBuilder to create update mutations.
  List<Mutation> mutations =
      Arrays.asList(
          Mutation.newUpdateBuilder("Albums")
              .set("SingerId")
              .to(1)
              .set("AlbumId")
              .to(1)
              .set("MarketingBudget")
              .to(1000000)
              .set("LastUpdateTime")
              .to(Value.COMMIT_TIMESTAMP)
              .build(),
          Mutation.newUpdateBuilder("Albums")
              .set("SingerId")
              .to(2)
              .set("AlbumId")
              .to(2)
              .set("MarketingBudget")
              .to(750000)
              .set("LastUpdateTime")
              .to(Value.COMMIT_TIMESTAMP)
              .build());
  // This writes all the mutations to Cloud Spanner atomically.
  dbClient.write(mutations);
}
 
Example #24
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void writeDatatypesData(DatabaseClient dbClient) {
  List<Mutation> mutations = new ArrayList<>();
  for (Venue venue : VENUES) {
    mutations.add(
        Mutation.newInsertBuilder("Venues")
            .set("VenueId")
            .to(venue.venueId)
            .set("VenueName")
            .to(venue.venueName)
            .set("VenueInfo")
            .to(venue.venueInfo)
            .set("Capacity")
            .to(venue.capacity)
            .set("AvailableDates")
            .to(venue.availableDates)
            .set("LastContactDate")
            .to(venue.lastContactDate)
            .set("OutdoorVenue")
            .to(venue.outdoorVenue)
            .set("PopularityScore")
            .to(venue.popularityScore)
            .set("LastUpdateTime")
            .to(Value.COMMIT_TIMESTAMP)
            .build());
  }
  dbClient.write(mutations);
}
 
Example #25
Source File: SpannerWriteMethodCoverageTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void allKnownMappingTypesTest() throws NoSuchFieldException {
	for (Method method : ValueBinder.class.getMethods()) {

		String methodName = method.getName();

		// ignoring non-public and non "to" named binder methods
		if (!Modifier.isPublic(method.getModifiers()) || !methodName.startsWith("to")
				|| method.getParameterCount() != 1) {
			continue;
		}

		Class<?> paramType = ConversionUtils.boxIfNeeded(method.getParameterTypes()[0]);
		if (paramType.equals(Struct.class) || paramType.equals(Value.class)) {
			/*
			 * 1. there is a method for binding a Struct value, but because Struct
			 * values cannot be written to table columns we will ignore it. 2. there
			 * is a method for binding a Value value. However, the purpose of the
			 * converters is to wrap java types into the Value for the user.
			 * Furthermore, the Cloud Spanner client lib does not give a way to read a
			 * Value back from a Struct, so we will ignore this method.
			 */
			continue;
		}
		else if (ConversionUtils.isIterableNonByteArrayType(paramType)) {
			Class<?> innerParamType = (Class) ((ParameterizedType) method
					.getGenericParameterTypes()[0]).getActualTypeArguments()[0];
			assertThat(
					ConverterAwareMappingSpannerEntityWriter.iterablePropertyTypeToMethodMap.keySet())
							.contains(innerParamType);
		}
		else {
			assertThat(
					ConverterAwareMappingSpannerEntityWriter.singleItemTypeValueBinderMethodMap.keySet())
							.contains(paramType);
		}
	}
}
 
Example #26
Source File: CloudSpannerResultSetMetaDataTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private CloudSpannerResultSet createFooPrimaryKeysResultSet(CloudSpannerStatement statement)
    throws SQLException {
  List<Struct> rows = new ArrayList<>(1);
  rows.add(Struct.newBuilder().set("COLUMN_NAME").to(Value.string(tableColumns().get(0).name))
      .build());
  ResultSet rs =
      ResultSets.forRows(Type.struct(StructField.of("COLUMN_NAME", Type.string())), rows);
  return new CloudSpannerResultSet(statement, rs, null);
}
 
Example #27
Source File: CloudSpannerPreparedStatementTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private static String[] getValues(Iterable<Value> values) {
  List<Value> valueList = Lists.newArrayList(values);
  String[] res = new String[valueList.size()];
  int index = 0;
  for (Value value : valueList) {
    res[index] = value.toString();
    index++;
  }
  return res;
}
 
Example #28
Source File: CloudSpannerPreparedStatementTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testInsertStatementWithArrayValue() throws SQLException {
  Mutation mutation = getMutation("INSERT INTO FOO (COL1) VALUES ('{\"foo\", \"bar\"}')");
  Value value = mutation.getValues().iterator().next();
  assertThat(value.getStringArray(), is(Arrays.asList("foo", "bar")));

  mutation = getMutation("INSERT INTO FOO (COL1) VALUES ('{\"foo, bar\", \"bar, foo\"}')");
  value = mutation.getValues().iterator().next();
  assertThat(value.getStringArray(), is(Arrays.asList("foo, bar", "bar, foo")));

  mutation = getMutation("INSERT INTO FOO (COL1) VALUES ('{1,2,3}')");
  value = mutation.getValues().iterator().next();
  assertThat(value.getInt64Array(), is(Arrays.asList(1L, 2L, 3L)));

  mutation = getMutation("INSERT INTO FOO (COL1) VALUES ('{1.0,2.0,3.5}')");
  value = mutation.getValues().iterator().next();
  assertThat(value.getFloat64Array(), is(Arrays.asList(1.0D, 2.0D, 3.5D)));

  mutation = getMutation(
      "INSERT INTO FOO (COL1) VALUES ('{{d \"2018-05-20\"}, {d \"2018-05-21\"},{d \"2018-05-22\"}}')");
  value = mutation.getValues().iterator().next();
  assertThat(value.getDateArray(),
      is(Arrays.asList(com.google.cloud.Date.fromYearMonthDay(2018, 5, 20),
          com.google.cloud.Date.fromYearMonthDay(2018, 5, 21),
          com.google.cloud.Date.fromYearMonthDay(2018, 5, 22))));

  mutation = getMutation(
      "INSERT INTO FOO (COL1) VALUES ('{{ts \"2018-05-20 10:05:15\"}, {ts \"2018-05-21T11:00:00\"},{ts \"2018-05-22 13:15:25.12345\"}}')");
  value = mutation.getValues().iterator().next();
  assertThat(value.getTimestampArray(),
      is(Arrays.asList(com.google.cloud.Timestamp.parseTimestamp("2018-05-20T10:05:15Z"),
          com.google.cloud.Timestamp.parseTimestamp("2018-05-21T11:00:00Z"),
          com.google.cloud.Timestamp.parseTimestamp("2018-05-22T13:15:25.12345Z"))));

  mutation = getMutation("INSERT INTO FOO (COL1) VALUES ('{true, false,true,false,false}')");
  value = mutation.getValues().iterator().next();
  assertThat(value.getBoolArray(), is(Arrays.asList(true, false, true, false, false)));
}
 
Example #29
Source File: SpannerStatementQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private void runPageableOrSortTest(Object[] params, Method method, String expectedSql) {
	when(this.queryMethod.getName()).thenReturn(
			"findByPriceLessThan");
	this.partTreeSpannerQuery = spy(createQuery());

	when(this.spannerTemplate.query((Function<Struct, Object>) any(), any(), any()))
			.thenReturn(Collections.singletonList(1L));

	doReturn(new DefaultParameters(method)).when(this.queryMethod).getParameters();

	when(this.spannerTemplate.query((Class) any(), any(), any()))
			.thenAnswer((invocation) -> {
				Statement statement = invocation.getArgument(1);

				assertThat(statement.getSql()).isEqualTo(expectedSql);

				Map<String, Value> paramMap = statement.getParameters();

				assertThat(paramMap.get("tag0").getFloat64()).isEqualTo(params[0]);
				assertThat(paramMap).hasSize(1);

				return null;
			});

	doReturn(Object.class).when(this.partTreeSpannerQuery)
			.getReturnedSimpleConvertableItemType();
	doReturn(null).when(this.partTreeSpannerQuery).convertToSimpleReturnType(any(),
			any());

	this.partTreeSpannerQuery.execute(params);
	verify(this.spannerTemplate, times(1)).query((Class) any(),
			any(), any());
}
 
Example #30
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void readNestedStructAsStructTest() {
	Struct innerStruct = Struct.newBuilder().set("value")
			.to(Value.string("inner-value")).build();
	Struct outerStruct = Struct.newBuilder().set("id").to(Value.string("key1"))
			.set("innerStruct").to(innerStruct).build();

	OuterTestHoldingStructEntity result = this.spannerEntityReader
			.read(OuterTestHoldingStructEntity.class, outerStruct);
	assertThat(result.id).isEqualTo("key1");
	assertThat(result.innerStruct.getString("value")).isEqualTo("inner-value");
}