sqlmesh
sqlmesh copied to clipboard
Fix MySQL DELETE using CONCAT_WS preventing index usage
Summary
Fixes #5711
- Override
_replace_by_keyinMySQLEngineAdapterto use a JOIN-based DELETE for composite keys instead ofCONCAT_WS('__SQLMESH_DELIM__', ...)which prevents MySQL/MariaDB from using indexes - Single-key DELETEs continue to use the existing efficient
IN-based approach since indexes work fine for single columns - Add tests verifying both composite key (JOIN-based) and single key (IN-based) DELETE behavior
Problem
When using INCREMENTAL_BY_UNIQUE_KEY with MySQL/MariaDB and composite keys, SQLMesh generates:
DELETE FROM `target_table`
WHERE CONCAT_WS('__SQLMESH_DELIM__', `col1`, `col2`)
IN (SELECT CONCAT_WS('__SQLMESH_DELIM__', `col1`, `col2`) FROM `temp_table`)
MySQL cannot use indexes on CONCAT_WS() expressions, causing full table scans that lead to multi-hour query times and connection timeouts on larger tables.
Fix
For composite keys, generate a JOIN-based DELETE that allows MySQL to use existing indexes:
DELETE `_target`
FROM `target_table` AS `_target`
INNER JOIN `temp_table` AS `_temp`
ON `_target`.`col1` = `_temp`.`col1`
AND `_target`.`col2` = `_temp`.`col2`
This changes the EXPLAIN plan from type=ALL (full scan) to type=ref (index lookup), reducing query times from hours to seconds.
Test plan
- [x] New test
test_replace_by_key_composite_uses_join_deleteverifies JOIN-based DELETE for composite keys - [x] New test
test_replace_by_key_single_key_uses_inverifies single-key DELETEs still use the IN-based approach - [x] Existing MySQL adapter tests pass
- [x] Existing mixin tests pass
- [x] Existing base engine adapter tests pass
@hashwnath Thanks for the fix!
A few things before merge:
- Do you think it's worth adding a test with a 3-column composite key (matching the issue scenario)? And a test for expression-based composite keys (e.g. DATE_TRUNC + column), since insert_overwrite_by_partition also hits _replace_by_key?
Let me know if I'm missing anything!