php代码
query pairs
* expired will be recompile automatically, any update on config should update ctime as well
*
* @author anthony.chen
* 2010-2012 reserved
*/
class pstmt{
public static $instances = array();
/**
* loading the prepare statment from db connection
* the stmts is config linked to db instance with 'stmts' k=>v array
*
* @return boolean
*/
public static function prepare($db='default'){
//getting statment from config
$_config = pexcel::config('database')->$db;
$_ctime = arr::get($_config,'ctime',0);
$_configstmts = arr::get($_config,'stmts',null);
if($_configstmts != null){//there is statments configured
if(!isset(self::$instances[$db])){
$_sql = 'select name , extract(epoch from prepare_time) as ctime from pg_prepared_statements';
$_pstmts = db::query(db::select,$_sql,true)->execute($db)->as_array();
if(!$_pstmts){
self::$instances[$db] = array();
}else{
//log::debug('before commpiling,statement found');
foreach($_pstmts as $_pstmt){
self::$instances[$db][$_pstmt->name] = $_pstmt->ctime;
}
}
}
//compile the statments
foreach($_configstmts as $stmtname => $stmtquery){
if(isset(self::$instances[$db][$stmtname])){
if( self::$instances[$db][$stmtname] < $_ctime){
//log::debug($stmtname.' expires');
}else{
//log::debug($stmtname.' exists');
continue;
}
}
self::compile($stmtname,$stmtquery,$db);
}
}else{
throw new error_exception('stmts not in config!');
}
return true;
}
/**
* compile the prepared statment
*
* @param string $stmtname, statement name
* @param string $stmtquery, statement query
* @param string $db ,instance name of database
*
* @return boolean
*/
public static function compile($stmtname, $stmtquery,$db ='default'){
if(isset(self::$instances[$db][$stmtname])){ //already compiled
//doing nothing
//log::debug('deallocate '.$stmtname);
db::query(db::update,'deallocate '.$stmtname)->execute($db);
}
$_ret = db::query(db::select,$stmtquery,false,null,$stmtname)->execute($db)->count();
//log::debug(__function__.':compiling the pstat:'.$stmtquery);
self::$instances[$db][$stmtname] = time();
return true;
}
/**
* execute the prepared statement
*
* @param string $stmtname, statement name
* @param array $params , the parameter to be transfered into query
* @param boolean $as_object, true to fetch result as object
* @param string $db, database instance name
*
* @return array of result set
*/
public static function execute($stmtname,$params = array(),$as_object = true,$db = 'default'){
if(isset(self::$instances[$db][$stmtname])){
return db::query(db::select,null,$as_object,$params,$stmtname)->execute($db);
}else{
$_config = pexcel::config('database')->$db;
$_configstmts = arr::get($_config,'stmts',null);
//compile the prepared statment
if(isset($_configstmts[$stmtname])){
self::compile($stmtname,$_configstmts[$stmtname],$db);
}else{
return false;
}
return db::query(db::select,null,$as_object,$params,$stmtname)->execute($db);
}
}
}