DbSqlsrv.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. defined('THINK_PATH') or exit();
  12. /**
  13. * Sqlsrv数据库驱动
  14. * @category Extend
  15. * @package Extend
  16. * @subpackage Driver.Db
  17. * @author liu21st <liu21st@gmail.com>
  18. */
  19. class DbSqlsrv extends Db{
  20. 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%';
  21. /**
  22. * 架构函数 读取数据库配置信息
  23. * @access public
  24. * @param array $config 数据库配置数组
  25. */
  26. public function __construct($config='') {
  27. if ( !function_exists('sqlsrv_connect') ) {
  28. throw_exception(L('_NOT_SUPPERT_').':sqlsrv');
  29. }
  30. if(!empty($config)) {
  31. $this->config = $config;
  32. }
  33. }
  34. /**
  35. * 连接数据库方法
  36. * @access public
  37. */
  38. public function connect($config='',$linkNum=0) {
  39. if ( !isset($this->linkID[$linkNum]) ) {
  40. if(empty($config)) $config = $this->config;
  41. $host = $config['hostname'].($config['hostport']?",{$config['hostport']}":'');
  42. $connectInfo = array('Database'=>$config['database'],'UID'=>$config['username'],'PWD'=>$config['password'],'CharacterSet' => C('DEFAULT_CHARSET'));
  43. $this->linkID[$linkNum] = sqlsrv_connect( $host, $connectInfo);
  44. if ( !$this->linkID[$linkNum] ) $this->error(false);
  45. // 标记连接成功
  46. $this->connected = true;
  47. //注销数据库安全信息
  48. if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
  49. }
  50. return $this->linkID[$linkNum];
  51. }
  52. /**
  53. * 释放查询结果
  54. * @access public
  55. */
  56. public function free() {
  57. sqlsrv_free_stmt($this->queryID);
  58. $this->queryID = null;
  59. }
  60. /**
  61. * 执行查询 返回数据集
  62. * @access public
  63. * @param string $str sql指令
  64. * @param array $bind 参数绑定
  65. * @return mixed
  66. */
  67. public function query($str,$bind=array()) {
  68. $this->initConnect(false);
  69. if ( !$this->_linkID ) return false;
  70. //释放前次的查询结果
  71. if ( $this->queryID ) $this->free();
  72. N('db_query',1);
  73. // 记录开始执行时间
  74. G('queryStartTime');
  75. $str = str_replace(array_keys($bind),'?',$str);
  76. $bind = array_values($bind);
  77. $this->queryStr = $str;
  78. $this->queryID = sqlsrv_query($this->_linkID,$str,$bind, array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
  79. $this->debug();
  80. if ( false === $this->queryID ) {
  81. $this->error();
  82. return false;
  83. } else {
  84. $this->numRows = sqlsrv_num_rows($this->queryID);
  85. return $this->getAll();
  86. }
  87. }
  88. /**
  89. * 执行语句
  90. * @access public
  91. * @param string $str sql指令
  92. * @param array $bind 参数绑定
  93. * @return integer
  94. */
  95. public function execute($str,$bind=array()) {
  96. $this->initConnect(true);
  97. if ( !$this->_linkID ) return false;
  98. //释放前次的查询结果
  99. if ( $this->queryID ) $this->free();
  100. N('db_write',1);
  101. // 记录开始执行时间
  102. G('queryStartTime');
  103. $str = str_replace(array_keys($bind),'?',$str);
  104. $bind = array_values($bind);
  105. $this->queryStr = $str;
  106. $this->queryID= sqlsrv_query($this->_linkID,$str,$bind);
  107. $this->debug();
  108. if ( false === $this->queryID ) {
  109. $this->error();
  110. return false;
  111. } else {
  112. $this->numRows = sqlsrv_rows_affected($this->queryID);
  113. $this->lastInsID = $this->mssql_insert_id();
  114. return $this->numRows;
  115. }
  116. }
  117. /**
  118. * 用于获取最后插入的ID
  119. * @access public
  120. * @return integer
  121. */
  122. public function mssql_insert_id() {
  123. $query = "SELECT @@IDENTITY as last_insert_id";
  124. $result = sqlsrv_query($this->_linkID,$query);
  125. list($last_insert_id) = sqlsrv_fetch_array($result);
  126. sqlsrv_free_stmt($result);
  127. return $last_insert_id;
  128. }
  129. /**
  130. * 启动事务
  131. * @access public
  132. * @return void
  133. */
  134. public function startTrans() {
  135. $this->initConnect(true);
  136. if ( !$this->_linkID ) return false;
  137. //数据rollback 支持
  138. if ($this->transTimes == 0) {
  139. sqlsrv_begin_transaction($this->_linkID);
  140. }
  141. $this->transTimes++;
  142. return ;
  143. }
  144. /**
  145. * 用于非自动提交状态下面的查询提交
  146. * @access public
  147. * @return boolen
  148. */
  149. public function commit() {
  150. if ($this->transTimes > 0) {
  151. $result = sqlsrv_commit($this->_linkID);
  152. $this->transTimes = 0;
  153. if(!$result){
  154. $this->error();
  155. return false;
  156. }
  157. }
  158. return true;
  159. }
  160. /**
  161. * 事务回滚
  162. * @access public
  163. * @return boolen
  164. */
  165. public function rollback() {
  166. if ($this->transTimes > 0) {
  167. $result = sqlsrv_rollback($this->_linkID);
  168. $this->transTimes = 0;
  169. if(!$result){
  170. $this->error();
  171. return false;
  172. }
  173. }
  174. return true;
  175. }
  176. /**
  177. * 获得所有的查询数据
  178. * @access private
  179. * @return array
  180. */
  181. private function getAll() {
  182. //返回数据集
  183. $result = array();
  184. if($this->numRows >0) {
  185. while($row = sqlsrv_fetch_array($this->queryID,SQLSRV_FETCH_ASSOC))
  186. $result[] = $row;
  187. }
  188. return $result;
  189. }
  190. /**
  191. * 取得数据表的字段信息
  192. * @access public
  193. * @return array
  194. */
  195. public function getFields($tableName) {
  196. $result = $this->query("
  197. SELECT column_name,data_type,column_default,is_nullable
  198. FROM information_schema.tables AS t
  199. JOIN information_schema.columns AS c
  200. ON t.table_catalog = c.table_catalog
  201. AND t.table_schema = c.table_schema
  202. AND t.table_name = c.table_name
  203. WHERE t.table_name = '{$tableName}'");
  204. $pk = $this->query("SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='{$tableName}'");
  205. $info = array();
  206. if($result) {
  207. foreach ($result as $key => $val) {
  208. $info[$val['column_name']] = array(
  209. 'name' => $val['column_name'],
  210. 'type' => $val['data_type'],
  211. 'notnull' => (bool) ($val['is_nullable'] === ''), // not null is empty, null is yes
  212. 'default' => $val['column_default'],
  213. 'primary' => $val['column_name'] == $pk[0]['COLUMN_NAME'],
  214. 'autoinc' => false,
  215. );
  216. }
  217. }
  218. return $info;
  219. }
  220. /**
  221. * 取得数据表的字段信息
  222. * @access public
  223. * @return array
  224. */
  225. public function getTables($dbName='') {
  226. $result = $this->query("SELECT TABLE_NAME
  227. FROM INFORMATION_SCHEMA.TABLES
  228. WHERE TABLE_TYPE = 'BASE TABLE'
  229. ");
  230. $info = array();
  231. foreach ($result as $key => $val) {
  232. $info[$key] = current($val);
  233. }
  234. return $info;
  235. }
  236. /**
  237. * order分析
  238. * @access protected
  239. * @param mixed $order
  240. * @return string
  241. */
  242. protected function parseOrder($order) {
  243. return !empty($order)? ' ORDER BY '.$order:' ORDER BY rand()';
  244. }
  245. /**
  246. * 字段名分析
  247. * @access protected
  248. * @param string $key
  249. * @return string
  250. */
  251. protected function parseKey(&$key) {
  252. $key = trim($key);
  253. if(!preg_match('/[,\'\"\*\(\)\[.\s]/',$key)) {
  254. $key = '['.$key.']';
  255. }
  256. return $key;
  257. }
  258. /**
  259. * limit
  260. * @access public
  261. * @param mixed $limit
  262. * @return string
  263. */
  264. public function parseLimit($limit) {
  265. if(empty($limit)) return '';
  266. $limit = explode(',',$limit);
  267. if(count($limit)>1)
  268. $limitStr = '(T1.ROW_NUMBER BETWEEN '.$limit[0].' + 1 AND '.$limit[0].' + '.$limit[1].')';
  269. else
  270. $limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND '.$limit[0].")";
  271. return 'WHERE '.$limitStr;
  272. }
  273. /**
  274. * 更新记录
  275. * @access public
  276. * @param mixed $data 数据
  277. * @param array $options 表达式
  278. * @return false | integer
  279. */
  280. public function update($data,$options) {
  281. $this->model = $options['model'];
  282. $sql = 'UPDATE '
  283. .$this->parseTable($options['table'])
  284. .$this->parseSet($data)
  285. .$this->parseWhere(!empty($options['where'])?$options['where']:'')
  286. .$this->parseLock(isset($options['lock'])?$options['lock']:false)
  287. .$this->parseComment(!empty($options['comment'])?$options['comment']:'');
  288. return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:array()));
  289. }
  290. /**
  291. * 删除记录
  292. * @access public
  293. * @param array $options 表达式
  294. * @return false | integer
  295. */
  296. public function delete($options=array()) {
  297. $this->model = $options['model'];
  298. $sql = 'DELETE FROM '
  299. .$this->parseTable($options['table'])
  300. .$this->parseWhere(!empty($options['where'])?$options['where']:'')
  301. .$this->parseLock(isset($options['lock'])?$options['lock']:false)
  302. .$this->parseComment(!empty($options['comment'])?$options['comment']:'');
  303. return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:array()));
  304. }
  305. /**
  306. * 关闭数据库
  307. * @access public
  308. */
  309. public function close() {
  310. if ($this->_linkID){
  311. sqlsrv_close($this->_linkID);
  312. }
  313. $this->_linkID = null;
  314. }
  315. /**
  316. * 数据库错误信息
  317. * 并显示当前的SQL语句
  318. * @access public
  319. * @return string
  320. */
  321. public function error($result = true) {
  322. $errors = sqlsrv_errors();
  323. $this->error = '';
  324. foreach( $errors as $error ) {
  325. $this->error .= $error['code'].':'.$error['message'];
  326. }
  327. if('' != $this->queryStr){
  328. $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
  329. }
  330. $result? trace($this->error,'','ERR'):throw_exception($this->error);
  331. return $this->error;
  332. }
  333. }