Search in sources :

Example 1 with GridQueryProperty

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

the class DdlStatementsProcessor method runDdlStatement.

/**
     * Execute DDL statement.
     *
     * @param sql SQL.
     * @param stmt H2 statement to parse and execute.
     */
@SuppressWarnings("unchecked")
public FieldsQueryCursor<List<?>> runDdlStatement(String sql, PreparedStatement stmt) throws IgniteCheckedException {
    assert stmt instanceof JdbcPreparedStatement;
    IgniteInternalFuture fut = null;
    try {
        GridSqlStatement stmt0 = new GridSqlQueryParser(false).parse(GridSqlQueryParser.prepared(stmt));
        if (stmt0 instanceof GridSqlCreateIndex) {
            GridSqlCreateIndex cmd = (GridSqlCreateIndex) stmt0;
            GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null)
                throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            assert tbl.rowDescriptor() != null;
            QueryIndex newIdx = new QueryIndex();
            newIdx.setName(cmd.index().getName());
            newIdx.setIndexType(cmd.index().getIndexType());
            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 (Map.Entry<String, Boolean> e : cmd.index().getFields().entrySet()) {
                GridQueryProperty prop = typeDesc.property(e.getKey());
                if (prop == null)
                    throw new SchemaOperationException(SchemaOperationException.CODE_COLUMN_NOT_FOUND, e.getKey());
                flds.put(prop.name(), e.getValue());
            }
            newIdx.setFields(flds);
            fut = ctx.query().dynamicIndexCreate(tbl.cacheName(), cmd.schemaName(), typeDesc.tableName(), newIdx, cmd.ifNotExists());
        } else if (stmt0 instanceof GridSqlDropIndex) {
            GridSqlDropIndex cmd = (GridSqlDropIndex) stmt0;
            GridH2Table tbl = idx.dataTableForIndex(cmd.schemaName(), cmd.indexName());
            if (tbl != null) {
                fut = ctx.query().dynamicIndexDrop(tbl.cacheName(), cmd.schemaName(), cmd.indexName(), cmd.ifExists());
            } else {
                if (cmd.ifExists())
                    fut = new GridFinishedFuture();
                else
                    throw new SchemaOperationException(SchemaOperationException.CODE_INDEX_NOT_FOUND, cmd.indexName());
            }
        } else if (stmt0 instanceof GridSqlCreateTable) {
            GridSqlCreateTable cmd = (GridSqlCreateTable) stmt0;
            if (!F.eq(QueryUtils.DFLT_SCHEMA, cmd.schemaName()))
                throw new SchemaOperationException("CREATE TABLE can only be executed on " + QueryUtils.DFLT_SCHEMA + " schema.");
            GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl != null) {
                if (!cmd.ifNotExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_EXISTS, cmd.tableName());
            } else {
                ctx.query().dynamicTableCreate(cmd.schemaName(), toQueryEntity(cmd), cmd.templateName(), cmd.atomicityMode(), cmd.backups(), cmd.ifNotExists());
            }
        } else if (stmt0 instanceof GridSqlDropTable) {
            GridSqlDropTable cmd = (GridSqlDropTable) stmt0;
            if (!F.eq(QueryUtils.DFLT_SCHEMA, cmd.schemaName()))
                throw new SchemaOperationException("DROP TABLE can only be executed on " + QueryUtils.DFLT_SCHEMA + " schema.");
            GridH2Table tbl = idx.dataTable(cmd.schemaName(), cmd.tableName());
            if (tbl == null) {
                if (!cmd.ifExists())
                    throw new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, cmd.tableName());
            } else
                ctx.query().dynamicTableDrop(tbl.cacheName(), cmd.tableName(), cmd.ifExists());
        } else
            throw new IgniteSQLException("Unsupported DDL operation: " + sql, IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (fut != null)
            fut.get();
        QueryCursorImpl<List<?>> resCur = (QueryCursorImpl<List<?>>) new QueryCursorImpl(Collections.singletonList(Collections.singletonList(0L)), null, false);
        resCur.fieldsMeta(UPDATE_RESULT_META);
        return resCur;
    } catch (SchemaOperationException e) {
        throw convert(e);
    } catch (IgniteSQLException e) {
        throw e;
    } catch (Exception e) {
        throw new IgniteSQLException("Unexpected DLL operation failure: " + e.getMessage(), e);
    }
}
Also used : GridSqlStatement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridSqlDropIndex(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropIndex) LinkedHashMap(java.util.LinkedHashMap) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) GridSqlCreateIndex(org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateIndex) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) QueryIndex(org.apache.ignite.cache.QueryIndex) List(java.util.List) JdbcPreparedStatement(org.h2.jdbc.JdbcPreparedStatement) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) GridSqlCreateTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateTable) QueryCursorImpl(org.apache.ignite.internal.processors.cache.QueryCursorImpl) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridSqlQueryParser(org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) GridSqlDropTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropTable)

