Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(exesql): serialize DATE/TIME columns for canvas SSE JSON (#19266)

leilei3167aadc4d7e7ec7
diff --git a/agent/tools/exesql.py b/agent/tools/exesql.py
index 11359755b4..0bd4d25ad3 100644
--- a/agent/tools/exesql.py
+++ b/agent/tools/exesql.py
@@ -16,9 +16,13 @@
import contextlib
import json
import logging
+import math
import os
import re
from abc import ABC
+from datetime import date, datetime, time
+from decimal import Decimal
+
import pandas as pd
import pymysql
import psycopg2
@@ -28,6 +32,34 @@ from common.connection_utils import timeout
from common.ssrf_guard import assert_host_is_safe
+def convert_decimals(obj):
+ """Make ExeSQL row values JSON-serializable.
+
+ SQL drivers may yield Decimal and plain date/datetime/time objects that
+ are not JSON-safe (object-dtype DATE columns skip the datetime64 path).
+ Recurse through dict/list the same way as before.
+ """
+ if isinstance(obj, float):
+ # Handle NaN and Infinity which are not valid JSON values
+ if math.isnan(obj) or math.isinf(obj):
+ return None
+ return obj
+ if isinstance(obj, Decimal):
+ return float(obj)
+ # datetime subclasses date — check datetime first and truncate to YYYY-MM-DD.
+ if isinstance(obj, datetime):
+ return obj.strftime("%Y-%m-%d")
+ if isinstance(obj, date):
+ return obj.isoformat()
+ if isinstance(obj, time):
+ return obj.isoformat()
+ if isinstance(obj, dict):
+ return {k: convert_decimals(v) for k, v in obj.items()}
+ if isinstance(obj, list):
+ return [convert_decimals(item) for item in obj]
+ return obj
+
+
class ExeSQLParam(ToolParamBase):
"""
Define the ExeSQL component parameters.
@@ -75,23 +107,6 @@ class ExeSQL(ToolBase, ABC):
if self.check_if_canceled("ExeSQL processing"):
return
- def convert_decimals(obj):
- from decimal import Decimal
- import math
-
- if isinstance(obj, float):
- # Handle NaN and Infinity which are not valid JSON values
- if math.isnan(obj) or math.isinf(obj):
- return None
- return obj
- if isinstance(obj, Decimal):
- return float(obj) # 或 str(obj)
- elif isinstance(obj, dict):
- return {k: convert_decimals(v) for k, v in obj.items()}
- elif isinstance(obj, list):
- return [convert_decimals(item) for item in obj]
- return obj
-
sql = kwargs.get("sql")
if not sql:
raise Exception("SQL for `ExeSQL` MUST not be empty.")
diff --git a/test/unit_test/agent/tools/test_exesql_convert_decimals.py b/test/unit_test/agent/tools/test_exesql_convert_decimals.py
new file mode 100644
index 0000000000..76cac7244f
--- /dev/null
+++ b/test/unit_test/agent/tools/test_exesql_convert_decimals.py
@@ -0,0 +1,120 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Unit tests for ExeSQL convert_decimals JSON serialization helpers.
+
+Plain ``datetime.date`` / ``datetime`` / ``time`` values from SQL DATE/TIME
+columns can survive as Python objects and must be serialized before canvas SSE
+``json.dumps`` (issue #19250). ``datetime`` truncates to ``YYYY-MM-DD``;
+``date`` / ``time`` use isoformat.
+"""
+
+import importlib.util
+import json
+import math
+import sys
+import types
+from datetime import date, datetime, time
+from decimal import Decimal
+from pathlib import Path
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[4]
+
+
+def _load_exesql_module():
+ with pytest.MonkeyPatch.context() as mp:
+ for name in ("pandas", "psycopg2", "pyodbc", "pymysql"):
+ if name not in sys.modules:
+ mod = types.ModuleType(name)
+ mod.connect = lambda *a, **k: None
+ mp.setitem(sys.modules, name, mod)
+
+ base = types.ModuleType("agent.tools.base")
+
+ class _ToolParamBase:
+ def __init__(self):
+ pass
+
+ class _ToolBase:
+ def __init__(self, *a, **k):
+ pass
+
+ base.ToolParamBase = _ToolParamBase
+ base.ToolBase = _ToolBase
+ base.ToolMeta = dict
+ for pkg in ("agent", "agent.tools"):
+ if pkg not in sys.modules:
+ mp.setitem(sys.modules, pkg, types.ModuleType(pkg))
+ mp.setitem(sys.modules, "agent.tools.base", base)
+
+ conn_utils = types.ModuleType("common.connection_utils")
+ conn_utils.timeout = lambda *a, **k: lambda f: f
+ mp.setitem(sys.modules, "common.connection_utils", conn_utils)
+
+ ssrf = types.ModuleType("common.ssrf_guard")
+ ssrf.assert_host_is_safe = lambda h: h
+ mp.setitem(sys.modules, "common.ssrf_guard", ssrf)
+
+ spec = importlib.util.spec_from_file_location("exesql_convert_uut", _REPO_ROOT / "agent" / "tools" / "exesql.py")
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+_exesql_mod = _load_exesql_module()
+convert_decimals = _exesql_mod.convert_decimals
+
+
+def test_convert_decimals_date_datetime_time():
+ # datetime must truncate to YYYY-MM-DD; plain date/time keep isoformat.
+ payload = {
+ "start_date": date(2026, 7, 27),
+ "ts": datetime(2026, 7, 27, 14, 30, 0),
+ "t": time(9, 15, 30),
+ }
+ out = convert_decimals(payload)
+ assert out == {
+ "start_date": "2026-07-27",
+ "ts": "2026-07-27",
+ "t": "09:15:30",
+ }
+ json.dumps(out) # must not raise
+
+
+def test_convert_decimals_decimal_and_nan_still_work():
+ payload = {
+ "amount": Decimal("12.34"),
+ "bad": float("nan"),
+ "inf": float("inf"),
+ "ok": 1.5,
+ }
+ out = convert_decimals(payload)
+ assert out["amount"] == pytest.approx(12.34)
+ assert out["bad"] is None
+ assert out["inf"] is None
+ assert out["ok"] == 1.5
+ json.dumps(out)
+
+
+def test_convert_decimals_recurses_lists():
+ rows = [{"d": date(2026, 7, 28), "n": Decimal("1")}, [date(2026, 1, 1), math.nan]]
+ out = convert_decimals(rows)
+ assert out == [{"d": "2026-07-28", "n": 1.0}, ["2026-01-01", None]]
+ json.dumps(out)