Search in sources :

Example 1 with CreateTableData

use of org.h2.command.ddl.CreateTableData in project h2database by h2database.

the class AlterTableAlterColumn method cloneTableStructure.

private Table cloneTableStructure(Table table, Column[] columns, Database db, String tempName, ArrayList<Column> newColumns) {
    for (Column col : columns) {
        newColumns.add(col.getClone());
    }
    if (type == CommandInterface.ALTER_TABLE_DROP_COLUMN) {
        for (Column removeCol : columnsToRemove) {
            Column foundCol = null;
            for (Column newCol : newColumns) {
                if (newCol.getName().equals(removeCol.getName())) {
                    foundCol = newCol;
                    break;
                }
            }
            if (foundCol == null) {
                throw DbException.throwInternalError(removeCol.getCreateSQL());
            }
            newColumns.remove(foundCol);
        }
    } else if (type == CommandInterface.ALTER_TABLE_ADD_COLUMN) {
        int position;
        if (addFirst) {
            position = 0;
        } else if (addBefore != null) {
            position = table.getColumn(addBefore).getColumnId();
        } else if (addAfter != null) {
            position = table.getColumn(addAfter).getColumnId() + 1;
        } else {
            position = columns.length;
        }
        if (columnsToAdd != null) {
            for (Column column : columnsToAdd) {
                newColumns.add(position++, column);
            }
        }
    } else if (type == CommandInterface.ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE) {
        int position = oldColumn.getColumnId();
        newColumns.set(position, newColumn);
    }
    // create a table object in order to get the SQL statement
    // can't just use this table, because most column objects are 'shared'
    // with the old table
    // still need a new id because using 0 would mean: the new table tries
    // to use the rows of the table 0 (the meta table)
    int id = db.allocateObjectId();
    CreateTableData data = new CreateTableData();
    data.tableName = tempName;
    data.id = id;
    data.columns = newColumns;
    data.temporary = table.isTemporary();
    data.persistData = table.isPersistData();
    data.persistIndexes = table.isPersistIndexes();
    data.isHidden = table.isHidden();
    data.create = true;
    data.session = session;
    Table newTable = getSchema().createTable(data);
    newTable.setComment(table.getComment());
    StringBuilder buff = new StringBuilder();
    buff.append(newTable.getCreateSQL());
    StringBuilder columnList = new StringBuilder();
    for (Column nc : newColumns) {
        if (columnList.length() > 0) {
            columnList.append(", ");
        }
        if (type == CommandInterface.ALTER_TABLE_ADD_COLUMN && columnsToAdd != null && columnsToAdd.contains(nc)) {
            Expression def = nc.getDefaultExpression();
            columnList.append(def == null ? "NULL" : def.getSQL());
        } else {
            columnList.append(nc.getSQL());
        }
    }
    buff.append(" AS SELECT ");
    if (columnList.length() == 0) {
        // special case: insert into test select * from
        buff.append('*');
    } else {
        buff.append(columnList);
    }
    buff.append(" FROM ").append(table.getSQL());
    String newTableSQL = buff.toString();
    String newTableName = newTable.getName();
    Schema newTableSchema = newTable.getSchema();
    newTable.removeChildrenAndResources(session);
    execute(newTableSQL, true);
    newTable = newTableSchema.getTableOrView(session, newTableName);
    ArrayList<String> triggers = New.arrayList();
    for (DbObject child : table.getChildren()) {
        if (child instanceof Sequence) {
            continue;
        } else if (child instanceof Index) {
            Index idx = (Index) child;
            if (idx.getIndexType().getBelongsToConstraint()) {
                continue;
            }
        }
        String createSQL = child.getCreateSQL();
        if (createSQL == null) {
            continue;
        }
        if (child instanceof TableView) {
            continue;
        } else if (child.getType() == DbObject.TABLE_OR_VIEW) {
            DbException.throwInternalError();
        }
        String quotedName = Parser.quoteIdentifier(tempName + "_" + child.getName());
        String sql = null;
        if (child instanceof ConstraintReferential) {
            ConstraintReferential r = (ConstraintReferential) child;
            if (r.getTable() != table) {
                sql = r.getCreateSQLForCopy(r.getTable(), newTable, quotedName, false);
            }
        }
        if (sql == null) {
            sql = child.getCreateSQLForCopy(newTable, quotedName);
        }
        if (sql != null) {
            if (child instanceof TriggerObject) {
                triggers.add(sql);
            } else {
                execute(sql, true);
            }
        }
    }
    table.setModified();
    // otherwise the sequence is dropped if the table is dropped
    for (Column col : newColumns) {
        Sequence seq = col.getSequence();
        if (seq != null) {
            table.removeSequence(seq);
            col.setSequence(null);
        }
    }
    for (String sql : triggers) {
        execute(sql, true);
    }
    return newTable;
}
Also used : Table(org.h2.table.Table) DbObject(org.h2.engine.DbObject) Schema(org.h2.schema.Schema) TriggerObject(org.h2.schema.TriggerObject) Index(org.h2.index.Index) Sequence(org.h2.schema.Sequence) ConstraintReferential(org.h2.constraint.ConstraintReferential) Constraint(org.h2.constraint.Constraint) Column(org.h2.table.Column) Expression(org.h2.expression.Expression) TableView(org.h2.table.TableView)

Example 2 with CreateTableData

use of org.h2.command.ddl.CreateTableData in project h2database by h2database.

the class PageStore method openMetaIndex.

private void openMetaIndex() {
    CreateTableData data = new CreateTableData();
    ArrayList<Column> cols = data.columns;
    cols.add(new Column("ID", Value.INT));
    cols.add(new Column("TYPE", Value.INT));
    cols.add(new Column("PARENT", Value.INT));
    cols.add(new Column("HEAD", Value.INT));
    cols.add(new Column("OPTIONS", Value.STRING));
    cols.add(new Column("COLUMNS", Value.STRING));
    metaSchema = new Schema(database, 0, "", null, true);
    data.schema = metaSchema;
    data.tableName = "PAGE_INDEX";
    data.id = META_TABLE_ID;
    data.temporary = false;
    data.persistData = true;
    data.persistIndexes = true;
    data.create = false;
    data.session = pageStoreSession;
    metaTable = new RegularTable(data);
    metaIndex = (PageDataIndex) metaTable.getScanIndex(pageStoreSession);
    metaObjects.clear();
    metaObjects.put(-1, metaIndex);
}
Also used : IndexColumn(org.h2.table.IndexColumn) Column(org.h2.table.Column) Schema(org.h2.schema.Schema) RegularTable(org.h2.table.RegularTable) CreateTableData(org.h2.command.ddl.CreateTableData)

Example 3 with CreateTableData

use of org.h2.command.ddl.CreateTableData in project h2database by h2database.

the class PageStore method addMeta.

