<?php<liu21st@gmail.com>
defined('THINK_PATH') or exit();
/**
* MSsql数据库驱动 要求sqlserver2005
* @category Extend
* @package Extend
* @subpackage Driver.Db
* @author liu21st <liu21st@gmail.com>
*/
class DbMssql extends Db{
protected $selectSql = 'SELECT T1.* FROM (SELECT thinkphp.*, ROW_NUMBER() OVER (%ORDER%) AS ROW_NUMBER FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%) AS thinkphp) AS T1 %LIMIT%%COMMENT%';
public function __construct($config=''){
if ( !function_exists('mssql_connect') ) {
throw_exception(L('_NOT_SUPPERT_').':mssql');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'mssql_pconnect':'mssql_connect';
$sepr = IS_WIN ? ',' : ':';
$host = $config['hostname'].($config['hostport']?$sepr."{$config['hostport']}":'');
$this->linkID[$linkNum] = $conn( $host, $config['username'], $config['password']);
if ( !$this->linkID[$linkNum] ) throw_exception("Couldn't connect to SQL Server on $host");
if ( !empty($config['database']) && !mssql_select_db($config['database'], $this->linkID[$linkNum]) ) {
throw_exception("Couldn't open database '".$config['database']);
}
$this->connected = true;
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
public function free() {
mssql_free_result($this->queryID);
$this->queryID = null;
}
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
if ( $this->queryID ) $this->free();
N('db_query',1);
G('queryStartTime');
$this->queryID = mssql_query($str, $this->_linkID);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = mssql_num_rows($this->queryID);
return $this->getAll();
}
}
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
if ( $this->queryID ) $this->free();
N('db_write',1);
G('queryStartTime');
$result = mssql_query($str, $this->_linkID);
$this->debug();
if ( false === $result ) {
$this->error();
return false;
} else {
$this->numRows = mssql_rows_affected($this->_linkID);
$this->lastInsID = $this->mssql_insert_id();
return $this->numRows;
}
}
public function mssql_insert_id() {
$query = "SELECT @@IDENTITY as last_insert_id";
$result = mssql_query($query, $this->_linkID);
list($last_insert_id) = mssql_fetch_row($result);
mssql_free_result($result);
return $last_insert_id;
}
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
if ($this->transTimes == 0) {
mssql_query('BEGIN TRAN', $this->_linkID);
}
$this->transTimes++;
return ;
}
public function commit() {
if ($this->transTimes > 0) {
$result = mssql_query('COMMIT TRAN', $this->_linkID);
$this->transTimes = 0;
if(!$result){
$this->error();
return false;
}
}
return true;
}
public function rollback() {
if ($this->transTimes > 0) {
$result = mssql_query('ROLLBACK TRAN', $this->_linkID);
$this->transTimes = 0;
if(!$result){
$this->error();
return false;
}
}
return true;
}
private function getAll() {
$result = array();
if($this->numRows >0) {
while($row = mssql_fetch_assoc($this->queryID))
$result[] = $row;
}
return $result;
}
public function getFields($tableName) {
$result = $this->query("SELECT column_name, data_type, column_default, is_nullable
FROM information_schema.tables AS t
JOIN information_schema.columns AS c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_name = '$tableName'");
$info = array();
if($result) {
foreach ($result as $key => $val) {
$info[$val['column_name']] = array(
'name' => $val['column_name'],
'type' => $val['data_type'],
'notnull' => (bool) ($val['is_nullable'] === ''), 'default' => $val['column_default'],
'primary' => false,
'autoinc' => false,
);
}
}
return $info;
}
public function getTables($dbName='') {
$result = $this->query("SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
protected function parseOrder($order) {
return !empty($order)? ' ORDER BY '.$order:' ORDER BY rand()';
}
public function parseLimit($limit) {
if(empty($limit)) return '';
$limit = explode(',',$limit);
if(count($limit)>1)
$limitStr = '(T1.ROW_NUMBER BETWEEN '.$limit[0].' + 1 AND '.$limit[0].' + '.$limit[1].')';
else
$limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND '.$limit[0].")";
return 'WHERE '.$limitStr;
}
public function update($data,$options) {
$this->model = $options['model'];
$sql = 'UPDATE '
.$this->parseTable($options['table'])
.$this->parseSet($data)
.$this->parseWhere(!empty($options['where'])?$options['where']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false)
.$this->parseComment(!empty($options['comment'])?$options['comment']:'');
return $this->execute($sql);
}
public function delete($options=array()) {
$this->model = $options['model'];
$sql = 'DELETE FROM '
.$this->parseTable($options['table'])
.$this->parseWhere(!empty($options['where'])?$options['where']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false)
.$this->parseComment(!empty($options['comment'])?$options['comment']:'');
return $this->execute($sql);
}
public function close() {
if ($this->_linkID){
mssql_close($this->_linkID);
}
$this->_linkID = null;
}
public function error() {
$this->error = mssql_get_last_message();
if('' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
trace($this->error,'','ERR');
return $this->error;
}
}