Skip to content

Commit

Permalink
In psycopg2 connect accept database name either as dbname or database
Browse files Browse the repository at this point in the history
  • Loading branch information
IlyaSukhanov committed Sep 10, 2018
1 parent 3038610 commit 314a36b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
15 changes: 9 additions & 6 deletions aws_xray_sdk/ext/psycopg2/patch.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
import wrapt
from operator import methodcaller

from aws_xray_sdk.ext.dbapi2 import XRayTracedConn

Expand All @@ -16,14 +17,16 @@ def patch():
def _xray_traced_connect(wrapped, instance, args, kwargs):

conn = wrapped(*args, **kwargs)
host = kwargs['host'] if 'host' in kwargs else re.search(r'host=(\S+)\b', args[0]).groups()[0]
dbname = kwargs['dbname'] if 'dbname' in kwargs else re.search(r'dbname=(\S+)\b', args[0]).groups()[0]
port = kwargs['port'] if 'port' in kwargs else re.search(r'port=(\S+)\b', args[0]).groups()[0]
user = kwargs['user'] if 'user' in kwargs else re.search(r'user=(\S+)\b', args[0]).groups()[0]
parameterized_dsn = { c[0]: c[-1] for c in map(methodcaller('split', '='), conn.dsn.split(' '))}
meta = {
'database_type': 'PostgreSQL',
'url': 'postgresql://{}@{}:{}/{}'.format(user, host, port, dbname),
'user': user,
'url': 'postgresql://{}@{}:{}/{}'.format(
parameterized_dsn.get('user', 'unknown'),
parameterized_dsn.get('host', 'unknown'),
parameterized_dsn.get('port', 'unknown'),
parameterized_dsn.get('dbname', 'unknown'),
),
'user': parameterized_dsn.get('user', 'unknown'),
'database_version': str(conn.server_version),
'driver_version': 'Psycopg 2'
}
Expand Down
26 changes: 26 additions & 0 deletions tests/ext/psycopg2/test_psycopg2.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,32 @@ def test_execute_dsn_kwargs():
assert sql['database_version']


def test_execute_dsn_kwargs_alt_dbname():
"""
Psycopg supports database to be passed as `database` or `dbname`
"""
q = 'SELECT 1'

with testing.postgresql.Postgresql() as postgresql:
url = postgresql.url()
dsn = postgresql.dsn()
conn = psycopg2.connect(database=dsn['database'],
user=dsn['user'],
password='',
host=dsn['host'],
port=dsn['port'])
cur = conn.cursor()
cur.execute(q)

subsegment = xray_recorder.current_segment().subsegments[0]
assert subsegment.name == 'execute'
sql = subsegment.sql
assert sql['database_type'] == 'PostgreSQL'
assert sql['user'] == dsn['user']
assert sql['url'] == url
assert sql['database_version']


def test_execute_dsn_string():
q = 'SELECT 1'
with testing.postgresql.Postgresql() as postgresql:
Expand Down

0 comments on commit 314a36b

Please sign in to comment.