com.google.cloud.spanner.Type Java Examples

The following examples show how to use com.google.cloud.spanner.Type. 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: CloudSpannerResultSet.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private Object getObject(Type type, int columnIndex) throws SQLException {
  if (type == Type.bool())
    return getBoolean(columnIndex);
  if (type == Type.bytes())
    return getBytes(columnIndex);
  if (type == Type.date())
    return getDate(columnIndex);
  if (type == Type.float64())
    return getDouble(columnIndex);
  if (type == Type.int64())
    return getLong(columnIndex);
  if (type == Type.string())
    return getString(columnIndex);
  if (type == Type.timestamp())
    return getTimestamp(columnIndex);
  if (type.getCode() == Code.ARRAY)
    return getArray(columnIndex);
  throw new CloudSpannerSQLException("Unknown type: " + type.toString(),
      com.google.rpc.Code.INVALID_ARGUMENT);
}
 
Example #2
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 #3
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 #4
Source File: CloudSpannerResultSetMetaDataTest.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private int getSqlType(Type type) {
  if (type == Type.bool())
    return Types.BOOLEAN;
  if (type == Type.bytes())
    return Types.BINARY;
  if (type == Type.date())
    return Types.DATE;
  if (type == Type.float64())
    return Types.DOUBLE;
  if (type == Type.int64())
    return Types.BIGINT;
  if (type == Type.string())
    return Types.NVARCHAR;
  if (type == Type.timestamp())
    return Types.TIMESTAMP;
  if (type.getCode() == Code.ARRAY)
    return Types.ARRAY;
  return Types.OTHER;
}
 
Example #5
Source File: CloudSpannerResultSetMetaDataTest.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private int getDefaultDisplaySize(Type type, int column) throws SQLException {
  if (type.getCode() == Code.ARRAY)
    return 50;
  if (type == Type.bool())
    return 5;
  if (type == Type.bytes())
    return 50;
  if (type == Type.date())
    return 10;
  if (type == Type.float64())
    return 14;
  if (type == Type.int64())
    return 10;
  if (type == Type.string()) {
    int length = subject.getPrecision(column);
    return length == 0 ? 50 : length;
  }
  if (type == Type.timestamp())
    return 16;
  return 10;
}
 
Example #6
Source File: ReadSpannerSchemaTest.java    From beam with Apache License 2.0 6 votes vote down vote up
private void preparePkMetadata(ReadOnlyTransaction tx, List<Struct> rows) {
  Type type =
      Type.struct(
          Type.StructField.of("table_name", Type.string()),
          Type.StructField.of("column_name", Type.string()),
          Type.StructField.of("column_ordering", Type.string()));
  when(tx.executeQuery(
          argThat(
              new ArgumentMatcher<Statement>() {

                @Override
                public boolean matches(Statement argument) {
                  if (!(argument instanceof Statement)) {
                    return false;
                  }
                  Statement st = (Statement) argument;
                  return st.getSql().contains("information_schema.index_columns");
                }
              })))
      .thenReturn(ResultSets.forRows(type, rows));
}
 
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: AbstractCloudSpannerWrapper.java    From spanner-jdbc with MIT License 6 votes vote down vote up
public static String getGoogleTypeName(int sqlType) {
  if (sqlType == Types.BOOLEAN)
    return Type.bool().getCode().name();
  if (sqlType == Types.BINARY)
    return Type.bytes().getCode().name();
  if (sqlType == Types.DATE)
    return Type.date().getCode().name();
  if (sqlType == Types.DOUBLE || sqlType == Types.FLOAT || sqlType == Types.DECIMAL)
    return Type.float64().getCode().name();
  if (sqlType == Types.BIGINT || sqlType == Types.INTEGER || sqlType == Types.TINYINT)
    return Type.int64().getCode().name();
  if (sqlType == Types.NVARCHAR)
    return Type.string().getCode().name();
  if (sqlType == Types.TIMESTAMP)
    return Type.timestamp().getCode().name();
  if (sqlType == Types.ARRAY)
    return Code.ARRAY.name();

  return "Other";
}
 
