Search in sources :

Example 11 with Sequence

use of org.h2.schema.Sequence in project h2database by h2database.

the class ScriptCommand method query.

@Override
public ResultInterface query(int maxrows) {
    session.getUser().checkAdmin();
    reset();
    Database db = session.getDatabase();
    if (schemaNames != null) {
        for (String schemaName : schemaNames) {
            Schema schema = db.findSchema(schemaName);
            if (schema == null) {
                throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
            }
        }
    }
    try {
        result = createResult();
        deleteStore();
        openOutput();
        if (out != null) {
            buffer = new byte[Constants.IO_BUFFER_SIZE];
        }
        if (settings) {
            for (Setting setting : db.getAllSettings()) {
                if (setting.getName().equals(SetTypes.getTypeName(SetTypes.CREATE_BUILD))) {
                    // (it is only set when creating the database)
                    continue;
                }
                add(setting.getCreateSQL(), false);
            }
        }
        if (out != null) {
            add("", true);
        }
        for (User user : db.getAllUsers()) {
            add(user.getCreateSQL(passwords), false);
        }
        for (Role role : db.getAllRoles()) {
            add(role.getCreateSQL(true), false);
        }
        for (Schema schema : db.getAllSchemas()) {
            if (excludeSchema(schema)) {
                continue;
            }
            add(schema.getCreateSQL(), false);
        }
        for (UserDataType datatype : db.getAllUserDataTypes()) {
            if (drop) {
                add(datatype.getDropSQL(), false);
            }
            add(datatype.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.CONSTANT)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constant constant = (Constant) obj;
            add(constant.getCreateSQL(), false);
        }
        final ArrayList<Table> tables = db.getAllTablesAndViews(false);
        // sort by id, so that views are after tables and views on views
        // after the base views
        Collections.sort(tables, new Comparator<Table>() {

            @Override
            public int compare(Table t1, Table t2) {
                return t1.getId() - t2.getId();
            }
        });
        // Generate the DROP XXX  ... IF EXISTS
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String sql = table.getCreateSQL();
            if (sql == null) {
                // null for metadata tables
                continue;
            }
            if (drop) {
                add(table.getDropSQL(), false);
            }
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.FUNCTION_ALIAS)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            if (drop) {
                add(obj.getDropSQL(), false);
            }
            add(obj.getCreateSQL(), false);
        }
        for (UserAggregate agg : db.getAllAggregates()) {
            if (drop) {
                add(agg.getDropSQL(), false);
            }
            add(agg.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.SEQUENCE)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Sequence sequence = (Sequence) obj;
            if (drop) {
                add(sequence.getDropSQL(), false);
            }
            add(sequence.getCreateSQL(), false);
        }
        // Generate CREATE TABLE and INSERT...VALUES
        int count = 0;
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String createTableSql = table.getCreateSQL();
            if (createTableSql == null) {
                // null for metadata tables
                continue;
            }
            final TableType tableType = table.getTableType();
            add(createTableSql, false);
            final ArrayList<Constraint> constraints = table.getConstraints();
            if (constraints != null) {
                for (Constraint constraint : constraints) {
                    if (Constraint.Type.PRIMARY_KEY == constraint.getConstraintType()) {
                        add(constraint.getCreateSQLWithoutIndexes(), false);
                    }
                }
            }
            if (TableType.TABLE == tableType) {
                if (table.canGetRowCount()) {
                    String rowcount = "-- " + table.getRowCountApproximation() + " +/- SELECT COUNT(*) FROM " + table.getSQL();
                    add(rowcount, false);
                }
                if (data) {
                    count = generateInsertValues(count, table);
                }
            }
            final ArrayList<Index> indexes = table.getIndexes();
            for (int j = 0; indexes != null && j < indexes.size(); j++) {
                Index index = indexes.get(j);
                if (!index.getIndexType().getBelongsToConstraint()) {
                    add(index.getCreateSQL(), false);
                }
            }
        }
        if (tempLobTableCreated) {
            add("DROP TABLE IF EXISTS SYSTEM_LOB_STREAM", true);
            add("CALL SYSTEM_COMBINE_BLOB(-1)", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_CLOB", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_BLOB", true);
            tempLobTableCreated = false;
        }
        // Generate CREATE CONSTRAINT ...
        final ArrayList<SchemaObject> constraints = db.getAllSchemaObjects(DbObject.CONSTRAINT);
        Collections.sort(constraints, new Comparator<SchemaObject>() {

            @Override
            public int compare(SchemaObject c1, SchemaObject c2) {
                return ((Constraint) c1).compareTo((Constraint) c2);
            }
        });
        for (SchemaObject obj : constraints) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constraint constraint = (Constraint) obj;
            if (excludeTable(constraint.getTable())) {
                continue;
            }
            if (constraint.getTable().isHidden()) {
                continue;
            }
            if (Constraint.Type.PRIMARY_KEY != constraint.getConstraintType()) {
                add(constraint.getCreateSQLWithoutIndexes(), false);
            }
        }
        // Generate CREATE TRIGGER ...
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.TRIGGER)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            TriggerObject trigger = (TriggerObject) obj;
            if (excludeTable(trigger.getTable())) {
                continue;
            }
            add(trigger.getCreateSQL(), false);
        }
        // Generate GRANT ...
        for (Right right : db.getAllRights()) {
            DbObject object = right.getGrantedObject();
            if (object != null) {
                if (object instanceof Schema) {
                    if (excludeSchema((Schema) object)) {
                        continue;
                    }
                } else if (object instanceof Table) {
                    Table table = (Table) object;
                    if (excludeSchema(table.getSchema())) {
                        continue;
                    }
                    if (excludeTable(table)) {
                        continue;
                    }
                }
            }
            add(right.getCreateSQL(), false);
        }
        // Generate COMMENT ON ...
        for (Comment comment : db.getAllComments()) {
            add(comment.getCreateSQL(), false);
        }
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        throw DbException.convertIOException(e, getFileName());
    } finally {
        closeIO();
    }
    result.done();
    LocalResult r = result;
    reset();
    return r;
}
Also used : SchemaObject(org.h2.schema.SchemaObject) User(org.h2.engine.User) Constraint(org.h2.constraint.Constraint) Constant(org.h2.schema.Constant) Schema(org.h2.schema.Schema) Right(org.h2.engine.Right) TriggerObject(org.h2.schema.TriggerObject) Index(org.h2.index.Index) ValueString(org.h2.value.ValueString) LocalResult(org.h2.result.LocalResult) Database(org.h2.engine.Database) Comment(org.h2.engine.Comment) Table(org.h2.table.Table) TableType(org.h2.table.TableType) DbObject(org.h2.engine.DbObject) Setting(org.h2.engine.Setting) UserDataType(org.h2.engine.UserDataType) Sequence(org.h2.schema.Sequence) IOException(java.io.IOException) Constraint(org.h2.constraint.Constraint) Role(org.h2.engine.Role) UserAggregate(org.h2.engine.UserAggregate)

