Search in sources :

Example 6 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class H2DynamicTableSelfTest method assertProperty.

/**
 * Check that a property in given descriptor is present and has parameters as expected.
 * @param desc Descriptor.
 * @param name Property name.
 * @param type Expected property type.
 * @param isKey {@code true} if the property is expected to belong to key, {@code false} is it's expected to belong
 *     to value.
 */
private void assertProperty(QueryTypeDescriptorImpl desc, String name, Class<?> type, boolean isKey) {
    GridQueryProperty p = desc.property(name);
    assertNotNull(name, p);
    assertEquals(type, p.type());
    assertEquals(isKey, p.key());
}
Also used : GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty)

Example 7 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class CommandProcessor method runCommandNativeDdl.

/**
 * Run DDL statement.
 *
 * @param sql Original SQL.
 * @param cmd Command.
 */
private void runCommandNativeDdl(String sql, SqlCommand cmd) {
    IgniteInternalFuture fut = null;
    try {
        isDdlOnSchemaSupported(cmd.schemaName());
        finishActiveTxIfNecessary();
        if (cmd instanceof SqlCreateIndexCommand) {
            SqlCreateIndexCommand cmd0 = (SqlCreateIndexCommand) cmd;
            GridH2Table tbl = schemaMgr.dataTable(cmd0.schemaName(), cmd0.tableName());
            if (tbl == null)
                throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd0.tableName());
            assert tbl.rowDescriptor() != null;
            ensureDdlSupported(tbl);
            QueryIndex newIdx = new QueryIndex();
            newIdx.setName(cmd0.indexName());
            newIdx.setIndexType(cmd0.spatial() ? QueryIndexType.GEOSPATIAL : QueryIndexType.SORTED);
            LinkedHashMap<String, Boolean> flds = new LinkedHashMap<>();
            // Let's replace H2's table and property names by those operated by GridQueryProcessor.
            GridQueryTypeDescriptor typeDesc = tbl.rowDescriptor().type();
            for (SqlIndexColumn col : cmd0.columns()) {
                GridQueryProperty prop = typeDesc.property(col.name());
                if (prop == null)
                    throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_NOT_FOUND, col.name());
                flds.put(prop.name(), !col.descending());
            }
            newIdx.setFields(flds);
            newIdx.setInlineSize(cmd0.inlineSize());
            fut = ctx.query().dynamicIndexCreate(tbl.cacheName(), cmd.schemaName(), typeDesc.tableName(), newIdx, cmd0.ifNotExists(), cmd0.parallel());
        } else if (cmd instanceof SqlDropIndexCommand) {
            SqlDropIndexCommand cmd0 = (SqlDropIndexCommand) cmd;
            GridH2Table tbl = schemaMgr.dataTableForIndex(cmd0.schemaName(), cmd0.indexName());
            if (tbl != null) {
                ensureDdlSupported(tbl);
                fut = ctx.query().dynamicIndexDrop(tbl.cacheName(), cmd0.schemaName(), cmd0.indexName(), cmd0.ifExists());
            } else {
                if (cmd0.ifExists())
                    fut = new GridFinishedFuture();
                else
                    throw new SchemaOperationException(SchemaOperationException.CODE_INDEX_NOT_FOUND, cmd0.indexName());
            }
        } else if (cmd instanceof SqlAlterTableCommand) {
            SqlAlterTableCommand cmd0 = (SqlAlterTableCommand) cmd;
            GridH2Table tbl = schemaMgr.dataTable(cmd0.schemaName(), cmd0.tableName());
            if (tbl == null) {
                throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd0.tableName());
            }
            Boolean logging = cmd0.logging();
            assert logging != null : "Only LOGGING/NOLOGGING are supported at the moment.";
            IgniteCluster cluster = ctx.grid().cluster();
            if (logging) {
                boolean res = cluster.enableWal(tbl.cacheName());
                if (!res)
                    throw new IgniteSQLException("Logging already enabled for table: " + cmd0.tableName());
            } else {
                boolean res = cluster.disableWal(tbl.cacheName());
                if (!res)
                    throw new IgniteSQLException("Logging already disabled for table: " + cmd0.tableName());
            }
            fut = new GridFinishedFuture();
        } else if (cmd instanceof SqlCreateUserCommand) {
            SqlCreateUserCommand addCmd = (SqlCreateUserCommand) cmd;
            ctx.security().createUser(addCmd.userName(), addCmd.password().toCharArray());
        } else if (cmd instanceof SqlAlterUserCommand) {
            SqlAlterUserCommand altCmd = (SqlAlterUserCommand) cmd;
            ctx.security().alterUser(altCmd.userName(), altCmd.password().toCharArray());
        } else if (cmd instanceof SqlDropUserCommand) {
            SqlDropUserCommand dropCmd = (SqlDropUserCommand) cmd;
            ctx.security().dropUser(dropCmd.userName());
        } else if (cmd instanceof SqlAnalyzeCommand)
            processAnalyzeCommand((SqlAnalyzeCommand) cmd);
        else if (cmd instanceof SqlRefreshStatitsicsCommand)
            processRefreshStatisticsCommand((SqlRefreshStatitsicsCommand) cmd);
        else if (cmd instanceof SqlDropStatisticsCommand)
            processDropStatisticsCommand((SqlDropStatisticsCommand) cmd);
        else
            throw new IgniteSQLException("Unsupported DDL operation: " + sql, IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (fut != null)
            fut.get();
    } catch (SchemaOperationException e) {
        throw convert(e);
    } catch (IgniteSQLException e) {
        throw e;
    } catch (Exception e) {
        throw new IgniteSQLException(e.getMessage(), e);
    }
}
Also used : SqlAlterTableCommand(org.apache.ignite.internal.sql.command.SqlAlterTableCommand) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) LinkedHashMap(java.util.LinkedHashMap) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) SqlCreateUserCommand(org.apache.ignite.internal.sql.command.SqlCreateUserCommand) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) QueryIndex(org.apache.ignite.cache.QueryIndex) SqlAnalyzeCommand(org.apache.ignite.internal.sql.command.SqlAnalyzeCommand) SqlAlterUserCommand(org.apache.ignite.internal.sql.command.SqlAlterUserCommand) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) SqlCreateIndexCommand(org.apache.ignite.internal.sql.command.SqlCreateIndexCommand) SqlDropStatisticsCommand(org.apache.ignite.internal.sql.command.SqlDropStatisticsCommand) SqlIndexColumn(org.apache.ignite.internal.sql.command.SqlIndexColumn) SqlRefreshStatitsicsCommand(org.apache.ignite.internal.sql.command.SqlRefreshStatitsicsCommand) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) SqlDropIndexCommand(org.apache.ignite.internal.sql.command.SqlDropIndexCommand) SqlDropUserCommand(org.apache.ignite.internal.sql.command.SqlDropUserCommand) IgniteCluster(org.apache.ignite.IgniteCluster) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 8 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class H2Utils method unwrapKeyColumns.

