mwag
mwag

Reputation: 4045

issue cursor.description never returns square bracket in column name (python 2.7 + sqlite3) alias

I'm trying to use cursor.description to get sqlite3 column names, and nothing I try works when the column name contains a square bracket. In looking at https://docs.python.org/2/library/sqlite3.html, it seems I might be able to use the detect_types param of sqlite3.connect(), but that does not seem to have any effect. Here's what I have tried:

import sqlite3
import sys

# tried using detect_types=0, sqlite3.PARSE_COLNAMES, or sqlite3.PARSE_DECLTYPES)
# all 3 values yield the same result
conn = sqlite3.connect(':memory:', detect_types=0)
cur = conn.cursor()
cur.execute('select 1 as "H[ello"')

for x in cur.description:
    sys.stderr.write("should write H[ello, but only writes: " + x[0])
    # output:
    #   should write H[ello, but only writes: H

Upvotes: 2

Views: 95

Answers (1)

alecxe
alecxe

Reputation: 474041

The [ appears to be a special case - it is filtered by the sqlite3 module while building a column name for the cursor description:

PyObject* _pysqlite_build_column_name(const char* colname)
{
    const char* pos;

    if (!colname) {
        Py_RETURN_NONE;
    }

    for (pos = colname;; pos++) {
        if (*pos == 0 || *pos == '[') {
            if ((*pos == '[') && (pos > colname) && (*(pos-1) == ' ')) {
                pos--;
            }
            return PyUnicode_FromStringAndSize(colname, pos - colname);
        }
    }
}

I'm though not sure why - probably related to compatibility with MS Access.

Upvotes: 1

Related Questions