From f896bb17596cff954e6b1c6a94c4f0d245a1fb38 Mon Sep 17 00:00:00 2001 From: Kevin Locke Date: Sun, 24 Sep 2017 14:07:40 -0600 Subject: [PATCH] Rewrite MySQL FIELD function to CASE statement PostgreSQL does not provide an equivalent to the MySQL FIELD function. It is possible to create such a function, although the syntax is version-dependent (and creates a persistent database object, which so far has not been done by this plugin). So use a generic CASE statement. Fixes: #12 Signed-off-by: Kevin Locke --- pg4wp/driver_pgsql.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/pg4wp/driver_pgsql.php b/pg4wp/driver_pgsql.php index 8807668..375fd3a 100644 --- a/pg4wp/driver_pgsql.php +++ b/pg4wp/driver_pgsql.php @@ -281,6 +281,22 @@ $pattern = '/DATE_ADD[ ]*\(([^,]+),([^\)]+)\)/'; $sql = preg_replace( $pattern, '($1 + $2)', $sql); + // Convert MySQL FIELD function to CASE statement + // https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_field + // Other implementations: https://stackoverflow.com/q/1309624 + function pg4wp_rewrite_field($matches) + { + $case = 'CASE ' . trim($matches[1]); + $comparands = explode(',', $matches[2]); + foreach($comparands as $i => $comparand) { + $case .= ' WHEN ' . trim($comparand) . ' THEN ' . ($i + 1); + } + $case .= ' ELSE 0 END'; + return $case; + } + $pattern = '/FIELD[ ]*\(([^\),]+),([^\)]+)\)/'; + $sql = preg_replace_callback( $pattern, 'pg4wp_rewrite_field', $sql); + $pattern = '/GROUP_CONCAT\(([^()]*(\(((?>[^()]+)|(?-2))*\))?[^()]*)\)/x'; $sql = preg_replace( $pattern, "string_agg($1, ',')", $sql);