From 90d1c4769507134a210698cbd6133be67bddd032 Mon Sep 17 00:00:00 2001 From: Matthew Bucci Date: Thu, 17 Oct 2024 02:36:24 -0700 Subject: [PATCH] cast numbers explictly as ints rather than adding 0 to them --- pg4wp/rewriters/SelectSQLRewriter.php | 8 +++++++ tests/rewriteTest.php | 34 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/pg4wp/rewriters/SelectSQLRewriter.php b/pg4wp/rewriters/SelectSQLRewriter.php index 62d2a2a..30f5d14 100644 --- a/pg4wp/rewriters/SelectSQLRewriter.php +++ b/pg4wp/rewriters/SelectSQLRewriter.php @@ -46,6 +46,12 @@ public function rewrite(): string $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 @@ public function rewrite(): string $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); } diff --git a/tests/rewriteTest.php b/tests/rewriteTest.php index df82566..8865f29 100644 --- a/tests/rewriteTest.php +++ b/tests/rewriteTest.php @@ -710,6 +710,40 @@ public function test_it_rewrites_mediumints() $this->assertSame(trim($expected), trim($postgresql)); } + public function test_it_rewrites_0CASTS() + { + + $sql = << '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 = << '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)); + } + +