Search in sources :

Example 26 with Sequence

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

the class TestSequence method testConcurrentCreate.

private void testConcurrentCreate() throws Exception {
    deleteDb("sequence");
    final String url = getURL("sequence;MULTI_THREADED=1;LOCK_TIMEOUT=2000", true);
    Connection conn = getConnection(url);
    Task[] tasks = new Task[2];
    try {
        Statement stat = conn.createStatement();
        stat.execute("create table dummy(id bigint primary key)");
        stat.execute("create table test(id bigint primary key)");
        stat.execute("create sequence test_seq cache 2");
        for (int i = 0; i < tasks.length; i++) {
            final int x = i;
            tasks[i] = new Task() {

                @Override
                public void call() throws Exception {
                    try (Connection conn = getConnection(url)) {
                        PreparedStatement prep = conn.prepareStatement("insert into test(id) values(next value for test_seq)");
                        PreparedStatement prep2 = conn.prepareStatement("delete from test");
                        while (!stop) {
                            prep.execute();
                            if (Math.random() < 0.01) {
                                prep2.execute();
                            }
                            if (Math.random() < 0.01) {
                                createDropTrigger(conn);
                            }
                        }
                    }
                }

                private void createDropTrigger(Connection conn) throws Exception {
                    String triggerName = "t_" + x;
                    Statement stat = conn.createStatement();
                    stat.execute("create trigger " + triggerName + " before insert on dummy call \"" + TriggerTest.class.getName() + "\"");
                    stat.execute("drop trigger " + triggerName);
                }
            }.execute();
        }
        Thread.sleep(1000);
        for (Task t : tasks) {
            t.get();
        }
    } finally {
        for (Task t : tasks) {
            t.join();
        }
        conn.close();
    }
}
Also used : Task(org.h2.util.Task) Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 27 with Sequence

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

the class Insert method prepare.

@Override
public void prepare() {
    if (columns == null) {
        if (!list.isEmpty() && list.get(0).length == 0) {
            // special case where table is used as a sequence
            columns = new Column[0];
        } else {
            columns = table.getColumns();
        }
    }
    if (!list.isEmpty()) {
        for (Expression[] expr : list) {
            if (expr.length != columns.length) {
                throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
            }
            for (int i = 0, len = expr.length; i < len; i++) {
                Expression e = expr[i];
                if (e != null) {
                    if (sourceTableFilter != null) {
                        e.mapColumns(sourceTableFilter, 0);
                    }
                    e = e.optimize(session);
                    if (e instanceof Parameter) {
                        Parameter p = (Parameter) e;
                        p.setColumn(columns[i]);
                    }
                    expr[i] = e;
                }
            }
        }
    } else {
        query.prepare();
        if (query.getColumnCount() != columns.length) {
            throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
        }
    }
}
Also used : Expression(org.h2.expression.Expression) Parameter(org.h2.expression.Parameter)

Example 28 with Sequence

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

the class Replace method prepare.

@Override
public void prepare() {
    if (columns == null) {
        if (!list.isEmpty() && list.get(0).length == 0) {
            // special case where table is used as a sequence
            columns = new Column[0];
        } else {
            columns = table.getColumns();
        }
    }
    if (!list.isEmpty()) {
        for (Expression[] expr : list) {
            if (expr.length != columns.length) {
                throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
            }
            for (int i = 0; i < expr.length; i++) {
                Expression e = expr[i];
                if (e != null) {
                    expr[i] = e.optimize(session);
                }
            }
        }
    } else {
        query.prepare();
        if (query.getColumnCount() != columns.length) {
            throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
        }
    }
    if (keys == null) {
        Index idx = table.getPrimaryKey();
        if (idx == null) {
            throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, "PRIMARY KEY");
        }
        keys = idx.getColumns();
    }
    // INSERT
    for (Column key : keys) {
        boolean found = false;
        for (Column column : columns) {
            if (column.getColumnId() == key.getColumnId()) {
                found = true;
                break;
            }
        }
        if (!found) {
            return;
        }
    }
    StatementBuilder buff = new StatementBuilder("UPDATE ");
    buff.append(table.getSQL()).append(" SET ");
    for (Column c : columns) {
        buff.appendExceptFirst(", ");
        buff.append(c.getSQL()).append("=?");
    }
    buff.append(" WHERE ");
    buff.resetCount();
    for (Column c : keys) {
        buff.appendExceptFirst(" AND ");
        buff.append(c.getSQL()).append("=?");
    }
    String sql = buff.toString();
    update = session.prepare(sql);
}
Also used : Expression(org.h2.expression.Expression) Column(org.h2.table.Column) StatementBuilder(org.h2.util.StatementBuilder) Index(org.h2.index.Index)

