Skip to content

Commit f58e582

Browse files
[3.15] gh-153695: Fix sqlite3.Row.__hash__ with an unhashable value (GH-153696) (#153723)
gh-153695: Fix sqlite3.Row.__hash__ with an unhashable value (GH-153696) (cherry picked from commit b704b64) Co-authored-by: tonghuaroot (童话) <tonghuaroot@gmail.com>
1 parent bec166a commit f58e582

3 files changed

Lines changed: 22 additions & 1 deletion

File tree

Lib/test/test_sqlite3/test_factory.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,17 @@ def test_sqlite_row_hash_cmp(self):
239239

240240
self.assertEqual(hash(row_1), hash(row_2))
241241

242+
def test_sqlite_row_hash_unhashable(self):
243+
# An unhashable value must raise TypeError, not SystemError.
244+
sqlite.register_converter("LST", lambda b: [1, 2, 3])
245+
self.addCleanup(sqlite.converters.pop, "LST", None)
246+
with memory_database(detect_types=sqlite.PARSE_DECLTYPES) as con:
247+
con.row_factory = sqlite.Row
248+
con.execute("create table t(x LST)")
249+
con.execute("insert into t values(?)", (b"x",))
250+
row = con.execute("select x from t").fetchone()
251+
self.assertRaisesRegex(TypeError, "unhashable", hash, row)
252+
242253
def test_sqlite_row_as_sequence(self):
243254
# Checks if the row object can act like a sequence.
244255
row = self.con.execute("select 1 as a, 2 as b").fetchone()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Hashing a :class:`sqlite3.Row` that contains an unhashable value now raises
2+
:exc:`TypeError` instead of :exc:`SystemError`. Patch by tonghuaroot.

Modules/_sqlite/row.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,15 @@ static Py_hash_t
232232
pysqlite_row_hash(PyObject *op)
233233
{
234234
pysqlite_Row *self = _pysqlite_Row_CAST(op);
235-
return PyObject_Hash(self->description) ^ PyObject_Hash(self->data);
235+
Py_hash_t hash_description = PyObject_Hash(self->description);
236+
if (hash_description == -1) {
237+
return -1;
238+
}
239+
Py_hash_t hash_data = PyObject_Hash(self->data);
240+
if (hash_data == -1) {
241+
return -1;
242+
}
243+
return hash_description ^ hash_data;
236244
}
237245

238246
static PyObject *

0 commit comments

Comments
 (0)