Search in sources :

Example 1 with IncompatibleTypeException

use of io.jans.orm.exception.operation.IncompatibleTypeException in project jans by JanssenProject.

the class SpannerOperationServiceImpl method searchImpl.

private <O> PagedResult<EntryData> searchImpl(TableMapping tableMapping, String key, ConvertedExpression expression, SearchScope scope, String[] attributes, Sort[] orderBy, SpannerBatchOperationWraper<O> batchOperationWraper, SearchReturnDataType returnDataType, int start, int count, int pageSize) throws SearchException {
    BatchOperation<O> batchOperation = null;
    if (batchOperationWraper != null) {
        batchOperation = (BatchOperation<O>) batchOperationWraper.getBatchOperation();
    }
    Table table = buildTable(tableMapping);
    PlainSelect sqlSelectQuery = new PlainSelect();
    sqlSelectQuery.setFromItem(table);
    List<SelectItem> selectItems = buildSelectAttributes(tableMapping, key, attributes);
    sqlSelectQuery.addSelectItems(selectItems);
    if (expression != null) {
        applyWhereExpression(sqlSelectQuery, expression);
    }
    if (orderBy != null) {
        OrderByElement[] orderByElements = new OrderByElement[orderBy.length];
        for (int i = 0; i < orderBy.length; i++) {
            Column column = new Column(orderBy[i].getName());
            orderByElements[i] = new OrderByElement();
            orderByElements[i].setExpression(column);
            if (orderBy[i].getSortOrder() != null) {
                orderByElements[i].setAscDescPresent(true);
                orderByElements[i].setAsc(SortOrder.ASCENDING == orderBy[i].getSortOrder());
            }
        }
        sqlSelectQuery.withOrderByElements(Arrays.asList(orderByElements));
    }
    List<EntryData> searchResultList = new LinkedList<EntryData>();
    if ((SearchReturnDataType.SEARCH == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) {
        List<EntryData> lastResult = null;
        if (pageSize > 0) {
            boolean collectSearchResult;
            Limit limit = new Limit();
            sqlSelectQuery.setLimit(limit);
            Offset offset = new Offset();
            sqlSelectQuery.setOffset(offset);
            int currentLimit;
            try {
                int resultCount = 0;
                int lastCountRows = 0;
                do {
                    collectSearchResult = true;
                    currentLimit = pageSize;
                    if (count > 0) {
                        currentLimit = Math.min(pageSize, count - resultCount);
                    }
                    // Change limit and offset
                    limit.setRowCount(new LongValue(currentLimit));
                    offset.setOffset(start + resultCount);
                    Statement.Builder statementBuilder = Statement.newBuilder(sqlSelectQuery.toString());
                    applyParametersBinding(statementBuilder, expression);
                    Statement statement = statementBuilder.build();
                    LOG.debug("Executing query: '{}'", statement);
                    try (ResultSet resultSet = databaseClient.singleUse().executeQuery(statement)) {
                        lastResult = getEntryDataList(tableMapping.getObjectClass(), resultSet);
                    }
                    lastCountRows = lastResult.size();
                    if (batchOperation != null) {
                        collectSearchResult = batchOperation.collectSearchResult(lastCountRows);
                    }
                    if (collectSearchResult) {
                        searchResultList.addAll(lastResult);
                    }
                    if (batchOperation != null) {
                        List<O> entries = batchOperationWraper.createEntities(lastResult);
                        batchOperation.performAction(entries);
                    }
                    resultCount += lastCountRows;
                    if ((count > 0) && (resultCount >= count)) {
                        break;
                    }
                } while (lastCountRows > 0);
            } catch (SpannerException | EntryConvertationException | IncompatibleTypeException ex) {
                LOG.error("Failed to execute query with expression: '{}'", expression);
                throw new SearchException(String.format("Failed to execute query '%s'  with key: '%s'", sqlSelectQuery, key), ex);
            }
        } else {
            try {
                long currentLimit = count;
                if (currentLimit <= 0) {
                    currentLimit = connectionProvider.getDefaultMaximumResultSize();
                }
                Limit limit = new Limit();
                limit.setRowCount(new LongValue(currentLimit));
                sqlSelectQuery.setLimit(limit);
                if (start > 0) {
                    Offset offset = new Offset();
                    offset.setOffset(start);
                    sqlSelectQuery.setOffset(offset);
                }
                Statement.Builder statementBuilder = Statement.newBuilder(sqlSelectQuery.toString());
                applyParametersBinding(statementBuilder, expression);
                Statement statement = statementBuilder.build();
                LOG.debug("Executing query: '{}'", statement);
                try (ResultSet resultSet = databaseClient.singleUse().executeQuery(statement)) {
                    lastResult = getEntryDataList(tableMapping.getObjectClass(), resultSet);
                    searchResultList.addAll(lastResult);
                }
            } catch (SpannerException | EntryConvertationException | IncompatibleTypeException ex) {
                LOG.error("Failed to execute query with expression: '{}'", expression);
                throw new SearchException(String.format("Failed to execute query '%s'  with key: '%s'", sqlSelectQuery, key), ex);
            }
        }
    }
    PagedResult<EntryData> result = new PagedResult<EntryData>();
    result.setEntries(searchResultList);
    result.setEntriesCount(searchResultList.size());
    result.setStart(start);
    if ((SearchReturnDataType.COUNT == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) {
        PlainSelect sqlCountSelectQuery = new PlainSelect();
        sqlCountSelectQuery.setFromItem(table);
        Function countFunction = new Function();
        countFunction.setName("COUNT");
        countFunction.setAllColumns(true);
        SelectExpressionItem selectCountItem = new SelectExpressionItem(countFunction);
        selectCountItem.setAlias(new Alias("TOTAL", false));
        sqlCountSelectQuery.addSelectItems(selectCountItem);
        if (expression != null) {
            applyWhereExpression(sqlCountSelectQuery, expression);
        }
        try {
            Statement.Builder statementBuilder = Statement.newBuilder(sqlCountSelectQuery.toString());
            applyParametersBinding(statementBuilder, expression);
            Statement statement = statementBuilder.build();
            LOG.debug("Calculating count. Executing query: '{}'", statement);
            try (ResultSet countResult = databaseClient.singleUse().executeQuery(statement)) {
                if (!countResult.next()) {
                    throw new SearchException(String.format("Failed to calculate count entries. Query: '%s'", statement));
                }
                result.setTotalEntriesCount((int) countResult.getLong("TOTAL"));
            }
        } catch (SpannerException | IncompatibleTypeException ex) {
            LOG.error("Failed to execute query with expression: '{}'", expression);
            throw new SearchException(String.format("Failed to build count search entries query. Key: '%s', expression: '%s'", key, expression.expression()), ex);
        }
    }
    return result;
}
Also used : EntryData(io.jans.orm.model.EntryData) SelectExpressionItem(net.sf.jsqlparser.statement.select.SelectExpressionItem) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) SearchException(io.jans.orm.exception.operation.SearchException) Function(net.sf.jsqlparser.expression.Function) Column(net.sf.jsqlparser.schema.Column) SelectItem(net.sf.jsqlparser.statement.select.SelectItem) ResultSet(com.google.cloud.spanner.ResultSet) IncompatibleTypeException(io.jans.orm.exception.operation.IncompatibleTypeException) OrderByElement(net.sf.jsqlparser.statement.select.OrderByElement) PagedResult(io.jans.orm.model.PagedResult) Table(net.sf.jsqlparser.schema.Table) Statement(com.google.cloud.spanner.Statement) LinkedList(java.util.LinkedList) Offset(net.sf.jsqlparser.statement.select.Offset) Alias(net.sf.jsqlparser.expression.Alias) LongValue(net.sf.jsqlparser.expression.LongValue) EntryConvertationException(io.jans.orm.exception.operation.EntryConvertationException) Limit(net.sf.jsqlparser.statement.select.Limit) SpannerException(com.google.cloud.spanner.SpannerException) Builder(com.google.cloud.spanner.Statement.Builder)

Example 2 with IncompatibleTypeException

use of io.jans.orm.exception.operation.IncompatibleTypeException in project jans by JanssenProject.

the class SpannerOperationServiceImpl method deleteImpl.

private long deleteImpl(TableMapping tableMapping, ConvertedExpression expression, int count) throws DeleteException {
    try {
        Table table = buildTable(tableMapping);
        // select
        PlainSelect sqlSelectQuery = new PlainSelect();
        sqlSelectQuery.setFromItem(table);
        // doc_id
        Column selectDocIdColumn = new Column(tableAlias, DOC_ID);
        SelectExpressionItem selectDocIdItem = new SelectExpressionItem(selectDocIdColumn);
        sqlSelectQuery.addSelectItems(selectDocIdItem);
        applyWhereExpression(sqlSelectQuery, expression);
        long useCount = connectionProvider.getMaximumResultDeleteSize();
        if (count > 0) {
            useCount = Math.min(count, useCount);
        }
        Limit limit = new Limit();
        limit.setRowCount(new LongValue(useCount));
        sqlSelectQuery.setLimit(limit);
        SubSelect subSelect = new SubSelect();
        subSelect.setSelectBody(sqlSelectQuery);
        subSelect.withUseBrackets(true);
        Expression inExpression = new InExpression(selectDocIdColumn, subSelect);
        Delete sqlDeleteQuery = new Delete();
        sqlDeleteQuery.setTable(table);
        sqlDeleteQuery.setWhere(inExpression);
        Statement.Builder statementBuilder = Statement.newBuilder(sqlDeleteQuery.toString());
        applyParametersBinding(statementBuilder, expression);
        Statement statement = statementBuilder.build();
        LOG.debug("Executing delete query: '{}'", statement);
        Long rowDeleted = databaseClient.readWriteTransaction().run(new TransactionCallable<Long>() {

            @Override
            public Long run(TransactionContext transaction) throws Exception {
                long rowCount = transaction.executeUpdate(statement);
                return rowCount;
            }
        });
        return rowDeleted;
    } catch (SpannerException | IncompatibleTypeException ex) {
        throw new DeleteException(String.format("Failed to delete entries. Expression: '%s'", expression.expression()), ex);
    }
}
Also used : Delete(net.sf.jsqlparser.statement.delete.Delete) Table(net.sf.jsqlparser.schema.Table) Statement(com.google.cloud.spanner.Statement) DeleteException(io.jans.orm.exception.operation.DeleteException) SelectExpressionItem(net.sf.jsqlparser.statement.select.SelectExpressionItem) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) DeleteException(io.jans.orm.exception.operation.DeleteException) IncompatibleTypeException(io.jans.orm.exception.operation.IncompatibleTypeException) PersistenceException(io.jans.orm.exception.operation.PersistenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EntryConvertationException(io.jans.orm.exception.operation.EntryConvertationException) DuplicateEntryException(io.jans.orm.exception.operation.DuplicateEntryException) SpannerException(com.google.cloud.spanner.SpannerException) SearchException(io.jans.orm.exception.operation.SearchException) EntryNotFoundException(io.jans.orm.exception.operation.EntryNotFoundException) Column(net.sf.jsqlparser.schema.Column) Expression(net.sf.jsqlparser.expression.Expression) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) ConvertedExpression(io.jans.orm.cloud.spanner.model.ConvertedExpression) TransactionContext(com.google.cloud.spanner.TransactionContext) LongValue(net.sf.jsqlparser.expression.LongValue) IncompatibleTypeException(io.jans.orm.exception.operation.IncompatibleTypeException) Limit(net.sf.jsqlparser.statement.select.Limit) SpannerException(com.google.cloud.spanner.SpannerException) SubSelect(net.sf.jsqlparser.statement.select.SubSelect) Builder(com.google.cloud.spanner.Statement.Builder)

