Search in sources :

Example 31 with Handle

use of jnc.platform.win32.Handle in project presto by prestodb.

the class TestOrcFileRewriter method testRewriterDropThenAddDifferentColumns.

/**
 * The following test add or drop different columns
 */
@Test
public void testRewriterDropThenAddDifferentColumns() throws Exception {
    FunctionAndTypeManager functionAndTypeManager = createTestFunctionAndTypeManager();
    DBI dbi = new DBI("jdbc:h2:mem:test" + System.nanoTime() + "_" + ThreadLocalRandom.current().nextInt());
    dbi.registerMapper(new TableColumn.Mapper(functionAndTypeManager));
    Handle dummyHandle = dbi.open();
    File dataDir = Files.createTempDir();
    StorageManager storageManager = createOrcStorageManager(dbi, dataDir);
    List<Long> columnIds = ImmutableList.of(3L, 7L);
    List<Type> columnTypes = ImmutableList.of(BIGINT, createVarcharType(20));
    File file = new File(temporary, randomUUID().toString());
    try (FileWriter writer = createFileWriter(columnIds, columnTypes, file, false)) {
        List<Page> pages = rowPagesBuilder(columnTypes).row(1L, "1").row(2L, "2").row(3L, "3").row(4L, "4").build();
        writer.appendPages(pages);
    }
    // Add a column
    File newFile1 = new File(temporary, randomUUID().toString());
    FileSystem fileSystem = new LocalOrcDataEnvironment().getFileSystem(DEFAULT_RAPTOR_CONTEXT);
    OrcFileInfo info = createFileRewriter().rewrite(fileSystem, getColumnTypes(ImmutableList.of(3L, 7L, 10L), ImmutableList.of(BIGINT, createVarcharType(20), DOUBLE)), path(file), path(newFile1), new BitSet(5));
    assertEquals(info.getRowCount(), 4);
    assertEquals(readAllBytes(file.toPath()), readAllBytes(newFile1.toPath()));
    // Drop a column
    File newFile2 = new File(temporary, randomUUID().toString());
    info = createFileRewriter().rewrite(fileSystem, getColumnTypes(ImmutableList.of(7L, 10L), ImmutableList.of(createVarcharType(20), DOUBLE)), path(newFile1), path(newFile2), new BitSet(5));
    assertEquals(info.getRowCount(), 4);
    // Optimized writer will keep the only column
    OrcReader orcReader = new OrcReader(fileOrcDataSource(newFile2), ORC, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), new RaptorOrcAggregatedMemoryContext(), OrcTestingUtil.createDefaultTestConfig(), false, NO_ENCRYPTION, DwrfKeyProvider.EMPTY, new RuntimeStats());
    orcReader.getColumnNames().equals(ImmutableList.of("7"));
    // Add a column with the different ID with different type
    File newFile3 = new File(temporary, randomUUID().toString());
    info = createFileRewriter().rewrite(fileSystem, getColumnTypes(ImmutableList.of(7L, 10L, 13L), ImmutableList.of(createVarcharType(20), DOUBLE, createVarcharType(5))), path(newFile2), path(newFile3), new BitSet(5));
    assertEquals(info.getRowCount(), 4);
    assertEquals(readAllBytes(newFile2.toPath()), readAllBytes(newFile3.toPath()));
    // Get prepared for the final file; make sure it is accessible from storage manager
    UUID uuid = randomUUID();
    File newFile4 = getFileSystemPath(new File(dataDir, "data/storage"), uuid);
    // Optimized ORC writer does not create the file itself
    newFile4.getParentFile().mkdirs();
    newFile4.createNewFile();
    // Drop a column and add a column; also delete 3 rows
    BitSet rowsToDelete = new BitSet(5);
    rowsToDelete.set(0);
    rowsToDelete.set(1);
    rowsToDelete.set(3);
    info = createFileRewriter().rewrite(fileSystem, getColumnTypes(ImmutableList.of(7L, 13L, 18L), ImmutableList.of(createVarcharType(20), createVarcharType(5), INTEGER)), path(newFile3), path(newFile4), rowsToDelete);
    assertEquals(info.getRowCount(), 1);
    ConnectorPageSource source = storageManager.getPageSource(DEFAULT_RAPTOR_CONTEXT, DEFAULT_HIVE_FILE_CONTEXT, uuid, Optional.empty(), false, OptionalInt.empty(), ImmutableList.of(13L, 7L, 18L), ImmutableList.of(createVarcharType(5), createVarcharType(20), INTEGER), TupleDomain.all(), READER_ATTRIBUTES);
    Page page = null;
    while (page == null) {
        page = source.getNextPage();
    }
    assertEquals(page.getPositionCount(), 1);
    // Column 13L
    Block column0 = page.getBlock(0);
    assertTrue(column0.isNull(0));
    // Column 7L
    Block column1 = page.getBlock(1);
    assertEquals(createVarcharType(20).getSlice(column1, 0), utf8Slice("3"));
    // Column 8L
    Block column2 = page.getBlock(2);
    assertTrue(column2.isNull(0));
    // Remove all the columns
    File newFile5 = new File(temporary, randomUUID().toString());
    info = createFileRewriter().rewrite(fileSystem, getColumnTypes(ImmutableList.of(13L, 18L), ImmutableList.of(createVarcharType(5), INTEGER)), path(newFile4), path(newFile5), new BitSet(5));
    // Optimized writer will drop the file
    assertEquals(info.getRowCount(), 0);
    assertFalse(newFile5.exists());
    dummyHandle.close();
    deleteRecursively(dataDir.toPath(), ALLOW_INSECURE);
}
Also used : RuntimeStats(com.facebook.presto.common.RuntimeStats) TestOrcStorageManager.createOrcStorageManager(com.facebook.presto.raptor.storage.TestOrcStorageManager.createOrcStorageManager) StorageOrcFileTailSource(com.facebook.presto.orc.cache.StorageOrcFileTailSource) DBI(org.skife.jdbi.v2.DBI) Page(com.facebook.presto.common.Page) RaptorOrcAggregatedMemoryContext(com.facebook.presto.raptor.RaptorOrcAggregatedMemoryContext) ConnectorPageSource(com.facebook.presto.spi.ConnectorPageSource) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) FunctionAndTypeManager.createTestFunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager.createTestFunctionAndTypeManager) FileSystem(org.apache.hadoop.fs.FileSystem) LocalOrcDataEnvironment(com.facebook.presto.raptor.filesystem.LocalOrcDataEnvironment) UUID(java.util.UUID) UUID.randomUUID(java.util.UUID.randomUUID) BitSet(java.util.BitSet) TableColumn(com.facebook.presto.raptor.metadata.TableColumn) Handle(org.skife.jdbi.v2.Handle) DecimalType(com.facebook.presto.common.type.DecimalType) VarcharType.createVarcharType(com.facebook.presto.common.type.VarcharType.createVarcharType) ArrayType(com.facebook.presto.common.type.ArrayType) Type(com.facebook.presto.common.type.Type) OrcReader(com.facebook.presto.orc.OrcReader) Block(com.facebook.presto.common.block.Block) StorageStripeMetadataSource(com.facebook.presto.orc.StorageStripeMetadataSource) File(java.io.File) Test(org.testng.annotations.Test)

