diff --git a/core/DB.php b/core/DB.php index afab2ff178..2b3d787dd7 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. * @@ -195,6 +205,25 @@ class DB { 'NOT BETWEEN', ); + /** + * Supported comparison operators for column-to-column and scalar comparisons. + * + * @since 4.3.0 + * + * @var string[] + */ + private static $comparison_operators = array( + '=', + '!=', + '<>', + '<', + '>', + '<=', + '>=', + 'LIKE', + 'NOT LIKE', + ); + // ───────────────────────────────────────────── // Factory & Database Accessors // ───────────────────────────────────────────── @@ -230,22 +259,97 @@ 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 (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. * - * @param string $table Table name (without prefix is fine). + * @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.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 static function table( string $table ): self { - $instance = new self(); - $instance->table = self::prepare_table_name( $table ); + 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 ); + $this->table = "({$sub_sql})"; + $this->is_derived = true; + $this->alias = null !== $alias ? $alias : ''; + + return $this; + } + + if ( ! is_string( $table ) || '' === trim( $table ) ) { + throw new InvalidArgumentException( 'Table name must be a non-empty string.' ); + } - return $instance; + $prepared_table = self::prepare_table_name( trim( $table ) ); + if ( ! self::is_valid_table_name( $prepared_table ) ) { + throw new InvalidArgumentException( 'Invalid table name.' ); + } + + $this->table = $prepared_table; + $this->is_derived = false; + if ( null !== $alias ) { + $this->alias = $alias; + } + + return $this; + } + + /** + * Set a derived table subquery as the FROM source. + * + * @since 4.3.0 + * + * @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 ) ) { + 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 ); } // ───────────────────────────────────────────── @@ -255,27 +359,67 @@ 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. + * + * @throws InvalidArgumentException If an associative alias => column pair has an invalid column or alias. * * @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( $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 ); + } + } + 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.3.0 + * + * @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 { + $aliased = self::parse_column_alias( $column ); + if ( null !== $aliased ) { + $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()." ) ); + } + } + /** * Add a raw SELECT expression. * @@ -290,12 +434,30 @@ public function select( string ...$columns ): self { * @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[] = $this->prepare_raw_expression( $expression, $bindings ); + + return $this; + } + + /** + * Add a subquery expression to the SELECT columns. + * + * @since 4.3.0 + * + * @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 { + if ( ! self::is_valid_identifier( $alias ) ) { + throw new InvalidArgumentException( 'Invalid column alias in select_sub().' ); } - $this->raw_columns[] = $expression; + $sub_sql = self::resolve_subquery( $subquery ); + $this->raw_columns[] = "({$sub_sql}) AS {$alias}"; return $this; } @@ -320,13 +482,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; } @@ -349,11 +515,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 +533,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 +551,121 @@ 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->compile_join( 'RIGHT', $this->parse_join_table( $table ), $first, $operator, $second ); + } - return $this->add_join( 'RIGHT', $table, $first, $operator, $second ); + /** + * Add a JOIN subquery clause. + * + * Supports standard 4-argument syntax or a closure for multiple ON conditions. + * + * @since 4.3.0 + * + * @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'. + * + * @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 { + return $this->add_subquery_join( $type, $subquery, $alias, $first, $operator, $second ); } /** - * Internal method to parse and prepare a join table with optional alias. + * Add a LEFT JOIN subquery clause. * - * @since 4.2.0 + * Supports standard 4-argument syntax or a closure for multiple ON conditions. * - * @param string $table Table name, may include alias e.g., 'users AS u'. + * @since 4.3.0 * - * @return string + * @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 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] ) : ''; + 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 ); + } - $table_expr = $table_name; - if ( ! empty( $table_alias ) && self::is_valid_identifier( $table_alias ) ) { - $table_expr .= " AS {$table_alias}"; + /** + * Add a RIGHT JOIN subquery clause. + * + * Supports standard 4-argument syntax or a closure for multiple ON conditions. + * + * @since 4.3.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 right_join_sub( $subquery, string $alias, $first, string $operator = '', string $second = '' ): self { + return $this->add_subquery_join( 'RIGHT', $subquery, $alias, $first, $operator, $second ); + } + + /** + * Add a CROSS JOIN subquery clause. + * + * @since 4.3.0 + * + * @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 ) ) { + throw new InvalidArgumentException( 'Invalid alias in cross_join_sub().' ); } - return $table_expr; + $sub_sql = self::resolve_subquery( $subquery ); + $this->joins[] = "CROSS JOIN ({$sub_sql}) AS {$alias}"; + + return $this; } /** - * Internal method to add a JOIN clause using a closure collector. + * Internal method to parse and prepare a join table with optional alias. * * @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 string $table Table name, may include alias e.g., 'users AS u'. * - * @return self + * @throws InvalidArgumentException If table name or alias is invalid. + * + * @return string */ - private function add_join_closure( string $type, string $table, callable $callback ): self { - $type = strtoupper( $type ); + private function parse_join_table( string $table ): string { + $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] ) : ''; - $allowed_types = array( 'INNER', 'LEFT', 'RIGHT', 'CROSS' ); - if ( ! in_array( $type, $allowed_types, true ) ) { - return $this; + if ( ! self::is_valid_table_name( $table_name ) ) { + throw new InvalidArgumentException( 'Invalid join table name.' ); } - $table_expr = $this->parse_join_table( $table ); - $collector = self::create_join_collector(); - - $callback( $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']}"; - } + $table_expr = $table_name; + if ( '' !== $table_alias ) { + if ( ! self::is_valid_identifier( $table_alias ) ) { + throw new InvalidArgumentException( 'Invalid join table alias.' ); } - $this->joins[] = "{$type} JOIN {$table_expr} ON {$on_parts}"; + $table_expr .= " AS {$table_alias}"; } - return $this; + return $table_expr; } /** @@ -485,6 +692,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 { @@ -502,6 +711,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 { @@ -520,153 +731,252 @@ 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 { - if ( DB::is_valid_column( $first ) - && DB::is_valid_operator( $operator ) - && DB::is_valid_column( $second ) - ) { - $operator = strtoupper( $operator ); - $this->conditions[] = array( - 'sql' => "{$first} {$operator} {$second}", - 'boolean' => $boolean, - ); + $operator = strtoupper( $operator ); + if ( ! DB::is_valid_comparison_operator( $operator ) ) { + throw new InvalidArgumentException( esc_html( "Invalid JOIN ON operator '{$operator}'." ) ); + } + + 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; } }; } /** - * 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. + * + * @throws InvalidArgumentException If join type, columns, or operator are invalid. * * @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' ); if ( ! in_array( $type, $allowed_types, true ) ) { + throw new InvalidArgumentException( esc_html( "Invalid join type '{$type}'." ) ); + } + + if ( $first instanceof Closure ) { + $collector = self::create_join_collector(); + $first( $collector ); + + 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}"; + return $this; } - $table_expr = $this->parse_join_table( $table ); + $operator = strtoupper( $operator ); + if ( ! self::is_valid_comparison_operator( $operator ) ) { + throw new InvalidArgumentException( esc_html( "Invalid JOIN operator '{$operator}'." ) ); + } - if ( 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}"; + 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; } + /** + * Internal method to add a JOIN subquery clause. + * + * @since 4.3.0 + * + * @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( esc_html( "Invalid join type '{$type}'." ) ); + } + + if ( ! self::is_valid_identifier( $alias ) ) { + throw new InvalidArgumentException( 'Invalid alias in join_sub().' ); + } + + $sub_sql = self::resolve_subquery( $subquery ); + + return $this->compile_join( $type, "({$sub_sql}) AS {$alias}", $first, $operator, $second ); + } + // ───────────────────────────────────────────── // WHERE // ───────────────────────────────────────────── /** - * Add a WHERE condition. + * Add a WHERE condition or multiple conditions. + * + * 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. * - * 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 { - return $this->add_where( $column, $operator_or_value, $value, 'AND', func_num_args() < 3 ); + public function where( $column, $operator_or_value = null, $value = null ): self { + return $this->dispatch_where( $column, $operator_or_value, $value, 'AND', func_num_args() ); } /** - * Add an OR WHERE condition. + * Add an OR WHERE condition or multiple conditions. * * @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|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() ); + } + + /** + * 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.3.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 comparing two columns. + * + * @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). + * @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 + * @since 4.3.0 Added subquery support. * - * @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' ); } @@ -680,14 +990,7 @@ public function or_where_not_in( string $column, array $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' ); } /** @@ -697,17 +1000,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' ); } /** @@ -717,17 +1015,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' ); } /** @@ -737,19 +1030,92 @@ 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; } + /** + * Add a WHERE EXISTS subquery condition. + * + * @since 4.3.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.3.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.3.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.3.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. * @@ -911,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; @@ -938,12 +1307,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; } @@ -962,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'; @@ -986,12 +1352,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; } @@ -1133,20 +1494,116 @@ public function first( string $output = 'OBJECT' ) { } /** - * Get the count of rows matching the query. + * Get the count of rows matching the query. + * + * @since 4.2.0 + * + * @param string $column Column to count, default '*'. + * + * @return int Total matching row count. + */ + public function count( string $column = '*' ): int { + if ( '*' !== $column && ! self::is_valid_column( $column ) ) { + $column = '*'; + } + + return (int) $this->aggregate( 'COUNT', $column ); + } + + /** + * Get the sum of a column's values matching the query. + * + * @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 ( false !== strpos( $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. + * + * 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 ( false !== strpos( $column, '*' ) || ! self::is_valid_column( $column ) ) { + return null; + } + + $result = $this->aggregate( 'MIN', $column ); + + return is_numeric( $result ) ? $result + 0 : $result; + } + + /** + * Get the maximum value of a column matching the query. + * + * 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 ( false !== strpos( $column, '*' ) || ! self::is_valid_column( $column ) ) { + return null; + } + + $result = $this->aggregate( 'MAX', $column ); + + return is_numeric( $result ) ? $result + 0 : $result; + } + + /** + * Get the average value of a column matching the query. + * + * @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 ( false !== strpos( $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 + * @since 4.3.0 * - * @param string $column Column to count, default '*'. + * @param string $function SQL aggregate function name. + * @param string $column Column name (or '*' for COUNT). * - * @return int Total matching row count. + * @return string|null Raw scalar result from $wpdb->get_var(). */ - public function count( string $column = '*' ): int { - if ( '*' !== $column && ! self::is_valid_column( $column ) ) { - $column = '*'; - } - - // Save state that count() modifies. + 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; @@ -1155,40 +1612,42 @@ public function count( string $column = '*' ): int { $saved_distinct = $this->is_distinct; $saved_lock = $this->lock; - // Override for count. - $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( "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( "COUNT({$column}) AS aggregate" ); + $this->raw_columns = array( "{$function}({$column}) AS aggregate" ); } - } else { - $this->raw_columns = array( "COUNT({$column}) AS aggregate" ); - } - $this->order_by_clauses = array(); - $this->limit_value = null; - $this->offset_value = 0; - $this->is_distinct = false; + $this->order_by_clauses = array(); + $this->limit_value = null; + $this->offset_value = 0; + $this->is_distinct = false; - $sql = $this->build_select_query(); - - // 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 (int) self::get_db()->get_var( $sql ); + return self::get_db()->get_var( $sql ); } /** @@ -1373,11 +1832,22 @@ 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 or if any column name is invalid. * * @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.' ); + } + + 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 @@ -1400,11 +1870,16 @@ 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. */ 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; } @@ -1413,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 ) ) { @@ -1459,22 +1935,29 @@ 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 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 DatabaseException If a database error occurs. + * @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. */ - 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.' ); + } + if ( empty( $data ) ) { return false; } $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 ) ) { @@ -1492,9 +1975,13 @@ public function update( array $data ): bool { $set_clause = implode( ', ', $set_parts ); $where_clause = $this->build_where_sql(); + 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}"; } @@ -1513,25 +2000,34 @@ 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 + * @since 4.3.0 Added $allow_all parameter. * - * @throws DatabaseException If a database error occurs. + * @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 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 ( '' === $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 { $sql = "DELETE FROM {$this->table}"; } - if ( ! empty( $where_clause ) ) { + if ( '' !== $where_clause ) { $sql .= " WHERE {$where_clause}"; } @@ -1576,6 +2072,165 @@ public function to_sql(): string { // Internal WHERE helpers // ───────────────────────────────────────────── + /** + * Internal method to add array-based WHERE conditions. + * + * Supports both associative column-value pairs and numeric array triples/tuples. + * + * @since 4.3.0 + * + * @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 { + if ( empty( $conditions ) ) { + return $this; + } + + $saved_wheres = $this->wheres; + $this->wheres = array(); + + 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 { + throw new InvalidArgumentException( 'Invalid condition tuple in where() array.' ); + } + } else { + throw new InvalidArgumentException( 'Invalid condition format in where() array.' ); + } + } + } finally { + $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', + ); + } + } + + return $this; + } + + /** + * Internal dispatcher for where() and or_where(). + * + * @since 4.3.0 + * + * @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 { + if ( is_array( $column ) ) { + return $this->add_array_where( $column, $boolean ); + } + + 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 ) ) { + 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 ); + } + + /** + * Internal method to add a WHERE condition with a subquery on the left-hand side. + * + * @since 4.3.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 ); + + return $this->append_where_condition( "({$sub_sql})", $operator_or_value, $value, $boolean, $is_two_arg ); + } + /** * Internal method to add a basic WHERE condition. * @@ -1590,13 +2245,34 @@ public function to_sql(): string { * @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 { 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 ); + } + + /** + * Shared helper to format and append a WHERE condition for a validated LHS expression. + * + * @since 4.3.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. + * + * @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 { // Determine operator and value. if ( $is_two_arg ) { $value = $operator_or_value; @@ -1605,11 +2281,32 @@ 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 ) ) { + throw new InvalidArgumentException( esc_html( "Invalid operator '{$operator}' for subquery comparison." ) ); + } + + $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'; $this->wheres[] = array( - 'sql' => "{$column} {$null_op} NULL", + 'sql' => "{$lhs} {$null_op} NULL", 'boolean' => $boolean, ); @@ -1617,13 +2314,13 @@ private function add_where( string $column, $operator_or_value, $value, string $ } if ( ! self::is_valid_operator( $operator ) ) { - return $this; + throw new InvalidArgumentException( esc_html( "Invalid operator '{$operator}'." ) ); } $prepared_value = self::prepare_value( $value ); $this->wheres[] = array( - 'sql' => "{$column} {$operator} {$prepared_value}", + 'sql' => "{$lhs} {$operator} {$prepared_value}", 'boolean' => $boolean, ); @@ -1631,19 +2328,44 @@ 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. + * + * @throws InvalidArgumentException If column, values, or subquery is invalid. * * @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 ) ) { + throw new InvalidArgumentException( 'Invalid column name in where_in().' ); + } + + if ( $values instanceof Closure || $values instanceof self ) { + $sub_sql = self::resolve_subquery( $values, false ); + $this->wheres[] = array( + 'sql' => "{$column} {$type} ({$sub_sql})", + 'boolean' => $boolean, + ); + + return $this; + } + + 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; } @@ -1657,6 +2379,66 @@ 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.3.0 + * + * @param Closure|self $subquery Subquery closure or DB instance. + * @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 ); + $this->wheres[] = array( + 'sql' => "{$type} ({$sub_sql})", + 'boolean' => $boolean, + ); + + return $this; + } + + /** + * Internal method to add a WHERE condition comparing two columns. + * + * @since 4.3.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. + * + * @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 { + if ( null === $second ) { + $operator = '='; + $second = $operator_or_second; + } else { + $operator = strtoupper( $operator_or_second ); + } + + if ( ! self::is_valid_column( $first ) + || ! self::is_valid_comparison_operator( $operator ) + || ! self::is_valid_column( $second ) + ) { + throw new InvalidArgumentException( 'Invalid column or operator in where_column().' ); + } + + $this->wheres[] = array( + 'sql' => "{$first} {$operator} {$second}", + 'boolean' => $boolean, + ); + + return $this; + } + /** * Internal method for BETWEEN / NOT BETWEEN conditions. * @@ -1668,11 +2450,13 @@ private function add_where_in( string $column, array $values, string $type, stri * @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 ); @@ -1698,11 +2482,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(); @@ -1727,20 +2513,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.3.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; } // ───────────────────────────────────────────── @@ -1754,11 +2562,18 @@ 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 { $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(); @@ -1777,7 +2592,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; @@ -1828,9 +2645,15 @@ 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 { + 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}"; } @@ -1969,7 +2792,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 ); } /** @@ -2014,6 +2837,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. * @@ -2039,6 +2875,45 @@ 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. + * + * 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 bool $allow_limit Whether LIMIT is allowed inside this subquery. + * + * @throws InvalidArgumentException If subquery is invalid, empty, or uses unsupported clauses. + * + * @return string The compiled SQL string. + */ + private static function resolve_subquery( $query, bool $allow_limit = true ): string { + if ( $query instanceof Closure ) { + $sub = new self(); + $result = $query( $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 ( empty( $sub->table ) && empty( $sub->raw_columns ) ) { + throw new InvalidArgumentException( 'Subquery must define a FROM table or raw select expression.' ); + } + + if ( ! $allow_limit && null !== $sub->limit_value ) { + throw new InvalidArgumentException( 'LIMIT is not supported inside IN/NOT IN subqueries.' ); + } + + $sub->lock = ''; + + return $sub->build_select_query(); + } + /** * Prepare a single value for safe SQL inclusion using $wpdb->prepare(). * diff --git a/docs/developer/core/DB.php.md b/docs/developer/core/DB.php.md index 71f08c749b..c9625e5b69 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( string $column, $operator_or_val, $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 where( $column, $operator_or_val = null, $val = null ): 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; @@ -128,13 +141,17 @@ 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 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; @@ -167,6 +184,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; } ``` @@ -290,24 +308,126 @@ 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 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). + +```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']); ``` -### 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 +435,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 +451,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 @@ -399,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 (`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. | ```php @@ -410,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 @@ -445,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([ @@ -488,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 )`). --- @@ -729,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_.*]*$/`. 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. 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 ff0dbfaf44..9a5000fc77 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -125,6 +125,327 @@ 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 throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( array() ) ); + } + ); + + // 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 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 throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( 123, 'random_string' ) ); + } + ); + + // 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 throws. + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( array( array( 'order_status', 'INVALID_OP', 'completed' ) ) ); + } + ); + } + + /** + * 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 ); + } + } + + /** + * 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 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 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 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"; + $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. * @@ -334,13 +655,18 @@ public function test_identifier_sanitization() { $prefix = $wpdb->prefix; - // Malicious column attempt should be ignored. - $sql = DB::table( 'tutor_orders' ) - ->select( 'id', 'status; DROP TABLE tutor_orders; --' ) - ->where( '1=1; --', 'val' ) - ->to_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->assertSame( "SELECT id FROM {$prefix}tutor_orders", $sql ); + $this->assert_throws_invalid_argument( + function () { + DB::table( 'tutor_orders' )->where( '1=1; --', 'val' ); + } + ); } /** @@ -484,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; --' ) + ); } /** @@ -616,26 +939,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' ); + } + ); + } + ); } /** @@ -687,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 ); @@ -1574,4 +1917,1066 @@ public function test_get_table_prefix() { $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. + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' ) + ->select( 'id' ) + ->select_sub( $sub, 'invalid alias;--' ); + } + ); + } + + /** + * 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. + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' )->from_sub( $sub, 'invalid alias;--' ); + } + ); + } + + /** + * 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. + $this->assert_throws_invalid_argument( + function () use ( $sub ) { + DB::table( 'users' )->join_sub( $sub, 'invalid alias;--', 'u.id', '=', 's.user_id' ); + } + ); + } + + /** + * 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 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' ) ); + + // 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' ) ); + $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' ); + $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 ) ); + } + + /** + * 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 throws InvalidArgumentException. + $this->assert_throws_invalid_argument( fn() => DB::table( new \stdClass() ) ); + + // 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 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' ) ); + } + + /** + * 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 (grouped with AND inside OR). + $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' AND 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 creates a grouped WHERE (...) clause. + $sql = DB::table( 'users' ) + ->where( 'user_status', 0 ) + ->where( + function ( $q ) { + $q->where( 'user_login', 'admin' ) + ->or_where( 'ID', 1 ); + } + ) + ->to_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 + ); + } + ); + } + + /** + * 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 / 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' ) + ->select_raw( 'COUNT(*)' ) + ->where_column( 'o.user_id', '=', 'u.id' ); + }, + 'max_spent' => $sub, + ) + ) + ->to_sql(); + + $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' ) + ->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' ) + ->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 + ); + + // 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; + $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->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() ); + + // 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 ) ) ); + } + + /** + * 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/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->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' ) ); + $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 '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' ) + ->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(); + } + } }