From 49403d5e83e50510b70ee2847ba80fc84df1db2f Mon Sep 17 00:00:00 2001 From: Ruslan Kuprieiev Date: Sat, 10 Jun 2023 02:40:14 +0300 Subject: [PATCH] trie: introduce delete_node --- src/sqltrie/pygtrie.py | 3 +++ src/sqltrie/serialized.py | 3 +++ src/sqltrie/sqlite/sqlite.py | 20 ++++++++++---------- src/sqltrie/trie.py | 5 +++++ 4 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/sqltrie/pygtrie.py b/src/sqltrie/pygtrie.py index 660a2e5..572b1ca 100644 --- a/src/sqltrie/pygtrie.py +++ b/src/sqltrie/pygtrie.py @@ -51,6 +51,9 @@ def __len__(self): def has_node(self, key): return bool(self._trie.has_node(key)) + def delete_node(self, key): + raise NotImplementedError + def items(self, prefix=None, shallow=False): kwargs = {"shallow": shallow} if prefix is not None: diff --git a/src/sqltrie/serialized.py b/src/sqltrie/serialized.py index a964164..5c54c57 100644 --- a/src/sqltrie/serialized.py +++ b/src/sqltrie/serialized.py @@ -99,6 +99,9 @@ def diff(self, *args, **kwargs): def has_node(self, key): return self._trie.has_node(key) + def delete_node(self, key): + return self._trie.delete_node(key) + def shortest_prefix(self, key): sprefix = self._trie.shortest_prefix(key) if sprefix is None: diff --git a/src/sqltrie/sqlite/sqlite.py b/src/sqltrie/sqlite/sqlite.py index 9e48303..72fe453 100644 --- a/src/sqltrie/sqlite/sqlite.py +++ b/src/sqltrie/sqlite/sqlite.py @@ -149,16 +149,6 @@ def _get_children(self, key, limit=None): (node["id"],), ).fetchall() - def _delete_node(self, key): - node = self._get_node(key) - del self._ids[key] - self._conn.execute( - """ - DELETE FROM nodes WHERE id = ? - """, - (node["id"],), - ) - def __setitem__(self, key, value): pid = self._create_node(key[:-1]) @@ -290,6 +280,16 @@ def has_node(self, key: TrieKey) -> bool: except KeyError: return False + def delete_node(self, key: TrieKey): + node = self._get_node(key) + del self._ids[key] + self._conn.execute( + """ + DELETE FROM nodes WHERE id = ? + """, + (node["id"],), + ) + def ls( self, key: TrieKey, with_values: Optional[bool] = False ) -> Iterator[Union[TrieKey, TrieNode]]: diff --git a/src/sqltrie/trie.py b/src/sqltrie/trie.py index aab9ccd..ad93a3e 100644 --- a/src/sqltrie/trie.py +++ b/src/sqltrie/trie.py @@ -85,6 +85,11 @@ def view(self, key: Optional[TrieKey] = None) -> "AbstractTrie": def has_node(self, key: TrieKey) -> bool: pass + @abstractmethod + def delete_node(self, key: TrieKey) -> bool: + # NOTE: this will leave orphans down the tree + pass + @abstractmethod def prefixes(self, key: TrieKey) -> Iterator[TrieStep]: pass