Java Code Examples for org.apache.hadoop.hive.metastore.TableType

The following examples show how to use org.apache.hadoop.hive.metastore.TableType. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: data-highway   Source File: AvroHiveTableStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Table newHiveTable(
    String databaseName,
    String tableName,
    String partitionColumnName,
    String location,
    Schema schema,
    int version) {

  Table table = new Table();
  table.setDbName(databaseName);
  table.setTableName(tableName);

  table.setTableType(TableType.EXTERNAL_TABLE.toString());
  table.putToParameters("EXTERNAL", "TRUE");
  addRoadAnnotations(table);

  URI schemaUri = uriResolver.resolve(schema, table.getTableName(), version);
  table.putToParameters(AVRO_SCHEMA_URL, schemaUri.toString());
  table.putToParameters(AVRO_SCHEMA_VERSION, Integer.toString(version));
  table.setPartitionKeys(Arrays.asList(new FieldSchema(partitionColumnName, "string", null)));

  table.setSd(AvroStorageDescriptorFactory.create(location));

  return table;
}
 
Example 2
/**
 * @return boolean
 *    true  -> directory created
 *    false -> directory not created
 */
public boolean validateNewTableAndCreateDirectory(org.apache.hadoop.hive.metastore.api.Table tbl) throws TException {
  checkNotNull(tbl, "tbl cannot be null");
  if (tableExists(tbl.getDbName(), tbl.getTableName())) {
    throw new AlreadyExistsException("Table " + tbl.getTableName() + " already exists.");
  }
  validateTableObject(tbl, conf);

  if (TableType.VIRTUAL_VIEW.toString().equals(tbl.getTableType())) {
    // we don't need to create directory for virtual views
    return false;
  }

  if (StringUtils.isEmpty(tbl.getSd().getLocation())) {
    org.apache.hadoop.hive.metastore.api.Database db = getDatabase(tbl.getDbName());
    tbl.getSd().setLocation(hiveShims.getDefaultTablePath(db, tbl.getTableName(), wh).toString());
  } else {
    tbl.getSd().setLocation(wh.getDnsPath(new Path(tbl.getSd().getLocation())).toString());
  }

  Path tblPath = new Path(tbl.getSd().getLocation());
  return makeDirs(wh, tblPath);
}
 
Example 3
@Test
public void testValidateTableAndCreateDirectoryVirtualView() throws Exception {
  testTbl.setTableType(TableType.VIRTUAL_VIEW.toString());
  testTbl.getStorageDescriptor().setLocation(null);
  org.apache.hadoop.hive.metastore.api.Table hiveTbl = CatalogToHiveConverter.convertTable(testTbl, testTbl.getDatabaseName());

  when(glueClient.getDatabase(any(GetDatabaseRequest.class)))
    .thenReturn(new GetDatabaseResult().withDatabase(testDb));
  when(glueClient.getTable(new GetTableRequest()
    .withDatabaseName(testTbl.getDatabaseName()).withName(testTbl.getName())))
    .thenThrow(EntityNotFoundException.class);

  assertFalse(metastoreClientDelegate.validateNewTableAndCreateDirectory(hiveTbl));
  assertNull(testTbl.getStorageDescriptor().getLocation());
  verify(wh, never()).mkdirs(any(Path.class), anyBoolean());
}
 
Example 4
@Test(expected=InvalidOperationException.class)
public void testRenamePartitionForUnknownTable() throws Exception {
  String dbName = testDB.getName();
  Table externalTable = getTestTable();
  externalTable.setTableType(TableType.EXTERNAL_TABLE.name());   
  
  StorageDescriptor sd = HiveToCatalogConverter.convertStorageDescriptor(testPartition.getSd());
  
  Partition oldPartition = new Partition()
      .withDatabaseName(dbName).withTableName(externalTable.getName())
      .withValues(Lists.newArrayList("oldval")).withStorageDescriptor(sd);
  
  Partition newPartition = new Partition()
                                    .withDatabaseName(dbName).withTableName(externalTable.getName())
                                    .withValues(Lists.newArrayList("newval")).withStorageDescriptor(sd);    
      
  when(glueClient.getDatabase(any(GetDatabaseRequest.class)))
    .thenReturn(new GetDatabaseResult().withDatabase(HiveToCatalogConverter.convertDatabase(testDB)));
  doThrow(EntityNotFoundException.class).when(glueClient).getTable(any(GetTableRequest.class));
  
  when(glueClient.getPartition(any(GetPartitionRequest.class)))
    .thenReturn(new GetPartitionResult().withPartition(oldPartition));     
  
  metastoreClient.renamePartition(dbName, externalTable.getName(), oldPartition.getValues(),
      CatalogToHiveConverter.convertPartition(newPartition));
}
 
