com.google.cloud.Date Java Examples

The following examples show how to use com.google.cloud.Date. 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: 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 #2
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetDateLabelCalendar() throws SQLException {
  Calendar cal = Calendar.getInstance();
  assertNotNull(subject.getDate(DATE_COL_NOT_NULL, cal));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10), subject.getDate(DATE_COL_NOT_NULL, cal));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getDate(DATE_COL_NULL, cal));
  assertTrue(subject.wasNull());

  Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  Calendar expected = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  expected.set(2017, 8, 10, 0, 0, 0);
  expected.clear(Calendar.MILLISECOND);
  assertEquals(new java.sql.Date(expected.getTimeInMillis()),
      subject.getDate(DATE_COL_NOT_NULL, calGMT));
}
 
Example #3
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetDateIndexCalendar() throws SQLException {
  Calendar cal = Calendar.getInstance();
  assertNotNull(subject.getDate(DATE_COLINDEX_NOTNULL, cal));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10),
      subject.getDate(DATE_COLINDEX_NOTNULL, cal));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getDate(DATE_COLINDEX_NULL, cal));
  assertTrue(subject.wasNull());

  Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  Calendar expected = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  expected.set(2017, 8, 10, 0, 0, 0);
  expected.clear(Calendar.MILLISECOND);
  assertEquals(new java.sql.Date(expected.getTimeInMillis()),
      subject.getDate(DATE_COLINDEX_NOTNULL, calGMT));
}
 
Example #4
Source File: ConverterAwareMappingSpannerEntityWriterTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void writeNullColumnsTest() {
	TestEntity t = new TestEntity();

	t.dateField = null;
	t.doubleList = null;

	WriteBuilder writeBuilder = mock(WriteBuilder.class);

	ValueBinder<WriteBuilder> dateFieldBinder = mock(ValueBinder.class);
	when(dateFieldBinder.to((Date) any())).thenReturn(null);
	when(writeBuilder.set(eq("dateField"))).thenReturn(dateFieldBinder);

	ValueBinder<WriteBuilder> doubleListFieldBinder = mock(ValueBinder.class);
	when(doubleListFieldBinder.toFloat64Array((Iterable<Double>) any()))
			.thenReturn(null);
	when(writeBuilder.set(eq("doubleList"))).thenReturn(doubleListFieldBinder);

	this.spannerEntityWriter.write(t, writeBuilder::set,
			Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("dateField", "doubleList"))));
	verify(dateFieldBinder, times(1)).to((Date) isNull());
	verify(doubleListFieldBinder, times(1))
			.toFloat64Array((Iterable<Double>) isNull());
}
 
Example #5
Source File: KeyConversionTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Parameterized.Parameters(name = "{index}: {0}")
public static Collection<Object[]> types() {
	return Arrays.asList(new Object[][] {
			{ "single boolean", true, Key.of(true) },
			{ "single int", 1, Key.of(1) },
			{ "single long", 23123123L, Key.of(23123123L) },
			{ "single float", .223f, Key.of(.223f) },
			{ "single double", 3.14, Key.of(3.14) },
			{ "single string", "hello", Key.of("hello") },
			{ "single bytearray", ByteArray.copyFrom("world"), Key.of(ByteArray.copyFrom("world")) },
			{ "single timestamp", Timestamp.ofTimeMicroseconds(123132),
					Key.of(Timestamp.ofTimeMicroseconds(123132)) },
			{ "single date", Date.parseDate("2018-04-20"), Key.of(Date.parseDate("2018-04-20")) },
			{ "mixed array", new Object[] { 1, true, false, "hello", ByteArray.copyFrom("world") },
					Key.of(1, true, false, "hello", ByteArray.copyFrom("world")) },
			{ "mixed list", Arrays.asList(1, true, false, "hello", ByteArray.copyFrom("world")),
					Key.of(1, true, false, "hello", ByteArray.copyFrom("world")) },
			{ "converted default type (date)",
					java.util.Date.from(Instant.ofEpochSecond(123)),
					Key.of(SpannerConverters.JAVA_TO_SPANNER_TIMESTAMP_CONVERTER
							.convert(java.sql.Timestamp.from(Instant.ofEpochSecond(123)))) },
			{ "unsupported type (TestEntity)", new TestEntities.TestEntity(), SpannerDataException.class },
			{ "empty key (Object[])", new Object[] {}, SpannerDataException.class },
			{ "empty key (List{})", Collections.emptyList(), SpannerDataException.class },
	});
}
 
