Search in sources :

Example 51 with Table

use of org.h2.table.Table in project ignite by apache.

the class DbH2ServerStartup method populateDatabase.

/**
 * Populate sample database.
 *
 * @throws SQLException if
 */
public static void populateDatabase() throws SQLException {
    // Try to connect to database TCP server.
    JdbcConnectionPool dataSrc = JdbcConnectionPool.create("jdbc:h2:tcp://localhost/mem:ExampleDb", "sa", "");
    // Create Person table in database.
    RunScript.execute(dataSrc.getConnection(), new StringReader(CREATE_PERSON_TABLE));
    // Populates Person table with sample data in database.
    RunScript.execute(dataSrc.getConnection(), new StringReader(POPULATE_PERSON_TABLE));
}
Also used : JdbcConnectionPool(org.h2.jdbcx.JdbcConnectionPool) StringReader(java.io.StringReader)

Example 52 with Table

use of org.h2.table.Table in project ignite by apache.

the class DbH2ServerStartup method main.

/**
 * Start H2 database TCP server.
 *
 * @param args Command line arguments, none required.
 * @throws IgniteException If start H2 database TCP server failed.
 */
public static void main(String[] args) throws IgniteException {
    try {
        // Start H2 database TCP server in order to access sample in-memory database from other processes.
        Server.createTcpServer("-tcpDaemon").start();
        populateDatabase();
        // Try to connect to database TCP server.
        JdbcConnectionPool dataSrc = JdbcConnectionPool.create("jdbc:h2:tcp://localhost/mem:ExampleDb", "sa", "");
        // Create Person table in database.
        RunScript.execute(dataSrc.getConnection(), new StringReader(CREATE_PERSON_TABLE));
        // Populates Person table with sample data in database.
        RunScript.execute(dataSrc.getConnection(), new StringReader(POPULATE_PERSON_TABLE));
    } catch (SQLException e) {
        throw new IgniteException("Failed to start database TCP server", e);
    }
    try {
        do {
            System.out.println("Type 'q' and press 'Enter' to stop H2 TCP server...");
        } while ('q' != System.in.read());
    } catch (IOException ignored) {
    // No-op.
    }
}
Also used : JdbcConnectionPool(org.h2.jdbcx.JdbcConnectionPool) SQLException(java.sql.SQLException) IgniteException(org.apache.ignite.IgniteException) StringReader(java.io.StringReader) IOException(java.io.IOException)

Example 53 with Table

use of org.h2.table.Table in project elastic-core-maven by OrdinaryDude.

the class FullTextTrigger method reindexTable.

/**
 * Reindex the table
 *
 * @param   conn                SQL connection
 * @throws  SQLException        Unable to reindex table
 */
private void reindexTable(Connection conn) throws SQLException {
    if (indexColumns.isEmpty()) {
        return;
    }
    // 
    // Build the SELECT statement for just the indexed columns
    // 
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT DB_ID");
    for (int index : indexColumns) {
        sb.append(", ").append(columnNames.get(index));
    }
    sb.append(" FROM ").append(tableName);
    Object[] row = new Object[columnNames.size()];
    // 
    try (Statement qstmt = conn.createStatement();
        ResultSet rs = qstmt.executeQuery(sb.toString())) {
        while (rs.next()) {
            row[dbColumn] = rs.getObject(1);
            int i = 2;
            for (int index : indexColumns) {
                row[index] = rs.getObject(i++);
            }
            indexRow(row);
        }
    }
    // 
    // Commit the index updates
    // 
    commitIndex();
}
Also used : Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 54 with Table

use of org.h2.table.Table 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 55 with Table

use of org.h2.table.Table 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)

Aggregations

Column (org.h2.table.Column)20 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)18 Statement (java.sql.Statement)13 SQLException (java.sql.SQLException)12 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)12 IndexColumn (org.h2.table.IndexColumn)11 ResultSet (java.sql.ResultSet)9 IgniteException (org.apache.ignite.IgniteException)9 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)8 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)8 SimpleResultSet (org.h2.tools.SimpleResultSet)8 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)7 Table (org.h2.table.Table)7 Connection (java.sql.Connection)6 HashSet (java.util.HashSet)6 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)6 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)6 Prepared (org.h2.command.Prepared)6 ValueString (org.h2.value.ValueString)6 PreparedStatement (java.sql.PreparedStatement)5