Example 5
@Test(expected=InvalidOperationException.class)
public void testRenamePartitionForUnknownPartition() throws Exception {
  String dbName = testDB.getName();
  Table externalTable = getTestTable();
  externalTable.setTableType(TableType.EXTERNAL_TABLE.name());   
  
  StorageDescriptor sd = HiveToCatalogConverter.convertStorageDescriptor(testPartition.getSd());
  
  Partition oldPartition = new Partition()
      .withDatabaseName(dbName).withTableName(externalTable.getName())
      .withValues(Lists.newArrayList("oldval")).withStorageDescriptor(sd);
  
  Partition newPartition = new Partition()
                                    .withDatabaseName(dbName).withTableName(externalTable.getName())
                                    .withValues(Lists.newArrayList("newval")).withStorageDescriptor(sd);

  when(glueClient.getDatabase(any(GetDatabaseRequest.class)))
    .thenReturn(new GetDatabaseResult().withDatabase(HiveToCatalogConverter.convertDatabase(testDB)));
  when(glueClient.getTable(any(GetTableRequest.class)))
  .thenReturn(new GetTableResult().withTable(externalTable));
  doThrow(EntityNotFoundException.class).when(glueClient).getPartition(any(GetPartitionRequest.class));
  
  metastoreClient.renamePartition(dbName, externalTable.getName(), oldPartition.getValues(),
      CatalogToHiveConverter.convertPartition(newPartition));
}
 
Example 6
@Test(expected=InvalidOperationException.class)
public void testRenamePartitionForInvalidSD() throws Exception {
  String dbName = testDB.getName();
  Table externalTable = getTestTable();
  externalTable.setTableType(TableType.EXTERNAL_TABLE.name());   
  
  StorageDescriptor sd = HiveToCatalogConverter.convertStorageDescriptor(testPartition.getSd());
  
  Partition oldPartition = new Partition()
      .withDatabaseName(dbName).withTableName(externalTable.getName())
      .withValues(Lists.newArrayList("oldval")).withStorageDescriptor(null);
  
  Partition newPartition = new Partition()
                                    .withDatabaseName(dbName).withTableName(externalTable.getName())
                                    .withValues(Lists.newArrayList("newval")).withStorageDescriptor(sd);

  when(glueClient.getDatabase(any(GetDatabaseRequest.class)))
    .thenReturn(new GetDatabaseResult().withDatabase(HiveToCatalogConverter.convertDatabase(testDB)));
  when(glueClient.getTable(any(GetTableRequest.class)))
  .thenReturn(new GetTableResult().withTable(externalTable));
  when(glueClient.getPartition(any(GetPartitionRequest.class)))
    .thenReturn(new GetPartitionResult().withPartition(oldPartition));

  metastoreClient.renamePartition(dbName, externalTable.getName(), oldPartition.getValues(),
      CatalogToHiveConverter.convertPartition(newPartition));
}
 
Example 7
Source Project: presto   Source File: HiveMetadata.java    License: Apache License 2.0 6 votes vote down vote up
private Optional<SystemTable> getPropertiesSystemTable(ConnectorSession session, SchemaTableName tableName, SchemaTableName sourceTableName)
{
    Optional<Table> table = metastore.getTable(new HiveIdentity(session), sourceTableName.getSchemaName(), sourceTableName.getTableName());
    if (table.isEmpty() || table.get().getTableType().equals(TableType.VIRTUAL_VIEW.name())) {
        throw new TableNotFoundException(tableName);
    }
    Map<String, String> sortedTableParameters = ImmutableSortedMap.copyOf(table.get().getParameters());
    List<ColumnMetadata> columns = sortedTableParameters.keySet().stream()
            .map(key -> new ColumnMetadata(key, VarcharType.VARCHAR))
            .collect(toImmutableList());
    List<Type> types = columns.stream()
            .map(ColumnMetadata::getType)
            .collect(toImmutableList());
    Iterable<List<Object>> propertyValues = ImmutableList.of(ImmutableList.copyOf(sortedTableParameters.values()));

    return Optional.of(createSystemTable(new ConnectorTableMetadata(sourceTableName, columns), constraint -> new InMemoryRecordSet(types, propertyValues).cursor()));
}
 