Aggregations

SpannerException (com.google.cloud.spanner.SpannerException)2 Statement (com.google.cloud.spanner.Statement)2 Builder (com.google.cloud.spanner.Statement.Builder)2 EntryConvertationException (io.jans.orm.exception.operation.EntryConvertationException)2 IncompatibleTypeException (io.jans.orm.exception.operation.IncompatibleTypeException)2 SearchException (io.jans.orm.exception.operation.SearchException)2 LongValue (net.sf.jsqlparser.expression.LongValue)2 Column (net.sf.jsqlparser.schema.Column)2 Table (net.sf.jsqlparser.schema.Table)2 Limit (net.sf.jsqlparser.statement.select.Limit)2 PlainSelect (net.sf.jsqlparser.statement.select.PlainSelect)2 SelectExpressionItem (net.sf.jsqlparser.statement.select.SelectExpressionItem)2 ResultSet (com.google.cloud.spanner.ResultSet)1 TransactionContext (com.google.cloud.spanner.TransactionContext)1 ConvertedExpression (io.jans.orm.cloud.spanner.model.ConvertedExpression)1 DeleteException (io.jans.orm.exception.operation.DeleteException)1 DuplicateEntryException (io.jans.orm.exception.operation.DuplicateEntryException)1 EntryNotFoundException (io.jans.orm.exception.operation.EntryNotFoundException)1 PersistenceException (io.jans.orm.exception.operation.PersistenceException)1 EntryData (io.jans.orm.model.EntryData)1