/**
 * Create list of index columns. Where possible _KEY columns will be unwrapped.
 *
 * @param tbl GridH2Table instance
 * @param idxCols List of index columns.
 *
 * @return Array of key and affinity columns. Key's, if it possible, splitted into simple components.
 */
@NotNull
public static IndexColumn[] unwrapKeyColumns(GridH2Table tbl, IndexColumn[] idxCols) {
    ArrayList<IndexColumn> keyCols = new ArrayList<>();
    boolean isSql = tbl.rowDescriptor().tableDescriptor().sql();
    if (!isSql)
        return idxCols;
    GridQueryTypeDescriptor type = tbl.rowDescriptor().type();
    for (IndexColumn idxCol : idxCols) {
        if (idxCol.column.getColumnId() == KEY_COL) {
            if (QueryUtils.isSqlType(type.keyClass())) {
                int altKeyColId = tbl.rowDescriptor().getAlternativeColumnId(QueryUtils.KEY_COL);
                // Remap simple key to alternative column.
                IndexColumn idxKeyCol = new IndexColumn();
                idxKeyCol.column = tbl.getColumn(altKeyColId);
                idxKeyCol.columnName = idxKeyCol.column.getName();
                idxKeyCol.sortType = idxCol.sortType;
                keyCols.add(idxKeyCol);
            } else {
                boolean added = false;
                for (String propName : type.fields().keySet()) {
                    GridQueryProperty prop = type.property(propName);
                    if (prop.key()) {
                        added = true;
                        Column col = tbl.getColumn(propName);
                        keyCols.add(tbl.indexColumn(col.getColumnId(), SortOrder.ASCENDING));
                    }
                }
                // we have to fall back to whole-key index.
                if (!added)
                    keyCols.add(idxCol);
            }
        } else
            keyCols.add(idxCol);
    }
    return keyCols.toArray(new IndexColumn[0]);
}
Also used : GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) IndexColumn(org.h2.table.IndexColumn) Column(org.h2.table.Column) ArrayList(java.util.ArrayList) ValueString(org.h2.value.ValueString) IndexColumn(org.h2.table.IndexColumn) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) NotNull(org.jetbrains.annotations.NotNull)