Example 8
Source Project: presto   Source File: TableMetadata.java    License: Apache License 2.0 6 votes vote down vote up
public TableMetadata(Table table, Map<String, HiveColumnStatistics> columnStatistics)
{
    owner = table.getOwner();
    tableType = table.getTableType();
    dataColumns = table.getDataColumns();
    partitionColumns = table.getPartitionColumns();
    parameters = table.getParameters();

    StorageFormat tableFormat = table.getStorage().getStorageFormat();
    storageFormat = Arrays.stream(HiveStorageFormat.values())
            .filter(format -> tableFormat.equals(StorageFormat.fromHiveStorageFormat(format)))
            .findFirst();
    bucketProperty = table.getStorage().getBucketProperty();
    serdeParameters = table.getStorage().getSerdeParameters();

    if (tableType.equals(TableType.EXTERNAL_TABLE.name())) {
        externalLocation = Optional.of(table.getStorage().getLocation());
    }
    else {
        externalLocation = Optional.empty();
    }

    viewOriginalText = table.getViewOriginalText();
    viewExpandedText = table.getViewExpandedText();
    this.columnStatistics = ImmutableMap.copyOf(requireNonNull(columnStatistics, "columnStatistics is null"));
}
 
Example 9
Source Project: presto   Source File: TestBackgroundHiveSplitLoader.java    License: Apache License 2.0 6 votes vote down vote up
private static Table table(
        String location,
        List<Column> partitionColumns,
        Optional<HiveBucketProperty> bucketProperty,
        Map<String, String> tableParameters,
        StorageFormat storageFormat)
{
    Table.Builder tableBuilder = Table.builder();
    tableBuilder.getStorageBuilder()
            .setStorageFormat(storageFormat)
            .setLocation(location)
            .setSkewed(false)
            .setBucketProperty(bucketProperty);

    return tableBuilder
            .setDatabaseName("test_dbname")
            .setOwner("testOwner")
            .setTableName("test_table")
            .setTableType(TableType.MANAGED_TABLE.toString())
            .setDataColumns(ImmutableList.of(new Column("col1", HIVE_STRING, Optional.empty())))
            .setParameters(tableParameters)
            .setPartitionColumns(partitionColumns)
            .build();
}
 
Example 10
Source Project: presto   Source File: MockThriftMetastoreClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Table getTable(String dbName, String tableName)
        throws TException
{
    accessCount.incrementAndGet();
    if (throwException) {
        throw new RuntimeException();
    }
    if (!dbName.equals(TEST_DATABASE) || !tableName.equals(TEST_TABLE)) {
        throw new NoSuchObjectException();
    }
    return new Table(
            TEST_TABLE,
            TEST_DATABASE,
            "",
            0,
            0,
            0,
            DEFAULT_STORAGE_DESCRIPTOR,
            ImmutableList.of(new FieldSchema("key", "string", null)),
            ImmutableMap.of(),
            "",
            "",
            TableType.MANAGED_TABLE.name());
}
 
Example 11
Source Project: flink   Source File: HiveShimV2.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getViews(IMetaStoreClient client, String databaseName) throws UnknownDBException, TException {
	try {
		Method method = client.getClass().getMethod("getTables", String.class, String.class, TableType.class);
		return (List<String>) method.invoke(client, databaseName, null, TableType.VIRTUAL_VIEW);
	} catch (InvocationTargetException ite) {
		Throwable targetEx = ite.getTargetException();
		if (targetEx instanceof TException) {
			throw (TException) targetEx;
		} else {
			throw new CatalogException(String.format("Failed to get views for %s", databaseName), targetEx);
		}
	} catch (NoSuchMethodException | IllegalAccessException e) {
		throw new CatalogException(String.format("Failed to get views for %s", databaseName), e);
	}
}
 
Example 12
Source Project: circus-train   Source File: ReplicaTest.java    License: Apache License 2.0 6 votes vote down vote up
private Table newTable() {
  Table table = new Table();
  table.setDbName(DB_NAME);
  table.setTableName(TABLE_NAME);
  table.setTableType(TableType.EXTERNAL_TABLE.name());

  StorageDescriptor sd = new StorageDescriptor();
  sd.setLocation(tableLocation);
  table.setSd(sd);

  HashMap<String, String> parameters = new HashMap<>();
  parameters.put(StatsSetupConst.ROW_COUNT, "1");
  table.setParameters(parameters);

  table.setPartitionKeys(PARTITIONS);
  return table;
}
 
