Skip to content

hive

HiveCatalog

Bases: Catalog

Source code in pyiceberg/catalog/hive.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
class HiveCatalog(Catalog):
    _client: _HiveClient

    def __init__(self, name: str, **properties: str):
        super().__init__(name, **properties)
        self._client = _HiveClient(properties["uri"])

    def _convert_hive_into_iceberg(self, table: HiveTable, io: FileIO) -> Table:
        properties: Dict[str, str] = table.parameters
        if TABLE_TYPE not in properties:
            raise NoSuchTableError(f"Property table_type missing, could not determine type: {table.dbName}.{table.tableName}")

        table_type = properties[TABLE_TYPE]
        if table_type.lower() != ICEBERG:
            raise NoSuchIcebergTableError(
                f"Property table_type is {table_type}, expected {ICEBERG}: {table.dbName}.{table.tableName}"
            )

        if prop_metadata_location := properties.get(METADATA_LOCATION):
            metadata_location = prop_metadata_location
        else:
            raise NoSuchTableError(f"Table property {METADATA_LOCATION} is missing")

        file = io.new_input(metadata_location)
        metadata = FromInputFile.table_metadata(file)
        return Table(
            identifier=(self.name, table.dbName, table.tableName),
            metadata=metadata,
            metadata_location=metadata_location,
            io=self._load_file_io(metadata.properties, metadata_location),
            catalog=self,
        )

    def create_table(
        self,
        identifier: Union[str, Identifier],
        schema: Union[Schema, "pa.Schema"],
        location: Optional[str] = None,
        partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
        sort_order: SortOrder = UNSORTED_SORT_ORDER,
        properties: Properties = EMPTY_DICT,
    ) -> Table:
        """Create a table.

        Args:
            identifier: Table identifier.
            schema: Table's schema.
            location: Location for the table. Optional Argument.
            partition_spec: PartitionSpec for the table.
            sort_order: SortOrder for the table.
            properties: Table properties that can be a string based dictionary.

        Returns:
            Table: the created table instance.

        Raises:
            AlreadyExistsError: If a table with the name already exists.
            ValueError: If the identifier is invalid.
        """
        schema: Schema = self._convert_schema_if_needed(schema)  # type: ignore

        properties = {**DEFAULT_PROPERTIES, **properties}
        database_name, table_name = self.identifier_to_database_and_table(identifier)
        current_time_millis = int(time.time() * 1000)

        location = self._resolve_table_location(location, database_name, table_name)

        metadata_location = self._get_metadata_location(location=location)
        metadata = new_table_metadata(
            location=location,
            schema=schema,
            partition_spec=partition_spec,
            sort_order=sort_order,
            properties=properties,
        )
        io = load_file_io({**self.properties, **properties}, location=location)
        self._write_metadata(metadata, io, metadata_location)

        tbl = HiveTable(
            dbName=database_name,
            tableName=table_name,
            owner=properties[OWNER] if properties and OWNER in properties else getpass.getuser(),
            createTime=current_time_millis // 1000,
            lastAccessTime=current_time_millis // 1000,
            sd=_construct_hive_storage_descriptor(schema, location),
            tableType=EXTERNAL_TABLE,
            parameters=_construct_parameters(metadata_location),
        )
        try:
            with self._client as open_client:
                open_client.create_table(tbl)
                hive_table = open_client.get_table(dbname=database_name, tbl_name=table_name)
        except AlreadyExistsException as e:
            raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e

        return self._convert_hive_into_iceberg(hive_table, io)

    def register_table(self, identifier: Union[str, Identifier], metadata_location: str) -> Table:
        """Register a new table using existing metadata.

        Args:
            identifier Union[str, Identifier]: Table identifier for the table
            metadata_location str: The location to the metadata

        Returns:
            Table: The newly registered table

        Raises:
            TableAlreadyExistsError: If the table already exists
        """
        raise NotImplementedError

    def _create_lock_request(self, database_name: str, table_name: str) -> LockRequest:
        lock_component: LockComponent = LockComponent(
            level=LockLevel.TABLE, type=LockType.EXCLUSIVE, dbname=database_name, tablename=table_name, isTransactional=True
        )

        lock_request: LockRequest = LockRequest(component=[lock_component], user=getpass.getuser(), hostname=socket.gethostname())

        return lock_request

    def _commit_table(self, table_request: CommitTableRequest) -> CommitTableResponse:
        """Update the table.

        Args:
            table_request (CommitTableRequest): The table requests to be carried out.

        Returns:
            CommitTableResponse: The updated metadata.

        Raises:
            NoSuchTableError: If a table with the given identifier does not exist.
        """
        identifier_tuple = self.identifier_to_tuple_without_catalog(
            tuple(table_request.identifier.namespace.root + [table_request.identifier.name])
        )
        current_table = self.load_table(identifier_tuple)
        database_name, table_name = self.identifier_to_database_and_table(identifier_tuple, NoSuchTableError)
        base_metadata = current_table.metadata
        for requirement in table_request.requirements:
            requirement.validate(base_metadata)

        updated_metadata = update_table_metadata(base_metadata, table_request.updates)
        if updated_metadata == base_metadata:
            # no changes, do nothing
            return CommitTableResponse(metadata=base_metadata, metadata_location=current_table.metadata_location)

        # write new metadata
        new_metadata_version = self._parse_metadata_version(current_table.metadata_location) + 1
        new_metadata_location = self._get_metadata_location(current_table.metadata.location, new_metadata_version)
        self._write_metadata(updated_metadata, current_table.io, new_metadata_location)

        # commit to hive
        # https://github.com/apache/hive/blob/master/standalone-metastore/metastore-common/src/main/thrift/hive_metastore.thrift#L1232
        with self._client as open_client:
            lock: LockResponse = open_client.lock(self._create_lock_request(database_name, table_name))

            try:
                if lock.state != LockState.ACQUIRED:
                    raise CommitFailedException(f"Failed to acquire lock for {table_request.identifier}, state: {lock.state}")

                tbl = open_client.get_table(dbname=database_name, tbl_name=table_name)
                tbl.parameters = _construct_parameters(
                    metadata_location=new_metadata_location, previous_metadata_location=current_table.metadata_location
                )
                open_client.alter_table(dbname=database_name, tbl_name=table_name, new_tbl=tbl)
            except NoSuchObjectException as e:
                raise NoSuchTableError(f"Table does not exist: {table_name}") from e
            finally:
                open_client.unlock(UnlockRequest(lockid=lock.lockid))

        return CommitTableResponse(metadata=updated_metadata, metadata_location=new_metadata_location)

    def load_table(self, identifier: Union[str, Identifier]) -> Table:
        """Load the table's metadata and return the table instance.

        You can also use this method to check for table existence using 'try catalog.table() except TableNotFoundError'.
        Note: This method doesn't scan data stored in the table.

        Args:
            identifier: Table identifier.

        Returns:
            Table: the table instance with its metadata.

        Raises:
            NoSuchTableError: If a table with the name does not exist, or the identifier is invalid.
        """
        identifier_tuple = self.identifier_to_tuple_without_catalog(identifier)
        database_name, table_name = self.identifier_to_database_and_table(identifier_tuple, NoSuchTableError)
        try:
            with self._client as open_client:
                hive_table = open_client.get_table(dbname=database_name, tbl_name=table_name)
        except NoSuchObjectException as e:
            raise NoSuchTableError(f"Table does not exists: {table_name}") from e

        io = load_file_io({**self.properties, **hive_table.parameters}, hive_table.sd.location)
        return self._convert_hive_into_iceberg(hive_table, io)

    def drop_table(self, identifier: Union[str, Identifier]) -> None:
        """Drop a table.

        Args:
            identifier: Table identifier.

        Raises:
            NoSuchTableError: If a table with the name does not exist, or the identifier is invalid.
        """
        identifier_tuple = self.identifier_to_tuple_without_catalog(identifier)
        database_name, table_name = self.identifier_to_database_and_table(identifier_tuple, NoSuchTableError)
        try:
            with self._client as open_client:
                open_client.drop_table(dbname=database_name, name=table_name, deleteData=False)
        except NoSuchObjectException as e:
            # When the namespace doesn't exist, it throws the same error
            raise NoSuchTableError(f"Table does not exists: {table_name}") from e

    def purge_table(self, identifier: Union[str, Identifier]) -> None:
        # This requires to traverse the reachability set, and drop all the data files.
        raise NotImplementedError("Not yet implemented")

    def rename_table(self, from_identifier: Union[str, Identifier], to_identifier: Union[str, Identifier]) -> Table:
        """Rename a fully classified table name.

        Args:
            from_identifier: Existing table identifier.
            to_identifier: New table identifier.

        Returns:
            Table: the updated table instance with its metadata.

        Raises:
            ValueError: When from table identifier is invalid.
            NoSuchTableError: When a table with the name does not exist.
            NoSuchNamespaceError: When the destination namespace doesn't exist.
        """
        from_identifier_tuple = self.identifier_to_tuple_without_catalog(from_identifier)
        from_database_name, from_table_name = self.identifier_to_database_and_table(from_identifier_tuple, NoSuchTableError)
        to_database_name, to_table_name = self.identifier_to_database_and_table(to_identifier)
        try:
            with self._client as open_client:
                tbl = open_client.get_table(dbname=from_database_name, tbl_name=from_table_name)
                tbl.dbName = to_database_name
                tbl.tableName = to_table_name
                open_client.alter_table(dbname=from_database_name, tbl_name=from_table_name, new_tbl=tbl)
        except NoSuchObjectException as e:
            raise NoSuchTableError(f"Table does not exist: {from_table_name}") from e
        except InvalidOperationException as e:
            raise NoSuchNamespaceError(f"Database does not exists: {to_database_name}") from e
        return self.load_table(to_identifier)

    def create_namespace(self, namespace: Union[str, Identifier], properties: Properties = EMPTY_DICT) -> None:
        """Create a namespace in the catalog.

        Args:
            namespace: Namespace identifier.
            properties: A string dictionary of properties for the given namespace.

        Raises:
            ValueError: If the identifier is invalid.
            AlreadyExistsError: If a namespace with the given name already exists.
        """
        database_name = self.identifier_to_database(namespace)
        hive_database = HiveDatabase(name=database_name, parameters=properties)

        try:
            with self._client as open_client:
                open_client.create_database(_annotate_namespace(hive_database, properties))
        except AlreadyExistsException as e:
            raise NamespaceAlreadyExistsError(f"Database {database_name} already exists") from e

    def drop_namespace(self, namespace: Union[str, Identifier]) -> None:
        """Drop a namespace.

        Args:
            namespace: Namespace identifier.

        Raises:
            NoSuchNamespaceError: If a namespace with the given name does not exist, or the identifier is invalid.
            NamespaceNotEmptyError: If the namespace is not empty.
        """
        database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
        try:
            with self._client as open_client:
                open_client.drop_database(database_name, deleteData=False, cascade=False)
        except InvalidOperationException as e:
            raise NamespaceNotEmptyError(f"Database {database_name} is not empty") from e
        except MetaException as e:
            raise NoSuchNamespaceError(f"Database does not exists: {database_name}") from e

    def list_tables(self, namespace: Union[str, Identifier]) -> List[Identifier]:
        """List tables under the given namespace in the catalog (including non-Iceberg tables).

        When the database doesn't exist, it will just return an empty list.

        Args:
            namespace: Database to list.

        Returns:
            List[Identifier]: list of table identifiers.

        Raises:
            NoSuchNamespaceError: If a namespace with the given name does not exist, or the identifier is invalid.
        """
        database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
        with self._client as open_client:
            return [(database_name, table_name) for table_name in open_client.get_all_tables(db_name=database_name)]

    def list_namespaces(self, namespace: Union[str, Identifier] = ()) -> List[Identifier]:
        """List namespaces from the given namespace. If not given, list top-level namespaces from the catalog.

        Returns:
            List[Identifier]: a List of namespace identifiers.
        """
        # Hierarchical namespace is not supported. Return an empty list
        if namespace:
            return []

        with self._client as open_client:
            return list(map(self.identifier_to_tuple, open_client.get_all_databases()))

    def load_namespace_properties(self, namespace: Union[str, Identifier]) -> Properties:
        """Get properties for a namespace.

        Args:
            namespace: Namespace identifier.

        Returns:
            Properties: Properties for the given namespace.

        Raises:
            NoSuchNamespaceError: If a namespace with the given name does not exist, or identifier is invalid.
        """
        database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
        try:
            with self._client as open_client:
                database = open_client.get_database(name=database_name)
                properties = database.parameters
                properties[LOCATION] = database.locationUri
                if comment := database.description:
                    properties[COMMENT] = comment
                return properties
        except NoSuchObjectException as e:
            raise NoSuchNamespaceError(f"Database does not exists: {database_name}") from e

    def update_namespace_properties(
        self, namespace: Union[str, Identifier], removals: Optional[Set[str]] = None, updates: Properties = EMPTY_DICT
    ) -> PropertiesUpdateSummary:
        """Remove provided property keys and update properties for a namespace.

        Args:
            namespace: Namespace identifier.
            removals: Set of property keys that need to be removed. Optional Argument.
            updates: Properties to be updated for the given namespace.

        Raises:
            NoSuchNamespaceError: If a namespace with the given name does not exist
            ValueError: If removals and updates have overlapping keys.
        """
        self._check_for_overlap(updates=updates, removals=removals)
        database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
        with self._client as open_client:
            try:
                database = open_client.get_database(database_name)
                parameters = database.parameters
            except NoSuchObjectException as e:
                raise NoSuchNamespaceError(f"Database does not exists: {database_name}") from e

            removed: Set[str] = set()
            updated: Set[str] = set()

            if removals:
                for key in removals:
                    if key in parameters:
                        parameters[key] = None
                        removed.add(key)
            if updates:
                for key, value in updates.items():
                    parameters[key] = value
                    updated.add(key)

            open_client.alter_database(database_name, _annotate_namespace(database, parameters))

        expected_to_change = (removals or set()).difference(removed)

        return PropertiesUpdateSummary(removed=list(removed or []), updated=list(updated or []), missing=list(expected_to_change))

