DB.php 12 KB

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