Skip to content

Commit

Permalink
Merge pull request #133 from PostgreSQL-For-Wordpress/hotfix/handle-z…
Browse files Browse the repository at this point in the history
…ero-int-addition-casting

cast numbers explictly as ints rather than adding 0 to them
  • Loading branch information
mattbucci authored Oct 17, 2024
2 parents 3de1eaa + 90d1c47 commit f03cc84
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pg4wp/rewriters/SelectSQLRewriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
Expand Down
34 changes: 34 additions & 0 deletions tests/rewriteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,40 @@ public function test_it_rewrites_mediumints()
$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));
}





Expand Down

0 comments on commit f03cc84

Please sign in to comment.