create_namespace(namespace, properties=EMPTY_DICT)

Create a namespace in the catalog.

Parameters:

Name Type Description Default
namespace Union[str, Identifier]

Namespace identifier.

required
properties Properties

A string dictionary of properties for the given namespace.

EMPTY_DICT

Raises:

Type Description
ValueError

If the identifier is invalid.

AlreadyExistsError

If a namespace with the given name already exists.

Source code in pyiceberg/catalog/hive.py
def create_namespace(self, namespace: Union[str, Identifier], properties: Properties = EMPTY_DICT) -> None:
    """Create a namespace in the catalog.

    Args:
        namespace: Namespace identifier.
        properties: A string dictionary of properties for the given namespace.

    Raises:
        ValueError: If the identifier is invalid.
        AlreadyExistsError: If a namespace with the given name already exists.
    """
    database_name = self.identifier_to_database(namespace)
    hive_database = HiveDatabase(name=database_name, parameters=properties)

    try:
        with self._client as open_client:
            open_client.create_database(_annotate_namespace(hive_database, properties))
    except AlreadyExistsException as e:
        raise NamespaceAlreadyExistsError(f"Database {database_name} already exists") from e

create_table(identifier, schema, location=None, partition_spec=UNPARTITIONED_PARTITION_SPEC, sort_order=UNSORTED_SORT_ORDER, properties=EMPTY_DICT)