private void addMeta(Row row, Session session, boolean redo) {
    int id = row.getValue(0).getInt();
    int type = row.getValue(1).getInt();
    int parent = row.getValue(2).getInt();
    int rootPageId = row.getValue(3).getInt();
    String[] options = StringUtils.arraySplit(row.getValue(4).getString(), ',', false);
    String columnList = row.getValue(5).getString();
    String[] columns = StringUtils.arraySplit(columnList, ',', false);
    Index meta;
    if (trace.isDebugEnabled()) {
        trace.debug("addMeta id=" + id + " type=" + type + " root=" + rootPageId + " parent=" + parent + " columns=" + columnList);
    }
    if (redo && rootPageId != 0) {
        // ensure the page is empty, but not used by regular data
        writePage(rootPageId, createData());
        allocatePage(rootPageId);
    }
    metaRootPageId.put(id, rootPageId);
    if (type == META_TYPE_DATA_INDEX) {
        CreateTableData data = new CreateTableData();
        if (SysProperties.CHECK) {
            if (columns == null) {
                throw DbException.throwInternalError(row.toString());
            }
        }
        for (int i = 0, len = columns.length; i < len; i++) {
            Column col = new Column("C" + i, Value.INT);
            data.columns.add(col);
        }
        data.schema = metaSchema;
        data.tableName = "T" + id;
        data.id = id;
        data.temporary = options[2].equals("temp");
        data.persistData = true;
        data.persistIndexes = true;
        data.create = false;
        data.session = session;
        RegularTable table = new RegularTable(data);
        boolean binaryUnsigned = SysProperties.SORT_BINARY_UNSIGNED;
        if (options.length > 3) {
            binaryUnsigned = Boolean.parseBoolean(options[3]);
        }
        CompareMode mode = CompareMode.getInstance(options[0], Integer.parseInt(options[1]), binaryUnsigned);
        table.setCompareMode(mode);
        meta = table.getScanIndex(session);
    } else {
        Index p = metaObjects.get(parent);
        if (p == null) {
            throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "Table not found:" + parent + " for " + row + " meta:" + metaObjects);
        }
        RegularTable table = (RegularTable) p.getTable();
        Column[] tableCols = table.getColumns();
        int len = columns.length;
        IndexColumn[] cols = new IndexColumn[len];
        for (int i = 0; i < len; i++) {
            String c = columns[i];
            IndexColumn ic = new IndexColumn();
            int idx = c.indexOf('/');
            if (idx >= 0) {
                String s = c.substring(idx + 1);
                ic.sortType = Integer.parseInt(s);
                c = c.substring(0, idx);
            }
            ic.column = tableCols[Integer.parseInt(c)];
            cols[i] = ic;
        }
        IndexType indexType;
        if (options[3].equals("d")) {
            indexType = IndexType.createPrimaryKey(true, false);
            Column[] tableColumns = table.getColumns();
            for (IndexColumn indexColumn : cols) {
                tableColumns[indexColumn.column.getColumnId()].setNullable(false);
            }
        } else {
            indexType = IndexType.createNonUnique(true);
        }
        meta = table.addIndex(session, "I" + id, id, cols, indexType, false, null);
    }
    PageIndex index;
    if (meta instanceof MultiVersionIndex) {
        index = (PageIndex) ((MultiVersionIndex) meta).getBaseIndex();
    } else {
        index = (PageIndex) meta;
    }
    metaObjects.put(id, index);
}
Also used : Index(org.h2.index.Index) PageIndex(org.h2.index.PageIndex) PageDelegateIndex(org.h2.index.PageDelegateIndex) MultiVersionIndex(org.h2.index.MultiVersionIndex) PageBtreeIndex(org.h2.index.PageBtreeIndex) PageDataIndex(org.h2.index.PageDataIndex) ValueString(org.h2.value.ValueString) PageIndex(org.h2.index.PageIndex) CreateTableData(org.h2.command.ddl.CreateTableData) IndexColumn(org.h2.table.IndexColumn) IndexColumn(org.h2.table.IndexColumn) Column(org.h2.table.Column) MultiVersionIndex(org.h2.index.MultiVersionIndex) RegularTable(org.h2.table.RegularTable) CompareMode(org.h2.value.CompareMode) IndexType(org.h2.index.IndexType)

Example 4 with CreateTableData

use of org.h2.command.ddl.CreateTableData in project h2database by h2database.

the class MVTableEngine method createTable.

@Override
public TableBase createTable(CreateTableData data) {
    Database db = data.session.getDatabase();
    Store store = init(db);
    MVTable table = new MVTable(data, store);
    table.init(data.session);
    store.tableMap.put(table.getMapName(), table);
    return table;
}
Also used : Database(org.h2.engine.Database) MVStore(org.h2.mvstore.MVStore) FileStore(org.h2.mvstore.FileStore)

Example 5 with CreateTableData

use of org.h2.command.ddl.CreateTableData in project ignite by apache.

the class GridReduceQueryExecutor method createMergeTable.

/**
 * @param conn Connection.
 * @param qry Query.
 * @param explain Explain.
 * @return Table.
 * @throws IgniteCheckedException If failed.
 */