Example #9
Source File: AbstractCloudSpannerWrapper.java    From spanner-jdbc with MIT License 6 votes vote down vote up
public static int extractColumnType(Type type) {
  if (type.equals(Type.bool()))
    return Types.BOOLEAN;
  if (type.equals(Type.bytes()))
    return Types.BINARY;
  if (type.equals(Type.date()))
    return Types.DATE;
  if (type.equals(Type.float64()))
    return Types.DOUBLE;
  if (type.equals(Type.int64()))
    return Types.BIGINT;
  if (type.equals(Type.string()))
    return Types.NVARCHAR;
  if (type.equals(Type.timestamp()))
    return Types.TIMESTAMP;
  if (type.getCode() == Code.ARRAY)
    return Types.ARRAY;
  return Types.OTHER;
}
 
Example #10
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 #11
Source File: ReadSpannerSchemaTest.java    From beam with Apache License 2.0 6 votes vote down vote up
private void prepareColumnMetadata(ReadOnlyTransaction tx, List<Struct> rows) {
  Type type =
      Type.struct(
          Type.StructField.of("table_name", Type.string()),
          Type.StructField.of("column_name", Type.string()),
          Type.StructField.of("spanner_type", Type.string()),
          Type.StructField.of("cells_mutated", Type.int64()));
  when(tx.executeQuery(
          argThat(
              new ArgumentMatcher<Statement>() {

                @Override
                public boolean matches(Statement argument) {
                  if (!(argument instanceof Statement)) {
                    return false;
                  }
                  Statement st = (Statement) argument;
                  return st.getSql().contains("information_schema.columns");
                }
              })))
      .thenReturn(ResultSets.forRows(type, rows));
}
 
Example #12
Source File: CloudSpannerConversionUtilTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private void testInvalidValue(Object value, Type fromType, Class<?> toType)
    throws CloudSpannerSQLException {
  try {
    CloudSpannerConversionUtil.convert(value, fromType, toType);
  } catch (CloudSpannerSQLException e) {
    if (e.getMessage().equals("Cannot convert " + value.toString() + " to " + toType.getName()))
      return;
    throw e;
  }
  throw new AssertionError("Expected exception not thrown");
}
 
Example #13
Source File: CloudSpannerResultSetMetaDataTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testIsSigned() throws SQLException {
  for (int i = 1; i <= TEST_COLUMNS.size(); i++) {
    Type type = TEST_COLUMNS.get(i - 1).type;
    if (type == Type.int64() || type == Type.float64()) {
      assertTrue(subject.isSigned(i));
    } else {
      assertFalse(subject.isSigned(i));
    }
  }
}
 
Example #14
Source File: CloudSpannerConversionUtilTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private void testInvalidType(Type fromType, Class<?> toType) throws CloudSpannerSQLException {
  try {
    CloudSpannerConversionUtil.convert(new Object(), fromType, toType);
  } catch (CloudSpannerSQLException e) {
    if (e.getMessage()
        .equals("Cannot convert " + fromType.getCode().name() + " to " + toType.getName()))
      return;
    throw e;
  }
  throw new AssertionError("Expected exception not thrown");
}
 
Example #15
Source File: CloudSpannerResultSetMetaDataTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private int getPrecision(TestColumn col) {
  if (col.type == Type.bool())
    return 1;
  if (col.type == Type.date())
    return 10;
  if (col.type == Type.float64())
    return 14;
  if (col.type == Type.int64())
    return 10;
  if (col.type == Type.timestamp())
    return 24;
  if (col.isTableColumn())
    return col.size;
  return 0;
}
 
Example #16
Source File: CloudSpannerConversionUtilTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testConvertInvalidType() throws SQLException {
  testInvalidType(Type.date(), Boolean.class);
  testInvalidType(Type.timestamp(), Boolean.class);
  testInvalidType(Type.int64(), Timestamp.class);
  testInvalidType(Type.int64(), Date.class);
  testInvalidType(Type.float64(), Timestamp.class);
  testInvalidType(Type.float64(), Date.class);
  testInvalidType(Type.timestamp(), Date.class);
}
 
