Thanks to visit codestin.com
Credit goes to github.com

Skip to content

python 3.12 slices are hashable, affects one area of Row for 1.4 only #9819

@zzzeek

Description

@zzzeek

due to python/cpython#101264

from sqlalchemy import create_engine

e = create_engine("sqlite://")

with e.connect() as conn:
    result = conn.exec_driver_sql("select 1, 2, 3, 4, 5")

    row = result.one()

    onetwo = row[0:2]
    threefive = row[3:5]

    print(f"{onetwo} {threefive}")

output on 1.4:

Traceback (most recent call last):
  File "/home/classic/dev/sqlalchemy/lib/sqlalchemy/engine/row.py", line 131, in _get_by_key_impl
    rec = self._keymap[key]
          ~~~~~~~~~~~~^^^^^
KeyError: slice(0, 2, None)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/classic/dev/sqlalchemy/test3.py", line 10, in <module>
    onetwo = row[0:2]
             ~~~^^^^^
  File "/home/classic/dev/sqlalchemy/lib/sqlalchemy/engine/row.py", line 135, in _get_by_key_impl
    rec = self._parent._key_fallback(key, ke)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/classic/dev/sqlalchemy/lib/sqlalchemy/engine/cursor.py", line 801, in _key_fallback
    util.raise_(
  File "/home/classic/dev/sqlalchemy/lib/sqlalchemy/util/compat.py", line 211, in raise_
    raise exception
sqlalchemy.exc.NoSuchColumnError: Could not locate column in row for column 'slice(0, 2, None)'

this does not seem to affect 2.0 since we've refactored.

a fix would be

diff --git a/lib/sqlalchemy/engine/row.py b/lib/sqlalchemy/engine/row.py
index f7c00bab37..eb12e29dd6 100644
--- a/lib/sqlalchemy/engine/row.py
+++ b/lib/sqlalchemy/engine/row.py
@@ -130,6 +130,8 @@ except ImportError:
             try:
                 rec = self._keymap[key]
             except KeyError as ke:
+                if isinstance(key, slice):
+                    return tuple(self._data[key])
                 rec = self._parent._key_fallback(key, ke)
             except TypeError:
                 if isinstance(key, slice):

now it would be nice to get 3.12 on CI, but then we have to make a tox build that does not need greenlet, or somehow get a 3.12 version of greenlet running.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingengineengines, connections, transactions, isolation levels, execution options

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions