2023-09-13 17:55:27 +08:00
|
|
|
# define a relation store class
|
2023-09-14 16:03:56 +08:00
|
|
|
import sqlite3
|
|
|
|
|
import os
|
|
|
|
|
import logging
|
2023-09-13 17:55:27 +08:00
|
|
|
from .object_id import ObjectID
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ObjectRelationStore:
|
|
|
|
|
def __init__(self, root_dir: str):
|
2023-09-14 16:03:56 +08:00
|
|
|
if not os.path.exists(root_dir):
|
|
|
|
|
os.makedirs(root_dir)
|
|
|
|
|
file = os.path.join(root_dir, "relationships.db")
|
|
|
|
|
logging.info(f"will init chunk tracker, db={file}")
|
|
|
|
|
|
|
|
|
|
self.conn = sqlite3.connect(file)
|
|
|
|
|
self.cursor = self.conn.cursor()
|
|
|
|
|
self.cursor.execute(
|
|
|
|
|
"""
|
|
|
|
|
CREATE TABLE IF NOT EXISTS relationships (
|
|
|
|
|
id TEXT NOT NULL,
|
|
|
|
|
parent TEXT NOT NULL,
|
|
|
|
|
PRIMARY KEY(id, parent)
|
|
|
|
|
)
|
|
|
|
|
"""
|
|
|
|
|
)
|
|
|
|
|
self.conn.commit()
|
2023-09-13 17:55:27 +08:00
|
|
|
|
|
|
|
|
def add_relation(self, object: ObjectID, parent: ObjectID):
|
2023-09-14 16:03:56 +08:00
|
|
|
self.cursor.execute(
|
|
|
|
|
"""
|
|
|
|
|
INSERT INTO relationships (id, parent)
|
|
|
|
|
VALUES (?, ?, ?, ?, ?)
|
|
|
|
|
""",
|
|
|
|
|
(
|
|
|
|
|
str(object),
|
|
|
|
|
str(parent),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
self.conn.commit()
|
2023-09-13 17:55:27 +08:00
|
|
|
|
|
|
|
|
def get_related_objects(self, object: ObjectID) -> [ObjectID]:
|
2023-09-14 16:03:56 +08:00
|
|
|
parents = []
|
|
|
|
|
cur = object
|
|
|
|
|
while True:
|
|
|
|
|
self.cursor.execute(
|
|
|
|
|
"""
|
|
|
|
|
SELECT id, parent FROM relationships WHERE id = ?
|
|
|
|
|
""",
|
|
|
|
|
(str(cur),),
|
|
|
|
|
)
|
|
|
|
|
parent = self.cursor.fetchone()
|
|
|
|
|
if parent is None:
|
|
|
|
|
break
|
|
|
|
|
parents.append(parent)
|
|
|
|
|
cur = parent
|
2023-09-13 17:55:27 +08:00
|
|
|
|
|
|
|
|
def delete_relation(self, object_id: ObjectID) -> [ObjectID]:
|
2023-09-14 16:03:56 +08:00
|
|
|
self.cursor.execute(
|
|
|
|
|
"""
|
|
|
|
|
DELETE FROM relationships WHERE id = ?
|
|
|
|
|
""",
|
|
|
|
|
(str(object_id),),
|
|
|
|
|
)
|
|
|
|
|
self.conn.commit()
|