Search in sources :

Example 1 with GridSqlColumn

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn in project ignite by apache.

the class DmlAstUtils method selectForUpdate.

/**
     * Generate SQL SELECT based on UPDATE's WHERE, LIMIT, etc.
     *
     * @param update Update statement.
     * @param keysParamIdx Index of new param for the array of keys.
     * @return SELECT statement.
     */
public static GridSqlSelect selectForUpdate(GridSqlUpdate update, @Nullable Integer keysParamIdx) {
    GridSqlSelect mapQry = new GridSqlSelect();
    mapQry.from(update.target());
    Set<GridSqlTable> tbls = new HashSet<>();
    collectAllGridTablesInTarget(update.target(), tbls);
    assert tbls.size() == 1 : "Failed to determine target table for UPDATE";
    GridSqlTable tbl = tbls.iterator().next();
    GridH2Table gridTbl = tbl.dataTable();
    assert gridTbl != null : "Failed to determine target grid table for UPDATE";
    Column h2KeyCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.KEY_COL);
    Column h2ValCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.VAL_COL);
    GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
    keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
    GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
    valCol.resultType(GridSqlType.fromColumn(h2ValCol));
    mapQry.addColumn(keyCol, true);
    mapQry.addColumn(valCol, true);
    for (GridSqlColumn c : update.cols()) {
        String newColName = Parser.quoteIdentifier("_upd_" + c.columnName());
        // We have to use aliases to cover cases when the user
        // wants to update _val field directly (if it's a literal)
        GridSqlAlias alias = new GridSqlAlias(newColName, elementOrDefault(update.set().get(c.columnName()), c), true);
        alias.resultType(c.resultType());
        mapQry.addColumn(alias, true);
    }
    GridSqlElement where = update.where();
    if (keysParamIdx != null)
        where = injectKeysFilterParam(where, keyCol, keysParamIdx);
    mapQry.where(where);
    mapQry.limit(update.limit());
    return mapQry;
}
Also used : Column(org.h2.table.Column) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) ValueString(org.h2.value.ValueString) HashSet(java.util.HashSet)

Example 2 with GridSqlColumn

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn in project ignite by apache.

the class GridSqlQueryParser method parseInsert.

/**
     * @param insert Insert.
     * @see <a href="http://h2database.com/html/grammar.html#insert">H2 insert spec</a>
     */
private GridSqlInsert parseInsert(Insert insert) {
    GridSqlInsert res = (GridSqlInsert) h2ObjToGridObj.get(insert);
    if (res != null)
        return res;
    res = new GridSqlInsert();
    h2ObjToGridObj.put(insert, res);
    Table srcTbl = INSERT_TABLE.get(insert);
    GridSqlElement tbl = parseTable(srcTbl);
    res.into(tbl).direct(INSERT_DIRECT.get(insert)).sorted(INSERT_SORTED.get(insert));
    Column[] srcCols = INSERT_COLUMNS.get(insert);
    GridSqlColumn[] cols = new GridSqlColumn[srcCols.length];
    for (int i = 0; i < srcCols.length; i++) {
        cols[i] = new GridSqlColumn(srcCols[i], tbl, null, null, srcCols[i].getName());
        cols[i].resultType(fromColumn(srcCols[i]));
    }
    res.columns(cols);
    List<Expression[]> srcRows = INSERT_ROWS.get(insert);
    if (!srcRows.isEmpty()) {
        List<GridSqlElement[]> rows = new ArrayList<>(srcRows.size());
        for (Expression[] srcRow : srcRows) {
            GridSqlElement[] row = new GridSqlElement[srcRow.length];
            for (int i = 0; i < srcRow.length; i++) row[i] = parseExpression(srcRow[i], false);
            rows.add(row);
        }
        res.rows(rows);
    } else {
        res.rows(Collections.<GridSqlElement[]>emptyList());
        res.query(parseQuery(INSERT_QUERY.get(insert)));
    }
    return res;
}
Also used : RangeTable(org.h2.table.RangeTable) CreateTable(org.h2.command.ddl.CreateTable) FunctionTable(org.h2.table.FunctionTable) Table(org.h2.table.Table) DropTable(org.h2.command.ddl.DropTable) ArrayList(java.util.ArrayList) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) GridSqlType.fromColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) Expression(org.h2.expression.Expression) GridSqlType.fromExpression(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromExpression) ValueExpression(org.h2.expression.ValueExpression)

Example 3 with GridSqlColumn

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn in project ignite by apache.

the class GridSqlQueryParser method parseCreateTable.

/**
     * Parse {@code CREATE TABLE} statement.
     *
     * @param createTbl {@code CREATE TABLE} statement.
     * @see <a href="http://h2database.com/html/grammar.html#create_table">H2 {@code CREATE TABLE} spec.</a>
     */
