@@ -121,47 +121,53 @@ template <> struct string_traits<pgvector::SparseVector> {
121121 static constexpr bool converts_from_string{true };
122122
123123 static pgvector::SparseVector from_string (std::string_view text) {
124- if (text.size () < 4 || text.front () != ' {' ) {
125- throw conversion_error (" Malformed sparsevec literal" );
126- }
124+ try {
125+ if (text.size () < 4 || text.front () != ' {' ) {
126+ throw conversion_error (" Malformed sparsevec literal" );
127+ }
127128
128- size_t n = text.find (" }/" , 1 );
129- if (n == std::string_view::npos) {
130- throw conversion_error (" Malformed sparsevec literal" );
131- }
129+ size_t n = text.find (" }/" , 1 );
130+ if (n == std::string_view::npos) {
131+ throw conversion_error (" Malformed sparsevec literal" );
132+ }
132133
133- int dimensions = std::stoi (std::string (text.substr (n + 2 )));
134- if (dimensions < 0 ) {
135- throw conversion_error (" Malformed sparsevec literal" );
136- }
134+ int dimensions = std::stoi (std::string (text.substr (n + 2 )));
135+ if (dimensions < 0 ) {
136+ throw conversion_error (" Malformed sparsevec literal" );
137+ }
137138
138- std::vector<int > indices;
139- std::vector<float > values;
139+ std::vector<int > indices;
140+ std::vector<float > values;
140141
141- if (n > 1 ) {
142- std::istringstream ss (std::string (text.substr (1 , n)));
143- while (ss.good ()) {
144- std::string substr;
145- std::getline (ss, substr, ' ,' );
142+ if (n > 1 ) {
143+ std::istringstream ss (std::string (text.substr (1 , n)));
144+ while (ss.good ()) {
145+ std::string substr;
146+ std::getline (ss, substr, ' ,' );
146147
147- size_t ne = substr.find (" :" );
148- if (ne == std::string::npos) {
149- throw conversion_error (" Malformed sparsevec literal" );
150- }
148+ size_t ne = substr.find (" :" );
149+ if (ne == std::string::npos) {
150+ throw conversion_error (" Malformed sparsevec literal" );
151+ }
151152
152- int index = std::stoi (substr.substr (0 , ne));
153- float value = std::stof (substr.substr (ne + 1 ));
153+ int index = std::stoi (substr.substr (0 , ne));
154+ float value = std::stof (substr.substr (ne + 1 ));
154155
155- if (index < 1 ) {
156- throw conversion_error (" Malformed sparsevec literal" );
157- }
156+ if (index < 1 ) {
157+ throw conversion_error (" Malformed sparsevec literal" );
158+ }
158159
159- indices.push_back (index - 1 );
160- values.push_back (value);
160+ indices.push_back (index - 1 );
161+ values.push_back (value);
162+ }
161163 }
162- }
163164
164- return pgvector::SparseVector (dimensions, indices, values);
165+ return pgvector::SparseVector (dimensions, indices, values);
166+ } catch (const std::invalid_argument& e) {
167+ throw conversion_error (e.what ());
168+ } catch (const std::out_of_range& e) {
169+ throw conversion_error (e.what ());
170+ }
165171 }
166172
167173 static zview to_buf (char * begin, char * end, const pgvector::SparseVector& value) {
0 commit comments