cast numbers explictly as ints rather than adding 0 to them
This commit is contained in:
@ -46,6 +46,12 @@ class SelectSQLRewriter extends AbstractSQLRewriter
|
||||
|
||||
$sql = $this->ensureOrderByInSelect($sql);
|
||||
|
||||
// Handle +0 casting in order by
|
||||
// Regular expression to match the "ORDER BY" pattern
|
||||
$pattern = '/ORDER BY\s+([a-zA-Z0-9_]+)\.meta_value\s*\+\s*0/i';
|
||||
$replacement = 'ORDER BY CAST($1.meta_value AS SIGNED)';
|
||||
$sql = preg_replace($pattern, $replacement, $sql);
|
||||
|
||||
// Convert CONVERT to CAST
|
||||
$pattern = '/CONVERT\(([^()]*(\(((?>[^()]+)|(?-2))*\))?[^()]*),\s*([^\s]+)\)/x';
|
||||
$sql = preg_replace($pattern, 'CAST($1 AS $4)', $sql);
|
||||
@ -120,6 +126,8 @@ class SelectSQLRewriter extends AbstractSQLRewriter
|
||||
$pattern = '/@@SESSION.sql_mode/';
|
||||
$sql = preg_replace($pattern, "''", $sql);
|
||||
|
||||
|
||||
// TODO: this seems wrong but if we remove it we get failures with XYZ is not part of the group By
|
||||
if(isset($wpdb)) {
|
||||
$sql = str_replace('GROUP BY ' . $wpdb->prefix . 'posts.ID', '', $sql);
|
||||
}
|
||||
|
@ -710,6 +710,40 @@ final class rewriteTest extends TestCase
|
||||
$this->assertSame(trim($expected), trim($postgresql));
|
||||
}
|
||||
|
||||
public function test_it_rewrites_0CASTS()
|
||||
{
|
||||
|
||||
$sql = <<<SQL
|
||||
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
|
||||
WHERE 1=1 AND (
|
||||
wp_posts.post_date > '2024-07-17 23:59:59'
|
||||
) AND (
|
||||
wp_postmeta.meta_key = 'make_feature_post'
|
||||
) AND (
|
||||
(wp_posts.post_type = 'announcement' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private'))
|
||||
)
|
||||
GROUP BY wp_posts.ID
|
||||
ORDER BY wp_postmeta.meta_value+0 DESC, wp_posts.post_date DESC
|
||||
SQL;
|
||||
|
||||
$expected = <<<SQL
|
||||
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts."ID" = wp_postmeta.post_id )
|
||||
WHERE 1=1 AND (
|
||||
wp_posts.post_date > '2024-07-17 23:59:59'
|
||||
) AND (
|
||||
wp_postmeta.meta_key = 'make_feature_post'
|
||||
) AND (
|
||||
(wp_posts.post_type = 'announcement' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private'))
|
||||
)
|
||||
|
||||
ORDER BY CAST(wp_postmeta.meta_value AS INTEGER) DESC, wp_posts.post_date DESC
|
||||
SQL;
|
||||
|
||||
$postgresql = pg4wp_rewrite($sql);
|
||||
$this->assertSame(trim($expected), trim($postgresql));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user