Use table aliases for columns in SQL generated by WP_Date_Query.

The use of non-aliased column names (eg 'post_date' instead of 'wp_posts.post_date')
in WP_Date_Query causes SQL notices and other failures when queries involve
table joins, such as date_query combined with tax_query or meta_query. This
changeset modifies WP_Date_Query::validate_column() to add the table alias when
it can be detected from the column name (ie, in the case of core columns).

A side effect of this change is that it is now possible to use WP_Date_Query
to build WHERE clauses across multiple tables, though there is currently no
core support for the automatic generation of the necessary JOIN clauses. See

Props ew_holmes, wonderboymusic, neoxx, Viper007Bond, boonebgorges.
Fixes #25775.

git-svn-id: https://develop.svn.wordpress.org/trunk@29933 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Boone Gorges
2014-10-17 01:19:03 +00:00
parent 8692199bb5
commit 42646e67b3
3 changed files with 140 additions and 22 deletions

View File

@@ -610,6 +610,8 @@ class Tests_Query_DateQuery extends WP_UnitTestCase {
}
public function test_date_params_monthnum_m_duplicate() {
global $wpdb;
$this->create_posts();
$posts = $this->_get_query_result( array(
@@ -629,11 +631,13 @@ class Tests_Query_DateQuery extends WP_UnitTestCase {
$this->assertEquals( $expected_dates, wp_list_pluck( $posts, 'post_date' ) );
$this->assertContains( "MONTH( post_date ) = 5", $this->q->request );
$this->assertNotContains( "MONTH( post_date ) = 9", $this->q->request );
$this->assertContains( "MONTH( $wpdb->posts.post_date ) = 5", $this->q->request );
$this->assertNotContains( "MONTH( $wpdb->posts.post_date ) = 9", $this->q->request );
}
public function test_date_params_week_w_duplicate() {
global $wpdb;
$this->create_posts();
$posts = $this->_get_query_result( array(
@@ -652,8 +656,40 @@ class Tests_Query_DateQuery extends WP_UnitTestCase {
$this->assertEquals( $expected_dates, wp_list_pluck( $posts, 'post_date' ) );
$this->assertContains( "WEEK( post_date, 1 ) = 21", $this->q->request );
$this->assertNotContains( "WEEK( post_date, 1 ) = 22", $this->q->request );
$this->assertContains( "WEEK( $wpdb->posts.post_date, 1 ) = 21", $this->q->request );
$this->assertNotContains( "WEEK( $wpdb->posts.post_date, 1 ) = 22", $this->q->request );
}
/**
* @ticket 25775
*/
public function test_date_query_with_taxonomy_join() {
$p1 = $this->factory->post->create( array(
'post_date' => '2013-04-27 01:01:01',
) );
$p2 = $this->factory->post->create( array(
'post_date' => '2013-03-21 01:01:01',
) );
register_taxonomy( 'foo', 'post' );
wp_set_object_terms( $p1, 'bar', 'foo' );
$posts = $this->_get_query_result( array(
'date_query' => array(
'year' => 2013,
),
'tax_query' => array(
array(
'taxonomy' => 'foo',
'terms' => array( 'bar' ),
'field' => 'name',
),
),
) );
_unregister_taxonomy( 'foo' );
$this->assertEquals( array( $p1 ), wp_list_pluck( $posts, 'ID' ) );
}
/**