@SuppressWarnings("unchecked")
private ReduceTable createMergeTable(H2PooledConnection conn, GridCacheSqlQuery qry, boolean explain) throws IgniteCheckedException {
    try {
        Session ses = H2Utils.session(conn);
        CreateTableData data = new CreateTableData();
        data.tableName = "T___";
        data.schema = ses.getDatabase().getSchema(ses.getCurrentSchemaName());
        data.create = true;
        if (!explain) {
            LinkedHashMap<String, ?> colsMap = qry.columns();
            assert colsMap != null;
            ArrayList<Column> cols = new ArrayList<>(colsMap.size());
            for (Map.Entry<String, ?> e : colsMap.entrySet()) {
                String alias = e.getKey();
                GridSqlType type = (GridSqlType) e.getValue();
                assert !F.isEmpty(alias);
                Column col0;
                if (type == GridSqlType.UNKNOWN) {
                    // Special case for parameter being set at the top of the query (e.g. SELECT ? FROM ...).
                    // Re-map it to STRING in the same way it is done in H2, because any argument can be cast
                    // to string.
                    col0 = new Column(alias, Value.STRING);
                } else {
                    col0 = new Column(alias, type.type(), type.precision(), type.scale(), type.displaySize());
                }
                cols.add(col0);
            }
            data.columns = cols;
        } else
            data.columns = planColumns();
        boolean sortedIndex = !F.isEmpty(qry.sortColumns());
        ReduceTable tbl = new ReduceTable(data);
        ArrayList<Index> idxs = new ArrayList<>(2);
        if (explain) {
            idxs.add(new UnsortedReduceIndexAdapter(ctx, tbl, sortedIndex ? MERGE_INDEX_SORTED : MERGE_INDEX_UNSORTED));
        } else if (sortedIndex) {
            List<GridSqlSortColumn> sortCols = (List<GridSqlSortColumn>) qry.sortColumns();
            SortedReduceIndexAdapter sortedMergeIdx = new SortedReduceIndexAdapter(ctx, tbl, MERGE_INDEX_SORTED, GridSqlSortColumn.toIndexColumns(tbl, sortCols));
            idxs.add(ReduceTable.createScanIndex(sortedMergeIdx));
            idxs.add(sortedMergeIdx);
        } else
            idxs.add(new UnsortedReduceIndexAdapter(ctx, tbl, MERGE_INDEX_UNSORTED));
        tbl.indexes(idxs);
        return tbl;
    } catch (Exception e) {
        throw new IgniteCheckedException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) Index(org.h2.index.Index) CreateTableData(org.h2.command.ddl.CreateTableData) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) TransactionAlreadyCompletedException(org.apache.ignite.transactions.TransactionAlreadyCompletedException) IgniteTxAlreadyCompletedCheckedException(org.apache.ignite.internal.transactions.IgniteTxAlreadyCompletedCheckedException) QueryRetryException(org.apache.ignite.cache.query.QueryRetryException) SQLException(java.sql.SQLException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) CacheException(javax.cache.CacheException) TransactionException(org.apache.ignite.transactions.TransactionException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridSqlSortColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) Column(org.h2.table.Column) GridSqlSortColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) GridSqlType(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap) Collections.singletonMap(java.util.Collections.singletonMap) Session(org.h2.engine.Session)

Aggregations

CreateTableData (org.h2.command.ddl.CreateTableData)7 Column (org.h2.table.Column)7 Index (org.h2.index.Index)4 Schema (org.h2.schema.Schema)4 IndexColumn (org.h2.table.IndexColumn)4 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)3 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 Collections.singletonList (java.util.Collections.singletonList)2 List (java.util.List)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 CacheException (javax.cache.CacheException)2 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)2 IgniteClientDisconnectedException (org.apache.ignite.IgniteClientDisconnectedException)2 IgniteException (org.apache.ignite.IgniteException)2 QueryCancelledException (org.apache.ignite.cache.query.QueryCancelledException)2 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)2