This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 27ae47166e [python] SQL CLI JSON output fails for TIMESTAMP and loses
BIGINT precision (#11107)
27ae47166e is described below
commit 27ae47166e32d0b22e1896485d581fb99fb19ff1
Author: Ran Tao <[email protected]>
AuthorDate: Thu Nov 12 17:27:32 2026 +0800
[python] SQL CLI JSON output fails for TIMESTAMP and loses BIGINT precision
(#11107)
---
docs/docs/pypaimon/sql.md | 4 ++
paimon-python/pypaimon/cli/cli_sql.py | 37 ++++++++++--
paimon-python/pypaimon/tests/cli_sql_test.py | 90 ++++++++++++++++++++++++++++
3 files changed, 127 insertions(+), 4 deletions(-)
diff --git a/docs/docs/pypaimon/sql.md b/docs/docs/pypaimon/sql.md
index 89ddb7572d..dba81ac413 100644
--- a/docs/docs/pypaimon/sql.md
+++ b/docs/docs/pypaimon/sql.md
@@ -176,6 +176,10 @@ paimon sql "SELECT city, COUNT(*) AS cnt FROM users GROUP
BY city ORDER BY cnt D
paimon sql "SELECT * FROM users LIMIT 5" --format json
```
+JSON output represents timestamps as ISO 8601 strings, preserving fractional
+seconds (up to nanosecond precision) and timezone offsets when present.
+SQL `NULL` values are represented as JSON `null`.
+
### Interactive REPL
Start an interactive SQL session by running `paimon sql` without a query
argument. The REPL supports arrow keys for line editing, and command history is
persisted across sessions in `~/.paimon_history`.
diff --git a/paimon-python/pypaimon/cli/cli_sql.py
b/paimon-python/pypaimon/cli/cli_sql.py
index f92d1846a1..27848f947f 100644
--- a/paimon-python/pypaimon/cli/cli_sql.py
+++ b/paimon-python/pypaimon/cli/cli_sql.py
@@ -25,6 +25,7 @@ import os
import re
import sys
import time
+from datetime import datetime
import pyarrow as pa
@@ -166,18 +167,46 @@ def _execute_query(ctx, query, output_format):
def _print_table(table, output_format, elapsed=None):
"""Print a PyArrow Table in the requested format."""
- df = table.to_pandas()
if output_format == 'json':
import json
- print(json.dumps(df.to_dict(orient='records'), ensure_ascii=False))
+ # Keep Arrow scalars: to_pylist() loses the minimum nanosecond
timestamp.
+ names = table.column_names
+ rows = [dict(zip(names, row)) for row in zip(*table.columns)]
+ print(json.dumps(rows, ensure_ascii=False, default=_json_default))
else:
- print(df.to_string(index=False))
+ print(table.to_pandas().to_string(index=False))
if elapsed is not None:
- row_count = len(df)
+ row_count = table.num_rows
print(f"({row_count} {'row' if row_count == 1 else 'rows'} in
{elapsed:.2f}s)")
+def _json_default(value):
+ """Serialize Arrow values and timestamps without losing precision or
nulls."""
+ if isinstance(value, pa.Scalar):
+ if not value.is_valid:
+ return None
+ if (isinstance(value, pa.TimestampScalar)
+ and value.type.unit == 'ns' and value.value == -(2 ** 63)):
+ # Pandas reserves -2**63 ns for NaT, but Arrow can store it as a
valid timestamp.
+ microseconds, nanoseconds = divmod(value.value, 1000)
+ timestamp = pa.scalar(microseconds, type=pa.timestamp('us',
tz=value.type.tz)).as_py()
+ fraction = f'.{timestamp.microsecond:06d}'
+ return timestamp.isoformat().replace(fraction,
f'{fraction}{nanoseconds:03d}', 1)
+ if isinstance(value, pa.StructScalar):
+ return dict(value.items())
+ if isinstance(value, pa.MapScalar):
+ return [(entry[0], entry[1]) for entry in value.values]
+ if isinstance(value, pa.ListScalar):
+ return list(value.values)
+ if isinstance(value, pa.DictionaryScalar):
+ return value.value
+ return value.as_py()
+ if isinstance(value, datetime):
+ return value.isoformat()
+ raise TypeError(f"Object of type {type(value).__name__} is not JSON
serializable")
+
+
def _read_multiline_query():
"""Read a potentially multi-line SQL query, terminated by ';'.
diff --git a/paimon-python/pypaimon/tests/cli_sql_test.py
b/paimon-python/pypaimon/tests/cli_sql_test.py
new file mode 100644
index 0000000000..3a6c4a02f0
--- /dev/null
+++ b/paimon-python/pypaimon/tests/cli_sql_test.py
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+
+import json
+from datetime import datetime
+
+import pyarrow as pa
+import pytest
+
+from pypaimon.cli import cli_sql
+
+
[email protected]('unit,value,timezone,expected', [
+ ('us', 1123456, None, '1970-01-01T00:00:01.123456'),
+ ('ns', 1123456789, 'Asia/Shanghai', '1970-01-01T08:00:01.123456789+08:00'),
+ ('ns', -(2 ** 63), None, '1677-09-21T00:12:43.145224192'),
+ ('ns', -(2 ** 63), '+08:00', '1677-09-21T08:12:43.145224192+08:00'),
+ ('ns', -(2 ** 63), '-05:00', '1677-09-20T19:12:43.145224192-05:00'),
+])
+def test_json_timestamp_precision_and_timezone(capsys, unit, value, timezone,
expected):
+ table = pa.table({'ts': pa.array([value, None], type=pa.timestamp(unit,
tz=timezone))})
+
+ cli_sql._print_table(table, 'json')
+
+ assert json.loads(capsys.readouterr().out) == [
+ {'ts': expected},
+ {'ts': None},
+ ]
+
+
+def test_json_nullable_bigint(capsys):
+ table = pa.table({
+ 'id': pa.array([9007199254740993, None], type=pa.int64()),
+ 'name': ['时间戳', None],
+ })
+
+ cli_sql._print_table(table, 'json')
+
+ output = capsys.readouterr().out
+ assert '时间戳' in output
+ assert json.loads(output) == [
+ {'id': 9007199254740993, 'name': '时间戳'},
+ {'id': None, 'name': None},
+ ]
+
+
+def test_json_minimum_timestamp_in_containers(capsys):
+ timestamp_type = pa.timestamp('ns', tz='UTC')
+ minimum = -(2 ** 63)
+ timestamps = pa.array([minimum, None], type=timestamp_type)
+ table = pa.table({
+ 'struct': pa.StructArray.from_arrays([timestamps], ['ts']),
+ 'list': pa.array([[minimum, None], None],
type=pa.list_(timestamp_type)),
+ 'map': pa.array([[('ts', minimum), ('null', None)], None],
+ type=pa.map_(pa.string(), timestamp_type)),
+ 'dictionary': pa.DictionaryArray.from_arrays(pa.array([0, None]),
timestamps.slice(0, 1)),
+ })
+
+ cli_sql._print_table(table, 'json')
+
+ expected = '1677-09-21T00:12:43.145224192+00:00'
+ assert json.loads(capsys.readouterr().out) == [
+ {'struct': {'ts': expected}, 'list': [expected, None],
+ 'map': [['ts', expected], ['null', None]], 'dictionary': expected},
+ {'struct': {'ts': None}, 'list': None, 'map': None, 'dictionary':
None},
+ ]
+
+
+def test_table_timestamp_output(capsys):
+ table = pa.table({'ts': [datetime(2026, 11, 11, 16, 13, 47)]})
+
+ cli_sql._print_table(table, 'table', elapsed=0.25)
+
+ assert [line.strip() for line in capsys.readouterr().out.splitlines()] == [
+ 'ts', '2026-11-11 16:13:47', '(1 row in 0.25s)',
+ ]