Opened 14 years ago
Closed 13 years ago
#22096 closed defect (bug) (fixed)
IN meta_query with empty array as meta_value results in invalid database query
| Reported by: | batmoo | Owned by: | wonderboymusic |
|---|---|---|---|
| Priority: | normal | Milestone: | 3.6 |
| Component: | Query | Version: | 3.1.3 |
| Severity: | normal | Keywords: | has-patch |
| Cc: | Focuses: |
Description
If you do an IN meta_query and pass in an empty array to the value, the INNER JOIN clause for the postmeta table isn't added, which results in an invalid query:
new WP_Query( array(
'meta_query' => array( array( 'key' => 'abc', 'value' => array(), 'compare' => 'IN' ) )
) );
This results in an error like so:
WordPress database error: [Unknown column 'wp_postmeta.meta_key' in 'where clause'] SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND (wp_postmeta.meta_key = 'abc' ) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 5
Attachments (2)
Change History (15)
#4
@
14 years ago
- Keywords has-patch added
- Milestone Awaiting Review → Future Release
- Owner set to
- Status new → accepted
We need to add WP_Meta_query::clean_query maybe
#5
@
14 years ago
- Milestone Future Release → 3.6
This patch still applies cleanly, works, etc (I have no recollection of actually writing this patch)
#6
@
13 years ago
Another example, this time when you combine a 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' with an empty value and another valid IN:
new WP_Query( array(
'meta_query' => array(
'relation' => 'AND',
array( 'key' => 'key1', 'value' => array( 'value1', 'value1b' ), 'compare' => 'IN' ),
array( 'key' => 'key2', 'value' => array(), 'compare' => 'NOT IN' )
)
) );
results in:
SELECT SQL_CALC_FOUND_ROWS wp_15797879_posts.ID FROM wp_15797879_posts INNER JOIN wp_15797879_postmeta ON (wp_15797879_posts.ID = wp_15797879_postmeta.post_id) WHERE 1=1 AND wp_15797879_posts.post_type = \'post\' AND (wp_15797879_posts.post_status = \'publish\') AND ( (wp_15797879_postmeta.meta_key = 'key1' AND CAST(wp_15797879_postmeta.meta_value AS CHAR) IN (\'value1\',\'value1b\')) AND mt1.meta_key = 'key2' ) GROUP BY wp_15797879_posts.ID ORDER BY wp_15797879_posts.post_date DESC LIMIT 0, 10
The JOIN for mt1 is unset and the meta_value ignored (http://core.trac.wordpress.org/browser/trunk/wp-includes/meta.php?rev=23961#L789) resulting in an invalid query and an SQL error:
Unknown column 'mt1.meta_key' in 'where clause'
#8
@
13 years ago
In 1276/tests:
#9
@
13 years ago
@wonderboymusic I just came across an incident of this again and wrote the above unit test.
Is this ready to commit or are there more test cases we should add here?
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
Reproduced in 3.4.