Pgsql.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. Lib::loadClass('Core_DataSource');
  3. class Core_DataSource_Pgsql extends Core_DataSource {
  4. function __construct($host, $user, $password, $database, $names = '', $params = array()) {
  5. parent::__construct($host, $user, $password, $database, $names, $params);
  6. list($host,$port)=explode(":", $host);
  7. $this->_conn = @pg_connect("host=".$host." port=".$port." dbname=".$database." user=".$user." password=".$password);
  8. //DEBUG_S(-3,'conn'.$names." ",$params);
  9. if (!is_resource($this->_conn)) {
  10. $this->_set_error('CREATE CONNECTION FAILED');
  11. return;
  12. }
  13. //if (false === mysql_select_db($database, $this->_conn)) {
  14. // $this->_set_error('SELECT DATABASE FAILED');
  15. // return;
  16. //}
  17. if ($names != '') {
  18. $this->query("SET CLIENT_ENCODING TO '".$names."';");
  19. }
  20. }
  21. function getConnection() {
  22. return $this->_conn;
  23. }
  24. function getVersion($version) {
  25. if (!$this->_version) {
  26. //$sql = "SHOW VARIABLES LIKE 'version';";
  27. $this->_version=pg_version($this->_conn);
  28. //if ($r = $this->fetch($res)) {
  29. // // [Variable_name] => version, [Value] => 4.0.26-log
  30. // $this->_version = $r->Value;
  31. //}
  32. }
  33. return $this->_version;
  34. }
  35. /**
  36. * Wykonuje podane zapytanie i zwraca wynik mysql_query().
  37. */
  38. function query( $query, $msg = 'Query ERROR.' ) {
  39. $null = null;
  40. if (!$this->_conn) { return $null; }
  41. $res = pg_query($this->_conn,$query);
  42. if (!$res) {
  43. DEBUG_S(-3,'error ',array($query),__FILE__,__FUNCTION__,__LINE__);
  44. $this->_set_error('SQL QUERY FAILED: '.pg_result_error($this->_conn)."(".$query.")".pg_last_error($this->_conn));
  45. return $null;
  46. }
  47. return $res;
  48. }
  49. function fetch( $res ) {
  50. $ret = null;
  51. if ($res) $ret = pg_fetch_object( $res );
  52. return $ret;
  53. }
  54. function fetch_row( $res ) {
  55. $ret = null;
  56. if ($res) $ret = pg_fetch_row( $res );
  57. return $ret;
  58. }
  59. function fetch_assoc( $res ) {
  60. $ret = null;
  61. if ($res) $ret = pg_fetch_assoc( $res );
  62. return $ret;
  63. }
  64. function fetch_array($res) {
  65. $ret = null;
  66. if ($res) $ret = pg_fetch_array($res);
  67. return $ret;
  68. }
  69. function count( $res ) {
  70. return pg_num_rows( $res );
  71. }
  72. function num_rows( $res ) {
  73. return pg_num_rows( $res );
  74. }
  75. function insert_id() {
  76. $sql="select lastval();";
  77. $res = $this->query($sql);
  78. $last=$this->fetch_array($res);
  79. return $last[0];
  80. //return fetch_row( $res ); //TODO TESTING!!!
  81. //die('TEST THIS FUNCTION!!!');
  82. //return mysql_insert_id( $this->_conn );
  83. }
  84. function affected_rows($res) {
  85. return pg_affected_rows( $res );
  86. }
  87. function _( $str ) {
  88. return pg_escape_string( $str);
  89. }
  90. function error() {
  91. return "#".pg_result_error_field($this->_conn).": ".pg_result_error($this->_conn);
  92. }
  93. function get_by_id( $table, $id ) {
  94. $primary=self::show_index_value($table); //TODO to optimalize cache
  95. $null = null;
  96. $sql = "select p.*
  97. from \"".$table."\" as p
  98. where p.\"".$primary."\"='".$id."'
  99. ";
  100. $res = $this->query( $sql );
  101. if ($r = $this->fetch( $res )) {
  102. return $r;
  103. }
  104. return $null;
  105. }
  106. /**
  107. * @returns int
  108. * 1 - changed but without add hist
  109. * 2 - changed and add hist
  110. * 0 - nothing to change
  111. * -1 - sql errors
  112. * -2 - error id not exists in DB
  113. * -3 - error ID not set
  114. *
  115. * TODO: sprawdzac czy w hist mozna odczytac aktualny stan, jesli nie to dodac caly rekord do HIST, jako 'procesy-fix-hist-data'
  116. */
  117. public function UPDATE_OBJ($table, $sql_obj,$timestamp=null,$skip_author=null) {
  118. $structure=self::describe_table_value($table);
  119. $primary=self::show_index_value($table);
  120. if (!isset($sql_obj->$primary) || $sql_obj->$primary <= 0) {
  121. return -3;
  122. }
  123. $id = $sql_obj->$primary;
  124. // check id record $id exists
  125. if (($curr_obj = $this->get_by_id( $table, $sql_obj->$primary )) == null) {
  126. return -2;
  127. }
  128. // check if enything changed
  129. $changed = false;
  130. $fields_to_change = get_object_vars($sql_obj);
  131. //DEBUG_S(-3,'chk',array($fields_to_change),__FILE__,__FUNCTION__,__LINE__);
  132. foreach ($fields_to_change as $k => $v) {
  133. if ($k == $primary) continue;
  134. if ($v == $curr_obj->$k) {// === ?
  135. unset($sql_obj->$k);
  136. } else {
  137. $changed = true;
  138. }
  139. }
  140. if ($changed == false) {
  141. return 0;// record not changed
  142. }
  143. $sql_arr = array();
  144. // TODO: add admin columns if exists in table - search in session
  145. $admin_col = array();
  146. $admin_col []= 'A_RECORD_CREATE_DATE';
  147. $admin_col []= 'A_RECORD_CREATE_AUTHOR';
  148. // ...
  149. // $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d H:i');
  150. if(!empty($timestamp)) //fixed timestamp option TODO @2015-01-not working due to trigger?
  151. $sql_obj->A_RECORD_UPDATE_DATE = $timestamp;
  152. else
  153. $sql_obj->A_RECORD_UPDATE_DATE = self::get_current_timestamp();
  154. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  155. foreach (get_object_vars($sql_obj) as $k => $v) {
  156. if($k=='A_RECORD_CREATE_DATE'&& $v=='0000-00-00 00:00:00') {
  157. unset($k);
  158. unset($v);
  159. continue;
  160. } else if(strstr(trim($structure[$k]->Type),'date') && (strstr($v,'-00'))) {
  161. $v="'".str_replace("-00","-01",$v)."'" ;
  162. } else if(strstr(trim($structure[$k]->Type),'date') && (strstr($v,'0000'))) {
  163. $v="'".str_replace("0000","1970",$v)."'" ;
  164. } else if (substr($v, 0, strlen('ST_GeomFromText')) == 'ST_GeomFromText') {
  165. } else if (strtoupper($v) == 'NOW()') {
  166. $v = 'NOW()';
  167. } else if (strtoupper($v) == 'NULL') {
  168. $v = 'NULL';
  169. } else {
  170. $v = $this->_($v);
  171. $v = "'{$v}'";
  172. }
  173. $sql_arr [] = '"'.$k.'"='.$v;
  174. }
  175. $sql = "update \"{$table}\" set ".implode(",", $sql_arr)." where \"".$primary."\"='{$id}' ; ";
  176. // DEBUG_S(-3,'update',array($sql),__FILE__,__FUNCTION__,__LINE__);
  177. // die();
  178. $res=$this->query($sql);
  179. if ($this->has_errors()) {
  180. //DEBUG_S(-3,'errors',$this->has_errors,__FILE__,__FUNCTION__,__LINE__);
  181. return -1;
  182. }
  183. $ret = $this->affected_rows($res);
  184. // DEBUG_S(-3,'affected',$ret,__FILE__,__FUNCTION__,__LINE__);
  185. if ($ret) {
  186. $sql_obj->ID_USERS2 = $sql_obj->$primary;
  187. unset($sql_obj->$primary);
  188. $new_id = $this->ADD_NEW_OBJ("{$table}_HIST", $sql_obj);
  189. if ($new_id) {
  190. $ret += 1;
  191. }
  192. }
  193. return $ret;
  194. }
  195. function ADD_NEW_OBJ( $table, $sql_obj,$dieonerror=null ) {
  196. $structure=self::describe_table_value($table);
  197. $primary=self::show_index_value($table);
  198. $sql_arr = array();
  199. // TODO: add admin columns if exists in table - search in session
  200. $admin_col = array();
  201. $admin_col []= 'A_RECORD_CREATE_DATE';
  202. $admin_col []= 'A_RECORD_CREATE_AUTHOR';
  203. $admin_col []= 'A_RECORD_UPDATE_DATE';
  204. $admin_col []= 'A_RECORD_UPDATE_AUTHOR';
  205. // ...
  206. if (substr($table, 0, -5) == '_HIST') {
  207. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d H:i');
  208. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  209. } else {
  210. $sql_obj->A_RECORD_CREATE_DATE = date('Y-m-d H:i');
  211. $sql_obj->A_RECORD_CREATE_AUTHOR = User::getName();
  212. }
  213. foreach (get_object_vars($sql_obj) as $k => $v) {
  214. if($k==$primary) {
  215. unset($k);
  216. unset($v);
  217. continue;
  218. } else if (substr($v, 0, strlen('ST_GeomFromText')) == 'ST_GeomFromText') {
  219. } else if(strstr(trim($structure[$k]->Type),'int')) {
  220. if(strlen($v)>0) {
  221. $v=$v;
  222. } else if(empty($v)) $v='null';
  223. else $v = $v;
  224. } else if(trim($structure[$k]->Type)=='datetime') {
  225. if(empty($v)) $v='null';
  226. else if(strstr($v,'-00')) $v="'".str_replace("-00","-01",$v)."'" ;
  227. else $v = "'".$v."'::timestamp";
  228. } else if(trim($structure[$k]->Type)=='date') {
  229. if($v=='0000-00-00') $v='null';
  230. else if(strstr($v,'-00')) $v="'".str_replace("-00","-01",$v)."'" ;
  231. else $v = "'".$v."'";
  232. } else if (strtoupper($v) == 'NOW()') {
  233. $v = 'NOW()';
  234. } else if (strtoupper($v) == 'NULL' && substr($table, -5) != '_HIST') {
  235. $v = 'NULL';
  236. } else if(strstr($structure[$k]->Type,'int(')) {
  237. $v = $v ;
  238. } else {
  239. $v = $this->_($v);
  240. $v = "'{$v}'";
  241. }
  242. $sql_arr ['"'.$k.'"'] = $v;
  243. }
  244. $sql = "insert into \"{$table}\" (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr))."); ";
  245. //DEBUG_S(-3,' insert sql ',$sql,__FILE__,__FUNCTION__,__LINE__);
  246. $this->query($sql);
  247. if ($this->has_errors()) {
  248. if($dieonerror) {
  249. DEBUG_S(-3,'Has errors died',$this->get_errors(),__FILE__,__FUNCTION__,__LINE__);
  250. die();
  251. }
  252. // echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">db errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->get_errors());print_r($sql);echo'</pre>';
  253. }
  254. $ret_id = $this->insert_id();
  255. if (substr($table, -5) == '_HIST') {
  256. return $ret_id;
  257. }
  258. if ($ret_id) {
  259. $sql_obj->ID_USERS2 = $ret_id;
  260. unset($sql_obj->ID);
  261. $new_id_hist = $this->ADD_NEW_OBJ($table . '_HIST', $sql_obj);
  262. // error jesli nie udalo sie dodac rekordu do tabeli _HIST
  263. }
  264. return $ret_id;
  265. }
  266. }