Mysql.php 10 KB

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