Example #6
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 #7
Source File: SpannerRecordConverterTest.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
@Test
public void dateTimestamp() {
  Ddl ddl = Ddl.builder()
      .createTable("users")
      .column("id").int64().notNull().endColumn()
      .column("date").date().endColumn()
      .column("ts").timestamp().endColumn()
      .primaryKey().asc("id").end()
      .endTable()
      .build();
  Schema schema = converter.convert(ddl).iterator().next();
  SpannerRecordConverter recordConverter = new SpannerRecordConverter(schema);
  Struct struct = Struct.newBuilder()
      .set("id").to(1L)
      .set("date").to(Date.fromYearMonthDay(2018, 2, 2))
      .set("ts").to(Timestamp.ofTimeMicroseconds(10))
      .build();

  GenericRecord avroRecord = recordConverter.convert(struct);

  assertThat(avroRecord.get("id"), equalTo(1L));
  assertThat(avroRecord.get("date"), equalTo("2018-02-02"));
  assertThat(avroRecord.get("ts"), equalTo("1970-01-01T00:00:00.000010000Z"));
}
 
Example #8
Source File: MutationSizeEstimator.java    From beam with Apache License 2.0 6 votes vote down vote up
private static long sizeOf(Key k) {
  long result = 0;
  for (Object part : k.getParts()) {
    if (part == null) {
      continue;
    }
    if (part instanceof Boolean) {
      result += 1;
    } else if (part instanceof Long) {
      result += 8;
    } else if (part instanceof Double) {
      result += 8;
    } else if (part instanceof String) {
      result += ((String) part).length();
    } else if (part instanceof ByteArray) {
      result += ((ByteArray) part).length();
    } else if (part instanceof Timestamp) {
      result += 12;
    } else if (part instanceof Date) {
      result += 12;
    }
  }
  return result;
}
 
Example #9
Source File: AvroRecordConverter.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
private Optional<Date> readDate(
    GenericRecord record, Schema.Type avroType, LogicalType logicalType, String fieldName) {
  switch (avroType) {
    case INT:
      if (logicalType == null || !LogicalTypes.date().equals(logicalType)) {
        throw new IllegalArgumentException(
            "Cannot interpret Avrotype INT Logicaltype " + logicalType + " as DATE");
      }
      // Avro Date is number of days since Jan 1, 1970.
      // Have to convert to Java Date first before creating google.cloud.core.Date
      return Optional.ofNullable((Integer) record.get(fieldName))
          .map(x -> new java.util.Date((long) x * 24L * 3600L * 1000L))
          .map(Date::fromJavaUtilDate);
    case STRING:
      return Optional.ofNullable((Utf8) record.get(fieldName))
          .map(Utf8::toString)
          .map(Date::parseDate);
    default:
      throw new IllegalArgumentException("Cannot interpret " + avroType + " as DATE");
  }
}
 
Example #10
Source File: AvroRecordConverter.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Optional<List<Date>> readDateArray(
    GenericRecord record, Schema.Type avroType, String fieldName) {
  switch (avroType) {
    case STRING:
      {
        List<Utf8> value = (List<Utf8>) record.get(fieldName);
        if (value == null) {
          return Optional.empty();
        }
        return Optional.of(
            value
                .stream()
                .map(x -> x == null ? null : Date.parseDate(x.toString()))
                .collect(Collectors.toList()));
      }
    default:
      throw new IllegalArgumentException("Cannot interpret " + avroType + " as DATE");
  }
}
 
Example #11
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 #12
Source File: ConverterAwareMappingSpannerEntityProcessorTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void canConvertDefaultTypesNoCustomConverters() {
	ConverterAwareMappingSpannerEntityProcessor converter = new ConverterAwareMappingSpannerEntityProcessor(
			new SpannerMappingContext());

	verifyCanConvert(converter, java.util.Date.class, Timestamp.class);
	verifyCanConvert(converter, Instant.class, Timestamp.class);
	verifyCanConvert(converter, LocalDate.class, Date.class);
}
 
