Skip to content

[Bug]: UNION of a DATE and a TIME column is typed DATE and drops the time (MySQL: DATETIME) #31913

Closed

Description

@MatrixAdventurer

问题描述

UNION 的两个分支分别是 DATE 和 TIME 时,MO 把结果列定成 DATE,TIME 分支被转成"当天日期",时间部分整个丢掉。MySQL 把这种组合合并成 DATETIME,时间部分保留。

后果:

  • UNION ALL 返回的 TIME 值全都变成同一个日期(例如 2026-10-30),数据丢失。
  • UNION(去重)会把本来不同的时间值合并成一行,行数变少。
  • CREATE TABLE ... AS SELECT ... UNION ... 建出的列是 date,写入的数据也丢了时间。

同样的 DATE/TIME 组合在 CASE 里 MO 能得出正确的 DATETIME,只有 UNION 的类型推导不对。

环境

  • 分支:main(c32e75a2,2026-10-30)
  • 对照:MySQL 8.4.9;两边 curdate() 都是 2026-10-30

复现步骤

create table a (d date);
create table b (t time);
insert into a values ('2024-01-01');
insert into b values ('10:30:00'), ('23:00:00');
select d as x from a union all select t from b;
select count(*) from (select d as x from a union select t from b) u;
create table c as select d as x from a union all select t from b;
show create table c;
select case when 1 = 0 then d else time'10:30:00' end from a;   -- 对照:MO 正确

实际结果(MO)

union all  -> 2026-10-30 / 2026-10-30 / 2024-01-01
union 去重 -> count(*) = 2
show create table c -> `x` date DEFAULT NULL
case ...   -> 2026-10-30 10:30:00

期望结果(MySQL 8.4.9)

union all  -> 2024-01-01 00:00:00 / 2026-10-30 10:30:00 / 2026-10-30 23:00:00
union 去重 -> count(*) = 3
show create table c -> `x` datetime DEFAULT NULL
case ...   -> 2026-10-30 10:30:00

本操作由 LW 授权的 Grok Bot 智能体执行。

