DbOci.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. namespace Mall\Framework\Db;
  3. class DbOci
  4. {
  5. static $queries = 0;
  6. public $options = array();
  7. public $master = array();
  8. public $slaves = array();
  9. public $slave = array();
  10. public $slave_key;
  11. public $sql;
  12. public $dbname;
  13. public $prefix;
  14. public $charset;
  15. protected $_error;
  16. protected $_cmstop_charset;
  17. protected $_transaction_started;
  18. protected $_table;
  19. protected $_mode;
  20. private $dbh;
  21. private $dbh_master;
  22. private $dbh_slave;
  23. function __construct($master = array(), $slaves = array())
  24. {
  25. $this->master = $master;
  26. $this->options = &$this->master;
  27. if ($slaves) $this->slaves = $slaves;
  28. // 设置全局字符集
  29. putenv('NLS_LANG=AMERICAN_AMERICA.UTF8');
  30. // 设置会话期间的日期格式
  31. $this->exec("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
  32. // 统一编码格式
  33. $this->_cmstop_charset = $this->_normorlize_charset(config('config', 'charset'));
  34. }
  35. function __destruct()
  36. {
  37. if ($this->dbh) {
  38. oci_close($this->dbh);
  39. }
  40. }
  41. function beginTransaction()
  42. {
  43. if (!$this->_transaction_started) {
  44. $this->_mode = OCI_DEFAULT;
  45. $this->_transaction_started = true;
  46. return true;
  47. }
  48. $this->_error = 'Transaction had already begin';
  49. return false;
  50. }
  51. function commit()
  52. {
  53. if (!$this->dbh()) return false;
  54. if ($this->_transaction_started) {
  55. $result = oci_commit($this->dbh);
  56. $this->_transaction_started = false;
  57. return $result;
  58. }
  59. $this->_error = 'No activied transaction';
  60. return false;
  61. }
  62. function rollBack()
  63. {
  64. if (!$this->dbh()) return false;
  65. if ($this->_transaction_started) {
  66. $result = oci_rollback($this->dbh);
  67. $this->_transaction_started = false;
  68. return $result;
  69. }
  70. $this->_error = 'No activied transaction';
  71. return false;
  72. }
  73. function lastInsertId($table = null, $primary_key = null)
  74. {
  75. if ($table !== null) {
  76. $this->_table = $table;
  77. }
  78. if (!$this->_table) {
  79. return 0;
  80. }
  81. $sequence_name = $this->_table;
  82. if ($primary_key) {
  83. $sequence_name .= "_{$primary_key}";
  84. }
  85. $sequence_name .= '_seq';
  86. return $this->lastSequenceId($sequence_name);
  87. }
  88. function lastSequenceId($sequence_name)
  89. {
  90. if (!$this->dbh()) return false;
  91. $sql = 'SELECT ' . $sequence_name . '.CURRVAL FROM dual';
  92. return $this->get($sql);
  93. }
  94. function nextSequenceId($sequence_name)
  95. {
  96. if (!$this->dbh()) return false;
  97. $sql = 'SELECT ' . $sequence_name . '.NEXTVAL FROM dual';
  98. return $this->get($sql);
  99. }
  100. static function get_instance($master = array(), $slaves = array())
  101. {
  102. static $instance;
  103. $key = implode('', $master);
  104. if (!isset($instance[$key])) {
  105. $instance[$key] = new DbOci($master, $slaves);
  106. }
  107. return $instance[$key];
  108. }
  109. function connect($options = array())
  110. {
  111. $host = value($options, 'host');
  112. $port = value($options, 'port');
  113. $dbname = value($options, 'dbname');
  114. $prefix = value($options, 'prefix', '');
  115. $charset = value($options, 'charset');
  116. $username = value($options, 'username');
  117. $password = value($options, 'password');
  118. $pconnect = value($options, 'pconnect');
  119. $handler = $pconnect ? 'oci_pconnect' : 'oci_connect';
  120. $server = '//' . $host . ($port ? (':' . $port) : '') . '/' . $dbname;
  121. if (!function_exists($handler)) {
  122. throw new \Exception("OCI extension not enabled");
  123. }
  124. if (!($dbh = $handler($username, $password, $server))) {
  125. return false;
  126. }
  127. $this->dbname = $dbname;
  128. $this->prefix = $prefix;
  129. // 统一编码格式
  130. $this->charset = $this->_normorlize_charset($charset);
  131. return $dbh;
  132. }
  133. private function connect_slave()
  134. {
  135. $this->slave_key = array_rand($this->slaves);
  136. $this->slave = $this->slaves[$this->slave_key];
  137. $this->dbh_slave = $this->connect($this->slave);
  138. if (!$this->dbh_slave && count($this->slaves) > 1) {
  139. unset($this->slaves[$this->slave_key]);
  140. return $this->connect_slave();
  141. }
  142. return $this->dbh_slave;
  143. }
  144. function exec($statement, $multiple = false)
  145. {
  146. if (!$this->dbh($statement)) return false;
  147. if (preg_match('/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i', $this->sql, $matches)) {
  148. $this->_table = $matches[2];
  149. }
  150. $this->_mode = OCI_COMMIT_ON_SUCCESS;
  151. $stmt = oci_parse($this->dbh, $this->_prepare_sql($this->sql));
  152. if (false === oci_execute($stmt, $this->_mode)) {
  153. return false;
  154. }
  155. if ($multiple) {
  156. $result = array();
  157. oci_fetch_all($stmt, $result, 0, -1, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC);
  158. } else {
  159. $result = oci_fetch_assoc($stmt);
  160. if (is_array($result)) {
  161. $result = array_shift(array_values($result));
  162. }
  163. }
  164. oci_free_statement($stmt);
  165. /*if ($this->charset != $this->_cmstop_charset)
  166. {
  167. $result = str_charset($this->charset, $this->_cmstop_charset, $result);
  168. }*/
  169. return $result;
  170. }
  171. function query($statement)
  172. {
  173. return $this->exec($statement);
  174. }
  175. function get($sql)
  176. {
  177. return $this->exec($sql);
  178. }
  179. function select($sql)
  180. {
  181. return $this->exec($sql, true);
  182. }
  183. function insert($sql)
  184. {
  185. return $this->exec($sql);
  186. }
  187. function update($sql)
  188. {
  189. return $this->exec($sql);
  190. }
  191. function replace($sql)
  192. {
  193. return $this->update($sql);
  194. }
  195. function delete($sql)
  196. {
  197. return $this->exec($sql);
  198. }
  199. public function limit($sql, $limit = 0, $offset = 0)
  200. {
  201. $limit_sql = "SELECT c2.*
  202. FROM (
  203. SELECT c1.*, ROWNUM AS \"cmstop_db_rownum\"
  204. FROM (
  205. {$sql}
  206. ) c1
  207. ) c2
  208. WHERE c2.\"cmstop_db_rownum\" BETWEEN " . ($offset + 1) . " AND " . ($offset + $limit);
  209. return $this->select($limit_sql);
  210. }
  211. public function page($sql, $page = 1, $size = 20)
  212. {
  213. $page = isset($page) ? max(intval($page), 1) : 1;
  214. $size = max(intval($size), 1);
  215. $offset = ($page - 1) * $size;
  216. return $this->limit($sql, $size, $offset);
  217. }
  218. function select_db($dbname)
  219. {
  220. return true;
  221. }
  222. function list_fields($table)
  223. {
  224. static $result = array();
  225. if (!is_array($result[$table])) {
  226. if ($fields = $this->select("SELECT a.column_name,
  227. data_type, decode(nullable, 'Y', 0,1) notnull,
  228. data_default, decode(a.column_name, b.column_name, 1, 0) pk
  229. FROM user_tab_columns a, (
  230. SELECT column_name
  231. FROM user_constraints c,user_cons_columns col
  232. WHERE c.constraint_name = col.constraint_name
  233. AND c.constraint_type='P'
  234. AND c.table_name = '" . strtoupper($table) . "'
  235. ) b
  236. WHERE table_name = '" . strtoupper($table) . "'
  237. AND a.column_name = b.column_name(+)")
  238. ) {
  239. foreach ($fields as $field) {
  240. $result[$table][$field['COLUMN_NAME']] = array(
  241. 'Field' => $field['COLUMN_NAME'],
  242. 'Type' => $field['DATA_TYPE'],
  243. 'Null' => $field['NOTNULL'] === 0 ? 'NO' : 'YES',
  244. 'Key' => '',
  245. 'Default' => $field['DATA_DEFAULT'],
  246. 'Extra' => ''
  247. );
  248. }
  249. }
  250. }
  251. return $result[$table];
  252. }
  253. function list_tables()
  254. {
  255. static $result;
  256. if (!is_array($result)) {
  257. if ($tables = $this->select("SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME ASC")) {
  258. foreach ($tables as $table) {
  259. $result[] = $table['TABLE_NAME'];
  260. }
  261. }
  262. }
  263. return $result;
  264. }
  265. function list_dbs()
  266. {
  267. return array(
  268. $this->master['dbname']
  269. );
  270. }
  271. function get_primary($table)
  272. {
  273. static $result = array();
  274. if (!array_key_exists($table, $result)) {
  275. $primarys = array();
  276. foreach ($this->exec("SELECT *
  277. FROM ALL_CONS_COLUMNS A
  278. JOIN ALL_CONSTRAINTS C
  279. ON A.CONSTRAINT_NAME = C.CONSTRAINT_NAME
  280. WHERE C.TABLE_NAME = '$table'
  281. AND C.CONSTRAINT_TYPE = 'P'", true) as $primary) {
  282. $primarys[] = $primary['COLUMN_NAME'];
  283. }
  284. $result[$table] = implode(',', $primarys);
  285. }
  286. return $result[$table];
  287. }
  288. function field_type($table, $field)
  289. {
  290. return false;
  291. }
  292. function version()
  293. {
  294. if (!$this->dbh()) return false;
  295. return oci_server_version($this->dbh);
  296. }
  297. function prefix()
  298. {
  299. return $this->master['prefix'];
  300. }
  301. function error()
  302. {
  303. if (is_null($this->_error)) {
  304. $this->_error = oci_error();
  305. if ($this->_error && $this->charset != $this->_cmstop_charset) {
  306. $this->_error = str_charset($this->charset, $this->_cmstop_charset, $this->_error);
  307. }
  308. }
  309. return $this->_error;
  310. }
  311. protected function _prepare_sql($sql)
  312. {
  313. $this->sql = str_replace('#table_', $this->master['prefix'], trim($sql));
  314. $this->sql = preg_replace('/(`(\w*)`)/Usim', '"$2"', $this->sql);
  315. return $this->sql;
  316. }
  317. protected function _normorlize_charset($charset)
  318. {
  319. return strtolower(str_replace('-', '', $charset));
  320. }
  321. private function dbh($sql = null)
  322. {
  323. if (is_null($sql)) {
  324. $this->sql = null;
  325. if (is_null($this->dbh)) {
  326. if (is_null($this->dbh_master)) $this->dbh_master = $this->connect($this->master);
  327. $this->dbh = $this->dbh_master;
  328. }
  329. return $this->dbh;
  330. }
  331. self::$queries++;
  332. $this->sql = str_replace('#table_', $this->master['prefix'], trim($sql));
  333. if ($this->slaves && is_null($this->dbh_master) && stripos($this->sql, 'select') === 0) {
  334. if (is_null($this->dbh_slave)) $this->dbh_slave = $this->connect_slave();
  335. $this->dbh = $this->dbh_slave;
  336. } else {
  337. if (is_null($this->dbh_master)) $this->dbh_master = $this->connect($this->master);
  338. $this->dbh = $this->dbh_master;
  339. }
  340. return $this->dbh;
  341. }
  342. }