Search in sources :

Example 76 with Alias

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

the class H2Utils method generateFieldsQueryString.

/**
 * Generate SqlFieldsQuery string from SqlQuery.
 *
 * @param qry Query string.
 * @param tableAlias table alias.
 * @param tbl Table to use.
 * @return Prepared statement.
 * @throws IgniteCheckedException In case of error.
 */
public static String generateFieldsQueryString(String qry, String tableAlias, H2TableDescriptor tbl) throws IgniteCheckedException {
    assert tbl != null;
    final String qry0 = qry;
    String t = tbl.fullTableName();
    String from = " ";
    qry = qry.trim();
    String upper = qry.toUpperCase();
    if (upper.startsWith("SELECT")) {
        qry = qry.substring(6).trim();
        final int star = qry.indexOf('*');
        if (star == 0)
            qry = qry.substring(1).trim();
        else if (star > 0) {
            if (F.eq('.', qry.charAt(star - 1))) {
                t = qry.substring(0, star - 1);
                qry = qry.substring(star + 1).trim();
            } else
                throw new IgniteCheckedException("Invalid query (missing alias before asterisk): " + qry0);
        } else
            throw new IgniteCheckedException("Only queries starting with 'SELECT *' and 'SELECT alias.*' " + "are supported (rewrite your query or use SqlFieldsQuery instead): " + qry0);
        upper = qry.toUpperCase();
    }
    if (!upper.startsWith("FROM"))
        from = " FROM " + t + (tableAlias != null ? " as " + tableAlias : "") + (upper.startsWith("WHERE") || upper.startsWith("ORDER") || upper.startsWith("LIMIT") ? " " : " WHERE ");
    if (tableAlias != null)
        t = tableAlias;
    qry = "SELECT " + t + "." + KEY_FIELD_NAME + ", " + t + "." + VAL_FIELD_NAME + from + qry;
    return qry;
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) ValueString(org.h2.value.ValueString)

Example 77 with Alias

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

the class GridSqlQueryParser method parseExpression0.

/**
 * @param expression Expression.
 * @param calcTypes Calculate types for all the expressions.
 * @return Parsed expression.
 */
