Search in sources :

Example 36 with Trace

use of org.h2.message.Trace in project h2database by h2database.

the class TestLob method testLobTransactions.

private void testLobTransactions(int spaceLen) throws SQLException {
    deleteDb("lob");
    Connection conn = reconnect(null);
    conn.createStatement().execute("CREATE TABLE TEST(ID IDENTITY, " + "DATA CLOB, DATA2 VARCHAR)");
    conn.setAutoCommit(false);
    Random random = new Random(0);
    int rows = 0;
    Savepoint sp = null;
    int len = getSize(100, 400);
    // config.traceTest = true;
    for (int i = 0; i < len; i++) {
        switch(random.nextInt(10)) {
            case 0:
                trace("insert " + i);
                conn.createStatement().execute("INSERT INTO TEST(DATA, DATA2) VALUES('" + i + "' || SPACE(" + spaceLen + "), '" + i + "')");
                rows++;
                break;
            case 1:
                if (rows > 0) {
                    int x = random.nextInt(rows);
                    trace("delete " + x);
                    conn.createStatement().execute("DELETE FROM TEST WHERE ID=" + x);
                }
                break;
            case 2:
                if (rows > 0) {
                    int x = random.nextInt(rows);
                    trace("update " + x);
                    conn.createStatement().execute("UPDATE TEST SET DATA='x' || DATA, " + "DATA2='x' || DATA2 WHERE ID=" + x);
                }
                break;
            case 3:
                if (rows > 0) {
                    trace("commit");
                    conn.commit();
                    sp = null;
                }
                break;
            case 4:
                if (rows > 0) {
                    trace("rollback");
                    conn.rollback();
                    sp = null;
                }
                break;
            case 5:
                trace("savepoint");
                sp = conn.setSavepoint();
                break;
            case 6:
                if (sp != null) {
                    trace("rollback to savepoint");
                    conn.rollback(sp);
                }
                break;
            case 7:
                if (rows > 0) {
                    trace("checkpoint");
                    conn.createStatement().execute("CHECKPOINT");
                    trace("shutdown immediately");
                    conn.createStatement().execute("SHUTDOWN IMMEDIATELY");
                    trace("shutdown done");
                    conn = reconnect(conn);
                    conn.setAutoCommit(false);
                    sp = null;
                }
                break;
            default:
        }
        ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
        while (rs.next()) {
            int id = rs.getInt("ID");
            String d1 = rs.getString("DATA").trim();
            String d2 = rs.getString("DATA2");
            assertEquals("id:" + id, d2, d1);
        }
    }
    conn.close();
}
Also used : Random(java.util.Random) Connection(java.sql.Connection) JdbcConnection(org.h2.jdbc.JdbcConnection) ResultSet(java.sql.ResultSet) Savepoint(java.sql.Savepoint) Savepoint(java.sql.Savepoint)

Example 37 with Trace

use of org.h2.message.Trace in project spring-boot by spring-projects.

the class H2ConsoleAutoConfiguration method h2Console.

@Bean
public ServletRegistrationBean<WebServlet> h2Console() {
    String path = this.properties.getPath();
    String urlMapping = (path.endsWith("/") ? path + "*" : path + "/*");
    ServletRegistrationBean<WebServlet> registration = new ServletRegistrationBean<>(new WebServlet(), urlMapping);
    H2ConsoleProperties.Settings settings = this.properties.getSettings();
    if (settings.isTrace()) {
        registration.addInitParameter("trace", "");
    }
    if (settings.isWebAllowOthers()) {
        registration.addInitParameter("webAllowOthers", "");
    }
    return registration;
}
Also used : WebServlet(org.h2.server.web.WebServlet) ServletRegistrationBean(org.springframework.boot.web.servlet.ServletRegistrationBean) ConditionalOnBean(org.springframework.boot.autoconfigure.condition.ConditionalOnBean) ServletRegistrationBean(org.springframework.boot.web.servlet.ServletRegistrationBean) Bean(org.springframework.context.annotation.Bean)

Example 38 with Trace

use of org.h2.message.Trace in project h2database by h2database.

the class Database method open.

