Search in sources :

Example 56 with StringJoiner

use of java.util.StringJoiner in project presto by prestodb.

the class TestRaptorIntegrationSmokeTest method testShardingByTemporalTimestampColumnBucketed.

@Test
public void testShardingByTemporalTimestampColumnBucketed() throws Exception {
    // Make sure we have at least 2 different orderdate.
    assertEquals(computeActual("SELECT count(DISTINCT orderdate) >= 2 FROM orders WHERE orderdate < date '1992-02-08'").getOnlyValue(), true);
    assertUpdate("" + "CREATE TABLE test_shard_temporal_timestamp_bucketed(col1 BIGINT, col2 TIMESTAMP) " + "WITH (temporal_column = 'col2', bucket_count = 3, bucketed_on = ARRAY ['col1'])");
    int rows = 100;
    StringJoiner joiner = new StringJoiner(", ", "INSERT INTO test_shard_temporal_timestamp_bucketed VALUES ", "");
    for (int i = 0; i < rows; i++) {
        joiner.add(format("(%s, TIMESTAMP '2016-08-08 01:00' + interval '%s' hour)", i, i));
    }
    assertUpdate(joiner.toString(), format("VALUES(%s)", rows));
    MaterializedResult results = computeActual("" + "SELECT format_datetime(col2, 'yyyyMMdd'), \"$shard_uuid\" " + "FROM test_shard_temporal_timestamp_bucketed");
    assertEquals(results.getRowCount(), rows);
    // Each shard will only contain data of one date.
    SetMultimap<String, String> shardDateMap = HashMultimap.create();
    for (MaterializedRow row : results.getMaterializedRows()) {
        shardDateMap.put((String) row.getField(1), (String) row.getField(0));
    }
    for (Collection<String> dates : shardDateMap.asMap().values()) {
        assertEquals(dates.size(), 1);
    }
    // Ensure one shard can contain different timestamps from the same day
    assertLessThan(shardDateMap.size(), rows);
}
Also used : MaterializedResult(com.facebook.presto.testing.MaterializedResult) StringJoiner(java.util.StringJoiner) MaterializedRow(com.facebook.presto.testing.MaterializedRow) Test(org.testng.annotations.Test) AbstractTestIntegrationSmokeTest(com.facebook.presto.tests.AbstractTestIntegrationSmokeTest)

Example 57 with StringJoiner

use of java.util.StringJoiner in project requery by requery.

the class EntityGenerator method generateImmutableTypeBuildMethod.

private void generateImmutableTypeBuildMethod(TypeSpec.Builder builder) {
    if (entity.isImmutable() && !entity.builderType().isPresent() && entity.factoryMethod().isPresent()) {
        String methodName = entity.factoryMethod().map(element -> element.getSimpleName().toString()).orElse("");
        List<String> argumentNames = entity.factoryArguments();
        StringJoiner joiner = new StringJoiner(",");
        argumentNames.forEach(name -> joiner.add("$L"));
        MethodSpec.Builder build = MethodSpec.methodBuilder("build").returns(ClassName.get(entity.element()));
        if (methodName.equals("<init>")) {
            Object[] args = new Object[1 + argumentNames.size()];
            args[0] = ClassName.get(entity.element());
            System.arraycopy(argumentNames.toArray(), 0, args, 1, argumentNames.size());
            build.addStatement("return new $T(" + joiner.toString() + ")", args).build();
        } else {
            Object[] args = new Object[2 + argumentNames.size()];
            args[0] = ClassName.get(entity.element());
            args[1] = methodName;
            System.arraycopy(argumentNames.toArray(), 0, args, 2, argumentNames.size());
            build.addStatement("return $T.$L(" + joiner.toString() + ")", args).build();
        }
        builder.addMethod(build.build());
    }
}
Also used : EntityProxy(io.requery.proxy.EntityProxy) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) Elements(javax.lang.model.util.Elements) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Map(java.util.Map) PropertyNameStyle(io.requery.PropertyNameStyle) ElementFilter(javax.lang.model.util.ElementFilter) javax.lang.model.element(javax.lang.model.element) Persistable(io.requery.Persistable) ParameterSpec(com.squareup.javapoet.ParameterSpec) Entity(io.requery.Entity) MethodSpec(com.squareup.javapoet.MethodSpec) Set(java.util.Set) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) IOException(java.io.IOException) Attribute(io.requery.meta.Attribute) PropertyState(io.requery.proxy.PropertyState) TypeSpec(com.squareup.javapoet.TypeSpec) Collectors(java.util.stream.Collectors) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) PreInsertListener(io.requery.proxy.PreInsertListener) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) StringJoiner(java.util.StringJoiner) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Annotation(java.lang.annotation.Annotation) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) MethodSpec(com.squareup.javapoet.MethodSpec) StringJoiner(java.util.StringJoiner)

