Search in sources :

Example 11 with ExpressionColumn

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

the class TableFunction method getTable.

private ValueResultSet getTable(Session session, Expression[] argList, boolean onlyColumnList, boolean distinctRows) {
    int len = columnList.length;
    Expression[] header = new Expression[len];
    Database db = session.getDatabase();
    for (int i = 0; i < len; i++) {
        Column c = columnList[i];
        ExpressionColumn col = new ExpressionColumn(db, c);
        header[i] = col;
    }
    LocalResult result = new LocalResult(session, header, len);
    if (distinctRows) {
        result.setDistinct();
    }
    if (!onlyColumnList) {
        Value[][] list = new Value[len][];
        int rows = 0;
        for (int i = 0; i < len; i++) {
            Value v = argList[i].getValue(session);
            if (v == ValueNull.INSTANCE) {
                list[i] = new Value[0];
            } else {
                ValueArray array = (ValueArray) v.convertTo(Value.ARRAY);
                Value[] l = array.getList();
                list[i] = l;
                rows = Math.max(rows, l.length);
            }
        }
        for (int row = 0; row < rows; row++) {
            Value[] r = new Value[len];
            for (int j = 0; j < len; j++) {
                Value[] l = list[j];
                Value v;
                if (l.length <= row) {
                    v = ValueNull.INSTANCE;
                } else {
                    Column c = columnList[j];
                    v = l[row];
                    v = c.convert(v);
                    v = v.convertPrecision(c.getPrecision(), false);
                    v = v.convertScale(true, c.getScale());
                }
                r[j] = v;
            }
            result.addRow(r);
        }
    }
    result.done();
    return ValueResultSet.get(getSimpleResultSet(result, Integer.MAX_VALUE));
}
Also used : LocalResult(org.h2.result.LocalResult) Column(org.h2.table.Column) Database(org.h2.engine.Database) Value(org.h2.value.Value) ValueArray(org.h2.value.ValueArray)

Example 12 with ExpressionColumn

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

the class FullText method addColumnData.

private static void addColumnData(ArrayList<String> columns, ArrayList<String> data, Expression expr) {
    if (expr instanceof ConditionAndOr) {
        ConditionAndOr and = (ConditionAndOr) expr;
        Expression left = and.getExpression(true);
        Expression right = and.getExpression(false);
        addColumnData(columns, data, left);
        addColumnData(columns, data, right);
    } else {
        Comparison comp = (Comparison) expr;
        ExpressionColumn ec = (ExpressionColumn) comp.getExpression(true);
        ValueExpression ev = (ValueExpression) comp.getExpression(false);
        String columnName = ec.getColumnName();
        columns.add(columnName);
        if (ev == null) {
            data.add(null);
        } else {
            data.add(ev.getValue(null).getString());
        }
    }
}
Also used : ValueExpression(org.h2.expression.ValueExpression) Expression(org.h2.expression.Expression) Comparison(org.h2.expression.Comparison) ValueExpression(org.h2.expression.ValueExpression) ConditionAndOr(org.h2.expression.ConditionAndOr) ExpressionColumn(org.h2.expression.ExpressionColumn)

Example 13 with ExpressionColumn

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

the class FullTextLucene 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);
        // take a reference as the searcher may change
        IndexSearcher searcher = access.getSearcher();
        try {
            // 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);
                }
            }
        } finally {
            access.returnSearcher(searcher);
        }
    } catch (Exception e) {
        throw convertException(e);
    }
    return result;
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) SimpleResultSet(org.h2.tools.SimpleResultSet) Query(org.apache.lucene.search.Query) JdbcConnection(org.h2.jdbc.JdbcConnection) Analyzer(org.apache.lucene.analysis.Analyzer) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) Document(org.apache.lucene.document.Document) SQLException(java.sql.SQLException) IOException(java.io.IOException) ScoreDoc(org.apache.lucene.search.ScoreDoc) Parser(org.h2.command.Parser) QueryParser(org.apache.lucene.queryParser.QueryParser) ExpressionColumn(org.h2.expression.ExpressionColumn) TopDocs(org.apache.lucene.search.TopDocs) QueryParser(org.apache.lucene.queryParser.QueryParser) Session(org.h2.engine.Session)

