Bug #121843 Derived condition pushdown compares with a UNION block's DATE/ENUM type instead of the VARCHAR result type

Submitted: 20 Nov 1:05
Reporter: Ke Han Email Updates:
Status: Open Impact on me:
None 
Category:MySQL Server: Optimizer Severity:S2 (Serious)
Version:26.10.0 (trunk 06bcb0eb0ad), 8.4.13 OS:Ubuntu
Assigned to: CPU Architecture:Any

[20 Nov 1:05] Ke Han
Description:
A view or derived table built with UNION [ALL] or EXCEPT whose query blocks
select a DATE (or DATETIME, TIMESTAMP, TIME) or ENUM (or SET) column in one
block and a VARCHAR column in the other has a string result column: in the
example below, CREATE TABLE ... SELECT * FROM the view gives shipped
varchar(30) and status varchar(10). An outer WHERE on such a column is
therefore a string comparison.

With derived_condition_pushdown=on (the default), the outer predicate is
copied into every query block and the column is replaced by the block's own
column. In the DATE or ENUM block the copy is then evaluated with that
column's type instead of the string value the set operation returns:

- shipped >= '2024-1-1' becomes orders.shipped >= DATE'2024-01-01' (see the
  EXPLAIN), so the row with '2024-01-05' qualifies, although the string
  '2024-01-05' is smaller than '2024-1-1';
- shipped = '2024-1-5' matches the DATE 2024-01-05;
- status = 2 compares the ENUM member index (2 = 'paid'), while the view's
  value 'paid' compares to a number as 0;
- over an EXCEPT, WHERE x = 20240105 returns '2024-01-05', a row that the
  same derived table without the WHERE does not return at all.

The same query with the NO_DERIVED_CONDITION_PUSHDOWN hint, or the same
predicate on a table holding the view's rows, gives the string-comparison
result. The wrong results come without an error, and the date-literal
queries and the DELETE below give no warning. CREATE TABLE ... SELECT and
INSERT ... SELECT store the wrong rows, and
DELETE ... WHERE id IN (SELECT id FROM <view> WHERE ...) deletes rows that
the view's predicate does not match (two current orders in the example).
Views that combine a typed current table with an archive table that holds
the same data as text are a common pattern.

The hypergraph optimizer (hypergraph_optimizer=on) returns the same wrong
results. MySQL 8.4.13 returns the same results as 26.10.0.

How to repeat:
-- run with: mysql -uroot --table < file
CREATE DATABASE m207;
USE m207;
CREATE TABLE orders (id INT PRIMARY KEY, shipped DATE, status ENUM('new','paid','shipped'));
CREATE TABLE legacy_orders (id INT PRIMARY KEY, shipped VARCHAR(30), status VARCHAR(10));
INSERT INTO orders VALUES (1,'2024-01-05','paid'), (2,'2024-01-06','new'), (3,'2023-12-31','shipped');
INSERT INTO legacy_orders VALUES (101,'2024-01-05','paid'), (102,'2024-1-5','paid'), (103,'05/01/2024','new');
CREATE VIEW all_orders AS
  SELECT id, shipped, status FROM orders
  UNION ALL
  SELECT id, shipped, status FROM legacy_orders;

-- the view's columns are strings: shipped varchar(30), status varchar(10)
CREATE TABLE snapshot AS SELECT * FROM all_orders;
SHOW CREATE TABLE snapshot;

SELECT GROUP_CONCAT(id ORDER BY id) AS ids FROM all_orders WHERE shipped >= '2024-1-1';
SELECT /*+ NO_DERIVED_CONDITION_PUSHDOWN(all_orders) */ GROUP_CONCAT(id ORDER BY id) AS ids
  FROM all_orders WHERE shipped >= '2024-1-1';
SELECT GROUP_CONCAT(id ORDER BY id) AS ids FROM snapshot WHERE shipped >= '2024-1-1';
SELECT GROUP_CONCAT(id ORDER BY id) AS ids FROM all_orders WHERE shipped = '2024-1-5';
SELECT GROUP_CONCAT(id ORDER BY id) AS ids FROM snapshot WHERE shipped = '2024-1-5';
SELECT GROUP_CONCAT(id ORDER BY id) AS ids FROM all_orders WHERE status = 2;
SELECT GROUP_CONCAT(id ORDER BY id) AS ids FROM snapshot WHERE status = 2;
EXPLAIN FORMAT=TREE SELECT id FROM all_orders WHERE shipped >= '2024-1-1';

