Skip to content

Commit e6ec472

Browse files
authored
fix(sqlalchemy): Guard against engine.url being None (#2708)
1 parent 75fd43f commit e6ec472

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

sentry_sdk/integrations/sqlalchemy.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,9 @@ def _set_db_data(span, conn):
153153
if db_system is not None:
154154
span.set_data(SPANDATA.DB_SYSTEM, db_system)
155155

156+
if conn.engine.url is None:
157+
return
158+
156159
db_name = conn.engine.url.database
157160
if db_name is not None:
158161
span.set_data(SPANDATA.DB_NAME, db_name)

tests/integrations/sqlalchemy/test_sqlalchemy.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,62 @@ class Address(Base):
154154
)
155155

156156

157+
@pytest.mark.skipif(
158+
sys.version_info < (3,), reason="This sqla usage seems to be broken on Py2"
159+
)
160+
def test_transactions_no_engine_url(sentry_init, capture_events):
161+
sentry_init(
162+
integrations=[SqlalchemyIntegration()],
163+
_experiments={"record_sql_params": True},
164+
traces_sample_rate=1.0,
165+
)
166+
events = capture_events()
167+
168+
Base = declarative_base() # noqa: N806
169+
170+
class Person(Base):
171+
__tablename__ = "person"
172+
id = Column(Integer, primary_key=True)
173+
name = Column(String(250), nullable=False)
174+
175+
class Address(Base):
176+
__tablename__ = "address"
177+
id = Column(Integer, primary_key=True)
178+
street_name = Column(String(250))
179+
street_number = Column(String(250))
180+
post_code = Column(String(250), nullable=False)
181+
person_id = Column(Integer, ForeignKey("person.id"))
182+
person = relationship(Person)
183+
184+
engine = create_engine("sqlite:///:memory:")
185+
engine.url = None
186+
Base.metadata.create_all(engine)
187+
188+
Session = sessionmaker(bind=engine) # noqa: N806
189+
session = Session()
190+
191+
with start_transaction(name="test_transaction", sampled=True):
192+
with session.begin_nested():
193+
session.query(Person).first()
194+
195+
for _ in range(2):
196+
with pytest.raises(IntegrityError):
197+
with session.begin_nested():
198+
session.add(Person(id=1, name="bob"))
199+
session.add(Person(id=1, name="bob"))
200+
201+
with session.begin_nested():
202+
session.query(Person).first()
203+
204+
(event,) = events
205+
206+
for span in event["spans"]:
207+
assert span["data"][SPANDATA.DB_SYSTEM] == "sqlite"
208+
assert SPANDATA.DB_NAME not in span["data"]
209+
assert SPANDATA.SERVER_ADDRESS not in span["data"]
210+
assert SPANDATA.SERVER_PORT not in span["data"]
211+
212+
157213
def test_long_sql_query_preserved(sentry_init, capture_events):
158214
sentry_init(
159215
traces_sample_rate=1,

0 commit comments

Comments
 (0)