<?php

add_action('template_redirect', function() {
	global $wpdb;

	assert_options(ASSERT_ACTIVE, 1);
	assert_options(ASSERT_QUIET_EVAL, 1);
	assert_options(ASSERT_WARNING, 0);
	assert_options(ASSERT_CALLBACK, function ($file, $line, $code) use ( &$failed ) {
		echo "Failed: $file (line $line)<hr />";
	});

	$mq = new WP_Meta_Query;

	// 'meta_key' & 'meta_value' = 0
	$qv = array(
		'meta_key' => 'foo',
		'meta_value' => 0,
	);

	$expected = array(
		array(
			'key' => 'foo',
			'value' => '0'
		)
	);

	$mq->parse_query_vars( $qv );
	assert( $mq->queries == $expected );

	$expected = " AND wp_postmeta.meta_key = 'foo' AND CAST(wp_postmeta.meta_value AS CHAR) = '0'";

	$clauses = $mq->get_sql( 'post', $wpdb->posts, 'ID' );
	assert( $clauses['where'] == $expected );

	// Only 'meta_key' (meta_value should be ignored)
	$qv = array(
		'meta_key' => 'foo',
		'meta_value' => '',
	);

	$expected = array(
		array(
			'key' => 'foo',
		)
	);

	$mq->parse_query_vars( $qv );
	assert( $mq->queries == $expected );

	$expected = " AND wp_postmeta.meta_key = 'foo'";

	$clauses = $mq->get_sql( 'post', $wpdb->posts, 'ID' );
	assert( $clauses['where'] == $expected );

	// 'key' and 'value' (value should _not_ be ignored)
	$meta_query = array(
		array(
			'key' => 'foo',
			'value' => '',
			'compare' => '!='
		)
	);

	$expected = " AND wp_postmeta.meta_key = 'foo' AND CAST(wp_postmeta.meta_value AS CHAR) != ''";

	$clauses = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );
	assert( $clauses['where'] == $expected );

	// empty 'value' with 'IN' comparison ('value' should not be ignored)
	$meta_query = array(
		array(
			'key' => 'foo',
			'value' => '0',
			'compare' => 'NOT IN',
		)
	);

	$expected = " AND wp_postmeta.meta_key = 'foo' AND CAST(wp_postmeta.meta_value AS CHAR) NOT IN ('0')";

	$clauses = get_meta_sql( $meta_query, 'post', $wpdb->posts, 'ID' );
	assert( $clauses['where'] == $expected );
});