Create a table.

Parameters:

Name Type Description Default
identifier Union[str, Identifier]

Table identifier.

required
schema Union[Schema, Schema]

Table's schema.

required
location Optional[str]

Location for the table. Optional Argument.

None
partition_spec PartitionSpec

PartitionSpec for the table.

UNPARTITIONED_PARTITION_SPEC
sort_order SortOrder

SortOrder for the table.

UNSORTED_SORT_ORDER
properties Properties

Table properties that can be a string based dictionary.

EMPTY_DICT

Returns:

Name Type Description
Table Table

the created table instance.

Raises:

Type Description
AlreadyExistsError

If a table with the name already exists.

ValueError

If the identifier is invalid.

Source code in pyiceberg/catalog/hive.py
def create_table(
    self,
    identifier: Union[str, Identifier],
    schema: Union[Schema, "pa.Schema"],
    location: Optional[str] = None,
    partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
    sort_order: SortOrder = UNSORTED_SORT_ORDER,
    properties: Properties = EMPTY_DICT,
) -> Table:
    """Create a table.

    Args:
        identifier: Table identifier.
        schema: Table's schema.
        location: Location for the table. Optional Argument.
        partition_spec: PartitionSpec for the table.
        sort_order: SortOrder for the table.
        properties: Table properties that can be a string based dictionary.

    Returns:
        Table: the created table instance.

    Raises:
        AlreadyExistsError: If a table with the name already exists.
        ValueError: If the identifier is invalid.
    """
    schema: Schema = self._convert_schema_if_needed(schema)  # type: ignore

    properties = {**DEFAULT_PROPERTIES, **properties}
    database_name, table_name = self.identifier_to_database_and_table(identifier)
    current_time_millis = int(time.time() * 1000)

    location = self._resolve_table_location(location, database_name, table_name)

    metadata_location = self._get_metadata_location(location=location)
    metadata = new_table_metadata(
        location=location,
        schema=schema,
        partition_spec=partition_spec,
        sort_order=sort_order,
        properties=properties,
    )
    io = load_file_io({**self.properties, **properties}, location=location)
    self._write_metadata(metadata, io, metadata_location)

    tbl = HiveTable(
        dbName=database_name,
        tableName=table_name,
        owner=properties[OWNER] if properties and OWNER in properties else getpass.getuser(),
        createTime=current_time_millis // 1000,
        lastAccessTime=current_time_millis // 1000,
        sd=_construct_hive_storage_descriptor(schema, location),
        tableType=EXTERNAL_TABLE,
        parameters=_construct_parameters(metadata_location),
    )
    try:
        with self._client as open_client:
            open_client.create_table(tbl)
            hive_table = open_client.get_table(dbname=database_name, tbl_name=table_name)
    except AlreadyExistsException as e:
        raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e

    return self._convert_hive_into_iceberg(hive_table, io)

