Search in sources :

Example 16 with ExpressionColumn

use of org.h2.expression.ExpressionColumn in project h2database by h2database.

the class SortOrder method getColumn.

/**
 * Get the column for the given table filter, if the sort column is for this
 * filter.
 *
 * @param index the column index (0, 1,..)
 * @param filter the table filter
 * @return the column, or null
 */
public Column getColumn(int index, TableFilter filter) {
    if (orderList == null) {
        return null;
    }
    SelectOrderBy order = orderList.get(index);
    Expression expr = order.expression;
    if (expr == null) {
        return null;
    }
    expr = expr.getNonAliasExpression();
    if (expr.isConstant()) {
        return null;
    }
    if (!(expr instanceof ExpressionColumn)) {
        return null;
    }
    ExpressionColumn exprCol = (ExpressionColumn) expr;
    if (exprCol.getTableFilter() != filter) {
        return null;
    }
    return exprCol.getColumn();
}
Also used : SelectOrderBy(org.h2.command.dml.SelectOrderBy) Expression(org.h2.expression.Expression) ExpressionColumn(org.h2.expression.ExpressionColumn)

Example 17 with ExpressionColumn

use of org.h2.expression.ExpressionColumn in project h2database by h2database.

the class TableView method initColumnsAndTables.

private void initColumnsAndTables(Session session, boolean literalsChecked) {
    Column[] cols;
    removeCurrentViewFromOtherTables();
    setTableExpression(isTableExpression);
    try {
        Query compiledQuery = compileViewQuery(session, querySQL, literalsChecked, getName());
        this.querySQL = compiledQuery.getPlanSQL();
        tables = new ArrayList<>(compiledQuery.getTables());
        ArrayList<Expression> expressions = compiledQuery.getExpressions();
        ArrayList<Column> list = New.arrayList();
        ColumnNamer columnNamer = new ColumnNamer(session);
        for (int i = 0, count = compiledQuery.getColumnCount(); i < count; i++) {
            Expression expr = expressions.get(i);
            String name = null;
            int type = Value.UNKNOWN;
            if (columnTemplates != null && columnTemplates.length > i) {
                name = columnTemplates[i].getName();
                type = columnTemplates[i].getType();
            }
            if (name == null) {
                name = expr.getAlias();
            }
            name = columnNamer.getColumnName(expr, i, name);
            if (type == Value.UNKNOWN) {
                type = expr.getType();
            }
            long precision = expr.getPrecision();
            int scale = expr.getScale();
            int displaySize = expr.getDisplaySize();
            String[] enumerators = null;
            if (type == Value.ENUM) {
                if (expr instanceof ExpressionColumn) {
                    enumerators = ((ExpressionColumn) expr).getColumn().getEnumerators();
                }
            }
            Column col = new Column(name, type, precision, scale, displaySize, enumerators);
            col.setTable(this, i);
            // Fetch check constraint from view column source
            ExpressionColumn fromColumn = null;
            if (expr instanceof ExpressionColumn) {
                fromColumn = (ExpressionColumn) expr;
            } else if (expr instanceof Alias) {
                Expression aliasExpr = expr.getNonAliasExpression();
                if (aliasExpr instanceof ExpressionColumn) {
                    fromColumn = (ExpressionColumn) aliasExpr;
                }
            }
            if (fromColumn != null) {
                Expression checkExpression = fromColumn.getColumn().getCheckConstraint(session, name);
                if (checkExpression != null) {
                    col.addCheckConstraint(session, checkExpression);
                }
            }
            list.add(col);
        }
        cols = list.toArray(new Column[0]);
        createException = null;
        viewQuery = compiledQuery;
    } catch (DbException e) {
        e.addSQL(getCreateSQL());
        createException = e;
        // table expression query.
        if (isRecursiveQueryExceptionDetected(createException)) {
            this.isRecursiveQueryDetected = true;
        }
        tables = New.arrayList();
        cols = new Column[0];
        if (allowRecursive && columnTemplates != null) {
            cols = new Column[columnTemplates.length];
            for (int i = 0; i < columnTemplates.length; i++) {
                cols[i] = columnTemplates[i].getClone();
            }
            index.setRecursive(true);
            createException = null;
        }
    }
    setColumns(cols);
    if (getId() != 0) {
        addDependentViewToTables();
    }
}
Also used : ColumnNamer(org.h2.util.ColumnNamer) Query(org.h2.command.dml.Query) ExpressionColumn(org.h2.expression.ExpressionColumn) DbException(org.h2.message.DbException) ExpressionColumn(org.h2.expression.ExpressionColumn) Expression(org.h2.expression.Expression) Alias(org.h2.expression.Alias)