Example #13
Source File: ConverterAwareMappingSpannerEntityProcessorTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void canConvertDefaultTypesCustomConverters() {
	ConverterAwareMappingSpannerEntityProcessor converter = new ConverterAwareMappingSpannerEntityProcessor(
			new SpannerMappingContext(), Arrays.asList(JAVA_TO_SPANNER),
			Arrays.asList(SPANNER_TO_JAVA));

	verifyCanConvert(converter, java.util.Date.class, Timestamp.class);
	verifyCanConvert(converter, LocalDate.class, Date.class);
	verifyCanConvert(converter, Instant.class, Timestamp.class);
	verifyCanConvert(converter, JavaType.class, SpannerType.class);
}
 
Example #14
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetObjectLabel() throws SQLException {
  assertNotNull(subject.getObject(DATE_COL_NOT_NULL));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10), subject.getObject(DATE_COL_NOT_NULL));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getObject(DATE_COL_NULL));
  assertTrue(subject.wasNull());
}
 
Example #15
Source File: ConverterAwareMappingSpannerEntityWriter.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> createIterableTypeMapping() {
	Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> map = new LinkedHashMap<>();
	map.put(Boolean.class, ValueBinder::toBoolArray);
	map.put(Long.class, ValueBinder::toInt64Array);
	map.put(Double.class, ValueBinder::toFloat64Array);
	map.put(Timestamp.class, ValueBinder::toTimestampArray);
	map.put(Date.class, ValueBinder::toDateArray);
	map.put(ByteArray.class, ValueBinder::toBytesArray);
	map.put(String.class, ValueBinder::toStringArray);

	return Collections.unmodifiableMap(map);
}
 
Example #16
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetObjectIndexMap() throws SQLException {
  Map<String, Class<?>> map = Collections.emptyMap();
  assertNotNull(subject.getObject(DATE_COLINDEX_NOTNULL, map));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10),
      subject.getObject(DATE_COLINDEX_NOTNULL, map));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getObject(DATE_COLINDEX_NULL, map));
  assertTrue(subject.wasNull());
}
 
Example #17
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetObjectLabelMap() throws SQLException {
  Map<String, Class<?>> map = new HashMap<>();
  assertNotNull(subject.getObject(DATE_COL_NOT_NULL, map));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10), subject.getObject(DATE_COL_NOT_NULL, map));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getObject(DATE_COL_NULL, map));
  assertTrue(subject.wasNull());
}
 
Example #18
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetObjectIndex() throws SQLException {
  assertNotNull(subject.getObject(DATE_COLINDEX_NOTNULL));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10), subject.getObject(DATE_COLINDEX_NOTNULL));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getObject(DATE_COLINDEX_NULL));
  assertTrue(subject.wasNull());
}
 
Example #19
Source File: MutationKeyEncoder.java    From beam with Apache License 2.0 5 votes vote down vote up
private void encodeKey(OrderedCode orderedCode, String tableName, Key key) {
  List<SpannerSchema.KeyPart> parts = schema.getKeyParts(tableName);
  Iterator<Object> it = key.getParts().iterator();
  for (SpannerSchema.KeyPart part : parts) {
    Object value = it.next();
    if (value == null) {
      if (part.isDesc()) {
        orderedCode.writeInfinityDecreasing();
      } else {
        orderedCode.writeInfinity();
      }
    } else {
      if (value instanceof Boolean) {
        writeNumber(orderedCode, part, (long) ((Boolean) value ? 0 : 1));
      } else if (value instanceof Long) {
        writeNumber(orderedCode, part, (long) value);
      } else if (value instanceof Double) {
        writeNumber(orderedCode, part, Double.doubleToLongBits((double) value));
      } else if (value instanceof String) {
        writeString(orderedCode, part, (String) value);
      } else if (value instanceof ByteArray) {
        writeBytes(orderedCode, part, (ByteArray) value);
      } else if (value instanceof Timestamp) {
        writeTimestamp(orderedCode, part, (Timestamp) value);
      } else if (value instanceof Date) {
        writeNumber(orderedCode, part, encodeDate((Date) value));
      } else {
        throw new IllegalArgumentException("Unknown key part " + value);
      }
    }
  }
}
 
