feat: include Trace ID in all SQL queries

This commit is contained in:
Ankush Menat 2023-08-19 20:17:46 +05:30
parent fe820ae8c8
commit 59e49d89fe
3 changed files with 17 additions and 1 deletions

View file

@ -29,6 +29,7 @@ from frappe.database.utils import (
is_query_type,
)
from frappe.exceptions import DoesNotExistError, ImplicitCommitError
from frappe.monitor import get_trace_id
from frappe.query_builder.functions import Count
from frappe.utils import CallbackManager
from frappe.utils import cast as cast_fieldtype
@ -113,6 +114,10 @@ class Database:
self.before_rollback = CallbackManager()
self.after_rollback = CallbackManager()
self._trace_comment = ""
if trace_id := get_trace_id():
self._trace_comment = f" /* FRAPPE_TRACE_ID: {trace_id} */"
# self.db_type: str
# self.last_query (lazy) attribute of last sql query executed
@ -223,7 +228,9 @@ class Database:
values = None
elif not isinstance(values, (tuple, dict, list)):
values = (values,)
query, values = self._transform_query(query, values)
query += self._trace_comment
try:
self._cursor.execute(query, values)

View file

@ -32,6 +32,12 @@ def add_data_to_monitor(**kwargs) -> None:
frappe.local.monitor.add_custom_data(**kwargs)
def get_trace_id() -> str | None:
"""Get unique ID for current transaction."""
if monitor := getattr(frappe.local, "monitor", None):
return monitor.data.uuid
def log_file():
return os.path.join(frappe.utils.get_bench_path(), "logs", "monitor.json.log")

View file

@ -100,7 +100,10 @@ class TestRecorder(FrappeTestCase):
for query, call in zip(queries, request["calls"]):
self.assertEqual(
call["query"], sqlparse.format(query[sql_dialect].strip(), keyword_case="upper", reindent=True)
call["query"],
sqlparse.format(
query[sql_dialect].strip(), keyword_case="upper", reindent=True, strip_comments=True
),
)
def test_duplicate_queries(self):