private GridSqlElement parseExpression0(Expression expression, boolean calcTypes) {
    if (expression instanceof ExpressionColumn) {
        ExpressionColumn expCol = (ExpressionColumn) expression;
        return new GridSqlColumn(expCol.getColumn(), parseTableFilter(expCol.getTableFilter()), SCHEMA_NAME.get(expCol), expCol.getOriginalTableAliasName(), expCol.getColumnName());
    }
    if (expression instanceof Alias)
        return new GridSqlAlias(expression.getAlias(), parseExpression(expression.getNonAliasExpression(), calcTypes), true);
    if (expression instanceof ValueExpression)
        // == comparison is legit, see ValueExpression#getSQL()
        return expression == ValueExpression.getDefault() ? GridSqlKeyword.DEFAULT : new GridSqlConst(expression.getValue(null));
    if (expression instanceof Operation) {
        Operation operation = (Operation) expression;
        Operation.OpType type = OPERATION_TYPE.get(operation);
        if (type == Operation.OpType.NEGATE) {
            assert OPERATION_RIGHT.get(operation) == null;
            return new GridSqlOperation(GridSqlOperationType.NEGATE, parseExpression(OPERATION_LEFT.get(operation), calcTypes));
        }
        return new GridSqlOperation(mapOperationType(type), parseExpression(OPERATION_LEFT.get(operation), calcTypes), parseExpression(OPERATION_RIGHT.get(operation), calcTypes));
    }
    if (expression instanceof Comparison) {
        Comparison cmp = (Comparison) expression;
        GridSqlOperationType opType = COMPARISON_TYPES[COMPARISON_TYPE.get(cmp)];
        assert opType != null : COMPARISON_TYPE.get(cmp);
        Expression leftExp = COMPARISON_LEFT.get(cmp);
        GridSqlElement left = parseExpression(leftExp, calcTypes);
        if (opType.childrenCount() == 1)
            return new GridSqlOperation(opType, left);
        Expression rightExp = COMPARISON_RIGHT.get(cmp);
        GridSqlElement right = parseExpression(rightExp, calcTypes);
        return new GridSqlOperation(opType, left, right);
    }
    if (expression instanceof ConditionNot)
        return new GridSqlOperation(NOT, parseExpression(expression.getNotIfPossible(null), calcTypes));
    if (expression instanceof ConditionAndOr) {
        ConditionAndOr andOr = (ConditionAndOr) expression;
        int type = ANDOR_TYPE.get(andOr);
        assert type == ConditionAndOr.AND || type == ConditionAndOr.OR;
        return new GridSqlOperation(type == ConditionAndOr.AND ? AND : OR, parseExpression(ANDOR_LEFT.get(andOr), calcTypes), parseExpression(ANDOR_RIGHT.get(andOr), calcTypes));
    }
    if (expression instanceof Subquery) {
        Query qry = ((Subquery) expression).getQuery();
        return parseQueryExpression(qry);
    }
    if (expression instanceof ConditionIn) {
        GridSqlOperation res = new GridSqlOperation(IN);
        res.addChild(parseExpression(LEFT_CI.get((ConditionIn) expression), calcTypes));
        List<Expression> vals = VALUE_LIST_CI.get((ConditionIn) expression);
        for (Expression val : vals) res.addChild(parseExpression(val, calcTypes));
        return res;
    }
    if (expression instanceof ConditionInConstantSet) {
        GridSqlOperation res = new GridSqlOperation(IN);
        res.addChild(parseExpression(LEFT_CICS.get((ConditionInConstantSet) expression), calcTypes));
        List<Expression> vals = VALUE_LIST_CICS.get((ConditionInConstantSet) expression);
        for (Expression val : vals) res.addChild(parseExpression(val, calcTypes));
        return res;
    }
    if (expression instanceof ConditionInSelect) {
        GridSqlOperation res = new GridSqlOperation(IN);
        boolean all = ALL.get((ConditionInSelect) expression);
        int compareType = COMPARE_TYPE.get((ConditionInSelect) expression);
        assert0(!all, expression);
        assert0(compareType == Comparison.EQUAL, expression);
        res.addChild(parseExpression(LEFT_CIS.get((ConditionInSelect) expression), calcTypes));
        Query qry = QUERY_IN.get((ConditionInSelect) expression);
        res.addChild(parseQueryExpression(qry));
        return res;
    }
    if (expression instanceof CompareLike) {
        assert0(ESCAPE.get((CompareLike) expression) == null, expression);
        boolean regexp = REGEXP_CL.get((CompareLike) expression);
        return new GridSqlOperation(regexp ? REGEXP : LIKE, parseExpression(LEFT.get((CompareLike) expression), calcTypes), parseExpression(RIGHT.get((CompareLike) expression), calcTypes));
    }
    if (expression instanceof Function) {
        Function f = (Function) expression;
        GridSqlFunction res = new GridSqlFunction(null, f.getName());
        if (f.getArgs() != null) {
            if (f.getFunctionType() == Function.TABLE || f.getFunctionType() == Function.TABLE_DISTINCT) {
                Column[] cols = FUNC_TBL_COLS.get((TableFunction) f);
                Expression[] args = f.getArgs();
                assert cols.length == args.length;
                for (int i = 0; i < cols.length; i++) {
                    GridSqlElement arg = parseExpression(args[i], calcTypes);
                    GridSqlAlias alias = new GridSqlAlias(cols[i].getName(), arg, false);
                    alias.resultType(fromColumn(cols[i]));
                    res.addChild(alias);
                }
            } else {
                for (Expression arg : f.getArgs()) {
                    if (arg == null) {
                        if (f.getFunctionType() != Function.CASE)
                            throw new IllegalStateException("Function type with null arg: " + f.getFunctionType());
                        res.addChild(GridSqlPlaceholder.EMPTY);
                    } else
                        res.addChild(parseExpression(arg, calcTypes));
                }
            }
        }
        if (f.getFunctionType() == Function.CAST || f.getFunctionType() == Function.CONVERT) {
            checkTypeSupported(f.getType(), "[expSql=" + f.getSQL() + ']');
            res.resultType(fromExpression(f));
        }
        return res;
    }
    if (expression instanceof JavaFunction) {
        JavaFunction f = (JavaFunction) expression;
        FunctionAlias alias = FUNC_ALIAS.get(f);
        GridSqlFunction res = new GridSqlFunction(alias.getSchema().getName(), f.getName());
        if (f.getArgs() != null) {
            for (Expression arg : f.getArgs()) res.addChild(parseExpression(arg, calcTypes));
        }
        return res;
    }
    if (expression instanceof Parameter)
        return new GridSqlParameter(((Parameter) expression).getIndex());
    if (expression instanceof Aggregate) {
        Aggregate.AggregateType type = TYPE.get((Aggregate) expression);
        if (GridSqlAggregateFunction.isValidType(type)) {
            GridSqlAggregateFunction res = new GridSqlAggregateFunction(DISTINCT.get((Aggregate) expression), type);
            Expression on = ON.get((Aggregate) expression);
            if (on != null)
                res.addChild(parseExpression(on, calcTypes));
            ArrayList<SelectOrderBy> orders = GROUP_CONCAT_ORDER_LIST.get((Aggregate) expression);
            if (!F.isEmpty(orders))
                parseGroupConcatOrder(res, orders, calcTypes);
            Expression separator = GROUP_CONCAT_SEPARATOR.get((Aggregate) expression);
            if (separator != null)
                res.setGroupConcatSeparator(parseExpression(separator, calcTypes));
            return res;
        }
    }
    if (expression instanceof ExpressionList) {
        Expression[] exprs = EXPR_LIST.get((ExpressionList) expression);
        GridSqlArray res = new GridSqlArray(exprs.length);
        for (Expression expr : exprs) res.addChild(parseExpression(expr, calcTypes));
        return res;
    }
    if (expression instanceof ConditionExists) {
        Query qry = QUERY_EXISTS.get((ConditionExists) expression);
        GridSqlOperation res = new GridSqlOperation(EXISTS);
        res.addChild(parseQueryExpression(qry));
        return res;
    }
    throw new IgniteException("Unsupported expression: " + expression + " [type=" + expression.getClass().getSimpleName() + ']');
}
Also used : SelectOrderBy(org.h2.command.dml.SelectOrderBy) ConditionNot(org.h2.expression.ConditionNot) Query(org.h2.command.dml.Query) JavaFunction(org.h2.expression.JavaFunction) Operation(org.h2.expression.Operation) ConditionAndOr(org.h2.expression.ConditionAndOr) Subquery(org.h2.expression.Subquery) ExpressionColumn(org.h2.expression.ExpressionColumn) Function(org.h2.expression.Function) TableFunction(org.h2.expression.TableFunction) JavaFunction(org.h2.expression.JavaFunction) Comparison(org.h2.expression.Comparison) GridSqlType.fromColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) IgniteException(org.apache.ignite.IgniteException) ExpressionList(org.h2.expression.ExpressionList) FunctionAlias(org.h2.engine.FunctionAlias) ConditionIn(org.h2.expression.ConditionIn) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) CompareLike(org.h2.expression.CompareLike) ConditionInConstantSet(org.h2.expression.ConditionInConstantSet) ConditionInSelect(org.h2.expression.ConditionInSelect) Expression(org.h2.expression.Expression) GridSqlType.fromExpression(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromExpression) ValueExpression(org.h2.expression.ValueExpression) FunctionAlias(org.h2.engine.FunctionAlias) Alias(org.h2.expression.Alias) ValueExpression(org.h2.expression.ValueExpression) Parameter(org.h2.expression.Parameter) Aggregate(org.h2.expression.Aggregate) ConditionExists(org.h2.expression.ConditionExists)

