Search in sources :

Example 1 with TableConsistencyCheckStatement

use of herddb.model.commands.TableConsistencyCheckStatement in project herddb by diennea.

the class TableManager method executeStatementAsync.

@Override
public CompletableFuture<StatementExecutionResult> executeStatementAsync(Statement statement, Transaction transaction, StatementEvaluationContext context) {
    CompletableFuture<StatementExecutionResult> res;
    long lockStamp = checkpointLock.readLock();
    if (statement instanceof UpdateStatement) {
        UpdateStatement update = (UpdateStatement) statement;
        res = executeUpdateAsync(update, transaction, context);
    } else if (statement instanceof InsertStatement) {
        InsertStatement insert = (InsertStatement) statement;
        res = executeInsertAsync(insert, transaction, context);
    } else if (statement instanceof GetStatement) {
        GetStatement get = (GetStatement) statement;
        res = executeGetAsync(get, transaction, context);
    } else if (statement instanceof DeleteStatement) {
        DeleteStatement delete = (DeleteStatement) statement;
        res = executeDeleteAsync(delete, transaction, context);
    } else if (statement instanceof TruncateTableStatement) {
        try {
            TruncateTableStatement truncate = (TruncateTableStatement) statement;
            res = CompletableFuture.completedFuture(executeTruncate(truncate, transaction, context));
        } catch (StatementExecutionException err) {
            LOGGER.log(Level.SEVERE, "Truncate table failed", err);
            res = Futures.exception(err);
        }
    } else if (statement instanceof TableConsistencyCheckStatement) {
        DBManager manager = this.tableSpaceManager.getDbmanager();
        res = CompletableFuture.completedFuture(manager.createTableCheckSum((TableConsistencyCheckStatement) statement, context));
    } else {
        res = Futures.exception(new StatementExecutionException("not implemented " + statement.getClass()));
    }
    res = res.whenComplete((r, error) -> {
        checkpointLock.unlockRead(lockStamp);
    });
    if (statement instanceof TruncateTableStatement) {
        res = res.whenComplete((r, error) -> {
            if (error == null) {
                try {
                    flush();
                } catch (DataStorageManagerException err) {
                    throw new HerdDBInternalException(new StatementExecutionException("internal data error: " + err, err));
                }
            }
        });
    }
    return res;
}
Also used : TruncateTableStatement(herddb.model.commands.TruncateTableStatement) Arrays(java.util.Arrays) NullLockManager(herddb.utils.NullLockManager) Table(herddb.model.Table) TruncateTableStatement(herddb.model.commands.TruncateTableStatement) DuplicatePrimaryKeyException(herddb.model.DuplicatePrimaryKeyException) TableStatus(herddb.storage.TableStatus) Map(java.util.Map) DataAccessor(herddb.utils.DataAccessor) LogNotAvailableException(herddb.log.LogNotAvailableException) CommitLogResult(herddb.log.CommitLogResult) LogSequenceNumber(herddb.log.LogSequenceNumber) UniqueIndexContraintViolationException(herddb.model.UniqueIndexContraintViolationException) Set(java.util.Set) RecordSerializer(herddb.codec.RecordSerializer) JSQLParserPlanner.delimit(herddb.sql.JSQLParserPlanner.delimit) DataPageMetaData(herddb.core.PageSet.DataPageMetaData) ScanStatement(herddb.model.commands.ScanStatement) Stream(java.util.stream.Stream) StatsLogger(org.apache.bookkeeper.stats.StatsLogger) Bytes(herddb.utils.Bytes) Holder(herddb.utils.Holder) LockHandle(herddb.utils.LockHandle) ForeignKeyViolationException(herddb.model.ForeignKeyViolationException) LogEntry(herddb.log.LogEntry) ArrayList(java.util.ArrayList) TransactionContext(herddb.model.TransactionContext) Transaction(herddb.model.Transaction) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Projection(herddb.model.Projection) ForeignKeyDef(herddb.model.ForeignKeyDef) EnsureLongIncrementAccumulator(herddb.utils.EnsureLongIncrementAccumulator) LogEntryType(herddb.log.LogEntryType) Record(herddb.model.Record) LogEntryFactory(herddb.log.LogEntryFactory) KeyToPageIndex(herddb.index.KeyToPageIndex) DataStorageManager(herddb.storage.DataStorageManager) ColumnTypes(herddb.model.ColumnTypes) ILocalLockManager(herddb.utils.ILocalLockManager) AtomicLong(java.util.concurrent.atomic.AtomicLong) Lock(java.util.concurrent.locks.Lock) IndexOperation(herddb.index.IndexOperation) Column(herddb.model.Column) StampedLock(java.util.concurrent.locks.StampedLock) UpdateStatement(herddb.model.commands.UpdateStatement) ScanLimitsImpl(herddb.model.ScanLimitsImpl) TupleComparator(herddb.model.TupleComparator) ServerConfiguration(herddb.server.ServerConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RecordTooBigException(herddb.model.RecordTooBigException) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) LocalLockManager(herddb.utils.LocalLockManager) Futures(herddb.utils.Futures) DataStorageManagerException(herddb.storage.DataStorageManagerException) Index(herddb.model.Index) InsertStatement(herddb.model.commands.InsertStatement) DataScanner(herddb.model.DataScanner) DDLException(herddb.model.DDLException) RecordFunction(herddb.model.RecordFunction) StatementExecutionException(herddb.model.StatementExecutionException) TableContext(herddb.model.TableContext) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) List(java.util.List) FullTableScanConsumer(herddb.storage.FullTableScanConsumer) GetStatement(herddb.model.commands.GetStatement) Entry(java.util.Map.Entry) Statement(herddb.model.Statement) LongAdder(java.util.concurrent.atomic.LongAdder) DataScannerException(herddb.model.DataScannerException) GetResult(herddb.model.GetResult) PrimaryIndexSeek(herddb.index.PrimaryIndexSeek) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) BatchOrderedExecutor(herddb.utils.BatchOrderedExecutor) ConcurrentMap(java.util.concurrent.ConcurrentMap) Level(java.util.logging.Level) HashSet(java.util.HashSet) BooleanHolder(herddb.utils.BooleanHolder) ScanLimits(herddb.model.ScanLimits) DeleteStatement(herddb.model.commands.DeleteStatement) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Semaphore(java.util.concurrent.Semaphore) DataPageDoesNotExistException(herddb.storage.DataPageDoesNotExistException) Counter(org.apache.bookkeeper.stats.Counter) StatementExecutionResult(herddb.model.StatementExecutionResult) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CommitLog(herddb.log.CommitLog) AbstractMap(java.util.AbstractMap) TableConsistencyCheckStatement(herddb.model.commands.TableConsistencyCheckStatement) Predicate(herddb.model.Predicate) StatementEvaluationContext(herddb.model.StatementEvaluationContext) Comparator(java.util.Comparator) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) TableManagerStats(herddb.core.stats.TableManagerStats) SystemProperties(herddb.utils.SystemProperties) UpdateStatement(herddb.model.commands.UpdateStatement) DataStorageManagerException(herddb.storage.DataStorageManagerException) DeleteStatement(herddb.model.commands.DeleteStatement) InsertStatement(herddb.model.commands.InsertStatement) StatementExecutionException(herddb.model.StatementExecutionException) GetStatement(herddb.model.commands.GetStatement) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) StatementExecutionResult(herddb.model.StatementExecutionResult) TableConsistencyCheckStatement(herddb.model.commands.TableConsistencyCheckStatement)