Example 58 with StringJoiner

use of java.util.StringJoiner in project requery by requery.

the class EntityMetaGenerator method generateAttribute.

private FieldSpec generateAttribute(AttributeDescriptor attribute, AttributeDescriptor parent, TypeName targetName, String fieldName, TypeMirror mirror, boolean expression) {
    TypeMirror typeMirror = mirror;
    TypeName typeName;
    if (attribute.isIterable()) {
        typeMirror = tryFirstTypeArgument(typeMirror);
        typeName = parameterizedCollectionName(attribute.typeMirror());
    } else if (attribute.isOptional()) {
        typeMirror = tryFirstTypeArgument(typeMirror);
        typeName = TypeName.get(typeMirror);
    } else {
        typeName = nameResolver.generatedTypeNameOf(typeMirror).orElse(null);
    }
    if (typeName == null) {
        typeName = boxedTypeName(typeMirror);
    }
    ParameterizedTypeName type;
    ClassName attributeType = null;
    boolean useKotlinDelegate = false;
    if (expression) {
        type = parameterizedTypeName(QueryExpression.class, typeName);
    } else {
        // if it's an association don't make it available as a query attribute
        boolean isQueryable = attribute.cardinality() == null || attribute.isForeignKey();
        Class<?> attributeClass = isQueryable ? QueryAttribute.class : Attribute.class;
        attributeType = ClassName.get(attributeClass);
        if (isQueryable) {
            TypeElement delegateType = elements.getTypeElement(KOTLIN_ATTRIBUTE_DELEGATE);
            if (delegateType != null) {
                attributeType = ClassName.get(delegateType);
                useKotlinDelegate = true;
            }
        }
        type = ParameterizedTypeName.get(attributeType, targetName, typeName);
    }
    CodeBlock.Builder builder = CodeBlock.builder();
    String attributeName = attribute.name();
    if (parent != null && parent.isEmbedded()) {
        attributeName = embeddedAttributeName(parent, attribute);
    }
    if (attribute.isIterable()) {
        typeMirror = tryFirstTypeArgument(typeMirror);
        TypeName name = nameResolver.tryGeneratedTypeName(typeMirror);
        TypeElement collection = (TypeElement) types.asElement(attribute.typeMirror());
        ParameterizedTypeName builderName = parameterizedTypeName(attribute.builderClass(), targetName, typeName, name);
        builder.add("\nnew $T($S, $T.class, $T.class)\n", builderName, attributeName, ClassName.get(collection), name);
    } else if (attribute.isMap() && attribute.cardinality() != null) {
        List<TypeMirror> parameters = Mirrors.listGenericTypeArguments(typeMirror);
        // key type
        TypeName keyName = TypeName.get(parameters.get(0));
        // value type
        typeMirror = parameters.get(1);
        TypeName valueName = nameResolver.tryGeneratedTypeName(typeMirror);
        TypeElement valueElement = (TypeElement) types.asElement(attribute.typeMirror());
        ParameterizedTypeName builderName = parameterizedTypeName(attribute.builderClass(), targetName, typeName, keyName, valueName);
        builder.add("\nnew $T($S, $T.class, $T.class, $T.class)\n", builderName, attributeName, ClassName.get(valueElement), keyName, valueName);
    } else {
        ParameterizedTypeName builderName = parameterizedTypeName(attribute.builderClass(), targetName, typeName);
        TypeName classType = typeName;
        if (typeMirror.getKind().isPrimitive()) {
            // if primitive just use the primitive class not the boxed version
            classType = TypeName.get(typeMirror);
        }
        String statement;
        if (Mirrors.listGenericTypeArguments(typeMirror).size() > 0) {
            // use the erased type and cast to class
            classType = TypeName.get(types.erasure(typeMirror));
            statement = "\nnew $T($S, (Class)$T.class)\n";
        } else {
            statement = "\nnew $T($S, $T.class)\n";
        }
        builder.add(statement, builderName, attributeName, classType);
    }
    if (!expression) {
        generateProperties(attribute, parent, typeMirror, targetName, typeName, builder);
    }
    // attribute builder properties
    if (attribute.isKey()) {
        builder.add(".setKey(true)\n");
    }
    builder.add(".setGenerated($L)\n", attribute.isGenerated());
    builder.add(".setLazy($L)\n", attribute.isLazy());
    builder.add(".setNullable($L)\n", attribute.isNullable());
    builder.add(".setUnique($L)\n", attribute.isUnique());
    if (!Names.isEmpty(attribute.defaultValue())) {
        builder.add(".setDefaultValue($S)\n", attribute.defaultValue());
    }
    if (!Names.isEmpty(attribute.collate())) {
        builder.add(".setCollate($S)\n", attribute.collate());
    }
    if (attribute.columnLength() != null) {
        builder.add(".setLength($L)\n", attribute.columnLength());
    }
    if (!Names.isEmpty(attribute.definition())) {
        builder.add(".setDefinition($S)\n", attribute.definition());
    }
    if (attribute.isVersion()) {
        builder.add(".setVersion($L)\n", attribute.isVersion());
    }
    if (attribute.converterName() != null) {
        builder.add(".setConverter(new $L())\n", attribute.converterName());
    }
    if (attribute.isForeignKey()) {
        builder.add(".setForeignKey($L)\n", attribute.isForeignKey());
        Optional<EntityDescriptor> referencedType = graph.referencingEntity(attribute);
        referencedType.ifPresent(referenced -> {
            builder.add(".setReferencedClass($T.class)\n", referenced.isImmutable() ? TypeName.get(referenced.element().asType()) : nameResolver.typeNameOf(referenced));
            graph.referencingAttribute(attribute, referenced).ifPresent(referencedAttribute -> {
                String name = upperCaseUnderscoreRemovePrefixes(referencedAttribute.fieldName());
                TypeSpec provider = CodeGeneration.createAnonymousSupplier(ClassName.get(Attribute.class), CodeBlock.builder().addStatement("return $T.$L", nameResolver.typeNameOf(referenced), name).build());
                builder.add(".setReferencedAttribute($L)\n", provider);
            });
        });
    }
    if (attribute.isIndexed()) {
        builder.add(".setIndexed($L)\n", attribute.isIndexed());
        if (!attribute.indexNames().isEmpty()) {
            StringJoiner joiner = new StringJoiner(",");
            attribute.indexNames().forEach(name -> joiner.add("$S"));
            builder.add(".setIndexNames(" + joiner + ")\n", attribute.indexNames().toArray());
        }
    }
    if (attribute.deleteAction() != null) {
        builder.add(".setDeleteAction($T.$L)\n", ClassName.get(ReferentialAction.class), attribute.deleteAction());
    }
    if (attribute.updateAction() != null) {
        builder.add(".setUpdateAction($T.$L)\n", ClassName.get(ReferentialAction.class), attribute.updateAction());
    }
    if (!attribute.cascadeActions().isEmpty()) {
        StringJoiner joiner = new StringJoiner(",");
        attribute.cascadeActions().forEach(action -> joiner.add("$T.$L"));
        int index = 0;
        ClassName cascadeClass = ClassName.get(CascadeAction.class);
        Object[] args = new Object[attribute.cascadeActions().size() * 2];
        for (CascadeAction action : attribute.cascadeActions()) {
            args[index++] = cascadeClass;
            args[index++] = action;
        }
        builder.add(".setCascadeAction(" + joiner + ")\n", args);
    }
    if (attribute.cardinality() != null) {
        if (!expression) {
            builder.add(".setCardinality($T.$L)\n", ClassName.get(Cardinality.class), attribute.cardinality());
        }
        graph.referencingEntity(attribute).ifPresent(referenced -> {
            Set<AttributeDescriptor> mappings = graph.mappedAttributes(entity, attribute, referenced);
            if (attribute.cardinality() == Cardinality.MANY_TO_MANY) {
                generateJunctionType(attribute, referenced, mappings).ifPresent(name -> builder.add(".setReferencedClass($T.class)\n", name));
            }
            if (mappings.size() == 1) {
                AttributeDescriptor mapped = mappings.iterator().next();
                String staticMemberName = upperCaseUnderscoreRemovePrefixes(mapped.fieldName());
                TypeSpec provider = CodeGeneration.createAnonymousSupplier(ClassName.get(Attribute.class), CodeBlock.builder().addStatement("return $T.$L", nameResolver.typeNameOf(referenced), staticMemberName).build());
                builder.add(".setMappedAttribute($L)\n", provider);
            }
            if (attribute.orderBy() != null) {
                referenced.attributes().values().stream().filter(entry -> entry.name().equals(attribute.orderBy())).findFirst().ifPresent(orderBy -> {
                    String staticMemberName = upperCaseUnderscoreRemovePrefixes(orderBy.fieldName());
                    TypeSpec provider = CodeGeneration.createAnonymousSupplier(ClassName.get(Attribute.class), CodeBlock.builder().addStatement("return $T.$L", nameResolver.typeNameOf(referenced), staticMemberName).build());
                    builder.add(".setOrderByAttribute($L)\n", provider);
                    builder.add(".setOrderByDirection($T.$L)\n", ClassName.get(Order.class), attribute.orderByDirection());
                });
            }
        });
    }
    builder.add(".build()");
    FieldSpec.Builder field = FieldSpec.builder(type, fieldName, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
    if (useKotlinDelegate) {
        return field.initializer("new $T($L)", attributeType, builder.build()).build();
    } else {
        return field.initializer("$L", builder.build()).build();
    }
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) QueryAttribute(io.requery.meta.QueryAttribute) Attribute(io.requery.meta.Attribute) ReferentialAction(io.requery.ReferentialAction) TypeMirror(javax.lang.model.type.TypeMirror) ClassName(com.squareup.javapoet.ClassName) LinkedList(java.util.LinkedList) List(java.util.List) QueryExpression(io.requery.meta.QueryExpression) StringJoiner(java.util.StringJoiner) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) CascadeAction(io.requery.CascadeAction) Order(io.requery.query.Order) Cardinality(io.requery.meta.Cardinality) TypeElement(javax.lang.model.element.TypeElement) CodeBlock(com.squareup.javapoet.CodeBlock) FieldSpec(com.squareup.javapoet.FieldSpec) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 59 with StringJoiner