Example 13
Source Project: circus-train   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Table createView(
    HiveMetaStoreClient metaStoreClient,
    String database,
    String view,
    String table,
    List<FieldSchema> partitionCols)
  throws TException {
  Table hiveView = new Table();
  hiveView.setDbName(database);
  hiveView.setTableName(view);
  hiveView.setTableType(TableType.VIRTUAL_VIEW.name());
  hiveView.setViewOriginalText(hql(database, table));
  hiveView.setViewExpandedText(expandHql(database, table, DATA_COLUMNS, partitionCols));
  hiveView.setPartitionKeys(partitionCols);

  StorageDescriptor sd = new StorageDescriptor();
  sd.setCols(DATA_COLUMNS);
  sd.setParameters(new HashMap<String, String>());
  sd.setSerdeInfo(new SerDeInfo());
  hiveView.setSd(sd);

  metaStoreClient.createTable(hiveView);

  return hiveView;
}
 
Example 14
/**
 * A base implementation for creating a non bucketed, external {@link HiveTable} for a {@link Path}.
 *
 * @param path a {@link Path} used to create the {@link HiveTable}.
 * @param dbName the database name for the created {@link HiveTable}.
 * @param tableName the table name for the created {@link HiveTable}.
 * @return a {@link HiveTable}s for the given {@link Path}.
 * @throws IOException
 */
protected HiveTable getTable(Path path, String dbName, String tableName) throws IOException {

  HiveTable.Builder tableBuilder = new HiveTable.Builder().withDbName(dbName).withTableName(tableName);

  if (!this.emptyInputPathFlag) {
    tableBuilder = tableBuilder.withSerdeManaager(HiveSerDeManager.get(this.props));
  }
  HiveTable table = tableBuilder.build();
  table.setLocation(this.fs.makeQualified(getTableLocation(path)).toString());

  if (!this.emptyInputPathFlag) {
    table.setSerDeProps(path);
  }

  // Setting table-level props.
  table.setProps(getRuntimePropsEnrichedTblProps());

  table.setStorageProps(this.props.getStorageProps());
  table.setSerDeProps(this.props.getSerdeProps());
  table.setNumBuckets(-1);
  table.setBucketColumns(Lists.<String> newArrayList());
  table.setTableType(TableType.EXTERNAL_TABLE.toString());
  return table;
}
 
Example 15
Source Project: waggle-dance   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
static Table createUnpartitionedTable(
    HiveMetaStoreClient metaStoreClient,
    String database,
    String table,
    File location)
  throws TException {
  Table hiveTable = new Table();
  hiveTable.setDbName(database);
  hiveTable.setTableName(table);
  hiveTable.setTableType(TableType.EXTERNAL_TABLE.name());
  hiveTable.putToParameters("EXTERNAL", "TRUE");

  StorageDescriptor sd = new StorageDescriptor();
  sd.setCols(DATA_COLUMNS);
  sd.setLocation(location.toURI().toString());
  sd.setParameters(new HashMap<>());
  sd.setSerdeInfo(new SerDeInfo());

  hiveTable.setSd(sd);

  metaStoreClient.createTable(hiveTable);

  return hiveTable;
}
 
Example 16
Source Project: waggle-dance   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
static Table createPartitionedTable(HiveMetaStoreClient metaStoreClient, String database, String table, File location)
  throws Exception {

  Table hiveTable = new Table();
  hiveTable.setDbName(database);
  hiveTable.setTableName(table);
  hiveTable.setTableType(TableType.EXTERNAL_TABLE.name());
  hiveTable.putToParameters("EXTERNAL", "TRUE");

  hiveTable.setPartitionKeys(PARTITION_COLUMNS);

  StorageDescriptor sd = new StorageDescriptor();
  sd.setCols(DATA_COLUMNS);
  sd.setLocation(location.toURI().toString());
  sd.setParameters(new HashMap<>());
  sd.setSerdeInfo(new SerDeInfo());

  hiveTable.setSd(sd);

  metaStoreClient.createTable(hiveTable);

  return hiveTable;
}
 
Example 17
Source Project: dremio-oss   Source File: HiveClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Table getTable(final String dbName, final String tableName, boolean ignoreAuthzErrors) throws TException{

  Table table = getTableWithoutTableTypeChecking(dbName, tableName, ignoreAuthzErrors);

  if(table == null){
    return null;
  }

  TableType type = TableType.valueOf(table.getTableType());
  switch (type) {
    case EXTERNAL_TABLE:
    case MANAGED_TABLE:
      return table;

    case VIRTUAL_VIEW:
      throw UserException.unsupportedError().message("Hive views are not supported").build(NOPLogger.NOP_LOGGER);
    case INDEX_TABLE:
    default:
      return null;
  }
}
 
