Mysql.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. Lib::loadClass('Core_DataSource');
  3. Lib::loadClass('DataSourceException');
  4. class Core_DataSource_Mysql extends Core_DataSource {
  5. function __construct($host, $user, $password, $database, $names = '', $params = array()) {
  6. parent::__construct($host, $user, $password, $database, $names, $params);
  7. $this->_conn = @mysql_pconnect($host, $user, $password);
  8. if (!is_resource($this->_conn)) throw new Exception("Create connection failed!");
  9. if (false === mysql_select_db($database, $this->_conn)) throw new Exception("Select database failed!");
  10. if ($names != '') {
  11. $this->query(" SET NAMES '$names' ");
  12. }
  13. }
  14. function getConnection() {
  15. return $this->_conn;
  16. }
  17. function getVersion($version) {
  18. if (!$this->_version) {
  19. $sql = "SHOW VARIABLES LIKE 'version';";
  20. $res = $this->query($sql);
  21. if ($r = $this->fetch($res)) {
  22. // [Variable_name] => version, [Value] => 4.0.26-log
  23. $this->_version = $r->Value;
  24. }
  25. }
  26. return $this->_version;
  27. }
  28. function insert($table, $data) {
  29. if (is_object($data)) $data = (array)$data;
  30. else if (!is_array($data)) throw new Exception("Wrong data type to insert.");
  31. $sqlFields = array();
  32. $sqlValues = array();
  33. foreach ($data as $fldName => $fldValue) {
  34. $sqlFields[] = "`{$fldName}`";
  35. $sqlValues[] = $this->parseValue($fldValue);
  36. }
  37. $sqlFields = implode(", ", $sqlFields);
  38. $sqlValues = implode(", ", $sqlValues);
  39. $sql = "insert into `{$table}` ({$sqlFields})
  40. values ({$sqlValues})
  41. ";
  42. $this->query($sql);
  43. return mysql_insert_id($this->_conn);
  44. }
  45. function getById($tableName, $id) {
  46. $sqlTableName = $this->_($tableName);
  47. $sqlId = (int)$this->_($id);
  48. if (!$sqlTableName) throw new Exception("Wrong table name!");
  49. if ($sqlId <= 0) throw new Exception("Wrong record id!");
  50. $sql = "select t.*
  51. from `{$sqlTableName}` as t
  52. where t.`ID`='{$sqlId}'
  53. ";
  54. $res = $this->query($sql);
  55. if ($r = $this->fetch($res)) {
  56. return $r;
  57. } else throw new Exception("Nie naleziono rekordu nr '{$sqlId}'");
  58. }
  59. function getListByQuery($sql) {
  60. $list = array();
  61. if (!$sql) throw new Exception("Empty query!");
  62. $res = $this->query($sql);
  63. while ($r = $this->fetch($res)) {
  64. $list[] = $r;
  65. }
  66. return $list;
  67. }
  68. public function parseValue($value) {
  69. $parsedValue = 'NULL';
  70. if ('NOW()' == strtoupper($value)) {
  71. $parsedValue = 'NOW()';
  72. } else if ('GeomFromText' == substr($value, 0, strlen('GeomFromText'))) {
  73. } else {
  74. $parsedValue = "'" . $this->_($value) . "'";
  75. }
  76. return $parsedValue;
  77. }
  78. function query($query) {
  79. $null = null;
  80. if (!$this->_conn) throw new Exception("Connection not exists!");
  81. $res = mysql_query($query, $this->_conn);
  82. if (!$res) {
  83. $exception = new DataSourceException("Query error: " . mysql_error($this->_conn), mysql_errno($this->_conn));
  84. $exception->setQuery($query);
  85. throw $exception;
  86. }
  87. return $res;
  88. }
  89. function fetch( $res ) {
  90. $ret = null;
  91. if ($res) $ret = mysql_fetch_object( $res );
  92. return $ret;
  93. }
  94. function fetch_row( $res ) {
  95. $ret = null;
  96. if ($res) $ret = mysql_fetch_row( $res );
  97. return $ret;
  98. }
  99. function fetch_assoc( $res ) {
  100. $ret = null;
  101. if ($res) $ret = mysql_fetch_assoc( $res );
  102. return $ret;
  103. }
  104. function fetch_array($res) {
  105. $ret = null;
  106. if ($res) $ret = mysql_fetch_array($res);
  107. return $ret;
  108. }
  109. function count( $res ) {
  110. return mysql_num_rows( $res );
  111. }
  112. function num_rows( $res ) {
  113. return mysql_num_rows( $res );
  114. }
  115. function insert_id() {
  116. return mysql_insert_id( $this->_conn );
  117. }
  118. function show_tables($table=null) {
  119. if(!empty($table)) $sql="show tables like '".$table."'";
  120. else $sql="show tables";
  121. $res = $this->query($sql);
  122. return $res;
  123. }
  124. function describe_table($table) {
  125. $sql='SHOW FIELDS FROM `'.$table.'`';
  126. $res = $this->query($sql);
  127. return $res;
  128. }
  129. function describe_table_value($table) {
  130. $res = self::describe_table($table);
  131. while($h=self::fetch($res)) {
  132. $result[$h->Field]=$h;
  133. }
  134. return $result;
  135. }
  136. function show_index($table,$only_primary_flag=false) {
  137. $sql="show index from `".$table."`";
  138. if($only_primary_flag) $sql.=" WHERE `Key_name` = 'PRIMARY' ";
  139. $res=self::query($sql);
  140. return $res;
  141. }
  142. function show_index_value($table) {
  143. $res=self::show_index($table,true);
  144. while($h=self::fetch($res)) {
  145. return $h->Column_name;
  146. }
  147. }
  148. function affected_rows($needed_in_psql_only=null) {
  149. return mysql_affected_rows( $this->_conn );
  150. }
  151. function _( $str ) {
  152. return mysql_real_escape_string( $str, $this->_conn );
  153. }
  154. function error() {
  155. return "#".mysql_errno($this->_conn).": ".mysql_error($this->_conn);
  156. }
  157. function errno() {
  158. return mysql_errno($this->_conn);
  159. }
  160. /**
  161. * @returns int
  162. * 1 - changed but without add hist
  163. * 2 - changed and add hist
  164. * 0 - nothing to change
  165. * -1 - sql errors
  166. * -2 - error id not exists in DB
  167. * -3 - error ID not set
  168. *
  169. * TODO: sprawdzac czy w hist mozna odczytac aktualny stan, jesli nie to dodac caly rekord do HIST, jako 'procesy-fix-hist-data'
  170. */
  171. public function UPDATE_OBJ($table, $sql_obj,$timestamp=null,$skip_author=null) {
  172. $structure=self::describe_table_value($table); //todo to cache optimize
  173. $primary=self::show_index_value($table); //todo to cache optimize
  174. if (!isset($sql_obj->$primary) || $sql_obj->$primary <= 0) {
  175. return -3;
  176. }
  177. $id = $sql_obj->$primary;
  178. // check id record $id exists
  179. if (($curr_obj = $this->get_by_id( $table, $sql_obj->$primary )) == null) {
  180. return -2;
  181. }
  182. // check if enything changed
  183. $changed = false;
  184. $fields_to_change = get_object_vars($sql_obj);
  185. foreach ($fields_to_change as $k => $v) {
  186. if ($k == $primary) continue;
  187. if ($v == $curr_obj->$k) {// === ?
  188. unset($sql_obj->$k);
  189. } else {
  190. $changed = true;
  191. }
  192. }
  193. if ($changed == false) {
  194. return 0;// record not changed
  195. }
  196. $sql_arr = array();
  197. // TODO: add admin columns if exists in table - search in session
  198. $admin_col = array();
  199. $admin_col[] = 'A_RECORD_CREATE_DATE';
  200. $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
  201. // ...
  202. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  203. // OFF - BUG w _HIST $sql_obj->A_RECORD_UPDATE_DATE = "FROM_UNIXTIME(".$this->get_current_time().")";
  204. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  205. foreach (get_object_vars($sql_obj) as $k => $v) {
  206. if(!empty($skip_author)) {
  207. if($k=='A_RECORD_UPDATE_AUTHOR') continue;
  208. if($k=='A_RECORD_UPDATE_DATE') continue;
  209. }
  210. if (strtoupper($v) == 'NOW()') {
  211. $v = 'NOW()';
  212. } else if (strtoupper($v) == 'NULL') {
  213. $v = 'NULL';
  214. } else if (substr($v, 0, strlen('GeomFromText')) == 'GeomFromText') {
  215. } else {
  216. $v = $this->_($v);
  217. $v = "'{$v}'";
  218. }
  219. $sql_arr [] = "`{$k}`={$v}";
  220. }
  221. $sql = "update `{$table}` set ".implode(",", $sql_arr)." where `ID`='{$id}' limit 1; ";
  222. $this->query($sql);
  223. $returnError = false;
  224. $skipDbErrorAddHist = false;
  225. if ($this->has_errors()) {
  226. $returnError = true;
  227. if (1146 == $this->errno()) {
  228. $skipDbErrorAddHist = true;
  229. }
  230. }
  231. $returnCode = 0;
  232. $affected = $this->affected_rows();
  233. if ($affected || $skipDbErrorAddHist) {
  234. $returnCode = 1;
  235. $sql_obj->ID_USERS2 = $sql_obj->$primary;
  236. unset($sql_obj->$primary);
  237. $new_id = $this->ADD_NEW_OBJ("{$table}_HIST", $sql_obj);
  238. if ($new_id) {
  239. $returnCode += 1;
  240. }
  241. }
  242. if ($returnError) {
  243. return -1;
  244. }
  245. return $returnCode;
  246. }
  247. function ADD_NEW_OBJ( $table, $sql_obj,$dieonerror=null ) {
  248. //TODO to optimize:
  249. $structure=self::describe_table_value($table);
  250. $primary=self::show_index_value($table);
  251. $sql_arr = array();
  252. // TODO: add admin columns if exists in table - search in session
  253. $admin_col = array();
  254. $admin_col []= 'ID';
  255. $admin_col []= 'A_RECORD_CREATE_DATE';
  256. $admin_col []= 'A_RECORD_CREATE_AUTHOR';
  257. $admin_col []= 'A_RECORD_UPDATE_DATE';
  258. $admin_col []= 'A_RECORD_UPDATE_AUTHOR';
  259. // ...
  260. $sql_arr["`ID`"] = "NULL";// add default value for ID, NULL in all inserts
  261. if (substr($table, 0, -5) == '_HIST') {
  262. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  263. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  264. } else {
  265. $sql_obj->A_RECORD_CREATE_DATE = date('Y-m-d-H:i');
  266. $sql_obj->A_RECORD_CREATE_AUTHOR = User::getName();
  267. }
  268. foreach (get_object_vars($sql_obj) as $k => $v) {
  269. if($k==$primary) $v='0';
  270. else if (strtoupper($v) == 'NOW()') {
  271. $v = 'NOW()';
  272. } else if (strtoupper($v) == 'NULL' && substr($table, -5) != '_HIST') {
  273. $v = 'NULL';
  274. } else if (substr($v, 0, strlen('GeomFromText')) == 'GeomFromText') {
  275. } else {
  276. $v = $this->_($v);
  277. $v = "'{$v}'";
  278. }
  279. $sql_arr ["`{$k}`"] = $v;
  280. }
  281. $sql = "insert into `{$table}` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr))."); ";
  282. //error_log($sql);
  283. $this->query($sql);
  284. if ($this->has_errors()) {
  285. if(!empty($dieonerror)) {
  286. 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());echo'</pre>';
  287. DEBUG_S(-3,'Bledne zapytanie sql',$sql,__FILE__,__FUNCTION__,__LINE__);
  288. }
  289. }
  290. $ret_id = $this->insert_id();
  291. if (substr($table, -5) == '_HIST') {
  292. return $ret_id;
  293. }
  294. if ($ret_id) {
  295. $sql_obj->ID_USERS2 = $ret_id;
  296. unset($sql_obj->ID);
  297. $new_id_hist = $this->ADD_NEW_OBJ($table . '_HIST', $sql_obj);
  298. // error jesli nie udalo sie dodac rekordu do tabeli _HIST
  299. }
  300. return $ret_id;
  301. }
  302. }