- // Split out the meta_key only queries (we can only do this for OR)
- if ( 'OR' == $this->relation ) {
- foreach ( $this->queries as $k => $q ) {
- if ( ! array_key_exists( 'value', $q ) && ! empty( $q['key'] ) )
- $key_only_queries[$k] = $q;
- else
- $queries[$k] = $q;
+ return $sql;
+ }
+
+ /**
+ * Generate SQL clauses for a single query array.
+ *
+ * If nested subqueries are found, this method recurses the tree to
+ * produce the properly nested SQL.
+ *
+ * @since 4.1.0
+ * @access protected
+ *
+ * @param array $query Query to parse, passed by reference.
+ * @param int $depth Optional. Number of tree levels deep we currently are.
+ * Used to calculate indentation. Default 0.
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to a single query array.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ protected function get_sql_for_query( &$query, $depth = 0 ) {
+ $sql_chunks = array(
+ 'join' => array(),
+ 'where' => array(),
+ );
+
+ $sql = array(
+ 'join' => '',
+ 'where' => '',
+ );
+
+ $indent = '';
+ for ( $i = 0; $i < $depth; $i++ ) {
+ $indent .= " ";
+ }
+
+ foreach ( $query as $key => &$clause ) {
+ if ( 'relation' === $key ) {
+ $relation = $query['relation'];
+ } elseif ( is_array( $clause ) ) {
+
+ // This is a first-order clause.
+ if ( $this->is_first_order_clause( $clause ) ) {
+ $clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
+
+ $where_count = count( $clause_sql['where'] );
+ if ( ! $where_count ) {
+ $sql_chunks['where'][] = '';
+ } elseif ( 1 === $where_count ) {
+ $sql_chunks['where'][] = $clause_sql['where'][0];
+ } else {
+ $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
+ }
+
+ $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
+ // This is a subquery, so we recurse.
+ } else {
+ $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
+
+ $sql_chunks['where'][] = $clause_sql['where'];
+ $sql_chunks['join'][] = $clause_sql['join'];
+ }