Example 78 with Alias

use of org.h2.expression.Alias in project elastic-core-maven by OrdinaryDude.

the class FullTextTrigger method init.

/**
 * Initialize the fulltext support for a new database
 *
 * This method should be called from NxtDbVersion when performing the database version update
 * that enables NRS fulltext search support
 */
public static void init() {
    String ourClassName = FullTextTrigger.class.getName();
    try (Connection conn = Db.db.getConnection();
        Statement stmt = conn.createStatement();
        Statement qstmt = conn.createStatement()) {
        // 
        // Check if we have already been initialized.
        // 
        boolean alreadyInitialized = true;
        boolean triggersExist = false;
        try (ResultSet rs = qstmt.executeQuery("SELECT JAVA_CLASS FROM INFORMATION_SCHEMA.TRIGGERS " + "WHERE SUBSTRING(TRIGGER_NAME, 0, 4) = 'FTL_'")) {
            while (rs.next()) {
                triggersExist = true;
                if (!rs.getString(1).startsWith(ourClassName)) {
                    alreadyInitialized = false;
                }
            }
        }
        if (triggersExist && alreadyInitialized) {
            Logger.logInfoMessage("NRS fulltext support is already initialized");
            return;
        }
        // 
        // We need to delete an existing Lucene index since the V3 file format is not compatible with V5
        // 
        getIndexPath(conn);
        removeIndexFiles(conn);
        // 
        // Drop the H2 Lucene V3 function aliases
        // 
        stmt.execute("DROP ALIAS IF EXISTS FTL_INIT");
        stmt.execute("DROP ALIAS IF EXISTS FTL_CREATE_INDEX");
        stmt.execute("DROP ALIAS IF EXISTS FTL_DROP_INDEX");
        stmt.execute("DROP ALIAS IF EXISTS FTL_DROP_ALL");
        stmt.execute("DROP ALIAS IF EXISTS FTL_REINDEX");
        stmt.execute("DROP ALIAS IF EXISTS FTL_SEARCH");
        stmt.execute("DROP ALIAS IF EXISTS FTL_SEARCH_DATA");
        Logger.logInfoMessage("H2 fulltext function aliases dropped");
        // 
        // Create our schema and table
        // 
        stmt.execute("CREATE SCHEMA IF NOT EXISTS FTL");
        stmt.execute("CREATE TABLE IF NOT EXISTS FTL.INDEXES " + "(SCHEMA VARCHAR, TABLE VARCHAR, COLUMNS VARCHAR, PRIMARY KEY(SCHEMA, TABLE))");
        Logger.logInfoMessage("NRS fulltext schema created");
        // 
        try (ResultSet rs = qstmt.executeQuery("SELECT * FROM FTL.INDEXES")) {
            while (rs.next()) {
                String schema = rs.getString("SCHEMA");
                String table = rs.getString("TABLE");
                stmt.execute("DROP TRIGGER IF EXISTS FTL_" + table);
                stmt.execute(String.format("CREATE TRIGGER FTL_%s AFTER INSERT,UPDATE,DELETE ON %s.%s " + "FOR EACH ROW CALL \"%s\"", table, schema, table, ourClassName));
            }
        }
        // 
        // Rebuild the Lucene index since the Lucene V3 index is not compatible with Lucene V5
        // 
        reindex(conn);
        // 
        // Create our function aliases
        // 
        stmt.execute("CREATE ALIAS FTL_CREATE_INDEX FOR \"" + ourClassName + ".createIndex\"");
        stmt.execute("CREATE ALIAS FTL_DROP_INDEX FOR \"" + ourClassName + ".dropIndex\"");
        stmt.execute("CREATE ALIAS FTL_SEARCH NOBUFFER FOR \"" + ourClassName + ".search\"");
        Logger.logInfoMessage("NRS fulltext aliases created");
    } catch (SQLException exc) {
        Logger.logErrorMessage("Unable to initialize NRS fulltext search support", exc);
        throw new RuntimeException(exc.toString(), exc);
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 79 with Alias

use of org.h2.expression.Alias in project elastic-core-maven by OrdinaryDude.

the class FullTextTrigger method init.

/**
 * Initialize the trigger (Trigger interface)
 *
 * @param   conn                Database connection
 * @param   schema              Database schema name
 * @param   trigger             Database trigger name
 * @param   table               Database table name
 * @param   before              TRUE if trigger is called before database operation
 * @param   type                Trigger type
 * @throws  SQLException        A SQL error occurred
 */
@Override
public void init(Connection conn, String schema, String trigger, String table, boolean before, int type) throws SQLException {
    // 
    if (!isActive || table.contains("_COPY_")) {
        return;
    }
    // 
    // Access the Lucene index
    // 
    // We need to get the access just once, either in a trigger or in a function alias
    // 
    getIndexAccess(conn);
    // 
    // Get table and index information
    // 
    tableName = schema + "." + table;
    try (Statement stmt = conn.createStatement()) {
        // 
        try (ResultSet rs = stmt.executeQuery("SHOW COLUMNS FROM " + table + " FROM " + schema)) {
            int index = 0;
            while (rs.next()) {
                String columnName = rs.getString("FIELD");
                String columnType = rs.getString("TYPE");
                columnType = columnType.substring(0, columnType.indexOf('('));
                columnNames.add(columnName);
                columnTypes.add(columnType);
                if (columnName.equals("DB_ID")) {
                    dbColumn = index;
                }
                index++;
            }
        }
        if (dbColumn < 0) {
            Logger.logErrorMessage("DB_ID column not found for table " + tableName);
            return;
        }
        // 
        try (ResultSet rs = stmt.executeQuery(String.format("SELECT COLUMNS FROM FTL.INDEXES WHERE SCHEMA = '%s' AND TABLE = '%s'", schema, table))) {
            if (rs.next()) {
                String[] columns = rs.getString(1).split(",");
                for (String column : columns) {
                    int pos = columnNames.indexOf(column);
                    if (pos >= 0) {
                        if (columnTypes.get(pos).equals("VARCHAR")) {
                            indexColumns.add(pos);
                        } else {
                            Logger.logErrorMessage("Indexed column " + column + " in table " + tableName + " is not a string");
                        }
                    } else {
                        Logger.logErrorMessage("Indexed column " + column + " not found in table " + tableName);
                    }
                }
            }
        }
        if (indexColumns.isEmpty()) {
            Logger.logErrorMessage("No indexed columns found for table " + tableName);
            return;
        }
        // 
        // Trigger is enabled
        // 
        isEnabled = true;
        indexTriggers.put(tableName, this);
    } catch (SQLException exc) {
        Logger.logErrorMessage("Unable to get table information", exc);
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 80 with Alias

use of org.h2.expression.Alias in project siena by mandubian.

the class FullText method init.

/**
 * Initializes full text search functionality for this database. This adds
 * the following Java functions to the database:
 * <ul>
 * <li>FT_CREATE_INDEX(schemaNameString, tableNameString,
 * columnListString)</li>
 * <li>FT_SEARCH(queryString, limitInt, offsetInt): result set</li>
 * <li>FT_REINDEX()</li>
 * <li>FT_DROP_ALL()</li>
 * </ul>
 * It also adds a schema FT to the database where bookkeeping information
 * is stored. This function may be called from a Java application, or by
 * using the SQL statements:
 *
 * <pre>
 * CREATE ALIAS IF NOT EXISTS FT_INIT FOR
 *      &quot;org.h2.fulltext.FullText.init&quot;;
 * CALL FT_INIT();
 * </pre>
 *
 * @param conn the connection
 */
public static void init(Connection conn) throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("CREATE SCHEMA IF NOT EXISTS " + SCHEMA);
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".FT_INDEXES(ID INT AUTO_INCREMENT PRIMARY KEY, SCHEMA VARCHAR, TABLE VARCHAR, COLUMNS VARCHAR, UNIQUE(SCHEMA, TABLE))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".WORDS(ID INT AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR, UNIQUE(NAME))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".ROWS(ID IDENTITY, HASH INT, INDEXID INT, \"KEY\" VARCHAR, UNIQUE(HASH, INDEXID, \"KEY\"))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".MAP(ROWID INT, WORDID INT, PRIMARY KEY(WORDID, ROWID))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".IGNORELIST(LIST VARCHAR)");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_CREATE_INDEX FOR \"" + FullText.class.getName() + ".createIndex\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_INDEX FOR \"" + FullText.class.getName() + ".dropIndex\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH FOR \"" + FullText.class.getName() + ".search\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH_DATA FOR \"" + FullText.class.getName() + ".searchData\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_REINDEX FOR \"" + FullText.class.getName() + ".reindex\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_ALL FOR \"" + FullText.class.getName() + ".dropAll\"");
    FullTextSettings setting = FullTextSettings.getInstance(conn);
    ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".IGNORELIST");
    while (rs.next()) {
        String commaSeparatedList = rs.getString(1);
        setIgnoreList(setting, commaSeparatedList);
    }
    rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".WORDS");
    HashMap<String, Integer> map = setting.getWordList();
    while (rs.next()) {
        String word = rs.getString("NAME");
        int id = rs.getInt("ID");
        word = setting.convertWord(word);
        if (word != null) {
            map.put(word, id);
        }
    }
    setting.setInitialized(true);
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Aggregations

ResultSet (java.sql.ResultSet)38 Statement (java.sql.Statement)38 Connection (java.sql.Connection)31 SimpleResultSet (org.h2.tools.SimpleResultSet)31 PreparedStatement (java.sql.PreparedStatement)28 CallableStatement (java.sql.CallableStatement)18 ValueString (org.h2.value.ValueString)17 SQLException (java.sql.SQLException)11 Column (org.h2.table.Column)10 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)6 Expression (org.h2.expression.Expression)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 GridSqlAlias (org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias)5 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)4 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)4 GridSqlSelect (org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)4 GridSqlTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable)4 Session (org.h2.engine.Session)4 ValueExpression (org.h2.expression.ValueExpression)4