Example 29 with Sequence

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

the class Database method flushSequences.

private void flushSequences() {
    for (SchemaObject obj : getAllSchemaObjects(DbObject.SEQUENCE)) {
        Sequence sequence = (Sequence) obj;
        sequence.flushWithoutMargin();
    }
}
Also used : SchemaObject(org.h2.schema.SchemaObject) Sequence(org.h2.schema.Sequence)

Example 30 with Sequence

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

the class Database method close.

/**
 * Close the database.
 *
 * @param fromShutdownHook true if this method is called from the shutdown
 *            hook
 */
void close(boolean fromShutdownHook) {
    try {
        synchronized (this) {
            if (closing) {
                return;
            }
            throwLastBackgroundException();
            if (fileLockMethod == FileLockMethod.SERIALIZED && !reconnectChangePending) {
                // another connection may have written something - don't write
                try {
                    closeOpenFilesAndUnlock(false);
                } catch (DbException e) {
                // ignore
                }
                traceSystem.close();
                return;
            }
            closing = true;
            stopServer();
            if (!userSessions.isEmpty()) {
                if (!fromShutdownHook) {
                    return;
                }
                trace.info("closing {0} from shutdown hook", databaseName);
                closeAllSessionsException(null);
            }
            trace.info("closing {0}", databaseName);
            if (eventListener != null) {
                // allow the event listener to connect to the database
                closing = false;
                DatabaseEventListener e = eventListener;
                // set it to null, to make sure it's called only once
                eventListener = null;
                e.closingDatabase();
                if (!userSessions.isEmpty()) {
                    // if a connection was opened, we can't close the database
                    return;
                }
                closing = true;
            }
        }
        if (!this.isReadOnly()) {
            removeOrphanedLobs();
        }
        try {
            if (systemSession != null) {
                if (powerOffCount != -1) {
                    for (Table table : getAllTablesAndViews(false)) {
                        if (table.isGlobalTemporary()) {
                            table.removeChildrenAndResources(systemSession);
                        } else {
                            table.close(systemSession);
                        }
                    }
                    for (SchemaObject obj : getAllSchemaObjects(DbObject.SEQUENCE)) {
                        Sequence sequence = (Sequence) obj;
                        sequence.close();
                    }
                }
                for (SchemaObject obj : getAllSchemaObjects(DbObject.TRIGGER)) {
                    TriggerObject trigger = (TriggerObject) obj;
                    try {
                        trigger.close();
                    } catch (SQLException e) {
                        trace.error(e, "close");
                    }
                }
                if (powerOffCount != -1) {
                    meta.close(systemSession);
                    systemSession.commit(true);
                }
            }
        } catch (DbException e) {
            trace.error(e, "close");
        }
        tempFileDeleter.deleteAll();
        try {
            closeOpenFilesAndUnlock(true);
        } catch (DbException e) {
            trace.error(e, "close");
        }
        trace.info("closed");
        traceSystem.close();
        if (closeOnExit != null) {
            closeOnExit.reset();
            try {
                Runtime.getRuntime().removeShutdownHook(closeOnExit);
            } catch (IllegalStateException e) {
            // ignore
            } catch (SecurityException e) {
            // applets may not do that - ignore
            }
            closeOnExit = null;
        }
        if (deleteFilesOnDisconnect && persistent) {
            deleteFilesOnDisconnect = false;
            try {
                String directory = FileUtils.getParent(databaseName);
                String name = FileUtils.getName(databaseName);
                DeleteDbFiles.execute(directory, name, true);
            } catch (Exception e) {
            // ignore (the trace is closed already)
            }
        }
    } finally {
        Engine.getInstance().close(databaseName);
    }
}
Also used : SchemaObject(org.h2.schema.SchemaObject) DatabaseEventListener(org.h2.api.DatabaseEventListener) MetaTable(org.h2.table.MetaTable) Table(org.h2.table.Table) SQLException(java.sql.SQLException) TriggerObject(org.h2.schema.TriggerObject) Sequence(org.h2.schema.Sequence) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) IOException(java.io.IOException) DbException(org.h2.message.DbException)

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