Example #17
Source File: CloudSpannerResultSetMetaDataTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private String getTypeClassName(Type type) {
  if (type == Type.bool())
    return Boolean.class.getName();
  if (type == Type.bytes())
    return Byte[].class.getName();
  if (type == Type.date())
    return Date.class.getName();
  if (type == Type.float64())
    return Double.class.getName();
  if (type == Type.int64())
    return Long.class.getName();
  if (type == Type.string())
    return String.class.getName();
  if (type == Type.timestamp())
    return Timestamp.class.getName();
  if (type.getCode() == Code.ARRAY) {
    if (type.getArrayElementType() == Type.bool())
      return Boolean[].class.getName();
    if (type.getArrayElementType() == Type.bytes())
      return Byte[][].class.getName();
    if (type.getArrayElementType() == Type.date())
      return Date[].class.getName();
    if (type.getArrayElementType() == Type.float64())
      return Double[].class.getName();
    if (type.getArrayElementType() == Type.int64())
      return Long[].class.getName();
    if (type.getArrayElementType() == Type.string())
      return String[].class.getName();
    if (type.getArrayElementType() == Type.timestamp())
      return Timestamp[].class.getName();
  }
  return null;
}
 
Example #18
Source File: CloudSpannerResultSetMetaDataTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testIsCaseSensitive() throws SQLException {
  for (int i = 1; i <= TEST_COLUMNS.size(); i++) {
    Type type = TEST_COLUMNS.get(i - 1).type;
    assertEquals(type == Type.string() || type == Type.bytes(), subject.isCaseSensitive(i));
  }
}
 
Example #19
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void ensureConstructorArgsAreReadOnce() {
	Struct row = mock(Struct.class);
	when(row.getString("id")).thenReturn("1234");
	when(row.getType()).thenReturn(
			Type.struct(Arrays.asList(Type.StructField.of("id", Type.string()))));
	when(row.getColumnType("id")).thenReturn(Type.string());

	TestEntities.SimpleConstructorTester result = this.spannerEntityReader
			.read(TestEntities.SimpleConstructorTester.class, row);

	assertThat(result.id).isEqualTo("1234");
	verify(row, times(1)).getString("id");
}
 
Example #20
Source File: CloudSpannerStatement.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Override
public ResultSet getGeneratedKeys() throws SQLException {
  com.google.cloud.spanner.ResultSet rs =
      ResultSets.forRows(Type.struct(StructField.of("COLUMN_NAME", Type.string()),
          StructField.of("VALUE", Type.int64())), Collections.emptyList());
  return new CloudSpannerResultSet(this, rs, null);
}
 
Example #21
Source File: AbstractCloudSpannerWrapper.java    From spanner-jdbc with MIT License 5 votes vote down vote up
public static String getClassName(Type type) {
  if (type == Type.bool())
    return Boolean.class.getName();
  if (type == Type.bytes())
    return Byte[].class.getName();
  if (type == Type.date())
    return Date.class.getName();
  if (type == Type.float64())
    return Double.class.getName();
  if (type == Type.int64())
    return Long.class.getName();
  if (type == Type.string())
    return String.class.getName();
  if (type == Type.timestamp())
    return Timestamp.class.getName();
  if (type.getCode() == Code.ARRAY) {
    if (type.getArrayElementType() == Type.bool())
      return Boolean[].class.getName();
    if (type.getArrayElementType() == Type.bytes())
      return Byte[][].class.getName();
    if (type.getArrayElementType() == Type.date())
      return Date[].class.getName();
    if (type.getArrayElementType() == Type.float64())
      return Double[].class.getName();
    if (type.getArrayElementType() == Type.int64())
      return Long[].class.getName();
    if (type.getArrayElementType() == Type.string())
      return String[].class.getName();
    if (type.getArrayElementType() == Type.timestamp())
      return Timestamp[].class.getName();
  }
  return null;
}
 
Example #22
Source File: SpannerSchemaUtils.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private String getTypeDdlString(Type.Code type, boolean isArray,
		OptionalLong dataLength, boolean isNotNull, boolean isCommitTimestamp) {
	return (isCommitTimestamp ? Type.Code.TIMESTAMP.toString()
			: getTypeDdlStringWithLength(type, isArray, dataLength))
			+ (isNotNull ? " NOT NULL" : "")
			+ (isCommitTimestamp ? " OPTIONS (allow_commit_timestamp=true)" : "");
}
 
Example #23
Source File: SpannerSchemaUtils.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private String getTypeDdlStringWithLength(Type.Code type, boolean isArray,
		OptionalLong dataLength) {
	Assert.notNull(type, "A valid Spanner column type is required.");
	if (isArray) {
		return "ARRAY<" + getTypeDdlStringWithLength(type, false, dataLength) + ">";
	}
	return type.toString() + ((type == Type.Code.STRING || type == Type.Code.BYTES)
			? "(" + (dataLength.isPresent() ? dataLength.getAsLong() : "MAX") + ")"
			: "");
}
 
