Skip to content
Merged
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
32 changes: 28 additions & 4 deletions mssql_python/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1124,14 +1124,17 @@ def _get_column_and_converter_maps(self):
# Build column map locally first, then assign to cache
column_map = {col_desc[0]: i for i, col_desc in enumerate(self.description)}
self._cached_column_map = column_map
self._cached_column_map_lower = (
{k.lower(): v for k, v in column_map.items()} if get_settings().lowercase else None
)

# Fallback to legacy column name map if no cached map
column_map = column_map or getattr(self, "_column_name_map", None)

# Get cached converter map
converter_map = getattr(self, "_cached_converter_map", None)

return column_map, converter_map
return column_map, converter_map, self._cached_column_map_lower

def _map_data_type(self, sql_type):
"""
Expand Down Expand Up @@ -1547,12 +1550,18 @@ def execute( # pylint: disable=too-many-locals,too-many-branches,too-many-state
self._cached_column_map = {
col_desc[0]: i for i, col_desc in enumerate(self.description)
}
self._cached_column_map_lower = (
{k.lower(): v for k, v in self._cached_column_map.items()}
if get_settings().lowercase
else None
)
self._cached_converter_map = self._build_converter_map()
self._uuid_str_indices = self._compute_uuid_str_indices()
else:
self.rowcount = ddbc_bindings.DDBCSQLRowCount(self.hstmt)
self._clear_rownumber()
self._cached_column_map = None
self._cached_column_map_lower = None
self._cached_converter_map = None
self._uuid_str_indices = None

Expand Down Expand Up @@ -2451,12 +2460,18 @@ def executemany( # pylint: disable=too-many-locals,too-many-branches,too-many-s
self._cached_column_map = {
col_desc[0]: i for i, col_desc in enumerate(self.description)
}
self._cached_column_map_lower = (
{k.lower(): v for k, v in self._cached_column_map.items()}
if get_settings().lowercase
else None
)
self._cached_converter_map = self._build_converter_map()
self._uuid_str_indices = self._compute_uuid_str_indices()
else:
self.rowcount = ddbc_bindings.DDBCSQLRowCount(self.hstmt)
self._clear_rownumber()
self._cached_column_map = None
self._cached_column_map_lower = None
self._cached_converter_map = None
self._uuid_str_indices = None
finally:
Expand Down Expand Up @@ -2506,13 +2521,14 @@ def fetchone(self) -> Union[None, Row]:
self.rowcount = self._next_row_index

# Get column and converter maps
column_map, converter_map = self._get_column_and_converter_maps()
column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()
return Row(
row_data,
column_map,
cursor=self,
converter_map=converter_map,
uuid_str_indices=self._uuid_str_indices,
column_map_lower=column_map_lower,
)
except Exception as e:
# On error, don't increment rownumber - rethrow the error
Expand Down Expand Up @@ -2569,7 +2585,7 @@ def fetchmany(self, size: Optional[int] = None) -> List[Row]:
self.rowcount = self._next_row_index

# Get column and converter maps
column_map, converter_map = self._get_column_and_converter_maps()
column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()

# Convert raw data to Row objects
uuid_idx = self._uuid_str_indices
Expand All @@ -2580,6 +2596,7 @@ def fetchmany(self, size: Optional[int] = None) -> List[Row]:
cursor=self,
converter_map=converter_map,
uuid_str_indices=uuid_idx,
column_map_lower=column_map_lower,
)
for row_data in rows_data
]
Expand Down Expand Up @@ -2630,7 +2647,7 @@ def fetchall(self) -> List[Row]:
self.rowcount = self._next_row_index

# Get column and converter maps
column_map, converter_map = self._get_column_and_converter_maps()
column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()

# Convert raw data to Row objects
uuid_idx = self._uuid_str_indices
Expand All @@ -2641,6 +2658,7 @@ def fetchall(self) -> List[Row]:
cursor=self,
converter_map=converter_map,
uuid_str_indices=uuid_idx,
column_map_lower=column_map_lower,
)
for row_data in rows_data
]
Expand Down Expand Up @@ -2754,6 +2772,7 @@ def nextset(self) -> Union[bool, None]:

# Clear cached column and converter maps for the new result set
self._cached_column_map = None
self._cached_column_map_lower = None
self._cached_converter_map = None
self._uuid_str_indices = None

Expand All @@ -2780,6 +2799,11 @@ def nextset(self) -> Union[bool, None]:
self._cached_column_map = {
col_desc[0]: i for i, col_desc in enumerate(self.description)
}
self._cached_column_map_lower = (
{k.lower(): v for k, v in self._cached_column_map.items()}
if get_settings().lowercase
else None
)
self._cached_converter_map = self._build_converter_map()
self._uuid_str_indices = self._compute_uuid_str_indices()
except Exception as e: # pylint: disable=broad-exception-caught
Expand Down
47 changes: 36 additions & 11 deletions mssql_python/row.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import decimal
import uuid as _uuid
from typing import Any
from mssql_python.helpers import get_settings
from mssql_python.logging import logger


Expand All @@ -27,7 +26,15 @@ class Row:
print(row.column_name) # Access by column name (case sensitivity varies)
"""

