| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439 |
- <?php
- /*
- # Usage:
- ## Usage - example 1:
- try {
- $pdo = DB::getPDO();
- $pdo->getDatabaseName();
- $pdo->getZasobId();
- $sth = $pdo->prepare("select * from CRM_LISTA_ZASOBOW limit 10");
- $sth->execute();
- $rows = $sth->fetchAll();
- } catch (Exception $e) {
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- }
- ## Usage - example 2:
- try {
- $pdo = DB::getPDO();
- $rows = $pdo->fetchAll("select * from CRM_LISTA_ZASOBOW limit 10");
- } catch (Exception $e) {
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- }
- */
- Lib::loadClass('Config');
- Lib::loadClass('DataSourceException');
- Lib::loadClass('Core_Pdo');
- class DB {
- public static function getDataSource($db = null) {
- static $_instanceList;
- if (!is_array($_instanceList)) {
- $_instanceList = array();
- }
- if (null === $db) {
- $configName = 'default_db';
- } else if (is_numeric($db) && $db > 0) {
- $configName = "zasob_{$db}";
- } else if ($db == 'import_db') {
- $configName = "import_db";
- } else if ($db == 'test_db') {
- $configName = "test_db";
- } else if ($db == 'billing_db') {
- $configName = "billing_db";
- } else {// TODO: check by name from zasoby
- throw new Exception("Unknown data source name!");
- }
- if (array_key_exists($configName, $_instanceList)) {
- return $_instanceList[$configName];
- }
- $_instanceList[$configName] = null;
- $conf = Config::getConfFile($configName);
- if (!$conf) throw new Exception("Config for data source '{$configName}' not found!");
- $type = V::get('type', 'mysql', $conf);
- $host = V::get('host', '', $conf);
- $port = V::get('port', '', $conf);
- $user = V::get('user', '', $conf);
- $pass = V::get('pass', '', $conf);
- $zasob_id = V::get('zasob_id', '', $conf);
- $database = V::get('database', '', $conf);
- if ($port && $host) $host .= ":{$port}";
- $names = 'utf8';
- $db_class = 'Core_DataSource_' . ucfirst($type);
- Lib::loadClass($db_class);
- if (!class_exists($db_class)) throw new Exception("Data source class for type '{$type}' not found!");
- $params = array();
- $tdsver = V::get('tdsver', '', $conf);
- if (!empty($tdsver)) $params['tdsver'] = $tdsver;
- if (!empty($zasob_id)) $params['zasob_id'] = $zasob_id;
- $_instanceList[$configName] = new $db_class($host, $user, $pass, $database, $names, $params);
- return $_instanceList[$configName];
- }
- /**
- * Get database object.
- *
- * @param string $db Zasob ID or database name (require config file @see Config::getZasobConf($db))
- *
- * @returns object Database
- */
- public static function getDB($db = null) {
- static $_instance;
- if (!is_array($_instance)) {
- $_instance = array();
- }
- $dbConfName = 'default_db';
- if (is_numeric($db) && $db > 0) {
- $dbConfName = "zasob_{$db}";
- } else if ($db == 'import_db') {
- $dbConfName = "import_db";
- } else if ($db == 'test_db') {
- $dbConfName = "test_db";
- } else if ($db == 'test3_db') {
- $dbConfName = "test3_db";
- } else if ($db == 'billing_db') {
- $dbConfName = "billing_db";
- }
- if (!array_key_exists($dbConfName, $_instance)) {
- $_instance[$dbConfName] = null;
- Lib::loadClass('Config');
- $conf = Config::getConfFile($dbConfName);
- if ($conf) {
- $type = V::get('type', 'mysql', $conf);
- $host = V::get('host', '', $conf);
- $port = V::get('port', '', $conf);
- $user = V::get('user', '', $conf);
- $pass = V::get('pass', '', $conf);
- $zasob_id = V::get('zasob_id', '', $conf);
- $database = V::get('database', '', $conf);
- if ($port && $host) {
- $host .= ":{$port}";
- }
- $names = 'utf8';
- $db_class = 'Core_Database_' . ucfirst($type);
- Lib::loadClass($db_class);
- if (class_exists($db_class)) {
- $params = array();
- $tdsver = V::get('tdsver', '', $conf);
- if (!empty($tdsver)) {
- $params['tdsver'] = $tdsver;
- }
- if(!empty($zasob_id)) {
- $params['zasob_id'] = $zasob_id;
- }
- $_instance[$dbConfName] = new $db_class($host, $user, $pass, $database, $names, $params);
- }
- } else {
- trigger_error("Config file for db {$dbConfName} not exists!", E_USER_WARNING);
- }
- }
- return $_instance[$dbConfName];
- }
- public static function getStorage($db = null) {
- $pdo = self::getPDO($db);
- switch ($pdo->getType()) {
- case 'mysql':
- Lib::loadClass('Core_Storage_Mysql');
- return new Core_Storage_Mysql($pdo);
- case 'pgsql':
- Lib::loadClass('Core_Storage_Pgsql');
- return new Core_Storage_Pgsql($pdo);
- default: throw new Exception("Storage for type '{$this->_type}' not implemented");
- }
- }
- public static function getPDO($db = null) {
- static $_instance;
- if (!is_array($_instance)) $_instance = array();
- $zasob_id = '';
- $dbConfName = 'default_db';
- if (is_numeric($db) && $db > 0) {
- $zasob_id = $db;
- $dbConfName = "zasob_{$zasob_id}";
- } else if ($db == 'import_db') {
- $dbConfName = "import_db";
- } else if ($db == 'test_db') {
- $dbConfName = "test_db";
- } else if ($db == 'billing_db') {
- $dbConfName = "billing_db";
- } else if (!$db || 'default_db' == $db) {
- $dbConfName = 'default_db';
- } else {
- throw new Exception("Not implemented database '{$db}'");
- }
- if (!array_key_exists($dbConfName, $_instance)) {
- $_instance[$dbConfName] = null;
- Lib::loadClass('Config');
- $conf = Config::getConfFile($dbConfName);
- if (!$conf) throw new Exception("Config file for db {$dbConfName} not exists!");
- $type = V::get('type', 'mysql', $conf);
- $host = V::get('host', '', $conf);
- $port = V::get('port', '', $conf);
- $user = V::get('user', '', $conf);
- $pass = V::get('pass', '', $conf);
- $database = V::get('database', '', $conf);
- $zasob_id = V::get('zasob_id', $zasob_id, $conf);
- if (empty($host)) throw new Exception("Brak zdefiniowanego pola 'host' dla bazy danych '{$dbConfName}'");
- if (empty($user)) throw new Exception("Brak zdefiniowanego loginu usera dla bazy danych '{$dbConfName}'");
- if (empty($pass)) throw new Exception("Brak zdefiniowanego hasła usera dla bazy danych '{$dbConfName}'");
- if (empty($database)) throw new Exception("Brak zdefiniowane nazwy bazy danych dla '{$dbConfName}'");
- 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....) ");
- $options = array();
- if ($port && $host) $host .= ";port={$port}";
- $names = 'utf8';
- $tdsver = V::get('tdsver', '', $conf);
- if (!empty($tdsver)) $options['tdsver'] = $tdsver;
- $options['zasob_id'] = $zasob_id;
- if (!empty($database)) $options['database'] = $database;
- //$pdo = new PDO($type . ':host=' . $host . ';dbname=' . $database, $user, $pass);
- //$pdo->exec("SET NAMES 'utf8'");
- //$sdb = new Core_Pdo($pdo);
- $options['type'] = $type;
- $sdb = new Core_Pdo($type . ':host=' . $host . ';dbname=' . $database, $user, $pass, $options);
- $sdb->exec("SET NAMES 'utf8'");
- $_instance[$dbConfName] = $sdb;
- }
- return $_instance[$dbConfName];
- }
- public static function connect() {
- static $conn;
- if (!is_resource($conn)) {
- $db = self::getDB();
- if (!$db) {
- die('Config file for main DB not exists!');
- }
- $conn = $db->getConnection();
- }
- return $conn;
- }
- public static function transaction_start() {
- DB::query(" START TRANSACTION; ");
- }
- public static function transaction_commit() {
- DB::query(" COMMIT; ");
- }
- public static function transaction_rollback() {
- DB::query(" ROLLBACK; ");
- }
- public static function query($sql, $die_on_error = true) {
- $conn = self::connect();
- $res = mysql_query($sql, $conn);
- if (!$res) {
- if ($die_on_error) {
- trigger_error("query error: #".mysql_errno($conn).": ".mysql_error($conn)."\n $sql", E_USER_ERROR);
- die("ERROR DB: QUERY ERROR");
- } else {
- 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>';
- $null = null;
- return $null;
- }
- } else {
- return $res;
- }
- }
- public static function fetch($res) {
- $ret = null;
- if ($res) $ret = mysql_fetch_object($res);
- return $ret;
- }
- public static function fetch_row($res) {
- $ret = null;
- if ($res) $ret = mysql_fetch_row($res);
- return $ret;
- }
- public static function fetch_array($res) {
- $ret = null;
- if ($res) $ret = mysql_fetch_array($res);
- return $ret;
- }
- public static function fetch_assoc($res) {
- $ret = null;
- if ($res) $ret = mysql_fetch_assoc($res);
- return $ret;
- }
- public static function _($str) {
- //PHP >= 4.3.0; dodaje lewe ukoᄊniki (backslash) do nast↑pujᄆcych znakw: \x00, \n, \r, \, ', " and \x1a
- return mysql_real_escape_string($str, self::connect());
- }
- public static function error() {
- $conn = self::connect();
- return "#".mysql_errno($conn).": ".mysql_error($conn);
- }
- // Pobiera liczb↑ wierszy przetworzonych w ostatnim zapytaniu INSERT, UPDATE, REPLACE lub DELETE skojarzonym z identyfikator_poᄈᄆczenia.
- public static function affected_rows() {
- return mysql_affected_rows(self::connect());
- }
- // Zwraca ID wygenerowane dla pola z wᄈasnoᄊciᄆ AUTO_INCREMENT lub 0 jesli error
- public static function insert_id() {
- return mysql_insert_id(self::connect());
- }
- // Zwraca liczb↑ wierszy w wyniku. T↑ funkcj↑ stosuje si↑ tylko do operacji SELECT.
- public static function num_rows($res) {
- return mysql_num_rows($res);
- }
- public static function get_by_id($table, $id) {
- $null = null;
- $sql = "select p.*
- from `{$table}` as p
- where p.`ID`='{$id}'
- ";
- $res = DB::query($sql);
- if ($r = DB::fetch($res)) {
- return $r;
- }
- return $null;
- }
- /**
- * @returns int
- * 1 - changed but without add hist
- * 2 - changed and add hist
- * 0 - nothing to change
- * -1 - error ID not set
- * -2 - error id not exists in DB
- *
- * TODO: sprawdzac czy w hist mozna odczytac aktualny stan, jesli nie to dodac caly rekord do HIST, jako 'procesy-fix-hist-data'
- */
- public static function UPDATE_OBJ($table, &$sql_obj) {
- if (!isset($sql_obj->ID) || $sql_obj->ID <= 0) {
- return -1;
- }
- $id = $sql_obj->ID;
- // check id record $id exists
- if (($curr_obj = self::get_by_id($table, $sql_obj->ID)) == null) {
- return -2;
- }
- // check if enything changed
- $changed = false;
- $fields_to_change = get_object_vars($sql_obj);
- foreach ($fields_to_change as $k => $v) {
- if ($k == 'ID') continue;
- if ($v == $curr_obj->$k) {
- unset($sql_obj->$k);
- } else {
- $changed = true;
- }
- }
- if ($changed == false) {
- return 0;// record not changed
- }
- $sql_arr = array();
- // TODO: add admin columns if exists in table - search in session
- $admin_col = array();
- $admin_col[] = 'A_RECORD_CREATE_DATE';
- $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
- // ...
- $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
- $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
- foreach (get_object_vars($sql_obj) as $k => $v) {
- $sql_arr [] = "`".$k."`=".(($v == 'NOW()')? $v : "'".self::_($v)."'");//"'".self::_($v)."'";
- }
- $sql = "update `".$table."` set ".implode(",", $sql_arr)." where `ID`='".$id."' limit 1; ";
- self::query( $sql );
- $ret = self::affected_rows();
- if ($ret) {
- $sql_obj->ID_USERS2 = $id;
- unset($sql_obj->ID);
- $new_id = self::ADD_NEW_OBJ($table . '_HIST', $sql_obj);
- if ($new_id) {
- $ret += 1;
- }
- }
- return $ret;
- }
- public static function ADD_NEW_OBJ($table, &$sql_obj) {
- $sql_arr = array();
- // TODO: add admin columns if exists in table - search in session
- $admin_col = array();
- $admin_col[] = 'ID';
- $admin_col[] = 'A_RECORD_CREATE_DATE';
- $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
- $admin_col[] = 'A_RECORD_UPDATE_DATE';
- $admin_col[] = 'A_RECORD_UPDATE_AUTHOR';
- // ...
- $sql_arr["`ID`"] = "NULL";// add default value for ID, NULL in all inserts
- if (substr($table, 0, -5) == '_HIST') {
- $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
- $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
- } else {
- $sql_obj->A_RECORD_CREATE_DATE = date('Y-m-d-H:i');
- $sql_obj->A_RECORD_CREATE_AUTHOR = User::getName();
- }
- foreach (get_object_vars($sql_obj) as $k => $v) {
- $sql_arr ["`".$k."`"] = ($v == 'NOW()')? $v : "'".self::_($v)."'";
- }
- $sql = "insert into `".$table."` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr))."); ";
- self::query($sql);
- $ret_id = self::insert_id();
- if (substr($table, -5) == '_HIST') {
- return $ret_id;
- }
- if ($ret_id) {
- $sql_obj->ID_USERS2 = $ret_id;
- unset($sql_obj->ID);
- $new_id_hist = self::ADD_NEW_OBJ($table . '_HIST', $sql_obj);
- // error jesli nie udalo sie dodac rekordu do tabeli _HIST
- }
- return $ret_id;
- }
- }
|