DbPgsql.class.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. * Pgsql数据库驱动
  14. * @category Extend
  15. * @package Extend
  16. * @subpackage Driver.Db
  17. * @author liu21st <liu21st@gmail.com>
  18. */
  19. class DbPgsql extends Db{
  20. /**
  21. * 架构函数 读取数据库配置信息
  22. * @access public
  23. * @param array $config 数据库配置数组
  24. */
  25. public function __construct($config='') {
  26. if ( !extension_loaded('pgsql') ) {
  27. throw_exception(L('_NOT_SUPPERT_').':pgsql');
  28. }
  29. if(!empty($config)) {
  30. $this->config = $config;
  31. if(empty($this->config['params'])) {
  32. $this->config['params'] = array();
  33. }
  34. }
  35. }
  36. /**
  37. * 连接数据库方法
  38. * @access public
  39. */
  40. public function connect($config='',$linkNum=0) {
  41. if ( !isset($this->linkID[$linkNum]) ) {
  42. if(empty($config)) $config = $this->config;
  43. $pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
  44. $conn = $pconnect ? 'pg_pconnect':'pg_connect';
  45. $this->linkID[$linkNum] = $conn('host='.$config['hostname'].' port='.$config['hostport'].' dbname='.$config['database'].' user='.$config['username'].' password='.$config['password']);
  46. if (0 !== pg_connection_status($this->linkID[$linkNum])){
  47. throw_exception($this->error(false));
  48. }
  49. //设置编码
  50. pg_set_client_encoding($this->linkID[$linkNum], C('DB_CHARSET'));
  51. //$pgInfo = pg_version($this->linkID[$linkNum]);
  52. //$dbVersion = $pgInfo['server'];
  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. pg_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 = pg_query($this->_linkID,$str);
  84. $this->debug();
  85. if ( false === $this->queryID ) {
  86. $this->error();
  87. return false;
  88. } else {
  89. $this->numRows = pg_num_rows($this->queryID);
  90. return $this->getAll();
  91. }
  92. }
  93. /**
  94. * 执行语句
  95. * @access public
  96. * @param string $str sql指令
  97. * @return integer
  98. */
  99. public function execute($str) {
  100. $this->initConnect(true);
  101. if ( !$this->_linkID ) return false;
  102. $this->queryStr = $str;
  103. //释放前次的查询结果
  104. if ( $this->queryID ) $this->free();
  105. N('db_write',1);
  106. // 记录开始执行时间
  107. G('queryStartTime');
  108. $result = pg_query($this->_linkID,$str);
  109. $this->debug();
  110. if ( false === $result ) {
  111. $this->error();
  112. return false;
  113. } else {
  114. $this->numRows = pg_affected_rows($result);
  115. $this->lastInsID = $this->last_insert_id();
  116. return $this->numRows;
  117. }
  118. }
  119. /**
  120. * 用于获取最后插入的ID
  121. * @access public
  122. * @return integer
  123. */
  124. public function last_insert_id() {
  125. $query = "SELECT LASTVAL() AS insert_id";
  126. $result = pg_query($this->_linkID,$query);
  127. list($last_insert_id) = pg_fetch_array($result,null,PGSQL_ASSOC);
  128. pg_free_result($result);
  129. return $last_insert_id;
  130. }
  131. /**
  132. * 启动事务
  133. * @access public
  134. * @return void
  135. */
  136. public function startTrans() {
  137. $this->initConnect(true);
  138. if ( !$this->_linkID ) return false;
  139. //数据rollback 支持
  140. if ($this->transTimes == 0) {
  141. pg_exec($this->_linkID,'begin;');
  142. }
  143. $this->transTimes++;
  144. return ;
  145. }
  146. /**
  147. * 用于非自动提交状态下面的查询提交
  148. * @access public
  149. * @return boolen
  150. */
  151. public function commit() {
  152. if ($this->transTimes > 0) {
  153. $result = pg_exec($this->_linkID,'end;');
  154. if(!$result){
  155. $this->error();
  156. return false;
  157. }
  158. $this->transTimes = 0;
  159. }
  160. return true;
  161. }
  162. /**
  163. * 事务回滚
  164. * @access public
  165. * @return boolen
  166. */
  167. public function rollback() {
  168. if ($this->transTimes > 0) {
  169. $result = pg_exec($this->_linkID,'abort;');
  170. if(!$result){
  171. $this->error();
  172. return false;
  173. }
  174. $this->transTimes = 0;
  175. }
  176. return true;
  177. }
  178. /**
  179. * 获得所有的查询数据
  180. * @access private
  181. * @return array
  182. */
  183. private function getAll() {
  184. //返回数据集
  185. $result = pg_fetch_all($this->queryID);
  186. pg_result_seek($this->queryID,0);
  187. return $result;
  188. }
  189. /**
  190. * 取得数据表的字段信息
  191. * @access public
  192. */
  193. public function getFields($tableName) {
  194. $result = $this->query("select a.attname as \"Field\",
  195. t.typname as \"Type\",
  196. a.attnotnull as \"Null\",
  197. i.indisprimary as \"Key\",
  198. d.adsrc as \"Default\"
  199. from pg_class c
  200. inner join pg_attribute a on a.attrelid = c.oid
  201. inner join pg_type t on a.atttypid = t.oid
  202. left join pg_attrdef d on a.attrelid=d.adrelid and d.adnum=a.attnum
  203. left join pg_index i on a.attnum=ANY(i.indkey) and c.oid = i.indrelid
  204. where (c.relname='{$tableName}' or c.relname = lower('{$tableName}')) AND a.attnum > 0
  205. order by a.attnum asc;");
  206. $info = array();
  207. if($result) {
  208. foreach ($result as $key => $val) {
  209. $info[$val['Field']] = array(
  210. 'name' => $val['Field'],
  211. 'type' => $val['Type'],
  212. 'notnull' => (bool) ($val['Null'] == 't'?1:0), // 't' is 'not null'
  213. 'default' => $val['Default'],
  214. 'primary' => (strtolower($val['Key']) == 't'),
  215. 'autoinc' => (strtolower($val['Default']) == "nextval('{$tableName}_id_seq'::regclass)"),
  216. );
  217. }
  218. }
  219. return $info;
  220. }
  221. /**
  222. * 取得数据库的表信息
  223. * @access public
  224. */
  225. public function getTables($dbName='') {
  226. $result = $this->query("select tablename as Tables_in_test from pg_tables where schemaname ='public'");
  227. $info = array();
  228. foreach ($result as $key => $val) {
  229. $info[$key] = current($val);
  230. }
  231. return $info;
  232. }
  233. /**
  234. * 关闭数据库
  235. * @access public
  236. */
  237. public function close() {
  238. if($this->_linkID){
  239. pg_close($this->_linkID);
  240. }
  241. $this->_linkID = null;
  242. }
  243. /**
  244. * 数据库错误信息
  245. * 并显示当前的SQL语句
  246. * @access public
  247. * @return string
  248. */
  249. public function error($result = true) {
  250. $this->error = $result?pg_result_error($this->queryID): pg_last_error($this->_linkID);
  251. if('' != $this->queryStr){
  252. $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
  253. }
  254. trace($this->error,'','ERR');
  255. return $this->error;
  256. }
  257. /**
  258. * SQL指令安全过滤
  259. * @access public
  260. * @param string $str SQL指令
  261. * @return string
  262. */
  263. public function escapeString($str) {
  264. return pg_escape_string($str);
  265. }
  266. /**
  267. * limit
  268. * @access public
  269. * @return string
  270. */
  271. public function parseLimit($limit) {
  272. $limitStr = '';
  273. if(!empty($limit)) {
  274. $limit = explode(',',$limit);
  275. if(count($limit)>1) {
  276. $limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
  277. }else{
  278. $limitStr .= ' LIMIT '.$limit[0].' ';
  279. }
  280. }
  281. return $limitStr;
  282. }
  283. }