Example 14 with ExpressionColumn

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

the class AggregateDataMedian method getMedianColumnIndex.

/**
 * Get the index (if any) for the column specified in the median aggregate.
 *
 * @param on the expression (usually a column expression)
 * @return the index, or null
 */
static Index getMedianColumnIndex(Expression on) {
    if (on instanceof ExpressionColumn) {
        ExpressionColumn col = (ExpressionColumn) on;
        Column column = col.getColumn();
        TableFilter filter = col.getTableFilter();
        if (filter != null) {
            Table table = filter.getTable();
            ArrayList<Index> indexes = table.getIndexes();
            Index result = null;
            if (indexes != null) {
                boolean nullable = column.isNullable();
                for (int i = 1, size = indexes.size(); i < size; i++) {
                    Index index = indexes.get(i);
                    if (!index.canFindNext()) {
                        continue;
                    }
                    if (!index.isFirstColumn(column)) {
                        continue;
                    }
                    // Prefer index without nulls last for nullable columns
                    if (result == null || result.getColumns().length > index.getColumns().length || nullable && isNullsLast(result) && !isNullsLast(index)) {
                        result = index;
                    }
                }
            }
            return result;
        }
    }
    return null;
}
Also used : Table(org.h2.table.Table) Column(org.h2.table.Column) IndexColumn(org.h2.table.IndexColumn) TableFilter(org.h2.table.TableFilter) Index(org.h2.index.Index)

Example 15 with ExpressionColumn

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

the class AggregateDataMedian method getResultFromIndex.

/**
 * Get the result from the index.
 *
 * @param session the session
 * @param on the expression
 * @param dataType the data type
 * @return the result
 */
static Value getResultFromIndex(Session session, Expression on, int dataType) {
    Index index = getMedianColumnIndex(on);
    long count = index.getRowCount(session);
    if (count == 0) {
        return ValueNull.INSTANCE;
    }
    Cursor cursor = index.find(session, null, null);
    cursor.next();
    int columnId = index.getColumns()[0].getColumnId();
    ExpressionColumn expr = (ExpressionColumn) on;
    if (expr.getColumn().isNullable()) {
        boolean hasNulls = false;
        SearchRow row;
        // will be used to read values.
        while (count > 0) {
            row = cursor.getSearchRow();
            if (row == null) {
                return ValueNull.INSTANCE;
            }
            if (row.getValue(columnId) == ValueNull.INSTANCE) {
                count--;
                cursor.next();
                hasNulls = true;
            } else {
                break;
            }
        }
        if (count == 0) {
            return ValueNull.INSTANCE;
        }
        // cursor to count nulls at the end.
        if (!hasNulls && isNullsLast(index)) {
            TableFilter tableFilter = expr.getTableFilter();
            SearchRow check = tableFilter.getTable().getTemplateSimpleRow(true);
            check.setValue(columnId, ValueNull.INSTANCE);
            Cursor nullsCursor = index.find(session, check, check);
            while (nullsCursor.next()) {
                count--;
            }
            if (count <= 0) {
                return ValueNull.INSTANCE;
            }
        }
    }
    long skip = (count - 1) / 2;
    for (int i = 0; i < skip; i++) {
        cursor.next();
    }
    SearchRow row = cursor.getSearchRow();
    if (row == null) {
        return ValueNull.INSTANCE;
    }
    Value v = row.getValue(columnId);
    if (v == ValueNull.INSTANCE) {
        return v;
    }
    if ((count & 1) == 0) {
        cursor.next();
        row = cursor.getSearchRow();
        if (row == null) {
            return v;
        }
        Value v2 = row.getValue(columnId);
        if (v2 == ValueNull.INSTANCE) {
            return v;
        }
        return getMedian(v, v2, dataType, session.getDatabase().getCompareMode());
    }
    return v;
}
Also used : TableFilter(org.h2.table.TableFilter) Value(org.h2.value.Value) Index(org.h2.index.Index) Cursor(org.h2.index.Cursor) SearchRow(org.h2.result.SearchRow)

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