Example 18
Source Project: streamx   Source File: AvroHiveUtil.java    License: Apache License 2.0 6 votes vote down vote up
private Table constructAvroTable(String database, String tableName, Schema schema, Partitioner partitioner)
    throws HiveMetaStoreException {
  Table table = new Table(database, tableName);
  table.setTableType(TableType.EXTERNAL_TABLE);
  table.getParameters().put("EXTERNAL", "TRUE");
  String tablePath = FileUtils.hiveDirectoryName(url, topicsDir, tableName);
  table.setDataLocation(new Path(tablePath));
  table.setSerializationLib(avroSerde);
  try {
    table.setInputFormatClass(avroInputFormat);
    table.setOutputFormatClass(avroOutputFormat);
  } catch (HiveException e) {
    throw new HiveMetaStoreException("Cannot find input/output format:", e);
  }
  List<FieldSchema> columns = HiveSchemaConverter.convertSchema(schema);
  table.setFields(columns);
  table.setPartCols(partitioner.partitionFields());
  table.getParameters().put(AVRO_SCHEMA_LITERAL, avroData.fromConnectSchema(schema).toString());
  return table;
}
 
Example 19
Source Project: streamx   Source File: ParquetHiveUtil.java    License: Apache License 2.0 6 votes vote down vote up
private Table constructParquetTable(String database, String tableName, Schema schema, Partitioner partitioner) throws HiveMetaStoreException {
  Table table = new Table(database, tableName);
  table.setTableType(TableType.EXTERNAL_TABLE);
  table.getParameters().put("EXTERNAL", "TRUE");
  String tablePath = FileUtils.hiveDirectoryName(url, topicsDir, tableName);
  table.setDataLocation(new Path(tablePath));
  table.setSerializationLib(getHiveParquetSerde());
  try {
    table.setInputFormatClass(getHiveParquetInputFormat());
    table.setOutputFormatClass(getHiveParquetOutputFormat());
  } catch (HiveException e) {
    throw new HiveMetaStoreException("Cannot find input/output format:", e);
  }
  // convert copycat schema schema to Hive columns
  List<FieldSchema> columns = HiveSchemaConverter.convertSchema(schema);
  table.setFields(columns);
  table.setPartCols(partitioner.partitionFields());
  return table;
}
 
Example 20
Source Project: incubator-atlas   Source File: HiveMetaStoreBridgeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testImportThatUpdatesRegisteredTable() throws Exception {
    setupDB(hiveClient, TEST_DB_NAME);

    List<Table> hiveTables = setupTables(hiveClient, TEST_DB_NAME, TEST_TABLE_NAME);

    returnExistingDatabase(TEST_DB_NAME, atlasClient, CLUSTER_NAME);

    // return existing table
    when(atlasClient.getEntity(HiveDataTypes.HIVE_TABLE.getName(),
        AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, HiveMetaStoreBridge.getTableQualifiedName(CLUSTER_NAME, TEST_DB_NAME, TEST_TABLE_NAME)))
        .thenReturn(getEntityReference(HiveDataTypes.HIVE_TABLE.getName(), "82e06b34-9151-4023-aa9d-b82103a50e77"));
    when(atlasClient.getEntity("82e06b34-9151-4023-aa9d-b82103a50e77")).thenReturn(createTableReference());
    String processQualifiedName = HiveMetaStoreBridge.getTableProcessQualifiedName(CLUSTER_NAME, hiveTables.get(0));
    when(atlasClient.getEntity(HiveDataTypes.HIVE_PROCESS.getName(),
        AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, processQualifiedName)).thenReturn(getEntityReference(HiveDataTypes.HIVE_PROCESS.getName(), "82e06b34-9151-4023-aa9d-b82103a50e77"));

    HiveMetaStoreBridge bridge = new HiveMetaStoreBridge(CLUSTER_NAME, hiveClient, atlasClient);
    bridge.importHiveMetadata(true);

    // verify update is called on table
    verify(atlasClient).updateEntity(eq("82e06b34-9151-4023-aa9d-b82103a50e77"),
            (Referenceable) argThat(new MatchesReferenceableProperty(HiveMetaStoreBridge.TABLE_TYPE_ATTR,
                    TableType.EXTERNAL_TABLE.name())));
}
 
Example 21
Source Project: flink   Source File: HiveShimV230.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getViews(IMetaStoreClient client, String databaseName) throws UnknownDBException, TException {
	try {
		Method method = client.getClass().getMethod("getTables", String.class, String.class, TableType.class);
		return (List<String>) method.invoke(client, databaseName, null, TableType.VIRTUAL_VIEW);
	} catch (InvocationTargetException ite) {
		Throwable targetEx = ite.getTargetException();
		if (targetEx instanceof TException) {
			throw (TException) targetEx;
		} else {
			throw new CatalogException(String.format("Failed to get views for %s", databaseName), targetEx);
		}
	} catch (NoSuchMethodException | IllegalAccessException e) {
		throw new CatalogException(String.format("Failed to get views for %s", databaseName), e);
	}
}
 
