You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Bug]: UNION of a DATE and a TIME column is typed DATE and drops the time (MySQL: DATETIME) #31913
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
复现步骤
createtablea (d date);
createtableb (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 allselect t from b;
selectcount(*) from (select d as x from a unionselect t from b) u;
createtablecasselect d as x from a union allselect 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
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.
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)+ })+}
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/TIMECASE 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.
Activity
MatrixAdventurer commentedon Nov 1, 2026
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:
MO_TEST_CLUSTER_TCP_ONLY=1 go test -p 2 ./pkg/tests/issues -run 'TestIssue31913UnionDateAndTime|TestIssue31882ValuesSubqueryAndNull' -count=1 -timeout=10mpassed, including CTAS and fractional seconds.go test -p 2 ./pkg/sql/plan -count=1 -timeout=10mpassed.Complete patch (
git apply):fix(sql): preserve typed VALUES branches and DATE/TIME set results (#…
XuPeng-SH commentedon Nov 8, 2026
QA 交接(main,尚非验收通过)
关联修复 #32350 已于 2026-11-08 00:02:40 UTC 合入 main。
本单覆盖:set-operation 同列同时含 DATE 和 TIME、其余非 NULL 输入也为时态类型时,公共类型改为保留最大 fractional-second precision 的 DATETIME,再沿现有 cast 路径统一各分支。NULL 分支不决定公共类型;DATE-only、TIME-only 或含非时态输入的组合保留原类型推导路径。它针对原先 TIME 被截成日期及 DISTINCT/CTAS 丢失信息,不宣称所有时态/时区转换都改变或已验证。
证据与限制:
当前完整讨论未见适用于最终合并修复的已验证反例或未完成开发 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 的日期部分沿现有转换语义,测试需记录会话日期/时区,避免跨午夜硬编码。不要只以行数或显示后缀代替完整值及元数据核验。
refactor: integrate temporal index planning with shared owners (#32341)
slyunnn commentedon Nov 10, 2026
Regression and extended verification for #31913 (2026-11-10)
Verification Environment
origin/mainat test start,11d2e1ef7e1b3ed3a20e6d7f29f912e55118db5b,fix(python): reconnect ORM export shortcuts to current exporters (#32447).git_version()=11d2e1ef7eat every endpoint. macOS26.6,arm64, Go1.27.1.2 CN / 1 TN / 1 Log service / Proxy, launched in one service process. Proxy6001, CN116001and CN216002were reachable. Original and extended SQL actually ran through each endpoint.1.1.2using MySQL text protocol (COM_QUERY).What Was Covered
DATE-table andTIME-table query through every endpoint. Full returned values preserve the date row at midnight and theTIMErows widened using the recorded session date.UNION ALL,UNION DISTINCT, duplicateTIMEvalues, and the original distinct count of3.TIME(6)microseconds,NULL, empty branches,INTERSECT, andEXCEPT.CTASbranch orders persistDATETIME(6)metadata and complete values. The maintained test normalizes current-date-dependent output while separately asserting time components, originalDATEcontent and schema.DATE-only/TIME-onlyCTASretain their own types, and a mixedDATE/TIMECASEexpression supplies a conversion control. Session timezone was+00:00, and the session date was checked before and after each endpoint run.Findings
7a73a7395506a04e2555422fee7dd5c766416f0f,fix(sql): preserve typed VALUES branches and DATE/TIME set results. The merge is an ancestor of the frozen main commit. PR #32350DATE/TIMEset columns resolve toDATETIMEwith the widest fractional-second precision. Deduplication andCTASpreserve the widened values. This is a type/value acceptance result.MOTR / BVT Coverage
suites/14_issue_regression/t/issue_31913_date_time_union.testand the matching.result. Recording passed, followed by2successful replays through each of the3endpoints.test/issue-31913-date-time-union, source commitd7cd0d686658d21ed435adf5910de130c91e4c44, pushed and remote/upstream verified. Weekly cherry-pickd2eec820a7a329d076caa968f7c3fbac533017f7is included in the existing weekly summary. MOTR PR #321-j 5 --repeat 2,7isolated cases,14/14executions per endpoint and42/42total. Databases and connections are independent, with session-local settings.142test/subtest passes. Complete external, function and value_scan packages recorded18,182passes with1unrelated 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
CTASmetadata depend on operand types and values.