Skip to content

Commit 4e5adc7

Browse files
committed
Improved from_string function for SparseVector
1 parent 3a2fb74 commit 4e5adc7

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

include/pgvector/pqxx.hpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,15 @@ template <> struct string_traits<pgvector::SparseVector> {
149149
throw conversion_error("Malformed sparsevec literal");
150150
}
151151

152-
indices.push_back(std::stoi(substr.substr(0, ne)) - 1);
153-
values.push_back(std::stof(substr.substr(ne + 1)));
152+
int index = std::stoi(substr.substr(0, ne));
153+
float value = std::stof(substr.substr(ne + 1));
154+
155+
if (index < 1) {
156+
throw conversion_error("Malformed sparsevec literal");
157+
}
158+
159+
indices.push_back(index - 1);
160+
values.push_back(value);
154161
}
155162
}
156163

test/pqxx_test.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,20 @@ void test_sparsevec_from_string() {
263263
assert(std::string_view(e.what()) == "Malformed sparsevec literal");
264264
}
265265

266+
try {
267+
auto unused = pqxx::from_string<pgvector::SparseVector>("{0:1}/1");
268+
assert(false);
269+
} catch (const pqxx::conversion_error& e) {
270+
assert(std::string_view(e.what()) == "Malformed sparsevec literal");
271+
}
272+
273+
try {
274+
auto unused = pqxx::from_string<pgvector::SparseVector>("{-2147483648:1}/1");
275+
assert(false);
276+
} catch (const pqxx::conversion_error& e) {
277+
assert(std::string_view(e.what()) == "Malformed sparsevec literal");
278+
}
279+
266280
// TODO change to pqxx::conversion_error
267281
try {
268282
auto unused = pqxx::from_string<pgvector::SparseVector>("{a:1}/1");

0 commit comments

Comments
 (0)