Skip to content

Commit 4a62a41

Browse files
authored
Add db.system data to SQLAlchemy db spans (#2039)
1 parent 727a3d1 commit 4a62a41

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

sentry_sdk/integrations/sqlalchemy.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import re
44

55
from sentry_sdk._types import TYPE_CHECKING
6+
from sentry_sdk.consts import SPANDATA
67
from sentry_sdk.hub import Hub
78
from sentry_sdk.integrations import Integration, DidNotEnable
89
from sentry_sdk.tracing_utils import record_sql_queries
@@ -67,6 +68,9 @@ def _before_cursor_execute(
6768
span = ctx_mgr.__enter__()
6869

6970
if span is not None:
71+
db_system = _get_db_system(conn.engine.name)
72+
if db_system is not None:
73+
span.set_data(SPANDATA.DB_SYSTEM, db_system)
7074
context._sentry_sql_span = span
7175

7276

@@ -102,3 +106,24 @@ def _handle_error(context, *args):
102106
if ctx_mgr is not None:
103107
execution_context._sentry_sql_span_manager = None
104108
ctx_mgr.__exit__(None, None, None)
109+
110+
111+
# See: https://docs.sqlalchemy.org/en/20/dialects/index.html
112+
def _get_db_system(name):
113+
# type: (str) -> Optional[str]
114+
if "sqlite" in name:
115+
return "sqlite"
116+
117+
if "postgres" in name:
118+
return "postgresql"
119+
120+
if "mariadb" in name:
121+
return "mariadb"
122+
123+
if "mysql" in name:
124+
return "mysql"
125+
126+
if "oracle" in name:
127+
return "oracle"
128+
129+
return None

tests/integrations/sqlalchemy/test_sqlalchemy.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from sqlalchemy.orm import relationship, sessionmaker
88

99
from sentry_sdk import capture_message, start_transaction, configure_scope
10+
from sentry_sdk.consts import SPANDATA
1011
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
1112
from sentry_sdk.serializer import MAX_EVENT_BYTES
1213
from sentry_sdk.utils import json_dumps, MAX_STRING_LENGTH
@@ -119,6 +120,9 @@ class Address(Base):
119120

120121
(event,) = events
121122

123+
for span in event["spans"]:
124+
assert span["data"][SPANDATA.DB_SYSTEM] == "sqlite"
125+
122126
assert (
123127
render_span_tree(event)
124128
== """\

0 commit comments

Comments
 (0)