Skip to content

Commit 503560d

Browse files
[3.15] gh-150449: Raise ValueError for sqlite3.Blob slices with a negative step (GH-155773)
Reading or writing such a slice computed a negative length and failed with SystemError. Empty slices, which select nothing, are still allowed. (cherry picked from commit d9e8d226a3d05ea020256086aee24d21f9792206)
1 parent d46288f commit 503560d

3 files changed

Lines changed: 29 additions & 0 deletions

File tree

‎Lib/test/test_sqlite3/test_dbapi.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1396,6 +1396,19 @@ def test_blob_set_slice(self):
13961396
actual = self.cx.execute("select b from test").fetchone()[0]
13971397
self.assertEqual(actual, expected)
13981398

1399+
def test_blob_slice_with_negative_step(self):
1400+
# gh-150449: this used to raise SystemError
1401+
for sl in (slice(9, 0, -2), slice(None, None, -1), slice(9, None, -2)):
1402+
with self.subTest(slice=sl):
1403+
with self.assertRaises(ValueError):
1404+
self.blob[sl]
1405+
with self.assertRaises(ValueError):
1406+
self.blob[sl] = b"1" * len(self.data[sl])
1407+
# an empty slice selects nothing and is still allowed
1408+
self.assertEqual(self.blob[3:8:-1], b"")
1409+
self.blob[3:8:-1] = b""
1410+
self.assertEqual(self.blob[:], self.data)
1411+
13991412
def test_blob_set_slice_with_step_keeps_bytes_intact(self):
14001413
# The buffer used for the read-patch-write cycle must not be the
14011414
# bytes object read from the blob: for a single byte it is an
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :class:`sqlite3.Blob` slices with a negative step.
2+
Reading or writing such a slice raised :exc:`SystemError`.
3+
It now raises :exc:`ValueError`.

‎Modules/_sqlite/blob.c‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,12 @@ subscript_slice(pysqlite_Blob *self, PyObject *item)
450450
return PyBytes_FromStringAndSize(NULL, 0);
451451
}
452452

453+
if (step < 0) {
454+
PyErr_SetString(PyExc_ValueError,
455+
"Blob doesn't support slices with a negative step");
456+
return NULL;
457+
}
458+
453459
if (step == 1) {
454460
return read_multiple(self, len, start);
455461
}
@@ -557,6 +563,13 @@ ass_subscript_slice(pysqlite_Blob *self, PyObject *item, PyObject *value)
557563
return 0;
558564
}
559565

566+
if (step < 0) {
567+
PyErr_SetString(PyExc_ValueError,
568+
"Blob doesn't support slices with a negative step");
569+
PyBuffer_Release(&vbuf);
570+
return -1;
571+
}
572+
560573
int rc = -1;
561574
if (step == 1) {
562575
rc = inner_write(self, vbuf.buf, len, start);

0 commit comments

Comments
 (0)