Example 9 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class H2Utils method tableCreateSql.

/**
 * Prepare SQL statement for CREATE TABLE command.
 *
 * @param tbl Table descriptor.
 * @return SQL.
 */
public static String tableCreateSql(H2TableDescriptor tbl) {
    String keyFieldName = tbl.type().keyFieldName();
    GridQueryProperty keyByNameProp = (keyFieldName == null) ? null : tbl.type().property(keyFieldName);
    GridQueryProperty keyProp = (keyByNameProp == null) ? tbl.type().property(KEY_FIELD_NAME) : keyByNameProp;
    GridQueryProperty valProp = tbl.type().property(VAL_FIELD_NAME);
    String keyType = dbTypeFromClass(tbl.type().keyClass(), keyProp == null ? -1 : keyProp.precision(), keyProp == null ? -1 : keyProp.scale());
    String valTypeStr = dbTypeFromClass(tbl.type().valueClass(), valProp == null ? -1 : valProp.precision(), valProp == null ? -1 : valProp.scale());
    SB sql = new SB();
    String keyValVisibility = tbl.type().fields().isEmpty() ? " VISIBLE" : " INVISIBLE";
    sql.a("CREATE TABLE ").a(tbl.fullTableName()).a(" (").a(KEY_FIELD_NAME).a(' ').a(keyType).a(keyValVisibility).a(" NOT NULL");
    sql.a(',').a(VAL_FIELD_NAME).a(' ').a(valTypeStr).a(keyValVisibility);
    for (Map.Entry<String, Class<?>> e : tbl.type().fields().entrySet()) {
        GridQueryProperty prop = tbl.type().property(e.getKey());
        sql.a(',').a(withQuotes(e.getKey())).a(' ').a(dbTypeFromClass(e.getValue(), prop.precision(), prop.scale())).a(prop.notNull() ? " NOT NULL" : "");
    }
    sql.a(')');
    return sql.toString();
}
Also used : GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) ValueString(org.h2.value.ValueString) Map(java.util.Map) SB(org.apache.ignite.internal.util.typedef.internal.SB)

Example 10 with GridQueryProperty

use of org.apache.ignite.internal.processors.query.GridQueryProperty in project ignite by apache.

the class DmlStatementsProcessor method rowToKeyValue.

/**
     * Convert row presented as an array of Objects into key-value pair to be inserted to cache.
     * @param cctx Cache context.
     * @param row Row to process.
     * @param plan Update plan.
     * @throws IgniteCheckedException if failed.
     */
