Skip to content

Commit

Permalink
enable to customize SQL comment prefix
Browse files Browse the repository at this point in the history
In our use case, it would be very handy to be able to have the SQL
comments formatted as correlation_id=XXX correlation_id=YYY (we may have
more than one cid for the same request).
We are using Splunk and this would provide auto-indexing for the
correlation_id field.
  • Loading branch information
Sébastien Diemer committed Feb 19, 2018
1 parent 862fab2 commit 47ba425
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
10 changes: 9 additions & 1 deletion cid/cursor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from django.conf import settings
from .locals import get_cid


def _base_comment_formatter(cid):
return 'cid: {}'.format(cid)


class CidCursorWrapper(object):
"""
A cursor wrapper that attempts to add a cid comment to each query
Expand All @@ -24,10 +29,13 @@ def __exit__(self, type, value, traceback):
self.close()

def add_comment(self, sql):
cid_sql_formatter = getattr(
settings, 'CID_SQL_COMMENT_FORMATTER', _base_comment_formatter
)
cid = get_cid()
if cid:
cid = cid.replace('/*', '\/\*').replace('*/', '\*\/')
return "/* cid: {} */\n{}".format(cid, sql)
return "/* {} */\n{}".format(cid_sql_formatter(cid), sql)
return sql

# The following methods cannot be implemented in __getattr__, because the
Expand Down
4 changes: 4 additions & 0 deletions docs/settings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ Settings
``CID_GENERATE``
Tell the cid middleware to generate a correlation id if it doesn't
already exist. Default value: ``False``.

``CID_SQL_COMMENT_FORMATTER``
Function taking a cid as argument and returning the str that will be
added as a SQL comment. Default returned value: ``cid: MY_CID``.
11 changes: 11 additions & 0 deletions tests/test_cursor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.test import TestCase
from django.test.utils import override_settings
from mock import Mock, patch

from cid.cursor import CidCursorWrapper
Expand All @@ -21,6 +22,16 @@ def test_adds_comment(self, get_cid):
self.cursor_wrapper.add_comment("SELECT 1;")
)

@override_settings(CID_SQL_COMMENT_FORMATTER=lambda cid: 'correlation_id={}'.format(cid))
@patch('cid.cursor.get_cid')
def test_adds_comment_setting_overriden(self, get_cid):
get_cid.return_value = 'testing-cursor'
expected = "/* correlation_id=testing-cursor */\nSELECT 1;"
self.assertEqual(
expected,
self.cursor_wrapper.add_comment("SELECT 1;")
)

@patch('cid.cursor.get_cid')
def test_no_comment_when_cid_is_none(self, get_cid):
get_cid.return_value = None
Expand Down

0 comments on commit 47ba425

Please sign in to comment.