Search in sources :

Example 1 with GridSqlCreateTable

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateTable 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 2 with GridSqlCreateTable

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateTable 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 3 with GridSqlCreateTable

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

the class DdlStatementsProcessor method toQueryEntity.

/**
     * Convert this statement to query entity and do Ignite specific sanity checks on the way.
     * @return Query entity mimicking this SQL statement.
     */
private static QueryEntity toQueryEntity(GridSqlCreateTable createTbl) {
    QueryEntity res = new QueryEntity();
    res.setTableName(createTbl.tableName());
    for (Map.Entry<String, GridSqlColumn> e : createTbl.columns().entrySet()) {
        GridSqlColumn gridCol = e.getValue();
        Column col = gridCol.column();
        res.addQueryField(e.getKey(), DataType.getTypeClassName(col.getType()), null);
    }
    res.setKeyType(createTbl.tableName() + "Key");
    res.setValueType(createTbl.tableName());
    res.setKeyFields(createTbl.primaryKeyColumns());
    return res;
}
Also used : Column(org.h2.table.Column) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) QueryEntity(org.apache.ignite.cache.QueryEntity) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)3 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)2 Column (org.h2.table.Column)2 HashMap (java.util.HashMap)1 IdentityHashMap (java.util.IdentityHashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)1 QueryEntity (org.apache.ignite.cache.QueryEntity)1 QueryIndex (org.apache.ignite.cache.QueryIndex)1 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)1 QueryCursorImpl (org.apache.ignite.internal.processors.cache.QueryCursorImpl)1 GridQueryProperty (org.apache.ignite.internal.processors.query.GridQueryProperty)1 GridQueryTypeDescriptor (org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor)1 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)1 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)1 GridSqlCreateIndex (org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateIndex)1 GridSqlCreateTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateTable)1 GridSqlDropIndex (org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropIndex)1