use of java.util.StringJoiner in project presto by prestodb.

the class DatabaseShardManager method createTable.

@Override
public void createTable(long tableId, List<ColumnInfo> columns, boolean bucketed, OptionalLong temporalColumnId) {
    StringJoiner tableColumns = new StringJoiner(",\n  ", "  ", ",\n").setEmptyValue("");
    for (ColumnInfo column : columns) {
        String columnType = sqlColumnType(column.getType());
        if (columnType != null) {
            tableColumns.add(minColumn(column.getColumnId()) + " " + columnType);
            tableColumns.add(maxColumn(column.getColumnId()) + " " + columnType);
        }
    }
    StringJoiner coveringIndexColumns = new StringJoiner(", ");
    // Add the max temporal column first to accelerate queries that usually scan recent data
    temporalColumnId.ifPresent(id -> coveringIndexColumns.add(maxColumn(id)));
    temporalColumnId.ifPresent(id -> coveringIndexColumns.add(minColumn(id)));
    String sql;
    if (bucketed) {
        coveringIndexColumns.add("bucket_number").add("shard_id").add("shard_uuid");
        sql = "" + "CREATE TABLE " + shardIndexTable(tableId) + " (\n" + "  shard_id BIGINT NOT NULL,\n" + "  shard_uuid BINARY(16) NOT NULL,\n" + "  bucket_number INT NOT NULL\n," + tableColumns + "  PRIMARY KEY (bucket_number, shard_uuid),\n" + "  UNIQUE (shard_id),\n" + "  UNIQUE (shard_uuid),\n" + "  UNIQUE (" + coveringIndexColumns + ")\n" + ")";
    } else {
        coveringIndexColumns.add("node_ids").add("shard_id").add("shard_uuid");
        sql = "" + "CREATE TABLE " + shardIndexTable(tableId) + " (\n" + "  shard_id BIGINT NOT NULL,\n" + "  shard_uuid BINARY(16) NOT NULL,\n" + "  node_ids VARBINARY(128) NOT NULL,\n" + tableColumns + "  PRIMARY KEY (node_ids, shard_uuid),\n" + "  UNIQUE (shard_id),\n" + "  UNIQUE (shard_uuid),\n" + "  UNIQUE (" + coveringIndexColumns + ")\n" + ")";
    }
    try (Handle handle = dbi.open()) {
        handle.execute(sql);
    } catch (DBIException e) {
        throw metadataError(e);
    }
}
Also used : DBIException(org.skife.jdbi.v2.exceptions.DBIException) StringJoiner(java.util.StringJoiner) RaptorColumnHandle(com.facebook.presto.raptor.RaptorColumnHandle) Handle(org.skife.jdbi.v2.Handle)

