Handle empty strings in sqlcommenter (#3309)

* Handle empty strings

Safer check for a trailing semicolon that could handle
empty strings as well.

* Updated CHANGELOG.md

* Test for empty SQL strings in sqlcommenter

---------

Co-authored-by: Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>
This commit is contained in:
Selcuk Ayguney
2025-03-13 21:18:35 +10:00
committed by GitHub
parent f96d14cc62
commit 3c88163c99
3 changed files with 31 additions and 1 deletions

View File

@ -46,6 +46,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#3249](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3249))
- `opentelemetry-instrumentation-asyncpg` Fix fallback for empty queries.
([#3253](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3253))
- `opentelemetry-instrumentation` Fix a traceback in sqlcommenter when psycopg connection pooling is enabled.
([#3309](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3309))
- `opentelemetry-instrumentation-threading` Fix broken context typehints
([#3322](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3322))
- `opentelemetry-instrumentation-requests` always record span status code in duration metric

View File

@ -146,3 +146,31 @@ class TestMiddleware(WsgiTestBase):
# check if query_wrapper is added to the context for 2 databases
self.assertEqual(query_wrapper.call_count, 2)
@patch(
"opentelemetry.instrumentation.django.middleware.sqlcommenter_middleware._get_opentelemetry_values"
)
def test_empty_sql(self, trace_capture):
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()
qw_instance(
execute_mock_obj,
"",
MagicMock("test"),
MagicMock("test1"),
MagicMock(),
)
output_sql = execute_mock_obj.call_args[0][0]
self.assertEqual(
output_sql,
" /*app_name='app',controller='view',route='route',traceparent='%%2Atraceparent%%3D%%2700-0000000"
"00000000000000000deadbeef-000000000000beef-00'*/",
)

View File

@ -23,7 +23,7 @@ def _add_sql_comment(sql, **meta) -> str:
meta.update(**_add_framework_tags())
comment = _generate_sql_comment(**meta)
sql = sql.rstrip()
if sql[-1] == ";":
if sql.endswith(";"):
sql = sql[:-1] + comment + ";"
else:
sql = sql + comment