Search in sources :

Example 11 with PageStore

use of org.h2.store.PageStore 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 12 with PageStore

use of org.h2.store.PageStore in project h2database by h2database.

the class PageDataLeaf method moveTo.

@Override
public void moveTo(Session session, int newPos) {
    PageStore store = index.getPageStore();
    // are written
    if (parentPageId != ROOT) {
        store.getPage(parentPageId);
    }
    store.logUndo(this, data);
    PageDataLeaf p2 = PageDataLeaf.create(index, newPos, parentPageId);
    readAllRows();
    p2.keys = keys;
    p2.overflowRowSize = overflowRowSize;
    p2.firstOverflowPageId = firstOverflowPageId;
    p2.rowRef = rowRef;
    p2.rows = rows;
    if (firstOverflowPageId != 0) {
        p2.rows[0] = getRowAt(0);
    }
    p2.entryCount = entryCount;
    p2.offsets = offsets;
    p2.start = start;
    p2.remapChildren(getPos());
    p2.writeData();
    p2.data.truncate(index.getPageStore().getPageSize());
    store.update(p2);
    if (parentPageId == ROOT) {
        index.setRootPageId(session, newPos);
    } else {
        PageDataNode p = (PageDataNode) store.getPage(parentPageId);
        p.moveChild(getPos(), newPos);
    }
    store.free(getPos());
}
Also used : PageStore(org.h2.store.PageStore)

Example 13 with PageStore

use of org.h2.store.PageStore in project h2database by h2database.

the class PageDataLeaf method getRowAt.

/**
 * Get the row at the given index.
 *
 * @param at the index
 * @return the row
 */
Row getRowAt(int at) {
    Row r = rows[at];
    if (r == null) {
        if (firstOverflowPageId == 0) {
            r = readRow(data, offsets[at], columnCount);
        } else {
            if (rowRef != null) {
                r = rowRef.get();
                if (r != null) {
                    return r;
                }
            }
            PageStore store = index.getPageStore();
            Data buff = store.createData();
            int pageSize = store.getPageSize();
            int offset = offsets[at];
            buff.write(data.getBytes(), offset, pageSize - offset);
            int next = firstOverflowPageId;
            do {
                PageDataOverflow page = index.getPageOverflow(next);
                next = page.readInto(buff);
            } while (next != 0);
            overflowRowSize = pageSize + buff.length();
            r = readRow(buff, 0, columnCount);
        }
        r.setKey(keys[at]);
        if (firstOverflowPageId != 0) {
            rowRef = new SoftReference<>(r);
        } else {
            rows[at] = r;
            memoryChange(true, r);
        }
    }
    return r;
}
Also used : PageStore(org.h2.store.PageStore) Data(org.h2.store.Data) Row(org.h2.result.Row)

Example 14 with PageStore

use of org.h2.store.PageStore in project h2database by h2database.

the class PageDataNode method moveTo.

@Override
public void moveTo(Session session, int newPos) {
    PageStore store = index.getPageStore();
    // are written
    for (int i = 0; i < entryCount + 1; i++) {
        int child = childPageIds[i];
        store.getPage(child);
    }
    if (parentPageId != ROOT) {
        store.getPage(parentPageId);
    }
    store.logUndo(this, data);
    PageDataNode p2 = PageDataNode.create(index, newPos, parentPageId);
    p2.rowCountStored = rowCountStored;
    p2.rowCount = rowCount;
    p2.childPageIds = childPageIds;
    p2.keys = keys;
    p2.entryCount = entryCount;
    p2.length = length;
    store.update(p2);
    if (parentPageId == ROOT) {
        index.setRootPageId(session, newPos);
    } else {
        PageDataNode p = (PageDataNode) store.getPage(parentPageId);
        p.moveChild(getPos(), newPos);
    }
    for (int i = 0; i < entryCount + 1; i++) {
        int child = childPageIds[i];
        PageData p = (PageData) store.getPage(child);
        p.setParentPageId(newPos);
        store.update(p);
    }
    store.free(getPos());
}
Also used : PageStore(org.h2.store.PageStore)

Aggregations

PageStore (org.h2.store.PageStore)8 Constraint (org.h2.constraint.Constraint)3 Row (org.h2.result.Row)3 ValueString (org.h2.value.ValueString)3 IOException (java.io.IOException)2 Database (org.h2.engine.Database)2 DbException (org.h2.message.DbException)2 Store (org.h2.mvstore.db.MVTableEngine.Store)2 StatementBuilder (org.h2.util.StatementBuilder)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 Timestamp (java.sql.Timestamp)1 ArrayList (java.util.ArrayList)1 BitSet (java.util.BitSet)1 HashMap (java.util.HashMap)1 Locale (java.util.Locale)1 Properties (java.util.Properties)1