Skip to content

Commit 70d6c85

Browse files
authored
[3.13] gh-153695: Fix sqlite3.Row.__hash__ with an unhashable value (GH-153696) (GH-153725)
(cherry picked from commit b704b64)
1 parent 0f1e563 commit 70d6c85

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
@@ -248,6 +248,17 @@ def test_sqlite_row_hash_cmp(self):
248248

249249
self.assertEqual(hash(row_1), hash(row_2))
250250

251+
def test_sqlite_row_hash_unhashable(self):
252+
# An unhashable value must raise TypeError, not SystemError.
253+
sqlite.register_converter("LST", lambda b: [1, 2, 3])
254+
self.addCleanup(sqlite.converters.pop, "LST", None)
255+
with memory_database(detect_types=sqlite.PARSE_DECLTYPES) as con:
256+
con.row_factory = sqlite.Row
257+
con.execute("create table t(x LST)")
258+
con.execute("insert into t values(?)", (b"x",))
259+
row = con.execute("select x from t").fetchone()
260+
self.assertRaisesRegex(TypeError, "unhashable", hash, row)
261+
251262
def test_sqlite_row_as_sequence(self):
252263
# Checks if the row object can act like a sequence.
253264
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
@@ -220,7 +220,15 @@ static PyObject* pysqlite_iter(pysqlite_Row* self)
220220

221221
static Py_hash_t pysqlite_row_hash(pysqlite_Row *self)
222222
{
223-
return PyObject_Hash(self->description) ^ PyObject_Hash(self->data);
223+
Py_hash_t hash_description = PyObject_Hash(self->description);
224+
if (hash_description == -1) {
225+
return -1;
226+
}
227+
Py_hash_t hash_data = PyObject_Hash(self->data);
228+
if (hash_data == -1) {
229+
return -1;
230+
}
231+
return hash_description ^ hash_data;
224232
}
225233

226234
static PyObject* pysqlite_row_richcompare(pysqlite_Row *self, PyObject *_other, int opid)

0 commit comments

Comments
 (0)