Search in sources :

Example 26 with Table

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

the class FullTextTrigger method search.

/**
 * Search the Lucene index
 *
 * The result set will have the following columns:
 *   SCHEMA  - Schema name (String)
 *   TABLE   - Table name (String)
 *   COLUMNS - Primary key column names (String[]) - this is always DB_ID
 *   KEYS    - Primary key values (Long[]) - this is always the DB_ID value for the table row
 *   SCORE   - Lucene score (Float)
 *
 * @param   conn                SQL connection
 * @param   schema              Schema name
 * @param   table               Table name
 * @param   queryText           Query expression
 * @param   limit               Number of rows to return
 * @param   offset              Offset with result set
 * @return                      Search results
 * @throws  SQLException        Unable to search the index
 */
public static ResultSet search(Connection conn, String schema, String table, String queryText, int limit, int offset) throws SQLException {
    // 
    // Get Lucene index access
    // 
    getIndexAccess(conn);
    // 
    // Create the result set columns
    // 
    SimpleResultSet result = new SimpleResultSet();
    result.addColumn("SCHEMA", Types.VARCHAR, 0, 0);
    result.addColumn("TABLE", Types.VARCHAR, 0, 0);
    result.addColumn("COLUMNS", Types.ARRAY, 0, 0);
    result.addColumn("KEYS", Types.ARRAY, 0, 0);
    result.addColumn("SCORE", Types.FLOAT, 0, 0);
    // 
    // Perform the search
    // 
    // The _QUERY field contains the table and row identification (schema.table;keyName;keyValue)
    // The _TABLE field is used to limit the search results to the current table
    // The _DATA field contains the indexed row data (this is the default search field)
    // The _MODIFIED field contains the row modification time (YYYYMMDDhhmmss) in GMT
    // 
    indexLock.readLock().lock();
    try {
        QueryParser parser = new QueryParser("_DATA", analyzer);
        parser.setDateResolution("_MODIFIED", DateTools.Resolution.SECOND);
        parser.setDefaultOperator(QueryParser.Operator.AND);
        Query query = parser.parse("_TABLE:" + schema.toUpperCase() + "." + table.toUpperCase() + " AND (" + queryText + ")");
        TopDocs documents = indexSearcher.search(query, limit);
        ScoreDoc[] hits = documents.scoreDocs;
        int resultCount = Math.min(hits.length, (limit == 0 ? hits.length : limit));
        int resultOffset = Math.min(offset, resultCount);
        for (int i = resultOffset; i < resultCount; i++) {
            Document document = indexSearcher.doc(hits[i].doc);
            String[] indexParts = document.get("_QUERY").split(";");
            String[] nameParts = indexParts[0].split("\\.");
            result.addRow(nameParts[0], nameParts[1], new String[] { indexParts[1] }, new Long[] { Long.parseLong(indexParts[2]) }, hits[i].score);
        }
    } catch (ParseException exc) {
        Logger.logDebugMessage("Lucene parse exception for query: " + queryText + "\n" + exc.getMessage());
        throw new SQLException("Lucene parse exception for query: " + queryText + "\n" + exc.getMessage());
    } catch (IOException exc) {
        Logger.logErrorMessage("Unable to search Lucene index", exc);
        throw new SQLException("Unable to search Lucene index", exc);
    } finally {
        indexLock.readLock().unlock();
    }
    return result;
}
Also used : SimpleResultSet(org.h2.tools.SimpleResultSet) Query(org.apache.lucene.search.Query) SQLException(java.sql.SQLException) IOException(java.io.IOException) Document(org.apache.lucene.document.Document) ScoreDoc(org.apache.lucene.search.ScoreDoc) TopDocs(org.apache.lucene.search.TopDocs) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) ParseException(org.apache.lucene.queryparser.classic.ParseException)

Example 27 with Table

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

the class GridSqlQueryParser method parseAddColumn.

/**
 * Parse {@code ALTER TABLE ... ADD COLUMN} statement.
 * @param addCol H2 statement.
 * @return Grid SQL statement.
 *
 * @see <a href="http://www.h2database.com/html/grammar.html#alter_table_add"></a>
 */