Example 22
Source Project: data-highway   Source File: AvroHiveTableStrategyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void newHiveTable() throws URISyntaxException {
  when(uriResolver.resolve(schema1, TABLE, 1))
      .thenReturn(new URI("https://s3.amazonaws.com/road-schema-bucket/roads/table/schemas/1/table_v1.avsc"));
  doReturn(Instant.ofEpochSecond(1526462225L)).when(clock).instant();

  Table result = underTest.newHiveTable(DATABASE, TABLE, PARTITION_COLUMN, LOCATION, schema1, 1);

  assertThat(result.getDbName(), is(DATABASE));
  assertThat(result.getTableName(), is(TABLE));
  assertThat(result.getTableType(), is(TableType.EXTERNAL_TABLE.toString()));
  Map<String, String> parameters = result.getParameters();
  assertThat(parameters.get("EXTERNAL"), is("TRUE"));
  assertThat(parameters.get("data-highway.version"), is(DataHighwayVersion.VERSION));
  assertThat(parameters.get("data-highway.last-revision"), is("2018-05-16T09:17:05Z"));
  assertThat(parameters.get(AvroHiveTableStrategy.AVRO_SCHEMA_URL),
      is("https://s3.amazonaws.com/road-schema-bucket/roads/table/schemas/1/table_v1.avsc"));
  assertThat(parameters.get(AvroHiveTableStrategy.AVRO_SCHEMA_VERSION), is("1"));
  List<FieldSchema> partitionKeys = result.getPartitionKeys();
  assertThat(partitionKeys.size(), is(1));
  assertThat(partitionKeys.get(0), is(new FieldSchema(PARTITION_COLUMN, "string", null)));
  StorageDescriptor storageDescriptor = result.getSd();
  assertThat(storageDescriptor.getInputFormat(), is(AvroStorageDescriptorFactory.AVRO_INPUT_FORMAT));
  assertThat(storageDescriptor.getOutputFormat(), is(AvroStorageDescriptorFactory.AVRO_OUTPUT_FORMAT));
  assertThat(storageDescriptor.getLocation(), is(LOCATION));
  assertThat(storageDescriptor.getCols().size(), is(0));
  SerDeInfo serdeInfo = storageDescriptor.getSerdeInfo();
  assertThat(serdeInfo.getSerializationLib(), is(AvroStorageDescriptorFactory.AVRO_SERDE));
}
 
Example 23
Source Project: data-highway   Source File: AvroHiveTableStrategyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void alterHiveTable() throws URISyntaxException {
  when(uriResolver.resolve(schema1, TABLE, 1))
      .thenReturn(new URI("https://s3.amazonaws.com/road-schema-bucket/roads/table/schemas/1/table_v1.avsc"));
  when(uriResolver.resolve(schema2, TABLE, 2))
      .thenReturn(new URI("https://s3.amazonaws.com/road-schema-bucket/roads/table/schemas/2/table_v2.avsc"));
  doReturn(Instant.ofEpochSecond(1526462225L)).when(clock).instant();

  Table table = underTest.newHiveTable(DATABASE, TABLE, PARTITION_COLUMN, LOCATION, schema1, 1);

  Table result = underTest.alterHiveTable(table, schema2, 2);

  assertThat(result.getDbName(), is(DATABASE));
  assertThat(result.getTableName(), is(TABLE));
  assertThat(result.getTableType(), is(TableType.EXTERNAL_TABLE.toString()));
  Map<String, String> parameters = result.getParameters();
  assertThat(parameters.get("EXTERNAL"), is("TRUE"));
  assertThat(parameters.get("data-highway.version"), is(DataHighwayVersion.VERSION));
  assertThat(parameters.get("data-highway.last-revision"), is("2018-05-16T09:17:05Z"));
  assertThat(parameters.get(AvroHiveTableStrategy.AVRO_SCHEMA_URL),
      is("https://s3.amazonaws.com/road-schema-bucket/roads/table/schemas/2/table_v2.avsc"));
  assertThat(parameters.get(AvroHiveTableStrategy.AVRO_SCHEMA_VERSION), is("2"));
  List<FieldSchema> partitionKeys = result.getPartitionKeys();
  assertThat(partitionKeys.size(), is(1));
  assertThat(partitionKeys.get(0), is(new FieldSchema(PARTITION_COLUMN, "string", null)));
  StorageDescriptor storageDescriptor = result.getSd();
  assertThat(storageDescriptor.getInputFormat(), is(AvroStorageDescriptorFactory.AVRO_INPUT_FORMAT));
  assertThat(storageDescriptor.getOutputFormat(), is(AvroStorageDescriptorFactory.AVRO_OUTPUT_FORMAT));
  assertThat(storageDescriptor.getLocation(), is(LOCATION));
  assertThat(storageDescriptor.getCols().size(), is(0));
  SerDeInfo serdeInfo = storageDescriptor.getSerdeInfo();
  assertThat(serdeInfo.getSerializationLib(), is(AvroStorageDescriptorFactory.AVRO_SERDE));
}
 
