From 487b0b8ddee70bcb224e64bd825c9f27d419e2d5 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 25 Nov 2026 10:33:54 +0600 Subject: [PATCH 01/13] new: array support added on where method --- core/DB.php | 61 +++++++- tests/phpunit/DBTest.php | 311 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 364 insertions(+), 8 deletions(-) diff --git a/core/DB.php b/core/DB.php index 3457f0a410..9fccc5542d 100644 --- a/core/DB.php +++ b/core/DB.php @@ -581,21 +581,34 @@ private function add_join( string $type, string $table, string $first, string $o // ───────────────────────────────────────────── /** - * Add a WHERE condition. + * Add a WHERE condition or multiple conditions. * - * Two-argument form uses '=' operator: where('col', 'value'). - * Three-argument form uses custom operator: where('col', '>=', 5). - * Passing null as value auto-converts to IS NULL / IS NOT NULL. + * Supports single-condition syntax: + * Two-argument form uses '=' operator: where('col', 'value'). + * Three-argument form uses custom operator: where('col', '>=', 5). + * Passing null as value auto-converts to IS NULL / IS NOT NULL. + * + * Supports array syntax (conditions combined with AND): + * Associative array: where(['status' => 'active', 'role' => 'admin']) + * Numeric array: where([['status', '=', 'active'], ['role', '!=', 'guest']]) * * @since 4.2.0 * - * @param string $column Column name. - * @param mixed $operator_or_value Operator (if 3 args) or value (if 2 args). - * @param mixed $value Value when operator is specified. + * @param string|array $column Column name, or array of conditions. + * @param mixed $operator_or_value Operator (if 3 args) or value (if 2 args). + * @param mixed $value Value when operator is specified. * * @return self */ - public function where( string $column, $operator_or_value, $value = null ): self { + public function where( $column, $operator_or_value = null, $value = null ): self { + if ( is_array( $column ) ) { + return $this->add_array_where( $column ); + } + + if ( ! is_string( $column ) ) { + return $this; + } + return $this->add_where( $column, $operator_or_value, $value, 'AND', func_num_args() < 3 ); } @@ -1576,6 +1589,38 @@ public function to_sql(): string { // Internal WHERE helpers // ───────────────────────────────────────────── + /** + * Internal method to add array-based WHERE conditions combined with AND. + * + * Supports both associative column-value pairs and numeric array triples/tuples. + * + * @since 4.2.0 + * + * @param array $conditions Array of conditions. + * + * @return self + */ + private function add_array_where( array $conditions ): self { + foreach ( $conditions as $key => $val ) { + if ( is_string( $key ) ) { + // Associative array: column => value. + $this->add_where( $key, $val, null, 'AND', true ); + } elseif ( is_array( $val ) ) { + // Numeric array: ['col', 'val'] or ['col', 'op', 'val']. + $items = array_values( $val ); + $count = count( $items ); + + if ( 2 === $count && is_string( $items[0] ) ) { + $this->add_where( $items[0], $items[1], null, 'AND', true ); + } elseif ( 3 === $count && is_string( $items[0] ) ) { + $this->add_where( $items[0], $items[1], $items[2], 'AND', false ); + } + } + } + + return $this; + } + /** * Internal method to add a basic WHERE condition. * diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index a31b861c97..fc22e2b686 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -125,6 +125,317 @@ public function test_where_conditions() { $this->assertSame( $expected, $sql ); } + /** + * Test WHERE with associative array conditions. + * + * @return void + */ + public function test_where_with_associative_array() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // Multiple column-value pairs combined with AND. + $sql = DB::table( 'tutor_orders' ) + ->where( + array( + 'order_status' => 'completed', + 'user_id' => 10, + 'total_price' => 99.5, + ) + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed' AND user_id = 10 AND total_price = 99.5"; + $this->assertSame( $expected, $sql ); + + // Associative array with null value (auto-converts to IS NULL). + $sql_null = DB::table( 'tutor_orders' ) + ->where( + array( + 'order_status' => 'completed', + 'deleted_at' => null, + ) + ) + ->to_sql(); + + $expected_null = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed' AND deleted_at IS NULL"; + $this->assertSame( $expected_null, $sql_null ); + + // Chaining associative array with existing single-condition syntax. + $sql_chained = DB::table( 'tutor_orders' ) + ->where( + array( + 'order_status' => 'completed', + ) + ) + ->where( 'user_id', 10 ) + ->where( 'total_price', '>', 50 ) + ->to_sql(); + + $expected_chained = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed' AND user_id = 10 AND total_price > 50"; + $this->assertSame( $expected_chained, $sql_chained ); + } + + /** + * Test WHERE with numeric array conditions. + * + * @return void + */ + public function test_where_with_numeric_array() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // 3-element format: [column, operator, value]. + $sql = DB::table( 'tutor_orders' ) + ->where( + array( + array( 'order_status', '=', 'completed' ), + array( 'total_price', '>', 50 ), + array( 'user_id', '!=', 5 ), + ) + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed' AND total_price > 50 AND user_id != 5"; + $this->assertSame( $expected, $sql ); + + // 2-element format: [column, value] defaulting to '='. + $sql_two_elem = DB::table( 'tutor_orders' ) + ->where( + array( + array( 'order_status', 'completed' ), + array( 'user_id', 10 ), + ) + ) + ->to_sql(); + + $expected_two_elem = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed' AND user_id = 10"; + $this->assertSame( $expected_two_elem, $sql_two_elem ); + + // Numeric array with null values. + $sql_null = DB::table( 'tutor_orders' ) + ->where( + array( + array( 'deleted_at', '=', null ), + array( 'completed_at', '!=', null ), + ) + ) + ->to_sql(); + + $expected_null = "SELECT * FROM {$prefix}tutor_orders WHERE deleted_at IS NULL AND completed_at IS NOT NULL"; + $this->assertSame( $expected_null, $sql_null ); + } + + /** + * Test WHERE array with various supported comparison operators. + * + * @return void + */ + public function test_where_array_supported_operators() { + global $wpdb; + + $prefix = $wpdb->prefix; + + $sql = DB::table( 'tutor_orders' ) + ->where( + array( + array( 'total_price', '>=', 20 ), + array( 'total_price', '<=', 100 ), + array( 'total_price', '<', 200 ), + array( 'user_id', '<>', 0 ), + array( 'order_status', 'LIKE', '%paid%' ), + array( 'order_status', 'NOT LIKE', '%failed%' ), + ) + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}tutor_orders WHERE total_price >= 20 AND total_price <= 100 AND total_price < 200 AND user_id <> 0 AND order_status LIKE '%paid%' AND order_status NOT LIKE '%failed%'"; + $this->assertSame( $expected, $sql ); + } + + /** + * Test WHERE with empty arrays and invalid condition formats. + * + * @return void + */ + public function test_where_empty_and_invalid_array_formats() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // Empty array produces no WHERE clause. + $sql_empty = DB::table( 'tutor_orders' ) + ->where( array() ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_empty ); + + // Empty nested array ignored. + $sql_nested_empty = DB::table( 'tutor_orders' ) + ->where( array( array() ) ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_nested_empty ); + + // Sub-array with 1 element ignored. + $sql_one_elem = DB::table( 'tutor_orders' ) + ->where( array( array( 'order_status' ) ) ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_one_elem ); + + // Sub-array with 4 elements ignored. + $sql_four_elem = DB::table( 'tutor_orders' ) + ->where( array( array( 'order_status', '=', 'completed', 'extra' ) ) ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_four_elem ); + + // Non-array scalar item in indexed array ignored. + $sql_scalar = DB::table( 'tutor_orders' ) + ->where( array( 123, 'random_string' ) ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_scalar ); + + // Non-string column in sub-array ignored. + $sql_non_string_col = DB::table( 'tutor_orders' ) + ->where( array( array( 123, '=', 'active' ) ) ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_non_string_col ); + + // Invalid operator in sub-array ignored. + $sql_invalid_op = DB::table( 'tutor_orders' ) + ->where( array( array( 'order_status', 'INVALID_OP', 'completed' ) ) ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_invalid_op ); + + // Valid conditions mixed with invalid condition formats. + $sql_mixed = DB::table( 'tutor_orders' ) + ->where( + array( + 'order_status' => 'completed', + array(), + array( 'invalid_op_col', 'BAD_OPERATOR', 'foo' ), + array( 'total_price', '>', 50 ), + 999, + ) + ) + ->to_sql(); + $expected_mixed = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed' AND total_price > 50"; + $this->assertSame( $expected_mixed, $sql_mixed ); + } + + /** + * Test SQL injection protection and value escaping in array conditions. + * + * @return void + */ + public function test_where_array_sql_injection_and_escaping() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // Malicious column attempt in associative key should be rejected. + $sql_assoc_col = DB::table( 'tutor_orders' ) + ->where( + array( + '1=1; --' => 'val', + 'order_status' => 'completed', + ) + ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed'", $sql_assoc_col ); + + // Malicious column attempt in numeric array should be rejected. + $sql_num_col = DB::table( 'tutor_orders' ) + ->where( + array( + array( 'id; DROP TABLE tutor_orders;--', '=', '1' ), + array( 'order_status', '=', 'completed' ), + ) + ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed'", $sql_num_col ); + + // Malicious operator attempt in numeric array should be rejected. + $sql_op = DB::table( 'tutor_orders' ) + ->where( + array( + array( 'order_status', '= 1; DROP TABLE tutor_orders;--', 'completed' ), + array( 'user_id', '=', 10 ), + ) + ) + ->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}tutor_orders WHERE user_id = 10", $sql_op ); + + // Value with SQL injection payload is properly escaped. + $malicious_val = "active' OR '1'='1"; + $sql_val = DB::table( 'tutor_orders' ) + ->where( + array( + 'order_status' => $malicious_val, + ) + ) + ->to_sql(); + $expected_val = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'active\' OR \'1\'=\'1'"; + $this->assertSame( $expected_val, $sql_val ); + + // Numeric array value with SQL injection payload is properly escaped. + $sql_num_val = DB::table( 'tutor_orders' ) + ->where( + array( + array( 'order_status', '=', $malicious_val ), + ) + ) + ->to_sql(); + $this->assertSame( $expected_val, $sql_num_val ); + + // Live execution test with associative and numeric array conditions. + $key1 = 'where_arr_test_1_' . time() . '_' . wp_rand( 1000, 9999 ); + $key2 = 'where_arr_test_2_' . time() . '_' . wp_rand( 1000, 9999 ); + + DB::table( 'options' )->insert( + array( + 'option_name' => $key1, + 'option_value' => 'val1', + 'autoload' => 'no', + ) + ); + DB::table( 'options' )->insert( + array( + 'option_name' => $key2, + 'option_value' => 'val2', + 'autoload' => 'no', + ) + ); + + // Query with associative array. + $res1 = DB::table( 'options' ) + ->where( + array( + 'option_name' => $key1, + 'autoload' => 'no', + ) + ) + ->first(); + $this->assertNotNull( $res1 ); + $this->assertSame( 'val1', $res1->option_value ); + + // Query with numeric array. + $res2 = DB::table( 'options' ) + ->where( + array( + array( 'option_name', '=', $key2 ), + array( 'autoload', '=', 'no' ), + ) + ) + ->first(); + $this->assertNotNull( $res2 ); + $this->assertSame( 'val2', $res2->option_value ); + + // Clean up. + DB::table( 'options' )->where( 'option_name', $key1 )->delete(); + DB::table( 'options' )->where( 'option_name', $key2 )->delete(); + } + /** * Test OR WHERE conditions. * From 3c69143292a61eb0a0b8db8cff93d4ced1832c00 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 25 Nov 2026 10:34:12 +0600 Subject: [PATCH 02/13] docs: update DB core documentation for array-based where conditions --- docs/developer/core/DB.php.md | 81 ++++++++++++++++++++++++++++++----- 1 file changed, 71 insertions(+), 10 deletions(-) diff --git a/docs/developer/core/DB.php.md b/docs/developer/core/DB.php.md index 71f08c749b..955aeab1e5 100644 --- a/docs/developer/core/DB.php.md +++ b/docs/developer/core/DB.php.md @@ -84,7 +84,7 @@ class DB { public function right_join( string $table, $first, string $operator = '', string $second = '' ): self; // Where Clauses - public function where( string $column, $operator_or_val, $val = null ): self; + public function where( $column, $operator_or_val = null, $val = null ): self; public function or_where( string $column, $operator_or_val, $val = null ): self; public function where_in( string $column, array $values ): self; public function or_where_in( string $column, array $values ): self; @@ -290,16 +290,77 @@ DB::table('users') ## Where Clauses -### 1. Basic Where -Supports both 2-argument (assumes `=`) and 3-argument syntax. +### 1. Basic Where (Single Condition) +Supports both 2-argument (assumes `=`) and 3-argument syntax with custom operators: ```php -DB::table('users')->where('user_status', 0); // user_status = 0 +DB::table('users')->where('user_status', 0); // user_status = 0 DB::table('tutor_orders')->where('total_price', '>=', 100); // total_price >= 100 -DB::table('users')->or_where('user_login', 'admin'); // OR user_login = 'admin' +DB::table('users')->where('deleted_at', null); // deleted_at IS NULL +DB::table('users')->or_where('user_login', 'admin'); // OR user_login = 'admin' ``` -### 2. IN / NOT IN +### 2. Array-Based Where Conditions +Pass multiple conditions as an array to `where()`. Conditions within the array are combined using `AND`. Both associative and numeric array formats are supported: + +#### Associative Array (Column-Value Pairs) +Matches column-value pairs with the `=` operator. Passing `null` as a value automatically converts to `IS NULL`: + +```php +DB::table('users')->where([ + 'status' => 'active', + 'role' => 'admin', +]); +// Generates: WHERE status = 'active' AND role = 'admin' + +DB::table('tutor_orders')->where([ + 'order_status' => 'completed', + 'deleted_at' => null, +]); +// Generates: WHERE order_status = 'completed' AND deleted_at IS NULL +``` + +#### Numeric Array (Operator / Tuple Conditions) +Allows explicit conditions as nested arrays. Supports 3-element `[column, operator, value]` or 2-element `[column, value]` (defaults to `=`) tuples: + +```php +DB::table('tutor_orders')->where([ + ['order_status', '=', 'completed'], + ['total_price', '>=', 50], + ['user_id', '!=', 5], +]); +// Generates: WHERE order_status = 'completed' AND total_price >= 50 AND user_id != 5 + +// 2-element tuples: +DB::table('users')->where([ + ['status', 'active'], + ['role', 'admin'], +]); +// Generates: WHERE status = 'active' AND role = 'admin' + +// Null handling in numeric arrays: +DB::table('tutor_orders')->where([ + ['deleted_at', '=', null], // deleted_at IS NULL + ['completed_at', '!=', null], // completed_at IS NOT NULL +]); +``` + +#### Chaining Array & Single Conditions +Array syntax seamlessly chains with existing single-condition calls and other query builder methods: + +```php +DB::table('tutor_orders') + ->where([ + 'order_status' => 'completed', + ]) + ->where('user_id', 10) + ->where('total_price', '>', 50); +``` + +> [!NOTE] +> All column identifiers in arrays are strictly validated against SQL injection patterns (`is_valid_column`), comparison operators are checked against whitelisted operators (`is_valid_operator`), and values are safely bound via `$wpdb->prepare()`. Empty arrays `where([])` or invalid formats are safely skipped without breaking query generation. + +### 3. IN / NOT IN ```php DB::table('posts')->where_in('ID', [10, 20, 30]); DB::table('posts')->where_not_in('post_status', ['trash', 'auto-draft']); @@ -307,7 +368,7 @@ DB::table('posts')->or_where_in('ID', [40, 50]); DB::table('posts')->or_where_not_in('post_type', ['attachment']); ``` -### 3. NULL / NOT NULL +### 4. NULL / NOT NULL ```php DB::table('posts')->where_null('post_parent'); DB::table('posts')->where_not_null('post_password'); @@ -315,13 +376,13 @@ DB::table('posts')->or_where_null('post_excerpt'); DB::table('posts')->or_where_not_null('to_ping'); ``` -### 4. BETWEEN +### 5. BETWEEN ```php DB::table('tutor_orders')->where_between('created_at', '2024-01-01', '2024-12-31'); DB::table('tutor_orders')->where_not_between('total_price', 10, 50); ``` -### 5. LIKE +### 6. LIKE Automatically wraps the search term with `%` wildcards and escapes internal characters using `$wpdb->esc_like()` to prevent LIKE-injection vulnerabilities. ```php @@ -331,7 +392,7 @@ DB::table('posts')->where_like('post_title', 'WordPress'); DB::table('posts')->where_not_like('post_content', 'deprecated'); ``` -### 6. Raw WHERE +### 7. Raw WHERE For advanced or database-native functions. Use `$wpdb->prepare()` placeholders (`%s`, `%d`, `%f`) in expressions. ```php From 0a30bcfd9039e76bfc1d831122d041b8479fac5a Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 25 Nov 2026 12:11:03 +0600 Subject: [PATCH 03/13] new: added subquery support --- core/DB.php | 712 +++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 591 insertions(+), 121 deletions(-) diff --git a/core/DB.php b/core/DB.php index 9fccc5542d..e19d52a494 100644 --- a/core/DB.php +++ b/core/DB.php @@ -195,6 +195,25 @@ class DB { 'NOT BETWEEN', ); + /** + * Supported comparison operators for column-to-column and scalar comparisons. + * + * @since 4.2.0 + * + * @var string[] + */ + private static $comparison_operators = array( + '=', + '!=', + '<>', + '<', + '>', + '<=', + '>=', + 'LIKE', + 'NOT LIKE', + ); + // ───────────────────────────────────────────── // Factory & Database Accessors // ───────────────────────────────────────────── @@ -230,22 +249,76 @@ public static function set_db( ?\wpdb $db = null ): void { } /** - * Create a new DB query instance for the given table. + * Create a new DB query instance for the given table or subquery. * * The table name will be automatically prefixed with the WordPress - * table prefix if not already present. + * table prefix if not already present. If a Closure or DB instance is + * provided, it will be treated as a derived table subquery. + * + * @since 4.2.0 + * + * @param string|Closure|self $table Table name or subquery. + * @param string|null $alias Optional table alias. + * + * @return self + */ + public static function table( $table, ?string $alias = null ): self { + return ( new self() )->from( $table, $alias ); + } + + /** + * Set the primary table for the query. + * + * Alias for setting the table on an existing instance, commonly used + * inside subquery closures: function( $q ) { $q->from('orders'); } + * + * @since 4.2.0 + * + * @param string|Closure|self $table Table name or subquery. + * @param string|null $alias Optional table alias. + * + * @return self + */ + public function from( $table, ?string $alias = null ): self { + if ( $table instanceof Closure || $table instanceof self ) { + $sub_sql = self::resolve_subquery( $table ); + if ( ! empty( $sub_sql ) ) { + $this->table = "({$sub_sql})"; + if ( null !== $alias && self::is_valid_identifier( $alias ) ) { + $this->alias = $alias; + } + } + return $this; + } + + if ( ! is_string( $table ) || '' === trim( $table ) ) { + return $this; + } + + $this->table = self::prepare_table_name( $table ); + if ( null !== $alias && self::is_valid_identifier( $alias ) ) { + $this->alias = $alias; + } + + return $this; + } + + /** + * Set a derived table subquery as the FROM source. * * @since 4.2.0 * - * @param string $table Table name (without prefix is fine). + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $alias Alias for the derived table. * * @return self */ - public static function table( string $table ): self { - $instance = new self(); - $instance->table = self::prepare_table_name( $table ); + public function from_sub( $subquery, string $alias ): self { + if ( ! ( $subquery instanceof Closure || $subquery instanceof self ) || ! self::is_valid_identifier( $alias ) ) { + return $this; + } - return $instance; + return $this->from( $subquery, $alias ); } // ───────────────────────────────────────────── @@ -255,27 +328,56 @@ public static function table( string $table ): self { /** * Set the columns to select. * - * Accepts one or more column names. Multiple calls are additive. + * Accepts column names or associative arrays mapping aliases to subqueries: + * select('id', 'name') + * select(['id', 'total_orders' => function($q) { ... }]) + * Multiple calls are additive. * * @since 4.2.0 * - * @param string ...$columns Column names to select. + * @param string|array ...$columns Column names or alias => subquery arrays. * * @return self */ - public function select( string ...$columns ): self { + public function select( ...$columns ): self { foreach ( $columns as $column ) { - $aliased = self::parse_column_alias( $column ); - if ( null !== $aliased ) { - $this->columns[] = $aliased; - } elseif ( self::is_valid_column( $column ) ) { - $this->columns[] = $column; + if ( is_array( $column ) ) { + foreach ( $column as $key => $val ) { + if ( is_string( $key ) && ( $val instanceof Closure || $val instanceof self ) ) { + $this->select_sub( $val, $key ); + } elseif ( is_string( $val ) ) { + $this->add_select_column( $val ); + } + } + continue; + } + + if ( is_string( $column ) ) { + $this->add_select_column( $column ); } } return $this; } + /** + * Internal helper to validate and append a single SELECT column or alias. + * + * @since 4.2.0 + * + * @param string $column Column name or aliased expression. + * + * @return void + */ + private function add_select_column( string $column ): void { + $aliased = self::parse_column_alias( $column ); + if ( null !== $aliased ) { + $this->columns[] = $aliased; + } elseif ( self::is_valid_column( $column ) ) { + $this->columns[] = $column; + } + } + /** * Add a raw SELECT expression. * @@ -300,6 +402,29 @@ public function select_raw( string $expression, array $bindings = array() ): sel return $this; } + /** + * Add a subquery expression to the SELECT columns. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $alias Column alias. + * + * @return self + */ + public function select_sub( $subquery, string $alias ): self { + if ( ! self::is_valid_identifier( $alias ) ) { + return $this; + } + + $sub_sql = self::resolve_subquery( $subquery ); + if ( ! empty( $sub_sql ) ) { + $this->raw_columns[] = "({$sub_sql}) AS {$alias}"; + } + + return $this; + } + /** * Apply DISTINCT to the query. * @@ -349,11 +474,7 @@ public function as( string $alias ): self { * @return self */ public function join( string $table, $first, string $operator = '', string $second = '' ): self { - if ( $first instanceof Closure ) { - return $this->add_join_closure( 'INNER', $table, $first ); - } - - return $this->add_join( 'INNER', $table, $first, $operator, $second ); + return $this->compile_join( 'INNER', $this->parse_join_table( $table ), $first, $operator, $second ); } /** @@ -371,11 +492,7 @@ public function join( string $table, $first, string $operator = '', string $seco * @return self */ public function left_join( string $table, $first, string $operator = '', string $second = '' ): self { - if ( $first instanceof Closure ) { - return $this->add_join_closure( 'LEFT', $table, $first ); - } - - return $this->add_join( 'LEFT', $table, $first, $operator, $second ); + return $this->compile_join( 'LEFT', $this->parse_join_table( $table ), $first, $operator, $second ); } /** @@ -393,72 +510,110 @@ public function left_join( string $table, $first, string $operator = '', string * @return self */ public function right_join( string $table, $first, string $operator = '', string $second = '' ): self { - if ( $first instanceof Closure ) { - return $this->add_join_closure( 'RIGHT', $table, $first ); - } - - return $this->add_join( 'RIGHT', $table, $first, $operator, $second ); + return $this->compile_join( 'RIGHT', $this->parse_join_table( $table ), $first, $operator, $second ); } /** - * Internal method to parse and prepare a join table with optional alias. + * Add a JOIN subquery clause. + * + * Supports standard 4-argument syntax or a closure for multiple ON conditions. * * @since 4.2.0 * - * @param string $table Table name, may include alias e.g., 'users AS u'. + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $alias Alias for the subquery table. + * @param string|Closure $first First column in ON condition, or Closure. + * @param string $operator Comparison operator. + * @param string $second Second column in ON condition. + * @param string $type Join type (INNER, LEFT, RIGHT, CROSS). Default 'INNER'. * - * @return string + * @return self */ - private function parse_join_table( string $table ): string { - $parts = preg_split( '/\s+(?:AS\s+)?/i', $table, 2 ); - $table_name = self::prepare_table_name( trim( $parts[0] ) ); - $table_alias = isset( $parts[1] ) ? trim( $parts[1] ) : ''; - - $table_expr = $table_name; - if ( ! empty( $table_alias ) && self::is_valid_identifier( $table_alias ) ) { - $table_expr .= " AS {$table_alias}"; - } + public function join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '', string $type = 'INNER' ): self { + return $this->add_subquery_join( $type, $subquery, $alias, $first, $operator, $second ); + } - return $table_expr; + /** + * Add a LEFT JOIN subquery clause. + * + * Supports standard 4-argument syntax or a closure for multiple ON conditions. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $alias Alias for the subquery table. + * @param string|Closure $first First column or Closure. + * @param string $operator Comparison operator. + * @param string $second Second column. + * + * @return self + */ + public function left_join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '' ): self { + return $this->add_subquery_join( 'LEFT', $subquery, $alias, $first, $operator, $second ); } /** - * Internal method to add a JOIN clause using a closure collector. + * Add a RIGHT JOIN subquery clause. + * + * Supports standard 4-argument syntax or a closure for multiple ON conditions. * * @since 4.2.0 * - * @param string $type Join type (INNER, LEFT, RIGHT, CROSS). - * @param string $table Table name, may include alias. - * @param callable $callback Closure to configure join conditions. + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $alias Alias for the subquery table. + * @param string|Closure $first First column or Closure. + * @param string $operator Comparison operator. + * @param string $second Second column. * * @return self */ - private function add_join_closure( string $type, string $table, callable $callback ): self { - $type = strtoupper( $type ); + public function right_join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '' ): self { + return $this->add_subquery_join( 'RIGHT', $subquery, $alias, $first, $operator, $second ); + } - $allowed_types = array( 'INNER', 'LEFT', 'RIGHT', 'CROSS' ); - if ( ! in_array( $type, $allowed_types, true ) ) { + /** + * Add a CROSS JOIN subquery clause. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $alias Alias for the subquery table. + * + * @return self + */ + public function cross_join_sub( $subquery, string $alias ): self { + if ( ! self::is_valid_identifier( $alias ) ) { return $this; } - $table_expr = $this->parse_join_table( $table ); - $collector = self::create_join_collector(); + $sub_sql = self::resolve_subquery( $subquery ); + if ( ! empty( $sub_sql ) ) { + $this->joins[] = "CROSS JOIN ({$sub_sql}) AS {$alias}"; + } - $callback( $collector ); + return $this; + } - if ( ! empty( $collector->conditions ) ) { - $on_parts = ''; - foreach ( $collector->conditions as $index => $condition ) { - if ( 0 === $index ) { - $on_parts .= $condition['sql']; - } else { - $on_parts .= " {$condition['boolean']} {$condition['sql']}"; - } - } - $this->joins[] = "{$type} JOIN {$table_expr} ON {$on_parts}"; + /** + * Internal method to parse and prepare a join table with optional alias. + * + * @since 4.2.0 + * + * @param string $table Table name, may include alias e.g., 'users AS u'. + * + * @return string + */ + private function parse_join_table( string $table ): string { + $parts = preg_split( '/\s+(?:AS\s+)?/i', $table, 2 ); + $table_name = self::prepare_table_name( trim( $parts[0] ) ); + $table_alias = isset( $parts[1] ) ? trim( $parts[1] ) : ''; + + $table_expr = $table_name; + if ( ! empty( $table_alias ) && self::is_valid_identifier( $table_alias ) ) { + $table_expr .= " AS {$table_alias}"; } - return $this; + return $table_expr; } /** @@ -540,22 +695,21 @@ private function add_on( string $first, string $operator, string $second, string } /** - * Internal method to add a JOIN clause. + * Internal method to compile a JOIN clause for a table or subquery expression. * - * Validates join type, table alias, columns, and operator before - * adding to the query. + * Validates join type, columns, and operator before adding to the query. * * @since 4.2.0 * - * @param string $type Join type (INNER, LEFT, RIGHT, CROSS). - * @param string $table Table name, may include alias e.g., 'users AS u'. - * @param string $first First column in the ON condition. - * @param string $operator Comparison operator. - * @param string $second Second column in the ON condition. + * @param string $type Join type (INNER, LEFT, RIGHT, CROSS). + * @param string $table_expr Prepared table or subquery expression with optional alias. + * @param string|Closure $first First column in ON condition, or Closure. + * @param string $operator Comparison operator. + * @param string $second Second column in ON condition. * * @return self */ - private function add_join( string $type, string $table, string $first, string $operator, string $second ): self { + private function compile_join( string $type, string $table_expr, $first, string $operator, string $second ): self { $type = strtoupper( $type ); $allowed_types = array( 'INNER', 'LEFT', 'RIGHT', 'CROSS' ); @@ -563,9 +717,27 @@ private function add_join( string $type, string $table, string $first, string $o return $this; } - $table_expr = $this->parse_join_table( $table ); + if ( $first instanceof Closure ) { + $collector = self::create_join_collector(); + $first( $collector ); + + if ( ! empty( $collector->conditions ) ) { + $on_parts = ''; + foreach ( $collector->conditions as $index => $condition ) { + if ( 0 === $index ) { + $on_parts .= $condition['sql']; + } else { + $on_parts .= " {$condition['boolean']} {$condition['sql']}"; + } + } + $this->joins[] = "{$type} JOIN {$table_expr} ON {$on_parts}"; + } + + return $this; + } - if ( self::is_valid_column( $first ) + if ( is_string( $first ) + && self::is_valid_column( $first ) && self::is_valid_operator( $operator ) && self::is_valid_column( $second ) ) { @@ -576,6 +748,33 @@ private function add_join( string $type, string $table, string $first, string $o return $this; } + /** + * Internal method to add a JOIN subquery clause. + * + * @since 4.2.0 + * + * @param string $type Join type (INNER, LEFT, RIGHT). + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $alias Alias for the subquery table. + * @param string|Closure $first First column in ON condition, or Closure. + * @param string $operator Comparison operator. + * @param string $second Second column in ON condition. + * + * @return self + */ + private function add_subquery_join( string $type, $subquery, string $alias, $first, string $operator, string $second ): self { + if ( ! self::is_valid_identifier( $alias ) ) { + return $this; + } + + $sub_sql = self::resolve_subquery( $subquery ); + if ( empty( $sub_sql ) ) { + return $this; + } + + return $this->compile_join( $type, "({$sub_sql}) AS {$alias}", $first, $operator, $second ); + } + // ───────────────────────────────────────────── // WHERE // ───────────────────────────────────────────── @@ -601,85 +800,110 @@ private function add_join( string $type, string $table, string $first, string $o * @return self */ public function where( $column, $operator_or_value = null, $value = null ): self { - if ( is_array( $column ) ) { - return $this->add_array_where( $column ); - } + return $this->dispatch_where( $column, $operator_or_value, $value, 'AND', func_num_args() ); + } - if ( ! is_string( $column ) ) { - return $this; - } + /** + * Add an OR WHERE condition or multiple conditions. + * + * @since 4.2.0 + * + * @param string|array|Closure|self $column Column name, array of conditions, or LHS subquery. + * @param mixed $operator_or_value Operator or value. + * @param mixed $value Value when operator is specified. + * + * @return self + */ + public function or_where( $column, $operator_or_value = null, $value = null ): self { + return $this->dispatch_where( $column, $operator_or_value, $value, 'OR', func_num_args() ); + } - return $this->add_where( $column, $operator_or_value, $value, 'AND', func_num_args() < 3 ); + /** + * Add a WHERE condition comparing two columns. + * + * Useful for correlated subqueries where an inner subquery column is compared + * to an outer table column: where_column('o.user_id', '=', 'u.id'). + * + * @since 4.2.0 + * + * @param string $first First column name. + * @param string $operator_or_second Operator (if 3 args) or second column (if 2 args). + * @param string|null $second Second column name when operator is specified. + * + * @return self + */ + public function where_column( string $first, string $operator_or_second, ?string $second = null ): self { + return $this->add_where_column( $first, $operator_or_second, $second, 'AND' ); } /** - * Add an OR WHERE condition. + * Add an OR WHERE condition comparing two columns. * * @since 4.2.0 * - * @param string $column Column name. - * @param mixed $operator_or_value Operator or value. - * @param mixed $value Value when operator is specified. + * @param string $first First column name. + * @param string $operator_or_second Operator (if 3 args) or second column (if 2 args). + * @param string|null $second Second column name when operator is specified. * * @return self */ - public function or_where( string $column, $operator_or_value, $value = null ): self { - return $this->add_where( $column, $operator_or_value, $value, 'OR', func_num_args() < 3 ); + public function or_where_column( string $first, string $operator_or_second, ?string $second = null ): self { + return $this->add_where_column( $first, $operator_or_second, $second, 'OR' ); } /** - * Add a WHERE IN condition. + * Add a WHERE IN condition or subquery. * * @since 4.2.0 * - * @param string $column Column name. - * @param array $values Array of values. + * @param string $column Column name. + * @param array|Closure|self $values Array of values, Closure, or DB subquery. * * @return self */ - public function where_in( string $column, array $values ): self { + public function where_in( string $column, $values ): self { return $this->add_where_in( $column, $values, 'IN', 'AND' ); } /** - * Add a WHERE NOT IN condition. + * Add a WHERE NOT IN condition or subquery. * * @since 4.2.0 * - * @param string $column Column name. - * @param array $values Array of values. + * @param string $column Column name. + * @param array|Closure|self $values Array of values, Closure, or DB subquery. * * @return self */ - public function where_not_in( string $column, array $values ): self { + public function where_not_in( string $column, $values ): self { return $this->add_where_in( $column, $values, 'NOT IN', 'AND' ); } /** - * Add an OR WHERE IN condition. + * Add an OR WHERE IN condition or subquery. * * @since 4.2.0 * - * @param string $column Column name. - * @param array $values Array of values. + * @param string $column Column name. + * @param array|Closure|self $values Array of values, Closure, or DB subquery. * * @return self */ - public function or_where_in( string $column, array $values ): self { + public function or_where_in( string $column, $values ): self { return $this->add_where_in( $column, $values, 'IN', 'OR' ); } /** - * Add an OR WHERE NOT IN condition. + * Add an OR WHERE NOT IN condition or subquery. * * @since 4.2.0 * - * @param string $column Column name. - * @param array $values Array of values. + * @param string $column Column name. + * @param array|Closure|self $values Array of values, Closure, or DB subquery. * * @return self */ - public function or_where_not_in( string $column, array $values ): self { + public function or_where_not_in( string $column, $values ): self { return $this->add_where_in( $column, $values, 'NOT IN', 'OR' ); } @@ -763,6 +987,58 @@ public function or_where_not_null( string $column ): self { return $this; } + /** + * Add a WHERE EXISTS subquery condition. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * + * @return self + */ + public function where_exists( $subquery ): self { + return $this->add_where_exists( $subquery, 'EXISTS', 'AND' ); + } + + /** + * Add an OR WHERE EXISTS subquery condition. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * + * @return self + */ + public function or_where_exists( $subquery ): self { + return $this->add_where_exists( $subquery, 'EXISTS', 'OR' ); + } + + /** + * Add a WHERE NOT EXISTS subquery condition. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * + * @return self + */ + public function where_not_exists( $subquery ): self { + return $this->add_where_exists( $subquery, 'NOT EXISTS', 'AND' ); + } + + /** + * Add an OR WHERE NOT EXISTS subquery condition. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * + * @return self + */ + public function or_where_not_exists( $subquery ): self { + return $this->add_where_exists( $subquery, 'NOT EXISTS', 'OR' ); + } + /** * Add a WHERE BETWEEN condition. * @@ -1590,30 +1866,31 @@ public function to_sql(): string { // ───────────────────────────────────────────── /** - * Internal method to add array-based WHERE conditions combined with AND. + * Internal method to add array-based WHERE conditions. * * Supports both associative column-value pairs and numeric array triples/tuples. * * @since 4.2.0 * - * @param array $conditions Array of conditions. + * @param array $conditions Array of conditions. + * @param string $boolean Boolean connector (AND or OR). * * @return self */ - private function add_array_where( array $conditions ): self { + private function add_array_where( array $conditions, string $boolean = 'AND' ): self { foreach ( $conditions as $key => $val ) { if ( is_string( $key ) ) { // Associative array: column => value. - $this->add_where( $key, $val, null, 'AND', true ); + $this->add_where( $key, $val, null, $boolean, true ); } elseif ( is_array( $val ) ) { // Numeric array: ['col', 'val'] or ['col', 'op', 'val']. $items = array_values( $val ); $count = count( $items ); if ( 2 === $count && is_string( $items[0] ) ) { - $this->add_where( $items[0], $items[1], null, 'AND', true ); + $this->add_where( $items[0], $items[1], null, $boolean, true ); } elseif ( 3 === $count && is_string( $items[0] ) ) { - $this->add_where( $items[0], $items[1], $items[2], 'AND', false ); + $this->add_where( $items[0], $items[1], $items[2], $boolean, false ); } } } @@ -1621,6 +1898,61 @@ private function add_array_where( array $conditions ): self { return $this; } + /** + * Internal dispatcher for where() and or_where(). + * + * @since 4.2.0 + * + * @param mixed $column Column name, array of conditions, or LHS subquery. + * @param mixed $operator_or_value Operator or value. + * @param mixed $value Value when operator is specified. + * @param string $boolean AND or OR. + * @param int $arg_count Number of arguments passed to the caller. + * + * @return self + */ + private function dispatch_where( $column, $operator_or_value, $value, string $boolean, int $arg_count ): self { + if ( is_array( $column ) ) { + return $this->add_array_where( $column, $boolean ); + } + + if ( $column instanceof Closure || $column instanceof self ) { + if ( $arg_count < 2 ) { + return $this; + } + + return $this->add_where_sub( $column, $operator_or_value, $value, $boolean, $arg_count < 3 ); + } + + if ( ! is_string( $column ) ) { + return $this; + } + + return $this->add_where( $column, $operator_or_value, $value, $boolean, $arg_count < 3 ); + } + + /** + * Internal method to add a WHERE condition with a subquery on the left-hand side. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * @param mixed $operator_or_value Operator or value. + * @param mixed $value Value when operator is specified. + * @param string $boolean AND or OR. + * @param bool $is_two_arg Whether this is a two-argument call. + * + * @return self + */ + private function add_where_sub( $subquery, $operator_or_value, $value, string $boolean, bool $is_two_arg ): self { + $sub_sql = self::resolve_subquery( $subquery ); + if ( empty( $sub_sql ) ) { + return $this; + } + + return $this->append_where_condition( "({$sub_sql})", $operator_or_value, $value, $boolean, $is_two_arg ); + } + /** * Internal method to add a basic WHERE condition. * @@ -1642,6 +1974,23 @@ private function add_where( string $column, $operator_or_value, $value, string $ return $this; } + return $this->append_where_condition( $column, $operator_or_value, $value, $boolean, $is_two_arg ); + } + + /** + * Shared helper to format and append a WHERE condition for a validated LHS expression. + * + * @since 4.2.0 + * + * @param string $lhs Validated column or parenthesized subquery. + * @param mixed $operator_or_value Operator or value. + * @param mixed $value Value (null when in two-arg form). + * @param string $boolean AND or OR. + * @param bool $is_two_arg Whether this is a two-argument call. + * + * @return self + */ + private function append_where_condition( string $lhs, $operator_or_value, $value, string $boolean, bool $is_two_arg ): self { // Determine operator and value. if ( $is_two_arg ) { $value = $operator_or_value; @@ -1650,11 +1999,29 @@ private function add_where( string $column, $operator_or_value, $value, string $ $operator = strtoupper( (string) $operator_or_value ); } + // Handle subquery value. + if ( $value instanceof Closure || $value instanceof self ) { + $allowed_subquery_ops = array_merge( self::$comparison_operators, array( 'IN', 'NOT IN' ) ); + if ( ! in_array( $operator, $allowed_subquery_ops, true ) ) { + return $this; + } + + $sub_sql = self::resolve_subquery( $value ); + if ( ! empty( $sub_sql ) ) { + $this->wheres[] = array( + 'sql' => "{$lhs} {$operator} ({$sub_sql})", + 'boolean' => $boolean, + ); + } + + return $this; + } + // Handle null values → IS NULL / IS NOT NULL. if ( is_null( $value ) ) { $null_op = in_array( $operator, array( '!=', '<>' ), true ) ? 'IS NOT' : 'IS'; $this->wheres[] = array( - 'sql' => "{$column} {$null_op} NULL", + 'sql' => "{$lhs} {$null_op} NULL", 'boolean' => $boolean, ); @@ -1668,7 +2035,7 @@ private function add_where( string $column, $operator_or_value, $value, string $ $prepared_value = self::prepare_value( $value ); $this->wheres[] = array( - 'sql' => "{$column} {$operator} {$prepared_value}", + 'sql' => "{$lhs} {$operator} {$prepared_value}", 'boolean' => $boolean, ); @@ -1676,19 +2043,35 @@ private function add_where( string $column, $operator_or_value, $value, string $ } /** - * Internal method to add WHERE IN / NOT IN conditions. + * Internal method to add WHERE IN / NOT IN conditions or subqueries. * * @since 4.2.0 * - * @param string $column Column name. - * @param array $values Array of values. - * @param string $type IN or NOT IN. - * @param string $boolean AND or OR. + * @param string $column Column name. + * @param array|Closure|self $values Array of values, Closure, or DB subquery. + * @param string $type IN or NOT IN. + * @param string $boolean AND or OR. * * @return self */ - private function add_where_in( string $column, array $values, string $type, string $boolean ): self { - if ( ! self::is_valid_column( $column ) || empty( $values ) ) { + private function add_where_in( string $column, $values, string $type, string $boolean ): self { + if ( ! self::is_valid_column( $column ) ) { + return $this; + } + + if ( $values instanceof Closure || $values instanceof self ) { + $sub_sql = self::resolve_subquery( $values ); + if ( ! empty( $sub_sql ) ) { + $this->wheres[] = array( + 'sql' => "{$column} {$type} ({$sub_sql})", + 'boolean' => $boolean, + ); + } + + return $this; + } + + if ( ! is_array( $values ) || empty( $values ) ) { return $this; } @@ -1702,6 +2085,62 @@ private function add_where_in( string $column, array $values, string $type, stri return $this; } + /** + * Internal method to add WHERE EXISTS / NOT EXISTS condition. + * + * @since 4.2.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * @param string $type EXISTS or NOT EXISTS. + * @param string $boolean AND or OR. + * + * @return self + */ + private function add_where_exists( $subquery, string $type, string $boolean ): self { + $sub_sql = self::resolve_subquery( $subquery ); + if ( ! empty( $sub_sql ) ) { + $this->wheres[] = array( + 'sql' => "{$type} ({$sub_sql})", + 'boolean' => $boolean, + ); + } + + return $this; + } + + /** + * Internal method to add a WHERE condition comparing two columns. + * + * @since 4.2.0 + * + * @param string $first First column name. + * @param string $operator_or_second Operator or second column if 2 args. + * @param string|null $second Second column name if 3 args. + * @param string $boolean AND or OR. + * + * @return self + */ + private function add_where_column( string $first, string $operator_or_second, ?string $second, string $boolean ): self { + if ( null === $second ) { + $operator = '='; + $second = $operator_or_second; + } else { + $operator = strtoupper( $operator_or_second ); + } + + if ( self::is_valid_column( $first ) + && in_array( $operator, self::$comparison_operators, true ) + && self::is_valid_column( $second ) + ) { + $this->wheres[] = array( + 'sql' => "{$first} {$operator} {$second}", + 'boolean' => $boolean, + ); + } + + return $this; + } + /** * Internal method for BETWEEN / NOT BETWEEN conditions. * @@ -1822,7 +2261,9 @@ private function build_select_query( bool $calc_found_rows = false ): string { } $parts[] = $select; - $parts[] = "FROM {$from}"; + if ( ! empty( $from ) ) { + $parts[] = "FROM {$from}"; + } if ( ! empty( $join ) ) { $parts[] = $join; @@ -2068,6 +2509,35 @@ private static function get_placeholder( $value ): string { // Value Preparation & DB Utilities (Self-Contained) // ───────────────────────────────────────────── + /** + * Resolve a subquery from a Closure or DB instance into a SQL string. + * + * @since 4.2.0 + * + * @param mixed $query Closure or DB instance. + * + * @return string|null The SQL string, or null if invalid. + */ + public static function resolve_subquery( $query ): ?string { + if ( $query instanceof Closure ) { + $sub = new self(); + $result = $query( $sub ); + $query = ( $result instanceof self ) ? $result : $sub; + } + + if ( ! $query instanceof self ) { + return null; + } + + if ( empty( $query->table ) && empty( $query->raw_columns ) ) { + return null; + } + + $sql = $query->to_sql(); + + return ! empty( $sql ) ? $sql : null; + } + /** * Prepare a single value for safe SQL inclusion using $wpdb->prepare(). * From e1fdde854689f901c28ce73006cfb804dad1c6d2 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 25 Nov 2026 12:11:35 +0600 Subject: [PATCH 04/13] test: add comprehensive unit tests for SQL subqueries and prefixing in DBTest --- tests/phpunit/DBTest.php | 761 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 761 insertions(+) diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index fc22e2b686..4d28ce4f7d 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -1612,4 +1612,765 @@ public function test_db_set_and_get() { DB::set_db( null ); $this->assertSame( $wpdb, $method->invoke( null ) ); } + + // ─── prepare_table_name & prefixing ───────────────────────────────────── + + /** + * Test DB::get_table_prefix. + * + * @since 4.2.1 + * + * @return void + */ + public function test_get_table_prefix() { + global $wpdb; + + $this->assertSame( $wpdb->prefix, DB::get_table_prefix() ); + + $orig_prefix = $wpdb->prefix; + try { + $wpdb->prefix = 'wp_custom_'; + $this->assertSame( 'wp_custom_', DB::get_table_prefix() ); + } finally { + $wpdb->prefix = $orig_prefix; + } + } + + // ─── Subquery Tests ───────────────────────────────────────────────────── + + /** + * Test WHERE comparison operators with subqueries. + * + * @since 4.2.0 + * + * @return void + */ + public function test_where_subquery_comparison() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // 3-argument syntax with closure. + $sql = DB::table( 'tutor_orders' ) + ->where( + 'total_price', + '>', + function ( $q ) { + $q->from( 'tutor_orders' )->select_raw( 'AVG(total_price)' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}tutor_orders WHERE total_price > (SELECT AVG(total_price) FROM {$prefix}tutor_orders)"; + $this->assertSame( $expected, $sql ); + + // 3-argument syntax with DB instance. + $sub = DB::table( 'tutor_orders' )->select_raw( 'AVG(total_price)' ); + $sql = DB::table( 'tutor_orders' ) + ->where( 'total_price', '>=', $sub ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}tutor_orders WHERE total_price >= (SELECT AVG(total_price) FROM {$prefix}tutor_orders)"; + $this->assertSame( $expected, $sql ); + + // 2-argument syntax with closure (defaults operator to '='). + $sql = DB::table( 'users' ) + ->where( + 'id', + function ( $q ) { + $q->from( 'posts' )->select( 'post_author' )->where( 'id', 1 ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users WHERE id = (SELECT post_author FROM {$prefix}posts WHERE id = 1)"; + $this->assertSame( $expected, $sql ); + + // or_where with subquery. + $sql = DB::table( 'tutor_orders' ) + ->where( 'total_price', '>', $sub ) + ->or_where( + 'total_price', + '<', + function ( $q ) { + $q->from( 'tutor_orders' )->select_raw( 'MIN(total_price)' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}tutor_orders WHERE total_price > (SELECT AVG(total_price) FROM {$prefix}tutor_orders) OR total_price < (SELECT MIN(total_price) FROM {$prefix}tutor_orders)"; + $this->assertSame( $expected, $sql ); + + // Array conditions with subquery. + $sql = DB::table( 'tutor_orders' ) + ->where( + array( + 'total_price' => $sub, + array( 'total_price', '>=', $sub ), + ) + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}tutor_orders WHERE total_price = (SELECT AVG(total_price) FROM {$prefix}tutor_orders) AND total_price >= (SELECT AVG(total_price) FROM {$prefix}tutor_orders)"; + $this->assertSame( $expected, $sql ); + } + + /** + * Test WHERE IN and WHERE NOT IN with subqueries. + * + * @since 4.2.0 + * + * @return void + */ + public function test_where_in_and_not_in_subquery() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // where_in with closure. + $sql = DB::table( 'users' ) + ->where_in( + 'id', + function ( $q ) { + $q->from( 'tutor_orders' ) + ->select( 'user_id' ) + ->where( 'order_status', 'completed' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users WHERE id IN (SELECT user_id FROM {$prefix}tutor_orders WHERE order_status = 'completed')"; + $this->assertSame( $expected, $sql ); + + // where_in with DB instance. + $sub = DB::table( 'tutor_orders' ) + ->select( 'user_id' ) + ->where( 'order_status', 'completed' ); + + $sql = DB::table( 'users' ) + ->where_in( 'id', $sub ) + ->to_sql(); + + $this->assertSame( $expected, $sql ); + + // where_not_in with closure. + $sql = DB::table( 'users' ) + ->where_not_in( + 'id', + function ( $q ) { + $q->from( 'tutor_orders' )->select( 'user_id' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users WHERE id NOT IN (SELECT user_id FROM {$prefix}tutor_orders)"; + $this->assertSame( $expected, $sql ); + + // or_where_in and or_where_not_in. + $sql = DB::table( 'users' ) + ->where( 'user_status', 0 ) + ->or_where_in( 'id', $sub ) + ->or_where_not_in( + 'id', + function ( $q ) { + $q->from( 'posts' )->select( 'post_author' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users WHERE user_status = 0 OR id IN (SELECT user_id FROM {$prefix}tutor_orders WHERE order_status = 'completed') OR id NOT IN (SELECT post_author FROM {$prefix}posts)"; + $this->assertSame( $expected, $sql ); + } + + /** + * Test WHERE EXISTS and WHERE NOT EXISTS subqueries. + * + * @since 4.2.0 + * + * @return void + */ + public function test_where_exists_and_not_exists() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // where_exists with closure. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->where_exists( + function ( $q ) { + $q->from( 'tutor_orders', 'o' ) + ->where_column( 'o.user_id', '=', 'u.id' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users AS u WHERE EXISTS (SELECT * FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id)"; + $this->assertSame( $expected, $sql ); + + // where_not_exists with DB instance. + $sub = DB::table( 'tutor_orders', 'o' ) + ->where_column( 'o.user_id', '=', 'u.id' ); + + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->where_not_exists( $sub ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users AS u WHERE NOT EXISTS (SELECT * FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id)"; + $this->assertSame( $expected, $sql ); + + // or_where_exists and or_where_not_exists. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->where( 'u.status', 'active' ) + ->or_where_exists( $sub ) + ->or_where_not_exists( + function ( $q ) { + $q->from( 'posts' )->where_column( 'post_author', '=', 'u.id' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users AS u WHERE u.status = 'active' OR EXISTS (SELECT * FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id) OR NOT EXISTS (SELECT * FROM {$prefix}posts WHERE post_author = u.id)"; + $this->assertSame( $expected, $sql ); + } + + /** + * Test SELECT subquery via select_sub(). + * + * @since 4.2.0 + * + * @return void + */ + public function test_select_subquery() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // select_sub with closure. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->select( 'u.id', 'u.user_login' ) + ->select_sub( + function ( $q ) { + $q->from( 'tutor_orders', 'o' ) + ->select_raw( 'COUNT(*)' ) + ->where_column( 'o.user_id', '=', 'u.id' ); + }, + 'order_count' + ) + ->to_sql(); + + $expected = "SELECT u.id, u.user_login, (SELECT COUNT(*) FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id) AS order_count FROM {$prefix}users AS u"; + $this->assertSame( $expected, $sql ); + + // select_sub with DB instance. + $sub = DB::table( 'tutor_orders' )->select_raw( 'MAX(total_price)' ); + $sql = DB::table( 'users' ) + ->select( 'id' ) + ->select_sub( $sub, 'max_spent' ) + ->to_sql(); + + $expected = "SELECT id, (SELECT MAX(total_price) FROM {$prefix}tutor_orders) AS max_spent FROM {$prefix}users"; + $this->assertSame( $expected, $sql ); + + // Invalid alias rejection. + $sql = DB::table( 'users' ) + ->select( 'id' ) + ->select_sub( $sub, 'invalid alias;--' ) + ->to_sql(); + + $this->assertSame( "SELECT id FROM {$prefix}users", $sql ); + } + + /** + * Test FROM derived table subquery. + * + * @since 4.2.0 + * + * @return void + */ + public function test_from_subquery() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // DB::table( Closure, alias ) + $sql = DB::table( + function ( $q ) { + $q->from( 'tutor_orders' )->where( 'order_status', 'completed' ); + }, + 'completed_orders' + ) + ->select( 'id', 'total_price' ) + ->to_sql(); + + $expected = "SELECT id, total_price FROM (SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed') AS completed_orders"; + $this->assertSame( $expected, $sql ); + + // DB::table( DB, alias ) + $sub = DB::table( 'users' )->where( 'user_status', 0 ); + $sql = DB::table( $sub, 'active_users' ) + ->select( 'id', 'user_email' ) + ->to_sql(); + + $expected = "SELECT id, user_email FROM (SELECT * FROM {$prefix}users WHERE user_status = 0) AS active_users"; + $this->assertSame( $expected, $sql ); + + // from_sub() method on existing query. + $sql = DB::table( 'dummy' ) + ->from_sub( $sub, 'active_users' ) + ->to_sql(); + + $expected = "SELECT * FROM (SELECT * FROM {$prefix}users WHERE user_status = 0) AS active_users"; + $this->assertSame( $expected, $sql ); + + // Invalid alias rejection. + $sql = DB::table( 'users' ) + ->from_sub( $sub, 'invalid alias;--' ) + ->to_sql(); + + $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + } + + /** + * Test JOIN subqueries (join_sub, left_join_sub, right_join_sub). + * + * @since 4.2.0 + * + * @return void + */ + public function test_join_subquery() { + global $wpdb; + + $prefix = $wpdb->prefix; + + $sub = DB::table( 'tutor_orders' ) + ->select( 'user_id' ) + ->select_raw( 'SUM(total_price) as total_spent' ) + ->group_by( 'user_id' ); + + // INNER JOIN subquery with 4 arguments. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->select( 'u.id', 's.total_spent' ) + ->join_sub( $sub, 's', 'u.id', '=', 's.user_id' ) + ->to_sql(); + + $expected = "SELECT u.id, s.total_spent FROM {$prefix}users AS u INNER JOIN (SELECT user_id, SUM(total_price) as total_spent FROM {$prefix}tutor_orders GROUP BY user_id) AS s ON u.id = s.user_id"; + $this->assertSame( $expected, $sql ); + + // LEFT JOIN subquery with 4 arguments. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->select( 'u.id', 's.total_spent' ) + ->left_join_sub( $sub, 's', 'u.id', '=', 's.user_id' ) + ->to_sql(); + + $expected = "SELECT u.id, s.total_spent FROM {$prefix}users AS u LEFT JOIN (SELECT user_id, SUM(total_price) as total_spent FROM {$prefix}tutor_orders GROUP BY user_id) AS s ON u.id = s.user_id"; + $this->assertSame( $expected, $sql ); + + // RIGHT JOIN subquery with 4 arguments. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->select( 'u.id', 's.total_spent' ) + ->right_join_sub( $sub, 's', 'u.id', '=', 's.user_id' ) + ->to_sql(); + + $expected = "SELECT u.id, s.total_spent FROM {$prefix}users AS u RIGHT JOIN (SELECT user_id, SUM(total_price) as total_spent FROM {$prefix}tutor_orders GROUP BY user_id) AS s ON u.id = s.user_id"; + $this->assertSame( $expected, $sql ); + + // JOIN subquery with closure ON condition. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->left_join_sub( + $sub, + 's', + function ( $join ) { + $join->on( 'u.id', '=', 's.user_id' ) + ->on( 's.total_spent', '>', 'u.id' ); + } + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users AS u LEFT JOIN (SELECT user_id, SUM(total_price) as total_spent FROM {$prefix}tutor_orders GROUP BY user_id) AS s ON u.id = s.user_id AND s.total_spent > u.id"; + $this->assertSame( $expected, $sql ); + + // Invalid alias rejection. + $sql = DB::table( 'users' ) + ->join_sub( $sub, 'invalid alias;--', 'u.id', '=', 's.user_id' ) + ->to_sql(); + + $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + } + + /** + * Test nested subqueries and live database execution with subqueries. + * + * @since 4.2.0 + * + * @return void + */ + public function test_nested_subqueries_and_live_execution() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // Nested subquery: WHERE IN (subquery with WHERE IN (subquery)). + $inner = DB::table( 'tutor_orders' )->select( 'user_id' )->where( 'total_price', '>', 50 ); + $middle = DB::table( 'users' )->select( 'id' )->where_in( 'id', $inner ); + $outer = DB::table( 'posts' )->where_in( 'post_author', $middle )->to_sql(); + + $expected = "SELECT * FROM {$prefix}posts WHERE post_author IN (SELECT id FROM {$prefix}users WHERE id IN (SELECT user_id FROM {$prefix}tutor_orders WHERE total_price > 50))"; + $this->assertSame( $expected, $outer ); + + // Live execution test with options table. + $key1 = 'subquery_test_key_1_' . time() . '_' . wp_rand( 1000, 9999 ); + $key2 = 'subquery_test_key_2_' . time() . '_' . wp_rand( 1000, 9999 ); + + DB::table( 'options' )->insert( + array( + 'option_name' => $key1, + 'option_value' => 'active_val', + 'autoload' => 'no', + ) + ); + DB::table( 'options' )->insert( + array( + 'option_name' => $key2, + 'option_value' => 'inactive_val', + 'autoload' => 'no', + ) + ); + + // Query using subquery. + $result = DB::table( 'options' ) + ->where_in( + 'option_name', + function ( $q ) use ( $key1 ) { + $q->from( 'options' ) + ->select( 'option_name' ) + ->where( 'option_name', $key1 ); + } + ) + ->first(); + + $this->assertNotNull( $result ); + $this->assertSame( $key1, $result->option_name ); + $this->assertSame( 'active_val', $result->option_value ); + + // Clean up. + DB::table( 'options' )->where( 'option_name', $key1 )->delete(); + DB::table( 'options' )->where( 'option_name', $key2 )->delete(); + } + + /** + * Test empty, uninitialized, and invalid subquery inputs and operators. + * + * @since 4.2.0 + * + * @return void + */ + public function test_subquery_empty_and_invalid_inputs() { + global $wpdb; + + $prefix = $wpdb->prefix; + $empty_closure = function ( $q ) { + // Intentionally left empty. + }; + $empty_db = new DB(); + + // Empty closure and uninitialized DB instance should be ignored. + $sql = DB::table( 'users' ) + ->where_in( 'id', $empty_closure ) + ->where_not_in( 'id', $empty_db ) + ->where_exists( $empty_closure ) + ->where_not_exists( $empty_db ) + ->select_sub( $empty_closure, 'empty_col' ) + ->join_sub( $empty_closure, 's', 'users.id', '=', 's.id' ) + ->to_sql(); + + $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + + // Non-Closure / non-DB values passed to subquery methods should be ignored. + $sql = DB::table( 'users' ) + ->where_exists( 'SELECT 1' ) + ->select_sub( 123, 'num_col' ) + ->from_sub( 'invalid', 'sub' ) + ->join_sub( 'invalid', 's', 'users.id', '=', 's.id' ) + ->to_sql(); + + $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + + // Invalid operators for subquery comparison in where() should be rejected. + $valid_sub = DB::table( 'tutor_orders' )->select( 'id' ); + $sql = DB::table( 'users' ) + ->where( 'id', 'BETWEEN', $valid_sub ) + ->where( 'id', 'IS', $valid_sub ) + ->where( 'id', 'INVALID_OP', $valid_sub ) + ->to_sql(); + + $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + } + + /** + * Test from(), DB::table() with subquery without alias, and scalar subqueries. + * + * @since 4.2.0 + * + * @return void + */ + public function test_from_and_table_subquery_chaining() { + global $wpdb; + + $prefix = $wpdb->prefix; + $sub = DB::table( 'users' )->where( 'user_status', 0 ); + + // DB::table( $sub ) chained with ->as( 'alias' ). + $sql = DB::table( $sub )->as( 'active_users' )->select( 'id' )->to_sql(); + $this->assertSame( "SELECT id FROM (SELECT * FROM {$prefix}users WHERE user_status = 0) AS active_users", $sql ); + + // Direct from() with table and alias. + $sql = ( new DB() )->from( 'tutor_orders', 'o' )->select( 'o.id' )->to_sql(); + $this->assertSame( "SELECT o.id FROM {$prefix}tutor_orders AS o", $sql ); + + // Non-string table safely ignored. + $sql = DB::table( new \stdClass() )->to_sql(); + $this->assertSame( 'SELECT *', $sql ); + + // Scalar subquery without FROM clause. + $sql = DB::table( 'users' ) + ->select_sub( + function ( $q ) { + $q->select_raw( '1' ); + }, + 'one_val' + ) + ->to_sql(); + + $this->assertSame( "SELECT (SELECT 1) AS one_val FROM {$prefix}users", $sql ); + } + + /** + * Test where_column() and or_where_column(). + * + * @since 4.2.0 + * + * @return void + */ + public function test_where_column_and_or_where_column() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // 2-arg and 3-arg where_column and or_where_column. + $sql = DB::table( 'posts' ) + ->where_column( 'post_modified', 'post_date' ) + ->where_column( 'post_modified_gmt', '>', 'post_date_gmt' ) + ->or_where_column( 'post_author', 'post_parent' ) + ->or_where_column( 'ID', '!=', 'post_parent' ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}posts WHERE post_modified = post_date AND post_modified_gmt > post_date_gmt OR post_author = post_parent OR ID != post_parent"; + $this->assertSame( $expected, $sql ); + + // Invalid columns and non-comparison operators should be rejected. + $sql = DB::table( 'posts' ) + ->where_column( '1=1; --', '=', 'post_date' ) + ->where_column( 'post_date', '=', '1=1; --' ) + ->where_column( 'post_date', 'BETWEEN', 'post_modified' ) + ->where_column( 'post_date', 'IN', 'post_modified' ) + ->to_sql(); + + $this->assertSame( "SELECT * FROM {$prefix}posts", $sql ); + } + + /** + * Test subquery value escaping, or_where array support, and DELETE with subquery. + * + * @since 4.2.0 + * + * @return void + */ + public function test_subquery_escaping_and_mutations() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // Subquery with SQL injection payload and LIKE inside where_in(). + $sql = DB::table( 'users' ) + ->where_in( + 'user_login', + function ( $q ) { + $q->from( 'usermeta' ) + ->select( 'meta_key' ) + ->where( 'meta_value', "val' OR '1'='1" ); + } + ) + ->to_sql(); + + $this->assertSame( + "SELECT * FROM {$prefix}users WHERE user_login IN (SELECT meta_key FROM {$prefix}usermeta WHERE meta_value = 'val\' OR \'1\'=\'1')", + $sql + ); + + // or_where() with array conditions. + $sql = DB::table( 'users' ) + ->where( 'user_status', 0 ) + ->or_where( + array( + 'user_login' => 'admin', + array( 'ID', '>', 5 ), + ) + ) + ->to_sql(); + + $this->assertSame( + "SELECT * FROM {$prefix}users WHERE user_status = 0 OR user_login = 'admin' OR ID > 5", + $sql + ); + + // Live DELETE with subquery. + $key = 'subquery_del_test_' . time() . '_' . wp_rand( 1000, 9999 ); + DB::table( 'options' )->insert( + array( + 'option_name' => $key, + 'option_value' => 'to_delete', + 'autoload' => 'no', + ) + ); + + $deleted = DB::table( 'options' ) + ->where_in( + 'option_name', + function ( $q ) use ( $key ) { + $q->from( + function ( $inner ) use ( $key ) { + $inner->from( 'options' ) + ->select( 'option_name' ) + ->where( 'option_name', $key ); + }, + 'sub' + )->select( 'option_name' ); + } + ) + ->delete(); + + $this->assertSame( 1, $deleted ); + $this->assertNull( DB::table( 'options' )->where( 'option_name', $key )->first() ); + } + + /** + * Test left-hand-side subqueries in where() and or_where(). + * + * @since 4.2.0 + * + * @return void + */ + public function test_where_lhs_subquery() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // 3-arg LHS subquery with Closure. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->where( + function ( $q ) { + $q->from( 'tutor_orders', 'o' ) + ->select_raw( 'COUNT(*)' ) + ->where_column( 'o.user_id', '=', 'u.id' ); + }, + '>', + 5 + ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users AS u WHERE (SELECT COUNT(*) FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id) > 5"; + $this->assertSame( $expected, $sql ); + + // 2-arg LHS subquery with DB instance (defaults to '=') and or_where. + $sub = DB::table( 'tutor_orders', 'o' ) + ->select( 'o.order_status' ) + ->where_column( 'o.user_id', 'u.id' ) + ->limit( 1 ); + + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->where( $sub, 'completed' ) + ->or_where( $sub, '!=', 'cancelled' ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users AS u WHERE (SELECT o.order_status FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id LIMIT 1 OFFSET 0) = 'completed' OR (SELECT o.order_status FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id LIMIT 1 OFFSET 0) != 'cancelled'"; + $this->assertSame( $expected, $sql ); + + // 1-arg Closure or empty LHS subquery should be safely ignored. + $sql = DB::table( 'users' ) + ->where( + function ( $q ) { + $q->from( 'tutor_orders' ); + } + ) + ->where( + function ( $q ) { + // Empty subquery. + }, + '=', + 1 + ) + ->to_sql(); + + $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + } + + /** + * Test select() array shorthand for columns and subqueries, and cross_join_sub() / join_sub() $type. + * + * @since 4.2.0 + * + * @return void + */ + public function test_select_array_subquery_and_cross_join_sub() { + global $wpdb; + + $prefix = $wpdb->prefix; + $sub = DB::table( 'tutor_orders' )->select_raw( 'MAX(total_price)' ); + + // select() with array of columns and alias => subquery pairs. + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->select( + array( 'u.id', 'u.user_login' ), + array( + 'order_count' => function ( $q ) { + $q->from( 'tutor_orders', 'o' ) + ->select_raw( 'COUNT(*)' ) + ->where_column( 'o.user_id', '=', 'u.id' ); + }, + 'max_spent' => $sub, + 'bad alias;' => $sub, + ) + ) + ->to_sql(); + + $expected = "SELECT u.id, u.user_login, (SELECT COUNT(*) FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id) AS order_count, (SELECT MAX(total_price) FROM {$prefix}tutor_orders) AS max_spent FROM {$prefix}users AS u"; + $this->assertSame( $expected, $sql ); + + // join_sub() with explicit $type parameter and cross_join_sub(). + $agg = DB::table( 'tutor_orders' ) + ->select( 'user_id' ) + ->select_raw( 'SUM(total_price) AS total_spent' ) + ->group_by( 'user_id' ); + + $sql = DB::table( 'users' ) + ->as( 'u' ) + ->join_sub( $agg, 's', 'u.id', '=', 's.user_id', 'LEFT' ) + ->cross_join_sub( $sub, 'm' ) + ->cross_join_sub( $sub, 'invalid alias;' ) + ->to_sql(); + + $expected = "SELECT * FROM {$prefix}users AS u LEFT JOIN (SELECT user_id, SUM(total_price) AS total_spent FROM {$prefix}tutor_orders GROUP BY user_id) AS s ON u.id = s.user_id CROSS JOIN (SELECT MAX(total_price) FROM {$prefix}tutor_orders) AS m"; + $this->assertSame( $expected, $sql ); + } } From ec9aa720362ce7941992f01d661eb35a57d01102 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 25 Nov 2026 13:10:44 +0600 Subject: [PATCH 05/13] refactor: update @since version tags from 4.2.0 to 4.3.0 in DB class --- core/DB.php | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/core/DB.php b/core/DB.php index e19d52a494..95503dd1ee 100644 --- a/core/DB.php +++ b/core/DB.php @@ -198,7 +198,7 @@ class DB { /** * Supported comparison operators for column-to-column and scalar comparisons. * - * @since 4.2.0 + * @since 4.3.0 * * @var string[] */ @@ -306,7 +306,7 @@ public function from( $table, ?string $alias = null ): self { /** * Set a derived table subquery as the FROM source. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the derived table. @@ -363,7 +363,7 @@ public function select( ...$columns ): self { /** * Internal helper to validate and append a single SELECT column or alias. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $column Column name or aliased expression. * @@ -405,7 +405,7 @@ public function select_raw( string $expression, array $bindings = array() ): sel /** * Add a subquery expression to the SELECT columns. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Column alias. @@ -538,7 +538,7 @@ public function join_sub( $subquery, string $alias, $first, string $operator = ' * * Supports standard 4-argument syntax or a closure for multiple ON conditions. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the subquery table. @@ -574,7 +574,7 @@ public function right_join_sub( $subquery, string $alias, $first, string $operat /** * Add a CROSS JOIN subquery clause. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the subquery table. @@ -597,7 +597,7 @@ public function cross_join_sub( $subquery, string $alias ): self { /** * Internal method to parse and prepare a join table with optional alias. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $table Table name, may include alias e.g., 'users AS u'. * @@ -751,7 +751,7 @@ private function compile_join( string $type, string $table_expr, $first, string /** * Internal method to add a JOIN subquery clause. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $type Join type (INNER, LEFT, RIGHT). * @param Closure|self $subquery Subquery closure or DB instance. @@ -839,7 +839,7 @@ public function where_column( string $first, string $operator_or_second, ?string /** * Add an OR WHERE condition comparing two columns. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $first First column name. * @param string $operator_or_second Operator (if 3 args) or second column (if 2 args). @@ -854,7 +854,7 @@ public function or_where_column( string $first, string $operator_or_second, ?str /** * Add a WHERE IN condition or subquery. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $column Column name. * @param array|Closure|self $values Array of values, Closure, or DB subquery. @@ -990,7 +990,7 @@ public function or_where_not_null( string $column ): self { /** * Add a WHERE EXISTS subquery condition. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @@ -1003,7 +1003,7 @@ public function where_exists( $subquery ): self { /** * Add an OR WHERE EXISTS subquery condition. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @@ -1016,7 +1016,7 @@ public function or_where_exists( $subquery ): self { /** * Add a WHERE NOT EXISTS subquery condition. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @@ -1029,7 +1029,7 @@ public function where_not_exists( $subquery ): self { /** * Add an OR WHERE NOT EXISTS subquery condition. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @@ -1870,7 +1870,7 @@ public function to_sql(): string { * * Supports both associative column-value pairs and numeric array triples/tuples. * - * @since 4.2.0 + * @since 4.3.0 * * @param array $conditions Array of conditions. * @param string $boolean Boolean connector (AND or OR). @@ -1901,7 +1901,7 @@ private function add_array_where( array $conditions, string $boolean = 'AND' ): /** * Internal dispatcher for where() and or_where(). * - * @since 4.2.0 + * @since 4.3.0 * * @param mixed $column Column name, array of conditions, or LHS subquery. * @param mixed $operator_or_value Operator or value. @@ -1934,7 +1934,7 @@ private function dispatch_where( $column, $operator_or_value, $value, string $bo /** * Internal method to add a WHERE condition with a subquery on the left-hand side. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param mixed $operator_or_value Operator or value. @@ -1980,7 +1980,7 @@ private function add_where( string $column, $operator_or_value, $value, string $ /** * Shared helper to format and append a WHERE condition for a validated LHS expression. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $lhs Validated column or parenthesized subquery. * @param mixed $operator_or_value Operator or value. @@ -2088,7 +2088,7 @@ private function add_where_in( string $column, $values, string $type, string $bo /** * Internal method to add WHERE EXISTS / NOT EXISTS condition. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param string $type EXISTS or NOT EXISTS. @@ -2111,7 +2111,7 @@ private function add_where_exists( $subquery, string $type, string $boolean ): s /** * Internal method to add a WHERE condition comparing two columns. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $first First column name. * @param string $operator_or_second Operator or second column if 2 args. @@ -2512,7 +2512,7 @@ private static function get_placeholder( $value ): string { /** * Resolve a subquery from a Closure or DB instance into a SQL string. * - * @since 4.2.0 + * @since 4.3.0 * * @param mixed $query Closure or DB instance. * From 3bdf4fb3ba2eafc31f43d8b6f1c04b232ada61c4 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 17:42:19 +0600 Subject: [PATCH 06/13] request changes added --- core/DB.php | 375 +++++++++++++++++++++++++--------- docs/developer/core/DB.php.md | 74 ++++++- tests/phpunit/DBTest.php | 309 +++++++++++++++++----------- 3 files changed, 537 insertions(+), 221 deletions(-) diff --git a/core/DB.php b/core/DB.php index 95503dd1ee..57b8540abc 100644 --- a/core/DB.php +++ b/core/DB.php @@ -13,6 +13,7 @@ namespace Tutor\Core; use Closure; +use InvalidArgumentException; use Tutor\Exceptions\DatabaseException; /** @@ -60,6 +61,15 @@ class DB { */ private $alias = ''; + /** + * Whether the primary FROM source is a derived table subquery. + * + * @since 4.3.0 + * + * @var bool + */ + private $is_derived = false; + /** * Columns to select. * @@ -253,13 +263,18 @@ public static function set_db( ?\wpdb $db = null ): void { * * The table name will be automatically prefixed with the WordPress * table prefix if not already present. If a Closure or DB instance is - * provided, it will be treated as a derived table subquery. + * provided, it will be treated as a derived table subquery (which requires + * an alias before the query is built). Note: DB subquery instances are + * compiled eagerly when passed. * * @since 4.2.0 + * @since 4.3.0 Added subquery and alias support. * * @param string|Closure|self $table Table name or subquery. * @param string|null $alias Optional table alias. * + * @throws InvalidArgumentException If table name, subquery, or alias is invalid. + * * @return self */ public static function table( $table, ?string $alias = null ): self { @@ -272,31 +287,41 @@ public static function table( $table, ?string $alias = null ): self { * Alias for setting the table on an existing instance, commonly used * inside subquery closures: function( $q ) { $q->from('orders'); } * - * @since 4.2.0 + * @since 4.3.0 * * @param string|Closure|self $table Table name or subquery. * @param string|null $alias Optional table alias. * + * @throws InvalidArgumentException If table name, subquery, or alias is invalid. + * * @return self */ public function from( $table, ?string $alias = null ): self { + if ( null !== $alias && ! self::is_valid_identifier( $alias ) ) { + throw new InvalidArgumentException( 'Invalid table alias.' ); + } + if ( $table instanceof Closure || $table instanceof self ) { - $sub_sql = self::resolve_subquery( $table ); - if ( ! empty( $sub_sql ) ) { - $this->table = "({$sub_sql})"; - if ( null !== $alias && self::is_valid_identifier( $alias ) ) { - $this->alias = $alias; - } - } + $sub_sql = self::resolve_subquery( $table ); + $this->table = "({$sub_sql})"; + $this->is_derived = true; + $this->alias = null !== $alias ? $alias : ''; + return $this; } if ( ! is_string( $table ) || '' === trim( $table ) ) { - return $this; + throw new InvalidArgumentException( 'Table name must be a non-empty string.' ); } - $this->table = self::prepare_table_name( $table ); - if ( null !== $alias && self::is_valid_identifier( $alias ) ) { + $prepared_table = self::prepare_table_name( trim( $table ) ); + if ( ! self::is_valid_identifier( $prepared_table ) ) { + throw new InvalidArgumentException( 'Invalid table name.' ); + } + + $this->table = $prepared_table; + $this->is_derived = false; + if ( null !== $alias ) { $this->alias = $alias; } @@ -311,11 +336,17 @@ public function from( $table, ?string $alias = null ): self { * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the derived table. * + * @throws InvalidArgumentException If subquery or alias is invalid. + * * @return self */ public function from_sub( $subquery, string $alias ): self { - if ( ! ( $subquery instanceof Closure || $subquery instanceof self ) || ! self::is_valid_identifier( $alias ) ) { - return $this; + if ( ! ( $subquery instanceof Closure || $subquery instanceof self ) ) { + throw new InvalidArgumentException( 'Subquery must be a Closure or DB instance.' ); + } + + if ( ! self::is_valid_identifier( $alias ) ) { + throw new InvalidArgumentException( 'Derived table alias must be a valid identifier.' ); } return $this->from( $subquery, $alias ); @@ -345,6 +376,11 @@ public function select( ...$columns ): self { foreach ( $column as $key => $val ) { if ( is_string( $key ) && ( $val instanceof Closure || $val instanceof self ) ) { $this->select_sub( $val, $key ); + } elseif ( is_string( $key ) && is_string( $val ) ) { + if ( ! self::is_valid_column( $val ) || ! self::is_valid_identifier( $key ) ) { + throw new InvalidArgumentException( 'Invalid column or alias in select().' ); + } + $this->columns[] = "{$val} AS {$key}"; } elseif ( is_string( $val ) ) { $this->add_select_column( $val ); } @@ -414,13 +450,11 @@ public function select_raw( string $expression, array $bindings = array() ): sel */ public function select_sub( $subquery, string $alias ): self { if ( ! self::is_valid_identifier( $alias ) ) { - return $this; + throw new InvalidArgumentException( 'Invalid column alias in select_sub().' ); } - $sub_sql = self::resolve_subquery( $subquery ); - if ( ! empty( $sub_sql ) ) { - $this->raw_columns[] = "({$sub_sql}) AS {$alias}"; - } + $sub_sql = self::resolve_subquery( $subquery ); + $this->raw_columns[] = "({$sub_sql}) AS {$alias}"; return $this; } @@ -518,7 +552,7 @@ public function right_join( string $table, $first, string $operator = '', string * * Supports standard 4-argument syntax or a closure for multiple ON conditions. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the subquery table. @@ -527,6 +561,8 @@ public function right_join( string $table, $first, string $operator = '', string * @param string $second Second column in ON condition. * @param string $type Join type (INNER, LEFT, RIGHT, CROSS). Default 'INNER'. * + * @throws InvalidArgumentException If join type, alias, or subquery is invalid. + * * @return self */ public function join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '', string $type = 'INNER' ): self { @@ -557,7 +593,7 @@ public function left_join_sub( $subquery, string $alias, $first, string $operato * * Supports standard 4-argument syntax or a closure for multiple ON conditions. * - * @since 4.2.0 + * @since 4.3.0 * * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the subquery table. @@ -579,17 +615,17 @@ public function right_join_sub( $subquery, string $alias, $first, string $operat * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the subquery table. * + * @throws InvalidArgumentException If alias or subquery is invalid. + * * @return self */ public function cross_join_sub( $subquery, string $alias ): self { if ( ! self::is_valid_identifier( $alias ) ) { - return $this; + throw new InvalidArgumentException( 'Invalid alias in cross_join_sub().' ); } - $sub_sql = self::resolve_subquery( $subquery ); - if ( ! empty( $sub_sql ) ) { - $this->joins[] = "CROSS JOIN ({$sub_sql}) AS {$alias}"; - } + $sub_sql = self::resolve_subquery( $subquery ); + $this->joins[] = "CROSS JOIN ({$sub_sql}) AS {$alias}"; return $this; } @@ -597,19 +633,28 @@ public function cross_join_sub( $subquery, string $alias ): self { /** * Internal method to parse and prepare a join table with optional alias. * - * @since 4.3.0 + * @since 4.2.0 * * @param string $table Table name, may include alias e.g., 'users AS u'. * + * @throws InvalidArgumentException If table name or alias is invalid. + * * @return string */ private function parse_join_table( string $table ): string { - $parts = preg_split( '/\s+(?:AS\s+)?/i', $table, 2 ); + $parts = preg_split( '/\s+(?:AS\s+)?/i', trim( $table ), 2 ); $table_name = self::prepare_table_name( trim( $parts[0] ) ); $table_alias = isset( $parts[1] ) ? trim( $parts[1] ) : ''; + if ( ! self::is_valid_identifier( $table_name ) ) { + throw new InvalidArgumentException( 'Invalid join table name.' ); + } + $table_expr = $table_name; - if ( ! empty( $table_alias ) && self::is_valid_identifier( $table_alias ) ) { + if ( '' !== $table_alias ) { + if ( ! self::is_valid_identifier( $table_alias ) ) { + throw new InvalidArgumentException( 'Invalid join table alias.' ); + } $table_expr .= " AS {$table_alias}"; } @@ -678,11 +723,12 @@ public function or_on( string $first, string $operator_or_second, ?string $secon * @return self */ private function add_on( string $first, string $operator, string $second, string $boolean ): self { - if ( DB::is_valid_column( $first ) - && DB::is_valid_operator( $operator ) - && DB::is_valid_column( $second ) - ) { - $operator = strtoupper( $operator ); + $operator = strtoupper( $operator ); + if ( ! DB::is_valid_comparison_operator( $operator ) ) { + throw new InvalidArgumentException( "Invalid JOIN ON operator '{$operator}'." ); + } + + if ( DB::is_valid_column( $first ) && DB::is_valid_column( $second ) ) { $this->conditions[] = array( 'sql' => "{$first} {$operator} {$second}", 'boolean' => $boolean, @@ -707,6 +753,8 @@ private function add_on( string $first, string $operator, string $second, string * @param string $operator Comparison operator. * @param string $second Second column in ON condition. * + * @throws InvalidArgumentException If join type or operator is invalid. + * * @return self */ private function compile_join( string $type, string $table_expr, $first, string $operator, string $second ): self { @@ -714,7 +762,7 @@ private function compile_join( string $type, string $table_expr, $first, string $allowed_types = array( 'INNER', 'LEFT', 'RIGHT', 'CROSS' ); if ( ! in_array( $type, $allowed_types, true ) ) { - return $this; + throw new InvalidArgumentException( "Invalid join type '{$type}'." ); } if ( $first instanceof Closure ) { @@ -736,12 +784,15 @@ private function compile_join( string $type, string $table_expr, $first, string return $this; } + $operator = strtoupper( $operator ); + if ( ! self::is_valid_comparison_operator( $operator ) ) { + throw new InvalidArgumentException( "Invalid JOIN operator '{$operator}'." ); + } + if ( is_string( $first ) && self::is_valid_column( $first ) - && self::is_valid_operator( $operator ) && self::is_valid_column( $second ) ) { - $operator = strtoupper( $operator ); $this->joins[] = "{$type} JOIN {$table_expr} ON {$first} {$operator} {$second}"; } @@ -753,24 +804,29 @@ private function compile_join( string $type, string $table_expr, $first, string * * @since 4.3.0 * - * @param string $type Join type (INNER, LEFT, RIGHT). + * @param string $type Join type (INNER, LEFT, RIGHT, CROSS). * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Alias for the subquery table. * @param string|Closure $first First column in ON condition, or Closure. * @param string $operator Comparison operator. * @param string $second Second column in ON condition. * + * @throws InvalidArgumentException If join type, alias, or subquery is invalid. + * * @return self */ private function add_subquery_join( string $type, $subquery, string $alias, $first, string $operator, string $second ): self { + $type = strtoupper( $type ); + $allowed_types = array( 'INNER', 'LEFT', 'RIGHT', 'CROSS' ); + if ( ! in_array( $type, $allowed_types, true ) ) { + throw new InvalidArgumentException( "Invalid join type '{$type}'." ); + } + if ( ! self::is_valid_identifier( $alias ) ) { - return $this; + throw new InvalidArgumentException( 'Invalid alias in join_sub().' ); } $sub_sql = self::resolve_subquery( $subquery ); - if ( empty( $sub_sql ) ) { - return $this; - } return $this->compile_join( $type, "({$sub_sql}) AS {$alias}", $first, $operator, $second ); } @@ -824,7 +880,7 @@ public function or_where( $column, $operator_or_value = null, $value = null ): s * Useful for correlated subqueries where an inner subquery column is compared * to an outer table column: where_column('o.user_id', '=', 'u.id'). * - * @since 4.2.0 + * @since 4.3.0 * * @param string $first First column name. * @param string $operator_or_second Operator (if 3 args) or second column (if 2 args). @@ -854,7 +910,8 @@ public function or_where_column( string $first, string $operator_or_second, ?str /** * Add a WHERE IN condition or subquery. * - * @since 4.3.0 + * @since 4.2.0 + * @since 4.3.0 Added subquery support. * * @param string $column Column name. * @param array|Closure|self $values Array of values, Closure, or DB subquery. @@ -1667,6 +1724,10 @@ public function when( $condition, callable $callback, ?callable $default_callbac * @return int Inserted row ID. */ public function insert( array $data, array $format = array() ): int { + if ( $this->is_derived ) { + throw new InvalidArgumentException( 'Insert operations are not allowed on a derived table.' ); + } + $db = self::get_db(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery @@ -1694,6 +1755,10 @@ public function insert( array $data, array $format = array() ): int { * @return bool True on success. */ public function insert_multiple( array $rows ): bool { + if ( $this->is_derived ) { + throw new InvalidArgumentException( 'Insert operations are not allowed on a derived table.' ); + } + if ( empty( $rows ) ) { return false; } @@ -1756,6 +1821,10 @@ public function insert_multiple( array $rows ): bool { * @return bool True on success. */ public function update( array $data ): bool { + if ( $this->is_derived ) { + throw new InvalidArgumentException( 'Update operations are not allowed on a derived table.' ); + } + if ( empty( $data ) ) { return false; } @@ -1812,6 +1881,10 @@ public function update( array $data ): bool { * @return int Number of affected rows. */ public function delete(): int { + if ( $this->is_derived ) { + throw new InvalidArgumentException( 'Delete operations are not allowed on a derived table.' ); + } + $where_clause = $this->build_where_sql(); if ( ! empty( $this->alias ) ) { @@ -1878,20 +1951,66 @@ public function to_sql(): string { * @return self */ private function add_array_where( array $conditions, string $boolean = 'AND' ): self { + if ( empty( $conditions ) ) { + return $this; + } + + $saved_wheres = $this->wheres; + $this->wheres = array(); + foreach ( $conditions as $key => $val ) { if ( is_string( $key ) ) { - // Associative array: column => value. - $this->add_where( $key, $val, null, $boolean, true ); + if ( is_array( $val ) ) { + $this->add_where_in( $key, $val, 'IN', 'AND' ); + } else { + // Associative array: column => value. + $this->add_where( $key, $val, null, 'AND', true ); + } } elseif ( is_array( $val ) ) { // Numeric array: ['col', 'val'] or ['col', 'op', 'val']. $items = array_values( $val ); $count = count( $items ); if ( 2 === $count && is_string( $items[0] ) ) { - $this->add_where( $items[0], $items[1], null, $boolean, true ); + if ( is_array( $items[1] ) ) { + $this->add_where_in( $items[0], $items[1], 'IN', 'AND' ); + } else { + $this->add_where( $items[0], $items[1], null, 'AND', true ); + } } elseif ( 3 === $count && is_string( $items[0] ) ) { - $this->add_where( $items[0], $items[1], $items[2], $boolean, false ); + $this->add_where( $items[0], $items[1], $items[2], 'AND', false ); + } else { + $this->wheres = $saved_wheres; + throw new InvalidArgumentException( 'Invalid condition tuple in where() array.' ); } + } else { + $this->wheres = $saved_wheres; + throw new InvalidArgumentException( 'Invalid condition format in where() array.' ); + } + } + + $group_wheres = $this->wheres; + $this->wheres = $saved_wheres; + + if ( empty( $group_wheres ) ) { + return $this; + } + + if ( 'OR' === $boolean && count( $group_wheres ) > 1 ) { + $parts = array(); + foreach ( $group_wheres as $index => $where ) { + $parts[] = 0 === $index ? $where['sql'] : "{$where['boolean']} {$where['sql']}"; + } + $this->wheres[] = array( + 'sql' => '(' . implode( ' ', $parts ) . ')', + 'boolean' => 'OR', + ); + } else { + foreach ( $group_wheres as $index => $where ) { + $this->wheres[] = array( + 'sql' => $where['sql'], + 'boolean' => 0 === $index ? $boolean : 'AND', + ); } } @@ -1903,12 +2022,14 @@ private function add_array_where( array $conditions, string $boolean = 'AND' ): * * @since 4.3.0 * - * @param mixed $column Column name, array of conditions, or LHS subquery. + * @param mixed $column Column name, array of conditions, Closure, or LHS subquery. * @param mixed $operator_or_value Operator or value. * @param mixed $value Value when operator is specified. * @param string $boolean AND or OR. * @param int $arg_count Number of arguments passed to the caller. * + * @throws InvalidArgumentException If arguments are invalid or closure produces no conditions. + * * @return self */ private function dispatch_where( $column, $operator_or_value, $value, string $boolean, int $arg_count ): self { @@ -1916,16 +2037,40 @@ private function dispatch_where( $column, $operator_or_value, $value, string $bo return $this->add_array_where( $column, $boolean ); } - if ( $column instanceof Closure || $column instanceof self ) { + if ( $column instanceof Closure ) { if ( $arg_count < 2 ) { + $sub = new self(); + $column( $sub ); + $group_sql = $sub->build_where_sql(); + if ( '' === $group_sql ) { + throw new InvalidArgumentException( 'Where closure produced no conditions.' ); + } + + $this->wheres[] = array( + 'sql' => "({$group_sql})", + 'boolean' => $boolean, + ); + return $this; } return $this->add_where_sub( $column, $operator_or_value, $value, $boolean, $arg_count < 3 ); } + if ( $column instanceof self ) { + if ( $arg_count < 2 ) { + throw new InvalidArgumentException( 'Subquery in where() requires an operator and value.' ); + } + + return $this->add_where_sub( $column, $operator_or_value, $value, $boolean, $arg_count < 3 ); + } + if ( ! is_string( $column ) ) { - return $this; + throw new InvalidArgumentException( 'Column name must be a string, array, or Closure.' ); + } + + if ( $arg_count < 2 ) { + throw new InvalidArgumentException( 'where() requires at least 2 arguments when column is a string.' ); } return $this->add_where( $column, $operator_or_value, $value, $boolean, $arg_count < 3 ); @@ -1946,9 +2091,6 @@ private function dispatch_where( $column, $operator_or_value, $value, string $bo */ private function add_where_sub( $subquery, $operator_or_value, $value, string $boolean, bool $is_two_arg ): self { $sub_sql = self::resolve_subquery( $subquery ); - if ( empty( $sub_sql ) ) { - return $this; - } return $this->append_where_condition( "({$sub_sql})", $operator_or_value, $value, $boolean, $is_two_arg ); } @@ -1967,6 +2109,8 @@ private function add_where_sub( $subquery, $operator_or_value, $value, string $b * @param string $boolean AND or OR. * @param bool $is_two_arg Whether this is a two-argument call. * + * @throws InvalidArgumentException If column name is invalid. + * * @return self */ private function add_where( string $column, $operator_or_value, $value, string $boolean, bool $is_two_arg ): self { @@ -1988,6 +2132,8 @@ private function add_where( string $column, $operator_or_value, $value, string $ * @param string $boolean AND or OR. * @param bool $is_two_arg Whether this is a two-argument call. * + * @throws InvalidArgumentException If operator or value is invalid. + * * @return self */ private function append_where_condition( string $lhs, $operator_or_value, $value, string $boolean, bool $is_two_arg ): self { @@ -2003,20 +2149,23 @@ private function append_where_condition( string $lhs, $operator_or_value, $value if ( $value instanceof Closure || $value instanceof self ) { $allowed_subquery_ops = array_merge( self::$comparison_operators, array( 'IN', 'NOT IN' ) ); if ( ! in_array( $operator, $allowed_subquery_ops, true ) ) { - return $this; + throw new InvalidArgumentException( "Invalid operator '{$operator}' for subquery comparison." ); } - $sub_sql = self::resolve_subquery( $value ); - if ( ! empty( $sub_sql ) ) { - $this->wheres[] = array( - 'sql' => "{$lhs} {$operator} ({$sub_sql})", - 'boolean' => $boolean, - ); - } + $allow_limit = ! in_array( $operator, array( 'IN', 'NOT IN' ), true ); + $sub_sql = self::resolve_subquery( $value, $allow_limit ); + $this->wheres[] = array( + 'sql' => "{$lhs} {$operator} ({$sub_sql})", + 'boolean' => $boolean, + ); return $this; } + if ( is_array( $value ) ) { + throw new InvalidArgumentException( 'Array values are not supported in scalar where() comparisons; use where_in() instead.' ); + } + // Handle null values → IS NULL / IS NOT NULL. if ( is_null( $value ) ) { $null_op = in_array( $operator, array( '!=', '<>' ), true ) ? 'IS NOT' : 'IS'; @@ -2052,27 +2201,27 @@ private function append_where_condition( string $lhs, $operator_or_value, $value * @param string $type IN or NOT IN. * @param string $boolean AND or OR. * + * @throws InvalidArgumentException If column, values, or subquery is invalid. + * * @return self */ private function add_where_in( string $column, $values, string $type, string $boolean ): self { if ( ! self::is_valid_column( $column ) ) { - return $this; + throw new InvalidArgumentException( 'Invalid column name in where_in().' ); } if ( $values instanceof Closure || $values instanceof self ) { - $sub_sql = self::resolve_subquery( $values ); - if ( ! empty( $sub_sql ) ) { - $this->wheres[] = array( - 'sql' => "{$column} {$type} ({$sub_sql})", - 'boolean' => $boolean, - ); - } + $sub_sql = self::resolve_subquery( $values, false ); + $this->wheres[] = array( + 'sql' => "{$column} {$type} ({$sub_sql})", + 'boolean' => $boolean, + ); return $this; } if ( ! is_array( $values ) || empty( $values ) ) { - return $this; + throw new InvalidArgumentException( 'where_in() values must be a non-empty array or subquery.' ); } $escaped_values = self::prepare_in_clause( $values ); @@ -2094,16 +2243,16 @@ private function add_where_in( string $column, $values, string $type, string $bo * @param string $type EXISTS or NOT EXISTS. * @param string $boolean AND or OR. * + * @throws InvalidArgumentException If subquery is invalid or empty. + * * @return self */ private function add_where_exists( $subquery, string $type, string $boolean ): self { - $sub_sql = self::resolve_subquery( $subquery ); - if ( ! empty( $sub_sql ) ) { - $this->wheres[] = array( - 'sql' => "{$type} ({$sub_sql})", - 'boolean' => $boolean, - ); - } + $sub_sql = self::resolve_subquery( $subquery ); + $this->wheres[] = array( + 'sql' => "{$type} ({$sub_sql})", + 'boolean' => $boolean, + ); return $this; } @@ -2118,6 +2267,8 @@ private function add_where_exists( $subquery, string $type, string $boolean ): s * @param string|null $second Second column name if 3 args. * @param string $boolean AND or OR. * + * @throws InvalidArgumentException If columns or operator are invalid. + * * @return self */ private function add_where_column( string $first, string $operator_or_second, ?string $second, string $boolean ): self { @@ -2128,16 +2279,18 @@ private function add_where_column( string $first, string $operator_or_second, ?s $operator = strtoupper( $operator_or_second ); } - if ( self::is_valid_column( $first ) - && in_array( $operator, self::$comparison_operators, true ) - && self::is_valid_column( $second ) + if ( ! self::is_valid_column( $first ) + || ! self::is_valid_comparison_operator( $operator ) + || ! self::is_valid_column( $second ) ) { - $this->wheres[] = array( - 'sql' => "{$first} {$operator} {$second}", - 'boolean' => $boolean, - ); + throw new InvalidArgumentException( 'Invalid column or operator in where_column().' ); } + $this->wheres[] = array( + 'sql' => "{$first} {$operator} {$second}", + 'boolean' => $boolean, + ); + return $this; } @@ -2243,6 +2396,11 @@ private function add_where_raw( string $expression, array $bindings, string $boo private function build_select_query( bool $calc_found_rows = false ): string { $select = $this->build_select_sql(); $from = $this->build_from_sql(); + + if ( empty( $from ) && ( empty( $this->raw_columns ) || ! empty( $this->columns ) || ! empty( $this->joins ) || ! empty( $this->wheres ) || ! empty( $this->group_by_columns ) || ! empty( $this->havings ) || ! empty( $this->order_by_clauses ) ) ) { + throw new InvalidArgumentException( 'Query requires a FROM table unless selecting raw expressions only.' ); + } + $join = $this->build_join_sql(); $where = $this->build_where_sql(); $group = $this->build_group_by_sql(); @@ -2317,6 +2475,10 @@ private function build_select_sql(): string { * @return string */ private function build_from_sql(): string { + if ( $this->is_derived && empty( $this->alias ) ) { + throw new InvalidArgumentException( 'Derived table subquery must have an alias.' ); + } + if ( ! empty( $this->alias ) ) { return "{$this->table} AS {$this->alias}"; } @@ -2484,6 +2646,19 @@ public static function is_valid_operator( string $operator ): bool { return in_array( strtoupper( $operator ), self::$valid_operators, true ); } + /** + * Check whether a comparison operator is valid for column-to-column comparisons. + * + * @since 4.3.0 + * + * @param string $operator SQL operator. + * + * @return bool True if the operator is valid for column comparisons. + */ + public static function is_valid_comparison_operator( string $operator ): bool { + return in_array( strtoupper( $operator ), self::$comparison_operators, true ); + } + /** * Get the wpdb format placeholder for a value based on its PHP type. * @@ -2512,30 +2687,40 @@ private static function get_placeholder( $value ): string { /** * Resolve a subquery from a Closure or DB instance into a SQL string. * + * Keeps wpdb placeholder escapes intact via build_select_query() so + * outer prepare() calls or wpdb->query() cannot misinterpret '%' in values. + * * @since 4.3.0 * - * @param mixed $query Closure or DB instance. + * @param mixed $query Closure or DB instance. + * @param bool $allow_limit Whether LIMIT is allowed inside this subquery. + * + * @throws InvalidArgumentException If subquery is invalid, empty, or uses unsupported clauses. * - * @return string|null The SQL string, or null if invalid. + * @return string The compiled SQL string. */ - public static function resolve_subquery( $query ): ?string { + private static function resolve_subquery( $query, bool $allow_limit = true ): string { if ( $query instanceof Closure ) { $sub = new self(); $result = $query( $sub ); - $query = ( $result instanceof self ) ? $result : $sub; + $sub = ( $result instanceof self ) ? $result : $sub; + } elseif ( $query instanceof self ) { + $sub = clone $query; + } else { + throw new InvalidArgumentException( 'Subquery must be a Closure or DB instance.' ); } - if ( ! $query instanceof self ) { - return null; + if ( empty( $sub->table ) && empty( $sub->raw_columns ) ) { + throw new InvalidArgumentException( 'Subquery must define a FROM table or raw select expression.' ); } - if ( empty( $query->table ) && empty( $query->raw_columns ) ) { - return null; + if ( ! $allow_limit && null !== $sub->limit_value ) { + throw new InvalidArgumentException( 'LIMIT is not supported inside IN/NOT IN subqueries.' ); } - $sql = $query->to_sql(); + $sub->lock = ''; - return ! empty( $sql ) ? $sql : null; + return $sub->build_select_query(); } /** diff --git a/docs/developer/core/DB.php.md b/docs/developer/core/DB.php.md index 955aeab1e5..e1444759b1 100644 --- a/docs/developer/core/DB.php.md +++ b/docs/developer/core/DB.php.md @@ -69,12 +69,15 @@ $courses = DB::table('posts') ```php class DB { - // Factory - public static function table( string $table ): self; + // Factory & Source + public static function table( $table, ?string $alias = null ): self; + public function from( $table, ?string $alias = null ): self; + public function from_sub( $subquery, string $alias ): self; // Selection & Projection - public function select( string ...$columns ): self; + public function select( ...$columns ): self; public function select_raw( string $expression, array $bindings = [] ): self; + public function select_sub( $subquery, string $alias ): self; public function distinct(): self; public function as( string $alias ): self; @@ -82,14 +85,24 @@ class DB { public function join( string $table, $first, string $operator = '', string $second = '' ): self; public function left_join( string $table, $first, string $operator = '', string $second = '' ): self; public function right_join( string $table, $first, string $operator = '', string $second = '' ): self; + public function join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '', string $type = 'INNER' ): self; + public function left_join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '' ): self; + public function right_join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '' ): self; + public function cross_join_sub( $subquery, string $alias ): self; // Where Clauses public function where( $column, $operator_or_val = null, $val = null ): self; - public function or_where( string $column, $operator_or_val, $val = null ): self; - public function where_in( string $column, array $values ): self; - public function or_where_in( string $column, array $values ): self; - public function where_not_in( string $column, array $values ): self; - public function or_where_not_in( string $column, array $values ): self; + public function or_where( $column, $operator_or_val = null, $val = null ): self; + public function where_column( string $first, string $operator_or_second, ?string $second = null ): self; + public function or_where_column( string $first, string $operator_or_second, ?string $second = null ): self; + public function where_in( string $column, $values ): self; + public function or_where_in( string $column, $values ): self; + public function where_not_in( string $column, $values ): self; + public function or_where_not_in( string $column, $values ): self; + public function where_exists( $subquery ): self; + public function or_where_exists( $subquery ): self; + public function where_not_exists( $subquery ): self; + public function or_where_not_exists( $subquery ): self; public function where_null( string $column ): self; public function or_where_null( string $column ): self; public function where_not_null( string $column ): self; @@ -358,11 +371,52 @@ DB::table('tutor_orders') ``` > [!NOTE] -> All column identifiers in arrays are strictly validated against SQL injection patterns (`is_valid_column`), comparison operators are checked against whitelisted operators (`is_valid_operator`), and values are safely bound via `$wpdb->prepare()`. Empty arrays `where([])` or invalid formats are safely skipped without breaking query generation. +> All column names, table names, and aliases are strictly validated (`is_valid_column`, `is_valid_identifier`), comparison operators are checked against whitelisted operators (`is_valid_operator`), and values are safely bound via `$wpdb->prepare()`. Invalid formats, operators, or empty subqueries throw `\InvalidArgumentException` (fail-closed). Empty arrays `where([])` produce no WHERE clause. + +### 3. Subqueries & Column Comparisons +Subqueries accept either a `Closure` (receiving a fresh `DB` instance) or an existing `DB` instance (note: `DB` instances are compiled eagerly when added to the outer query). -### 3. IN / NOT IN +```php +// Derived table in FROM +DB::table(function ($q) { + $q->from('tutor_orders')->where('order_status', 'completed'); +}, 'o')->select('o.id')->get(); + +// Or using from_sub() +DB::table('posts')->from_sub($subquery, 'p')->get(); + +// Scalar subquery in SELECT +DB::table('users') + ->as('u') + ->select('u.ID') + ->select_sub(function ($q) { + $q->from('tutor_orders', 'o') + ->select_raw('COUNT(*)') + ->where_column('o.user_id', 'u.ID'); + }, 'order_count') + ->get(); + +// Subquery JOINs +DB::table('users') + ->as('u') + ->left_join_sub($subquery, 's', 'u.ID', '=', 's.user_id') + ->get(); + +// WHERE EXISTS / NOT EXISTS +DB::table('users') + ->as('u') + ->where_exists(function ($q) { + $q->from('tutor_orders', 'o')->where_column('o.user_id', 'u.ID'); + }) + ->get(); +``` + +### 4. IN / NOT IN (Values or Subquery) ```php DB::table('posts')->where_in('ID', [10, 20, 30]); +DB::table('posts')->where_in('post_author', function ($q) { + $q->from('users')->select('ID')->where('user_status', 0); +}); DB::table('posts')->where_not_in('post_status', ['trash', 'auto-draft']); DB::table('posts')->or_where_in('ID', [40, 50]); DB::table('posts')->or_where_not_in('post_type', ['attachment']); diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index 4d28ce4f7d..d2452c0851 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -271,56 +271,62 @@ public function test_where_empty_and_invalid_array_formats() { ->to_sql(); $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_empty ); - // Empty nested array ignored. - $sql_nested_empty = DB::table( 'tutor_orders' ) - ->where( array( array() ) ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_nested_empty ); + // Empty nested array throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( array() ) ); + } + ); - // Sub-array with 1 element ignored. - $sql_one_elem = DB::table( 'tutor_orders' ) - ->where( array( array( 'order_status' ) ) ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_one_elem ); + // Sub-array with 1 element throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( array( 'order_status' ) ) ); + } + ); - // Sub-array with 4 elements ignored. - $sql_four_elem = DB::table( 'tutor_orders' ) - ->where( array( array( 'order_status', '=', 'completed', 'extra' ) ) ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_four_elem ); + // Sub-array with 4 elements throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( array( 'order_status', '=', 'completed', 'extra' ) ) ); + } + ); - // Non-array scalar item in indexed array ignored. - $sql_scalar = DB::table( 'tutor_orders' ) - ->where( array( 123, 'random_string' ) ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_scalar ); + // Non-array scalar item in indexed array throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( 123, 'random_string' ) ); + } + ); - // Non-string column in sub-array ignored. - $sql_non_string_col = DB::table( 'tutor_orders' ) - ->where( array( array( 123, '=', 'active' ) ) ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_non_string_col ); + // Non-string column in sub-array throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( array( 123, '=', 'active' ) ) ); + } + ); // Invalid operator in sub-array ignored. $sql_invalid_op = DB::table( 'tutor_orders' ) ->where( array( array( 'order_status', 'INVALID_OP', 'completed' ) ) ) ->to_sql(); $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_invalid_op ); + } - // Valid conditions mixed with invalid condition formats. - $sql_mixed = DB::table( 'tutor_orders' ) - ->where( - array( - 'order_status' => 'completed', - array(), - array( 'invalid_op_col', 'BAD_OPERATOR', 'foo' ), - array( 'total_price', '>', 50 ), - 999, - ) - ) - ->to_sql(); - $expected_mixed = "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed' AND total_price > 50"; - $this->assertSame( $expected_mixed, $sql_mixed ); + /** + * Helper to assert that a callable throws InvalidArgumentException. + * + * @param callable $callback Callback expected to throw. + * + * @return void + */ + private function assert_throws_invalid_argument( callable $callback ): void { + try { + $callback(); + $this->fail( 'Expected InvalidArgumentException was not thrown.' ); + } catch ( \InvalidArgumentException $e ) { + $this->assertInstanceOf( \InvalidArgumentException::class, $e ); + } } /** @@ -1876,12 +1882,13 @@ function ( $q ) { $this->assertSame( $expected, $sql ); // Invalid alias rejection. - $sql = DB::table( 'users' ) - ->select( 'id' ) - ->select_sub( $sub, 'invalid alias;--' ) - ->to_sql(); - - $this->assertSame( "SELECT id FROM {$prefix}users", $sql ); + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' ) + ->select( 'id' ) + ->select_sub( $sub, 'invalid alias;--' ); + } + ); } /** @@ -1927,11 +1934,11 @@ function ( $q ) { $this->assertSame( $expected, $sql ); // Invalid alias rejection. - $sql = DB::table( 'users' ) - ->from_sub( $sub, 'invalid alias;--' ) - ->to_sql(); - - $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' )->from_sub( $sub, 'invalid alias;--' ); + } + ); } /** @@ -1998,11 +2005,11 @@ function ( $join ) { $this->assertSame( $expected, $sql ); // Invalid alias rejection. - $sql = DB::table( 'users' ) - ->join_sub( $sub, 'invalid alias;--', 'u.id', '=', 's.user_id' ) - ->to_sql(); - - $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' )->join_sub( $sub, 'invalid alias;--', 'u.id', '=', 's.user_id' ); + } + ); } /** @@ -2073,45 +2080,31 @@ function ( $q ) use ( $key1 ) { * @return void */ public function test_subquery_empty_and_invalid_inputs() { - global $wpdb; - - $prefix = $wpdb->prefix; $empty_closure = function ( $q ) { // Intentionally left empty. }; $empty_db = new DB(); - // Empty closure and uninitialized DB instance should be ignored. - $sql = DB::table( 'users' ) - ->where_in( 'id', $empty_closure ) - ->where_not_in( 'id', $empty_db ) - ->where_exists( $empty_closure ) - ->where_not_exists( $empty_db ) - ->select_sub( $empty_closure, 'empty_col' ) - ->join_sub( $empty_closure, 's', 'users.id', '=', 's.id' ) - ->to_sql(); - - $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); - - // Non-Closure / non-DB values passed to subquery methods should be ignored. - $sql = DB::table( 'users' ) - ->where_exists( 'SELECT 1' ) - ->select_sub( 123, 'num_col' ) - ->from_sub( 'invalid', 'sub' ) - ->join_sub( 'invalid', 's', 'users.id', '=', 's.id' ) - ->to_sql(); - - $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); - - // Invalid operators for subquery comparison in where() should be rejected. + // Empty closure and uninitialized DB instance should throw (fail closed). + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_in( 'id', $empty_closure ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_not_in( 'id', $empty_db ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_exists( $empty_closure ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_not_exists( $empty_db ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->select_sub( $empty_closure, 'empty_col' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->join_sub( $empty_closure, 's', 'users.id', '=', 's.id' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_in( 'id', array() ) ); + + // Non-Closure / non-DB values passed to subquery methods should throw. + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_exists( 'SELECT 1' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->select_sub( 123, 'num_col' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->from_sub( 'invalid', 'sub' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->join_sub( 'invalid', 's', 'users.id', '=', 's.id' ) ); + + // Invalid operators for subquery comparison in where() should throw. $valid_sub = DB::table( 'tutor_orders' )->select( 'id' ); - $sql = DB::table( 'users' ) - ->where( 'id', 'BETWEEN', $valid_sub ) - ->where( 'id', 'IS', $valid_sub ) - ->where( 'id', 'INVALID_OP', $valid_sub ) - ->to_sql(); - - $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where( 'id', 'BETWEEN', $valid_sub ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where( 'id', 'IS', $valid_sub ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where( 'id', 'INVALID_OP', $valid_sub ) ); } /** @@ -2135,9 +2128,8 @@ public function test_from_and_table_subquery_chaining() { $sql = ( new DB() )->from( 'tutor_orders', 'o' )->select( 'o.id' )->to_sql(); $this->assertSame( "SELECT o.id FROM {$prefix}tutor_orders AS o", $sql ); - // Non-string table safely ignored. - $sql = DB::table( new \stdClass() )->to_sql(); - $this->assertSame( 'SELECT *', $sql ); + // Non-string table throws InvalidArgumentException. + $this->assert_throws_invalid_argument( fn() => DB::table( new \stdClass() ) ); // Scalar subquery without FROM clause. $sql = DB::table( 'users' ) @@ -2175,15 +2167,11 @@ public function test_where_column_and_or_where_column() { $expected = "SELECT * FROM {$prefix}posts WHERE post_modified = post_date AND post_modified_gmt > post_date_gmt OR post_author = post_parent OR ID != post_parent"; $this->assertSame( $expected, $sql ); - // Invalid columns and non-comparison operators should be rejected. - $sql = DB::table( 'posts' ) - ->where_column( '1=1; --', '=', 'post_date' ) - ->where_column( 'post_date', '=', '1=1; --' ) - ->where_column( 'post_date', 'BETWEEN', 'post_modified' ) - ->where_column( 'post_date', 'IN', 'post_modified' ) - ->to_sql(); - - $this->assertSame( "SELECT * FROM {$prefix}posts", $sql ); + // Invalid columns and non-comparison operators should throw. + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_column( '1=1; --', '=', 'post_date' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_column( 'post_date', '=', '1=1; --' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_column( 'post_date', 'BETWEEN', 'post_modified' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_column( 'post_date', 'IN', 'post_modified' ) ); } /** @@ -2215,7 +2203,7 @@ function ( $q ) { $sql ); - // or_where() with array conditions. + // or_where() with array conditions (grouped with AND inside OR). $sql = DB::table( 'users' ) ->where( 'user_status', 0 ) ->or_where( @@ -2227,7 +2215,7 @@ function ( $q ) { ->to_sql(); $this->assertSame( - "SELECT * FROM {$prefix}users WHERE user_status = 0 OR user_login = 'admin' OR ID > 5", + "SELECT * FROM {$prefix}users WHERE user_status = 0 OR (user_login = 'admin' AND ID > 5)", $sql ); @@ -2305,23 +2293,40 @@ function ( $q ) { $expected = "SELECT * FROM {$prefix}users AS u WHERE (SELECT o.order_status FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id LIMIT 1 OFFSET 0) = 'completed' OR (SELECT o.order_status FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id LIMIT 1 OFFSET 0) != 'cancelled'"; $this->assertSame( $expected, $sql ); - // 1-arg Closure or empty LHS subquery should be safely ignored. + // 1-arg Closure creates a grouped WHERE (...) clause. $sql = DB::table( 'users' ) + ->where( 'user_status', 0 ) ->where( function ( $q ) { - $q->from( 'tutor_orders' ); + $q->where( 'user_login', 'admin' ) + ->or_where( 'ID', 1 ); } ) - ->where( - function ( $q ) { - // Empty subquery. - }, - '=', - 1 - ) ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}users", $sql ); + $this->assertSame( "SELECT * FROM {$prefix}users WHERE user_status = 0 AND (user_login = 'admin' OR ID = 1)", $sql ); + + // Empty 1-arg Closure or empty LHS subquery throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'users' )->where( + function ( $q ) { + // No conditions added. + } + ); + } + ); + $this->assert_throws_invalid_argument( + function () { + DB::table( 'users' )->where( + function ( $q ) { + // Empty subquery. + }, + '=', + 1 + ); + } + ); } /** @@ -2337,11 +2342,12 @@ public function test_select_array_subquery_and_cross_join_sub() { $prefix = $wpdb->prefix; $sub = DB::table( 'tutor_orders' )->select_raw( 'MAX(total_price)' ); - // select() with array of columns and alias => subquery pairs. + // select() with array of columns and alias => subquery / alias => column pairs. $sql = DB::table( 'users' ) ->as( 'u' ) ->select( array( 'u.id', 'u.user_login' ), + array( 'name' => 'u.display_name' ), array( 'order_count' => function ( $q ) { $q->from( 'tutor_orders', 'o' ) @@ -2349,14 +2355,19 @@ public function test_select_array_subquery_and_cross_join_sub() { ->where_column( 'o.user_id', '=', 'u.id' ); }, 'max_spent' => $sub, - 'bad alias;' => $sub, ) ) ->to_sql(); - $expected = "SELECT u.id, u.user_login, (SELECT COUNT(*) FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id) AS order_count, (SELECT MAX(total_price) FROM {$prefix}tutor_orders) AS max_spent FROM {$prefix}users AS u"; + $expected = "SELECT u.id, u.user_login, u.display_name AS name, (SELECT COUNT(*) FROM {$prefix}tutor_orders AS o WHERE o.user_id = u.id) AS order_count, (SELECT MAX(total_price) FROM {$prefix}tutor_orders) AS max_spent FROM {$prefix}users AS u"; $this->assertSame( $expected, $sql ); + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' )->select( array( 'bad alias;' => $sub ) ); + } + ); + // join_sub() with explicit $type parameter and cross_join_sub(). $agg = DB::table( 'tutor_orders' ) ->select( 'user_id' ) @@ -2367,10 +2378,76 @@ public function test_select_array_subquery_and_cross_join_sub() { ->as( 'u' ) ->join_sub( $agg, 's', 'u.id', '=', 's.user_id', 'LEFT' ) ->cross_join_sub( $sub, 'm' ) - ->cross_join_sub( $sub, 'invalid alias;' ) ->to_sql(); $expected = "SELECT * FROM {$prefix}users AS u LEFT JOIN (SELECT user_id, SUM(total_price) AS total_spent FROM {$prefix}tutor_orders GROUP BY user_id) AS s ON u.id = s.user_id CROSS JOIN (SELECT MAX(total_price) FROM {$prefix}tutor_orders) AS m"; $this->assertSame( $expected, $sql ); + + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' )->cross_join_sub( $sub, 'invalid alias;' ); + } + ); + } + + /** + * Test security hardening and edge-case validations from PR feedback. + * + * @since 4.3.0 + * + * @return void + */ + public function test_security_and_validation_hardening() { + global $wpdb; + + $prefix = $wpdb->prefix; + + // Table-name injection in table(), from(), and join() throws. + $this->assert_throws_invalid_argument( fn() => DB::table( 'users; DROP TABLE wp_users' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts WHERE 1=1 --' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'x' )->from( 'users; DROP TABLE wp_users' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->join( 'posts) UNION SELECT 1 -- ', 'a', '=', 'b' ) ); + + // Single-argument string where('ID') throws instead of becoming ID IS NULL. + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where( 'ID' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->or_where( 'ID' ) ); + + // Array value in associative where() routes to IN. + $sql = DB::table( 'users' )->where( array( 'ID' => array( 1, 2, 3 ) ) )->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}users WHERE ID IN (1, 2, 3)", $sql ); + + // Derived table without alias throws when building query, and write ops throw. + $sub = DB::table( 'users' )->select( 'ID' ); + $this->assert_throws_invalid_argument( fn() => DB::table( $sub )->to_sql() ); + $this->assert_throws_invalid_argument( fn() => DB::table( $sub, 's' )->update( array( 'user_status' => 1 ) ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( $sub, 's' )->delete() ); + $this->assert_throws_invalid_argument( fn() => DB::table( $sub, 's' )->insert( array( 'ID' => 1 ) ) ); + + // Invalid join type in join_sub() and invalid ON operator throw. + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->join_sub( $sub, 's', 'users.ID', '=', 's.ID', 'FULL' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->join( 'posts', 'users.ID', 'IN', 'posts.post_author' ) ); + + // lock_for_update() is stripped in subquery context; LIMIT is rejected in where_in subquery. + $locked_sub = DB::table( 'posts' )->select( 'post_author' )->lock_for_update(); + $sql = DB::table( 'users' )->where_in( 'ID', $locked_sub )->to_sql(); + $this->assertSame( "SELECT * FROM {$prefix}users WHERE ID IN (SELECT post_author FROM {$prefix}posts)", $sql ); + + $limited_sub = DB::table( 'posts' )->select( 'post_author' )->limit( 5 ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_in( 'ID', $limited_sub ) ); + + // '%' round-trip in a subquery value combined with outer where_raw() bindings. + $sql = DB::table( 'users' ) + ->where_in( + 'ID', + function ( $q ) { + $q->from( 'posts' )->select( 'post_author' )->where( 'post_title', '%s' ); + } + ) + ->where_raw( 'user_login = %s', array( 'admin' ) ) + ->to_sql(); + $this->assertSame( + "SELECT * FROM {$prefix}users WHERE ID IN (SELECT post_author FROM {$prefix}posts WHERE post_title = '%s') AND user_login = 'admin'", + $sql + ); } } From 08489e0b523d855e913f88e90e195aa08434b758 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 17:59:39 +0600 Subject: [PATCH 07/13] refactor: throw InvalidArgumentException for invalid identifiers in DB query builder --- core/DB.php | 74 +++++++++++++++++++---------------- tests/phpunit/DBTest.php | 83 ++++++++++++++++++++++------------------ 2 files changed, 87 insertions(+), 70 deletions(-) diff --git a/core/DB.php b/core/DB.php index 57b8540abc..a093c80469 100644 --- a/core/DB.php +++ b/core/DB.php @@ -479,13 +479,17 @@ public function distinct(): self { * * @param string $alias Alias for the primary table. * + * @throws InvalidArgumentException If alias is invalid. + * * @return self */ public function as( string $alias ): self { - if ( self::is_valid_identifier( $alias ) ) { - $this->alias = $alias; + if ( ! self::is_valid_identifier( $alias ) ) { + throw new InvalidArgumentException( 'Invalid table alias.' ); } + $this->alias = $alias; + return $this; } @@ -974,14 +978,7 @@ public function or_where_not_in( string $column, $values ): self { * @return self */ public function where_null( string $column ): self { - if ( self::is_valid_column( $column ) ) { - $this->wheres[] = array( - 'sql' => "{$column} IS NULL", - 'boolean' => 'AND', - ); - } - - return $this; + return $this->add_where_null( $column, 'IS NULL', 'AND' ); } /** @@ -991,17 +988,12 @@ public function where_null( string $column ): self { * * @param string $column Column name. * + * @throws InvalidArgumentException If column name is invalid. + * * @return self */ public function where_not_null( string $column ): self { - if ( self::is_valid_column( $column ) ) { - $this->wheres[] = array( - 'sql' => "{$column} IS NOT NULL", - 'boolean' => 'AND', - ); - } - - return $this; + return $this->add_where_null( $column, 'IS NOT NULL', 'AND' ); } /** @@ -1011,17 +1003,12 @@ public function where_not_null( string $column ): self { * * @param string $column Column name. * + * @throws InvalidArgumentException If column name is invalid. + * * @return self */ public function or_where_null( string $column ): self { - if ( self::is_valid_column( $column ) ) { - $this->wheres[] = array( - 'sql' => "{$column} IS NULL", - 'boolean' => 'OR', - ); - } - - return $this; + return $this->add_where_null( $column, 'IS NULL', 'OR' ); } /** @@ -1031,16 +1018,37 @@ public function or_where_null( string $column ): self { * * @param string $column Column name. * + * @throws InvalidArgumentException If column name is invalid. + * * @return self */ public function or_where_not_null( string $column ): self { - if ( self::is_valid_column( $column ) ) { - $this->wheres[] = array( - 'sql' => "{$column} IS NOT NULL", - 'boolean' => 'OR', - ); + return $this->add_where_null( $column, 'IS NOT NULL', 'OR' ); + } + + /** + * Internal helper to add an IS NULL / IS NOT NULL condition. + * + * @since 4.3.0 + * + * @param string $column Column name. + * @param string $null_op 'IS NULL' or 'IS NOT NULL'. + * @param string $boolean 'AND' or 'OR'. + * + * @throws InvalidArgumentException If column name is invalid. + * + * @return self + */ + private function add_where_null( string $column, string $null_op, string $boolean ): self { + if ( ! self::is_valid_column( $column ) ) { + throw new InvalidArgumentException( 'Invalid column name in where_null().' ); } + $this->wheres[] = array( + 'sql' => "{$column} {$null_op}", + 'boolean' => $boolean, + ); + return $this; } @@ -2115,7 +2123,7 @@ private function add_where_sub( $subquery, $operator_or_value, $value, string $b */ private function add_where( string $column, $operator_or_value, $value, string $boolean, bool $is_two_arg ): self { if ( ! self::is_valid_column( $column ) ) { - return $this; + throw new InvalidArgumentException( 'Invalid column name in where().' ); } return $this->append_where_condition( $column, $operator_or_value, $value, $boolean, $is_two_arg ); @@ -2178,7 +2186,7 @@ private function append_where_condition( string $lhs, $operator_or_value, $value } if ( ! self::is_valid_operator( $operator ) ) { - return $this; + throw new InvalidArgumentException( "Invalid operator '{$operator}'." ); } $prepared_value = self::prepare_value( $value ); diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index d2452c0851..58c1229771 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -306,11 +306,12 @@ function () { } ); - // Invalid operator in sub-array ignored. - $sql_invalid_op = DB::table( 'tutor_orders' ) - ->where( array( array( 'order_status', 'INVALID_OP', 'completed' ) ) ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders", $sql_invalid_op ); + // Invalid operator in sub-array throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( array( 'order_status', 'INVALID_OP', 'completed' ) ) ); + } + ); } /** @@ -339,38 +340,41 @@ public function test_where_array_sql_injection_and_escaping() { $prefix = $wpdb->prefix; - // Malicious column attempt in associative key should be rejected. - $sql_assoc_col = DB::table( 'tutor_orders' ) - ->where( - array( - '1=1; --' => 'val', - 'order_status' => 'completed', - ) - ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed'", $sql_assoc_col ); + // Malicious column attempt in associative key should throw. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( + array( + '1=1; --' => 'val', + 'order_status' => 'completed', + ) + ); + } + ); - // Malicious column attempt in numeric array should be rejected. - $sql_num_col = DB::table( 'tutor_orders' ) - ->where( - array( - array( 'id; DROP TABLE tutor_orders;--', '=', '1' ), - array( 'order_status', '=', 'completed' ), - ) - ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders WHERE order_status = 'completed'", $sql_num_col ); + // Malicious column attempt in numeric array should throw. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( + array( + array( 'id; DROP TABLE tutor_orders;--', '=', '1' ), + array( 'order_status', '=', 'completed' ), + ) + ); + } + ); - // Malicious operator attempt in numeric array should be rejected. - $sql_op = DB::table( 'tutor_orders' ) - ->where( - array( - array( 'order_status', '= 1; DROP TABLE tutor_orders;--', 'completed' ), - array( 'user_id', '=', 10 ), - ) - ) - ->to_sql(); - $this->assertSame( "SELECT * FROM {$prefix}tutor_orders WHERE user_id = 10", $sql_op ); + // Malicious operator attempt in numeric array should throw. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( + array( + array( 'order_status', '= 1; DROP TABLE tutor_orders;--', 'completed' ), + array( 'user_id', '=', 10 ), + ) + ); + } + ); // Value with SQL injection payload is properly escaped. $malicious_val = "active' OR '1'='1"; @@ -651,13 +655,18 @@ public function test_identifier_sanitization() { $prefix = $wpdb->prefix; - // Malicious column attempt should be ignored. + // Malicious select column attempt should be ignored; malicious where column should throw. $sql = DB::table( 'tutor_orders' ) ->select( 'id', 'status; DROP TABLE tutor_orders; --' ) - ->where( '1=1; --', 'val' ) ->to_sql(); $this->assertSame( "SELECT id FROM {$prefix}tutor_orders", $sql ); + + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( '1=1; --', 'val' ); + } + ); } /** From b77717cfc2ae3ee1261f9d130d6b52643fed8d55 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Fri, 27 Nov 2026 12:37:52 +0600 Subject: [PATCH 08/13] refactor: improve SQL validation, exception handling, and error messages in DB query builder --- core/DB.php | 149 ++++++++++++++++++++-------------- docs/developer/core/DB.php.md | 3 +- tests/phpunit/DBTest.php | 83 +++++++++++++++---- 3 files changed, 157 insertions(+), 78 deletions(-) diff --git a/core/DB.php b/core/DB.php index a093c80469..25782d310d 100644 --- a/core/DB.php +++ b/core/DB.php @@ -315,7 +315,7 @@ public function from( $table, ?string $alias = null ): self { } $prepared_table = self::prepare_table_name( trim( $table ) ); - if ( ! self::is_valid_identifier( $prepared_table ) ) { + if ( ! self::is_valid_table_name( $prepared_table ) ) { throw new InvalidArgumentException( 'Invalid table name.' ); } @@ -368,6 +368,8 @@ public function from_sub( $subquery, string $alias ): self { * * @param string|array ...$columns Column names or alias => subquery arrays. * + * @throws InvalidArgumentException If an associative alias => column pair has an invalid column or alias. + * * @return self */ public function select( ...$columns ): self { @@ -446,6 +448,8 @@ public function select_raw( string $expression, array $bindings = array() ): sel * @param Closure|self $subquery Subquery closure or DB instance. * @param string $alias Column alias. * + * @throws InvalidArgumentException If alias or subquery is invalid. + * * @return self */ public function select_sub( $subquery, string $alias ): self { @@ -650,7 +654,7 @@ private function parse_join_table( string $table ): string { $table_name = self::prepare_table_name( trim( $parts[0] ) ); $table_alias = isset( $parts[1] ) ? trim( $parts[1] ) : ''; - if ( ! self::is_valid_identifier( $table_name ) ) { + if ( ! self::is_valid_table_name( $table_name ) ) { throw new InvalidArgumentException( 'Invalid join table name.' ); } @@ -724,21 +728,25 @@ public function or_on( string $first, string $operator_or_second, ?string $secon * @param string $second Second column. * @param string $boolean Boolean connector (AND/OR). * + * @throws InvalidArgumentException If operator or column name is invalid. + * * @return self */ private function add_on( string $first, string $operator, string $second, string $boolean ): self { $operator = strtoupper( $operator ); if ( ! DB::is_valid_comparison_operator( $operator ) ) { - throw new InvalidArgumentException( "Invalid JOIN ON operator '{$operator}'." ); + throw new InvalidArgumentException( esc_html( "Invalid JOIN ON operator '{$operator}'." ) ); } - if ( DB::is_valid_column( $first ) && DB::is_valid_column( $second ) ) { - $this->conditions[] = array( - 'sql' => "{$first} {$operator} {$second}", - 'boolean' => $boolean, - ); + if ( ! DB::is_valid_column( $first ) || ! DB::is_valid_column( $second ) ) { + throw new InvalidArgumentException( 'Invalid column name in JOIN ON condition.' ); } + $this->conditions[] = array( + 'sql' => "{$first} {$operator} {$second}", + 'boolean' => $boolean, + ); + return $this; } }; @@ -757,7 +765,7 @@ private function add_on( string $first, string $operator, string $second, string * @param string $operator Comparison operator. * @param string $second Second column in ON condition. * - * @throws InvalidArgumentException If join type or operator is invalid. + * @throws InvalidArgumentException If join type, columns, or operator are invalid. * * @return self */ @@ -766,40 +774,41 @@ private function compile_join( string $type, string $table_expr, $first, string $allowed_types = array( 'INNER', 'LEFT', 'RIGHT', 'CROSS' ); if ( ! in_array( $type, $allowed_types, true ) ) { - throw new InvalidArgumentException( "Invalid join type '{$type}'." ); + throw new InvalidArgumentException( esc_html( "Invalid join type '{$type}'." ) ); } if ( $first instanceof Closure ) { $collector = self::create_join_collector(); $first( $collector ); - if ( ! empty( $collector->conditions ) ) { - $on_parts = ''; - foreach ( $collector->conditions as $index => $condition ) { - if ( 0 === $index ) { - $on_parts .= $condition['sql']; - } else { - $on_parts .= " {$condition['boolean']} {$condition['sql']}"; - } + if ( empty( $collector->conditions ) ) { + throw new InvalidArgumentException( 'JOIN closure must add at least one ON condition.' ); + } + + $on_parts = ''; + foreach ( $collector->conditions as $index => $condition ) { + if ( 0 === $index ) { + $on_parts .= $condition['sql']; + } else { + $on_parts .= " {$condition['boolean']} {$condition['sql']}"; } - $this->joins[] = "{$type} JOIN {$table_expr} ON {$on_parts}"; } + $this->joins[] = "{$type} JOIN {$table_expr} ON {$on_parts}"; return $this; } $operator = strtoupper( $operator ); if ( ! self::is_valid_comparison_operator( $operator ) ) { - throw new InvalidArgumentException( "Invalid JOIN operator '{$operator}'." ); + throw new InvalidArgumentException( esc_html( "Invalid JOIN operator '{$operator}'." ) ); } - if ( is_string( $first ) - && self::is_valid_column( $first ) - && self::is_valid_column( $second ) - ) { - $this->joins[] = "{$type} JOIN {$table_expr} ON {$first} {$operator} {$second}"; + if ( ! is_string( $first ) || ! self::is_valid_column( $first ) || ! self::is_valid_column( $second ) ) { + throw new InvalidArgumentException( 'Invalid column name in JOIN condition.' ); } + $this->joins[] = "{$type} JOIN {$table_expr} ON {$first} {$operator} {$second}"; + return $this; } @@ -823,7 +832,7 @@ private function add_subquery_join( string $type, $subquery, string $alias, $fir $type = strtoupper( $type ); $allowed_types = array( 'INNER', 'LEFT', 'RIGHT', 'CROSS' ); if ( ! in_array( $type, $allowed_types, true ) ) { - throw new InvalidArgumentException( "Invalid join type '{$type}'." ); + throw new InvalidArgumentException( esc_html( "Invalid join type '{$type}'." ) ); } if ( ! self::is_valid_identifier( $alias ) ) { @@ -1966,40 +1975,40 @@ private function add_array_where( array $conditions, string $boolean = 'AND' ): $saved_wheres = $this->wheres; $this->wheres = array(); - foreach ( $conditions as $key => $val ) { - if ( is_string( $key ) ) { - if ( is_array( $val ) ) { - $this->add_where_in( $key, $val, 'IN', 'AND' ); - } else { - // Associative array: column => value. - $this->add_where( $key, $val, null, 'AND', true ); - } - } elseif ( is_array( $val ) ) { - // Numeric array: ['col', 'val'] or ['col', 'op', 'val']. - $items = array_values( $val ); - $count = count( $items ); - - if ( 2 === $count && is_string( $items[0] ) ) { - if ( is_array( $items[1] ) ) { - $this->add_where_in( $items[0], $items[1], 'IN', 'AND' ); + try { + foreach ( $conditions as $key => $val ) { + if ( is_string( $key ) ) { + if ( is_array( $val ) ) { + $this->add_where_in( $key, $val, 'IN', 'AND' ); + } else { + // Associative array: column => value. + $this->add_where( $key, $val, null, 'AND', true ); + } + } elseif ( is_array( $val ) ) { + // Numeric array: ['col', 'val'] or ['col', 'op', 'val']. + $items = array_values( $val ); + $count = count( $items ); + + if ( 2 === $count && is_string( $items[0] ) ) { + if ( is_array( $items[1] ) ) { + $this->add_where_in( $items[0], $items[1], 'IN', 'AND' ); + } else { + $this->add_where( $items[0], $items[1], null, 'AND', true ); + } + } elseif ( 3 === $count && is_string( $items[0] ) ) { + $this->add_where( $items[0], $items[1], $items[2], 'AND', false ); } else { - $this->add_where( $items[0], $items[1], null, 'AND', true ); + throw new InvalidArgumentException( 'Invalid condition tuple in where() array.' ); } - } elseif ( 3 === $count && is_string( $items[0] ) ) { - $this->add_where( $items[0], $items[1], $items[2], 'AND', false ); } else { - $this->wheres = $saved_wheres; - throw new InvalidArgumentException( 'Invalid condition tuple in where() array.' ); + throw new InvalidArgumentException( 'Invalid condition format in where() array.' ); } - } else { - $this->wheres = $saved_wheres; - throw new InvalidArgumentException( 'Invalid condition format in where() array.' ); } + } finally { + $group_wheres = $this->wheres; + $this->wheres = $saved_wheres; } - $group_wheres = $this->wheres; - $this->wheres = $saved_wheres; - if ( empty( $group_wheres ) ) { return $this; } @@ -2157,7 +2166,7 @@ private function append_where_condition( string $lhs, $operator_or_value, $value if ( $value instanceof Closure || $value instanceof self ) { $allowed_subquery_ops = array_merge( self::$comparison_operators, array( 'IN', 'NOT IN' ) ); if ( ! in_array( $operator, $allowed_subquery_ops, true ) ) { - throw new InvalidArgumentException( "Invalid operator '{$operator}' for subquery comparison." ); + throw new InvalidArgumentException( esc_html( "Invalid operator '{$operator}' for subquery comparison." ) ); } $allow_limit = ! in_array( $operator, array( 'IN', 'NOT IN' ), true ); @@ -2186,7 +2195,7 @@ private function append_where_condition( string $lhs, $operator_or_value, $value } if ( ! self::is_valid_operator( $operator ) ) { - throw new InvalidArgumentException( "Invalid operator '{$operator}'." ); + throw new InvalidArgumentException( esc_html( "Invalid operator '{$operator}'." ) ); } $prepared_value = self::prepare_value( $value ); @@ -2228,8 +2237,17 @@ private function add_where_in( string $column, $values, string $type, string $bo return $this; } - if ( ! is_array( $values ) || empty( $values ) ) { - throw new InvalidArgumentException( 'where_in() values must be a non-empty array or subquery.' ); + if ( ! is_array( $values ) ) { + throw new InvalidArgumentException( 'where_in() values must be an array or subquery.' ); + } + + if ( empty( $values ) ) { + $this->wheres[] = array( + 'sql' => 'IN' === $type ? '0 = 1' : '1 = 1', + 'boolean' => $boolean, + ); + + return $this; } $escaped_values = self::prepare_in_clause( $values ); @@ -2625,7 +2643,7 @@ public static function parse_column_alias( string $expression ): ?string { * @return bool True if valid. */ public static function is_valid_column( string $column ): bool { - return (bool) preg_match( '/^[A-Za-z_*][A-Za-z0-9_.*]*$/', $column ); + return (bool) preg_match( '/^(?:[A-Za-z0-9_]+\.)?[A-Za-z_*][A-Za-z0-9_.*]*$/', $column ); } /** @@ -2641,6 +2659,19 @@ public static function is_valid_identifier( string $identifier ): bool { return (bool) preg_match( '/^[A-Za-z_][A-Za-z0-9_]*$/', $identifier ); } + /** + * Validate a SQL table name (allows leading digits for numeric WP table prefixes). + * + * @since 4.3.0 + * + * @param string $table Table name to validate. + * + * @return bool True if valid. + */ + public static function is_valid_table_name( string $table ): bool { + return (bool) preg_match( '/^[A-Za-z0-9_]+$/', $table ); + } + /** * Check whether a comparison operator is supported. * @@ -2928,7 +2959,7 @@ private static function resolve_existing_table( string $table ): ?string { // Check prefixed table name first. $prefixed = self::prepare_table_name( $table ); - if ( self::is_valid_identifier( $prefixed ) && self::table_exists_in_db( $prefixed ) ) { + if ( self::is_valid_table_name( $prefixed ) && self::table_exists_in_db( $prefixed ) ) { return $prefixed; } diff --git a/docs/developer/core/DB.php.md b/docs/developer/core/DB.php.md index e1444759b1..e000d27c8e 100644 --- a/docs/developer/core/DB.php.md +++ b/docs/developer/core/DB.php.md @@ -180,6 +180,7 @@ class DB { public static function parse_column_alias( string $expression ): ?string; public static function is_valid_column( string $column ): bool; public static function is_valid_identifier( string $identifier ): bool; + public static function is_valid_table_name( string $table ): bool; public static function is_valid_operator( string $operator ): bool; } ``` @@ -371,7 +372,7 @@ DB::table('tutor_orders') ``` > [!NOTE] -> All column names, table names, and aliases are strictly validated (`is_valid_column`, `is_valid_identifier`), comparison operators are checked against whitelisted operators (`is_valid_operator`), and values are safely bound via `$wpdb->prepare()`. Invalid formats, operators, or empty subqueries throw `\InvalidArgumentException` (fail-closed). Empty arrays `where([])` produce no WHERE clause. +> All column names, table names, and aliases are strictly validated (`is_valid_column`, `is_valid_table_name`, `is_valid_identifier`), comparison operators are checked against whitelisted operators (`is_valid_operator`), and values are safely bound via `$wpdb->prepare()`. Invalid formats, operators, or empty subqueries throw `\InvalidArgumentException` (fail-closed). Empty arrays `where([])` produce no WHERE clause, while empty `where_in(col, [])` / `where_not_in(col, [])` emit `0 = 1` / `1 = 1`. ### 3. Subqueries & Column Comparisons Subqueries accept either a `Closure` (receiving a fresh `DB` instance) or an existing `DB` instance (note: `DB` instances are compiled eagerly when added to the outer query). diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index 58c1229771..f4793e659c 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -942,26 +942,22 @@ function ( $join ) { } /** - * Test that invalid ON conditions within a join closure are safely ignored. + * Test that invalid ON conditions within a join closure throw InvalidArgumentException. * * @return void */ public function test_join_closure_invalid_conditions_rejected() { - global $wpdb; - - $prefix = $wpdb->prefix; - $sql = DB::table( 'users' ) - ->join( - 'contacts', - function ( $join ) { - $join->on( 'users.id', '=', 'contacts.user_id' ) - ->on( '1=1; DROP TABLE users; --', '=', 'contacts.status' ); - } - ) - ->to_sql(); - - $expected = "SELECT * FROM {$prefix}users INNER JOIN {$prefix}contacts ON users.id = contacts.user_id"; - $this->assertSame( $expected, $sql ); + $this->assert_throws_invalid_argument( + function () { + DB::table( 'users' )->join( + 'contacts', + function ( $join ) { + $join->on( 'users.id', '=', 'contacts.user_id' ) + ->on( '1=1; DROP TABLE users; --', '=', 'contacts.status' ); + } + ); + } + ); } /** @@ -2089,10 +2085,13 @@ function ( $q ) use ( $key1 ) { * @return void */ public function test_subquery_empty_and_invalid_inputs() { + global $wpdb; + + $prefix = $wpdb->prefix; $empty_closure = function ( $q ) { // Intentionally left empty. }; - $empty_db = new DB(); + $empty_db = new DB(); // Empty closure and uninitialized DB instance should throw (fail closed). $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_in( 'id', $empty_closure ) ); @@ -2101,7 +2100,16 @@ public function test_subquery_empty_and_invalid_inputs() { $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_not_exists( $empty_db ) ); $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->select_sub( $empty_closure, 'empty_col' ) ); $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->join_sub( $empty_closure, 's', 'users.id', '=', 's.id' ) ); - $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_in( 'id', array() ) ); + + // Empty IN / NOT IN arrays fail closed without throwing (0 = 1 / 1 = 1). + $this->assertSame( + "SELECT * FROM {$prefix}users WHERE 0 = 1", + DB::table( 'users' )->where_in( 'id', array() )->to_sql() + ); + $this->assertSame( + "SELECT * FROM {$prefix}users WHERE 1 = 1", + DB::table( 'users' )->where_not_in( 'id', array() )->to_sql() + ); // Non-Closure / non-DB values passed to subquery methods should throw. $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->where_exists( 'SELECT 1' ) ); @@ -2458,5 +2466,44 @@ function ( $q ) { "SELECT * FROM {$prefix}users WHERE ID IN (SELECT post_author FROM {$prefix}posts WHERE post_title = '%s') AND user_login = 'admin'", $sql ); + + // Invalid JOIN columns (4-arg and empty closure) throw. + $this->assert_throws_invalid_argument( fn() => DB::table( 'users' )->join( 'posts', 'users.ID', '=', 'posts.post_author; DROP' ) ); + $this->assert_throws_invalid_argument( + function () { + DB::table( 'users' )->join( + 'posts', + function ( $j ) { + // No ON conditions added. + } + ); + } + ); + + // add_array_where() preserves existing WHERE conditions when throwing mid-array. + $q = DB::table( 'posts' )->where( 'post_author', 5 ); + try { + $q->where( + array( + 'ID' => 1, + 'bad col' => 2, + ) + ); + $this->fail( 'Expected InvalidArgumentException was not thrown.' ); + } catch ( \InvalidArgumentException $e ) { + $this->assertSame( "SELECT * FROM {$prefix}posts WHERE post_author = 5", $q->to_sql() ); + } + + // Table prefix starting with a digit (e.g. '2fa_') is valid in table()/from()/join(). + $orig_prefix = $wpdb->prefix; + $wpdb->prefix = '2fa_'; + try { + $sql = DB::table( 'users' ) + ->join( 'posts', '2fa_users.ID', '=', '2fa_posts.post_author' ) + ->to_sql(); + $this->assertSame( 'SELECT * FROM 2fa_users INNER JOIN 2fa_posts ON 2fa_users.ID = 2fa_posts.post_author', $sql ); + } finally { + $wpdb->prefix = $orig_prefix; + } } } From a98bd2848a844f83483f833d5f334c31923cfd53 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Fri, 27 Nov 2026 12:46:07 +0600 Subject: [PATCH 09/13] docs: add missing @throws docblocks to DB class methods --- core/DB.php | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/core/DB.php b/core/DB.php index 25782d310d..7ac8732420 100644 --- a/core/DB.php +++ b/core/DB.php @@ -693,6 +693,8 @@ private static function create_join_collector(): object { * @param string $operator_or_second Operator or second column if 2 args. * @param string|null $second Second column if 3 args. * + * @throws InvalidArgumentException If operator or column name is invalid. + * * @return self */ public function on( string $first, string $operator_or_second, ?string $second = null ): self { @@ -710,6 +712,8 @@ public function on( string $first, string $operator_or_second, ?string $second = * @param string $operator_or_second Operator or second column if 2 args. * @param string|null $second Second column if 3 args. * + * @throws InvalidArgumentException If operator or column name is invalid. + * * @return self */ public function or_on( string $first, string $operator_or_second, ?string $second = null ): self { @@ -1736,7 +1740,8 @@ public function when( $condition, callable $callback, ?callable $default_callbac * @param array $data Assoc array of column => value pairs. * @param array $format Optional format specifiers (%s, %d, %f) for each value. * - * @throws DatabaseException If a database error occurs. + * @throws DatabaseException If a database error occurs. + * @throws InvalidArgumentException If called on a derived table. * * @return int Inserted row ID. */ @@ -1767,7 +1772,8 @@ public function insert( array $data, array $format = array() ): int { * * @param array $rows Array of assoc arrays, each representing a row. * - * @throws DatabaseException If a database error occurs. + * @throws DatabaseException If a database error occurs. + * @throws InvalidArgumentException If called on a derived table. * * @return bool True on success. */ @@ -1833,7 +1839,8 @@ public function insert_multiple( array $rows ): bool { * * @param array $data Assoc array of column => value pairs to update. * - * @throws DatabaseException If a database error occurs. + * @throws DatabaseException If a database error occurs. + * @throws InvalidArgumentException If called on a derived table. * * @return bool True on success. */ @@ -1893,7 +1900,8 @@ public function update( array $data ): bool { * * @since 4.2.0 * - * @throws DatabaseException If a database error occurs. + * @throws DatabaseException If a database error occurs. + * @throws InvalidArgumentException If called on a derived table. * * @return int Number of affected rows. */ @@ -1965,6 +1973,8 @@ public function to_sql(): string { * @param array $conditions Array of conditions. * @param string $boolean Boolean connector (AND or OR). * + * @throws InvalidArgumentException If a condition tuple or format is invalid. + * * @return self */ private function add_array_where( array $conditions, string $boolean = 'AND' ): self { @@ -2417,6 +2427,8 @@ private function add_where_raw( string $expression, array $bindings, string $boo * * @param bool $calc_found_rows Whether to include SQL_CALC_FOUND_ROWS. * + * @throws InvalidArgumentException If FROM table is missing for a non-raw query. + * * @return string The complete SQL query. */ private function build_select_query( bool $calc_found_rows = false ): string { @@ -2498,6 +2510,8 @@ private function build_select_sql(): string { * * @since 4.2.0 * + * @throws InvalidArgumentException If a derived table subquery has no alias. + * * @return string */ private function build_from_sql(): string { From 0ae21b19f1c18d5c8f58162a3125f487ba3ea4d6 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 2 Dec 2026 17:49:06 +0600 Subject: [PATCH 10/13] feat: add sum, min, max, and avg aggregate methods to database query builder --- core/DB.php | 100 +++++++++++++++++++++++++++-- docs/developer/core/DB.php.md | 17 +++++ tests/phpunit/DBTest.php | 117 ++++++++++++++++++++++++++++++++++ 3 files changed, 227 insertions(+), 7 deletions(-) diff --git a/core/DB.php b/core/DB.php index 7ac8732420..3a3bd55c3b 100644 --- a/core/DB.php +++ b/core/DB.php @@ -1513,7 +1513,93 @@ public function count( string $column = '*' ): int { $column = '*'; } - // Save state that count() modifies. + return (int) $this->aggregate( 'COUNT', $column ); + } + + /** + * Get the sum of a column's values matching the query. + * + * @since 4.2.0 + * + * @param string $column Column name to sum. + * + * @return int|float Sum of matching column values, or 0 if no rows match. + */ + public function sum( string $column ) { + if ( '*' === $column || ! self::is_valid_column( $column ) ) { + return 0; + } + + $result = $this->aggregate( 'SUM', $column ); + + return is_numeric( $result ) ? $result + 0 : 0; + } + + /** + * Get the minimum value of a column matching the query. + * + * @since 4.2.0 + * + * @param string $column Column name. + * + * @return mixed Minimum value or null if no rows match. + */ + public function min( string $column ) { + if ( '*' === $column || ! self::is_valid_column( $column ) ) { + return null; + } + + return $this->aggregate( 'MIN', $column ); + } + + /** + * Get the maximum value of a column matching the query. + * + * @since 4.2.0 + * + * @param string $column Column name. + * + * @return mixed Maximum value or null if no rows match. + */ + public function max( string $column ) { + if ( '*' === $column || ! self::is_valid_column( $column ) ) { + return null; + } + + return $this->aggregate( 'MAX', $column ); + } + + /** + * Get the average value of a column matching the query. + * + * @since 4.2.0 + * + * @param string $column Column name. + * + * @return int|float|null Average value or null if no rows match. + */ + public function avg( string $column ) { + if ( '*' === $column || ! self::is_valid_column( $column ) ) { + return null; + } + + $result = $this->aggregate( 'AVG', $column ); + + return is_numeric( $result ) ? $result + 0 : null; + } + + /** + * Execute an aggregate SQL function (COUNT, SUM, MIN, MAX, AVG). + * + * @since 4.2.0 + * + * @param string $function SQL aggregate function name. + * @param string $column Column name (or '*' for COUNT). + * + * @return string|null Raw scalar result from $wpdb->get_var(). + */ + private function aggregate( string $function, string $column ) { + // Save state that aggregate() modifies. $saved_columns = $this->columns; $saved_raw = $this->raw_columns; $saved_order = $this->order_by_clauses; @@ -1522,20 +1608,20 @@ public function count( string $column = '*' ): int { $saved_distinct = $this->is_distinct; $saved_lock = $this->lock; - // Override for count. + // Override for aggregate. $this->columns = array(); $this->lock = ''; if ( $saved_distinct ) { if ( '*' !== $column ) { - $this->raw_columns = array( "COUNT(DISTINCT {$column}) AS aggregate" ); - } elseif ( 1 === count( $saved_columns ) && self::is_valid_column( $saved_columns[0] ) && '*' !== $saved_columns[0] ) { + $this->raw_columns = array( "{$function}(DISTINCT {$column}) AS aggregate" ); + } elseif ( 'COUNT' === $function && 1 === count( $saved_columns ) && self::is_valid_column( $saved_columns[0] ) && '*' !== $saved_columns[0] ) { $this->raw_columns = array( "COUNT(DISTINCT {$saved_columns[0]}) AS aggregate" ); } else { - $this->raw_columns = array( "COUNT({$column}) AS aggregate" ); + $this->raw_columns = array( "{$function}({$column}) AS aggregate" ); } } else { - $this->raw_columns = array( "COUNT({$column}) AS aggregate" ); + $this->raw_columns = array( "{$function}({$column}) AS aggregate" ); } $this->order_by_clauses = array(); @@ -1555,7 +1641,7 @@ public function count( string $column = '*' ): int { $this->lock = $saved_lock; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - return (int) self::get_db()->get_var( $sql ); + return self::get_db()->get_var( $sql ); } /** diff --git a/docs/developer/core/DB.php.md b/docs/developer/core/DB.php.md index e000d27c8e..acc7bc2890 100644 --- a/docs/developer/core/DB.php.md +++ b/docs/developer/core/DB.php.md @@ -141,6 +141,10 @@ class DB { public function value( string $column ); public function pluck( string $column, ?string $key = null ): array; public function count( string $column = '*' ): int; + public function sum( string $column ); + public function min( string $column ); + public function max( string $column ); + public function avg( string $column ); public function exists(): bool; // Mutations @@ -515,6 +519,10 @@ $results = DB::table('posts') | `value( $column )` | `mixed\|null` | Retrieves a single field value from the first matching row. | | `pluck( $column, $key )` | `array` | Extracts a flat list of column values, optionally indexed by `$key`. | | `count( $column )` | `int` | Returns total row count matching the query. | +| `sum( $column )` | `int\|float` | Returns sum of matching column values, or `0` if no rows match. | +| `min( $column )` | `mixed` | Returns minimum matching column value, or `null` if no rows match. | +| `max( $column )` | `mixed` | Returns maximum matching column value, or `null` if no rows match. | +| `avg( $column )` | `int\|float\|null` | Returns average of matching column values, or `null` if no rows match. | | `exists()` | `bool` | Returns `true` if at least one matching record exists. | ```php @@ -526,6 +534,15 @@ $course_map = DB::table('posts') ->where('post_type', 'courses') ->pluck('post_title', 'ID'); +// Aggregate values +$total_marks = DB::table('tutor_quiz_questions') + ->where('quiz_id', 10) + ->sum('question_mark'); + +$avg_price = DB::table('tutor_orders')->where('order_status', 'completed')->avg('total_price'); +$min_price = DB::table('tutor_orders')->min('total_price'); +$max_price = DB::table('tutor_orders')->max('total_price'); + // Check existence if ( DB::table('tutor_enrolments')->where('user_id', 5)->where('course_id', 12)->exists() ) { // User already enrolled diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index f4793e659c..82a5338ed3 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -2506,4 +2506,121 @@ function ( $j ) { $wpdb->prefix = $orig_prefix; } } + + /** + * Test sum(), min(), max(), and avg() aggregate methods. + * + * @return void + */ + public function test_aggregate_methods() { + global $wpdb; + + $prefix = $wpdb->prefix; + $post_type = 'qb_agg_' . wp_rand( 1000, 9999 ); + $meta_key = 'qb_agg_meta_' . wp_rand( 1000, 9999 ); + + try { + DB::table( 'posts' )->insert_multiple( + array( + array( + 'post_title' => 'beta', + 'post_type' => $post_type, + 'post_status' => 'publish', + 'menu_order' => 10, + ), + array( + 'post_title' => 'alpha', + 'post_type' => $post_type, + 'post_status' => 'publish', + 'menu_order' => 20, + ), + array( + 'post_title' => 'gamma', + 'post_type' => $post_type, + 'post_status' => 'publish', + 'menu_order' => 20, + ), + array( + 'post_title' => 'delta', + 'post_type' => $post_type, + 'post_status' => 'publish', + 'menu_order' => 30, + ), + ) + ); + + // Integer sum, avg, min, max, and distinct sum. + $this->assertSame( 80, DB::table( 'posts' )->where( 'post_type', $post_type )->sum( 'menu_order' ) ); + $this->assertSame( 60, DB::table( 'posts' )->distinct()->where( 'post_type', $post_type )->sum( 'menu_order' ) ); + $this->assertSame( 20.0, DB::table( 'posts' )->where( 'post_type', $post_type )->avg( 'menu_order' ) ); + $this->assertEquals( 10, DB::table( 'posts' )->where( 'post_type', $post_type )->min( 'menu_order' ) ); + $this->assertEquals( 30, DB::table( 'posts' )->where( 'post_type', $post_type )->max( 'menu_order' ) ); + + // String min and max. + $this->assertSame( 'alpha', DB::table( 'posts' )->where( 'post_type', $post_type )->min( 'post_title' ) ); + $this->assertSame( 'gamma', DB::table( 'posts' )->where( 'post_type', $post_type )->max( 'post_title' ) ); + + // Decimal sum and avg via postmeta. + DB::table( 'postmeta' )->insert_multiple( + array( + array( + 'post_id' => 1, + 'meta_key' => $meta_key, + 'meta_value' => '1.5', + ), + array( + 'post_id' => 2, + 'meta_key' => $meta_key, + 'meta_value' => '2.5', + ), + array( + 'post_id' => 3, + 'meta_key' => $meta_key, + 'meta_value' => '3.5', + ), + ) + ); + + $this->assertSame( 7.5, DB::table( 'postmeta' )->where( 'meta_key', $meta_key )->sum( 'meta_value' ) ); + $this->assertSame( 2.5, DB::table( 'postmeta' )->where( 'meta_key', $meta_key )->avg( 'meta_value' ) ); + + // Empty / no matching rows. + $empty = DB::table( 'posts' )->where( 'post_type', $post_type . '_missing' ); + $this->assertSame( 0, $empty->sum( 'menu_order' ) ); + $this->assertNull( $empty->min( 'menu_order' ) ); + $this->assertNull( $empty->max( 'menu_order' ) ); + $this->assertNull( $empty->avg( 'menu_order' ) ); + + // Invalid column or '*' returns safe defaults without executing SQL. + $valid = DB::table( 'posts' )->where( 'post_type', $post_type ); + $this->assertSame( 0, $valid->sum( '*' ) ); + $this->assertSame( 0, $valid->sum( 'bad col' ) ); + $this->assertNull( $valid->min( '*' ) ); + $this->assertNull( $valid->min( 'bad col' ) ); + $this->assertNull( $valid->max( '*' ) ); + $this->assertNull( $valid->max( 'bad col' ) ); + $this->assertNull( $valid->avg( '*' ) ); + $this->assertNull( $valid->avg( 'bad col' ) ); + + // Builder state is preserved after calling aggregates. + $builder = DB::table( 'posts' ) + ->select( 'ID', 'menu_order' ) + ->where( 'post_type', $post_type ) + ->order_by( 'menu_order', 'DESC' ) + ->limit( 2 ) + ->offset( 1 ); + + $this->assertSame( 80, $builder->sum( 'menu_order' ) ); + $this->assertEquals( 10, $builder->min( 'menu_order' ) ); + $this->assertEquals( 30, $builder->max( 'menu_order' ) ); + $this->assertSame( 20.0, $builder->avg( 'menu_order' ) ); + $this->assertSame( + "SELECT ID, menu_order FROM {$prefix}posts WHERE post_type = '{$post_type}' ORDER BY menu_order DESC LIMIT 2 OFFSET 1", + $builder->to_sql() + ); + } finally { + DB::table( 'posts' )->where( 'post_type', $post_type )->delete(); + DB::table( 'postmeta' )->where( 'meta_key', $meta_key )->delete(); + } + } } From c262e9bee625c653a9fc9ce6ec50bc5debf05748 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 2 Dec 2026 21:52:03 +0600 Subject: [PATCH 11/13] test: handle base prefix in DBTest for numeric table prefix test --- tests/phpunit/DBTest.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index 0ab3d7c8a5..8da474abfa 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -2745,15 +2745,18 @@ function ( $j ) { } // Table prefix starting with a digit (e.g. '2fa_') is valid in table()/from()/join(). - $orig_prefix = $wpdb->prefix; - $wpdb->prefix = '2fa_'; + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + $wpdb->prefix = '2fa_'; + $wpdb->base_prefix = '2fa_'; try { $sql = DB::table( 'users' ) ->join( 'posts', '2fa_users.ID', '=', '2fa_posts.post_author' ) ->to_sql(); $this->assertSame( 'SELECT * FROM 2fa_users INNER JOIN 2fa_posts ON 2fa_users.ID = 2fa_posts.post_author', $sql ); } finally { - $wpdb->prefix = $orig_prefix; + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; } } From 99a0c99a7d80c3af12dc87ea4e91b48d95f63618 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 3 Dec 2026 11:42:47 +0600 Subject: [PATCH 12/13] refactor: add safeguards for raw expressions, column validation, and unsafe updates or deletes in DB class --- core/DB.php | 93 ++++++++++++++++++++++------------- docs/developer/core/DB.php.md | 14 +++--- tests/phpunit/DBTest.php | 31 ++++++++++++ 3 files changed, 97 insertions(+), 41 deletions(-) diff --git a/core/DB.php b/core/DB.php index ac6f7abde5..1a64b02a66 100644 --- a/core/DB.php +++ b/core/DB.php @@ -430,12 +430,7 @@ private function add_select_column( string $column ): void { * @return self */ public function select_raw( string $expression, array $bindings = array() ): self { - if ( ! empty( $bindings ) ) { - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- User-provided expression with bindings. - $expression = self::get_db()->prepare( $expression, $bindings ); - } - - $this->raw_columns[] = $expression; + $this->raw_columns[] = $this->prepare_raw_expression( $expression, $bindings ); return $this; } @@ -1305,12 +1300,7 @@ public function group_by( string ...$columns ): self { * @return self */ public function having_raw( string $expression, array $bindings = array() ): self { - if ( ! empty( $bindings ) ) { - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Raw expression with user-controlled bindings. - $expression = self::get_db()->prepare( $expression, $bindings ); - } - - $this->havings[] = $expression; + $this->havings[] = $this->prepare_raw_expression( $expression, $bindings ); return $this; } @@ -1353,12 +1343,7 @@ public function order_by( string $column, string $direction = 'ASC' ): self { * @return self */ public function order_by_raw( string $expression, array $bindings = array() ): self { - if ( ! empty( $bindings ) ) { - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared - $expression = self::get_db()->prepare( $expression, $bindings ); - } - - $this->order_by_clauses[] = $expression; + $this->order_by_clauses[] = $this->prepare_raw_expression( $expression, $bindings ); return $this; } @@ -1827,7 +1812,7 @@ public function when( $condition, callable $callback, ?callable $default_callbac * @param array $format Optional format specifiers (%s, %d, %f) for each value. * * @throws DatabaseException If a database error occurs. - * @throws InvalidArgumentException If called on a derived table. + * @throws InvalidArgumentException If called on a derived table or if any column name is invalid. * * @return int Inserted row ID. */ @@ -1836,6 +1821,12 @@ public function insert( array $data, array $format = array() ): int { throw new InvalidArgumentException( 'Insert operations are not allowed on a derived table.' ); } + foreach ( array_keys( $data ) as $column ) { + if ( ! self::is_valid_identifier( (string) $column ) ) { + throw new InvalidArgumentException( esc_html( "Invalid column name '{$column}' in insert()." ) ); + } + } + $db = self::get_db(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery @@ -1923,14 +1914,15 @@ public function insert_multiple( array $rows ): bool { * * @since 4.2.0 * - * @param array $data Assoc array of column => value pairs to update. + * @param array $data Assoc array of column => value pairs to update. + * @param bool $allow_all Explicit opt-in to update all rows when no WHERE conditions are set. * * @throws DatabaseException If a database error occurs. - * @throws InvalidArgumentException If called on a derived table. + * @throws InvalidArgumentException If called on a derived table or without WHERE conditions when $allow_all is false. * * @return bool True on success. */ - public function update( array $data ): bool { + public function update( array $data, bool $allow_all = false ): bool { if ( $this->is_derived ) { throw new InvalidArgumentException( 'Update operations are not allowed on a derived table.' ); } @@ -1960,6 +1952,10 @@ public function update( array $data ): bool { $set_clause = implode( ', ', $set_parts ); $where_clause = $this->build_where_sql(); + if ( empty( $where_clause ) && ! $allow_all ) { + throw new InvalidArgumentException( 'Update operations require a WHERE condition unless $allow_all is true.' ); + } + $table_name = ! empty( $this->alias ) ? "{$this->table} AS {$this->alias}" : $this->table; $sql = "UPDATE {$table_name} SET {$set_clause}"; if ( ! empty( $where_clause ) ) { @@ -1981,23 +1977,26 @@ public function update( array $data ): bool { /** * Delete rows matching the accumulated WHERE conditions. * - * WARNING: Calling delete() without any where() conditions will - * delete ALL rows from the table. - * * @since 4.2.0 * + * @param bool $allow_all Explicit opt-in to delete all rows when no WHERE conditions are set. + * * @throws DatabaseException If a database error occurs. - * @throws InvalidArgumentException If called on a derived table. + * @throws InvalidArgumentException If called on a derived table or without WHERE conditions when $allow_all is false. * * @return int Number of affected rows. */ - public function delete(): int { + public function delete( bool $allow_all = false ): int { if ( $this->is_derived ) { throw new InvalidArgumentException( 'Delete operations are not allowed on a derived table.' ); } $where_clause = $this->build_where_sql(); + if ( empty( $where_clause ) && ! $allow_all ) { + throw new InvalidArgumentException( 'Delete operations require a WHERE condition unless $allow_all is true.' ); + } + if ( ! empty( $this->alias ) ) { $sql = "DELETE {$this->alias} FROM {$this->table} AS {$this->alias}"; } else { @@ -2427,11 +2426,13 @@ private function add_where_column( string $first, string $operator_or_second, ?s * @param string $type BETWEEN or NOT BETWEEN. * @param string $boolean AND or OR. * + * @throws InvalidArgumentException If column name is invalid. + * * @return self */ private function add_where_between( string $column, $min, $max, string $type, string $boolean ): self { if ( ! self::is_valid_column( $column ) ) { - return $this; + throw new InvalidArgumentException( esc_html( "Invalid column name '{$column}'." ) ); } $min_prepared = self::prepare_value( $min ); @@ -2457,11 +2458,13 @@ private function add_where_between( string $column, $min, $max, string $type, st * @param string $type LIKE or NOT LIKE. * @param string $boolean AND or OR. * + * @throws InvalidArgumentException If column name is invalid. + * * @return self */ private function add_where_like( string $column, string $value, string $type, string $boolean ): self { if ( ! self::is_valid_column( $column ) ) { - return $this; + throw new InvalidArgumentException( esc_html( "Invalid column name '{$column}'." ) ); } $db = self::get_db(); @@ -2486,20 +2489,42 @@ private function add_where_like( string $column, string $value, string $type, st * @param array $bindings Values to bind. * @param string $boolean AND or OR. * + * @throws InvalidArgumentException If expression preparation fails or results in an empty string. + * * @return self */ private function add_where_raw( string $expression, array $bindings, string $boolean ): self { + $this->wheres[] = array( + 'sql' => $this->prepare_raw_expression( $expression, $bindings ), + 'boolean' => $boolean, + ); + + return $this; + } + + /** + * Prepare a raw SQL expression with optional bindings. + * + * @since 4.2.0 + * + * @param string $expression Raw SQL expression. + * @param array $bindings Optional values to bind. + * + * @throws InvalidArgumentException If expression preparation fails or results in an empty string. + * + * @return string Prepared SQL expression. + */ + private function prepare_raw_expression( string $expression, array $bindings ): string { if ( ! empty( $bindings ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Raw expression with user-controlled bindings. $expression = self::get_db()->prepare( $expression, $bindings ); } - $this->wheres[] = array( - 'sql' => $expression, - 'boolean' => $boolean, - ); + if ( ! is_string( $expression ) || '' === trim( $expression ) ) { + throw new InvalidArgumentException( 'Raw SQL expression preparation failed or resulted in an empty expression.' ); + } - return $this; + return $expression; } // ───────────────────────────────────────────── diff --git a/docs/developer/core/DB.php.md b/docs/developer/core/DB.php.md index acc7bc2890..b7fc602009 100644 --- a/docs/developer/core/DB.php.md +++ b/docs/developer/core/DB.php.md @@ -150,8 +150,8 @@ class DB { // Mutations public function insert( array $data, array $format = [] ): int; public function insert_multiple( array $rows ): bool; - public function update( array $data ): bool; - public function delete(): int; + public function update( array $data, bool $allow_all = false ): bool; + public function delete( bool $allow_all = false ): int; // Row Locking public function lock_for_update(): self; @@ -578,7 +578,7 @@ $pagination = DB::table('tutor_orders') ## Data Mutations (CRUD) ### 1. Insert -Inserts a single row and returns the new auto-increment ID: +Inserts a single row and returns the new auto-increment ID. Column keys in `$data` are validated via `is_valid_identifier()` and throw `InvalidArgumentException` if invalid: ```php $insert_id = DB::table('options')->insert([ @@ -621,7 +621,7 @@ $deleted_rows = DB::table('options') ``` > [!CAUTION] -> Calling `delete()` without any `where()` conditions will delete **all rows** in the target table. +> Both `update()` and `delete()` throw `InvalidArgumentException` if called without any `where()` conditions. To intentionally affect **all rows** in the target table, pass `true` as `$allow_all` (e.g., `->update( $data, true )` or `->delete( true )`). --- @@ -862,9 +862,9 @@ DB::get_last_query(); // Returns $wpdb->last_query ## Security Architecture -1. **Prepared Statements:** All literal values passed into `where()`, `where_in()`, `where_between()`, `insert()`, `update()`, and raw bindings are passed through `$wpdb->prepare()`. -2. **Identifier Validation:** Column identifiers and table names are strictly validated against `/^[A-Za-z_*][A-Za-z0-9_.*]*$/`. Column aliases in `select()` are parsed and verified against strict column and alias patterns (`is_valid_column` and `is_valid_identifier`). Join conditions (including closure-based `on()` and `or_on()` conditions) validate both columns and operators against allowlists before inclusion. Characters that could trigger SQL injection (semicolons, comments, quotes, brackets) are rejected. -3. **LIKE-Injection Protection:** `where_like()` automatically processes input values via `$wpdb->esc_like()`, preventing wildcard abuse (`%` or `_`). +1. **Prepared Statements:** All literal values passed into `where()`, `where_in()`, `where_between()`, `insert()`, `update()`, and raw bindings are passed through `$wpdb->prepare()`. Raw expression methods (`select_raw()`, `where_raw()`, `or_where_raw()`, `having_raw()`, `order_by_raw()`) throw `InvalidArgumentException` if `prepare()` fails or produces an empty expression. +2. **Identifier Validation:** Column identifiers and table names are strictly validated against `/^[A-Za-z_*][A-Za-z0-9_.*]*$/`. All `where_*` builders (including `where_like()` and `where_between()` and their `or_`/`not_` variants) as well as `insert()` (`is_valid_identifier()`) throw `InvalidArgumentException` on invalid column names. Column aliases in `select()` are parsed and verified against strict column and alias patterns (`is_valid_column` and `is_valid_identifier`). Join conditions (including closure-based `on()` and `or_on()` conditions) validate both columns and operators against allowlists before inclusion. Characters that could trigger SQL injection (semicolons, comments, quotes, brackets) are rejected. +3. **Mass-Mutation Guard & LIKE-Injection Protection:** `update()` and `delete()` refuse to execute without a `WHERE` clause (throwing `InvalidArgumentException`) unless `$allow_all = true` is explicitly passed. `where_like()` automatically processes input values via `$wpdb->esc_like()`, preventing wildcard abuse (`%` or `_`). 4. **Schema Inspection Safety:** `has_table()`, `has_column()`, and `has_columns()` validate all identifiers before running schema queries. Table lookups employ `$wpdb->esc_like()` with `SHOW TABLES LIKE`, and column queries quote validated table names within backticks. 5. **Robust Exception & Rollback Handling:** `DB::transaction()` catches all `\Throwable` instances (both exceptions and fatal PHP errors), ensuring transactions roll back reliably. Secondary rollback failures are trapped so the original root cause exception propagates cleanly. 6. **WPCS Compliance:** Follows WordPress Coding Standards (WPCS) with full escaping and cache awareness annotations. diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index 8da474abfa..f335336aea 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -2758,6 +2758,37 @@ function ( $j ) { $wpdb->prefix = $orig_prefix; $wpdb->base_prefix = $orig_base_prefix; } + + // where_like() and where_between() (and variants) throw on invalid columns. + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_like( 'bad col', 'a' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_not_like( 'bad col', 'a' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->or_where_like( 'bad col', 'a' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->or_where_not_like( 'bad col', 'a' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_between( 'bad col', 1, 10 ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_not_between( 'bad col', 1, 10 ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->or_where_between( 'bad col', 1, 10 ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->or_where_not_between( 'bad col', 1, 10 ) ); + + // Raw expression methods throw on empty expressions or failed prepare(). + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_raw( '' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->or_where_raw( ' ' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->select_raw( '' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->having_raw( '' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->order_by_raw( '' ) ); + + $this->setExpectedIncorrectUsage( 'wpdb::prepare' ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->where_raw( 'ID = %d AND post_author = %d', array( 1 ) ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->select_raw( 'COUNT(%s, %s)', array( 'a' ) ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->having_raw( 'COUNT(*) > %d AND SUM(ID) > %d', array( 1 ) ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->order_by_raw( 'FIELD(ID, %d, %d)', array( 1 ) ) ); + + // update() and delete() refuse to run without a WHERE condition unless $allow_all is true. + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->update( array( 'post_title' => 'x' ) ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->delete() ); + + // insert() validates column names. + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->insert( array( 'bad col' => 'value' ) ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->insert( array( 'ID; DROP TABLE wp_posts' => 1 ) ) ); } /** From 0a39d5e50a27ad4926116b9801c0e51eb6da2de7 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 3 Dec 2026 12:02:23 +0600 Subject: [PATCH 13/13] refactor: throw exceptions for invalid columns in DB query builder and improve aggregate methods --- core/DB.php | 124 ++++++++++++++++++------------- docs/developer/core/DB.php.md | 6 +- tests/phpunit/DBTest.php | 134 ++++++++++++++++++++++++++-------- 3 files changed, 180 insertions(+), 84 deletions(-) diff --git a/core/DB.php b/core/DB.php index 1a64b02a66..2b3d787dd7 100644 --- a/core/DB.php +++ b/core/DB.php @@ -405,6 +405,8 @@ public function select( ...$columns ): self { * * @param string $column Column name or aliased expression. * + * @throws InvalidArgumentException If column name or alias is invalid. + * * @return void */ private function add_select_column( string $column ): void { @@ -413,6 +415,8 @@ private function add_select_column( string $column ): void { $this->columns[] = $aliased; } elseif ( self::is_valid_column( $column ) ) { $this->columns[] = $column; + } else { + throw new InvalidArgumentException( esc_html( "Invalid column or alias '{$column}' in select()." ) ); } } @@ -1273,13 +1277,16 @@ public function or_where_raw( string $expression, array $bindings = array() ): s * * @param string ...$columns Column names to group by. * + * @throws InvalidArgumentException If any column name is invalid. + * * @return self */ public function group_by( string ...$columns ): self { foreach ( $columns as $column ) { - if ( self::is_valid_column( $column ) ) { - $this->group_by_columns[] = $column; + if ( ! self::is_valid_column( $column ) ) { + throw new InvalidArgumentException( esc_html( "Invalid column name '{$column}' in group_by()." ) ); } + $this->group_by_columns[] = $column; } return $this; @@ -1319,11 +1326,13 @@ public function having_raw( string $expression, array $bindings = array() ): sel * @param string $column Column name. * @param string $direction ASC or DESC, default ASC. * + * @throws InvalidArgumentException If column name is invalid. + * * @return self */ public function order_by( string $column, string $direction = 'ASC' ): self { if ( ! self::is_valid_column( $column ) ) { - return $this; + throw new InvalidArgumentException( esc_html( "Invalid column name '{$column}' in order_by()." ) ); } $direction = 'DESC' === strtoupper( $direction ) ? 'DESC' : 'ASC'; @@ -1504,14 +1513,14 @@ public function count( string $column = '*' ): int { /** * Get the sum of a column's values matching the query. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $column Column name to sum. * * @return int|float Sum of matching column values, or 0 if no rows match. */ public function sum( string $column ) { - if ( '*' === $column || ! self::is_valid_column( $column ) ) { + if ( false !== strpos( $column, '*' ) || ! self::is_valid_column( $column ) ) { return 0; } @@ -1523,48 +1532,58 @@ public function sum( string $column ) { /** * Get the minimum value of a column matching the query. * - * @since 4.2.0 + * Numeric values are cast to int or float; non-numeric values (e.g. dates, + * strings) are returned as strings. + * + * @since 4.3.0 * * @param string $column Column name. * * @return mixed Minimum value or null if no rows match. */ public function min( string $column ) { - if ( '*' === $column || ! self::is_valid_column( $column ) ) { + if ( false !== strpos( $column, '*' ) || ! self::is_valid_column( $column ) ) { return null; } - return $this->aggregate( 'MIN', $column ); + $result = $this->aggregate( 'MIN', $column ); + + return is_numeric( $result ) ? $result + 0 : $result; } /** * Get the maximum value of a column matching the query. * - * @since 4.2.0 + * Numeric values are cast to int or float; non-numeric values (e.g. dates, + * strings) are returned as strings. + * + * @since 4.3.0 * * @param string $column Column name. * * @return mixed Maximum value or null if no rows match. */ public function max( string $column ) { - if ( '*' === $column || ! self::is_valid_column( $column ) ) { + if ( false !== strpos( $column, '*' ) || ! self::is_valid_column( $column ) ) { return null; } - return $this->aggregate( 'MAX', $column ); + $result = $this->aggregate( 'MAX', $column ); + + return is_numeric( $result ) ? $result + 0 : $result; } /** * Get the average value of a column matching the query. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $column Column name. * * @return int|float|null Average value or null if no rows match. */ public function avg( string $column ) { - if ( '*' === $column || ! self::is_valid_column( $column ) ) { + if ( false !== strpos( $column, '*' ) || ! self::is_valid_column( $column ) ) { return null; } @@ -1576,7 +1595,7 @@ public function avg( string $column ) { /** * Execute an aggregate SQL function (COUNT, SUM, MIN, MAX, AVG). * - * @since 4.2.0 + * @since 4.3.0 * * @param string $function SQL aggregate function name. * @param string $column Column name (or '*' for COUNT). @@ -1593,37 +1612,39 @@ private function aggregate( string $function, string $column ) { $saved_distinct = $this->is_distinct; $saved_lock = $this->lock; - // Override for aggregate. - $this->columns = array(); - $this->lock = ''; - - if ( $saved_distinct ) { - if ( '*' !== $column ) { - $this->raw_columns = array( "{$function}(DISTINCT {$column}) AS aggregate" ); - } elseif ( 'COUNT' === $function && 1 === count( $saved_columns ) && self::is_valid_column( $saved_columns[0] ) && '*' !== $saved_columns[0] ) { - $this->raw_columns = array( "COUNT(DISTINCT {$saved_columns[0]}) AS aggregate" ); + try { + // Override for aggregate. + $this->columns = array(); + $this->lock = ''; + + if ( $saved_distinct ) { + if ( '*' !== $column ) { + $this->raw_columns = array( "{$function}(DISTINCT {$column}) AS aggregate" ); + } elseif ( 'COUNT' === $function && 1 === count( $saved_columns ) && self::is_valid_column( $saved_columns[0] ) && '*' !== $saved_columns[0] ) { + $this->raw_columns = array( "COUNT(DISTINCT {$saved_columns[0]}) AS aggregate" ); + } else { + $this->raw_columns = array( "{$function}({$column}) AS aggregate" ); + } } else { $this->raw_columns = array( "{$function}({$column}) AS aggregate" ); } - } else { - $this->raw_columns = array( "{$function}({$column}) AS aggregate" ); - } - - $this->order_by_clauses = array(); - $this->limit_value = null; - $this->offset_value = 0; - $this->is_distinct = false; - $sql = $this->build_select_query(); + $this->order_by_clauses = array(); + $this->limit_value = null; + $this->offset_value = 0; + $this->is_distinct = false; - // Restore state. - $this->columns = $saved_columns; - $this->raw_columns = $saved_raw; - $this->order_by_clauses = $saved_order; - $this->limit_value = $saved_limit; - $this->offset_value = $saved_offset; - $this->is_distinct = $saved_distinct; - $this->lock = $saved_lock; + $sql = $this->build_select_query(); + } finally { + // Restore state even if build_select_query() throws. + $this->columns = $saved_columns; + $this->raw_columns = $saved_raw; + $this->order_by_clauses = $saved_order; + $this->limit_value = $saved_limit; + $this->offset_value = $saved_offset; + $this->is_distinct = $saved_distinct; + $this->lock = $saved_lock; + } // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return self::get_db()->get_var( $sql ); @@ -1867,9 +1888,10 @@ public function insert_multiple( array $rows ): bool { $columns = is_array( $first_row ) ? array_keys( $first_row ) : array(); $valid_cols = array(); foreach ( $columns as $col ) { - if ( self::is_valid_identifier( $col ) ) { - $valid_cols[] = $col; + if ( ! self::is_valid_identifier( (string) $col ) ) { + throw new InvalidArgumentException( esc_html( "Invalid column name '{$col}' in insert_multiple()." ) ); } + $valid_cols[] = $col; } if ( empty( $valid_cols ) ) { @@ -1913,12 +1935,13 @@ public function insert_multiple( array $rows ): bool { * NULL values produce `SET column = NULL`. * * @since 4.2.0 + * @since 4.3.0 Added $allow_all parameter. * * @param array $data Assoc array of column => value pairs to update. * @param bool $allow_all Explicit opt-in to update all rows when no WHERE conditions are set. * * @throws DatabaseException If a database error occurs. - * @throws InvalidArgumentException If called on a derived table or without WHERE conditions when $allow_all is false. + * @throws InvalidArgumentException If called on a derived table, if any column name is invalid, or without WHERE conditions when $allow_all is false. * * @return bool True on success. */ @@ -1933,8 +1956,8 @@ public function update( array $data, bool $allow_all = false ): bool { $set_parts = array(); foreach ( $data as $column => $value ) { - if ( ! self::is_valid_identifier( $column ) ) { - continue; + if ( ! self::is_valid_identifier( (string) $column ) ) { + throw new InvalidArgumentException( esc_html( "Invalid column name '{$column}' in update()." ) ); } if ( is_null( $value ) ) { @@ -1952,13 +1975,13 @@ public function update( array $data, bool $allow_all = false ): bool { $set_clause = implode( ', ', $set_parts ); $where_clause = $this->build_where_sql(); - if ( empty( $where_clause ) && ! $allow_all ) { + if ( '' === $where_clause && ! $allow_all ) { throw new InvalidArgumentException( 'Update operations require a WHERE condition unless $allow_all is true.' ); } $table_name = ! empty( $this->alias ) ? "{$this->table} AS {$this->alias}" : $this->table; $sql = "UPDATE {$table_name} SET {$set_clause}"; - if ( ! empty( $where_clause ) ) { + if ( '' !== $where_clause ) { $sql .= " WHERE {$where_clause}"; } @@ -1978,6 +2001,7 @@ public function update( array $data, bool $allow_all = false ): bool { * Delete rows matching the accumulated WHERE conditions. * * @since 4.2.0 + * @since 4.3.0 Added $allow_all parameter. * * @param bool $allow_all Explicit opt-in to delete all rows when no WHERE conditions are set. * @@ -1993,7 +2017,7 @@ public function delete( bool $allow_all = false ): int { $where_clause = $this->build_where_sql(); - if ( empty( $where_clause ) && ! $allow_all ) { + if ( '' === $where_clause && ! $allow_all ) { throw new InvalidArgumentException( 'Delete operations require a WHERE condition unless $allow_all is true.' ); } @@ -2003,7 +2027,7 @@ public function delete( bool $allow_all = false ): int { $sql = "DELETE FROM {$this->table}"; } - if ( ! empty( $where_clause ) ) { + if ( '' !== $where_clause ) { $sql .= " WHERE {$where_clause}"; } @@ -2505,7 +2529,7 @@ private function add_where_raw( string $expression, array $bindings, string $boo /** * Prepare a raw SQL expression with optional bindings. * - * @since 4.2.0 + * @since 4.3.0 * * @param string $expression Raw SQL expression. * @param array $bindings Optional values to bind. diff --git a/docs/developer/core/DB.php.md b/docs/developer/core/DB.php.md index b7fc602009..c9625e5b69 100644 --- a/docs/developer/core/DB.php.md +++ b/docs/developer/core/DB.php.md @@ -520,8 +520,8 @@ $results = DB::table('posts') | `pluck( $column, $key )` | `array` | Extracts a flat list of column values, optionally indexed by `$key`. | | `count( $column )` | `int` | Returns total row count matching the query. | | `sum( $column )` | `int\|float` | Returns sum of matching column values, or `0` if no rows match. | -| `min( $column )` | `mixed` | Returns minimum matching column value, or `null` if no rows match. | -| `max( $column )` | `mixed` | Returns maximum matching column value, or `null` if no rows match. | +| `min( $column )` | `mixed` | Returns minimum matching column value (`int\|float` for numeric, `string` otherwise), or `null` if no rows match. | +| `max( $column )` | `mixed` | Returns maximum matching column value (`int\|float` for numeric, `string` otherwise), or `null` if no rows match. | | `avg( $column )` | `int\|float\|null` | Returns average of matching column values, or `null` if no rows match. | | `exists()` | `bool` | Returns `true` if at least one matching record exists. | @@ -863,7 +863,7 @@ DB::get_last_query(); // Returns $wpdb->last_query ## Security Architecture 1. **Prepared Statements:** All literal values passed into `where()`, `where_in()`, `where_between()`, `insert()`, `update()`, and raw bindings are passed through `$wpdb->prepare()`. Raw expression methods (`select_raw()`, `where_raw()`, `or_where_raw()`, `having_raw()`, `order_by_raw()`) throw `InvalidArgumentException` if `prepare()` fails or produces an empty expression. -2. **Identifier Validation:** Column identifiers and table names are strictly validated against `/^[A-Za-z_*][A-Za-z0-9_.*]*$/`. All `where_*` builders (including `where_like()` and `where_between()` and their `or_`/`not_` variants) as well as `insert()` (`is_valid_identifier()`) throw `InvalidArgumentException` on invalid column names. Column aliases in `select()` are parsed and verified against strict column and alias patterns (`is_valid_column` and `is_valid_identifier`). Join conditions (including closure-based `on()` and `or_on()` conditions) validate both columns and operators against allowlists before inclusion. Characters that could trigger SQL injection (semicolons, comments, quotes, brackets) are rejected. +2. **Identifier Validation:** Column identifiers and table names are strictly validated against `/^[A-Za-z_*][A-Za-z0-9_.*]*$/`. Invalid columns or aliases throw `InvalidArgumentException` across `select()`, `group_by()`, `order_by()`, all `where_*` builders (including `where_like()` and `where_between()` and their `or_`/`not_` variants), and all write methods (`insert()`, `insert_multiple()`, `update()` via `is_valid_identifier()`). Aggregate methods (`sum()`, `min()`, `max()`, `avg()`) also reject wildcard `*` expressions. Join conditions (including closure-based `on()` and `or_on()` conditions) validate both columns and operators against allowlists before inclusion. Characters that could trigger SQL injection (semicolons, comments, quotes, brackets) are rejected. 3. **Mass-Mutation Guard & LIKE-Injection Protection:** `update()` and `delete()` refuse to execute without a `WHERE` clause (throwing `InvalidArgumentException`) unless `$allow_all = true` is explicitly passed. `where_like()` automatically processes input values via `$wpdb->esc_like()`, preventing wildcard abuse (`%` or `_`). 4. **Schema Inspection Safety:** `has_table()`, `has_column()`, and `has_columns()` validate all identifiers before running schema queries. Table lookups employ `$wpdb->esc_like()` with `SHOW TABLES LIKE`, and column queries quote validated table names within backticks. 5. **Robust Exception & Rollback Handling:** `DB::transaction()` catches all `\Throwable` instances (both exceptions and fatal PHP errors), ensuring transactions roll back reliably. Secondary rollback failures are trapped so the original root cause exception propagates cleanly. diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index f335336aea..9a5000fc77 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -655,12 +655,12 @@ public function test_identifier_sanitization() { $prefix = $wpdb->prefix; - // Malicious select column attempt should be ignored; malicious where column should throw. - $sql = DB::table( 'tutor_orders' ) - ->select( 'id', 'status; DROP TABLE tutor_orders; --' ) - ->to_sql(); - - $this->assertSame( "SELECT id FROM {$prefix}tutor_orders", $sql ); + // Malicious select and where columns should throw. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->select( 'id', 'status; DROP TABLE tutor_orders; --' ); + } + ); $this->assert_throws_invalid_argument( function () { @@ -810,15 +810,12 @@ public function test_select_aliases_with_table_prefix() { * @return void */ public function test_select_invalid_aliases_rejected() { - global $wpdb; - - $prefix = $wpdb->prefix; - $sql = DB::table( 'orders' ) - ->select( 'id AS valid_id', 'id AS 123invalid', 'id; DROP TABLE orders; --' ) - ->to_sql(); - - $expected = "SELECT id AS valid_id FROM {$prefix}orders"; - $this->assertSame( $expected, $sql ); + $this->assert_throws_invalid_argument( + fn() => DB::table( 'orders' )->select( 'id AS valid_id', 'id AS 123invalid' ) + ); + $this->assert_throws_invalid_argument( + fn() => DB::table( 'orders' )->select( 'id; DROP TABLE orders; --' ) + ); } /** @@ -1009,30 +1006,54 @@ public function test_join_with_string_callable_not_treated_as_closure() { public function test_write_operations_preserve_casing_and_reject_invalid() { $unique_key = 'qb_test_case_' . time() . '_' . wp_rand( 1000, 9999 ); - // insert_multiple with mixed casing and invalid column. - $rows = array( - array( - 'option_name' => $unique_key, - 'option_value' => 'val1', - 'autoload' => 'no', - 'invalid; DROP TABLE;--' => 'injected', - ), + // insert_multiple with invalid column throws. + $this->assert_throws_invalid_argument( + fn() => DB::table( 'options' )->insert_multiple( + array( + array( + 'option_name' => $unique_key, + 'option_value' => 'val1', + 'autoload' => 'no', + 'invalid; DROP TABLE;--' => 'injected', + ), + ) + ) ); - $result = DB::table( 'options' )->insert_multiple( $rows ); + // Valid insert_multiple succeeds. + $result = DB::table( 'options' )->insert_multiple( + array( + array( + 'option_name' => $unique_key, + 'option_value' => 'val1', + 'autoload' => 'no', + ), + ) + ); $this->assertTrue( $result ); // Verify row was inserted. $val = DB::table( 'options' )->where( 'option_name', $unique_key )->value( 'option_value' ); $this->assertSame( 'val1', $val ); - // update with invalid column ignored. + // update with invalid column throws. + $this->assert_throws_invalid_argument( + fn() => DB::table( 'options' ) + ->where( 'option_name', $unique_key ) + ->update( + array( + 'option_value' => 'val2', + 'invalid; DROP TABLE;--' => 'ignored', + ) + ) + ); + + // Valid update succeeds. $update_result = DB::table( 'options' ) ->where( 'option_name', $unique_key ) ->update( array( - 'option_value' => 'val2', - 'invalid; DROP TABLE;--' => 'ignored', + 'option_value' => 'val2', ) ); $this->assertTrue( $update_result ); @@ -2786,6 +2807,35 @@ function ( $j ) { $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->update( array( 'post_title' => 'x' ) ) ); $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->delete() ); + // Positive path: update( $data, true ) and delete( true ) execute without WHERE when explicitly allowed. + $mock_db = new class() extends \wpdb { + public $queries = array(); + public function __construct() {} + public function _real_escape( $data ) { + return addslashes( (string) $data ); + } + public function query( $query ) { + $this->queries[] = $query; + return 3; + } + }; + $mock_db->prefix = $wpdb->prefix; + $mock_db->base_prefix = $wpdb->base_prefix; + DB::set_db( $mock_db ); + try { + $this->assertTrue( DB::table( 'posts' )->update( array( 'post_title' => 'x' ), true ) ); + $this->assertSame( 3, DB::table( 'posts' )->delete( true ) ); + $this->assertSame( "UPDATE {$wpdb->prefix}posts SET post_title = 'x'", $mock_db->queries[0] ); + $this->assertSame( "DELETE FROM {$wpdb->prefix}posts", $mock_db->queries[1] ); + } finally { + DB::set_db( null ); + } + + // select(), group_by(), and order_by() throw on invalid columns. + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->select( 'bad; col' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->group_by( 'bad col' ) ); + $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->order_by( 'bad col' ) ); + // insert() validates column names. $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->insert( array( 'bad col' => 'value' ) ) ); $this->assert_throws_invalid_argument( fn() => DB::table( 'posts' )->insert( array( 'ID; DROP TABLE wp_posts' => 1 ) ) ); @@ -2833,12 +2883,13 @@ public function test_aggregate_methods() { ) ); - // Integer sum, avg, min, max, and distinct sum. + // Integer sum, avg, min, max, and distinct sum/avg. $this->assertSame( 80, DB::table( 'posts' )->where( 'post_type', $post_type )->sum( 'menu_order' ) ); $this->assertSame( 60, DB::table( 'posts' )->distinct()->where( 'post_type', $post_type )->sum( 'menu_order' ) ); $this->assertSame( 20.0, DB::table( 'posts' )->where( 'post_type', $post_type )->avg( 'menu_order' ) ); - $this->assertEquals( 10, DB::table( 'posts' )->where( 'post_type', $post_type )->min( 'menu_order' ) ); - $this->assertEquals( 30, DB::table( 'posts' )->where( 'post_type', $post_type )->max( 'menu_order' ) ); + $this->assertSame( 20.0, DB::table( 'posts' )->distinct()->where( 'post_type', $post_type )->avg( 'menu_order' ) ); + $this->assertSame( 10, DB::table( 'posts' )->where( 'post_type', $post_type )->min( 'menu_order' ) ); + $this->assertSame( 30, DB::table( 'posts' )->where( 'post_type', $post_type )->max( 'menu_order' ) ); // String min and max. $this->assertSame( 'alpha', DB::table( 'posts' )->where( 'post_type', $post_type )->min( 'post_title' ) ); @@ -2875,17 +2926,38 @@ public function test_aggregate_methods() { $this->assertNull( $empty->max( 'menu_order' ) ); $this->assertNull( $empty->avg( 'menu_order' ) ); - // Invalid column or '*' returns safe defaults without executing SQL. + // Invalid column, '*', or 't.*' returns safe defaults without executing SQL. $valid = DB::table( 'posts' )->where( 'post_type', $post_type ); $this->assertSame( 0, $valid->sum( '*' ) ); + $this->assertSame( 0, $valid->sum( 't.*' ) ); $this->assertSame( 0, $valid->sum( 'bad col' ) ); $this->assertNull( $valid->min( '*' ) ); + $this->assertNull( $valid->min( 't.*' ) ); $this->assertNull( $valid->min( 'bad col' ) ); $this->assertNull( $valid->max( '*' ) ); + $this->assertNull( $valid->max( 't.*' ) ); $this->assertNull( $valid->max( 'bad col' ) ); $this->assertNull( $valid->avg( '*' ) ); + $this->assertNull( $valid->avg( 't.*' ) ); $this->assertNull( $valid->avg( 'bad col' ) ); + // Builder state is preserved after calling aggregates, even when build_select_query() throws. + $missing_table = DB::table( 'posts' )->select( 'ID' )->where( 'ID', 1 )->limit( 5 ); + $ref_table = new \ReflectionProperty( DB::class, 'table' ); + $ref_table->setAccessible( true ); + $ref_table->setValue( $missing_table, '' ); + try { + $missing_table->sum( 'menu_order' ); + $this->fail( 'Expected InvalidArgumentException was not thrown.' ); + } catch ( \InvalidArgumentException $e ) { + $ref_cols = new \ReflectionProperty( DB::class, 'columns' ); + $ref_limit = new \ReflectionProperty( DB::class, 'limit_value' ); + $ref_cols->setAccessible( true ); + $ref_limit->setAccessible( true ); + $this->assertSame( array( 'ID' ), $ref_cols->getValue( $missing_table ) ); + $this->assertSame( 5, $ref_limit->getValue( $missing_table ) ); + } + // Builder state is preserved after calling aggregates. $builder = DB::table( 'posts' ) ->select( 'ID', 'menu_order' )