Search in sources :

Example 16 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class PostgreSqlQueryGenerator method getSqlDefaulValue.

private static String getSqlDefaulValue(Attribute attribute, String defaultValueAsString) {
    String sqlDefaultValue;
    Object defaultTypedValue = AttributeUtils.getDefaultTypedValue(attribute, defaultValueAsString);
    AttributeType attributeType = attribute.getDataType();
    switch(attributeType) {
        case BOOL:
            Boolean booleanDefaultValue = (Boolean) defaultTypedValue;
            sqlDefaultValue = booleanDefaultValue ? "TRUE" : "FALSE";
            break;
        case CATEGORICAL:
        case FILE:
        case XREF:
            Entity refDefaultValue = (Entity) defaultTypedValue;
            sqlDefaultValue = getSqlDefaulValue(attribute.getRefEntity().getIdAttribute(), refDefaultValue.getIdValue().toString());
            break;
        case DATE:
            LocalDate dateDefaultValue = (LocalDate) defaultTypedValue;
            sqlDefaultValue = '\'' + dateDefaultValue.toString() + '\'';
            break;
        case DATE_TIME:
            Instant instantDefaultValue = (Instant) defaultTypedValue;
            // As a workaround for #5674, we don't store milliseconds
            sqlDefaultValue = '\'' + instantDefaultValue.truncatedTo(ChronoUnit.SECONDS).atOffset(UTC).toString() + '\'';
            break;
        case DECIMAL:
            Double doubleDefaultValue = (Double) defaultTypedValue;
            sqlDefaultValue = doubleDefaultValue.toString();
            break;
        case EMAIL:
        case ENUM:
        case HTML:
        case HYPERLINK:
        case SCRIPT:
        case STRING:
        case TEXT:
            sqlDefaultValue = '\'' + (String) defaultTypedValue + '\'';
            break;
        case INT:
            Integer intDefaultValue = (Integer) defaultTypedValue;
            sqlDefaultValue = intDefaultValue.toString();
            break;
        case LONG:
            Long longDefaultValue = (Long) defaultTypedValue;
            sqlDefaultValue = longDefaultValue.toString();
            break;
        case CATEGORICAL_MREF:
        case COMPOUND:
        case MREF:
        case ONE_TO_MANY:
            throw new RuntimeException(format("Illegal attribute type [%s]", attributeType.toString()));
        default:
            throw new UnexpectedEnumException(attributeType);
    }
    return sqlDefaultValue;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) AttributeType(org.molgenis.data.meta.AttributeType) Instant(java.time.Instant) LocalDate(java.time.LocalDate)

Example 17 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class PostgreSqlUtils method getPostgreSqlValue.

/**
 * Returns the PostgreSQL value for the given entity attribute
 *
 * @param entity entity
 * @param attr   attribute
 * @return PostgreSQL value
 */