Activity

  1. added
    kind/bug
    on Oct 30, 2026
  2. MatrixAdventurer commented on Nov 1, 2026

    @MatrixAdventurer
    ContributorAuthor

    Proposed fix based on 4d18136d9274f8b8e1b960b1096a97e89a274d6c.

    Resolve a set-operation column containing both DATE and TIME as DATETIME, retaining the widest fractional-second precision. Other input combinations keep their existing resolution path. The regression coverage includes both branch orders, UNION DISTINCT, NULL branches, INTERSECT/EXCEPT, CTAS, and TIME(6).

    Validation:

    • On the unmodified base, the embedded SQL reproduction returned the same date for both TIME values, and the planner selected DATE.
    • With both proposed fixes applied, MO_TEST_CLUSTER_TCP_ONLY=1 go test -p 2 ./pkg/tests/issues -run 'TestIssue31913UnionDateAndTime|TestIssue31882ValuesSubqueryAndNull' -count=1 -timeout=10m passed, including CTAS and fractional seconds.
    • With both fixes applied, go test -p 2 ./pkg/sql/plan -count=1 -timeout=10m passed.
    • The DATE/TIME planner regression also passed with the other proposed fix replaced by its base version. The patch applies cleanly on its own and in either order with the patch for [Bug]: INSERT VALUES with a scalar subquery and a bare NULL in one column panics: unexpect type ANY for function vector.GetUnionFunction #31882.

    Complete patch (git apply):

    diff --git a/pkg/sql/plan/query_builder.go b/pkg/sql/plan/query_builder.go
    index 04c06d5..a22d25d 100644
    --- a/pkg/sql/plan/query_builder.go
    +++ b/pkg/sql/plan/query_builder.go
    @@ -783,6 +783,31 @@ func setOperationPureCharCommonType(source []types.Type) (types.Type, bool) {
     	return result, true
     }
     
    +// DATE and TIME need a DATETIME result to retain both domains in a set
    +// operation. NULL branches have already been removed from source.
    +func setOperationDateTimeCommonType(source []types.Type) (types.Type, bool) {
    +	hasDate, hasTime := false, false
    +	var scale int32
    +	for _, typ := range source {
    +		switch typ.Oid {
    +		case types.T_date:
    +			hasDate = true
    +		case types.T_time:
    +			hasTime = true
    +		case types.T_datetime, types.T_timestamp:
    +		default:
    +			return types.Type{}, false
    +		}
    +		if typ.Scale > scale {
    +			scale = typ.Scale
    +		}
    +	}
    +	if !hasDate || !hasTime {
    +		return types.Type{}, false
    +	}
    +	return types.New(types.T_datetime, scale, scale), true
    +}
    +
     // Fixed-width binary branches must share one padded representation before a
     // set operation compares or materializes their rows. A nonpositive width
     // denotes an unspecified bound, so it must remain unbounded rather than
    @@ -4899,7 +4924,9 @@ func (builder *QueryBuilder) buildUnionWithResultLen(
     			var targetArgType types.Type
     			pureBinaryType, pureFixedBinary := setOperationPureBinaryCommonType(tmpArgsType)
     			mixedTextBinaryType, mixedTextBinary := function.MixedTextBinaryCommonType(tmpArgsType)
    -			if pureCharType, ok := setOperationPureCharCommonType(tmpArgsType); ok {
    +			if temporalType, ok := setOperationDateTimeCommonType(tmpArgsType); ok {
    +				targetArgType = temporalType
    +			} else if pureCharType, ok := setOperationPureCharCommonType(tmpArgsType); ok {
     				targetArgType = pureCharType
     			} else if pureFixedBinary {
     				targetArgType = pureBinaryType
    diff --git a/pkg/sql/plan/set_temporal_common_type_test.go b/pkg/sql/plan/set_temporal_common_type_test.go
    new file mode 100644
    index 0000000..cc588e5
    --- /dev/null
    +++ b/pkg/sql/plan/set_temporal_common_type_test.go
    @@ -0,0 +1,62 @@
    +// Copyright 2026 Matrix Origin
    +//
    +// 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.
    +
    +package plan
    +
    +import (
    +	"testing"
    +
    +	"github.com/matrixorigin/matrixone/pkg/container/types"
    +	"github.com/matrixorigin/matrixone/pkg/pb/plan"
    +	"github.com/stretchr/testify/require"
    +)
    +
    +func TestSetOperationDateTimeCommonType(t *testing.T) {
    +	for _, tc := range []struct {
    +		name, sql string
    +		kind      plan.Node_NodeType
    +		want      types.T
    +		scale     int32
    +	}{
    +		{"date-time", "select cast('2024-01-01' as date) union all select cast('10:30:00' as time)", plan.Node_UNION_ALL, types.T_datetime, 0},
    +		{"time-date", "select cast('10:30:00' as time) union all select cast('2024-01-01' as date)", plan.Node_UNION_ALL, types.T_datetime, 0},
    +		{"fractional-time", "select cast('2024-01-01' as date) union all select cast('10:30:00.123456' as time(6))", plan.Node_UNION_ALL, types.T_datetime, 6},
    +		{"null-branch", "select cast('2024-01-01' as date) union all select null union all select cast('10:30:00' as time)", plan.Node_UNION_ALL, types.T_datetime, 0},
    +		{"distinct", "select cast('10:30:00' as time) union select cast('2024-01-01' as date)", plan.Node_UNION, types.T_datetime, 0},
    +		{"intersect", "select cast('2024-01-01' as date) intersect select cast('10:30:00' as time)", plan.Node_INTERSECT, types.T_datetime, 0},
    +		{"except", "select cast('2024-01-01' as date) except select cast('10:30:00' as time)", plan.Node_MINUS, types.T_datetime, 0},
    +		{"time-control", "select cast('10:30:00.12' as time(2)) union all select cast('11:30:00' as time)", plan.Node_UNION_ALL, types.T_time, 2},
    +		{"date-control", "select cast('2024-01-01' as date) union all select cast('2025-01-01' as date)", plan.Node_UNION_ALL, types.T_date, 0},
    +	} {
    +		t.Run(tc.name, func(t *testing.T) {
    +			p, err := runOneStmt(NewMockOptimizer(true, newPlanTestProcess(t)), t, tc.sql)
    +			require.NoError(t, err)
    +			query := p.GetQuery()
    +			var setNode *plan.Node
    +			for _, node := range query.Nodes {
    +				if node.NodeType == tc.kind {
    +					setNode = node
    +				}
    +			}
    +			require.NotNil(t, setNode)
    +			require.Len(t, setNode.ProjectList, 1)
    +			require.Equal(t, int32(tc.want), setNode.ProjectList[0].Typ.Id)
    +			require.Equal(t, tc.scale, setNode.ProjectList[0].Typ.Scale)
    +			for _, child := range setNode.Children {
    +				require.Equal(t, int32(tc.want), query.Nodes[child].ProjectList[0].Typ.Id)
    +				require.Equal(t, tc.scale, query.Nodes[child].ProjectList[0].Typ.Scale)
    +			}
    +		})
    +	}
    +}
    diff --git a/pkg/tests/issues/issue_31913_test.go b/pkg/tests/issues/issue_31913_test.go
    new file mode 100644
    index 0000000..86cd8b4
    --- /dev/null
    +++ b/pkg/tests/issues/issue_31913_test.go
    @@ -0,0 +1,92 @@
    +// Copyright 2026 Matrix Origin
    +//
    +// 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.
    +
    +package issues
    +
    +import (
    +	"context"
    +	"database/sql"
    +	"fmt"
    +	"strings"
    +	"testing"
    +	"time"
    +
    +	"github.com/matrixorigin/matrixone/pkg/embed"
    +	"github.com/stretchr/testify/require"
    +)
    +
    +func TestIssue31913UnionDateAndTime(t *testing.T) {
    +	embed.RunSingleCNBaseClusterTests(t, func(cluster embed.Cluster) {
    +		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    +		defer cancel()
    +		cn, err := cluster.GetCNService(0)
    +		require.NoError(t, err)
    +		db, err := sql.Open("mysql", fmt.Sprintf("dump:111@tcp(127.0.0.1:%d)/", cn.GetServiceConfig().CN.Frontend.Port))
    +		require.NoError(t, err)
    +		defer db.Close()
    +		name := fmt.Sprintf("issue_31913_%d", time.Now().UnixNano())
    +		execSQLRequire(t, ctx, db, "create database "+name)
    +		defer execSQLMaybe(t, context.Background(), db, "drop database if exists "+name)
    +		execSQLRequire(t, ctx, db, "create table "+name+".dates (d date)")
    +		execSQLRequire(t, ctx, db, "create table "+name+".clocks (v time)")
    +		execSQLRequire(t, ctx, db, "insert into "+name+".dates values ('2024-01-01')")
    +		execSQLRequire(t, ctx, db, "insert into "+name+".clocks values ('10:30:00'),('23:00:00')")
    +		for _, query := range []string{
    +			"select d as x from " + name + ".dates union all select v from " + name + ".clocks",
    +			"select v as x from " + name + ".clocks union all select d from " + name + ".dates",
    +			"select d as x from " + name + ".dates union select v from " + name + ".clocks",
    +		} {
    +			rows, err := db.QueryContext(ctx, query)
    +			require.NoError(t, err, query)
    +			var values []string
    +			for rows.Next() {
    +				var value string
    +				require.NoError(t, rows.Scan(&value))
    +				values = append(values, value)
    +			}
    +			require.NoError(t, rows.Err())
    +			require.NoError(t, rows.Close())
    +			require.Len(t, values, 3, query)
    +			var morning, evening bool
    +			for _, value := range values {
    +				morning = morning || strings.HasSuffix(value, "10:30:00")
    +				evening = evening || strings.HasSuffix(value, "23:00:00")
    +			}
    +			require.True(t, morning, "%s: %v", query, values)
    +			require.True(t, evening, "%s: %v", query, values)
    +		}
    +
    +		execSQLRequire(t, ctx, db, "create table "+name+".copy as select d as x from "+name+".dates union all select v from "+name+".clocks")
    +		var dataType string
    +		err = db.QueryRowContext(ctx, "select data_type from information_schema.columns where table_schema=? and table_name='copy' and column_name='x'", name).Scan(&dataType)
    +		require.NoError(t, err)
    +		require.Equal(t, "datetime", strings.ToLower(dataType))
    +		var count int
    +		err = db.QueryRowContext(ctx, "select count(distinct x) from "+name+".copy").Scan(&count)
    +		require.NoError(t, err)
    +		require.Equal(t, 3, count)
    +
    +		rows, err := db.QueryContext(ctx, "select cast('2024-01-01' as date) as x union all select cast('10:30:00.123456' as time(6))")
    +		require.NoError(t, err)
    +		defer rows.Close()
    +		var fractionalTime bool
    +		for rows.Next() {
    +			var value string
    +			require.NoError(t, rows.Scan(&value))
    +			fractionalTime = fractionalTime || strings.HasSuffix(value, "10:30:00.123456")
    +		}
    +		require.NoError(t, rows.Err())
    +		require.True(t, fractionalTime)
    +	})
    +}
  3. assigned and unassigned on Nov 7, 2026
  4. added a commit that references this issue on Nov 8, 2026
    7a73a73
  5. XuPeng-SH commented on Nov 8, 2026

    @XuPeng-SH
    Contributor

    QA 交接(main,尚非验收通过)

    关联修复 #32350 已于 2026-11-08 00:02:40 UTC 合入 main。

    • Merge SHA:7a73a7395506a04e2555422fee7dd5c766416f0f
    • 最终 PR head:c983301ee24fb6732b218d9015d1b8a81652de8d

    本单覆盖:set-operation 同列同时含 DATE 和 TIME、其余非 NULL 输入也为时态类型时,公共类型改为保留最大 fractional-second precision 的 DATETIME,再沿现有 cast 路径统一各分支。NULL 分支不决定公共类型;DATE-only、TIME-only 或含非时态输入的组合保留原类型推导路径。它针对原先 TIME 被截成日期及 DISTINCT/CTAS 丢失信息,不宣称所有时态/时区转换都改变或已验证。

    证据与限制:

    • 作者报告最终源上的 planner/value_scan 定向测试通过,并报告同一编译 fixture 的两项问题场景通过(父测试 6.14s);BIT 公开 SQL 用例返回 20101,随后同一连接可正常写入 '[1,2,3]',l2_distance 为 0。17 个 RED 子测试是替换此前 PR 自身 producer 的单文件 overlay 对照,不是 clean-main 测试。vecf64 定向测试使用本地 resolver twin,不等同于公开 SQL 验证。
    • 作者报告 336 包依赖闭包的 molint/golangci-lint 均为 0,不是全仓覆盖率。最终 head 的 review 5815662261 已批准,明确关闭旧 BIT P2,并复用该 head 的 build、UT/coverage、SCA 和两项 multi-CN BVT 成功记录。Mergify 报告 CI Required 成功、未解决线程为 0;因已 up-to-date,合并队列没有重新运行 CI。
    • 本轮仅核对远端正文、完整评论及最终 diff,未运行本地 Go/SQL/race/BVT,也未独立取得作者原始日志或 CI 逐用例日志。旧 issue 中基于 4d18136 的 proposed-fix 测试不冒充最终 merge 实测。

    当前完整讨论未见适用于最终合并修复的已验证反例或未完成开发 follow-up,交给 @Ariznawlll 验证,保持 issue 开放。请在包含上述 merge 的构建上复验 DATE/TIME 两种分支顺序的完整行值和类型、UNION ALL 与 DISTINCT(三行不合并成两行)、CTAS 的 DATETIME schema 与数据、TIME(6) 的六位小数、NULL 分支及 INTERSECT/EXCEPT;同类 DATE-only/TIME-only 和 CASE 作对照。TIME 转 DATETIME 的日期部分沿现有转换语义,测试需记录会话日期/时区,避免跨午夜硬编码。不要只以行数或显示后缀代替完整值及元数据核验。

  6. slyunnn commented on Nov 10, 2026

    @slyunnn

    Regression and extended verification for #31913 (2026-11-10)

    Verification Environment

    • Frozen latest origin/main at test start, 11d2e1ef7e1b3ed3a20e6d7f29f912e55118db5b, fix(python): reconnect ORM export shortcuts to current exporters (#32447).
    • Freshly built CPU binary, matching native-library provenance, and runtime git_version()=11d2e1ef7e at every endpoint. macOS 26.6, arm64, Go 1.27.1.
    • Complete co-hosted topology of 2 CN / 1 TN / 1 Log service / Proxy, launched in one service process. Proxy 6001, CN1 16001 and CN2 16002 were reachable. Original and extended SQL actually ran through each endpoint.
    • PyMySQL 1.1.2 using MySQL text protocol (COM_QUERY).

    What Was Covered

    • OK — Replayed the original DATE-table and TIME-table query through every endpoint. Full returned values preserve the date row at midnight and the TIME rows widened using the recorded session date.
    • OK — Both branch orders, UNION ALL, UNION DISTINCT, duplicate TIME values, and the original distinct count of 3.
    • OK — TIME(6) microseconds, NULL, empty branches, INTERSECT, and EXCEPT.
    • OK — Both CTAS branch orders persist DATETIME(6) metadata and complete values. The maintained test normalizes current-date-dependent output while separately asserting time components, original DATE content and schema.
    • OK — DATE-only/TIME-only CTAS retain their own types, and a mixed DATE/TIME CASE expression supplies a conversion control. Session timezone was +00:00, and the session date was checked before and after each endpoint run.
    • Not covered — A deliberate midnight/timezone-transition stress run. All current-date-dependent checks completed without crossing a date boundary.

    Findings

    • Associated fix 7a73a7395506a04e2555422fee7dd5c766416f0f, fix(sql): preserve typed VALUES branches and DATE/TIME set results. The merge is an ancestor of the frozen main commit. PR #32350
    • DATE/TIME set columns resolve to DATETIME with the widest fractional-second precision. Deduplication and CTAS preserve the widened values. This is a type/value acceptance result.

    MOTR / BVT Coverage

    • Added suites/14_issue_regression/t/issue_31913_date_time_union.test and the matching .result. Recording passed, followed by 2 successful replays through each of the 3 endpoints.
    • Independent branch test/issue-31913-date-time-union, source commit d7cd0d686658d21ed435adf5910de130c91e4c44, pushed and remote/upstream verified. Weekly cherry-pick d2eec820a7a329d076caa968f7c3fbac533017f7 is included in the existing weekly summary. MOTR PR #321
    • Combined weekly tests passed with -j 5 --repeat 2, 7 isolated cases, 14/14 executions per endpoint and 42/42 total. Databases and connections are independent, with session-local settings.
    • Focused product tests recorded 142 test/subtest passes. Complete external, function and value_scan packages recorded 18,182 passes with 1 unrelated Arrow/MinIO integration skip. These counts include subtests.

    Final Conclusion

    Fixed for the issue contract on the verified main build and topology.

    Large-data regression — Not required. Common-type resolution, fractional precision, deduplication and CTAS metadata depend on operand types and values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions