Search in sources :

Example 6 with Key

use of com.google.cloud.spanner.Key in project spring-cloud-gcp by spring-cloud.

the class SpannerKeyIdConverter method toRequestId.

@Override
public String toRequestId(Serializable source, Class<?> entityType) {
    Key id = (Key) source;
    StringJoiner stringJoiner = new StringJoiner(getUrlIdSeparator());
    id.getParts().forEach((p) -> stringJoiner.add(p.toString()));
    return stringJoiner.toString();
}
Also used : Key(com.google.cloud.spanner.Key) StringJoiner(java.util.StringJoiner)

Example 7 with Key

use of com.google.cloud.spanner.Key in project spring-cloud-gcp by spring-cloud.

the class SpannerStatementQueryExecutor method buildQuery.

/**
 * Builds a query that returns the rows associated with a key set with additional SQL-where.
 * The {@link org.springframework.cloud.gcp.data.spanner.core.mapping.Where} of the {@code persistentEntity} parameter
 * is ignored, you should pass the SQL-where as a {@code whereClause} parameter.
 * The secondary {@code index} will be used instead of the table name when the corresponding parameter is not null.
 * @param keySet the key set whose members to get.
 * @param persistentEntity the persistent entity of the table.
 * @param <T> the type of the persistent entity
 * @param writeConverter a converter to convert key values as needed to bind to the query statement.
 * @param mappingContext mapping context
 * @param whereClause SQL where clause
 * @param index the secondary index name
 * @return the Spanner statement to perform the retrieval.
 */
public static <T> Statement buildQuery(KeySet keySet, SpannerPersistentEntity<T> persistentEntity, SpannerCustomConverter writeConverter, SpannerMappingContext mappingContext, String whereClause, String index) {
    List<String> orParts = new ArrayList<>();
    List<String> tags = new ArrayList<>();
    List keyParts = new ArrayList();
    int tagNum = 0;
    List<SpannerPersistentProperty> keyProperties = persistentEntity.getFlattenedPrimaryKeyProperties();
    for (Key key : keySet.getKeys()) {
        StringJoiner andJoiner = new StringJoiner(" AND ");
        Iterator parentKeyParts = key.getParts().iterator();
        while (parentKeyParts.hasNext()) {
            SpannerPersistentProperty keyProp = keyProperties.get(tagNum % keyProperties.size());
            String tagName = "tag" + tagNum;
            andJoiner.add(keyProp.getColumnName() + " = @" + tagName);
            tags.add(tagName);
            keyParts.add(parentKeyParts.next());
            tagNum++;
        }
        orParts.add(andJoiner.toString());
    }
    String keyClause = orParts.stream().map(s -> "(" + s + ")").collect(Collectors.joining(" OR "));
    String condition = combineWithAnd(keyClause, whereClause);
    String sb = "SELECT " + getColumnsStringForSelect(persistentEntity, mappingContext, true) + " FROM " + (StringUtils.isEmpty(index) ? persistentEntity.tableName() : String.format("%s@{FORCE_INDEX=%s}", persistentEntity.tableName(), index)) + (condition.isEmpty() ? "" : " WHERE " + condition);
    return buildStatementFromSqlWithArgs(sb, tags, null, writeConverter, keyParts.toArray(), null);
}
Also used : IgnoreCaseType(org.springframework.data.repository.query.parser.Part.IgnoreCaseType) BiFunction(java.util.function.BiFunction) SpannerDataException(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException) HashMap(java.util.HashMap) Function(java.util.function.Function) ConversionUtils(org.springframework.cloud.gcp.data.spanner.core.convert.ConversionUtils) ArrayList(java.util.ArrayList) Parameter(java.lang.reflect.Parameter) Map(java.util.Map) Key(com.google.cloud.spanner.Key) StreamSupport(java.util.stream.StreamSupport) SpannerTemplate(org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) SpannerPersistentEntity(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentEntity) SpannerMappingContext(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerMappingContext) SpannerPageableQueryOptions(org.springframework.cloud.gcp.data.spanner.core.SpannerPageableQueryOptions) Iterator(java.util.Iterator) PartTree(org.springframework.data.repository.query.parser.PartTree) ParameterAccessor(org.springframework.data.repository.query.ParameterAccessor) Collectors(java.util.stream.Collectors) KeySet(com.google.cloud.spanner.KeySet) Statement(com.google.cloud.spanner.Statement) List(java.util.List) SpannerPersistentProperty(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentProperty) Where(org.springframework.cloud.gcp.data.spanner.core.mapping.Where) ParameterizedType(java.lang.reflect.ParameterizedType) Struct(com.google.cloud.spanner.Struct) StringJoiner(java.util.StringJoiner) ValueBinder(com.google.cloud.spanner.ValueBinder) ConverterAwareMappingSpannerEntityWriter(org.springframework.cloud.gcp.data.spanner.core.convert.ConverterAwareMappingSpannerEntityWriter) SpannerCustomConverter(org.springframework.cloud.gcp.data.spanner.core.convert.SpannerCustomConverter) StringUtils(org.springframework.util.StringUtils) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) Key(com.google.cloud.spanner.Key) StringJoiner(java.util.StringJoiner) SpannerPersistentProperty(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentProperty)

Example 8 with Key

use of com.google.cloud.spanner.Key in project spring-cloud-gcp by spring-cloud.

the class SpannerPersistentEntityImpl method getPropertyAccessor.