Example #20
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetDateLabel() throws SQLException {
  assertNotNull(subject.getDate(DATE_COL_NOT_NULL));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10), subject.getDate(DATE_COL_NOT_NULL));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getDate(DATE_COL_NULL));
  assertTrue(subject.wasNull());
}
 
Example #21
Source File: ClientLibraryOperations.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Statement buildSingleInsert() {
  Statement statement =
      Statement.newBuilder(AIRPORT_INSERT_TEMPLATE)
          .bind("id").to(UUID.randomUUID().toString())
          .bind("address").to("100 Main Street")
          .bind("country").to("United States")
          .bind("date_built").to(Date.parseDate("2000-04-14"))
          .bind("name").to("Foobar Airport")
          .bind("plane_capacity").to((int) (1000 * Math.random()))
          .build();

  return statement;
}
 
Example #22
Source File: SpannerConverters.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
/**
 * Helper to parse array types. Arrays are converted to JSON representation. Array inner types use
 * the same serialization algorithm as in {@link this#getColumnParser(Code)}, for example [test,
 * foo] is transformed to [""test"", ""foo""]
 */
private static String parseArrayValue(Struct currentRow, String columnName) {
  Code code = currentRow.getColumnType(columnName).getArrayElementType().getCode();
  switch (code) {
    case BOOL:
      return GSON.toJson(currentRow.getBooleanArray(columnName));
    case INT64:
      return GSON.toJson(currentRow.getLongArray(columnName));
    case FLOAT64:
      return GSON.toJson(currentRow.getDoubleArray(columnName));
    case STRING:
      return GSON.toJson(currentRow.getStringList(columnName));
    case BYTES:
      return GSON.toJson(
          currentRow
              .getBytesList(columnName)
              .stream()
              .map(byteArray -> Base64.getEncoder().encodeToString(byteArray.toByteArray()))
              .collect(Collectors.toList()));
    case DATE:
      return GSON.toJson(
          currentRow
              .getDateList(columnName)
              .stream()
              .map(Date::toString)
              .collect(Collectors.toList()));
    case TIMESTAMP:
      return GSON.toJson(
          currentRow
              .getTimestampList(columnName)
              .stream()
              .map(Timestamp::toString)
              .collect(Collectors.toList()));
    default:
      throw new RuntimeException("Unsupported type: " + code);
  }
}
 
Example #23
Source File: SpannerConverterTest.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
@Test
public void testDate() {
  assertEquals(
      "\"2018-03-26\"",
      structCsvPrinter.print(
          Struct.newBuilder()
              .set("col").to(Value.date(Date.fromYearMonthDay(2018, 3, 26)))
              .build()));
}
 
Example #24
Source File: SpannerConverterTest.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
@Test
public void testDateArray() {
  assertEquals(
      "\"[\"\"2018-03-26\"\"]\"",
      structCsvPrinter.print(
          Struct.newBuilder()
              .set("col")
              .to(
                  Value.dateArray(Collections.singletonList(Date.fromYearMonthDay(2018, 3, 26))))
              .build()));
}
 
Example #25
Source File: SpannerRecordConverterTest.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
@Test
public void nulls() {
  Ddl ddl = Ddl.builder()
      .createTable("users")
      .column("id").int64().notNull().endColumn()
      .column("age").int64().endColumn()
      .column("name").string().max().endColumn()
      .column("bytes").bytes().max().endColumn()
      .column("date").date().endColumn()
      .column("ts").timestamp().endColumn()
      .primaryKey().asc("id").end()
      .endTable()
      .build();
  Schema schema = converter.convert(ddl).iterator().next();
  SpannerRecordConverter recordConverter = new SpannerRecordConverter(schema);
  Struct struct = Struct.newBuilder()
      .set("id").to(1L)
      .set("age").to((Long) null)
      .set("name").to((String) null)
      .set("bytes").to((ByteArray) null)
      .set("date").to((Date) null)
      .set("ts").to((Timestamp) null)
      .build();

  GenericRecord avroRecord = recordConverter.convert(struct);

  assertThat(avroRecord.get("id"), equalTo(1L));
  assertThat(avroRecord.get("age"), is((Long) null));
  assertThat(avroRecord.get("name"), is((String) null));
  assertThat(avroRecord.get("bytes"), is((ByteArray) null));
  assertThat(avroRecord.get("date"), is((String) null));
  assertThat(avroRecord.get("ts"), is((String) null));
}
 