Example 24
@Test
public void testValidate_ViewTableType() {
  Table tbl = getTestTable();
  tbl.setTableType(TableType.VIRTUAL_VIEW.name());
  tbl.getStorageDescriptor().getSerdeInfo().setSerializationLibrary(null);
  REQUIRED_PROPERTIES_VALIDATOR.validate(tbl);
}
 
Example 25
@Test
public void testGetTableMeta() throws Exception {
  List<Table> tables = Lists.newArrayList(testTbl);
  List<String> tableTypes = Lists.newArrayList(TableType.MANAGED_TABLE.name());

  when(glueClient.getDatabases(any(GetDatabasesRequest.class))).thenReturn(
      new GetDatabasesResult().withDatabaseList(testDb));
  when(glueClient.getTables(any(GetTablesRequest.class))).thenReturn(
      new GetTablesResult().withTableList(tables));

  List<TableMeta> tableMetaResult = metastoreClientDelegate.getTableMeta(testDb.getName(), testTbl.getName(), tableTypes);
  assertEquals(CatalogToHiveConverter.convertTableMeta(testTbl, testDb.getName()), Iterables.getOnlyElement(tableMetaResult));
}
 
Example 26
Source Project: incubator-gobblin   Source File: HiveMetaStoreUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert a {@link HiveTable} into a {@link Table}.
 */
public static Table getTable(HiveTable hiveTable) {
  State props = hiveTable.getProps();
  Table table = new Table();
  table.setDbName(hiveTable.getDbName());
  table.setTableName(hiveTable.getTableName());
  table.setParameters(getParameters(props));
  if (hiveTable.getCreateTime().isPresent()) {
    table.setCreateTime(Ints.checkedCast(hiveTable.getCreateTime().get()));
  }
  if (hiveTable.getLastAccessTime().isPresent()) {
    table.setLastAccessTime(Ints.checkedCast(hiveTable.getLastAccessTime().get()));
  }
  if (hiveTable.getOwner().isPresent()) {
    table.setOwner(hiveTable.getOwner().get());
  }
  if (hiveTable.getRetention().isPresent()) {
    table.setRetention(Ints.checkedCast(hiveTable.getRetention().get()));
  }
  if (hiveTable.getTableType().isPresent()) {
    table.setTableType(hiveTable.getTableType().get());
  } else {
    table.setTableType(DEFAULT_TABLE_TYPE.toString());
  }
  if (table.getTableType().equals(TableType.EXTERNAL_TABLE.toString())) {
    table.getParameters().put(EXTERNAL, Boolean.TRUE.toString().toUpperCase());
  }
  table.setPartitionKeys(getFieldSchemas(hiveTable.getPartitionKeys()));
  table.setSd(getStorageDescriptor(hiveTable));
  return table;
}
 
Example 27
Source Project: presto   Source File: Procedures.java    License: Apache License 2.0 5 votes vote down vote up
public static void checkIsPartitionedTable(Table table)
{
    if (table.getTableType().equals(TableType.VIRTUAL_VIEW.name())) {
        throw new PrestoException(INVALID_PROCEDURE_ARGUMENT, "Table is a view: " + table.getSchemaTableName());
    }

    if (table.getTableType().equals(TableType.MATERIALIZED_VIEW.name())) {
        throw new PrestoException(INVALID_PROCEDURE_ARGUMENT, "Table is a materialized view: " + table.getSchemaTableName());
    }

    if (table.getPartitionColumns().isEmpty()) {
        throw new PrestoException(INVALID_PROCEDURE_ARGUMENT, "Table is not partitioned: " + table.getSchemaTableName());
    }
}
 
