DB.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <?php
  2. /*
  3. # Usage:
  4. ## Usage - example 1:
  5. try {
  6. $pdo = DB::getPDO();
  7. $pdo->getDatabaseName();
  8. $pdo->getZasobId();
  9. $sth = $pdo->prepare("select * from CRM_LISTA_ZASOBOW limit 10");
  10. $sth->execute();
  11. $rows = $sth->fetchAll();
  12. } catch (Exception $e) {
  13. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  14. }
  15. ## Usage - example 2:
  16. try {
  17. $pdo = DB::getPDO();
  18. $rows = $pdo->fetchAll("select * from CRM_LISTA_ZASOBOW limit 10");
  19. } catch (Exception $e) {
  20. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  21. }
  22. */
  23. Lib::loadClass('Config');
  24. Lib::loadClass('DataSourceException');
  25. Lib::loadClass('Core_Pdo');
  26. Lib::loadClass('Core_TypeFactory');
  27. class DB {
  28. /**
  29. * Get database object.
  30. *
  31. * @param string $db Zasob ID or database name (require config file @see Config::getZasobConf($db))
  32. *
  33. * @returns object Database
  34. */
  35. public static function getDB($db = null) {
  36. static $_instance;
  37. if (!is_array($_instance)) {
  38. $_instance = array();
  39. }
  40. $dbConfName = 'default_db';
  41. if (is_numeric($db) && $db > 0) {
  42. $dbConfName = "zasob_{$db}";
  43. } else if ($db == 'import_db') {
  44. $dbConfName = "import_db";
  45. } else if ($db == 'test_db') {
  46. $dbConfName = "test_db";
  47. } else if ($db == 'test3_db') {
  48. $dbConfName = "test3_db";
  49. } else if ($db == 'billing_db') {
  50. $dbConfName = "billing_db";
  51. }
  52. if (!array_key_exists($dbConfName, $_instance)) {
  53. $_instance[$dbConfName] = null;
  54. Lib::loadClass('Config');
  55. $conf = Config::getConfFile($dbConfName);
  56. if ($conf) {
  57. $type = V::get('type', 'mysql', $conf);
  58. $host = V::get('host', '', $conf);
  59. $port = V::get('port', '', $conf);
  60. $user = V::get('user', '', $conf);
  61. $pass = V::get('pass', '', $conf);
  62. $zasob_id = V::get('zasob_id', '', $conf);
  63. $database = V::get('database', '', $conf);
  64. if ($port && $host) {
  65. $host .= ":{$port}";
  66. }
  67. $names = 'utf8';
  68. $db_class = 'Core_Database_' . ucfirst($type);
  69. Lib::loadClass($db_class);
  70. if (class_exists($db_class)) {
  71. $params = array();
  72. $tdsver = V::get('tdsver', '', $conf);
  73. if (!empty($tdsver)) {
  74. $params['tdsver'] = $tdsver;
  75. }
  76. if(!empty($zasob_id)) {
  77. $params['zasob_id'] = $zasob_id;
  78. }
  79. $_instance[$dbConfName] = new $db_class($host, $user, $pass, $database, $names, $params);
  80. }
  81. } else {
  82. trigger_error("Config file for db {$dbConfName} not exists!", E_USER_WARNING);
  83. }
  84. }
  85. return $_instance[$dbConfName];
  86. }
  87. public static function getStorage($db = null) {
  88. $pdo = self::getPDO($db);
  89. $type = $pdo->getType();
  90. switch ($type) {
  91. case 'mysql':
  92. Lib::loadClass('Core_Storage_Mysql');
  93. return new Core_Storage_Mysql($pdo);
  94. case 'pgsql':
  95. Lib::loadClass('Core_Storage_Pgsql');
  96. return new Core_Storage_Pgsql($pdo);
  97. default: throw new Exception("Storage for type '{$type}' not implemented");
  98. }
  99. }
  100. public static function getPDO($db = null) {
  101. static $_instance;
  102. if (!is_array($_instance)) $_instance = array();
  103. $zasob_id = '';
  104. $dbConfName = 'default_db';
  105. if (is_numeric($db) && $db > 0) {
  106. $zasob_id = $db;
  107. $dbConfName = "zasob_{$zasob_id}";
  108. } else if ($db == 'import_db') {
  109. $dbConfName = "import_db";
  110. } else if ($db == 'test_db') {
  111. $dbConfName = "test_db";
  112. } else if ($db == 'billing_db') {
  113. $dbConfName = "billing_db";
  114. } else if (!$db || 'default_db' == $db) {
  115. $dbConfName = 'default_db';
  116. } else {
  117. throw new Exception("Not implemented database '{$db}'");
  118. }
  119. if (!array_key_exists($dbConfName, $_instance)) {
  120. $_instance[$dbConfName] = null;
  121. Lib::loadClass('Config');
  122. $conf = Config::getConfFile($dbConfName);
  123. if (!$conf) throw new Exception("Config file for db {$dbConfName} not exists!");
  124. $type = V::get('type', 'mysql', $conf);
  125. $host = V::get('host', '', $conf);
  126. $port = V::get('port', '', $conf);
  127. $user = V::get('user', '', $conf);
  128. $pass = V::get('pass', '', $conf);
  129. $database = V::get('database', '', $conf);
  130. $zasob_id = V::get('zasob_id', $zasob_id, $conf);
  131. $schema = V::get('schema', '', $conf);
  132. if (empty($host)) throw new Exception("Brak zdefiniowanego pola 'host' dla bazy danych '{$dbConfName}'");
  133. if (empty($user)) throw new Exception("Brak zdefiniowanego loginu usera dla bazy danych '{$dbConfName}'");
  134. if (empty($pass)) throw new Exception("Brak zdefiniowanego hasła usera dla bazy danych '{$dbConfName}'");
  135. if (empty($database)) throw new Exception("Brak zdefiniowane nazwy bazy danych dla '{$dbConfName}'");
  136. if (empty($zasob_id)) throw new Exception("Brak zdefiniowanego id zasobu dla bazy danych '{$dbConfName}' (po prostu dodaj definicje np. zasob_id=2 do ....default_db.conf....) ");
  137. $options = array();
  138. if ($port && $host) $host .= ";port={$port}";
  139. $names = 'utf8';
  140. $tdsver = V::get('tdsver', '', $conf);
  141. if (!empty($tdsver)) $options['tdsver'] = $tdsver;
  142. $options['zasob_id'] = $zasob_id;
  143. if (!empty($database)) $options['database'] = $database;
  144. if (!empty($schema)) $options['schema'] = $schema;
  145. //$pdo = new PDO($type . ':host=' . $host . ';dbname=' . $database, $user, $pass);
  146. //$pdo->exec("SET NAMES 'utf8'");
  147. //$sdb = new Core_Pdo($pdo);
  148. $options['type'] = $type;
  149. $sdb = new Core_Pdo($type . ':host=' . $host . ';dbname=' . $database, $user, $pass, $options);
  150. $sdb->exec("SET NAMES 'utf8'");
  151. $_instance[$dbConfName] = $sdb;
  152. }
  153. return $_instance[$dbConfName];
  154. }
  155. public static function identifierQuote($type, $identifier) { // $type: mysql | mssql | pgsql
  156. switch (strtolower($type)) {
  157. case 'pgsql': return self::pgsqlIdentifierQuote($identifier);
  158. case 'mysql': return "`{$identifier}`";
  159. default: throw new Exception("Not Implemented database type in identifierQuote '{$type}'");
  160. }
  161. }
  162. public static function pgsqlIdentifierQuote($identifier) {
  163. if (false !== strpos($identifier, '.')) {
  164. return implode('.', array_map(function ($token) {
  165. return "\"{$token}\"";
  166. }, explode('.', $identifier)));
  167. }
  168. return "\"{$identifier}\""; // https://www.postgresql.org/docs/9.1/sql-syntax-lexical.html
  169. }
  170. public static function makeValue($type, $value, $params = []) {
  171. return Core_TypeFactory::make($type, $value, $params);
  172. }
  173. public static function connect() {
  174. static $conn;
  175. if (!is_resource($conn)) {
  176. $db = self::getDB();
  177. if (!$db) {
  178. die('Config file for main DB not exists!');
  179. }
  180. $conn = $db->getConnection();
  181. }
  182. return $conn;
  183. }
  184. public static function transaction_start() {
  185. DB::query(" START TRANSACTION; ");
  186. }
  187. public static function transaction_commit() {
  188. DB::query(" COMMIT; ");
  189. }
  190. public static function transaction_rollback() {
  191. DB::query(" ROLLBACK; ");
  192. }
  193. public static function query($sql, $die_on_error = true) {
  194. $conn = self::connect();
  195. $res = mysql_query($sql, $conn);
  196. if (!$res) {
  197. if ($die_on_error) {
  198. trigger_error("query error: #".mysql_errno($conn).": ".mysql_error($conn)."\n $sql", E_USER_ERROR);
  199. die("ERROR DB: QUERY ERROR");
  200. } else {
  201. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r("query error: #".mysql_errno($conn).": ".mysql_error($conn)."\n $sql");echo'</pre>';
  202. $null = null;
  203. return $null;
  204. }
  205. } else {
  206. return $res;
  207. }
  208. }
  209. public static function fetch($res) {
  210. $ret = null;
  211. if ($res) $ret = mysql_fetch_object($res);
  212. return $ret;
  213. }
  214. public static function fetch_row($res) {
  215. $ret = null;
  216. if ($res) $ret = mysql_fetch_row($res);
  217. return $ret;
  218. }
  219. public static function fetch_array($res) {
  220. $ret = null;
  221. if ($res) $ret = mysql_fetch_array($res);
  222. return $ret;
  223. }
  224. public static function fetch_assoc($res) {
  225. $ret = null;
  226. if ($res) $ret = mysql_fetch_assoc($res);
  227. return $ret;
  228. }
  229. public static function _($str) {
  230. //PHP >= 4.3.0; dodaje lewe ukoᄊniki (backslash) do nast↑pujᄆcych znak￳w: \x00, \n, \r, \, ', " and \x1a
  231. return mysql_real_escape_string($str, self::connect());
  232. }
  233. public static function error() {
  234. $conn = self::connect();
  235. return "#".mysql_errno($conn).": ".mysql_error($conn);
  236. }
  237. // Pobiera liczb↑ wierszy przetworzonych w ostatnim zapytaniu INSERT, UPDATE, REPLACE lub DELETE skojarzonym z identyfikator_poᄈᄆczenia.
  238. public static function affected_rows() {
  239. return mysql_affected_rows(self::connect());
  240. }
  241. // Zwraca ID wygenerowane dla pola z wᄈasnoᄊciᄆ AUTO_INCREMENT lub 0 jesli error
  242. public static function insert_id() {
  243. return mysql_insert_id(self::connect());
  244. }
  245. // Zwraca liczb↑ wierszy w wyniku. T↑ funkcj↑ stosuje si↑ tylko do operacji SELECT.
  246. public static function num_rows($res) {
  247. return mysql_num_rows($res);
  248. }
  249. public static function get_by_id($table, $id) {
  250. $null = null;
  251. $sql = "select p.*
  252. from `{$table}` as p
  253. where p.`ID`='{$id}'
  254. ";
  255. $res = DB::query($sql);
  256. if ($r = DB::fetch($res)) {
  257. return $r;
  258. }
  259. return $null;
  260. }
  261. /**
  262. * @returns int
  263. * 1 - changed but without add hist
  264. * 2 - changed and add hist
  265. * 0 - nothing to change
  266. * -1 - error ID not set
  267. * -2 - error id not exists in DB
  268. *
  269. * TODO: sprawdzac czy w hist mozna odczytac aktualny stan, jesli nie to dodac caly rekord do HIST, jako 'procesy-fix-hist-data'
  270. */
  271. public static function UPDATE_OBJ($table, &$sql_obj) {
  272. if (!isset($sql_obj->ID) || $sql_obj->ID <= 0) {
  273. return -1;
  274. }
  275. $id = $sql_obj->ID;
  276. // check id record $id exists
  277. if (($curr_obj = self::get_by_id($table, $sql_obj->ID)) == null) {
  278. return -2;
  279. }
  280. // check if enything changed
  281. $changed = false;
  282. $fields_to_change = get_object_vars($sql_obj);
  283. foreach ($fields_to_change as $k => $v) {
  284. if ($k == 'ID') continue;
  285. if ($v == $curr_obj->$k) {
  286. unset($sql_obj->$k);
  287. } else {
  288. $changed = true;
  289. }
  290. }
  291. if ($changed == false) {
  292. return 0;// record not changed
  293. }
  294. $sql_arr = array();
  295. // TODO: add admin columns if exists in table - search in session
  296. $admin_col = array();
  297. $admin_col[] = 'A_RECORD_CREATE_DATE';
  298. $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
  299. // ...
  300. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  301. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  302. foreach (get_object_vars($sql_obj) as $k => $v) {
  303. $sql_arr [] = "`".$k."`=".(($v == 'NOW()')? $v : "'".self::_($v)."'");//"'".self::_($v)."'";
  304. }
  305. $sql = "update `".$table."` set ".implode(",", $sql_arr)." where `ID`='".$id."' limit 1; ";
  306. self::query( $sql );
  307. $ret = self::affected_rows();
  308. if ($ret) {
  309. $sql_obj->ID_USERS2 = $id;
  310. unset($sql_obj->ID);
  311. $new_id = self::ADD_NEW_OBJ($table . '_HIST', $sql_obj);
  312. if ($new_id) {
  313. $ret += 1;
  314. }
  315. }
  316. return $ret;
  317. }
  318. public static function ADD_NEW_OBJ($table, &$sql_obj) {
  319. $sql_arr = array();
  320. // TODO: add admin columns if exists in table - search in session
  321. $admin_col = array();
  322. $admin_col[] = 'ID';
  323. $admin_col[] = 'A_RECORD_CREATE_DATE';
  324. $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
  325. $admin_col[] = 'A_RECORD_UPDATE_DATE';
  326. $admin_col[] = 'A_RECORD_UPDATE_AUTHOR';
  327. // ...
  328. $sql_arr["`ID`"] = "NULL";// add default value for ID, NULL in all inserts
  329. if (substr($table, 0, -5) == '_HIST') {
  330. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  331. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  332. } else {
  333. $sql_obj->A_RECORD_CREATE_DATE = date('Y-m-d-H:i');
  334. $sql_obj->A_RECORD_CREATE_AUTHOR = User::getName();
  335. }
  336. foreach (get_object_vars($sql_obj) as $k => $v) {
  337. $sql_arr ["`".$k."`"] = ($v == 'NOW()')? $v : "'".self::_($v)."'";
  338. }
  339. $sql = "insert into `".$table."` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr))."); ";
  340. self::query($sql);
  341. $ret_id = self::insert_id();
  342. if (substr($table, -5) == '_HIST') {
  343. return $ret_id;
  344. }
  345. if ($ret_id) {
  346. $sql_obj->ID_USERS2 = $ret_id;
  347. unset($sql_obj->ID);
  348. $new_id_hist = self::ADD_NEW_OBJ($table . '_HIST', $sql_obj);
  349. // error jesli nie udalo sie dodac rekordu do tabeli _HIST
  350. }
  351. return $ret_id;
  352. }
  353. }