From ebbe2915c64db39a2dafa8d9a9491ee21fdce23d Mon Sep 17 00:00:00 2001 From: Matthew Bucci Date: Wed, 21 Feb 2024 01:15:51 -0800 Subject: [PATCH] add rewrite logic for SHOW TABLE STATUS and a catch for calls to information_schema --- pg4wp/driver_pgsql_rewrite.php | 2 +- pg4wp/rewriters/SelectSQLRewriter.php | 35 ++++++++++++ .../rewriters/ShowTableStatusSQLRewriter.php | 54 +++++++++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 pg4wp/rewriters/ShowTableStatusSQLRewriter.php diff --git a/pg4wp/driver_pgsql_rewrite.php b/pg4wp/driver_pgsql_rewrite.php index 0292cd0..d666d28 100644 --- a/pg4wp/driver_pgsql_rewrite.php +++ b/pg4wp/driver_pgsql_rewrite.php @@ -12,7 +12,7 @@ spl_autoload_register(function ($className) { function createSQLRewriter(string $sql): AbstractSQLRewriter { $sql = trim($sql); - if (preg_match('/^(SELECT|INSERT|UPDATE|DELETE|DESCRIBE|ALTER TABLE|CREATE TABLE|DROP TABLE|SHOW INDEX|SHOW VARIABLES|SHOW TABLES|OPTIMIZE TABLE|SET NAMES|SHOW FULL COLUMNS)\b/i', $sql, $matches)) { + if (preg_match('/^(SELECT|INSERT|UPDATE|DELETE|DESCRIBE|ALTER TABLE|CREATE TABLE|DROP TABLE|SHOW INDEX|SHOW VARIABLES|SHOW TABLES|OPTIMIZE TABLE|SET NAMES|SHOW FULL COLUMNS|SHOW TABLE STATUS)\b/i', $sql, $matches)) { // Convert to a format suitable for class names (e.g., "SHOW TABLES" becomes "ShowTables") $type = str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($matches[1])))); $className = $type . 'SQLRewriter'; diff --git a/pg4wp/rewriters/SelectSQLRewriter.php b/pg4wp/rewriters/SelectSQLRewriter.php index 90b6d37..e8e0e8a 100644 --- a/pg4wp/rewriters/SelectSQLRewriter.php +++ b/pg4wp/rewriters/SelectSQLRewriter.php @@ -31,6 +31,16 @@ class SelectSQLRewriter extends AbstractSQLRewriter $sql = preg_replace('/SELECT\s+.*?\s+FROM\s+/is', 'SELECT COUNT(*) FROM ', $sql, 1); } + if(false !== strpos($sql, 'information_schema')) { + // WP Site Health rewrites + if (false !== strpos($sql, "SELECT TABLE_NAME AS 'table', TABLE_ROWS AS 'rows', SUM(data_length + index_length)")) { + $sql = $this->postgresTableSizeRewrite(); + return $sql; + } + + throw new Exception("Unsupported call to information_schema, this probably won't work correctly and needs to be specifically handled, open a github issue with the SQL"); + } + $sql = $this->ensureOrderByInSelect($sql); // Convert CONVERT to CAST @@ -347,4 +357,29 @@ class SelectSQLRewriter extends AbstractSQLRewriter return $sql; } + // This method is specifically to handle should_suggest_persistent_object_cache in wp site health + protected function postgresTableSizeRewrite() + { + + $sql = <<original(); + return $this->generatePostgresShowTableStatus(); + } + + + /** + * Generates a PostgreSQL-compatible SQL query to mimic MySQL's "SHOW TABLE STATUS". + * + * @return string The generated SQL query + */ + public function generatePostgresShowTableStatus($schema = "public") + { + $sql = <<