Skip to content

Commit b58f9a5

Browse files
committed
feat(sqla-core): Add support for rendering Database Specific queries
This makes the sqla-core plugin aware of how to compile a database specific query. It seems in some cases, we see strings come through (mostly pragma calls when doing 'create_all'), so do a check to see if the object looks like a SQL Expression object. Fixes: #290
1 parent 6e923b4 commit b58f9a5

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

aws_xray_sdk/ext/sqlalchemy_core/patch.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
from aws_xray_sdk.core.utils import stacktrace
1414
from aws_xray_sdk.ext.util import unwrap
1515

16+
from sqlalchemy.sql.expression import ClauseElement
17+
1618

1719
def _sql_meta(engine_instance, args):
1820
try:
@@ -41,7 +43,10 @@ def _sql_meta(engine_instance, args):
4143
metadata['database_version'] = '.'.join(map(str, engine_instance.dialect.server_version_info))
4244
if xray_recorder.stream_sql:
4345
try:
44-
metadata['sanitized_query'] = str(args[0])
46+
if isinstance(args[0], ClauseElement):
47+
metadata['sanitized_query'] = str(args[0].compile(engine_instance.engine))
48+
else:
49+
metadata['sanitized_query'] = str(args[0])
4550
except Exception:
4651
logging.getLogger(__name__).exception('Error getting the sanitized query')
4752
except Exception:

tests/ext/sqlalchemy_core/test_postgres.py

+14
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from .test_base import connection, User, session, Base
44

55
from sqlalchemy import create_engine
6+
from sqlalchemy.dialects.postgresql import insert as pg_insert
67

78
from aws_xray_sdk.core import xray_recorder, patch
89
from aws_xray_sdk.core.context import Context
@@ -56,3 +57,16 @@ def test_all(session, sanitized_db_url):
5657
assert sql_meta['url'] == sanitized_db_url
5758
assert sql_meta['sanitized_query'].startswith('SELECT')
5859
assert sql_meta['sanitized_query'].endswith('FROM users')
60+
61+
62+
def test_insert_on_conflict_renders(self, connection):
63+
statement = pg_insert(User).values(name='John', fullname="John Doe", password='123456')
64+
statement = statement.on_conflict_do_nothing()
65+
66+
connection.execute(statement)
67+
68+
assert len(xray_recorder.current_segment().subsegments) == 1
69+
sql_meta = xray_recorder.current_segment().subsegments[0].sql
70+
71+
assert sql_meta['sanitized_query'].startswith('INSERT INTO users')
72+
assert 'ON CONFLICT DO NOTHING' in sql_meta['sanitized_query']

0 commit comments

Comments
 (0)