Search in sources :

Example 91 with Call

use of org.h2.command.dml.Call in project h2database by h2database.

the class TestRunscript method testCancelScript.

private void testCancelScript() throws Exception {
    if (config.travis) {
        // fails regularly under Travis, not sure why
        return;
    }
    deleteDb("runscript");
    Connection conn;
    conn = getConnection("runscript");
    final Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key) as " + "select x from system_range(1, 20000)");
    stat.execute("script simple drop to '" + getBaseDir() + "/backup.sql'");
    stat.execute("set throttle 1000");
    // need to wait a bit (throttle is only used every 50 ms)
    Thread.sleep(200);
    final String dir = getBaseDir();
    Task task;
    task = new Task() {

        @Override
        public void call() throws SQLException {
            stat.execute("script simple drop to '" + dir + "/backup2.sql'");
        }
    };
    task.execute();
    Thread.sleep(200);
    stat.cancel();
    SQLException e = (SQLException) task.getException();
    assertNotNull(e);
    assertEquals(ErrorCode.STATEMENT_WAS_CANCELED, e.getErrorCode());
    stat.execute("set throttle 1000");
    // need to wait a bit (throttle is only used every 50 ms)
    Thread.sleep(100);
    task = new Task() {

        @Override
        public void call() throws SQLException {
            stat.execute("runscript from '" + dir + "/backup.sql'");
        }
    };
    task.execute();
    Thread.sleep(200);
    stat.cancel();
    e = (SQLException) task.getException();
    assertNotNull(e);
    assertEquals(ErrorCode.STATEMENT_WAS_CANCELED, e.getErrorCode());
    conn.close();
    FileUtils.delete(getBaseDir() + "/backup.sql");
    FileUtils.delete(getBaseDir() + "/backup2.sql");
}
Also used : Task(org.h2.util.Task) SQLException(java.sql.SQLException) Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) Connection(java.sql.Connection)

Example 92 with Call

use of org.h2.command.dml.Call 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)

Example 93 with Call

use of org.h2.command.dml.Call in project ignite by apache.

the class H2DynamicTableSelfTest method testSqlFlagCompatibilityCheck.

/**
 * Test that attempting to start a node that has a cache with the name already present in the grid and whose
 * SQL flag does not match that of cache with the same name that is already started, yields an error.
 * @throws Exception if failed.
 */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public void testSqlFlagCompatibilityCheck() throws Exception {
    execute("CREATE TABLE \"Person\" (\"id\" int, \"city\" varchar, \"name\" varchar, \"surname\" varchar, " + "\"age\" int, PRIMARY KEY (\"id\", \"city\")) WITH \"template=cache\"");
    GridTestUtils.assertThrows(null, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            String cacheName = cacheName("Person");
            Ignition.start(clientConfiguration(5).setCacheConfiguration(new CacheConfiguration(cacheName)));
            return null;
        }
    }, IgniteException.class, "Cache configuration mismatch (local cache was created via Ignite API, while " + "remote cache was created via CREATE TABLE): SQL_PUBLIC_Person");
}
Also used : BinaryObject(org.apache.ignite.binary.BinaryObject) IgniteException(org.apache.ignite.IgniteException) SQLException(java.sql.SQLException) CacheException(javax.cache.CacheException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration)

Example 94 with Call

use of org.h2.command.dml.Call 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 95 with Call

use of org.h2.command.dml.Call in project h2database by h2database.

the class Query method initOrder.

/**
 * Initialize the order by list. This call may extend the expressions list.
 *
 * @param session the session
 * @param expressions the select list expressions
 * @param expressionSQL the select list SQL snippets
 * @param orderList the order by list
 * @param visible the number of visible columns in the select list
 * @param mustBeInResult all order by expressions must be in the select list
 * @param filters the table filters
 */