-- EXCEPT: the filtered result has a row that the unfiltered result does not have
SELECT x FROM (SELECT shipped AS x FROM orders EXCEPT SELECT shipped FROM legacy_orders) d;
SELECT x FROM (SELECT shipped AS x FROM orders EXCEPT SELECT shipped FROM legacy_orders) d
  WHERE x = 20240105;

CREATE TABLE report AS SELECT id, shipped FROM all_orders WHERE shipped >= '2024-1-1';
SELECT * FROM report ORDER BY id;
DELETE FROM orders WHERE id IN (SELECT id FROM all_orders WHERE shipped >= '2024-1-1');
SELECT * FROM orders;

Result on 26.10.0 (8.4.13 gives the same):
  SHOW CREATE TABLE snapshot:   `shipped` varchar(30), `status` varchar(10)
  all_orders WHERE shipped >= '2024-1-1':           1,2,102   <- wrong
  ... with NO_DERIVED_CONDITION_PUSHDOWN(all_orders): 102
  snapshot WHERE shipped >= '2024-1-1':             102
  all_orders WHERE shipped = '2024-1-5':            1,102     <- wrong
  snapshot WHERE shipped = '2024-1-5':              102
  all_orders WHERE status = 2:                      1         <- wrong
  snapshot WHERE status = 2:                        NULL (no rows)
  EXPLAIN:
    -> Table scan on all_orders  (cost=2.82..4.09 rows=2)
        -> Union all materialize  (cost=1.56..1.56 rows=2)
            -> Filter: (orders.shipped >= DATE'2024-01-01')  (cost=0.55 rows=1)
                -> Table scan on orders  (cost=0.55 rows=3)
            -> Filter: (legacy_orders.shipped >= '2024-1-1')  (cost=0.55 rows=1)
                -> Table scan on legacy_orders  (cost=0.55 rows=3)
  EXCEPT without WHERE:         2024-01-06, 2023-12-31
  EXCEPT WHERE x = 20240105:    2024-01-05                    <- wrong (expected: no rows)
  report:                       (1, 2024-01-05), (2, 2024-01-06), (102, 2024-1-5)   <- expected only 102
  orders after the DELETE:      (3, 2023-12-31, shipped)      <- orders 1 and 2 deleted

Expected: the string-comparison results that NO_DERIVED_CONDITION_PUSHDOWN
and the snapshot table give (102; 102; no rows; no rows for the EXCEPT;
report = 102 only; the DELETE removes nothing from orders). The manual
(Set Operations with UNION, INTERSECT, and EXCEPT) says that when the
blocks' column types differ, the result column's type takes all blocks into
account, and the restrictions listed for derived condition pushdown do not
include this case; pushdown should not change a query's result.

Suggested fix:
The only guard is in Item_field::is_valid_for_pushdown(). Its comment says
that pushdown is not done when the expression's type differs across the
query blocks of a set operation, but the check compares only
Item::result_type(), which is STRING_RESULT for DATE, DATETIME, TIMESTAMP,
TIME, ENUM, SET, CHAR and VARCHAR alike:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...

Condition_pushdown::make_cond_for_derived() clones the condition for each
query block of the set operation, and Item_field::replace_with_derived_expr()
replaces the derived table's column with a clone of the block's select-list
expression:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/sq...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/it...
so the comparison reads the DATE/ENUM column itself rather than its string
value in the set operation's result: numeric comparisons get 20240105 or the
member index, and the optimizer's constant folding turns '2024-1-1' into
DATE'2024-01-01' (the optimizer trace shows this under
"trivial_condition_removal" in the block). Comparing data_type() of each
block's expression with the derived column's type in is_valid_for_pushdown()
(not only result_type()), or wrapping the substituted expression in a cast to
the derived column's type, would fix it.

Workaround: the NO_DERIVED_CONDITION_PUSHDOWN hint, or CAST(shipped AS CHAR)
and CAST(status AS CHAR) in the view's typed block (with the casts the
queries above return 102 and no rows).

Portions of this website are copyright © 2001, 2002 The PHP Group

Page generated in 0.049 sec. using MySQL 8.4.7-u6-cloud

Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.