psycopg2 2.7 introduces the psycopg2.sql module, which "contains objects and functions useful to generate SQL dynamically, in a convenient and safe way."
http://initd.org/psycopg/docs/sql.html
Unfortunately, format_sql() doesn't know how to work with a 'Composed' object. So when we try to make use of this in a Django application, we get tracebacks from the sentry_sdk.
Here's a simple management command that illustrates the problem.
from django.core.management.base import BaseCommand
from django.db import connection
from psycopg2 import sql
class Command(BaseCommand):
def handle(self, *args, **options):
cursor = connection.cursor()
cursor.execute(sql.SQL("""
SELECT
%(my_param)s
"""), {
'my_param': 10,
})
Running it with sentry_sdk's DjangoIntegration() enabled produces the following error:
bdavis@257db183b518:/ph$ python manage.py example_error
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/ph/ph/phdb/management/commands/example_error.py", line 14, in handle
'my_param': 10,
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py", line 257, in execute
record_sql(sql, params)
File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py", line 224, in record_sql
real_sql, real_params = format_sql(sql, params)
File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py", line 206, in format_sql
sql = sql % conv
TypeError: unsupported operand type(s) for %: 'SQL' and '_FormatConverter'
Sentry is attempting to send 1 pending error messages
Waiting up to 2.0 seconds
Press Ctrl-C to quit
bdavis@257db183b518:/ph$
psycopg2 2.7 introduces the psycopg2.sql module, which "contains objects and functions useful to generate SQL dynamically, in a convenient and safe way."
http://initd.org/psycopg/docs/sql.html
Unfortunately, format_sql() doesn't know how to work with a 'Composed' object. So when we try to make use of this in a Django application, we get tracebacks from the sentry_sdk.
Here's a simple management command that illustrates the problem.
Running it with sentry_sdk's DjangoIntegration() enabled produces the following error: