#!/usr/bin/php
<?php
/*
Copyright (c) 2010, Justin Swanhart
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*This script requires PEAR Net_Gearman */
/*It also requires Console_Getopt, but this should be installed by default with pear */
set_include_path(get_include_path() . PATH_SEPARATOR . '../include');
require_once 'Console/Getopt.php';
require_once 'shard-query.php';
require_once 'common.php';
$verbose=false;

main();
exit;

function help() {
	shard_query_common_help();
	run_query_help();
	echo "\n";
	exit;
}

function main() {
	$params = get_commandline(array('file='));

	if(has_short_opt('help',$params)) help();

	$verbose = false;
	if(has_short_opt('verbose',$params)) {
		$verbose = true;
	}

	if(empty($params['file'])) {
		$params['file'] = 'php://stdin';
	}

	if(!empty($params['schema'])) {
		$schema = $params['schema'];
	} else {
		$schema=null;
	}

	$fh = fopen($params['file'],'r');
	if(!$fh) {
		die('Could not open file: ' . $params['file'] . "\n");
	}
	$sql = "";
	$stmt = false;

	#read lines until semicolon then execute the statement
	#super simple (line MUST end with ;)
	while ($line = fgets($fh)) {
		if(substr(trim($line),0,2) == '--') { echo $line; continue; }
		if(substr(trim($line),0,1) == '#') { echo $line; continue; }
		if ($sql) $sql .= " ";
		$sql .= trim($line);

#		$shard_query = null;	
		if(feof($fh) || substr($sql,-1) == ";") {

			if(!isset($shard_query)) $shard_query = new ShardQuery($schema);

			unset($shard_query->errors);
			if(!empty($shard_query->errors)) {
				echo "ERRORS RETURNED BY OPERATION:\n";
				print_r($shard_query->errors);
				continue;
			}
#$shard_query->async=true;
			$stime = microtime(true);
			$stmt = $shard_query->query($sql);
			$endtime = microtime(true);

			if($verbose && isset($shard_query->state->explain)) echo $shard_query->state->explain . "\n";

			if($stmt === false || !empty($shard_query->errors)) {
				if(!empty($shard_query->errors)) {
					echo "ERRORS RETURNED BY OPERATION:\n";
					print_r($shard_query->errors);
				}
			}

			if(is_resource($stmt) || is_object($stmt)) {
				$count=0;
				while($row = $shard_query->DAL->my_fetch_assoc($stmt)) {
					print_r($row);
					++$count;
				}
				echo "$count rows returned\n";
				$shard_query->DAL->my_free_result($stmt);
			} else {
				if(!empty($shard_query->info)) print_r($shard_query->info);
				echo "no query results\n";
			}
			echo "Exec time: " . ($endtime - $stime) . "\n";
			$sql = "";

			if($verbose) {
				echo "INSTRUMENATION:\n";
				print_r(Instrumentation::get_instance()->dump_counters('array'));
			}
		}
	}
}
