DbIbase.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. * Firebird数据库驱动
  14. * @category Extend
  15. * @package Extend
  16. * @subpackage Driver.Db
  17. * @author 剑雷
  18. */
  19. class DbIbase extends Db{
  20. protected $selectSql = 'SELECT %LIMIT% %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%';
  21. /**
  22. * 架构函数 读取数据库配置信息
  23. * @access public
  24. * @param array $config 数据库配置数组
  25. */
  26. public function __construct($config='') {
  27. if ( !extension_loaded('interbase') ) {
  28. throw_exception(L('_NOT_SUPPERT_').':Interbase or Firebird');
  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. * @throws ThinkExecption
  41. */
  42. public function connect($config='',$linkNum=0) {
  43. if ( !isset($this->linkID[$linkNum]) ) {
  44. if(empty($config)) $config = $this->config;
  45. $pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
  46. $conn = $pconnect ? 'ibase_pconnect':'ibase_connect';
  47. // 处理不带端口号的socket连接情况
  48. $host = $config['hostname'].($config['hostport']?"/{$config['hostport']}":'');
  49. $this->linkID[$linkNum] = $conn($host.':'.$config['database'], $config['username'], $config['password'],C('DB_CHARSET'),0,3);
  50. if ( !$this->linkID[$linkNum]) {
  51. throw_exception(ibase_errmsg());
  52. }
  53. // 标记连接成功
  54. $this->connected = true;
  55. // 注销数据库连接配置信息
  56. if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
  57. }
  58. return $this->linkID[$linkNum];
  59. }
  60. /**
  61. * 释放查询结果
  62. * @access public
  63. */
  64. public function free() {
  65. ibase_free_result($this->queryID);
  66. $this->queryID = null;
  67. }
  68. /**
  69. * 执行查询 返回数据集
  70. * @access public
  71. * @param string $str sql指令
  72. * @return mixed
  73. */
  74. public function query($str) {
  75. $this->initConnect(false);
  76. if ( !$this->_linkID ) return false;
  77. $this->queryStr = $str;
  78. //释放前次的查询结果
  79. if ( $this->queryID ) $this->free();
  80. N('db_query',1);
  81. // 记录开始执行时间
  82. G('queryStartTime');
  83. $this->queryID = ibase_query($this->_linkID, $str);
  84. $this->debug();
  85. if ( false === $this->queryID ) {
  86. $this->error();
  87. return false;
  88. } else {
  89. return $this->getAll();
  90. }
  91. }
  92. /**
  93. * 执行语句
  94. * @access public
  95. * @param string $str sql指令
  96. * @return integer
  97. */
  98. public function execute($str) {
  99. $this->initConnect(true);
  100. if ( !$this->_linkID ) return false;
  101. $this->queryStr = $str;
  102. //释放前次的查询结果
  103. if ( $this->queryID ) $this->free();
  104. N('db_write',1);
  105. // 记录开始执行时间
  106. G('queryStartTime');
  107. $result = ibase_query($this->_linkID, $str) ;
  108. $this->debug();
  109. if ( false === $result) {
  110. $this->error();
  111. return false;
  112. } else {
  113. $this->numRows = ibase_affected_rows($this->_linkID);
  114. $this->lastInsID =0;
  115. return $this->numRows;
  116. }
  117. }
  118. public function startTrans() {
  119. $this->initConnect(true);
  120. if ( !$this->_linkID ) return false;
  121. //数据rollback 支持
  122. if ($this->transTimes == 0) {
  123. ibase_trans( IBASE_DEFAULT, $this->_linkID);
  124. }
  125. $this->transTimes++;
  126. return ;
  127. }
  128. /**
  129. * 用于非自动提交状态下面的查询提交
  130. * @access public
  131. * @return boolen
  132. */
  133. public function commit() {
  134. if ($this->transTimes > 0) {
  135. $result = ibase_commit($this->_linkID);
  136. $this->transTimes = 0;
  137. if(!$result){
  138. $this->error();
  139. return false;
  140. }
  141. }
  142. return true;
  143. }
  144. /**
  145. * 事务回滚
  146. * @access public
  147. * @return boolen
  148. */
  149. public function rollback() {
  150. if ($this->transTimes > 0) {
  151. $result =ibase_rollback($this->_linkID);
  152. $this->transTimes = 0;
  153. if(!$result){
  154. $this->error();
  155. return false;
  156. }
  157. }
  158. return true;
  159. }
  160. /**
  161. * BLOB字段解密函数 Firebird特有
  162. * @access public
  163. * @param $blob 待解密的BLOB
  164. * @return 二进制数据
  165. */
  166. public function BlobDecode($blob) {
  167. $maxblobsize = 262144;
  168. $blob_data = ibase_blob_info($this->_linkID, $blob );
  169. $blobid = ibase_blob_open($this->_linkID, $blob );
  170. if( $blob_data[0] > $maxblobsize ) {
  171. $realblob = ibase_blob_get($blobid, $maxblobsize);
  172. while($string = ibase_blob_get($blobid, 8192)){
  173. $realblob .= $string;
  174. }
  175. } else {
  176. $realblob = ibase_blob_get($blobid, $blob_data[0]);
  177. }
  178. ibase_blob_close( $blobid );
  179. return( $realblob );
  180. }
  181. /**
  182. * 获得所有的查询数据
  183. * @access private
  184. * @return array
  185. */
  186. private function getAll() {
  187. //返回数据集
  188. $result = array();
  189. while ( $row = ibase_fetch_assoc($this->queryID)) {
  190. $result[] = $row;
  191. }
  192. //剑雷 2007.12.30 自动解密BLOB字段
  193. //取BLOB字段清单
  194. $bloblist = array();
  195. $fieldCount = ibase_num_fields($this->queryID);
  196. for ($i = 0; $i < $fieldCount; $i++) {
  197. $col_info = ibase_field_info($this->queryID, $i);
  198. if ($col_info['type']=='BLOB') {
  199. $bloblist[]=trim($col_info['name']);
  200. }
  201. }
  202. //如果有BLOB字段,就进行解密处理
  203. if (!empty($bloblist)) {
  204. $i=0;
  205. foreach ($result as $row) {
  206. foreach($bloblist as $field) {
  207. if (!empty($row[$field])) $result[$i][$field]=$this->BlobDecode($row[$field]);
  208. }
  209. $i++;
  210. }
  211. }
  212. return $result;
  213. }
  214. /**
  215. * 取得数据表的字段信息
  216. * @access public
  217. */
  218. public function getFields($tableName) {
  219. $result = $this->query('SELECT RDB$FIELD_NAME AS FIELD, RDB$DEFAULT_VALUE AS DEFAULT1, RDB$NULL_FLAG AS NULL1 FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME=UPPER(\''.$tableName.'\') ORDER By RDB$FIELD_POSITION');
  220. $info = array();
  221. if($result) {
  222. foreach ($result as $key => $val) {
  223. $info[trim($val['FIELD'])] = array(
  224. 'name' => trim($val['FIELD']),
  225. 'type' => '',
  226. 'notnull' => (bool) ($val['NULL1'] ==1), // 1表示不为Null
  227. 'default' => $val['DEFAULT1'],
  228. 'primary' => false,
  229. 'autoinc' => false,
  230. );
  231. }
  232. }
  233. //剑雷 取表字段类型
  234. $sql='select first 1 * from '. $tableName;
  235. $rs_temp = ibase_query ($this->_linkID, $sql);
  236. $fieldCount = ibase_num_fields($rs_temp);
  237. for ($i = 0; $i < $fieldCount; $i++)
  238. {
  239. $col_info = ibase_field_info($rs_temp, $i);
  240. $info[trim($col_info['name'])]['type']=$col_info['type'];
  241. }
  242. ibase_free_result ($rs_temp);
  243. //剑雷 取表的主键
  244. $sql='select b.rdb$field_name as FIELD_NAME from rdb$relation_constraints a join rdb$index_segments b
  245. on a.rdb$index_name=b.rdb$index_name
  246. where a.rdb$constraint_type=\'PRIMARY KEY\' and a.rdb$relation_name=UPPER(\''.$tableName.'\')';
  247. $rs_temp = ibase_query ($this->_linkID, $sql);
  248. while ($row=ibase_fetch_object($rs_temp)) {
  249. $info[trim($row->FIELD_NAME)]['primary']=True;
  250. }
  251. ibase_free_result ($rs_temp);
  252. return $info;
  253. }
  254. /**
  255. * 取得数据库的表信息
  256. * @access public
  257. */
  258. public function getTables($dbName='') {
  259. $sql='SELECT DISTINCT RDB$RELATION_NAME FROM RDB$RELATION_FIELDS WHERE RDB$SYSTEM_FLAG=0';
  260. $result = $this->query($sql);
  261. $info = array();
  262. foreach ($result as $key => $val) {
  263. $info[$key] = trim(current($val));
  264. }
  265. return $info;
  266. }
  267. /**
  268. * 关闭数据库
  269. * @access public
  270. */
  271. public function close() {
  272. if ($this->_linkID){
  273. ibase_close($this->_linkID);
  274. }
  275. $this->_linkID = null;
  276. }
  277. /**
  278. * 数据库错误信息
  279. * 并显示当前的SQL语句
  280. * @access public
  281. * @return string
  282. */
  283. public function error() {
  284. $this->error = ibase_errcode().':'.ibase_errmsg();
  285. if('' != $this->queryStr){
  286. $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
  287. }
  288. trace($this->error,'','ERR');
  289. return $this->error;
  290. }
  291. /**
  292. * SQL指令安全过滤
  293. * @access public
  294. * @param string $str SQL指令
  295. * @return string
  296. */
  297. public function escapeString($str) {
  298. return str_replace("'", "''", $str);
  299. }
  300. /**
  301. * limit
  302. * @access public
  303. * @param $limit limit表达式
  304. * @return string
  305. */
  306. public function parseLimit($limit) {
  307. $limitStr = '';
  308. if(!empty($limit)) {
  309. $limit = explode(',',$limit);
  310. if(count($limit)>1) {
  311. $limitStr = ' FIRST '.($limit[1]-$limit[0]).' SKIP '.$limit[0].' ';
  312. }else{
  313. $limitStr = ' FIRST '.$limit[0].' ';
  314. }
  315. }
  316. return $limitStr;
  317. }
  318. }