Example 60 with StringJoiner

use of java.util.StringJoiner in project opennms by OpenNMS.

the class GraphPainter method getStyleName.

/**
	 * Cannot return null
	 */
private String getStyleName(Edge edge) {
    final String styleName = edge.getStyleName();
    final StringJoiner stringJoiner = new StringJoiner(" ");
    if (!Strings.isNullOrEmpty(styleName)) {
        stringJoiner.add(styleName);
    }
    if (isSelected(m_graphContainer.getSelectionManager(), edge)) {
        stringJoiner.add("selected");
    }
    String status = getEdgeStatus(edge);
    if (!Strings.isNullOrEmpty(status)) {
        stringJoiner.add(status);
    }
    return stringJoiner.toString();
}
Also used : StringJoiner(java.util.StringJoiner)

Aggregations

StringJoiner (java.util.StringJoiner)94 ArrayList (java.util.ArrayList)20 List (java.util.List)10 HashSet (java.util.HashSet)6 Map (java.util.Map)6 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 Collectors (java.util.stream.Collectors)4 ClassName (com.squareup.javapoet.ClassName)3 FieldSpec (com.squareup.javapoet.FieldSpec)3 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)3 TypeName (com.squareup.javapoet.TypeName)3 TypeSpec (com.squareup.javapoet.TypeSpec)3 Expression (com.sri.ai.expresso.api.Expression)3 Attribute (io.requery.meta.Attribute)3 Scanner (java.util.Scanner)3 RaptorColumnHandle (com.facebook.presto.raptor.RaptorColumnHandle)2 Range (com.facebook.presto.spi.predicate.Range)2 MaterializedResult (com.facebook.presto.testing.MaterializedResult)2 MaterializedRow (com.facebook.presto.testing.MaterializedRow)2