drop_namespace(namespace)

Drop a namespace.

Parameters:

Name Type Description Default
namespace Union[str, Identifier]

Namespace identifier.

required

Raises:

Type Description
NoSuchNamespaceError

If a namespace with the given name does not exist, or the identifier is invalid.

NamespaceNotEmptyError

If the namespace is not empty.

Source code in pyiceberg/catalog/hive.py
def drop_namespace(self, namespace: Union[str, Identifier]) -> None:
    """Drop a namespace.

    Args:
        namespace: Namespace identifier.

    Raises:
        NoSuchNamespaceError: If a namespace with the given name does not exist, or the identifier is invalid.
        NamespaceNotEmptyError: If the namespace is not empty.
    """
    database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
    try:
        with self._client as open_client:
            open_client.drop_database(database_name, deleteData=False, cascade=False)
    except InvalidOperationException as e:
        raise NamespaceNotEmptyError(f"Database {database_name} is not empty") from e
    except MetaException as e:
        raise NoSuchNamespaceError(f"Database does not exists: {database_name}") from e

drop_table(identifier)

Drop a table.

Parameters:

Name Type Description Default
identifier Union[str, Identifier]

Table identifier.

required

Raises:

Type Description
NoSuchTableError

If a table with the name does not exist, or the identifier is invalid.

