pdo;
}
public function __construct($name = 'master') {
global $_W;
$this->cfg = $_W['config']['db'];
unset($_W['config']['db']);
$_W['config']['db']['tablepre'] = $this->cfg['tablepre'];
$_W['config']['db']['slave_status'] = $this->cfg['slave_status'];
$this->connect($name);
}
public function connect($name = 'master') {
if(is_array($name)) {
$cfg = $name;
} else {
$cfg = $this->cfg[$name];
}
$this->tablepre = $cfg['tablepre'];
if(empty($cfg)) {
exit("The master database is not found, Please checking 'data/config.php'");
}
$dsn = "mysql:dbname={$cfg['database']};host={$cfg['host']};port={$cfg['port']};charset={$cfg['charset']}";
$dbclass = '';
$options = array();
if (class_exists('PDO')) {
if (extension_loaded("pdo_mysql") && in_array('mysql', PDO::getAvailableDrivers())) {
$dbclass = 'PDO';
$options = array(PDO::ATTR_PERSISTENT => $cfg['pconnect']);
} else {
if(!class_exists('_PDO')) {
include IA_ROOT . '/framework/library/pdo/PDO.class.php';
}
$dbclass = '_PDO';
}
} else {
include IA_ROOT . '/framework/library/pdo/PDO.class.php';
$dbclass = 'PDO';
}
$this->pdo = new $dbclass($dsn, $cfg['username'], $cfg['password'], $options);
$sql = "SET NAMES '{$cfg['charset']}';";
$this->pdo->exec($sql);
$this->pdo->exec("SET sql_mode='';");
if(is_string($name)) {
$this->link[$name] = $this->pdo;
}
$this->logging($sql);
}
public function prepare($sql) {
$sqlsafe = SqlPaser::checkquery($sql);
if (is_error($sqlsafe)) {
trigger_error($sqlsafe['message'], E_USER_ERROR);
return false;
}
if ($GLOBALS['_W']['config']['setting']['development'] == 3) {
if ($GLOBALS['error_handler'] instanceof Raven_ErrorHandler) {
$GLOBALS['error_handler']->handleError(E_USER_ERROR, $sql);
}
}
$statement = $this->pdo->prepare($sql);
return $statement;
}
public function query($sql, $params = array()) {
$sqlsafe = SqlPaser::checkquery($sql);
if (is_error($sqlsafe)) {
trigger_error($sqlsafe['message'], E_USER_ERROR);
return false;
}
$starttime = microtime(true);
if (empty($params)) {
$result = $this->pdo->exec($sql);
$this->logging($sql, array(), $this->pdo->errorInfo());
return $result;
}
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = microtime(true);
$this->performance($sql, $endtime - $starttime);
if (!$result) {
return false;
} else {
return $statement->rowCount();
}
}
public function fetchcolumn($sql, $params = array(), $column = 0) {
$starttime = microtime();
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = microtime();
$this->performance($sql, $endtime - $starttime);
if (!$result) {
return false;
} else {
$data = $statement->fetchColumn($column);
return $data;
}
}
public function fetch($sql, $params = array()) {
$starttime = microtime();
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = microtime();
$this->performance($sql, $endtime - $starttime);
if (!$result) {
return false;
} else {
$data = $statement->fetch(pdo::FETCH_ASSOC);
return $data;
}
}
public function fetchall($sql, $params = array(), $keyfield = '') {
$starttime = microtime();
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = microtime();
$this->performance($sql, $endtime - $starttime);
if (!$result) {
return false;
} else {
if (empty($keyfield)) {
$result = $statement->fetchAll(pdo::FETCH_ASSOC);
} else {
$temp = $statement->fetchAll(pdo::FETCH_ASSOC);
$result = array();
if (!empty($temp)) {
foreach ($temp as $key => &$row) {
if (isset($row[$keyfield])) {
$result[$row[$keyfield]] = $row;
} else {
$result[] = $row;
}
}
}
}
return $result;
}
}
public function get($tablename, $params = array(), $fields = array(), $orderby = array()) {
$select = SqlPaser::parseSelect($fields);
$condition = SqlPaser::parseParameter($params, 'AND');
$orderbysql = SqlPaser::parseOrderby($orderby);
$sql = "{$select} FROM " . $this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . " $orderbysql LIMIT 1";
return $this->fetch($sql, $condition['params']);
}
public function getall($tablename, $params = array(), $fields = array(), $keyfield = '', $orderby = array(), $limit = array()) {
$select = SqlPaser::parseSelect($fields);
$condition = SqlPaser::parseParameter($params, 'AND');
$limitsql = SqlPaser::parseLimit($limit);
$orderbysql = SqlPaser::parseOrderby($orderby);
$sql = "{$select} FROM " .$this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . $orderbysql . $limitsql;
return $this->fetchall($sql, $condition['params'], $keyfield);
}
public function getslice($tablename, $params = array(), $limit = array(), &$total = null, $fields = array(), $keyfield = '', $orderby = array()) {
$select = SqlPaser::parseSelect($fields);
$condition = SqlPaser::parseParameter($params, 'AND');
$limitsql = SqlPaser::parseLimit($limit);
if (!empty($orderby)) {
if (is_array($orderby)) {
$orderbysql = implode(',', $orderby);
} else {
$orderbysql = $orderby;
}
}
$sql = "{$select} FROM " . $this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . (!empty($orderbysql) ? " ORDER BY $orderbysql " : '') . $limitsql;
$total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : ''), $condition['params']);
return $this->fetchall($sql, $condition['params'], $keyfield);
}
public function getcolumn($tablename, $params = array(), $field = '') {
$result = $this->get($tablename, $params, $field);
if (!empty($result)) {
if (strexists($field, '(')) {
return array_shift($result);
} else {
return $result[$field];
}
} else {
return false;
}
}
public function update($table, $data = array(), $params = array(), $glue = 'AND') {
$fields = SqlPaser::parseParameter($data, ',');
$condition = SqlPaser::parseParameter($params, $glue);
$params = array_merge($fields['params'], $condition['params']);
$sql = "UPDATE " . $this->tablename($table) . " SET {$fields['fields']}";
$sql .= $condition['fields'] ? ' WHERE '.$condition['fields'] : '';
return $this->query($sql, $params);
}
public function insert($table, $data = array(), $replace = FALSE) {
$cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
$condition = SqlPaser::parseParameter($data, ',');
return $this->query("$cmd " . $this->tablename($table) . " SET {$condition['fields']}", $condition['params']);
}
public function insertid() {
return $this->pdo->lastInsertId();
}
public function delete($table, $params = array(), $glue = 'AND') {
$condition = SqlPaser::parseParameter($params, $glue);
$sql = "DELETE FROM " . $this->tablename($table);
$sql .= $condition['fields'] ? ' WHERE '.$condition['fields'] : '';
return $this->query($sql, $condition['params']);
}
public function exists($tablename, $params = array()) {
$row = $this->get($tablename, $params);
if (empty($row) || !is_array($row) || count($row) == 0) {
return false;
} else {
return true;
}
}
public function count($tablename, $params = array(), $cachetime = 30) {
$total = pdo_getcolumn($tablename, $params, 'count(*)');
return intval($total);
}
public function begin() {
$this->pdo->beginTransaction();
}
public function commit() {
$this->pdo->commit();
}
public function rollback() {
$this->pdo->rollBack();
}
public function run($sql, $stuff = 'ims_') {
if(!isset($sql) || empty($sql)) return;
$sql = str_replace("\r", "\n", str_replace(' ' . $stuff, ' ' . $this->tablepre, $sql));
$sql = str_replace("\r", "\n", str_replace(' `' . $stuff, ' `' . $this->tablepre, $sql));
$ret = array();
$num = 0;
$sql = preg_replace("/\;[ \f\t\v]+/", ';', $sql);
foreach(explode(";\n", trim($sql)) as $query) {
$ret[$num] = '';
$queries = explode("\n", trim($query));
foreach($queries as $query) {
$ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
}
$num++;
}
unset($sql);
foreach($ret as $query) {
$query = trim($query);
if($query) {
$this->query($query, array());
}
}
}
public function fieldexists($tablename, $fieldname) {
$isexists = $this->fetch("DESCRIBE " . $this->tablename($tablename) . " `{$fieldname}`", array());
return !empty($isexists) ? true : false;
}
public function fieldmatch($tablename, $fieldname, $datatype = '', $length = '') {
$datatype = strtolower($datatype);
$field_info = $this->fetch("DESCRIBE " . $this->tablename($tablename) . " `{$fieldname}`", array());
if (empty($field_info)) {
return false;
}
if (!empty($datatype)) {
$find = strexists($field_info['Type'], '(');
if (empty($find)) {
$length = '';
}
if (!empty($length)) {
$datatype .= ("({$length})");
}
return strpos($field_info['Type'], $datatype) === 0 ? true : -1;
}
return true;
}
public function indexexists($tablename, $indexname) {
if (!empty($indexname)) {
$indexs = $this->fetchall("SHOW INDEX FROM " . $this->tablename($tablename), array(), '');
if (!empty($indexs) && is_array($indexs)) {
foreach ($indexs as $row) {
if ($row['Key_name'] == $indexname) {
return true;
}
}
}
}
return false;
}
public function tablename($table) {
return (strpos($table, $this->tablepre) === 0 || strpos($table, 'ims_') === 0) ? $table : "`{$this->tablepre}{$table}`";
}
public function debug($output = true, $append = array()) {
if(!empty($append)) {
$output = false;
array_push($this->errors, $append);
}
if($output) {
print_r($this->errors);
} else {
if (!empty($append['error'][1])) {
$traces = debug_backtrace();
$ts = '';
foreach($traces as $trace) {
$trace['file'] = str_replace('\\', '/', $trace['file']);
$trace['file'] = str_replace(IA_ROOT, '', $trace['file']);
$ts .= "file: {$trace['file']}; line: {$trace['line']};
";
}
$params = var_export($append['params'], true);
if (!function_exists('message')) {
load()->web('common');
load()->web('template');
}
trigger_error("SQL:
{$append['sql']}