@SuppressWarnings({ "unchecked", "ConstantConditions", "ResultOfMethodCallIgnored" })
private IgniteBiTuple<?, ?> rowToKeyValue(GridCacheContext cctx, List<?> row, UpdatePlan plan) throws IgniteCheckedException {
    GridH2RowDescriptor rowDesc = plan.tbl.rowDescriptor();
    GridQueryTypeDescriptor desc = rowDesc.type();
    Object key = plan.keySupplier.apply(row);
    if (QueryUtils.isSqlType(desc.keyClass())) {
        assert plan.keyColIdx != -1;
        key = convert(key, rowDesc, desc.keyClass(), plan.colTypes[plan.keyColIdx]);
    }
    Object val = plan.valSupplier.apply(row);
    if (QueryUtils.isSqlType(desc.valueClass())) {
        assert plan.valColIdx != -1;
        val = convert(val, rowDesc, desc.valueClass(), plan.colTypes[plan.valColIdx]);
    }
    if (key == null)
        throw new IgniteSQLException("Key for INSERT or MERGE must not be null", IgniteQueryErrorCode.NULL_KEY);
    if (val == null)
        throw new IgniteSQLException("Value for INSERT or MERGE must not be null", IgniteQueryErrorCode.NULL_VALUE);
    Map<String, Object> newColVals = new HashMap<>();
    for (int i = 0; i < plan.colNames.length; i++) {
        if (i == plan.keyColIdx || i == plan.valColIdx)
            continue;
        String colName = plan.colNames[i];
        GridQueryProperty prop = desc.property(colName);
        assert prop != null;
        Class<?> expCls = prop.type();
        newColVals.put(colName, convert(row.get(i), rowDesc, expCls, plan.colTypes[i]));
    }
    // We update columns in the order specified by the table for a reason - table's
    // column order preserves their precedence for correct update of nested properties.
    Column[] cols = plan.tbl.getColumns();
    // First 3 columns are _key, _val and _ver. Skip 'em.
    for (int i = DEFAULT_COLUMNS_COUNT; i < cols.length; i++) {
        if (plan.tbl.rowDescriptor().isKeyValueOrVersionColumn(i))
            continue;
        String colName = cols[i].getName();
        if (!newColVals.containsKey(colName))
            continue;
        Object colVal = newColVals.get(colName);
        desc.setValue(colName, key, val, colVal);
    }
    if (cctx.binaryMarshaller()) {
        if (key instanceof BinaryObjectBuilder)
            key = ((BinaryObjectBuilder) key).build();
        if (val instanceof BinaryObjectBuilder)
            val = ((BinaryObjectBuilder) val).build();
    }
    return new IgniteBiTuple<>(key, val);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) GridBoundedConcurrentLinkedHashMap(org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) Column(org.h2.table.Column) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) BinaryObject(org.apache.ignite.binary.BinaryObject) BinaryObjectBuilder(org.apache.ignite.binary.BinaryObjectBuilder)

Aggregations

GridQueryProperty (org.apache.ignite.internal.processors.query.GridQueryProperty)20 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)15 GridQueryTypeDescriptor (org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor)13 LinkedHashMap (java.util.LinkedHashMap)8 Column (org.h2.table.Column)8 ArrayList (java.util.ArrayList)7 Map (java.util.Map)7 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)7 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)7 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)7 HashMap (java.util.HashMap)6 List (java.util.List)6 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)6 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)6 QueryIndex (org.apache.ignite.cache.QueryIndex)5 SchemaOperationException (org.apache.ignite.internal.processors.query.schema.SchemaOperationException)5 GridFinishedFuture (org.apache.ignite.internal.util.future.GridFinishedFuture)5 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)4 QueryCursorImpl (org.apache.ignite.internal.processors.cache.QueryCursorImpl)3 QueryField (org.apache.ignite.internal.processors.query.QueryField)3