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.
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 e15a5a6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion cid/cursor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.conf import settings
from .locals import get_cid


Expand All @@ -24,10 +25,11 @@ def __exit__(self, type, value, traceback):
self.close()

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

# The following methods cannot be implemented in __getattr__, because the
Expand Down
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_PREFIX='correlation_id=')
@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 e15a5a6

Please sign in to comment.