def __init__(self, values, column_map, cursor=None, converter_map=None, uuid_str_indices=None):
def __init__(
self,
values,
column_map,
cursor=None,
converter_map=None,
uuid_str_indices=None,
column_map_lower=None,
):
"""
Initialize a Row object with values and pre-built column map.
Args:
Expand All @@ -38,6 +45,9 @@ def __init__(self, values, column_map, cursor=None, converter_map=None, uuid_str
uuid_str_indices: Tuple of column indices whose uuid.UUID values should be
converted to str. Pre-computed once per result set when native_uuid=False.
None means no conversion (native_uuid=True, the default).
column_map_lower: Pre-built lowercase column map for O(1) case-insensitive
lookups. Built once per result set in the cursor when lowercase is enabled;
None when lowercase is off (the default). Shared across all rows.
"""
# Apply output converters if available using pre-computed converter map
if converter_map:
Expand All @@ -60,6 +70,9 @@ def __init__(self, values, column_map, cursor=None, converter_map=None, uuid_str

self._column_map = column_map
self._cursor = cursor
# Lowercase map is pre-built once per result set in the cursor and shared
# across all rows. None when lowercase is off (the default) — zero cost.
self._column_map_lower = column_map_lower

def _stringify_uuids(self, indices):
"""
Expand Down Expand Up @@ -156,9 +169,22 @@ def _apply_output_converters_optimized(self, values, converter_map):

return converted_values

def __getitem__(self, index: int) -> Any:
"""Allow accessing by numeric index: row[0]"""
return self._values[index]
def __getitem__(self, index) -> Any:
"""Allow accessing by numeric index (row[0]) or column name (row["col"])."""
if isinstance(index, str):
if index in self._column_map:
return self._values[self._column_map[index]]
# O(1) case-insensitive lookup when lowercase is enabled
if self._column_map_lower is not None:
idx = self._column_map_lower.get(index.lower())
if idx is not None:
return self._values[idx]
raise KeyError(f"Row has no column '{index}'")
Comment thread
jahnvi480 marked this conversation as resolved.
if isinstance(index, (int, slice)):
return self._values[index]
raise TypeError(
f"Row indices must be integers, slices, or strings, not {type(index).__name__}"
)

def __getattr__(self, name: str) -> Any:
"""
Expand All @@ -175,12 +201,11 @@ def __getattr__(self, name: str) -> Any:
if name in self._column_map:
return self._values[self._column_map[name]]

# If lowercase is enabled on the cursor, try case-insensitive lookup
if hasattr(self._cursor, "lowercase") and self._cursor.lowercase:
name_lower = name.lower()
for col_name in self._column_map:
if col_name.lower() == name_lower:
return self._values[self._column_map[col_name]]
# O(1) case-insensitive lookup when lowercase is enabled
if self._column_map_lower is not None:
idx = self._column_map_lower.get(name.lower())
if idx is not None:
return self._values[idx]

raise AttributeError(f"Row has no attribute '{name}'")

Expand Down
63 changes: 63 additions & 0 deletions tests/test_001_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -996,3 +996,66 @@ def test_stringify_uuids_with_tuple_values():
assert row[2] == "hello"
# Internal storage should now be a list (converted from tuple)
assert isinstance(row._values, list)


def test_row_string_key_indexing():
Comment thread
jahnvi480 marked this conversation as resolved.
"""Test Row supports string-key indexing via __getitem__ (row['col'])."""
from mssql_python.row import Row

row = Row(
[1, "foo", 3.14],
{"ProductID": 0, "Name": 1, "Price": 2},
cursor=None,
)

# String-key access
assert row["ProductID"] == 1
assert row["Name"] == "foo"
assert row["Price"] == 3.14

# Integer index access still works
assert row[0] == 1
assert row[1] == "foo"
assert row[2] == 3.14

# Slice access still works
assert row[0:2] == [1, "foo"]

# Missing key raises KeyError
with pytest.raises(KeyError):
row["nonexistent"]

# Unsupported index types raise TypeError
with pytest.raises(TypeError):
row[3.5]
with pytest.raises(TypeError):
row[None]


def test_row_string_key_case_insensitive_with_lowercase():
"""Test Row string-key indexing is case-insensitive when column_map_lower is provided."""
from mssql_python.row import Row

column_map = {"productid": 0, "name": 1}
column_map_lower = {k.lower(): v for k, v in column_map.items()}

row = Row(
[1, "bar"],
column_map,
cursor=None,
column_map_lower=column_map_lower,
)

# Exact match via __getitem__
assert row["productid"] == 1
# Exact match via __getattr__
assert row.productid == 1
# Case-insensitive match via __getitem__
assert row["ProductID"] == 1
assert row["NAME"] == "bar"
# Case-insensitive match via __getattr__ (attribute access)
assert row.ProductID == 1
assert row.NAME == "bar"
# Non-existent attribute raises AttributeError
with pytest.raises(AttributeError):
row.nonexistent
38 changes: 38 additions & 0 deletions tests/test_004_cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2876,6 +2876,44 @@ def test_row_attribute_access(cursor, db_connection):
db_connection.commit()


def test_row_string_key_indexing(cursor, db_connection):
"""Test accessing row values by column name as string key: row['col']"""
try:
cursor.execute(
"CREATE TABLE #pytest_row_strkey (id INT PRIMARY KEY, name VARCHAR(50), age INT)"
)
db_connection.commit()

cursor.execute("INSERT INTO #pytest_row_strkey (id, name, age) VALUES (1, 'Alice', 25)")
db_connection.commit()

cursor.execute("SELECT * FROM #pytest_row_strkey")
row = cursor.fetchone()

# String-key access
assert row["id"] == 1, "Failed to access 'id' by string key"
assert row["name"] == "Alice", "Failed to access 'name' by string key"
assert row["age"] == 25, "Failed to access 'age' by string key"

# Consistency with index and attribute access
assert row["id"] == row[0] == row.id
assert row["name"] == row[1] == row.name
assert row["age"] == row[2] == row.age

# Non-existent key raises KeyError
with pytest.raises(KeyError):
row["nonexistent"]

except Exception as e:
pytest.fail(f"Row string-key indexing test failed: {e}")
finally:
try:
cursor.execute("DROP TABLE IF EXISTS #pytest_row_strkey")
db_connection.commit()
except Exception:
pass


def test_row_comparison_with_list(cursor, db_connection):
"""Test comparing Row objects with lists (__eq__ method)"""
try:
Expand Down
Loading