Example 32 with Handle

use of jnc.platform.win32.Handle in project presto by prestodb.

the class RaptorMetadata method beginInsert.

@Override
public ConnectorInsertTableHandle beginInsert(ConnectorSession session, ConnectorTableHandle tableHandle) {
    RaptorTableHandle handle = (RaptorTableHandle) tableHandle;
    long tableId = handle.getTableId();
    ImmutableList.Builder<RaptorColumnHandle> columnHandles = ImmutableList.builder();
    ImmutableList.Builder<Type> columnTypes = ImmutableList.builder();
    for (TableColumn column : dao.listTableColumns(tableId)) {
        columnHandles.add(new RaptorColumnHandle(connectorId, column.getColumnName(), column.getColumnId(), column.getDataType()));
        columnTypes.add(column.getDataType());
    }
    long transactionId = shardManager.beginTransaction();
    setTransactionId(transactionId);
    Optional<String> externalBatchId = getExternalBatchId(session);
    List<RaptorColumnHandle> sortColumnHandles = getSortColumnHandles(tableId);
    List<RaptorColumnHandle> bucketColumnHandles = getBucketColumnHandles(tableId);
    Optional<RaptorColumnHandle> temporalColumnHandle = Optional.ofNullable(dao.getTemporalColumnId(tableId)).map(temporalColumnId -> getOnlyElement(columnHandles.build().stream().filter(columnHandle -> columnHandle.getColumnId() == temporalColumnId).collect(toList())));
    return new RaptorInsertTableHandle(connectorId, transactionId, tableId, columnHandles.build(), columnTypes.build(), externalBatchId, sortColumnHandles, nCopies(sortColumnHandles.size(), ASC_NULLS_FIRST), handle.getBucketCount(), bucketColumnHandles, temporalColumnHandle);
}
Also used : ShardDeleteDelta(com.facebook.presto.raptor.metadata.ShardDeleteDelta) SHARD_UUID_COLUMN_TYPE(com.facebook.presto.raptor.RaptorColumnHandle.SHARD_UUID_COLUMN_TYPE) NOT_FOUND(com.facebook.presto.spi.StandardErrorCode.NOT_FOUND) ComputedStatistics(com.facebook.presto.spi.statistics.ComputedStatistics) DatabaseUtil.runIgnoringConstraintViolation(com.facebook.presto.raptor.util.DatabaseUtil.runIgnoringConstraintViolation) Map(java.util.Map) ShardManager(com.facebook.presto.raptor.metadata.ShardManager) SystemTable(com.facebook.presto.spi.SystemTable) ColumnRangesSystemTable.getSourceTable(com.facebook.presto.raptor.systemtables.ColumnRangesSystemTable.getSourceTable) INVALID_TABLE_PROPERTY(com.facebook.presto.spi.StandardErrorCode.INVALID_TABLE_PROPERTY) RaptorTableProperties.getSortColumns(com.facebook.presto.raptor.RaptorTableProperties.getSortColumns) ColumnInfo(com.facebook.presto.raptor.metadata.ColumnInfo) ViewResult(com.facebook.presto.raptor.metadata.ViewResult) Set(java.util.Set) JsonCodec.jsonCodec(com.facebook.airlift.json.JsonCodec.jsonCodec) ConnectorSession(com.facebook.presto.spi.ConnectorSession) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) RaptorColumnHandle.shardUuidColumnHandle(com.facebook.presto.raptor.RaptorColumnHandle.shardUuidColumnHandle) ConnectorPartitioningHandle(com.facebook.presto.spi.connector.ConnectorPartitioningHandle) Slice(io.airlift.slice.Slice) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) ColumnRangesSystemTable(com.facebook.presto.raptor.systemtables.ColumnRangesSystemTable) ConnectorOutputTableHandle(com.facebook.presto.spi.ConnectorOutputTableHandle) DATE(com.facebook.presto.common.type.DateType.DATE) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) OptionalLong(java.util.OptionalLong) BUCKET_NUMBER_COLUMN_NAME(com.facebook.presto.raptor.RaptorColumnHandle.BUCKET_NUMBER_COLUMN_NAME) RaptorSessionProperties.getExternalBatchId(com.facebook.presto.raptor.RaptorSessionProperties.getExternalBatchId) DatabaseUtil.daoTransaction(com.facebook.presto.raptor.util.DatabaseUtil.daoTransaction) Nullable(javax.annotation.Nullable) RaptorTableProperties.isOrganized(com.facebook.presto.raptor.RaptorTableProperties.isOrganized) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) Distribution(com.facebook.presto.raptor.metadata.Distribution) BUCKETED_ON_PROPERTY(com.facebook.presto.raptor.RaptorTableProperties.BUCKETED_ON_PROPERTY) ORDERING_PROPERTY(com.facebook.presto.raptor.RaptorTableProperties.ORDERING_PROPERTY) RaptorSessionProperties.getOneSplitPerBucketThreshold(com.facebook.presto.raptor.RaptorSessionProperties.getOneSplitPerBucketThreshold) Constraint(com.facebook.presto.spi.Constraint) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) RaptorTableProperties.getBucketColumns(com.facebook.presto.raptor.RaptorTableProperties.getBucketColumns) MetadataDao(com.facebook.presto.raptor.metadata.MetadataDao) ConnectorTableLayoutResult(com.facebook.presto.spi.ConnectorTableLayoutResult) RAPTOR_ERROR(com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_ERROR) SchemaTablePrefix(com.facebook.presto.spi.SchemaTablePrefix) TreeMap(java.util.TreeMap) ColumnHandle(com.facebook.presto.spi.ColumnHandle) ConnectorNewTableLayout(com.facebook.presto.spi.ConnectorNewTableLayout) ConnectorViewDefinition(com.facebook.presto.spi.ConnectorViewDefinition) BUCKET_COUNT_PROPERTY(com.facebook.presto.raptor.RaptorTableProperties.BUCKET_COUNT_PROPERTY) DeltaInfoPair(com.facebook.presto.raptor.metadata.DeltaInfoPair) RaptorTableProperties.isTableSupportsDeltaDelete(com.facebook.presto.raptor.RaptorTableProperties.isTableSupportsDeltaDelete) ViewNotFoundException(com.facebook.presto.spi.ViewNotFoundException) JsonCodec(com.facebook.airlift.json.JsonCodec) ShardDelta(com.facebook.presto.raptor.metadata.ShardDelta) IDBI(org.skife.jdbi.v2.IDBI) RaptorBucketFunction.validateBucketType(com.facebook.presto.raptor.RaptorBucketFunction.validateBucketType) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) SchemaTableName(com.facebook.presto.spi.SchemaTableName) ConnectorTablePartitioning(com.facebook.presto.spi.ConnectorTablePartitioning) TableColumn(com.facebook.presto.raptor.metadata.TableColumn) DatabaseUtil.runTransaction(com.facebook.presto.raptor.util.DatabaseUtil.runTransaction) ImmutableSet(com.google.common.collect.ImmutableSet) RaptorTableProperties.getDistributionName(com.facebook.presto.raptor.RaptorTableProperties.getDistributionName) ImmutableMap(com.google.common.collect.ImmutableMap) DISTRIBUTION_NAME_PROPERTY(com.facebook.presto.raptor.RaptorTableProperties.DISTRIBUTION_NAME_PROPERTY) Collections.nCopies(java.util.Collections.nCopies) Collection(java.util.Collection) RaptorTableProperties.getTemporalColumn(com.facebook.presto.raptor.RaptorTableProperties.getTemporalColumn) UUID(java.util.UUID) RaptorColumnHandle.isHiddenColumn(com.facebook.presto.raptor.RaptorColumnHandle.isHiddenColumn) Collectors(java.util.stream.Collectors) RaptorColumnHandle.bucketNumberColumnHandle(com.facebook.presto.raptor.RaptorColumnHandle.bucketNumberColumnHandle) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) RaptorTableProperties.getBucketCount(com.facebook.presto.raptor.RaptorTableProperties.getBucketCount) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) NOT_SUPPORTED(com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED) TEMPORAL_COLUMN_PROPERTY(com.facebook.presto.raptor.RaptorTableProperties.TEMPORAL_COLUMN_PROPERTY) Optional(java.util.Optional) StorageTypeConverter(com.facebook.presto.raptor.storage.StorageTypeConverter) SortedMap(java.util.SortedMap) ConnectorMetadata(com.facebook.presto.spi.connector.ConnectorMetadata) Logger(com.facebook.airlift.log.Logger) ORGANIZED_PROPERTY(com.facebook.presto.raptor.RaptorTableProperties.ORGANIZED_PROPERTY) ConnectorTableLayoutHandle(com.facebook.presto.spi.ConnectorTableLayoutHandle) TABLE_SUPPORTS_DELTA_DELETE(com.facebook.presto.raptor.RaptorTableProperties.TABLE_SUPPORTS_DELTA_DELETE) ConnectorTableHandle(com.facebook.presto.spi.ConnectorTableHandle) PrestoException(com.facebook.presto.spi.PrestoException) OptionalInt(java.util.OptionalInt) AtomicReference(java.util.concurrent.atomic.AtomicReference) Collectors.toCollection(java.util.stream.Collectors.toCollection) ImmutableList(com.google.common.collect.ImmutableList) ALREADY_EXISTS(com.facebook.presto.spi.StandardErrorCode.ALREADY_EXISTS) TypeManager(com.facebook.presto.common.type.TypeManager) SHARD_UUID_COLUMN_NAME(com.facebook.presto.raptor.RaptorColumnHandle.SHARD_UUID_COLUMN_NAME) Objects.requireNonNull(java.util.Objects.requireNonNull) DatabaseUtil.onDemandDao(com.facebook.presto.raptor.util.DatabaseUtil.onDemandDao) Type(com.facebook.presto.common.type.Type) Table(com.facebook.presto.raptor.metadata.Table) ConnectorInsertTableHandle(com.facebook.presto.spi.ConnectorInsertTableHandle) ConnectorOutputMetadata(com.facebook.presto.spi.connector.ConnectorOutputMetadata) ConnectorTableLayout(com.facebook.presto.spi.ConnectorTableLayout) ASC_NULLS_FIRST(com.facebook.presto.common.block.SortOrder.ASC_NULLS_FIRST) Maps(com.google.common.collect.Maps) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) ShardInfo(com.facebook.presto.raptor.metadata.ShardInfo) LongConsumer(java.util.function.LongConsumer) Collectors.toList(java.util.stream.Collectors.toList) TableNotFoundException(com.facebook.presto.spi.TableNotFoundException) Handle(org.skife.jdbi.v2.Handle) RaptorColumnHandle.shardRowIdHandle(com.facebook.presto.raptor.RaptorColumnHandle.shardRowIdHandle) ImmutableList(com.google.common.collect.ImmutableList) TableColumn(com.facebook.presto.raptor.metadata.TableColumn) RaptorBucketFunction.validateBucketType(com.facebook.presto.raptor.RaptorBucketFunction.validateBucketType) Type(com.facebook.presto.common.type.Type)

Example 33 with Handle

use of jnc.platform.win32.Handle in project presto by prestodb.

the class SchemaDaoUtil method createTablesWithRetry.

public static void createTablesWithRetry(IDBI dbi) {
    Duration delay = new Duration(2, TimeUnit.SECONDS);
    while (true) {
        try (Handle handle = dbi.open()) {
            createTables(handle.attach(SchemaDao.class));
            alterTables(handle.getConnection(), handle.attach(SchemaDao.class));
            return;
        } catch (UnableToObtainConnectionException | SQLTransientException e) {
            log.warn("Failed to connect to database. Will retry again in %s. Exception: %s", delay, e.getMessage());
            sleep(delay);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : SQLException(java.sql.SQLException) SQLTransientException(java.sql.SQLTransientException) UnableToObtainConnectionException(org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException) Duration(io.airlift.units.Duration) Handle(org.skife.jdbi.v2.Handle)

Example 34 with Handle

use of jnc.platform.win32.Handle in project presto by prestodb.

the class DatabaseShardManager method getExistingShardUuids.

@Override
public Set<UUID> getExistingShardUuids(long tableId, Set<UUID> shardUuids) {
    try (Handle handle = dbi.open()) {
        String args = Joiner.on(",").join(nCopies(shardUuids.size(), "?"));
        String selectShards = format("SELECT shard_uuid FROM %s WHERE shard_uuid IN (%s)", shardIndexTable(tableId), args);
        ImmutableSet.Builder<UUID> existingShards = ImmutableSet.builder();
        try (PreparedStatement statement = handle.getConnection().prepareStatement(selectShards)) {
            bindUuids(statement, shardUuids);
            try (ResultSet rs = statement.executeQuery()) {
                while (rs.next()) {
                    existingShards.add(uuidFromBytes(rs.getBytes("shard_uuid")));
                }
            }
        }
        return existingShards.build();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) UUID(java.util.UUID) RaptorColumnHandle(com.facebook.presto.raptor.RaptorColumnHandle) Handle(org.skife.jdbi.v2.Handle)

Example 35 with Handle

use of jnc.platform.win32.Handle in project killbill by killbill.

the class EntitySqlDaoTransactionalJdbiWrapper method execute.

/**
 * @param <ReturnType>                   object type to return from the transaction
 * @param requestedRO                    hint as whether to use the read-only connection
 * @param entitySqlDaoTransactionWrapper transaction to execute
 * @return result from the transaction fo type ReturnType
 */
public <ReturnType> ReturnType execute(final boolean requestedRO, final EntitySqlDaoTransactionWrapper<ReturnType> entitySqlDaoTransactionWrapper) {
    final String debugInfo = logger.isDebugEnabled() ? getDebugInfo() : null;
    final Handle handle = dbRouter.getHandle(requestedRO);
    logger.debug("DBI handle created, transaction: {}", debugInfo);
    try {
        final EntitySqlDao<EntityModelDao<Entity>, Entity> entitySqlDao = handle.attach(InitialEntitySqlDao.class);
        // The transaction isolation level is now set at the pool level: this avoids 3 roundtrips for each transaction
        // Note that if the pool isn't used (tests or PostgreSQL), the transaction level will depend on the DB configuration
        // return entitySqlDao.inTransaction(TransactionIsolationLevel.READ_COMMITTED, new JdbiTransaction<ReturnType, EntityModelDao<Entity>, Entity>(handle, entitySqlDaoTransactionWrapper));
        logger.debug("Starting transaction {}", debugInfo);
        final ReturnType returnType = entitySqlDao.inTransaction(new JdbiTransaction<ReturnType, EntityModelDao<Entity>, Entity>(handle, entitySqlDaoTransactionWrapper));
        logger.debug("Exiting  transaction {}, returning {}", debugInfo, returnType);
        return returnType;
    } finally {
        handle.close();
        logger.debug("DBI handle closed,  transaction: {}", debugInfo);
    }
}
Also used : Entity(org.killbill.billing.util.entity.Entity) Handle(org.skife.jdbi.v2.Handle)

Aggregations

Handle (org.skife.jdbi.v2.Handle)103 DBI (org.skife.jdbi.v2.DBI)28 Before (org.junit.Before)21 IOException (java.io.IOException)18 List (java.util.List)17 DataSourceFactory (io.dropwizard.db.DataSourceFactory)15 DBIFactory (io.dropwizard.jdbi.DBIFactory)15 SQLException (java.sql.SQLException)15 Map (java.util.Map)14 Test (org.junit.Test)14 Test (org.testng.annotations.Test)14 DateTime (org.joda.time.DateTime)13 ArrayList (java.util.ArrayList)11 TransactionStatus (org.skife.jdbi.v2.TransactionStatus)11 ResultSet (java.sql.ResultSet)10 ImmutableList (com.google.common.collect.ImmutableList)8 UUID (java.util.UUID)8 CallbackFailedException (org.skife.jdbi.v2.exceptions.CallbackFailedException)7 ImmutableSet (com.google.common.collect.ImmutableSet)6 Set (java.util.Set)6