Mysql.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 mysql_real_escape_string($str, $this->_conn);
  85. }
  86. function fetch_row( $res ) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  87. $ret = null;
  88. if ($res) $ret = mysql_fetch_row( $res );
  89. return $ret;
  90. }
  91. function fetch_assoc( $res ) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  92. $ret = null;
  93. if ($res) $ret = mysql_fetch_assoc( $res );
  94. return $ret;
  95. }
  96. function fetch_array($res) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  97. $ret = null;
  98. if ($res) $ret = mysql_fetch_array($res);
  99. return $ret;
  100. }
  101. function count( $res ) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  102. return mysql_num_rows( $res );
  103. }
  104. function num_rows( $res ) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  105. return mysql_num_rows( $res );
  106. }
  107. function insert_id() { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  108. return mysql_insert_id( $this->_conn );
  109. }
  110. function show_tables($table=null) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  111. if(!empty($table)) $sql="show tables like '".$table."'";
  112. else $sql="show tables";
  113. $res = $this->query($sql);
  114. return $res;
  115. }
  116. function describe_table($table) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  117. $sql='SHOW FIELDS FROM `'.$table.'`';
  118. $res = $this->query($sql);
  119. return $res;
  120. }
  121. function describe_table_value($table) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  122. $res = self::describe_table($table);
  123. while($h=self::fetch($res)) {
  124. $result[$h->Field]=$h;
  125. }
  126. return $result;
  127. }
  128. function show_index($table,$only_primary_flag=false) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  129. $sql="show index from `".$table."`";
  130. if($only_primary_flag) $sql.=" WHERE `Key_name` = 'PRIMARY' ";
  131. $res=self::query($sql);
  132. return $res;
  133. }
  134. function show_index_value($table) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  135. $res=self::show_index($table,true);
  136. while($h=self::fetch($res)) {
  137. return $h->Column_name;
  138. }
  139. }
  140. function affected_rows($needed_in_psql_only=null) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  141. return mysql_affected_rows( $this->_conn );
  142. }
  143. function error() { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  144. return "#".mysql_errno($this->_conn).": ".mysql_error($this->_conn);
  145. }
  146. function errno() { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  147. return mysql_errno($this->_conn);
  148. }
  149. /**
  150. * @returns int
  151. * 1 - changed but without add hist
  152. * 2 - changed and add hist
  153. * 0 - nothing to change
  154. * -1 - sql errors
  155. * -2 - error id not exists in DB
  156. * -3 - error ID not set
  157. *
  158. * TODO: sprawdzac czy w hist mozna odczytac aktualny stan, jesli nie to dodac caly rekord do HIST, jako 'procesy-fix-hist-data'
  159. */
  160. public function UPDATE_OBJ($table, $sql_obj,$timestamp=null,$skip_author=null) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  161. $structure=self::describe_table_value($table); //todo to cache optimize
  162. $primary=self::show_index_value($table); //todo to cache optimize
  163. if (!isset($sql_obj->$primary) || $sql_obj->$primary <= 0) {
  164. return -3;
  165. }
  166. $id = $sql_obj->$primary;
  167. // check id record $id exists
  168. if (($curr_obj = $this->get_by_id( $table, $sql_obj->$primary )) == null) {
  169. return -2;
  170. }
  171. // check if enything changed
  172. $changed = false;
  173. $fields_to_change = get_object_vars($sql_obj);
  174. foreach ($fields_to_change as $k => $v) {
  175. if ($k == $primary) continue;
  176. if ($v == $curr_obj->$k) {// === ?
  177. unset($sql_obj->$k);
  178. } else {
  179. $changed = true;
  180. }
  181. }
  182. if ($changed == false) {
  183. return 0;// record not changed
  184. }
  185. $sql_arr = array();
  186. // TODO: add admin columns if exists in table - search in session
  187. $admin_col = array();
  188. $admin_col[] = 'A_RECORD_CREATE_DATE';
  189. $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
  190. // ...
  191. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  192. // OFF - BUG w _HIST $sql_obj->A_RECORD_UPDATE_DATE = "FROM_UNIXTIME(".$this->get_current_time().")";
  193. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  194. foreach (get_object_vars($sql_obj) as $k => $v) {
  195. if(!empty($skip_author)) {
  196. if($k=='A_RECORD_UPDATE_AUTHOR') continue;
  197. if($k=='A_RECORD_UPDATE_DATE') continue;
  198. }
  199. if (strtoupper($v) == 'NOW()') {
  200. $v = 'NOW()';
  201. } else if (strtoupper($v) == 'NULL') {
  202. $v = 'NULL';
  203. } else if (substr($v, 0, strlen('GeomFromText')) == 'GeomFromText') {
  204. } else {
  205. $v = $this->_($v);
  206. $v = "'{$v}'";
  207. }
  208. $sql_arr [] = "`{$k}`={$v}";
  209. }
  210. $sql = "update `{$table}` set ".implode(",", $sql_arr)." where `ID`='{$id}' limit 1; ";
  211. $this->query($sql);
  212. $returnError = false;
  213. $skipDbErrorAddHist = false;
  214. if ($this->has_errors()) {
  215. $returnError = true;
  216. if (1146 == $this->errno()) {
  217. $skipDbErrorAddHist = true;
  218. }
  219. }
  220. $returnCode = 0;
  221. $affected = $this->affected_rows();
  222. if ($affected || $skipDbErrorAddHist) {
  223. $returnCode = 1;
  224. $sql_obj->ID_USERS2 = $sql_obj->$primary;
  225. unset($sql_obj->$primary);
  226. $new_id = $this->ADD_NEW_OBJ("{$table}_HIST", $sql_obj);
  227. if ($new_id) {
  228. $returnCode += 1;
  229. }
  230. }
  231. if ($returnError) {
  232. return -1;
  233. }
  234. return $returnCode;
  235. }
  236. function ADD_NEW_OBJ( $table, $sql_obj,$dieonerror=null ) { throw new Exception("Unimplemented Data Source function '" . __FUNCTION__ . "'!");
  237. //TODO to optimize:
  238. $structure=self::describe_table_value($table);
  239. $primary=self::show_index_value($table);
  240. $sql_arr = array();
  241. // TODO: add admin columns if exists in table - search in session
  242. $admin_col = array();
  243. $admin_col []= 'ID';
  244. $admin_col []= 'A_RECORD_CREATE_DATE';
  245. $admin_col []= 'A_RECORD_CREATE_AUTHOR';
  246. $admin_col []= 'A_RECORD_UPDATE_DATE';
  247. $admin_col []= 'A_RECORD_UPDATE_AUTHOR';
  248. // ...
  249. $sql_arr["`ID`"] = "NULL";// add default value for ID, NULL in all inserts
  250. if (substr($table, 0, -5) == '_HIST') {
  251. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  252. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  253. } else {
  254. $sql_obj->A_RECORD_CREATE_DATE = date('Y-m-d-H:i');
  255. $sql_obj->A_RECORD_CREATE_AUTHOR = User::getName();
  256. }
  257. foreach (get_object_vars($sql_obj) as $k => $v) {
  258. if($k==$primary) $v='0';
  259. else if (strtoupper($v) == 'NOW()') {
  260. $v = 'NOW()';
  261. } else if (strtoupper($v) == 'NULL' && substr($table, -5) != '_HIST') {
  262. $v = 'NULL';
  263. } else if (substr($v, 0, strlen('GeomFromText')) == 'GeomFromText') {
  264. } else {
  265. $v = $this->_($v);
  266. $v = "'{$v}'";
  267. }
  268. $sql_arr ["`{$k}`"] = $v;
  269. }
  270. $sql = "insert into `{$table}` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr))."); ";
  271. //error_log($sql);
  272. $this->query($sql);
  273. if ($this->has_errors()) {
  274. if(!empty($dieonerror)) {
  275. 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>';
  276. DEBUG_S(-3,'Bledne zapytanie sql',$sql,__FILE__,__FUNCTION__,__LINE__);
  277. }
  278. }
  279. $ret_id = $this->insert_id();
  280. if (substr($table, -5) == '_HIST') {
  281. return $ret_id;
  282. }
  283. if ($ret_id) {
  284. $sql_obj->ID_USERS2 = $ret_id;
  285. unset($sql_obj->ID);
  286. $new_id_hist = $this->ADD_NEW_OBJ($table . '_HIST', $sql_obj);
  287. // error jesli nie udalo sie dodac rekordu do tabeli _HIST
  288. }
  289. return $ret_id;
  290. }
  291. }