Example 28
Source Project: presto   Source File: TableMetadata.java    License: Apache License 2.0 5 votes vote down vote up
@JsonCreator
public TableMetadata(
        @JsonProperty("owner") String owner,
        @JsonProperty("tableType") String tableType,
        @JsonProperty("dataColumns") List<Column> dataColumns,
        @JsonProperty("partitionColumns") List<Column> partitionColumns,
        @JsonProperty("parameters") Map<String, String> parameters,
        @JsonProperty("storageFormat") Optional<HiveStorageFormat> storageFormat,
        @JsonProperty("bucketProperty") Optional<HiveBucketProperty> bucketProperty,
        @JsonProperty("serdeParameters") Map<String, String> serdeParameters,
        @JsonProperty("externalLocation") Optional<String> externalLocation,
        @JsonProperty("viewOriginalText") Optional<String> viewOriginalText,
        @JsonProperty("viewExpandedText") Optional<String> viewExpandedText,
        @JsonProperty("columnStatistics") Map<String, HiveColumnStatistics> columnStatistics)
{
    this.owner = requireNonNull(owner, "owner is null");
    this.tableType = requireNonNull(tableType, "tableType is null");
    this.dataColumns = ImmutableList.copyOf(requireNonNull(dataColumns, "dataColumns is null"));
    this.partitionColumns = ImmutableList.copyOf(requireNonNull(partitionColumns, "partitionColumns is null"));
    this.parameters = ImmutableMap.copyOf(requireNonNull(parameters, "parameters is null"));

    this.storageFormat = requireNonNull(storageFormat, "storageFormat is null");
    this.bucketProperty = requireNonNull(bucketProperty, "bucketProperty is null");
    this.serdeParameters = requireNonNull(serdeParameters, "serdeParameters is null");
    this.externalLocation = requireNonNull(externalLocation, "externalLocation is null");
    if (tableType.equals(TableType.EXTERNAL_TABLE.name())) {
        checkArgument(externalLocation.isPresent(), "External location is required for external tables");
    }
    else {
        checkArgument(externalLocation.isEmpty(), "External location is only allowed for external tables");
    }

    this.viewOriginalText = requireNonNull(viewOriginalText, "viewOriginalText is null");
    this.viewExpandedText = requireNonNull(viewExpandedText, "viewExpandedText is null");
    this.columnStatistics = ImmutableMap.copyOf(requireNonNull(columnStatistics, "columnStatistics is null"));
    checkArgument(partitionColumns.isEmpty() || columnStatistics.isEmpty(), "column statistics cannot be set for partitioned table");
}
 
Example 29
Source Project: presto   Source File: TestingMetastoreObjects.java    License: Apache License 2.0 5 votes vote down vote up
public static io.prestosql.plugin.hive.metastore.Table getPrestoTestTable(String dbName)
{
    return io.prestosql.plugin.hive.metastore.Table.builder()
            .setDatabaseName(dbName)
            .setTableName("test-tbl" + generateRandom())
            .setOwner("owner")
            .setParameters(ImmutableMap.of())
            .setTableType(TableType.EXTERNAL_TABLE.name())
            .setDataColumns(ImmutableList.of(getPrestoTestColumn()))
            .setPartitionColumns(ImmutableList.of(getPrestoTestColumn()))
            .setViewOriginalText(Optional.of("originalText"))
            .setViewExpandedText(Optional.of("expandedText"))
            .withStorage(STORAGE_CONSUMER).build();
}
 
Example 30
Source Project: presto   Source File: InMemoryThriftMetastore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void createTable(HiveIdentity identity, Table table)
{
    TableType tableType = TableType.valueOf(table.getTableType());
    checkArgument(EnumSet.of(MANAGED_TABLE, EXTERNAL_TABLE, VIRTUAL_VIEW).contains(tableType), "Invalid table type: %s", tableType);

    if (tableType == VIRTUAL_VIEW) {
        checkArgument(table.getSd().getLocation() == null, "Storage location for view must be null");
    }
    else {
        File directory = new File(new Path(table.getSd().getLocation()).toUri());
        checkArgument(directory.exists(), "Table directory does not exist");
        if (tableType == MANAGED_TABLE) {
            checkArgument(isParentDir(directory, baseDirectory), "Table directory must be inside of the metastore base directory");
        }
    }

    SchemaTableName schemaTableName = new SchemaTableName(table.getDbName(), table.getTableName());
    Table tableCopy = table.deepCopy();

    if (relations.putIfAbsent(schemaTableName, tableCopy) != null) {
        throw new TableAlreadyExistsException(schemaTableName);
    }

    if (tableType == VIRTUAL_VIEW) {
        views.put(schemaTableName, tableCopy);
    }

    PrincipalPrivilegeSet privileges = table.getPrivileges();
    if (privileges != null) {
        throw new UnsupportedOperationException();
    }
}