Example 12 with Sequence

use of org.h2.schema.Sequence in project h2database by h2database.

the class AlterSequence method update.

@Override
public int update() {
    Database db = session.getDatabase();
    if (sequence == null) {
        sequence = getSchema().findSequence(sequenceName);
        if (sequence == null) {
            if (!ifExists) {
                throw DbException.get(ErrorCode.SEQUENCE_NOT_FOUND_1, sequenceName);
            }
            return 0;
        }
    }
    if (table != null) {
        session.getUser().checkRight(table, Right.ALL);
    }
    if (cycle != null) {
        sequence.setCycle(cycle);
    }
    if (cacheSize != null) {
        long size = cacheSize.optimize(session).getValue(session).getLong();
        sequence.setCacheSize(size);
    }
    if (start != null || minValue != null || maxValue != null || increment != null) {
        Long startValue = getLong(start);
        Long min = getLong(minValue);
        Long max = getLong(maxValue);
        Long inc = getLong(increment);
        sequence.modify(startValue, min, max, inc);
    }
    db.updateMeta(session, sequence);
    return 0;
}
Also used : Database(org.h2.engine.Database)

Example 13 with Sequence

use of org.h2.schema.Sequence in project h2database by h2database.

the class CreateSequence method update.

@Override
public int update() {
    session.commit(true);
    Database db = session.getDatabase();
    if (getSchema().findSequence(sequenceName) != null) {
        if (ifNotExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.SEQUENCE_ALREADY_EXISTS_1, sequenceName);
    }
    int id = getObjectId();
    Long startValue = getLong(start);
    Long inc = getLong(increment);
    Long cache = getLong(cacheSize);
    Long min = getLong(minValue);
    Long max = getLong(maxValue);
    Sequence sequence = new Sequence(getSchema(), id, sequenceName, startValue, inc, cache, min, max, cycle, belongsToTable);
    db.addSchemaObject(session, sequence);
    return 0;
}
Also used : Database(org.h2.engine.Database) Sequence(org.h2.schema.Sequence)

Example 14 with Sequence

use of org.h2.schema.Sequence in project h2database by h2database.

the class CreateTable method update.