Source code in pyiceberg/catalog/hive.py
def drop_table(self, identifier: Union[str, Identifier]) -> None:
    """Drop a table.

    Args:
        identifier: Table identifier.

    Raises:
        NoSuchTableError: If a table with the name does not exist, or the identifier is invalid.
    """
    identifier_tuple = self.identifier_to_tuple_without_catalog(identifier)
    database_name, table_name = self.identifier_to_database_and_table(identifier_tuple, NoSuchTableError)
    try:
        with self._client as open_client:
            open_client.drop_table(dbname=database_name, name=table_name, deleteData=False)
    except NoSuchObjectException as e:
        # When the namespace doesn't exist, it throws the same error
        raise NoSuchTableError(f"Table does not exists: {table_name}") from e

list_namespaces(namespace=())

List namespaces from the given namespace. If not given, list top-level namespaces from the catalog.

Returns:

Type Description
List[Identifier]

List[Identifier]: a List of namespace identifiers.

Source code in pyiceberg/catalog/hive.py
def list_namespaces(self, namespace: Union[str, Identifier] = ()) -> List[Identifier]:
    """List namespaces from the given namespace. If not given, list top-level namespaces from the catalog.

    Returns:
        List[Identifier]: a List of namespace identifiers.
    """
    # Hierarchical namespace is not supported. Return an empty list
    if namespace:
        return []

    with self._client as open_client:
        return list(map(self.identifier_to_tuple, open_client.get_all_databases()))