Example 18 with ExpressionColumn

use of org.h2.expression.ExpressionColumn in project frostwire by frostwire.

the class FullTextLucene2 method search.

/**
 * Do the search.
 *
 * @param conn the database connection
 * @param text the query
 * @param limit the limit
 * @param offset the offset
 * @param data whether the raw data should be returned
 * @return the result set
 */
protected static ResultSet search(Connection conn, String text, int limit, int offset, boolean data) throws SQLException {
    SimpleResultSet result = createResultSet(data);
    if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
        // this is just to query the result set columns
        return result;
    }
    if (text == null || text.trim().length() == 0) {
        return result;
    }
    try {
        IndexAccess access = getIndexAccess(conn);
        /*## LUCENE2 ##
            access.modifier.flush();
            String path = getIndexPath(conn);
            IndexReader reader = IndexReader.open(path);
            Analyzer analyzer = new StandardAnalyzer();
            Searcher searcher = new IndexSearcher(reader);
            QueryParser parser = new QueryParser(LUCENE_FIELD_DATA, analyzer);
            Query query = parser.parse(text);
            Hits hits = searcher.search(query);
            int max = hits.length();
            if (limit == 0) {
                limit = max;
            }
            for (int i = 0; i < limit && i + offset < max; i++) {
                Document doc = hits.doc(i + offset);
                float score = hits.score(i + offset);
            //*/
        // ## LUCENE3 ##
        // take a reference as the searcher may change
        Searcher searcher = access.searcher;
        // reuse the same analyzer; it's thread-safe;
        // also allows subclasses to control the analyzer used.
        Analyzer analyzer = access.writer.getAnalyzer();
        QueryParser parser = new QueryParser(Version.LUCENE_30, LUCENE_FIELD_DATA, analyzer);
        Query query = parser.parse(text);
        // Lucene 3 insists on a hard limit and will not provide
        // a total hits value. Take at least 100 which is
        // an optimal limit for Lucene as any more
        // will trigger writing results to disk.
        int maxResults = (limit == 0 ? 100 : limit) + offset;
        TopDocs docs = searcher.search(query, maxResults);
        if (limit == 0) {
            limit = docs.totalHits;
        }
        for (int i = 0, len = docs.scoreDocs.length; i < limit && i + offset < docs.totalHits && i + offset < len; i++) {
            ScoreDoc sd = docs.scoreDocs[i + offset];
            Document doc = searcher.doc(sd.doc);
            float score = sd.score;
            // */
            String q = doc.get(LUCENE_FIELD_QUERY);
            if (data) {
                int idx = q.indexOf(" WHERE ");
                JdbcConnection c = (JdbcConnection) conn;
                Session session = (Session) c.getSession();
                Parser p = new Parser(session);
                String tab = q.substring(0, idx);
                ExpressionColumn expr = (ExpressionColumn) p.parseExpression(tab);
                String schemaName = expr.getOriginalTableAliasName();
                String tableName = expr.getColumnName();
                q = q.substring(idx + " WHERE ".length());
                Object[][] columnData = parseKey(conn, q);
                result.addRow(schemaName, tableName, columnData[0], columnData[1], score);
            } else {
                result.addRow(q, score);
            }
        }
    /*## LUCENE2 ##
            // TODO keep it open if possible
            reader.close();
            //*/
    } catch (Exception e) {
        throw convertException(e);
    }
    return result;
}
Also used : SimpleResultSet(org.h2.tools.SimpleResultSet) JdbcConnection(org.h2.jdbc.JdbcConnection) Analyzer(org.apache.lucene.analysis.Analyzer) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) Document(org.apache.lucene.document.Document) IOException(java.io.IOException) Parser(org.h2.command.Parser) QueryParser(org.apache.lucene.queryParser.QueryParser) ExpressionColumn(org.h2.expression.ExpressionColumn) QueryParser(org.apache.lucene.queryParser.QueryParser) Session(org.h2.engine.Session)

Example 19 with ExpressionColumn

use of org.h2.expression.ExpressionColumn in project ignite by apache.

the class GridH2CollocationModel method isAffinityColumn.

/**
 * @param f Table filter.
 * @param expCol Expression column.
 * @param validate Query validation flag.
 * @return {@code true} It it is an affinity column.
 */