static Object getPostgreSqlValue(Entity entity, Attribute attr) {
    String attrName = attr.getName();
    AttributeType attrType = attr.getDataType();
    switch(attrType) {
        case BOOL:
            return entity.getBoolean(attrName);
        case CATEGORICAL:
        case XREF:
            Entity xrefEntity = entity.getEntity(attrName);
            return xrefEntity != null ? getPostgreSqlValue(xrefEntity, xrefEntity.getEntityType().getIdAttribute()) : null;
        case CATEGORICAL_MREF:
        case MREF:
        case ONE_TO_MANY:
            Iterable<Entity> entities = entity.getEntities(attrName);
            return stream(entities.spliterator(), false).map(mrefEntity -> getPostgreSqlValue(mrefEntity, mrefEntity.getEntityType().getIdAttribute())).collect(toList());
        case DATE:
            return entity.getLocalDate(attrName);
        case DATE_TIME:
            // As a workaround for #5674, we don't store milliseconds
            Instant instant = entity.getInstant(attrName);
            return instant != null ? instant.truncatedTo(ChronoUnit.SECONDS).atOffset(UTC) : null;
        case DECIMAL:
            return entity.getDouble(attrName);
        case EMAIL:
        case ENUM:
        case HTML:
        case HYPERLINK:
        case SCRIPT:
        case STRING:
        case TEXT:
            return entity.getString(attrName);
        case FILE:
            FileMeta fileEntity = entity.getEntity(attrName, FileMeta.class);
            return fileEntity != null ? getPostgreSqlValue(fileEntity, fileEntity.getEntityType().getIdAttribute()) : null;
        case INT:
            return entity.getInt(attrName);
        case LONG:
            return entity.getLong(attrName);
        case COMPOUND:
            throw new RuntimeException(format("Illegal attribute type [%s]", attrType.toString()));
        default:
            throw new UnexpectedEnumException(attrType);
    }
}
Also used : AttributeType(org.molgenis.data.meta.AttributeType) Instant(java.time.Instant) Attribute(org.molgenis.data.meta.model.Attribute) String.format(java.lang.String.format) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) FileMeta(org.molgenis.data.file.model.FileMeta) Collectors.toList(java.util.stream.Collectors.toList) ChronoUnit(java.time.temporal.ChronoUnit) StreamSupport.stream(java.util.stream.StreamSupport.stream) LocalDate(java.time.LocalDate) UTC(java.time.ZoneOffset.UTC) MolgenisDataException(org.molgenis.data.MolgenisDataException) Entity(org.molgenis.data.Entity) Entity(org.molgenis.data.Entity) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) AttributeType(org.molgenis.data.meta.AttributeType) Instant(java.time.Instant) FileMeta(org.molgenis.data.file.model.FileMeta)

Example 18 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class EntitySerializer method serialize.

@Override
public JsonElement serialize(Entity entity, Type type, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.addProperty("__entityTypeId", entity.getEntityType().getId());
    for (Attribute attr : entity.getEntityType().getAtomicAttributes()) {
        String attributeName = attr.getName();
        Object value = entity.get(attributeName);
        if (value != null) {
            AttributeType attrType = attr.getDataType();
            switch(attrType) {
                case BOOL:
                    result.addProperty(attributeName, entity.getBoolean(attributeName));
                    break;
                case CATEGORICAL:
                case XREF:
                case FILE:
                    Entity refEntity = entity.getEntity(attributeName);
                    result.add(attributeName, serializeReference(refEntity, context));
                    break;
                case CATEGORICAL_MREF:
                case MREF:
                case ONE_TO_MANY:
                    JsonArray jsonArray = new JsonArray();
                    entity.getEntities(attributeName).forEach(e -> jsonArray.add(serializeReference(e, context)));
                    result.add(attributeName, jsonArray);
                    break;
                case DATE:
                    LocalDate localDateValue = entity.getLocalDate(attributeName);
                    result.add(attributeName, context.serialize(localDateValue));
                    break;
                case DATE_TIME:
                    Instant instantValue = entity.getInstant(attributeName);
                    result.add(attributeName, context.serialize(instantValue));
                    break;
                case DECIMAL:
                    result.addProperty(attributeName, entity.getDouble(attributeName));
                    break;
                case INT:
                    result.addProperty(attributeName, entity.getInt(attributeName));
                    break;
                case LONG:
                    result.addProperty(attributeName, entity.getLong(attributeName));
                    break;
                case ENUM:
                case HTML:
                case HYPERLINK:
                case SCRIPT:
                case EMAIL:
                case STRING:
                case TEXT:
                    result.addProperty(attributeName, value.toString());
                    break;
                case COMPOUND:
                    throw new RuntimeException(format("Illegal attribute type [%s]", attrType.toString()));
                default:
                    throw new UnexpectedEnumException(attrType);
            }
        }
    }
    return result;
}
Also used : Entity(org.molgenis.data.Entity) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) Attribute(org.molgenis.data.meta.model.Attribute) AttributeType(org.molgenis.data.meta.AttributeType) Instant(java.time.Instant) LocalDate(java.time.LocalDate)

Example 19 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class PostgreSqlQueryGenerator method getSqlColumn.

