DbOracle.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. * Oracle数据库驱动
  14. * @category Extend
  15. * @package Extend
  16. * @subpackage Driver.Db
  17. * @author ZhangXuehun <zhangxuehun@sohu.com>
  18. */
  19. class DbOracle extends Db{
  20. private $mode = OCI_COMMIT_ON_SUCCESS;
  21. private $table = '';
  22. protected $selectSql = 'SELECT * FROM (SELECT thinkphp.*, rownum AS numrow FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%) thinkphp ) %LIMIT%%COMMENT%';
  23. /**
  24. * 架构函数 读取数据库配置信息
  25. * @access public
  26. * @param array $config 数据库配置数组
  27. */
  28. public function __construct($config=''){
  29. putenv("NLS_LANG=AMERICAN_AMERICA.UTF8");
  30. if ( !extension_loaded('oci8') ) {
  31. throw_exception(L('_NOT_SUPPERT_').'oracle');
  32. }
  33. if(!empty($config)) {
  34. $this->config = $config;
  35. if(empty($this->config['params'])) {
  36. $this->config['params'] = array();
  37. }
  38. }
  39. }
  40. /**
  41. * 连接数据库方法
  42. * @access public
  43. */
  44. public function connect($config='',$linkNum=0) {
  45. if ( !isset($this->linkID[$linkNum]) ) {
  46. if(empty($config)) $config = $this->config;
  47. $pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
  48. $conn = $pconnect ? 'oci_pconnect':'oci_new_connect';
  49. $this->linkID[$linkNum] = $conn($config['username'], $config['password'],$config['database']);//modify by wyfeng at 2008.12.19
  50. if (!$this->linkID[$linkNum]){
  51. $this->error(false);
  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. oci_free_statement($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. $this->mode = OCI_COMMIT_ON_SUCCESS;
  80. //释放前次的查询结果
  81. if ( $this->queryID ) $this->free();
  82. N('db_query',1);
  83. // 记录开始执行时间
  84. G('queryStartTime');
  85. $this->queryID = oci_parse($this->_linkID,$str);
  86. $this->debug();
  87. if (false === oci_execute($this->queryID, $this->mode)) {
  88. $this->error();
  89. return false;
  90. } else {
  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. $flag = false;
  106. if(preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $this->queryStr, $match)) {
  107. $this->table = C("DB_SEQUENCE_PREFIX") .str_ireplace(C("DB_PREFIX"), "", $match[2]);
  108. $flag = (boolean)$this->query("SELECT * FROM user_sequences WHERE sequence_name='" . strtoupper($this->table) . "'");
  109. }//modify by wyfeng at 2009.08.28
  110. //更改事务模式
  111. $this->mode = OCI_COMMIT_ON_SUCCESS;
  112. //释放前次的查询结果
  113. if ( $this->queryID ) $this->free();
  114. N('db_write',1);
  115. // 记录开始执行时间
  116. G('queryStartTime');
  117. $stmt = oci_parse($this->_linkID,$str);
  118. $this->debug();
  119. if (false === oci_execute($stmt)) {
  120. $this->error();
  121. return false;
  122. } else {
  123. $this->numRows = oci_num_rows($stmt);
  124. $this->lastInsID = $flag?$this->insertLastId():0;//modify by wyfeng at 2009.08.28
  125. return $this->numRows;
  126. }
  127. }
  128. /**
  129. * 启动事务
  130. * @access public
  131. * @return void
  132. */
  133. public function startTrans() {
  134. $this->initConnect(true);
  135. if ( !$this->_linkID ) return false;
  136. //数据rollback 支持
  137. if ($this->transTimes == 0) {
  138. $this->mode = OCI_DEFAULT;
  139. }
  140. $this->transTimes++;
  141. return ;
  142. }
  143. /**
  144. * 用于非自动提交状态下面的查询提交
  145. * @access public
  146. * @return boolen
  147. */
  148. public function commit(){
  149. if ($this->transTimes > 0) {
  150. $result = oci_commit($this->_linkID);
  151. if(!$result){
  152. $this->error();
  153. return false;
  154. }
  155. $this->transTimes = 0;
  156. }
  157. return true;
  158. }
  159. /**
  160. * 事务回滚
  161. * @access public
  162. * @return boolen
  163. */
  164. public function rollback(){
  165. if ($this->transTimes > 0) {
  166. $result = oci_rollback($this->_linkID);
  167. if(!$result){
  168. $this->error();
  169. return false;
  170. }
  171. $this->transTimes = 0;
  172. }
  173. return true;
  174. }
  175. /**
  176. * 获得所有的查询数据
  177. * @access private
  178. * @return array
  179. */
  180. private function getAll() {
  181. //返回数据集
  182. $result = array();
  183. $this->numRows = oci_fetch_all($this->queryID, $result, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  184. //add by wyfeng at 2008-12-23 强制将字段名转换为小写,以配合Model类函数如count等
  185. if(C("DB_CASE_LOWER")) {
  186. foreach($result as $k=>$v) {
  187. $result[$k] = array_change_key_case($result[$k], CASE_LOWER);
  188. }
  189. }
  190. return $result;
  191. }
  192. /**
  193. * 取得数据表的字段信息
  194. * @access public
  195. */
  196. public function getFields($tableName) {
  197. $result = $this->query("select a.column_name,data_type,decode(nullable,'Y',0,1) notnull,data_default,decode(a.column_name,b.column_name,1,0) pk "
  198. ."from user_tab_columns a,(select column_name from user_constraints c,user_cons_columns col "
  199. ."where c.constraint_name=col.constraint_name and c.constraint_type='P'and c.table_name='".strtoupper($tableName)
  200. ."') b where table_name='".strtoupper($tableName)."' and a.column_name=b.column_name(+)");
  201. $info = array();
  202. if($result) {
  203. foreach ($result as $key => $val) {
  204. $info[strtolower($val['column_name'])] = array(
  205. 'name' => strtolower($val['column_name']),
  206. 'type' => strtolower($val['data_type']),
  207. 'notnull' => $val['notnull'],
  208. 'default' => $val['data_default'],
  209. 'primary' => $val['pk'],
  210. 'autoinc' => $val['pk'],
  211. );
  212. }
  213. }
  214. return $info;
  215. }
  216. /**
  217. * 取得数据库的表信息(暂时实现取得用户表信息)
  218. * @access public
  219. */
  220. public function getTables($dbName='') {
  221. $result = $this->query("select table_name from user_tables");
  222. $info = array();
  223. foreach ($result as $key => $val) {
  224. $info[$key] = current($val);
  225. }
  226. return $info;
  227. }
  228. /**
  229. * 关闭数据库
  230. * @access public
  231. */
  232. public function close() {
  233. if($this->_linkID){
  234. oci_close($this->_linkID);
  235. }
  236. $this->_linkID = null;
  237. }
  238. /**
  239. * 数据库错误信息
  240. * 并显示当前的SQL语句
  241. * @access public
  242. * @return string
  243. */
  244. public function error($result = true) {
  245. if($result){
  246. $error = oci_error($this->queryID);
  247. }elseif(!$this->_linkID){
  248. $error = oci_error();
  249. }else{
  250. $error = oci_error($this->_linkID);
  251. }
  252. if('' != $this->queryStr){
  253. $error['message'] .= "\n [ SQL语句 ] : ".$this->queryStr;
  254. }
  255. $result? trace($error['message'],'','ERR'):throw_exception($error['message'],'',$error['code']);
  256. $this->error = $error['message'];
  257. return $this->error;
  258. }
  259. /**
  260. * SQL指令安全过滤
  261. * @access public
  262. * @param string $str SQL指令
  263. * @return string
  264. */
  265. public function escapeString($str) {
  266. return str_ireplace("'", "''", $str);
  267. }
  268. /**
  269. * 获取最后插入id ,仅适用于采用序列+触发器结合生成ID的方式
  270. * 在config.php中指定
  271. 'DB_TRIGGER_PREFIX' => 'tr_',
  272. 'DB_SEQUENCE_PREFIX' => 'ts_',
  273. * eg:表 tb_user
  274. 相对tb_user的序列为:
  275. -- Create sequence
  276. create sequence TS_USER
  277. minvalue 1
  278. maxvalue 999999999999999999999999999
  279. start with 1
  280. increment by 1
  281. nocache;
  282. 相对tb_user,ts_user的触发器为:
  283. create or replace trigger TR_USER
  284. before insert on "TB_USER"
  285. for each row
  286. begin
  287. select "TS_USER".nextval into :NEW.ID from dual;
  288. end;
  289. * @access public
  290. * @return integer
  291. */
  292. public function insertLastId() {
  293. if(empty($this->table)) {
  294. return 0;
  295. }
  296. $sequenceName = $this->table;
  297. $vo = $this->query("SELECT {$sequenceName}.currval currval FROM dual");
  298. return $vo?$vo[0]["currval"]:0;
  299. }
  300. /**
  301. * limit
  302. * @access public
  303. * @return string
  304. */
  305. public function parseLimit($limit) {
  306. $limitStr = '';
  307. if(!empty($limit)) {
  308. $limit = explode(',',$limit);
  309. if(count($limit)>1)
  310. $limitStr = "(numrow>" . $limit[0] . ") AND (numrow<=" . ($limit[0]+$limit[1]) . ")";
  311. else
  312. $limitStr = "(numrow>0 AND numrow<=".$limit[0].")";
  313. }
  314. return $limitStr?' WHERE '.$limitStr:'';
  315. }
  316. }