summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>2020-03-11 10:50:56 +1300
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>2020-03-11 10:50:56 +1300
commit054123254e49ee5edeb35a2d648fce52755f5afe (patch)
tree3d1c95c35e05905a6f0f747072107a84dfbdbb66
parent5d96b0c02419fb2fd0c8fdee7dad0a5d5f4ac1a9 (diff)
downloadpsycopg2-column-slice.tar.gz
Column objects can be slicedcolumn-slice
Close #1034.
-rw-r--r--NEWS2
-rw-r--r--psycopg/column_type.c28
-rwxr-xr-xtests/test_cursor.py5
3 files changed, 34 insertions, 1 deletions
diff --git a/NEWS b/NEWS
index 0d43481..29aef12 100644
--- a/NEWS
+++ b/NEWS
@@ -8,6 +8,8 @@ What's new in psycopg 2.8.5
(:ticket:`#1019`).
- Added support for `~logging.LoggerAdapter` in
`~psycopg2.extras.LoggingConnection` (:ticket:`#1026`).
+- `~psycopg2.extensions.Column` objects in `cursor.description` can be sliced
+ (:ticket:`#1034`).
What's new in psycopg 2.8.4
diff --git a/psycopg/column_type.c b/psycopg/column_type.c
index 4947af2..b700706 100644
--- a/psycopg/column_type.c
+++ b/psycopg/column_type.c
@@ -233,6 +233,32 @@ column_getitem(columnObject *self, Py_ssize_t item)
}
+static PyObject*
+column_subscript(columnObject* self, PyObject* item)
+{
+ PyObject *t = NULL;
+ PyObject *rv = NULL;
+
+ /* t = tuple(self) */
+ if (!(t = PyObject_CallFunctionObjArgs(
+ (PyObject *)&PyTuple_Type, (PyObject *)self, NULL))) {
+ goto exit;
+ }
+
+ /* rv = t[item] */
+ rv = PyObject_GetItem(t, item);
+
+exit:
+ Py_XDECREF(t);
+ return rv;
+}
+
+static PyMappingMethods column_mapping = {
+ (lenfunc)column_len, /* mp_length */
+ (binaryfunc)column_subscript, /* mp_subscript */
+ 0 /* mp_ass_subscript */
+};
+
static PySequenceMethods column_sequence = {
(lenfunc)column_len, /* sq_length */
0, /* sq_concat */
@@ -346,7 +372,7 @@ PyTypeObject columnType = {
(reprfunc)column_repr, /*tp_repr*/
0, /*tp_as_number*/
&column_sequence, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
+ &column_mapping, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
diff --git a/tests/test_cursor.py b/tests/test_cursor.py
index 4d18096..9bf9ccf 100755
--- a/tests/test_cursor.py
+++ b/tests/test_cursor.py
@@ -433,6 +433,11 @@ class CursorTests(ConnectingTestCase):
self.assertEqual(curs.description[2].table_oid, None)
self.assertEqual(curs.description[2].table_column, None)
+ def test_description_slice(self):
+ curs = self.conn.cursor()
+ curs.execute("select 1::int as a")
+ self.assertEqual(curs.description[0][0:2], ('a', 23))
+
def test_pickle_description(self):
curs = self.conn.cursor()
curs.execute('SELECT 1 AS foo')