list_tables(namespace)

List tables under the given namespace in the catalog (including non-Iceberg tables).

When the database doesn't exist, it will just return an empty list.

Parameters:

Name Type Description Default
namespace Union[str, Identifier]

Database to list.

required

Returns:

Type Description
List[Identifier]

List[Identifier]: list of table identifiers.

Raises:

Type Description
NoSuchNamespaceError

If a namespace with the given name does not exist, or the identifier is invalid.

Source code in pyiceberg/catalog/hive.py
def list_tables(self, namespace: Union[str, Identifier]) -> List[Identifier]:
    """List tables under the given namespace in the catalog (including non-Iceberg tables).

    When the database doesn't exist, it will just return an empty list.

    Args:
        namespace: Database to list.

    Returns:
        List[Identifier]: list of table identifiers.

    Raises:
        NoSuchNamespaceError: If a namespace with the given name does not exist, or the identifier is invalid.
    """
    database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
    with self._client as open_client:
        return [(database_name, table_name) for table_name in open_client.get_all_tables(db_name=database_name)]

load_namespace_properties(namespace)

Get properties for a namespace.

Parameters:

Name Type Description Default
namespace Union[str, Identifier]

Namespace identifier.

required

Returns:

Name Type Description
Properties Properties

Properties for the given namespace.

Raises:

Type Description
NoSuchNamespaceError

If a namespace with the given name does not exist, or identifier is invalid.

Source code in pyiceberg/catalog/hive.py
def load_namespace_properties(self, namespace: Union[str, Identifier]) -> Properties:
    """Get properties for a namespace.

    Args:
        namespace: Namespace identifier.

    Returns:
        Properties: Properties for the given namespace.

    Raises:
        NoSuchNamespaceError: If a namespace with the given name does not exist, or identifier is invalid.
    """
    database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
    try:
        with self._client as open_client:
            database = open_client.get_database(name=database_name)
            properties = database.parameters
            properties[LOCATION] = database.locationUri
            if comment := database.description:
                properties[COMMENT] = comment
            return properties
    except NoSuchObjectException as e:
        raise NoSuchNamespaceError(f"Database does not exists: {database_name}") from e

load_table(identifier)

Load the table's metadata and return the table instance.

You can also use this method to check for table existence using 'try catalog.table() except TableNotFoundError'. Note: This method doesn't scan data stored in the table.

Parameters:

Name Type Description Default
identifier Union[str, Identifier]

Table identifier.

required

Returns:

Name Type Description
Table Table

the table instance with its metadata.

Raises:

Type Description
NoSuchTableError

If a table with the name does not exist, or the identifier is invalid.

Source code in pyiceberg/catalog/hive.py
def load_table(self, identifier: Union[str, Identifier]) -> Table:
    """Load the table's metadata and return the table instance.

    You can also use this method to check for table existence using 'try catalog.table() except TableNotFoundError'.
    Note: This method doesn't scan data stored in the table.

    Args:
        identifier: Table identifier.

    Returns:
        Table: the table instance with its metadata.

    Raises:
        NoSuchTableError: If a table with the name does not exist, or the identifier is invalid.
    """
    identifier_tuple = self.identifier_to_tuple_without_catalog(identifier)
    database_name, table_name = self.identifier_to_database_and_table(identifier_tuple, NoSuchTableError)
    try:
        with self._client as open_client:
            hive_table = open_client.get_table(dbname=database_name, tbl_name=table_name)
    except NoSuchObjectException as e:
        raise NoSuchTableError(f"Table does not exists: {table_name}") from e

    io = load_file_io({**self.properties, **hive_table.parameters}, hive_table.sd.location)
    return self._convert_hive_into_iceberg(hive_table, io)

register_table(identifier, metadata_location)

Register a new table using existing metadata.

Parameters:

Name Type Description Default
identifier Union[str, Identifier]

Table identifier for the table

required
metadata_location str

The location to the metadata

required

Returns:

Name Type Description
Table Table

The newly registered table

Raises:

Type Description
TableAlreadyExistsError

If the table already exists