private static String getSqlColumn(EntityType entityType, Attribute attr, ColumnMode columnMode) {
    StringBuilder sqlBuilder = new StringBuilder(getColumnName(attr)).append(' ');
    AttributeType attrType = attr.getDataType();
    switch(attrType) {
        case BOOL:
        case DATE:
        case DATE_TIME:
        case DECIMAL:
        case EMAIL:
        case ENUM:
        case HTML:
        case HYPERLINK:
        case INT:
        case LONG:
        case SCRIPT:
        case STRING:
        case TEXT:
            sqlBuilder.append(getPostgreSqlType(attr));
            break;
        case CATEGORICAL:
        case FILE:
        case XREF:
            sqlBuilder.append(getPostgreSqlType(attr.getRefEntity().getIdAttribute()));
            break;
        case ONE_TO_MANY:
        case COMPOUND:
        case CATEGORICAL_MREF:
        case MREF:
            throw new RuntimeException(format("Illegal attribute type [%s]", attrType.toString()));
        default:
            throw new UnexpectedEnumException(attrType);
    }
    String sqlColumnConstraints = getSqlColumnConstraints(entityType, attr, columnMode);
    if (!sqlColumnConstraints.isEmpty()) {
        sqlBuilder.append(' ').append(sqlColumnConstraints);
    }
    return sqlBuilder.toString();
}
Also used : UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) AttributeType(org.molgenis.data.meta.AttributeType)

Example 20 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class PostgreSqlQueryGenerator method getSqlWhere.