private synchronized void open(int traceLevelFile, int traceLevelSystemOut) {
    if (persistent) {
        String dataFileName = databaseName + Constants.SUFFIX_OLD_DATABASE_FILE;
        boolean existsData = FileUtils.exists(dataFileName);
        String pageFileName = databaseName + Constants.SUFFIX_PAGE_FILE;
        String mvFileName = databaseName + Constants.SUFFIX_MV_FILE;
        boolean existsPage = FileUtils.exists(pageFileName);
        boolean existsMv = FileUtils.exists(mvFileName);
        if (existsData && (!existsPage && !existsMv)) {
            throw DbException.get(ErrorCode.FILE_VERSION_ERROR_1, "Old database: " + dataFileName + " - please convert the database " + "to a SQL script and re-create it.");
        }
        if (existsPage && !FileUtils.canWrite(pageFileName)) {
            readOnly = true;
        }
        if (existsMv && !FileUtils.canWrite(mvFileName)) {
            readOnly = true;
        }
        if (existsPage && !existsMv) {
            dbSettings.mvStore = false;
        }
        if (readOnly) {
            if (traceLevelFile >= TraceSystem.DEBUG) {
                String traceFile = Utils.getProperty("java.io.tmpdir", ".") + "/" + "h2_" + System.currentTimeMillis();
                traceSystem = new TraceSystem(traceFile + Constants.SUFFIX_TRACE_FILE);
            } else {
                traceSystem = new TraceSystem(null);
            }
        } else {
            traceSystem = new TraceSystem(databaseName + Constants.SUFFIX_TRACE_FILE);
        }
        traceSystem.setLevelFile(traceLevelFile);
        traceSystem.setLevelSystemOut(traceLevelSystemOut);
        trace = traceSystem.getTrace(Trace.DATABASE);
        trace.info("opening {0} (build {1})", databaseName, Constants.BUILD_ID);
        if (autoServerMode) {
            if (readOnly || fileLockMethod == FileLockMethod.NO || fileLockMethod == FileLockMethod.SERIALIZED || fileLockMethod == FileLockMethod.FS || !persistent) {
                throw DbException.getUnsupportedException("autoServerMode && (readOnly || " + "fileLockMethod == NO || " + "fileLockMethod == SERIALIZED || " + "fileLockMethod == FS || " + "inMemory)");
            }
        }
        String lockFileName = databaseName + Constants.SUFFIX_LOCK_FILE;
        if (readOnly) {
            if (FileUtils.exists(lockFileName)) {
                throw DbException.get(ErrorCode.DATABASE_ALREADY_OPEN_1, "Lock file exists: " + lockFileName);
            }
        }
        if (!readOnly && fileLockMethod != FileLockMethod.NO) {
            if (fileLockMethod != FileLockMethod.FS) {
                lock = new FileLock(traceSystem, lockFileName, Constants.LOCK_SLEEP);
                lock.lock(fileLockMethod);
                if (autoServerMode) {
                    startServer(lock.getUniqueId());
                }
            }
        }
        if (SysProperties.MODIFY_ON_WRITE) {
            while (isReconnectNeeded()) {
            // wait until others stopped writing
            }
        } else {
            while (isReconnectNeeded() && !beforeWriting()) {
            // wait until others stopped writing and
            // until we can write (the file is not yet open -
            // no need to re-connect)
            }
        }
        deleteOldTempFiles();
        starting = true;
        if (SysProperties.MODIFY_ON_WRITE) {
            try {
                getPageStore();
            } catch (DbException e) {
                if (e.getErrorCode() != ErrorCode.DATABASE_IS_READ_ONLY) {
                    throw e;
                }
                pageStore = null;
                while (!beforeWriting()) {
                // wait until others stopped writing and
                // until we can write (the file is not yet open -
                // no need to re-connect)
                }
                getPageStore();
            }
        } else {
            getPageStore();
        }
        starting = false;
        if (mvStore == null) {
            writer = WriterThread.create(this, writeDelay);
        } else {
            setWriteDelay(writeDelay);
        }
    } else {
        if (autoServerMode) {
            throw DbException.getUnsupportedException("autoServerMode && inMemory");
        }
        traceSystem = new TraceSystem(null);
        trace = traceSystem.getTrace(Trace.DATABASE);
        if (dbSettings.mvStore) {
            getPageStore();
        }
    }
    systemUser = new User(this, 0, SYSTEM_USER_NAME, true);
    mainSchema = new Schema(this, 0, Constants.SCHEMA_MAIN, systemUser, true);
    infoSchema = new Schema(this, -1, "INFORMATION_SCHEMA", systemUser, true);
    schemas.put(mainSchema.getName(), mainSchema);
    schemas.put(infoSchema.getName(), infoSchema);
    publicRole = new Role(this, 0, Constants.PUBLIC_ROLE_NAME, true);
    roles.put(Constants.PUBLIC_ROLE_NAME, publicRole);
    systemUser.setAdmin(true);
    systemSession = new Session(this, systemUser, ++nextSessionId);
    lobSession = new Session(this, systemUser, ++nextSessionId);
    CreateTableData data = new CreateTableData();
    ArrayList<Column> cols = data.columns;
    Column columnId = new Column("ID", Value.INT);
    columnId.setNullable(false);
    cols.add(columnId);
    cols.add(new Column("HEAD", Value.INT));
    cols.add(new Column("TYPE", Value.INT));
    cols.add(new Column("SQL", Value.STRING));
    boolean create = true;
    if (pageStore != null) {
        create = pageStore.isNew();
    }
    data.tableName = "SYS";
    data.id = 0;
    data.temporary = false;
    data.persistData = persistent;
    data.persistIndexes = persistent;
    data.create = create;
    data.isHidden = true;
    data.session = systemSession;
    meta = mainSchema.createTable(data);
    IndexColumn[] pkCols = IndexColumn.wrap(new Column[] { columnId });
    metaIdIndex = meta.addIndex(systemSession, "SYS_ID", 0, pkCols, IndexType.createPrimaryKey(false, false), true, null);
    objectIds.set(0);
    starting = true;
    Cursor cursor = metaIdIndex.find(systemSession, null, null);
    ArrayList<MetaRecord> records = New.arrayList();
    while (cursor.next()) {
        MetaRecord rec = new MetaRecord(cursor.get());
        objectIds.set(rec.getId());
        records.add(rec);
    }
    Collections.sort(records);
    synchronized (systemSession) {
        for (MetaRecord rec : records) {
            rec.execute(this, systemSession, eventListener);
        }
    }
    if (mvStore != null) {
        mvStore.initTransactions();
        mvStore.removeTemporaryMaps(objectIds);
    }
    recompileInvalidViews(systemSession);
    starting = false;
    if (!readOnly) {
        // set CREATE_BUILD in a new database
        String name = SetTypes.getTypeName(SetTypes.CREATE_BUILD);
        if (settings.get(name) == null) {
            Setting setting = new Setting(this, allocateObjectId(), name);
            setting.setIntValue(Constants.BUILD_ID);
            lockMeta(systemSession);
            addDatabaseObject(systemSession, setting);
        }
        // mark all ids used in the page store
        if (pageStore != null) {
            BitSet f = pageStore.getObjectIds();
            for (int i = 0, len = f.length(); i < len; i++) {
                if (f.get(i) && !objectIds.get(i)) {
                    trace.info("unused object id: " + i);
                    objectIds.set(i);
                }
            }
        }
    }
    getLobStorage().init();
    systemSession.commit(true);
    trace.info("opened {0}", databaseName);
    if (checkpointAllowed > 0) {
        afterWriting();
    }
}
Also used : Schema(org.h2.schema.Schema) BitSet(java.util.BitSet) TraceSystem(org.h2.message.TraceSystem) CreateTableData(org.h2.command.ddl.CreateTableData) Cursor(org.h2.index.Cursor) Constraint(org.h2.constraint.Constraint) DbException(org.h2.message.DbException) IndexColumn(org.h2.table.IndexColumn) IndexColumn(org.h2.table.IndexColumn) Column(org.h2.table.Column) FileLock(org.h2.store.FileLock)