Source code in pyiceberg/catalog/hive.py
def register_table(self, identifier: Union[str, Identifier], metadata_location: str) -> Table:
    """Register a new table using existing metadata.

    Args:
        identifier Union[str, Identifier]: Table identifier for the table
        metadata_location str: The location to the metadata

    Returns:
        Table: The newly registered table

    Raises:
        TableAlreadyExistsError: If the table already exists
    """
    raise NotImplementedError

rename_table(from_identifier, to_identifier)

Rename a fully classified table name.

Parameters:

Name Type Description Default
from_identifier Union[str, Identifier]

Existing table identifier.

required
to_identifier Union[str, Identifier]

New table identifier.

required

Returns:

Name Type Description
Table Table

the updated table instance with its metadata.

Raises:

Type Description
ValueError

When from table identifier is invalid.

NoSuchTableError

When a table with the name does not exist.

NoSuchNamespaceError

When the destination namespace doesn't exist.

Source code in pyiceberg/catalog/hive.py
def rename_table(self, from_identifier: Union[str, Identifier], to_identifier: Union[str, Identifier]) -> Table:
    """Rename a fully classified table name.

    Args:
        from_identifier: Existing table identifier.
        to_identifier: New table identifier.

    Returns:
        Table: the updated table instance with its metadata.

    Raises:
        ValueError: When from table identifier is invalid.
        NoSuchTableError: When a table with the name does not exist.
        NoSuchNamespaceError: When the destination namespace doesn't exist.
    """
    from_identifier_tuple = self.identifier_to_tuple_without_catalog(from_identifier)
    from_database_name, from_table_name = self.identifier_to_database_and_table(from_identifier_tuple, NoSuchTableError)
    to_database_name, to_table_name = self.identifier_to_database_and_table(to_identifier)
    try:
        with self._client as open_client:
            tbl = open_client.get_table(dbname=from_database_name, tbl_name=from_table_name)
            tbl.dbName = to_database_name
            tbl.tableName = to_table_name
            open_client.alter_table(dbname=from_database_name, tbl_name=from_table_name, new_tbl=tbl)
    except NoSuchObjectException as e:
        raise NoSuchTableError(f"Table does not exist: {from_table_name}") from e
    except InvalidOperationException as e:
        raise NoSuchNamespaceError(f"Database does not exists: {to_database_name}") from e
    return self.load_table(to_identifier)

update_namespace_properties(namespace, removals=None, updates=EMPTY_DICT)

Remove provided property keys and update properties for a namespace.

Parameters:

Name Type Description Default
namespace Union[str, Identifier]

Namespace identifier.

required
removals Optional[Set[str]]

Set of property keys that need to be removed. Optional Argument.

None
updates Properties

Properties to be updated for the given namespace.

EMPTY_DICT

Raises:

Type Description
NoSuchNamespaceError

If a namespace with the given name does not exist

ValueError

If removals and updates have overlapping keys.

Source code in pyiceberg/catalog/hive.py
def update_namespace_properties(
    self, namespace: Union[str, Identifier], removals: Optional[Set[str]] = None, updates: Properties = EMPTY_DICT
) -> PropertiesUpdateSummary:
    """Remove provided property keys and update properties for a namespace.

    Args:
        namespace: Namespace identifier.
        removals: Set of property keys that need to be removed. Optional Argument.
        updates: Properties to be updated for the given namespace.

    Raises:
        NoSuchNamespaceError: If a namespace with the given name does not exist
        ValueError: If removals and updates have overlapping keys.
    """
    self._check_for_overlap(updates=updates, removals=removals)
    database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
    with self._client as open_client:
        try:
            database = open_client.get_database(database_name)
            parameters = database.parameters
        except NoSuchObjectException as e:
            raise NoSuchNamespaceError(f"Database does not exists: {database_name}") from e

        removed: Set[str] = set()
        updated: Set[str] = set()

        if removals:
            for key in removals:
                if key in parameters:
                    parameters[key] = None
                    removed.add(key)
        if updates:
            for key, value in updates.items():
                parameters[key] = value
                updated.add(key)

        open_client.alter_database(database_name, _annotate_namespace(database, parameters))

    expected_to_change = (removals or set()).difference(removed)

    return PropertiesUpdateSummary(removed=list(removed or []), updated=list(updated or []), missing=list(expected_to_change))