@Override
public int update() {
    if (!transactional) {
        session.commit(true);
    }
    Database db = session.getDatabase();
    if (!db.isPersistent()) {
        data.persistIndexes = false;
    }
    boolean isSessionTemporary = data.temporary && !data.globalTemporary;
    if (!isSessionTemporary) {
        db.lockMeta(session);
    }
    if (getSchema().resolveTableOrView(session, data.tableName) != null) {
        if (ifNotExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, data.tableName);
    }
    if (asQuery != null) {
        asQuery.prepare();
        if (data.columns.isEmpty()) {
            generateColumnsFromQuery();
        } else if (data.columns.size() != asQuery.getColumnCount()) {
            throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
        }
    }
    changePrimaryKeysToNotNull(data.columns);
    data.id = getObjectId();
    data.create = create;
    data.session = session;
    Table table = getSchema().createTable(data);
    ArrayList<Sequence> sequences = generateSequences(data.columns, data.temporary);
    table.setComment(comment);
    if (isSessionTemporary) {
        if (onCommitDrop) {
            table.setOnCommitDrop(true);
        }
        if (onCommitTruncate) {
            table.setOnCommitTruncate(true);
        }
        session.addLocalTempTable(table);
    } else {
        db.lockMeta(session);
        db.addSchemaObject(session, table);
    }
    try {
        for (Column c : data.columns) {
            c.prepareExpression(session);
        }
        for (Sequence sequence : sequences) {
            table.addSequence(sequence);
        }
        createConstraints();
        if (asQuery != null) {
            boolean old = session.isUndoLogEnabled();
            try {
                session.setUndoLogEnabled(false);
                session.startStatementWithinTransaction();
                Insert insert = new Insert(session);
                insert.setSortedInsertMode(sortedInsertMode);
                insert.setQuery(asQuery);
                insert.setTable(table);
                insert.setInsertFromSelect(true);
                insert.prepare();
                insert.update();
            } finally {
                session.setUndoLogEnabled(old);
            }
        }
        HashSet<DbObject> set = new HashSet<>();
        set.clear();
        table.addDependencies(set);
        for (DbObject obj : set) {
            if (obj == table) {
                continue;
            }
            if (obj.getType() == DbObject.TABLE_OR_VIEW) {
                if (obj instanceof Table) {
                    Table t = (Table) obj;
                    if (t.getId() > table.getId()) {
                        throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, "Table depends on another table " + "with a higher ID: " + t + ", this is currently not supported, " + "as it would prevent the database from " + "being re-opened");
                    }
                }
            }
        }
    } catch (DbException e) {
        db.checkPowerOff();
        db.removeSchemaObject(session, table);
        if (!transactional) {
            session.commit(true);
        }
        throw e;
    }
    return 0;
}
Also used : Table(org.h2.table.Table) ExpressionColumn(org.h2.expression.ExpressionColumn) Column(org.h2.table.Column) DbObject(org.h2.engine.DbObject) Database(org.h2.engine.Database) Sequence(org.h2.schema.Sequence) Insert(org.h2.command.dml.Insert) HashSet(java.util.HashSet) DbException(org.h2.message.DbException)

Example 15 with Sequence

use of org.h2.schema.Sequence in project h2database by h2database.

the class Function method getSequence.

private Sequence getSequence(Session session, Value v0, Value v1) {
    String schemaName, sequenceName;
    if (v1 == null) {
        Parser p = new Parser(session);
        String sql = v0.getString();
        Expression expr = p.parseExpression(sql);
        if (expr instanceof ExpressionColumn) {
            ExpressionColumn seq = (ExpressionColumn) expr;
            schemaName = seq.getOriginalTableAliasName();
            if (schemaName == null) {
                schemaName = session.getCurrentSchemaName();
                sequenceName = sql;
            } else {
                sequenceName = seq.getColumnName();
            }
        } else {
            throw DbException.getSyntaxError(sql, 1);
        }
    } else {
        schemaName = v0.getString();
        sequenceName = v1.getString();
    }
    Schema s = database.findSchema(schemaName);
    if (s == null) {
        schemaName = StringUtils.toUpperEnglish(schemaName);
        s = database.getSchema(schemaName);
    }
    Sequence seq = s.findSequence(sequenceName);
    if (seq == null) {
        sequenceName = StringUtils.toUpperEnglish(sequenceName);
        seq = s.getSequence(sequenceName);
    }
    return seq;
}
Also used : Schema(org.h2.schema.Schema) LinkSchema(org.h2.table.LinkSchema) ValueString(org.h2.value.ValueString) Sequence(org.h2.schema.Sequence) ToDateParser(org.h2.util.ToDateParser) Parser(org.h2.command.Parser)

Aggregations

Sequence (org.h2.schema.Sequence)19 ValueString (org.h2.value.ValueString)14 PreparedStatement (java.sql.PreparedStatement)10 Column (org.h2.table.Column)10 Database (org.h2.engine.Database)9 Expression (org.h2.expression.Expression)8 DbException (org.h2.message.DbException)8 Table (org.h2.table.Table)8 ResultSet (java.sql.ResultSet)7 Statement (java.sql.Statement)7 Constraint (org.h2.constraint.Constraint)7 Index (org.h2.index.Index)7 Connection (java.sql.Connection)6 SQLException (java.sql.SQLException)6 SchemaObject (org.h2.schema.SchemaObject)6 ArrayList (java.util.ArrayList)5 DropSequence (org.h2.command.ddl.DropSequence)5 DbObject (org.h2.engine.DbObject)5 Schema (org.h2.schema.Schema)5 TriggerObject (org.h2.schema.TriggerObject)5