Skip to content

Commit daf3a73

Browse files
Add fallbacks in case driver module not PEP 249-compliant
1 parent c461544 commit daf3a73

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -307,9 +307,17 @@ def calculate_commenter_data(
307307

308308
commenter_data = {
309309
"db_driver": f"{db_driver}:{db_version.split(' ')[0]}",
310-
"dbapi_threadsafety": self.connect_module.threadsafety,
311-
"dbapi_level": self.connect_module.apilevel,
312-
"driver_paramstyle": self.connect_module.paramstyle,
310+
# PEP 249-compliant drivers should have the following attributes.
311+
# We can assume apilevel "1.0" if not given.
312+
# We use "unknown" for others to prevent uncaught AttributeError.
313+
# https://peps.python.org/pep-0249/#globals
314+
"dbapi_threadsafety": getattr(
315+
self.connect_module, "threadsafety", "unknown"
316+
),
317+
"dbapi_level": getattr(self.connect_module, "apilevel", "1.0"),
318+
"driver_paramstyle": getattr(
319+
self.connect_module, "paramstyle", "unknown"
320+
),
313321
}
314322

315323
if self.database_system == "postgresql":

instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,35 @@ def test_executemany_comment(self):
277277
r"Select 1 /\*dbapi_threadsafety=123,driver_paramstyle='test',libpq_version=123,traceparent='\d{1,2}-[a-zA-Z0-9_]{32}-[a-zA-Z0-9_]{16}-\d{1,2}'\*/;",
278278
)
279279

280+
def test_executemany_comment_non_pep_249_compliant(self):
281+
class MockConnectModule:
282+
def __getattr__(self, name):
283+
if name == "__name__":
284+
return "test"
285+
if name == "__version__":
286+
return mock.MagicMock()
287+
if name == "__libpq_version__":
288+
return 123
289+
raise AttributeError("attribute missing")
290+
291+
connect_module = MockConnectModule()
292+
db_integration = dbapi.DatabaseApiIntegration(
293+
"testname",
294+
"postgresql",
295+
enable_commenter=True,
296+
connect_module=connect_module,
297+
commenter_options={"db_driver": False},
298+
)
299+
mock_connection = db_integration.wrapped_connection(
300+
mock_connect, {}, {}
301+
)
302+
cursor = mock_connection.cursor()
303+
cursor.executemany("Select 1;")
304+
self.assertRegex(
305+
cursor.query,
306+
r"Select 1 /\*dbapi_level='1.0',dbapi_threadsafety='unknown',driver_paramstyle='unknown',libpq_version=123,traceparent='\d{1,2}-[a-zA-Z0-9_]{32}-[a-zA-Z0-9_]{16}-\d{1,2}'\*/;",
307+
)
308+
280309
def test_compatible_build_version_psycopg_psycopg2_libpq(self):
281310
connect_module = mock.MagicMock()
282311
connect_module.__name__ = "test"

0 commit comments

Comments
 (0)