Example #24
Source File: StructAccessor.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
Object getSingleValue(String colName) {
	Type colType = this.struct.getColumnType(colName);
	Class sourceType = getSingleItemTypeCode(colType);
	BiFunction readFunction = singleItemReadMethodMapping.get(sourceType);
	if (readFunction == null) {
		// This case should only occur if the POJO field is non-Iterable, but the column type
		// is ARRAY of STRUCT, TIMESTAMP, DATE, BYTES, or STRING. This use-case is not supported.
		return null;
	}
	return readFunction.apply(this.struct, colName);
}
 
Example #25
Source File: CloudSpannerResultSet.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private Object convertObject(Object o, Map<String, Class<?>> map, Type type) throws SQLException {
  if (map == null)
    throw new CloudSpannerSQLException("Map may not be null",
        com.google.rpc.Code.INVALID_ARGUMENT);
  if (o == null)
    return null;
  Class<?> javaType = map.get(type.getCode().name());
  if (javaType == null)
    return o;
  return CloudSpannerConversionUtil.convert(o, type, javaType);
}
 
Example #26
Source File: StructAccessor.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
public Object getSingleValue(int colIndex) {
	Type colType = this.struct.getColumnType(colIndex);
	Class sourceType = getSingleItemTypeCode(colType);
	BiFunction readFunction = singleItemReadMethodMappingIntCol.get(sourceType);
	if (readFunction == null) {
		// This case should only occur if the POJO field is non-Iterable, but the
		// column type
		// is ARRAY of STRUCT, TIMESTAMP, DATE, BYTES, or STRING. This use-case is not
		// supported.
		return null;
	}
	return readFunction.apply(this.struct, colIndex);
}
 
Example #27
Source File: StructAccessor.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
List getListValue(String colName) {
	if (this.struct.getColumnType(colName).getCode() != Code.ARRAY) {
		throw new SpannerDataException("Column is not an ARRAY type: " + colName);
	}
	Type.Code innerTypeCode = this.struct.getColumnType(colName).getArrayElementType().getCode();
	Class clazz = SpannerTypeMapper.getSimpleJavaClassFor(innerTypeCode);
	BiFunction<Struct, String, List> readMethod = readIterableMapping.get(clazz);
	return readMethod.apply(this.struct, colName);
}
 
Example #28
Source File: CloudSpannerResultSet.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Override
public Array getArray(int columnIndex) throws SQLException {
  if (isNull(columnIndex))
    return null;
  Type type = resultSet.getColumnType(columnIndex - 1);
  if (type.getCode() != Code.ARRAY)
    throw new CloudSpannerSQLException(
        "Column with index " + columnIndex + " does not contain an array",
        com.google.rpc.Code.INVALID_ARGUMENT);
  CloudSpannerDataType dataType =
      CloudSpannerDataType.getType(type.getArrayElementType().getCode());
  List<? extends Object> elements = dataType.getArrayElements(resultSet, columnIndex - 1);

  return CloudSpannerArray.createArray(dataType, elements);
}
 
Example #29
Source File: CloudSpannerResultSet.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Override
public Array getArray(String columnLabel) throws SQLException {
  Type type = resultSet.getColumnType(columnLabel);
  if (type.getCode() != Code.ARRAY)
    throw new CloudSpannerSQLException(
        "Column with label " + columnLabel + " does not contain an array",
        com.google.rpc.Code.INVALID_ARGUMENT);
  return getArray(resultSet.getColumnIndex(columnLabel) + 1);
}
 
Example #30
Source File: CloudSpannerConnection.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private ResultSet createResultSet(CloudSpannerStatement statement, Map<String, String> values)
    throws SQLException {
  List<Struct> rows = new ArrayList<>(values.size());
  for (Entry<String, String> entry : values.entrySet()) {
    rows.add(Struct.newBuilder().set("NAME").to(Value.string(entry.getKey())).set("VALUE")
        .to(Value.string(entry.getValue())).build());
  }
  com.google.cloud.spanner.ResultSet rs = ResultSets.forRows(
      Type.struct(StructField.of("NAME", Type.string()), StructField.of("VALUE", Type.string())),
      rows);
  return new CloudSpannerResultSet(statement, rs, null);
}