Example 39 with Trace

use of org.h2.message.Trace 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)

Example 40 with Trace

use of org.h2.message.Trace in project h2database by h2database.

the class Session method getTrace.

@Override
public Trace getTrace() {
    if (trace != null && !closed) {
        return trace;
    }
    String traceModuleName = "jdbc[" + id + "]";
    if (closed) {
        return new TraceSystem(null).getTrace(traceModuleName);
    }
    trace = database.getTraceSystem().getTrace(traceModuleName);
    return trace;
}
Also used : ValueString(org.h2.value.ValueString) TraceSystem(org.h2.message.TraceSystem)

Aggregations

SQLException (java.sql.SQLException)16 DbException (org.h2.message.DbException)14 Connection (java.sql.Connection)11 ResultSet (java.sql.ResultSet)10 PreparedStatement (java.sql.PreparedStatement)9 Statement (java.sql.Statement)8 IOException (java.io.IOException)7 Savepoint (java.sql.Savepoint)7 Random (java.util.Random)7 ArrayList (java.util.ArrayList)5 Properties (java.util.Properties)5 TraceSystem (org.h2.message.TraceSystem)5 Server (org.h2.tools.Server)5 ValueString (org.h2.value.ValueString)5 SQLClientInfoException (java.sql.SQLClientInfoException)4 SysProperties (org.h2.engine.SysProperties)4 JdbcConnection (org.h2.jdbc.JdbcConnection)4 SortedProperties (org.h2.util.SortedProperties)4 Value (org.h2.value.Value)4 Socket (java.net.Socket)3