Skip to content

Commit 4003693

Browse files
ankaneAryanRG
andcommitted
Prepared validation for SparseVector indexes - resolves #167 [skip ci]
Co-authored-by: AryanRG <aryanrganjoo@gmail.com>
1 parent 7329d8a commit 4003693

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

‎pgvector/sparsevec.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ def _from_dict(self, d: dict[int, float], dim: int) -> None:
101101
self._dim = int(dim)
102102
self._indices = [int(v[0]) for v in elements]
103103
self._values = [float(v[1]) for v in elements]
104+
# TODO uncomment in 0.6.0
105+
# self._validate()
104106

105107
def _from_sparse(self, arr: sparray | spmatrix, /) -> None:
106108
value: coo_array | coo_matrix = arr.tocoo(copy=False) # type: ignore
@@ -138,6 +140,10 @@ def _from_dense(self, value: list[float] | ndarray, /) -> None:
138140
self._indices = [i for i, v in enumerate(value) if v != 0]
139141
self._values = [float(value[i]) for i in self._indices]
140142

143+
def _validate(self):
144+
if any(i < 0 or i >= self._dim for i in self._indices):
145+
raise ValueError('sparsevec index out of bounds')
146+
141147
@classmethod
142148
def from_text(cls, value: str, /) -> SparseVector:
143149
elements, dim = value.split('/', 2)
@@ -171,6 +177,8 @@ def _from_parts(cls, dim: int, indices: list[int], values: list[float], /) -> Sp
171177
vec._dim = dim
172178
vec._indices = indices
173179
vec._values = values
180+
# TODO uncomment in 0.6.0
181+
# vec._validate()
174182
return vec
175183

176184
@classmethod

‎tests/test_sparse_vector.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,16 @@ def test_dict(self) -> None:
4545
def test_dict_empty(self) -> None:
4646
assert SparseVector({}, 0).to_list() == []
4747

48+
# TODO uncomment in 0.6.0
49+
# def test_dict_negative_index(self) -> None:
50+
# with pytest.raises(ValueError, match='sparsevec index out of bounds'):
51+
# SparseVector({-1: 1}, 3)
52+
53+
# TODO uncomment in 0.6.0
54+
# def test_dict_higher_index(self) -> None:
55+
# with pytest.raises(ValueError, match='sparsevec index out of bounds'):
56+
# SparseVector({3: 1}, 3)
57+
4858
def test_dict_no_dimensions(self) -> None:
4959
with pytest.raises(ValueError) as error:
5060
SparseVector({0: 1, 2: 2, 4: 3}) # type: ignore

0 commit comments

Comments
 (0)