Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

bug_fix(1477): type handling in _add_sql_comment #3113

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
b75a977
bug_fix(1477): type handling in _add_sql_comment
aryabharat Dec 17, 2024
03561c8
bug_fix(1477): type handling in _add_sql_comment
aryabharat Dec 17, 2024
1d45193
Merge branch 'fix/1477' of https://github.com/aryabharat/opentelemetr…
aryabharat Jan 19, 2025
e90eefe
Merge branch 'main' into fix/1477
aryabharat Jan 19, 2025
ba3b51a
bug_fix(1477): type handling in _add_sql_comment
aryabharat Dec 17, 2024
cc7332d
Merge branch 'fix/1477' of https://github.com/aryabharat/opentelemetr…
aryabharat Jan 19, 2025
341899d
bug_fix(1477): updated type handling for _add_sql_comment
aryabharat Feb 4, 2025
a18df5e
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Feb 11, 2025
226c8e6
bug_fix(1477): updated type handling for _add_sql_comment
aryabharat Feb 4, 2025
ce7f69a
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Feb 15, 2025
14d0200
Merge branch 'fix/1477' of https://github.com/aryabharat/opentelemetr…
aryabharat Feb 15, 2025
2c8d008
bug_fix(1477): added unit tests
aryabharat Feb 15, 2025
1060c80
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Feb 19, 2025
592903c
updated change log file
aryabharat Feb 19, 2025
79321ed
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Feb 19, 2025
113222a
bug_fix(1477): updated change log.
aryabharat Feb 23, 2025
43750c0
Merge branch 'main' into fix/1477
tammy-baylis-swi Feb 25, 2025
7b4e3cb
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Feb 27, 2025
44d9f8d
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Feb 28, 2025
0e1c38f
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Mar 2, 2025
e6c47ac
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Mar 3, 2025
3e80a2d
Merge branch 'open-telemetry:main' into fix/1477
aryabharat Mar 7, 2025
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- `opentelemetry-instrumentation-dbapi`, `opentelemetry-instrumentation-django`,
`opentelemetry-instrumentation-sqlalchemy`: Fix sqlcomment for non string query and composable object.
([#3113](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3113))
- `opentelemetry-instrumentation-redis` Add missing entry in doc string for `def _instrument`
([#3247](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3247))
- `opentelemetry-instrumentation-asyncpg` Fix fallback for empty queries.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,11 @@ def _update_args_with_added_sql_comment(self, args, cursor) -> tuple:
args_list = list(args)
self._capture_mysql_version(cursor)
commenter_data = self._get_commenter_data()
# Convert sql statement to string, handling psycopg2.sql.Composable object
if hasattr(args_list[0], "as_string"):
args_list[0] = args_list[0].as_string(cursor.connection)

args_list[0] = str(args_list[0])
statement = _add_sql_comment(args_list[0], **commenter_data)
args_list[0] = statement
args = tuple(args_list)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,39 @@ def test_uninstrument_connection(self):
connection4 = dbapi.uninstrument_connection(mocked_conn)
self.assertIs(connection4, mocked_conn)

def test_non_string_sql_conversion(self):
"""Test that non-string SQL statements are converted to strings before adding comments."""
# Create a mock connect_module with required attributes
connect_module = mock.MagicMock()
connect_module.__name__ = "test"
connect_module.__version__ = "1.0"
connect_module.__libpq_version__ = 123
connect_module.apilevel = "2.0"
connect_module.threadsafety = 1
connect_module.paramstyle = "test"

db_integration = dbapi.DatabaseApiIntegration(
"testname",
"postgresql",
enable_commenter=True,
connect_module=connect_module,
)
mock_connection = db_integration.wrapped_connection(
mock_connect, {}, {}
)
cursor = mock_connection.cursor()

input_sql = mock.MagicMock(as_string=lambda conn: "SELECT 2")
expected_sql = "SELECT 2"

cursor.executemany(input_sql)
# Extract the SQL part (before the comment)
actual_sql = cursor.query.split("/*")[0].strip()
self.assertEqual(actual_sql, expected_sql)

spans_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(spans_list), 1)


# pylint: disable=unused-argument
def mock_connect(*args, **kwargs):
Expand All @@ -1100,6 +1133,7 @@ class MockCursor:
def __init__(self) -> None:
self.query = ""
self.params = None
self.connection = None
# Mock mysql.connector modules and method
self._cnx = mock.MagicMock()
self._cnx._cmysql = mock.MagicMock()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ def __call__(self, execute: Type[T], sql, params, many, context) -> T:
db_driver = context["connection"].settings_dict.get("ENGINE", "")
resolver_match = self.request.resolver_match

# Convert sql statement to string, handling psycopg2.sql.Composable object
if hasattr(sql, "as_string"):
sql = sql.as_string(context["connection"])

sql = str(sql)

sql = _add_sql_comment(
sql,
# Information about the controller.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,38 @@ def test_query_wrapper(self, trace_capture):
"00000000000000000deadbeef-000000000000beef-00'*/;",
)

@patch(
"opentelemetry.instrumentation.django.middleware.sqlcommenter_middleware._get_opentelemetry_values"
)
def test_query_wrapper_non_string_queries(self, trace_capture):
"""Test that non-string queries and psycopg2 composable objects are handled correctly."""
requests_mock = MagicMock()
requests_mock.resolver_match.view_name = "view"
requests_mock.resolver_match.route = "route"
requests_mock.resolver_match.app_name = "app"

trace_capture.return_value = {
"traceparent": "*traceparent='00-000000000000000000000000deadbeef-000000000000beef-00"
}
qw_instance = _QueryWrapper(requests_mock)
execute_mock_obj = MagicMock()

input_query = MagicMock(as_string=lambda conn: "SELECT 2")
expected_query_start = "SELECT 2"

qw_instance(
execute_mock_obj,
input_query,
MagicMock("test"),
MagicMock("test1"),
MagicMock(),
)
output_sql = execute_mock_obj.call_args[0][0]
self.assertTrue(
str(output_sql).startswith(str(expected_query_start)),
f"Query should start with {expected_query_start!r}, got {output_sql!r}",
)

@patch(
"opentelemetry.instrumentation.django.middleware.sqlcommenter_middleware._QueryWrapper"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,9 @@ def _before_cur_exec(
commenter_data = self._get_commenter_data(conn)

if self.enable_attribute_commenter:
# just to handle type safety
statement = str(statement)

# sqlcomment is added to executed query and db.statement span attribute
statement = _add_sql_comment(
statement, **commenter_data
Expand Down