static <E extends Entity> String getSqlWhere(EntityType entityType, Query<E> q, List<Object> parameters, AtomicInteger mrefFilterIndex) {
    StringBuilder result = new StringBuilder();
    for (QueryRule r : q.getRules()) {
        Attribute attr = null;
        if (r.getField() != null) {
            attr = entityType.getAttribute(r.getField());
            if (attr == null) {
                throw new MolgenisDataException(format("Unknown attribute [%s]", r.getField()));
            }
            if (isPersistedInOtherTable(attr)) {
                mrefFilterIndex.incrementAndGet();
            }
        }
        StringBuilder predicate = new StringBuilder();
        Operator operator = r.getOperator();
        switch(operator) {
            case AND:
                result.append(" AND ");
                break;
            case NESTED:
                QueryImpl<Entity> nestedQ = new QueryImpl<>(r.getNestedRules());
                result.append('(').append(getSqlWhere(entityType, nestedQ, parameters, mrefFilterIndex)).append(')');
                break;
            case OR:
                result.append(" OR ");
                break;
            case LIKE:
                requireNonNull(attr, format(UNSPECIFIED_ATTRIBUTE_MSG, LIKE));
                String columnName;
                if (isPersistedInOtherTable(attr)) {
                    columnName = getFilterColumnName(attr, mrefFilterIndex.get());
                } else {
                    columnName = "this." + getColumnName(attr);
                }
                if (isStringType(attr) || isTextType(attr)) {
                    result.append(' ').append(columnName);
                } else {
                    result.append(" CAST(").append(columnName).append(" as TEXT)");
                }
                result.append(" LIKE ?");
                parameters.add("%" + PostgreSqlUtils.getPostgreSqlQueryValue(r.getValue(), attr) + '%');
                break;
            case IN:
                {
                    requireNonNull(attr, format(UNSPECIFIED_ATTRIBUTE_MSG, IN));
                    Object inValue = r.getValue();
                    if (inValue == null) {
                        throw new MolgenisDataException("Missing value for IN query");
                    }
                    if (!(inValue instanceof Iterable<?>)) {
                        throw new MolgenisDataException(format("IN value is of type [%s] instead of [Iterable]", inValue.getClass().getSimpleName()));
                    }
                    StringBuilder in = new StringBuilder();
                    Attribute inAttr = attr;
                    Stream<Object> postgreSqlIds = stream(((Iterable<?>) inValue).spliterator(), false).map(idValue -> PostgreSqlUtils.getPostgreSqlQueryValue(idValue, inAttr));
                    for (Iterator<Object> it = postgreSqlIds.iterator(); it.hasNext(); ) {
                        Object postgreSqlId = it.next();
                        in.append('?');
                        if (it.hasNext()) {
                            in.append(',');
                        }
                        parameters.add(postgreSqlId);
                    }
                    if (isPersistedInOtherTable(attr)) {
                        result.append(getFilterColumnName(attr, mrefFilterIndex.get()));
                    } else {
                        result.append("this");
                    }
                    Attribute equalsAttr;
                    if (attr.isMappedBy()) {
                        equalsAttr = attr.getRefEntity().getIdAttribute();
                    } else {
                        equalsAttr = entityType.getAttribute(r.getField());
                    }
                    result.append('.').append(getColumnName(equalsAttr));
                    result.append(" IN (").append(in).append(')');
                    break;
                }
            case NOT:
                result.append(" NOT ");
                break;
            case RANGE:
                requireNonNull(attr, format(UNSPECIFIED_ATTRIBUTE_MSG, RANGE));
                Object range = r.getValue();
                if (range == null) {
                    throw new MolgenisDataException("Missing value for RANGE query");
                }
                if (!(range instanceof Iterable<?>)) {
                    throw new MolgenisDataException(format("RANGE value is of type [%s] instead of [Iterable]", range.getClass().getSimpleName()));
                }
                Iterator<?> rangeValues = ((Iterable<?>) range).iterator();
                // from
                parameters.add(rangeValues.next());
                // to
                parameters.add(rangeValues.next());
                StringBuilder column = new StringBuilder();
                if (isPersistedInOtherTable(attr)) {
                    column.append(getFilterColumnName(attr, mrefFilterIndex.get()));
                } else {
                    column.append("this");
                }
                column.append('.').append(getColumnName(entityType.getAttribute(r.getField())));
                predicate.append(column).append(" >= ? AND ").append(column).append(" <= ?");
                result.append(predicate);
                break;
            case EQUALS:
                if (attr == null) {
                    throw new MolgenisDataException("Missing attribute field in EQUALS query rule");
                }
                if (isPersistedInOtherTable(attr)) {
                    predicate.append(getFilterColumnName(attr, mrefFilterIndex.get()));
                } else {
                    predicate.append("this");
                }
                Attribute equalsAttr;
                if (attr.isMappedBy()) {
                    equalsAttr = attr.getRefEntity().getIdAttribute();
                } else {
                    equalsAttr = entityType.getAttribute(r.getField());
                }
                predicate.append('.').append(getColumnName(equalsAttr));
                if (r.getValue() == null) {
                    // expression = null is not valid, use IS NULL
                    predicate.append(" IS NULL ");
                } else {
                    Object postgreSqlVal = PostgreSqlUtils.getPostgreSqlQueryValue(r.getValue(), attr);
                    // It does however return those rows when queried with "... NOT abstract IS TRUE"
                    if (attr.getDataType() == BOOL) {
                        Boolean bool = (Boolean) postgreSqlVal;
                        // noinspection ConstantConditions (getPostgreSqlQueryValue() != null if r.getValue() != null)
                        if (bool)
                            predicate.append(" IS TRUE");
                        else
                            predicate.append(" IS FALSE");
                    } else {
                        predicate.append(" =");
                        predicate.append(" ? ");
                        parameters.add(postgreSqlVal);
                    }
                }
                if (result.length() > 0 && !result.toString().endsWith(" OR ") && !result.toString().endsWith(" AND ") && !result.toString().endsWith(" NOT ")) {
                    result.append(" AND ");
                }
                result.append(predicate);
                break;
            case GREATER:
            case GREATER_EQUAL:
            case LESS:
            case LESS_EQUAL:
                requireNonNull(attr, format(UNSPECIFIED_ATTRIBUTE_MSG, format("%s, %s, %s or %s", GREATER, GREATER_EQUAL, LESS, LESS_EQUAL)));
                if (isPersistedInOtherTable(attr)) {
                    predicate.append(getFilterColumnName(attr, mrefFilterIndex.get()));
                } else {
                    predicate.append("this");
                }
                predicate.append('.').append(getColumnName(entityType.getAttribute(r.getField())));
                switch(operator) {
                    case GREATER:
                        predicate.append(" >");
                        break;
                    case GREATER_EQUAL:
                        predicate.append(" >=");
                        break;
                    case LESS:
                        predicate.append(" <");
                        break;
                    case LESS_EQUAL:
                        predicate.append(" <=");
                        break;
                    // $CASES-OMITTED$
                    default:
                        throw new RuntimeException(format("Unexpected query operator [%s]", operator));
                }
                predicate.append(" ? ");
                parameters.add(PostgreSqlUtils.getPostgreSqlQueryValue(r.getValue(), attr));
                if (result.length() > 0 && !result.toString().endsWith(" OR ") && !result.toString().endsWith(" AND ") && !result.toString().endsWith(" NOT ")) {
                    result.append(" AND ");
                }
                result.append(predicate);
                break;
            case DIS_MAX:
            case FUZZY_MATCH:
            case FUZZY_MATCH_NGRAM:
            case SEARCH:
            case SHOULD:
                // PostgreSQL does not support semantic searching and sorting matching rows on relevance.
                throw new UnsupportedOperationException(format("Query operator [%s] not supported by PostgreSQL repository", operator.toString()));
            default:
                throw new UnexpectedEnumException(operator);
        }
    }
    return result.toString().trim();
}
Also used : Operator(org.molgenis.data.QueryRule.Operator) IntStream.range(java.util.stream.IntStream.range) Operator(org.molgenis.data.QueryRule.Operator) LoggerFactory(org.slf4j.LoggerFactory) QueryImpl(org.molgenis.data.support.QueryImpl) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(org.molgenis.data.meta.model.Attribute) MessageFormat(java.text.MessageFormat) Lists(com.google.common.collect.Lists) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AttributeUtils(org.molgenis.data.support.AttributeUtils) Objects.requireNonNull(java.util.Objects.requireNonNull) PostgreSqlNameGenerator(org.molgenis.data.postgresql.PostgreSqlNameGenerator) AttributeType(org.molgenis.data.meta.AttributeType) Logger(org.slf4j.Logger) PostgreSqlQueryUtils(org.molgenis.data.postgresql.PostgreSqlQueryUtils) org.molgenis.data(org.molgenis.data) Iterator(java.util.Iterator) Collection(java.util.Collection) EntityTypeUtils(org.molgenis.data.support.EntityTypeUtils) Instant(java.time.Instant) EntityType(org.molgenis.data.meta.model.EntityType) String.format(java.lang.String.format) Collectors.joining(java.util.stream.Collectors.joining) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) INCLUDE_DEFAULT_CONSTRAINT(org.molgenis.data.postgresql.PostgreSqlQueryGenerator.ColumnMode.INCLUDE_DEFAULT_CONSTRAINT) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) StreamSupport.stream(java.util.stream.StreamSupport.stream) LocalDate(java.time.LocalDate) UTC(java.time.ZoneOffset.UTC) Attribute(org.molgenis.data.meta.model.Attribute) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) QueryImpl(org.molgenis.data.support.QueryImpl) Iterator(java.util.Iterator) Stream(java.util.stream.Stream)

Aggregations

UnexpectedEnumException (org.molgenis.util.UnexpectedEnumException)39 AttributeType (org.molgenis.data.meta.AttributeType)26 Attribute (org.molgenis.data.meta.model.Attribute)20 Entity (org.molgenis.data.Entity)13 Instant (java.time.Instant)10 LocalDate (java.time.LocalDate)10 String.format (java.lang.String.format)4 Collectors.toList (java.util.stream.Collectors.toList)4 MolgenisDataException (org.molgenis.data.MolgenisDataException)4 Iterator (java.util.Iterator)3 List (java.util.List)3 StreamSupport.stream (java.util.stream.StreamSupport.stream)3 EntityType (org.molgenis.data.meta.model.EntityType)3 UTC (java.time.ZoneOffset.UTC)2 ChronoUnit (java.time.temporal.ChronoUnit)2 Collection (java.util.Collection)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Collectors.joining (java.util.stream.Collectors.joining)2 Stream (java.util.stream.Stream)2