Example 2 with TableConsistencyCheckStatement

use of herddb.model.commands.TableConsistencyCheckStatement in project herddb by diennea.

the class JSQLParserPlanner method queryConsistencyCheckStatement.

public Statement queryConsistencyCheckStatement(String defaultTablespace, String query, List<Object> parameters) {
    if (query.startsWith(TABLE_CONSISTENCY_COMMAND)) {
        query = query.substring(query.substring(0, 21).length());
        String tableSpace = defaultTablespace;
        String tableName;
        if (query.contains(".")) {
            String[] tokens = query.split("\\.");
            tableSpace = tokens[0].trim().replaceAll("\'", "");
            tableName = tokens[1].trim().replaceAll("\'", "");
        } else {
            tableName = query.trim();
        }
        TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(tableSpace);
        if (tableSpaceManager == null) {
            throw new TableSpaceDoesNotExistException(String.format("Tablespace %s does not exist.", tableSpace));
        }
        AbstractTableManager tableManager = tableSpaceManager.getTableManager(tableName);
        if (tableManager == null || tableManager.getCreatedInTransaction() > 0) {
            throw new TableDoesNotExistException(String.format("Table %s does not exist.", tableName));
        }
        return new TableConsistencyCheckStatement(tableName, tableSpace);
    } else {
        throw new StatementExecutionException(String.format("Incorrect Syntax for tableconsistencycheck"));
    }
}
Also used : TableDoesNotExistException(herddb.model.TableDoesNotExistException) TableSpaceDoesNotExistException(herddb.model.TableSpaceDoesNotExistException) AbstractTableManager(herddb.core.AbstractTableManager) TableSpaceManager(herddb.core.TableSpaceManager) StatementExecutionException(herddb.model.StatementExecutionException) TableConsistencyCheckStatement(herddb.model.commands.TableConsistencyCheckStatement)