Example #26
Source File: SpannerRecordConverterTest.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
@Test
public void arrays() {
  Ddl ddl = Ddl.builder()
      .createTable("users")
      .column("id").int64().notNull().endColumn()
      .column("ints").type(Type.array(Type.int64())).endColumn()
      .column("strings").type(Type.array(Type.string())).max().endColumn()
      .column("ts").type(Type.array(Type.timestamp())).endColumn()
      .column("date").type(Type.array(Type.date())).endColumn()
      .primaryKey().asc("id").end()
      .endTable()
      .build();
  Schema schema = converter.convert(ddl).iterator().next();
  SpannerRecordConverter recordConverter = new SpannerRecordConverter(schema);
  Struct struct = Struct.newBuilder()
      .set("id").to(1L)
      .set("ints").toInt64Array(Lists.newArrayList(1L, null, 2L))
      .set("strings").toStringArray(Lists.newArrayList(null, null, "one"))
      .set("ts").toTimestampArray(Lists.newArrayList(null, null,
          Timestamp.ofTimeMicroseconds(10L)))
      .set("date").toDateArray(Lists.newArrayList(null, null,
          Date.fromYearMonthDay(2018, 2, 2)))
      .build();

  GenericRecord avroRecord = recordConverter.convert(struct);

  assertThat(avroRecord.get("id"), equalTo(1L));
  assertThat(avroRecord.get("ints"), equalTo(Arrays.asList(1L, null, 2L)));
  assertThat(avroRecord.get("strings"), equalTo(Arrays.asList(null, null, "one")));
  assertThat(avroRecord.get("date"), equalTo(Arrays.asList(null, null, "2018-02-02")));
  assertThat(avroRecord.get("ts"),
      equalTo(Arrays.asList(null, null, "1970-01-01T00:00:00.000010000Z")));
}
 
Example #27
Source File: CloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testGetDateIndex() throws SQLException {
  assertNotNull(subject.getDate(DATE_COLINDEX_NOTNULL));
  assertEquals(new java.sql.Date(2017 - 1900, 8, 10), subject.getDate(DATE_COLINDEX_NOTNULL));
  assertEquals(false, subject.wasNull());
  assertNull(subject.getDate(DATE_COLINDEX_NULL));
  assertTrue(subject.wasNull());
}
 
Example #28
Source File: ClientLibraryOperations.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Mutation buildSingleMutationInsert() {
  Mutation mutation = Mutation.newInsertBuilder(AIRPORT_TABLE)
      .set("id").to(UUID.randomUUID().toString())
      .set("address").to("100 Main Street")
      .set("country").to("United States")
      .set("date_built").to(Date.parseDate("2000-04-14"))
      .set("name").to("Foobar Airport")
      .set("plane_capacity").to((int) (1000 * Math.random()))
      .build();
  return mutation;
}
 