private GridSqlStatement parseAddColumn(AlterTableAlterColumn addCol) {
    assert addCol.getType() == CommandInterface.ALTER_TABLE_ADD_COLUMN;
    if (ALTER_COLUMN_BEFORE_COL.get(addCol) != null || ALTER_COLUMN_AFTER_COL.get(addCol) != null)
        throw new IgniteSQLException("ALTER TABLE ADD COLUMN BEFORE/AFTER is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    GridSqlAlterTableAddColumn res = new GridSqlAlterTableAddColumn();
    ArrayList<Column> h2NewCols = ALTER_COLUMN_NEW_COLS.get(addCol);
    GridSqlColumn[] gridNewCols = new GridSqlColumn[h2NewCols.size()];
    for (int i = 0; i < h2NewCols.size(); i++) {
        Column col = h2NewCols.get(i);
        if (col.getDefaultExpression() != null)
            throw new IgniteSQLException("ALTER TABLE ADD COLUMN with DEFAULT value is not supported " + "[col=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        gridNewCols[i] = parseColumn(h2NewCols.get(i));
    }
    res.columns(gridNewCols);
    if (gridNewCols.length == 1)
        res.ifNotExists(ALTER_COLUMN_IF_NOT_EXISTS.get(addCol));
    res.ifTableExists(ALTER_COLUMN_IF_TBL_EXISTS.get(addCol));
    Schema schema = SCHEMA_COMMAND_SCHEMA.get(addCol);
    res.schemaName(schema.getName());
    res.tableName(ALTER_COLUMN_TBL_NAME.get(addCol));
    return res;
}
Also used : 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) Schema(org.h2.schema.Schema) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint)

Example 28 with Table

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

the class GridSqlQueryParser method parseDropColumn.

/**
 * Parse {@code ALTER TABLE ... DROP COLUMN} statement.
 * @param dropCol H2 statement.
 * @see <a href="http://www.h2database.com/html/grammar.html#alter_table_add"></a>
 */
private GridSqlStatement parseDropColumn(AlterTableAlterColumn dropCol) {
    assert dropCol.getType() == CommandInterface.ALTER_TABLE_DROP_COLUMN;
    GridSqlAlterTableDropColumn res = new GridSqlAlterTableDropColumn();
    ArrayList<Column> h2DropCols = ALTER_COLUMN_REMOVE_COLS.get(dropCol);
    String[] gridDropCols = new String[h2DropCols.size()];
    for (int i = 0; i < h2DropCols.size(); i++) gridDropCols[i] = h2DropCols.get(i).getName();
    res.columns(gridDropCols);
    if (gridDropCols.length == 1)
        res.ifExists(!ALTER_COLUMN_IF_NOT_EXISTS.get(dropCol));
    res.ifTableExists(ALTER_COLUMN_IF_TBL_EXISTS.get(dropCol));
    Schema schema = SCHEMA_COMMAND_SCHEMA.get(dropCol);
    res.schemaName(schema.getName());
    res.tableName(ALTER_COLUMN_TBL_NAME.get(dropCol));
    return res;
}
Also used : 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) Schema(org.h2.schema.Schema) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint)

Example 29 with Table

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

the class GridSqlQueryParser method parseDropTable.

/**
 * Parse {@code DROP TABLE} statement.
 *
 * @param dropTbl {@code DROP TABLE} statement.
 * @see <a href="http://h2database.com/html/grammar.html#drop_table">H2 {@code DROP TABLE} spec.</a>
 */
private GridSqlDropTable parseDropTable(DropTable dropTbl) {
    GridSqlDropTable res = new GridSqlDropTable();
    Schema schema = SCHEMA_COMMAND_SCHEMA.get(dropTbl);
    res.schemaName(schema.getName());
    res.ifExists(DROP_TABLE_IF_EXISTS.get(dropTbl));
    res.tableName(DROP_TABLE_NAME.get(dropTbl));
    return res;
}
Also used : Schema(org.h2.schema.Schema)

Example 30 with Table

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

the class GridSqlQueryParser method processExtraParam.

/**
 * @param name Param name.
 * @param val Param value.
 * @param res Table params to update.
 */
