Skip to content

Commit

Permalink
view: create node if doesn't exist
Browse files Browse the repository at this point in the history
  • Loading branch information
efiop committed Feb 3, 2023
1 parent 8c599df commit 04f6ab8
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/sqltrie/pygtrie.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,11 @@ def view(self, key=None):
if key is not None:
kwargs["prefix"] = key

for ikey, value in self._trie.iteritems(**kwargs):
ret[ikey[len(key) :]] = value
try:
for ikey, value in self._trie.iteritems(**kwargs):
ret[ikey[len(key) :]] = value
except KeyError:
pass

return ret

Expand Down
8 changes: 6 additions & 2 deletions src/sqltrie/sqlite/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,16 @@ def view( # type: ignore
return self

self.commit()
node = self._get_node(key)
try:
nid = self._get_node(key)["id"]
except KeyError:
nid = self._create_node(key)
self.commit()

trie = SQLiteTrie()
trie._path = self._path # pylint: disable=protected-access
trie._root_key = key # pylint: disable=protected-access
trie._root_id = node["id"] # pylint: disable=protected-access
trie._root_id = nid # pylint: disable=protected-access
return trie

def items(self, prefix=None, shallow=False):
Expand Down
14 changes: 14 additions & 0 deletions tests/test_sqltrie.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,17 @@ def test_open(tmp_path):

assert trie[("foo",)] == b"foo-value"
assert trie[("foo", "bar", "baz")] == b"baz-value"


@pytest.mark.parametrize("cls", [SQLiteTrie, PyGTrie])
def test_view(cls):
trie = cls()

view = trie.view(("a",))
assert not list(view.items())

view = trie.view(("a", "b"))
assert not list(view.items())

view = trie.view(("a", "b", "c"))
assert not list(view.items())

0 comments on commit 04f6ab8

Please sign in to comment.