@Override
public <B> PersistentPropertyAccessor<B> getPropertyAccessor(B object) {
    PersistentPropertyAccessor<B> delegatedAccessor = super.getPropertyAccessor(object);
    return new PersistentPropertyAccessor<B>() {

        @Override
        public void setProperty(PersistentProperty<?> property, @Nullable Object value) {
            if (property.isIdProperty()) {
                SpannerPersistentEntity<?> owner = (SpannerPersistentEntity<?>) property.getOwner();
                SpannerPersistentProperty[] primaryKeyProperties = owner.getPrimaryKeyProperties();
                Iterator<Object> partsIterator;
                if (value instanceof Key) {
                    Key keyValue = (Key) value;
                    if (keyValue.size() != primaryKeyProperties.length) {
                        throwWrongNumOfPartsException();
                    }
                    partsIterator = keyValue.getParts().iterator();
                } else {
                    if (primaryKeyProperties.length > 1) {
                        throwWrongNumOfPartsException();
                    }
                    partsIterator = Collections.singleton(value).iterator();
                }
                for (int i = 0; i < primaryKeyProperties.length; i++) {
                    SpannerPersistentProperty prop = primaryKeyProperties[i];
                    delegatedAccessor.setProperty(prop, SpannerPersistentEntityImpl.this.spannerEntityProcessor.getReadConverter().convert(partsIterator.next(), prop.getType()));
                }
            } else {
                delegatedAccessor.setProperty(property, value);
            }
        }

        private void throwWrongNumOfPartsException() {
            throw new SpannerDataException("The number of key parts is not equal to the number of primary key properties");
        }

        @Nullable
        @Override
        public Object getProperty(PersistentProperty<?> property) {
            if (property.isIdProperty()) {
                return ((SpannerCompositeKeyProperty) property).getId(getBean());
            } else {
                return delegatedAccessor.getProperty(property);
            }
        }

        @Override
        public B getBean() {
            return delegatedAccessor.getBean();
        }
    };
}
Also used : PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) PersistentProperty(org.springframework.data.mapping.PersistentProperty) Nullable(org.springframework.lang.Nullable) Key(com.google.cloud.spanner.Key)

Example 9 with Key

use of com.google.cloud.spanner.Key in project spring-cloud-gcp by spring-cloud.

the class SpannerMutationFactoryImpl method delete.

@Override
public <T> Mutation delete(Class<T> entityClass, Iterable<? extends T> entities) {
    SpannerPersistentEntity<?> persistentEntity = this.spannerMappingContext.getPersistentEntity(entityClass);
    KeySet.Builder builder = KeySet.newBuilder();
    for (T entity : entities) {
        PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(entity);
        PersistentProperty idProperty = persistentEntity.getIdProperty();
        Key value = (Key) accessor.getProperty(idProperty);
        builder.addKey(value);
    }
    return delete(entityClass, builder.build());
}
Also used : KeySet(com.google.cloud.spanner.KeySet) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) PersistentProperty(org.springframework.data.mapping.PersistentProperty) Key(com.google.cloud.spanner.Key)

Example 10 with Key

use of com.google.cloud.spanner.Key in project spring-cloud-gcp by spring-cloud.

the class ConverterAwareMappingSpannerEntityWriter method convertToKey.

@Override
public Key convertToKey(Object key) {
    Assert.notNull(key, "Key of an entity to be written cannot be null!");
    Key k;
    boolean isIterable = Iterable.class.isAssignableFrom(key.getClass());
    boolean isArray = Object[].class.isAssignableFrom(key.getClass());
    if ((isIterable || isArray) && !ByteArray.class.isAssignableFrom(key.getClass())) {
        Key.Builder kb = Key.newBuilder();
        for (Object keyPart : (isArray ? (Arrays.asList((Object[]) key)) : ((Iterable) key))) {
            kb.appendObject(convertKeyPart(keyPart));
        }
        k = kb.build();
        if (k.size() == 0) {
            throw new SpannerDataException("A key must have at least one component, but 0 were given.");
        }
    } else {
        k = Key.class.isAssignableFrom(key.getClass()) ? (Key) key : Key.of(convertKeyPart(key));
    }
    return k;
}
Also used : SpannerDataException(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException) Key(com.google.cloud.spanner.Key)

Aggregations

Key (com.google.cloud.spanner.Key)26 Test (org.junit.Test)16 KeySet (com.google.cloud.spanner.KeySet)8 PrimaryKey (org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey)7 ArrayList (java.util.ArrayList)4 PersistentPropertyAccessor (org.springframework.data.mapping.PersistentPropertyAccessor)4 Mutation (com.google.cloud.spanner.Mutation)3 ResultSet (com.google.cloud.spanner.ResultSet)3 SpannerOperations (org.springframework.cloud.gcp.data.spanner.core.SpannerOperations)3 SpannerPageableQueryOptions (org.springframework.cloud.gcp.data.spanner.core.SpannerPageableQueryOptions)3 SpannerDataException (org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException)3 Sort (org.springframework.data.domain.Sort)3 PersistentProperty (org.springframework.data.mapping.PersistentProperty)3 Statement (com.google.cloud.spanner.Statement)2 Struct (com.google.cloud.spanner.Struct)2 List (java.util.List)2 StringJoiner (java.util.StringJoiner)2 Pageable (org.springframework.data.domain.Pageable)2 ApiFuture (com.google.api.core.ApiFuture)1 AsyncResultSet (com.google.cloud.spanner.AsyncResultSet)1