Example 2 with GridQueryProperty

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

the class JdbcRequestHandler method getColumnsMeta.

/**
 * {@link OdbcQueryGetColumnsMetaRequest} command handler.
 *
 * @param req Get columns metadata request.
 * @return Response.
 */
@SuppressWarnings("unchecked")
private JdbcResponse getColumnsMeta(JdbcMetaColumnsRequest req) {
    try {
        Collection<JdbcColumnMeta> meta = new LinkedHashSet<>();
        for (String cacheName : ctx.cache().publicCacheNames()) {
            for (GridQueryTypeDescriptor table : ctx.query().types(cacheName)) {
                if (!matches(table.schemaName(), req.schemaName()))
                    continue;
                if (!matches(table.tableName(), req.tableName()))
                    continue;
                for (Map.Entry<String, Class<?>> field : table.fields().entrySet()) {
                    String colName = field.getKey();
                    if (!matches(colName, req.columnName()))
                        continue;
                    JdbcColumnMeta columnMeta;
                    if (protocolVer.compareTo(VER_2_4_0) >= 0) {
                        GridQueryProperty prop = table.property(colName);
                        columnMeta = new JdbcColumnMetaV3(table.schemaName(), table.tableName(), field.getKey(), field.getValue(), !prop.notNull(), prop.defaultValue());
                    } else if (protocolVer.compareTo(VER_2_3_0) >= 0) {
                        GridQueryProperty prop = table.property(colName);
                        columnMeta = new JdbcColumnMetaV2(table.schemaName(), table.tableName(), field.getKey(), field.getValue(), !prop.notNull());
                    } else
                        columnMeta = new JdbcColumnMeta(table.schemaName(), table.tableName(), field.getKey(), field.getValue());
                    if (!meta.contains(columnMeta))
                        meta.add(columnMeta);
                }
            }
        }
        JdbcMetaColumnsResult res;
        if (protocolVer.compareTo(VER_2_4_0) >= 0)
            res = new JdbcMetaColumnsResultV3(meta);
        else if (protocolVer.compareTo(VER_2_3_0) >= 0)
            res = new JdbcMetaColumnsResultV2(meta);
        else
            res = new JdbcMetaColumnsResult(meta);
        return new JdbcResponse(res);
    } catch (Exception e) {
        U.error(log, "Failed to get columns metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
        return exceptionToResult(e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BatchUpdateException(java.sql.BatchUpdateException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 3 with GridQueryProperty

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

the class OdbcRequestHandler method getColumnsMeta.

/**
 * {@link OdbcQueryGetColumnsMetaRequest} command handler.
 *
 * @param req Get columns metadata request.
 * @return Response.
 */
private ClientListenerResponse getColumnsMeta(OdbcQueryGetColumnsMetaRequest req) {
    try {
        List<OdbcColumnMeta> meta = new ArrayList<>();
        String schemaPattern;
        String tablePattern;
        if (req.tablePattern().contains(".")) {
            // Parsing two-part table name.
            String[] parts = req.tablePattern().split("\\.");
            schemaPattern = parts[0];
            tablePattern = parts[1];
        } else {
            schemaPattern = req.schemaPattern();
            tablePattern = req.tablePattern();
        }
        schemaPattern = OdbcUtils.removeQuotationMarksIfNeeded(schemaPattern);
        for (String cacheName : ctx.cache().publicCacheNames()) {
            for (GridQueryTypeDescriptor table : ctx.query().types(cacheName)) {
                if (!matches(table.schemaName(), schemaPattern) || !matches(table.tableName(), tablePattern))
                    continue;
                for (Map.Entry<String, Class<?>> field : table.fields().entrySet()) {
                    if (!matches(field.getKey(), req.columnPattern()))
                        continue;
                    GridQueryProperty prop = table.property(field.getKey());
                    OdbcColumnMeta columnMeta = new OdbcColumnMeta(table.schemaName(), table.tableName(), field.getKey(), field.getValue(), prop.precision(), prop.scale(), prop.notNull() ? columnNoNulls : columnNullable);
                    if (!meta.contains(columnMeta))
                        meta.add(columnMeta);
                }
            }
        }
        OdbcQueryGetColumnsMetaResult res = new OdbcQueryGetColumnsMetaResult(meta);
        return new OdbcResponse(res);
    } catch (Exception e) {
        U.error(log, "Failed to get columns metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
        return exceptionToResult(e);
    }
}
Also used : ArrayList(java.util.ArrayList) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) BatchUpdateException(java.sql.BatchUpdateException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 4 with GridQueryProperty

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

the class UpdatePlan method processRowForUpdate.

/**
 * Convert a row into value.
 *
 * @param row Row to process.
 * @throws IgniteCheckedException if failed.
 * @return Tuple contains: [key, old value, new value]
 */
public T3<Object, Object, Object> processRowForUpdate(List<?> row) throws IgniteCheckedException {
    GridH2RowDescriptor rowDesc = tbl.rowDescriptor();
    GridQueryTypeDescriptor desc = rowDesc.type();
    GridCacheContext cctx = rowDesc.context();
    boolean hasNewVal = (valColIdx != -1);
    boolean hasProps = !hasNewVal || colNames.length > 1;
    Object key = row.get(0);
    Object oldVal = row.get(1);
    if (cctx.binaryMarshaller() && !(oldVal instanceof BinaryObject))
        oldVal = cctx.grid().binary().toBinary(oldVal);
    Object newVal;
    Map<String, Object> newColVals = new HashMap<>();
    for (int i = 0; i < colNames.length; i++) {
        if (hasNewVal && i == valColIdx - 2)
            continue;
        GridQueryProperty prop = tbl.rowDescriptor().type().property(colNames[i]);
        assert prop != null : "Unknown property: " + colNames[i];
        newColVals.put(colNames[i], DmlUtils.convert(row.get(i + 2), rowDesc, prop.type(), colTypes[i], colNames[i]));
    }
    newVal = valSupplier.apply(row);
    if (newVal == null)
        throw new IgniteSQLException("New value for UPDATE must not be null", IgniteQueryErrorCode.NULL_VALUE);
    // Skip key and value - that's why we start off with 3rd column
    for (int i = 0; i < tbl.getColumns().length - QueryUtils.DEFAULT_COLUMNS_COUNT; i++) {
        Column c = tbl.getColumn(i + QueryUtils.DEFAULT_COLUMNS_COUNT);
        if (rowDesc.isKeyValueOrVersionColumn(c.getColumnId()))
            continue;
        GridQueryProperty prop = desc.property(c.getName());
        if (prop.key())
            // Don't get values of key's columns - we won't use them anyway
            continue;
        boolean hasNewColVal = newColVals.containsKey(c.getName());
        if (!hasNewColVal)
            continue;
        Object colVal = newColVals.get(c.getName());
        // UPDATE currently does not allow to modify key or its fields, so we must be safe to pass null as key.
        rowDesc.setColumnValue(null, newVal, colVal, i);
    }
    if (cctx.binaryMarshaller() && hasProps) {
        assert newVal instanceof BinaryObjectBuilder;
        newVal = ((BinaryObjectBuilder) newVal).build();
    }
    desc.validateKeyAndValue(key, newVal);
    return new T3<>(key, oldVal, newVal);
}
Also used : GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) HashMap(java.util.HashMap) 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) BinaryObject(org.apache.ignite.binary.BinaryObject) 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) T3(org.apache.ignite.internal.util.typedef.T3)

Example 5 with GridQueryProperty

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

the class UpdatePlan method processRow.

/**
 * Convert a row into key-value pair.
 *
 * @param row Row to process.
 * @throws IgniteCheckedException if failed.
 */
public IgniteBiTuple<?, ?> processRow(List<?> row) throws IgniteCheckedException {
    if (mode != BULK_LOAD && row.size() != colNames.length)
        throw new IgniteSQLException("Not enough values in a row: " + row.size() + " instead of " + colNames.length, IgniteQueryErrorCode.ENTRY_PROCESSING);
    GridH2RowDescriptor rowDesc = tbl.rowDescriptor();
    GridQueryTypeDescriptor desc = rowDesc.type();
    GridCacheContext cctx = rowDesc.context();
    Object key = keySupplier.apply(row);
    if (QueryUtils.isSqlType(desc.keyClass())) {
        assert keyColIdx != -1;
        key = DmlUtils.convert(key, rowDesc, desc.keyClass(), colTypes[keyColIdx], colNames[keyColIdx]);
    }
    Object val = valSupplier.apply(row);
    if (QueryUtils.isSqlType(desc.valueClass())) {
        assert valColIdx != -1;
        val = DmlUtils.convert(val, rowDesc, desc.valueClass(), colTypes[valColIdx], colNames[valColIdx]);
    }
    if (key == null) {
        if (F.isEmpty(desc.keyFieldName()))
            throw new IgniteSQLException("Key for INSERT, COPY, or MERGE must not be null", IgniteQueryErrorCode.NULL_KEY);
        else
            throw new IgniteSQLException("Null value is not allowed for column '" + desc.keyFieldName() + "'", IgniteQueryErrorCode.NULL_KEY);
    }
    if (val == null) {
        if (F.isEmpty(desc.valueFieldName()))
            throw new IgniteSQLException("Value for INSERT, COPY, MERGE, or UPDATE must not be null", IgniteQueryErrorCode.NULL_VALUE);
        else
            throw new IgniteSQLException("Null value is not allowed for column '" + desc.valueFieldName() + "'", IgniteQueryErrorCode.NULL_VALUE);
    }
    int actualColCnt = Math.min(colNames.length, row.size());
    Map<String, Object> newColVals = new HashMap<>();
    for (int i = 0; i < actualColCnt; i++) {
        if (i == keyColIdx || i == valColIdx)
            continue;
        String colName = colNames[i];
        GridQueryProperty prop = desc.property(colName);
        assert prop != null;
        Class<?> expCls = prop.type();
        newColVals.put(colName, DmlUtils.convert(row.get(i), rowDesc, expCls, colTypes[i], colNames[i]));
    }
    desc.setDefaults(key, val);
    // 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[] tblCols = tbl.getColumns();
    // First 2 columns are _key and _val Skip 'em.
    for (int i = QueryUtils.DEFAULT_COLUMNS_COUNT; i < tblCols.length; i++) {
        if (tbl.rowDescriptor().isKeyValueOrVersionColumn(i))
            continue;
        String colName = tblCols[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();
    }
    desc.validateKeyAndValue(key, val);
    return new IgniteBiTuple<>(key, val);
}
Also used : GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) HashMap(java.util.HashMap) 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