static void initOrder(Session session, ArrayList<Expression> expressions, ArrayList<String> expressionSQL, ArrayList<SelectOrderBy> orderList, int visible, boolean mustBeInResult, ArrayList<TableFilter> filters) {
    Database db = session.getDatabase();
    for (SelectOrderBy o : orderList) {
        Expression e = o.expression;
        if (e == null) {
            continue;
        }
        // special case: SELECT 1 AS A FROM DUAL ORDER BY A
        // (oracle supports it, but only in order by, not in group by and
        // not in having):
        // SELECT 1 AS A FROM DUAL ORDER BY -A
        boolean isAlias = false;
        int idx = expressions.size();
        if (e instanceof ExpressionColumn) {
            // order by expression
            ExpressionColumn exprCol = (ExpressionColumn) e;
            String tableAlias = exprCol.getOriginalTableAliasName();
            String col = exprCol.getOriginalColumnName();
            for (int j = 0; j < visible; j++) {
                boolean found = false;
                Expression ec = expressions.get(j);
                if (ec instanceof ExpressionColumn) {
                    // select expression
                    ExpressionColumn c = (ExpressionColumn) ec;
                    found = db.equalsIdentifiers(col, c.getColumnName());
                    if (found && tableAlias != null) {
                        String ca = c.getOriginalTableAliasName();
                        if (ca == null) {
                            found = false;
                            if (filters != null) {
                                // select id from test order by test.id
                                for (TableFilter f : filters) {
                                    if (db.equalsIdentifiers(f.getTableAlias(), tableAlias)) {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                        } else {
                            found = db.equalsIdentifiers(ca, tableAlias);
                        }
                    }
                } else if (!(ec instanceof Alias)) {
                    continue;
                } else if (tableAlias == null && db.equalsIdentifiers(col, ec.getAlias())) {
                    found = true;
                } else {
                    Expression ec2 = ec.getNonAliasExpression();
                    if (ec2 instanceof ExpressionColumn) {
                        ExpressionColumn c2 = (ExpressionColumn) ec2;
                        String ta = exprCol.getSQL();
                        String tb = c2.getSQL();
                        String s2 = c2.getColumnName();
                        found = db.equalsIdentifiers(col, s2);
                        if (!db.equalsIdentifiers(ta, tb)) {
                            found = false;
                        }
                    }
                }
                if (found) {
                    idx = j;
                    isAlias = true;
                    break;
                }
            }
        } else {
            String s = e.getSQL();
            if (expressionSQL != null) {
                for (int j = 0, size = expressionSQL.size(); j < size; j++) {
                    String s2 = expressionSQL.get(j);
                    if (db.equalsIdentifiers(s2, s)) {
                        idx = j;
                        isAlias = true;
                        break;
                    }
                }
            }
        }
        if (!isAlias) {
            if (mustBeInResult) {
                throw DbException.get(ErrorCode.ORDER_BY_NOT_IN_RESULT, e.getSQL());
            }
            expressions.add(e);
            String sql = e.getSQL();
            expressionSQL.add(sql);
        }
        o.columnIndexExpr = ValueExpression.get(ValueInt.get(idx + 1));
        o.expression = expressions.get(idx).getNonAliasExpression();
    }
}
Also used : ValueExpression(org.h2.expression.ValueExpression) Expression(org.h2.expression.Expression) TableFilter(org.h2.table.TableFilter) Alias(org.h2.expression.Alias) Database(org.h2.engine.Database) ExpressionColumn(org.h2.expression.ExpressionColumn)

Aggregations

Task (org.h2.util.Task)69 Connection (java.sql.Connection)68 Statement (java.sql.Statement)64 PreparedStatement (java.sql.PreparedStatement)60 ResultSet (java.sql.ResultSet)48 SQLException (java.sql.SQLException)42 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)24 SimpleResultSet (org.h2.tools.SimpleResultSet)24 MVStore (org.h2.mvstore.MVStore)20 Random (java.util.Random)19 JdbcConnection (org.h2.jdbc.JdbcConnection)19 CallableStatement (java.sql.CallableStatement)14 DbException (org.h2.message.DbException)13 IOException (java.io.IOException)10 JdbcSQLException (org.h2.jdbc.JdbcSQLException)7 ArrayList (java.util.ArrayList)6 Expression (org.h2.expression.Expression)6 ValueString (org.h2.value.ValueString)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 OutputStream (java.io.OutputStream)4