Example #29
Source File: TextRowToMutationTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
@Test
public void parseRowToMutation() {
  PCollectionView<Ddl> ddlView =
      pipeline.apply("ddl", Create.of(getTestDdl())).apply(View.asSingleton());
  PCollectionView<Map<String, List<TableManifest.Column>>> tableColumnsMapView =
      pipeline
          .apply(
              "tableColumnsMap",
              Create.<Map<String, List<TableManifest.Column>>>of(getEmptyTableColumnsMap())
                  .withCoder(
                      MapCoder.of(
                          StringUtf8Coder.of(),
                          ListCoder.of(ProtoCoder.of(TableManifest.Column.class)))))
          .apply("Map as view", View.asSingleton());

  PCollection<KV<String, String>> input =
      pipeline.apply(
          "input",
          Create.of(
              KV.of(
                  testTableName,
                  "123,a string,`another"
                      + " string`,1.23,True,2019-01-01,2018-12-31T23:59:59Z,1567637083,aGk=,")));
  PCollection<Mutation> mutations =
      input.apply(
          ParDo.of(
                  new TextRowToMutation(
                      ddlView,
                      tableColumnsMapView,
                      columnDelimiter,
                      StaticValueProvider.of('`'),
                      StaticValueProvider.of(true),
                      escape,
                      nullString,
                      dateFormat,
                      timestampFormat))
              .withSideInputs(ddlView, tableColumnsMapView));

  PAssert.that(mutations)
      .containsInAnyOrder(
          Mutation.newInsertOrUpdateBuilder(testTableName)
              .set("int_col")
              .to(123)
              .set("str_10_col")
              .to("a string")
              .set("str_max_col")
              .to("another string")
              .set("float_col")
              .to(1.23)
              .set("bool_col")
              .to(true)
              .set("date_col")
              .to(Value.date(Date.parseDate("2019-01-01")))
              .set("timestamp_col")
              .to(Value.timestamp(Timestamp.parseTimestamp("2018-12-31T23:59:59Z")))
              .set("timestamp_col_epoch")
              .to(Value.timestamp(Timestamp.ofTimeMicroseconds(1567637083)))
              .set("byte_col")
              .to(Value.bytes(ByteArray.fromBase64("aGk=")))
              .build());

  pipeline.run();
}
 
Example #30
Source File: RandomInsertMutationGenerator.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
public Mutation generateMutation(Map<String, Value> overrides) {
  Mutation.WriteBuilder builder = Mutation.newInsertOrUpdateBuilder(randomCase(table.name()));
  for (Map.Entry<String, Iterator<Value>> values : valueGenerators.entrySet()) {
    String columnName = values.getKey();
    Value value = overrides.get(columnName);
    if (value == null) {
      value = values.getValue().next();
    }
    switch (value.getType().getCode()) {
      case BOOL:
        Boolean bool = value.isNull() ? null : value.getBool();
        builder.set(columnName).to(bool);
        break;
      case INT64:
        Long l = value.isNull() ? null : value.getInt64();
        builder.set(columnName).to(l);
        break;
      case FLOAT64:
        Double f = value.isNull() ? null : value.getFloat64();
        builder.set(columnName).to(f);
        break;
      case BYTES:
        ByteArray bytes = value.isNull() ? null : value.getBytes();
        builder.set(columnName).to(bytes);
        break;
      case STRING:
        String string = value.isNull() ? null : value.getString();
        builder.set(columnName).to(string);
        break;
      case TIMESTAMP:
        Timestamp timestamp = value.isNull() ? null : value.getTimestamp();
        builder.set(columnName).to(timestamp);
        break;
      case DATE:
        Date date = value.isNull() ? null : value.getDate();
        builder.set(columnName).to(date);
        break;
      case ARRAY:
        switch (value.getType().getArrayElementType().getCode()) {
          case BOOL:
            List<Boolean> bools = value.isNull() ? null : value.getBoolArray();
            builder.set(columnName).toBoolArray(bools);
            break;
          case INT64:
            List<Long> longs = value.isNull() ? null : value.getInt64Array();
            builder.set(columnName).toInt64Array(longs);
            break;
          case FLOAT64:
            List<Double> doubles = value.isNull() ? null : value.getFloat64Array();
            builder.set(columnName).toFloat64Array(doubles);
            break;
          case BYTES:
            List<ByteArray> bytesArray = value.isNull() ? null : value.getBytesArray();
            builder.set(columnName).toBytesArray(bytesArray);
            break;
          case STRING:
            List<String> strings = value.isNull() ? null : value.getStringArray();
            builder.set(columnName).toStringArray(strings);
            break;
          case TIMESTAMP:
            List<Timestamp> timestamps = value.isNull() ? null : value.getTimestampArray();
            builder.set(columnName).toTimestampArray(timestamps);
            break;
          case DATE:
            List<Date> dates = value.isNull() ? null : value.getDateArray();
            builder.set(columnName).toDateArray(dates);
            break;
        }
        break;
      default:
        throw new IllegalArgumentException("Unknown toValue " + value);
    }
  }
  return builder.build();
}