private GridSqlCreateTable parseCreateTable(CreateTable createTbl) {
    GridSqlCreateTable res = new GridSqlCreateTable();
    res.templateName(QueryUtils.TEMPLATE_PARTITIONED);
    Query qry = CREATE_TABLE_QUERY.get(createTbl);
    if (qry != null)
        throw new IgniteSQLException("CREATE TABLE ... AS ... syntax is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    List<DefineCommand> constraints = CREATE_TABLE_CONSTRAINTS.get(createTbl);
    if (constraints.size() == 0)
        throw new IgniteSQLException("No PRIMARY KEY defined for CREATE TABLE", IgniteQueryErrorCode.PARSING);
    if (constraints.size() > 1)
        throw new IgniteSQLException("Too many constraints - only PRIMARY KEY is supported for CREATE TABLE", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    DefineCommand constraint = constraints.get(0);
    if (!(constraint instanceof AlterTableAddConstraint))
        throw new IgniteSQLException("Unsupported type of constraint for CREATE TABLE - only PRIMARY KEY " + "is supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    AlterTableAddConstraint alterTbl = (AlterTableAddConstraint) constraint;
    if (alterTbl.getType() != Command.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY)
        throw new IgniteSQLException("Unsupported type of constraint for CREATE TABLE - only PRIMARY KEY " + "is supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    Schema schema = SCHEMA_COMMAND_SCHEMA.get(createTbl);
    res.schemaName(schema.getName());
    CreateTableData data = CREATE_TABLE_DATA.get(createTbl);
    LinkedHashMap<String, GridSqlColumn> cols = new LinkedHashMap<>(data.columns.size());
    for (Column col : data.columns) {
        if (col.isAutoIncrement())
            throw new IgniteSQLException("AUTO_INCREMENT columns are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (!col.isNullable())
            throw new IgniteSQLException("Non nullable columns are forbidden [colName=" + col.getName() + ']', IgniteQueryErrorCode.PARSING);
        if (COLUMN_IS_COMPUTED.get(col))
            throw new IgniteSQLException("Computed columns are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (col.getDefaultExpression() != null)
            throw new IgniteSQLException("DEFAULT expressions are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (col.getSequence() != null)
            throw new IgniteSQLException("SEQUENCE columns are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (col.getSelectivity() != Constants.SELECTIVITY_DEFAULT)
            throw new IgniteSQLException("SELECTIVITY column attr is not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        if (COLUMN_CHECK_CONSTRAINT.get(col) != null)
            throw new IgniteSQLException("Column CHECK constraints are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
        GridSqlColumn gridCol = new GridSqlColumn(col, null, col.getName());
        gridCol.resultType(GridSqlType.fromColumn(col));
        cols.put(col.getName(), gridCol);
    }
    if (cols.containsKey(QueryUtils.KEY_FIELD_NAME.toUpperCase()) || cols.containsKey(QueryUtils.VAL_FIELD_NAME.toUpperCase()))
        throw new IgniteSQLException("Direct specification of _KEY and _VAL columns is forbidden", IgniteQueryErrorCode.PARSING);
    IndexColumn[] pkIdxCols = CREATE_TABLE_PK.get(createTbl);
    if (F.isEmpty(pkIdxCols))
        throw new AssertionError("No PRIMARY KEY columns specified");
    LinkedHashSet<String> pkCols = new LinkedHashSet<>();
    for (IndexColumn pkIdxCol : pkIdxCols) {
        GridSqlColumn gridCol = cols.get(pkIdxCol.columnName);
        assert gridCol != null;
        pkCols.add(gridCol.columnName());
    }
    int valColsNum = cols.size() - pkCols.size();
    if (valColsNum == 0)
        throw new IgniteSQLException("No cache value related columns found");
    res.columns(cols);
    res.primaryKeyColumns(pkCols);
    res.tableName(data.tableName);
    res.ifNotExists(CREATE_TABLE_IF_NOT_EXISTS.get(createTbl));
    List<String> extraParams = data.tableEngineParams != null ? new ArrayList<String>() : null;
    if (data.tableEngineParams != null)
        for (String s : data.tableEngineParams) extraParams.addAll(F.asList(s.split(",")));
    res.params(extraParams);
    if (!F.isEmpty(extraParams)) {
        Map<String, String> params = new HashMap<>();
        for (String p : extraParams) {
            String[] parts = p.split(PARAM_NAME_VALUE_SEPARATOR);
            if (parts.length > 2)
                throw new IgniteSQLException("Invalid parameter (key[=value] expected): " + p, IgniteQueryErrorCode.PARSING);
            String name = parts[0].trim().toUpperCase();
            String val = parts.length > 1 ? parts[1].trim() : null;
            if (F.isEmpty(name))
                throw new IgniteSQLException("Invalid parameter (key[=value] expected): " + p, IgniteQueryErrorCode.PARSING);
            if (params.put(name, val) != null)
                throw new IgniteSQLException("Duplicate parameter: " + p, IgniteQueryErrorCode.PARSING);
        }
        for (Map.Entry<String, String> e : params.entrySet()) processExtraParam(e.getKey(), e.getValue(), res);
    }
    return res;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Query(org.h2.command.dml.Query) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) Schema(org.h2.schema.Schema) DefineCommand(org.h2.command.ddl.DefineCommand) LinkedHashMap(java.util.LinkedHashMap) IndexColumn(org.h2.table.IndexColumn) GridSqlType.fromColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) CreateTableData(org.h2.command.ddl.CreateTableData) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap)

Example 4 with GridSqlColumn

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn in project ignite by apache.

the class DmlAstUtils method selectForDelete.

/**
     * Generate SQL SELECT based on DELETE's WHERE, LIMIT, etc.
     *
     * @param del Delete statement.
     * @param keysParamIdx Index for .
     * @return SELECT statement.
     */
public static GridSqlSelect selectForDelete(GridSqlDelete del, @Nullable Integer keysParamIdx) {
    GridSqlSelect mapQry = new GridSqlSelect();
    mapQry.from(del.from());
    Set<GridSqlTable> tbls = new HashSet<>();
    collectAllGridTablesInTarget(del.from(), tbls);
    assert tbls.size() == 1 : "Failed to determine target table for DELETE";
    GridSqlTable tbl = tbls.iterator().next();
    GridH2Table gridTbl = tbl.dataTable();
    assert gridTbl != null : "Failed to determine target grid table for DELETE";
    Column h2KeyCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.KEY_COL);
    Column h2ValCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.VAL_COL);
    GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
    keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
    GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
    valCol.resultType(GridSqlType.fromColumn(h2ValCol));
    mapQry.addColumn(keyCol, true);
    mapQry.addColumn(valCol, true);
    GridSqlElement where = del.where();
    if (keysParamIdx != null)
        where = injectKeysFilterParam(where, keyCol, keysParamIdx);
    mapQry.where(where);
    mapQry.limit(del.limit());
    return mapQry;
}
Also used : Column(org.h2.table.Column) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) HashSet(java.util.HashSet)

Example 5 with GridSqlColumn

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn in project ignite by apache.

the class GridSqlQuerySplitter method extractPartitionFromEquality.

/**
     * Analyses the equality operation and extracts the partition if possible
     *
     * @param op AST equality operation.
     * @param ctx Kernal Context.
     * @return partition info, or {@code null} if none identified
     */
private static CacheQueryPartitionInfo extractPartitionFromEquality(GridSqlOperation op, GridKernalContext ctx) throws IgniteCheckedException {
    assert op.operationType() == GridSqlOperationType.EQUAL;
    GridSqlElement left = op.child(0);
    GridSqlElement right = op.child(1);
    if (!(left instanceof GridSqlColumn))
        return null;
    if (!(right instanceof GridSqlConst) && !(right instanceof GridSqlParameter))
        return null;
    GridSqlColumn column = (GridSqlColumn) left;
    assert column.column().getTable() instanceof GridH2Table;
    GridH2Table tbl = (GridH2Table) column.column().getTable();
    GridH2RowDescriptor desc = tbl.rowDescriptor();
    IndexColumn affKeyCol = tbl.getAffinityKeyColumn();
    int colId = column.column().getColumnId();
    if ((affKeyCol == null || colId != affKeyCol.column.getColumnId()) && !desc.isKeyColumn(colId))
        return null;
    if (right instanceof GridSqlConst) {
        GridSqlConst constant = (GridSqlConst) right;
        return new CacheQueryPartitionInfo(ctx.affinity().partition(tbl.cacheName(), constant.value().getObject()), null, -1);
    }
    assert right instanceof GridSqlParameter;
    GridSqlParameter param = (GridSqlParameter) right;
    return new CacheQueryPartitionInfo(-1, tbl.cacheName(), param.index());
}
Also used : GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) CacheQueryPartitionInfo(org.apache.ignite.internal.processors.cache.query.CacheQueryPartitionInfo) IndexColumn(org.h2.table.IndexColumn)

Aggregations

Column (org.h2.table.Column)9 IndexColumn (org.h2.table.IndexColumn)6 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)5 GridSqlType.fromColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn)5 ExpressionColumn (org.h2.expression.ExpressionColumn)5 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)4 GridSqlType.fromExpression (org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromExpression)4 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)4 Expression (org.h2.expression.Expression)4 ValueExpression (org.h2.expression.ValueExpression)4 ArrayList (java.util.ArrayList)3 LinkedHashMap (java.util.LinkedHashMap)3 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)3 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)3 HashSet (java.util.HashSet)2 Map (java.util.Map)2 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)2 GridSqlSelect (org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)2 GridSqlTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable)2 CreateTable (org.h2.command.ddl.CreateTable)2