private static void processExtraParam(String name, String val, GridSqlCreateTable res) {
    assert !F.isEmpty(name);
    switch(name) {
        case PARAM_TEMPLATE:
            ensureNotEmpty(name, val);
            res.templateName(val);
            break;
        case PARAM_BACKUPS:
            ensureNotEmpty(name, val);
            int backups = parseIntParam(PARAM_BACKUPS, val);
            if (backups < 0)
                throw new IgniteSQLException("\"" + PARAM_BACKUPS + "\" cannot be negative: " + backups, IgniteQueryErrorCode.PARSING);
            res.backups(backups);
            break;
        case PARAM_ATOMICITY:
            ensureNotEmpty(name, val);
            CacheAtomicityMode atomicityMode;
            if (CacheAtomicityMode.TRANSACTIONAL.name().equalsIgnoreCase(val))
                atomicityMode = CacheAtomicityMode.TRANSACTIONAL;
            else if (CacheAtomicityMode.ATOMIC.name().equalsIgnoreCase(val))
                atomicityMode = CacheAtomicityMode.ATOMIC;
            else
                throw new IgniteSQLException("Invalid value of \"" + PARAM_ATOMICITY + "\" parameter " + "(should be either TRANSACTIONAL or ATOMIC): " + val, IgniteQueryErrorCode.PARSING);
            res.atomicityMode(atomicityMode);
            break;
        case PARAM_CACHE_NAME:
            ensureNotEmpty(name, val);
            res.cacheName(val);
            break;
        case PARAM_KEY_TYPE:
            ensureNotEmpty(name, val);
            res.keyTypeName(val);
            break;
        case PARAM_VAL_TYPE:
            ensureNotEmpty(name, val);
            res.valueTypeName(val);
            break;
        case PARAM_CACHE_GROUP_OLD:
        case PARAM_CACHE_GROUP:
            ensureNotEmpty(name, val);
            res.cacheGroup(val);
            break;
        case PARAM_AFFINITY_KEY_OLD:
        case PARAM_AFFINITY_KEY:
            ensureNotEmpty(name, val);
            String affColName = null;
            // Either strip column name off its quotes, or uppercase it.
            if (val.startsWith("'")) {
                if (val.length() == 1 || !val.endsWith("'"))
                    throw new IgniteSQLException("Affinity key column name does not have trailing quote: " + val, IgniteQueryErrorCode.PARSING);
                val = val.substring(1, val.length() - 1);
                ensureNotEmpty(name, val);
                affColName = val;
            } else {
                for (String colName : res.columns().keySet()) {
                    if (val.equalsIgnoreCase(colName)) {
                        if (affColName != null)
                            throw new IgniteSQLException("Ambiguous affinity column name, use single quotes " + "for case sensitivity: " + val, IgniteQueryErrorCode.PARSING);
                        affColName = colName;
                    }
                }
            }
            if (affColName == null || !res.columns().containsKey(affColName))
                throw new IgniteSQLException("Affinity key column with given name not found: " + val, IgniteQueryErrorCode.PARSING);
            if (!res.primaryKeyColumns().contains(affColName))
                throw new IgniteSQLException("Affinity key column must be one of key columns: " + affColName, IgniteQueryErrorCode.PARSING);
            res.affinityKey(affColName);
            break;
        case PARAM_WRITE_SYNC:
            ensureNotEmpty(name, val);
            CacheWriteSynchronizationMode writeSyncMode;
            if (CacheWriteSynchronizationMode.FULL_ASYNC.name().equalsIgnoreCase(val))
                writeSyncMode = CacheWriteSynchronizationMode.FULL_ASYNC;
            else if (CacheWriteSynchronizationMode.FULL_SYNC.name().equalsIgnoreCase(val))
                writeSyncMode = CacheWriteSynchronizationMode.FULL_SYNC;
            else if (CacheWriteSynchronizationMode.PRIMARY_SYNC.name().equalsIgnoreCase(val))
                writeSyncMode = CacheWriteSynchronizationMode.PRIMARY_SYNC;
            else
                throw new IgniteSQLException("Invalid value of \"" + PARAM_WRITE_SYNC + "\" parameter " + "(should be FULL_SYNC, FULL_ASYNC, or PRIMARY_SYNC): " + val, IgniteQueryErrorCode.PARSING);
            res.writeSynchronizationMode(writeSyncMode);
            break;
        case PARAM_WRAP_KEY:
            {
                res.wrapKey(F.isEmpty(val) || Boolean.parseBoolean(val));
                break;
            }
        case PARAM_WRAP_VALUE:
            res.wrapValue(F.isEmpty(val) || Boolean.parseBoolean(val));
            break;
        case PARAM_DATA_REGION:
            ensureNotEmpty(name, val);
            res.dataRegionName(val);
            break;
        default:
            throw new IgniteSQLException("Unsupported parameter: " + name, IgniteQueryErrorCode.PARSING);
    }
}
Also used : CacheWriteSynchronizationMode(org.apache.ignite.cache.CacheWriteSynchronizationMode) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) CacheAtomicityMode(org.apache.ignite.cache.CacheAtomicityMode) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint)

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