DbMssql.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. * MSsql数据库驱动 要求sqlserver2005
  14. * @category Extend
  15. * @package Extend
  16. * @subpackage Driver.Db
  17. * @author liu21st <liu21st@gmail.com>
  18. */
  19. class DbMssql 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('mssql_connect') ) {
  28. throw_exception(L('_NOT_SUPPERT_').':mssql');
  29. }
  30. if(!empty($config)) {
  31. $this->config = $config;
  32. if(empty($this->config['params'])) {
  33. $this->config['params'] = array();
  34. }
  35. }
  36. }
  37. /**
  38. * 连接数据库方法
  39. * @access public
  40. */
  41. public function connect($config='',$linkNum=0) {
  42. if ( !isset($this->linkID[$linkNum]) ) {
  43. if(empty($config)) $config = $this->config;
  44. $pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
  45. $conn = $pconnect ? 'mssql_pconnect':'mssql_connect';
  46. // 处理不带端口号的socket连接情况
  47. $sepr = IS_WIN ? ',' : ':';
  48. $host = $config['hostname'].($config['hostport']?$sepr."{$config['hostport']}":'');
  49. $this->linkID[$linkNum] = $conn( $host, $config['username'], $config['password']);
  50. if ( !$this->linkID[$linkNum] ) throw_exception("Couldn't connect to SQL Server on $host");
  51. if ( !empty($config['database']) && !mssql_select_db($config['database'], $this->linkID[$linkNum]) ) {
  52. throw_exception("Couldn't open database '".$config['database']);
  53. }
  54. // 标记连接成功
  55. $this->connected = true;
  56. //注销数据库安全信息
  57. if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
  58. }
  59. return $this->linkID[$linkNum];
  60. }
  61. /**
  62. * 释放查询结果
  63. * @access public
  64. */
  65. public function free() {
  66. mssql_free_result($this->queryID);
  67. $this->queryID = null;
  68. }
  69. /**
  70. * 执行查询 返回数据集
  71. * @access public
  72. * @param string $str sql指令
  73. * @return mixed
  74. */
  75. public function query($str) {
  76. $this->initConnect(false);
  77. if ( !$this->_linkID ) return false;
  78. $this->queryStr = $str;
  79. //释放前次的查询结果
  80. if ( $this->queryID ) $this->free();
  81. N('db_query',1);
  82. // 记录开始执行时间
  83. G('queryStartTime');
  84. $this->queryID = mssql_query($str, $this->_linkID);
  85. $this->debug();
  86. if ( false === $this->queryID ) {
  87. $this->error();
  88. return false;
  89. } else {
  90. $this->numRows = mssql_num_rows($this->queryID);
  91. return $this->getAll();
  92. }
  93. }
  94. /**
  95. * 执行语句
  96. * @access public
  97. * @param string $str sql指令
  98. * @return integer
  99. */
  100. public function execute($str) {
  101. $this->initConnect(true);
  102. if ( !$this->_linkID ) return false;
  103. $this->queryStr = $str;
  104. //释放前次的查询结果
  105. if ( $this->queryID ) $this->free();
  106. N('db_write',1);
  107. // 记录开始执行时间
  108. G('queryStartTime');
  109. $result = mssql_query($str, $this->_linkID);
  110. $this->debug();
  111. if ( false === $result ) {
  112. $this->error();
  113. return false;
  114. } else {
  115. $this->numRows = mssql_rows_affected($this->_linkID);
  116. $this->lastInsID = $this->mssql_insert_id();
  117. return $this->numRows;
  118. }
  119. }
  120. /**
  121. * 用于获取最后插入的ID
  122. * @access public
  123. * @return integer
  124. */
  125. public function mssql_insert_id() {
  126. $query = "SELECT @@IDENTITY as last_insert_id";
  127. $result = mssql_query($query, $this->_linkID);
  128. list($last_insert_id) = mssql_fetch_row($result);
  129. mssql_free_result($result);
  130. return $last_insert_id;
  131. }
  132. /**
  133. * 启动事务
  134. * @access public
  135. * @return void
  136. */
  137. public function startTrans() {
  138. $this->initConnect(true);
  139. if ( !$this->_linkID ) return false;
  140. //数据rollback 支持
  141. if ($this->transTimes == 0) {
  142. mssql_query('BEGIN TRAN', $this->_linkID);
  143. }
  144. $this->transTimes++;
  145. return ;
  146. }
  147. /**
  148. * 用于非自动提交状态下面的查询提交
  149. * @access public
  150. * @return boolen
  151. */
  152. public function commit() {
  153. if ($this->transTimes > 0) {
  154. $result = mssql_query('COMMIT TRAN', $this->_linkID);
  155. $this->transTimes = 0;
  156. if(!$result){
  157. $this->error();
  158. return false;
  159. }
  160. }
  161. return true;
  162. }
  163. /**
  164. * 事务回滚
  165. * @access public
  166. * @return boolen
  167. */
  168. public function rollback() {
  169. if ($this->transTimes > 0) {
  170. $result = mssql_query('ROLLBACK TRAN', $this->_linkID);
  171. $this->transTimes = 0;
  172. if(!$result){
  173. $this->error();
  174. return false;
  175. }
  176. }
  177. return true;
  178. }
  179. /**
  180. * 获得所有的查询数据
  181. * @access private
  182. * @return array
  183. */
  184. private function getAll() {
  185. //返回数据集
  186. $result = array();
  187. if($this->numRows >0) {
  188. while($row = mssql_fetch_assoc($this->queryID))
  189. $result[] = $row;
  190. }
  191. return $result;
  192. }
  193. /**
  194. * 取得数据表的字段信息
  195. * @access public
  196. * @return array
  197. */
  198. public function getFields($tableName) {
  199. $result = $this->query("SELECT column_name, data_type, column_default, is_nullable
  200. FROM information_schema.tables AS t
  201. JOIN information_schema.columns AS c
  202. ON t.table_catalog = c.table_catalog
  203. AND t.table_schema = c.table_schema
  204. AND t.table_name = c.table_name
  205. WHERE t.table_name = '$tableName'");
  206. $info = array();
  207. if($result) {
  208. foreach ($result as $key => $val) {
  209. $info[$val['column_name']] = array(
  210. 'name' => $val['column_name'],
  211. 'type' => $val['data_type'],
  212. 'notnull' => (bool) ($val['is_nullable'] === ''), // not null is empty, null is yes
  213. 'default' => $val['column_default'],
  214. 'primary' => false,
  215. 'autoinc' => false,
  216. );
  217. }
  218. }
  219. return $info;
  220. }
  221. /**
  222. * 取得数据表的字段信息
  223. * @access public
  224. * @return array
  225. */
  226. public function getTables($dbName='') {
  227. $result = $this->query("SELECT TABLE_NAME
  228. FROM INFORMATION_SCHEMA.TABLES
  229. WHERE TABLE_TYPE = 'BASE TABLE'
  230. ");
  231. $info = array();
  232. foreach ($result as $key => $val) {
  233. $info[$key] = current($val);
  234. }
  235. return $info;
  236. }
  237. /**
  238. * order分析
  239. * @access protected
  240. * @param mixed $order
  241. * @return string
  242. */
  243. protected function parseOrder($order) {
  244. return !empty($order)? ' ORDER BY '.$order:' ORDER BY rand()';
  245. }
  246. /**
  247. * limit
  248. * @access public
  249. * @return string
  250. */
  251. public function parseLimit($limit) {
  252. if(empty($limit)) return '';
  253. $limit = explode(',',$limit);
  254. if(count($limit)>1)
  255. $limitStr = '(T1.ROW_NUMBER BETWEEN '.$limit[0].' + 1 AND '.$limit[0].' + '.$limit[1].')';
  256. else
  257. $limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND '.$limit[0].")";
  258. return 'WHERE '.$limitStr;
  259. }
  260. /**
  261. * 更新记录
  262. * @access public
  263. * @param mixed $data 数据
  264. * @param array $options 表达式
  265. * @return false | integer
  266. */
  267. public function update($data,$options) {
  268. $this->model = $options['model'];
  269. $sql = 'UPDATE '
  270. .$this->parseTable($options['table'])
  271. .$this->parseSet($data)
  272. .$this->parseWhere(!empty($options['where'])?$options['where']:'')
  273. .$this->parseLock(isset($options['lock'])?$options['lock']:false)
  274. .$this->parseComment(!empty($options['comment'])?$options['comment']:'');
  275. return $this->execute($sql);
  276. }
  277. /**
  278. * 删除记录
  279. * @access public
  280. * @param array $options 表达式
  281. * @return false | integer
  282. */
  283. public function delete($options=array()) {
  284. $this->model = $options['model'];
  285. $sql = 'DELETE FROM '
  286. .$this->parseTable($options['table'])
  287. .$this->parseWhere(!empty($options['where'])?$options['where']:'')
  288. .$this->parseLock(isset($options['lock'])?$options['lock']:false)
  289. .$this->parseComment(!empty($options['comment'])?$options['comment']:'');
  290. return $this->execute($sql);
  291. }
  292. /**
  293. * 关闭数据库
  294. * @access public
  295. */
  296. public function close() {
  297. if ($this->_linkID){
  298. mssql_close($this->_linkID);
  299. }
  300. $this->_linkID = null;
  301. }
  302. /**
  303. * 数据库错误信息
  304. * 并显示当前的SQL语句
  305. * @access public
  306. * @return string
  307. */
  308. public function error() {
  309. $this->error = mssql_get_last_message();
  310. if('' != $this->queryStr){
  311. $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
  312. }
  313. trace($this->error,'','ERR');
  314. return $this->error;
  315. }
  316. }