Example 3 with TableConsistencyCheckStatement

use of herddb.model.commands.TableConsistencyCheckStatement in project herddb by diennea.

the class DataConsistencyCheckTest method emptyTableConsistencyCheck.

@Test
public void emptyTableConsistencyCheck() throws Exception {
    String tableSpaceName = "tblspace1";
    String tableName = "t1";
    try (DBManager manager = new DBManager("localhost", new MemoryMetadataStorageManager(), new MemoryDataStorageManager(), new MemoryCommitLogManager(), null, null)) {
        manager.start();
        assertTrue(manager.waitForBootOfLocalTablespaces(10000));
        execute(manager, "CREATE TABLESPACE 'tblspace1'", Collections.emptyList());
        manager.waitForTablespace("tblspace1", 10000);
        Table table = Table.builder().tablespace(tableSpaceName).name(tableName).column("k1", ColumnTypes.STRING).column("n1", ColumnTypes.INTEGER).column("s1", ColumnTypes.STRING).primaryKey("k1").build();
        CreateTableStatement st = new CreateTableStatement(table);
        manager.executeStatement(st, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        // check empty table
        TableConsistencyCheckStatement statement = new TableConsistencyCheckStatement(tableName, tableSpaceName);
        DataConsistencyStatementResult result = manager.createTableCheckSum(statement, null);
        assertTrue("Check empty table ", result.getOk());
    }
}
Also used : DBManager(herddb.core.DBManager) Table(herddb.model.Table) MemoryDataStorageManager(herddb.mem.MemoryDataStorageManager) MemoryCommitLogManager(herddb.mem.MemoryCommitLogManager) CreateTableStatement(herddb.model.commands.CreateTableStatement) DataConsistencyStatementResult(herddb.model.DataConsistencyStatementResult) MemoryMetadataStorageManager(herddb.mem.MemoryMetadataStorageManager) TableConsistencyCheckStatement(herddb.model.commands.TableConsistencyCheckStatement) Test(org.junit.Test)

Example 4 with TableConsistencyCheckStatement

use of herddb.model.commands.TableConsistencyCheckStatement in project herddb by diennea.

the class DataConsistencyCheckTest method tableWithNullValueConsistencyCheck.

@Test
public void tableWithNullValueConsistencyCheck() throws Exception {
    String tableSpaceName = "t1";
    String tableName = "nulltable";
    try (DBManager manager = new DBManager("localhost", new MemoryMetadataStorageManager(), new MemoryDataStorageManager(), new MemoryCommitLogManager(), null, null)) {
        manager.start();
        assertTrue(manager.waitForBootOfLocalTablespaces(10000));
        execute(manager, "CREATE TABLESPACE 't1'", Collections.emptyList());
        manager.waitForTablespace(tableSpaceName, 10000);
        Table table = Table.builder().tablespace(tableSpaceName).name(tableName).column("k1", ColumnTypes.INTEGER).column("n1", ColumnTypes.INTEGER).column("s1", ColumnTypes.STRING).primaryKey("k1", true).build();
        CreateTableStatement st = new CreateTableStatement(table);
        manager.executeStatement(st, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        execute(manager, "INSERT INTO " + tableSpaceName + "." + tableName + " (n1 ,s1) values (?,?)", Arrays.asList(null, null));
        execute(manager, "INSERT INTO " + tableSpaceName + "." + tableName + " (n1 ,s1) values (?,?)", Arrays.asList(null, null));
        execute(manager, "INSERT INTO " + tableSpaceName + "." + tableName + " (n1 ,s1) values (?,?)", Arrays.asList(null, null));
        execute(manager, "INSERT INTO " + tableSpaceName + "." + tableName + " (n1 ,s1) values (?,?)", Arrays.asList(null, null));
        TableConsistencyCheckStatement statement = new TableConsistencyCheckStatement(tableName, tableSpaceName);
        DataConsistencyStatementResult result = manager.createTableCheckSum(statement, null);
        assertTrue("Check table with null value ", result.getOk());
    }
}
Also used : DBManager(herddb.core.DBManager) Table(herddb.model.Table) MemoryDataStorageManager(herddb.mem.MemoryDataStorageManager) MemoryCommitLogManager(herddb.mem.MemoryCommitLogManager) CreateTableStatement(herddb.model.commands.CreateTableStatement) DataConsistencyStatementResult(herddb.model.DataConsistencyStatementResult) MemoryMetadataStorageManager(herddb.mem.MemoryMetadataStorageManager) TableConsistencyCheckStatement(herddb.model.commands.TableConsistencyCheckStatement) Test(org.junit.Test)

Example 5 with TableConsistencyCheckStatement

use of herddb.model.commands.TableConsistencyCheckStatement in project herddb by diennea.

the class ConsistencyCheckDuringRecoveryTest method consistencyCheckReplicaTest.

@Test
public void consistencyCheckReplicaTest() throws Exception {
    final AtomicInteger callCount = new AtomicInteger();
    SystemInstrumentation.addListener(new SystemInstrumentation.SingleInstrumentationPointListener("createChecksum") {

        @Override
        public void acceptSingle(Object... args) throws Exception {
            callCount.incrementAndGet();
        }
    });
    try (DBManager manager1 = startDBManager("node1")) {
        manager1.executeStatement(new CreateTableSpaceStatement(tableSpaceName, new HashSet<>(Arrays.asList("node1", "node2")), "node1", 1, 0, 0), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        manager1.waitForTablespace(tableSpaceName, 10000, true);
        try (DBManager manager2 = startDBManager("node2")) {
            manager2.waitForTablespace(tableSpaceName, 10000, false);
            Table table = Table.builder().tablespace(tableSpaceName).name(tableName).column("id", ColumnTypes.STRING).column("name", ColumnTypes.BOOLEAN).primaryKey("id").build();
            CreateTableStatement st = new CreateTableStatement(table);
            manager1.executeStatement(st, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager1.waitForTable(tableSpaceName, tableName, 10000, true);
            execute(manager1, "INSERT INTO t2.table1 (id,name) values (?,?)", Arrays.asList("1", true));
            execute(manager1, "INSERT INTO t2.table1 (id,name) values (?,?)", Arrays.asList("2", false));
            manager2.waitForTable(tableSpaceName, tableName, 10000, false);
            TableConsistencyCheckStatement statement = new TableConsistencyCheckStatement("table1", "t2");
            DataConsistencyStatementResult result = manager1.createTableCheckSum(statement, null);
            assertTrue("Consistency check replicated test ", result.getOk());
            // The follower is always back 1, I make an entry to make him apply consistency log
            execute(manager1, "INSERT INTO t2.table1 (id,name) values (?,?)", Arrays.asList("3", false));
        }
    }
    try (DBManager manager1 = startDBManager("node1")) {
        // restart leader node
        manager1.waitForTablespace("t2", 10000);
    }
    try (DBManager manager1 = startDBManager("node2")) {
        // restart follower  node
        manager1.waitForTablespace("t2", 1000);
    }
    // Expected 2 call for createChecksum (node1 and node2)
    assertEquals(2, callCount.get());
}
Also used : Table(herddb.model.Table) CreateTableStatement(herddb.model.commands.CreateTableStatement) DataConsistencyStatementResult(herddb.model.DataConsistencyStatementResult) CreateTableSpaceStatement(herddb.model.commands.CreateTableSpaceStatement) DBManager(herddb.core.DBManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SystemInstrumentation(herddb.utils.SystemInstrumentation) HashSet(java.util.HashSet) TableConsistencyCheckStatement(herddb.model.commands.TableConsistencyCheckStatement) Test(org.junit.Test)

Aggregations

TableConsistencyCheckStatement (herddb.model.commands.TableConsistencyCheckStatement)7 Table (herddb.model.Table)6 DBManager (herddb.core.DBManager)5 DataConsistencyStatementResult (herddb.model.DataConsistencyStatementResult)5 CreateTableStatement (herddb.model.commands.CreateTableStatement)5 Test (org.junit.Test)5 MemoryCommitLogManager (herddb.mem.MemoryCommitLogManager)3 MemoryDataStorageManager (herddb.mem.MemoryDataStorageManager)3 MemoryMetadataStorageManager (herddb.mem.MemoryMetadataStorageManager)3 StatementExecutionException (herddb.model.StatementExecutionException)2 CreateTableSpaceStatement (herddb.model.commands.CreateTableSpaceStatement)2 SystemInstrumentation (herddb.utils.SystemInstrumentation)2 HashSet (java.util.HashSet)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 RecordSerializer (herddb.codec.RecordSerializer)1 AbstractTableManager (herddb.core.AbstractTableManager)1 DataPageMetaData (herddb.core.PageSet.DataPageMetaData)1 TableSpaceManager (herddb.core.TableSpaceManager)1 TableManagerStats (herddb.core.stats.TableManagerStats)1 IndexOperation (herddb.index.IndexOperation)1