private static boolean isAffinityColumn(TableFilter f, ExpressionColumn expCol, boolean validate) {
    Column col = expCol.getColumn();
    if (col == null)
        return false;
    Table t = col.getTable();
    if (t.isView()) {
        Query qry;
        if (f.getIndex() != null)
            qry = getSubQuery(f);
        else
            qry = GridSqlQueryParser.VIEW_QUERY.get((TableView) t);
        return isAffinityColumn(qry, expCol, validate);
    }
    if (t instanceof GridH2Table) {
        if (validate && ((GridH2Table) t).rowDescriptor().context().customAffinityMapper())
            throw customAffinityError(((GridH2Table) t).cacheName());
        IndexColumn affCol = ((GridH2Table) t).getAffinityKeyColumn();
        return affCol != null && col.getColumnId() == affCol.column.getColumnId();
    }
    return false;
}
Also used : Table(org.h2.table.Table) Query(org.h2.command.dml.Query) ExpressionColumn(org.h2.expression.ExpressionColumn) Column(org.h2.table.Column) IndexColumn(org.h2.table.IndexColumn) IndexColumn(org.h2.table.IndexColumn)

Example 20 with ExpressionColumn

use of org.h2.expression.ExpressionColumn in project ignite by apache.

the class GridH2CollocationModel method joinedWithCollocated.

/**
 * @param f Filter.
 * @return Affinity join type.
 */
@SuppressWarnings("ForLoopReplaceableByForEach")
private Affinity joinedWithCollocated(int f) {
    TableFilter tf = childFilters[f];
    GridH2Table tbl = (GridH2Table) tf.getTable();
    if (validate) {
        if (tbl.rowDescriptor().context().customAffinityMapper())
            throw customAffinityError(tbl.cacheName());
        if (F.isEmpty(tf.getIndexConditions())) {
            throw new CacheException("Failed to prepare distributed join query: " + "join condition does not use index [joinedCache=" + tbl.cacheName() + ", plan=" + tf.getSelect().getPlanSQL() + ']');
        }
    }
    IndexColumn affCol = tbl.getAffinityKeyColumn();
    boolean affKeyCondFound = false;
    if (affCol != null) {
        ArrayList<IndexCondition> idxConditions = tf.getIndexConditions();
        int affColId = affCol.column.getColumnId();
        for (int i = 0; i < idxConditions.size(); i++) {
            IndexCondition c = idxConditions.get(i);
            int colId = c.getColumn().getColumnId();
            int cmpType = c.getCompareType();
            if ((cmpType == Comparison.EQUAL || cmpType == Comparison.EQUAL_NULL_SAFE) && (colId == affColId || tbl.rowDescriptor().isKeyColumn(colId)) && c.isEvaluatable()) {
                affKeyCondFound = true;
                Expression exp = c.getExpression();
                exp = exp.getNonAliasExpression();
                if (exp instanceof ExpressionColumn) {
                    ExpressionColumn expCol = (ExpressionColumn) exp;
                    // This is one of our previous joins.
                    TableFilter prevJoin = expCol.getTableFilter();
                    if (prevJoin != null) {
                        GridH2CollocationModel cm = child(indexOf(prevJoin), true);
                        // different affinity columns from different tables.
                        if (cm != null && !cm.view) {
                            Type t = cm.type(true);
                            if (t.isPartitioned() && t.isCollocated() && isAffinityColumn(prevJoin, expCol, validate))
                                return Affinity.COLLOCATED_JOIN;
                        }
                    }
                }
            }
        }
    }
    return affKeyCondFound ? Affinity.HAS_AFFINITY_CONDITION : Affinity.NONE;
}
Also used : TableFilter(org.h2.table.TableFilter) CacheException(javax.cache.CacheException) Expression(org.h2.expression.Expression) IndexCondition(org.h2.index.IndexCondition) IndexColumn(org.h2.table.IndexColumn) ExpressionColumn(org.h2.expression.ExpressionColumn)

Aggregations

ExpressionColumn (org.h2.expression.ExpressionColumn)21 Column (org.h2.table.Column)18 Expression (org.h2.expression.Expression)17 ValueExpression (org.h2.expression.ValueExpression)9 IndexColumn (org.h2.table.IndexColumn)9 TableFilter (org.h2.table.TableFilter)8 Query (org.h2.command.dml.Query)6 Comparison (org.h2.expression.Comparison)6 ConditionAndOr (org.h2.expression.ConditionAndOr)6 ValueString (org.h2.value.ValueString)6 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)4 Database (org.h2.engine.Database)4 Index (org.h2.index.Index)4 Value (org.h2.value.Value)4 Parser (org.h2.command.Parser)3 LocalResult (org.h2.result.LocalResult)3 Table (org.h2.table.Table)3 IOException (java.io.IOException)2 SQLException (java.sql.SQLException)2 CacheException (javax.cache.CacheException)2