Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-100450: Add sqlite.Row.__contains__ method #100457

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/test/test_sqlite3/test_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,14 @@ def test_sqlite_row_as_sequence(self):
self.assertEqual(list(reversed(row)), list(reversed(as_tuple)))
self.assertIsInstance(row, Sequence)

def test_sqlite_row_contains(self):
"""Checks if the row object can be used with `in`"""
erlend-aasland marked this conversation as resolved.
Show resolved Hide resolved
self.con.row_factory = sqlite.Row
row = self.con.execute("select 1 as a, 2 as b").fetchone()
self.assertIn('a', row)
self.assertIn('b', row)
self.assertNotIn('c', row)

def test_fake_cursor_class(self):
# Issue #24257: Incorrect use of PyObject_IsInstance() caused
# segmentation fault.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add ``sqlite.Row.__contains__`` method.
19 changes: 19 additions & 0 deletions Modules/_sqlite/row.c
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,24 @@ PyObject* pysqlite_row_item(pysqlite_Row* self, Py_ssize_t idx)
return Py_XNewRef(item);
}

static int
pysqlite_row_contains(pysqlite_Row* self, PyObject *arg)
{
Py_ssize_t nitems;
Py_ssize_t i;
PyObject *key;
int cmp = 0;

nitems = PyTuple_Size(self->description);

for (i = 0; cmp == 0 && i < nitems; i++) {
key = PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0);
cmp = PyObject_RichCompareBool(arg, key, Py_EQ);
}

return cmp;
}

static int
equal_ignore_case(PyObject *left, PyObject *right)
{
Expand Down Expand Up @@ -249,6 +267,7 @@ static PyType_Slot row_slots[] = {
{Py_mp_subscript, pysqlite_row_subscript},
{Py_sq_length, pysqlite_row_length},
{Py_sq_item, pysqlite_row_item},
{Py_sq_contains, pysqlite_row_contains},
{Py_tp_new, pysqlite_row_new},
{Py_tp_traverse, row_traverse},
{Py_tp_clear, row_clear},
Expand Down