Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
14 changes: 12 additions & 2 deletions mssql_python/row.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,18 @@ 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]"""
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]]
# Case-insensitive lookup when lowercase is enabled
if hasattr(self._cursor, "lowercase") and self._cursor.lowercase:
index_lower = index.lower()
for col_name in self._column_map:
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
if col_name.lower() == index_lower:
return self._values[self._column_map[col_name]]
raise KeyError(f"Row has no column '{index}'")
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
Comment thread
jahnvi480 marked this conversation as resolved.
return self._values[index]

def __getattr__(self, name: str) -> Any:
Expand Down
50 changes: 50 additions & 0 deletions tests/test_001_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -996,3 +996,53 @@ 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"]


def test_row_string_key_case_insensitive_with_lowercase():
"""Test Row string-key indexing is case-insensitive when cursor.lowercase is True."""
from mssql_python.row import Row
from unittest.mock import Mock

mock_cursor = Mock()
mock_cursor.lowercase = True
mock_cursor.connection._output_converters = None

row = Row(
[1, "bar"],
{"productid": 0, "name": 1},
cursor=mock_cursor,
)

# Exact match
assert row["productid"] == 1
# Case-insensitive match
assert row["ProductID"] == 1
assert row["NAME"] == "bar"
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
37 changes: 36 additions & 1 deletion tests/test_004_cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2876,6 +2876,41 @@ 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:
cursor.execute("DROP TABLE #pytest_row_strkey")
db_connection.commit()
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated


def test_row_comparison_with_list(cursor, db_connection):
"""Test comparing Row objects with lists (__eq__ method)"""
try:
Expand Down Expand Up @@ -16200,4 +16235,4 @@ def test_long_print_message(cursor, message_len):
cursor.execute(query)
msg = cursor.messages[0][1]
# SQL Server truncates at 8000 characters
assert msg.endswith("a" * min(8000, message_len)), msg
assert msg.endswith("a" * min(8000, message_len)), msg
Loading