Skip to content

Commit 063995b

Browse files
committed
Prepared validation for SparseVector order [skip ci]
1 parent 8be9673 commit 063995b

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

‎pgvector/sparsevec.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,11 @@ def _validate(self) -> None:
147147
if any(i < 0 or i >= self._dim for i in self._indices):
148148
raise ValueError('sparsevec index out of bounds')
149149

150+
def _validate_sorted(self) -> None:
151+
for i in range(len(self._indices) - 1):
152+
if self._indices[i] >= self._indices[i + 1]:
153+
raise ValueError('sparsevec indices must be in ascending order')
154+
150155
@classmethod
151156
def from_text(cls, value: str, /) -> SparseVector:
152157
elements, dim = value.split('/', 2)
@@ -182,6 +187,7 @@ def _from_parts(cls, dim: int, indices: list[int], values: list[float], /) -> Sp
182187
vec._values = values
183188
# TODO uncomment in 0.6.0
184189
# vec._validate()
190+
# vec._validate_sorted()
185191
return vec
186192

187193
@classmethod

‎tests/test_sparse_vector.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,16 @@ def test_from_text(self) -> None:
169169
assert np.array_equal(vec.to_numpy(), [1.5, 0, 2, 0, 3, 0])
170170
assert vec.to_text() == '{1:1.5,3:2.0,5:3.0}/6'
171171

172+
# TODO uncomment in 0.6.0
173+
# def test_from_text_unsorted(self) -> None:
174+
# with pytest.raises(ValueError, match='sparsevec indices must be in ascending order'):
175+
# SparseVector.from_text('{2:1,1:1}/3')
176+
177+
# TODO uncomment in 0.6.0
178+
# def test_from_text_duplicate(self) -> None:
179+
# with pytest.raises(ValueError, match='sparsevec indices must be in ascending order'):
180+
# SparseVector.from_text('{2:1,2:1}/3')
181+
172182
def test_from_binary(self) -> None:
173183
data = pack('>iii3i3f', 6, 3, 0, 0, 2, 4, 1.5, 2, 3)
174184
vec = SparseVector.from_binary(data)

0 commit comments

Comments
 (0)