Skip to content

Commit f649f73

Browse files
committed
Add client.clean_space() method
1 parent 7598138 commit f649f73

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

fairgraph/client.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,12 +421,15 @@ def replace_instance(self, instance_id: str, data: JsonLdDocument) -> JsonLdDocu
421421
error_context = f"replace_instance(data={data}, instance_id={instance_id})"
422422
return self._check_response(response, error_context=error_context).data
423423

424-
def delete_instance(self, instance_id: str, ignore_not_found: bool = True):
424+
def delete_instance(self, instance_id: str, ignore_not_found: bool = True, ignore_errors: bool = True):
425425
"""
426426
Delete a KG instance.
427427
"""
428428
response = self._kg_client.instances.delete(instance_id)
429429
# response is None if no errors
430+
if response: # error
431+
if not ignore_errors:
432+
raise Exception(response.message)
430433
return response
431434

432435
def uri_from_uuid(self, uuid: str) -> str:
@@ -628,6 +631,32 @@ def space_info(self, space_name: str, scope: str = "released"):
628631
response[cls] = item.occurrences
629632
return response
630633

634+
def clean_space(self, space_name):
635+
"""Delete all instances from a given space."""
636+
# todo: check for released instances, they must be unreleased
637+
# before deletion.
638+
space_info = self.space_info(space_name, scope="in progress")
639+
if sum(space_info.values()) > 0:
640+
print(f"The space '{space_name}' contains the following instances:\n")
641+
for cls, count in space_info.items():
642+
if count > 0:
643+
print(cls.__name__, count)
644+
response = input("\nAre you sure you want to delete them? ")
645+
if response not in ("y", "Y", "yes", "YES"):
646+
return
647+
for cls, count in space_info.items():
648+
if count > 0 and hasattr(cls, "list"): # exclude embedded metadata instances
649+
print(f"Deleting {cls.__name__} instances", end="")
650+
instances = cls.list(self, scope="in progress", space=space_name)
651+
assert len(instances) <= count
652+
for instance in instances:
653+
assert instance.space == space_name
654+
print(".", end="")
655+
instance.delete(self, ignore_errors=False)
656+
print()
657+
else:
658+
print(f"The space '{space_name}' is already clean")
659+
631660
def is_released(self, uri: str, with_children: bool = False) -> bool:
632661
"""
633662
Release status of a KG instance identified by its URI.

0 commit comments

Comments
 (0)