private function __construct() { $connectionSettings = ConfigHandler::LoadConfigFile("db"); switch ($connectionSettings['type']) { case 'cassandra': require_once(ROOT_PDIR . 'core/libs/phpcassa-0.7.a.4/connection.php'); require_once(ROOT_PDIR . 'core/libs/core/ADODB_cassandra.class.php'); $this->connection = new ADODB_cassandra(); $this->connection->connect($connectionSettings['server'], null, null, $connectionSettings['name']); //var_dump($this->connection); die(); break; default: $dsn = "{$connectionSettings['type']}://" . "{$connectionSettings['user']}:{$connectionSettings['pass']}" . "@{$connectionSettings['server']}" . "/{$connectionSettings['name']}" . "?persist&fetchmode=ASSOC"; $this->connection =& ADONewConnection($dsn); break; } // No go? if (!$this->connection) return; // Caching? // @todo Make this a config option. //$this->connection->memCache = true; //$this->connection->memCacheHost = 'localhost'; //$this->connection->memCacheCompress = false; }
/** * Override the default `doquote` method to better sanitize numeric values. * * @param ADOConnection $db * @param mixed $value * @param string $type * @return mixed */ public function doquote(&$db, $value, $type) { switch ($type) { case 'L': case 'I': case 'I1': case 'I2': case 'I4': case 'I8': case 'F': case 'N': if (!is_numeric($value)) { if (is_null($value)) { return null; } if ($value === true) { return 1; } if ($value === false) { return 0; } $db->outp_throw('Numeric field type "' . $type . '" requires numeric value.', 'DOQUOTE'); return 0; } default: return parent::doquote($db, $value, $type); } }
/** * Constructor * * @param ADOConnection $db An instance of ADOConnection. * * @throws XML_Query2XML_DBException If the ADOConnection instance passed as * argument was not connected to the database server. */ public function __construct(ADOConnection $db) { if (!$db->IsConnected()) { throw new XML_Query2XML_DBException('ADOConnection instance was not connected'); } $db->SetFetchMode(ADODB_FETCH_ASSOC); $this->_db = $db; }
function __construct($type, $host, $user, $pass, $db, $debug) { $this->_adoConnection = NewADOConnection($type); $this->_adoConnection->debug = $debug; $status = $this->_adoConnection->Connect($host, $user, $pass, $db); if (!$status) { throw new Exception("Không kết nối được CSDL"); } $this->_adoConnection->SetCharSet('utf8'); $this->_adoConnection->SetFetchMode(ADODB_FETCH_ASSOC); }
function DropColumnSQL($tabname, $flds) { if ($this->debug) { ADOConnection::outp("DropColumnSQL not supported"); } return array(); }
public function DropColumnSQL($tabname, $flds, $tableflds = '', $tableoptions = '') { if ($this->debug) { ADOConnection::outp("DropColumnSQL not supported"); } return array(); }
function BindTimeStamp($d) { $d = ADOConnection::DBTimeStamp($d); if (strncmp($d,"'",1)) return $d; return substr($d,1,strlen($d)-2); }
function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $arg3 = false, $secs2cache = 0) { if (!preg_match('/ORDER[ \\t\\r\\n]+BY/is', $sql)) { $sql .= ' ORDER BY 1'; } return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $arg3, $secs2cache); }
/** * Sends the sql to the database and returns the results. * * @internal Switches between ADOConnection::Execute() and * ADOConnection::SelectLimit() depending on the $query parameter's * $solutionModifier "limit" and "offset" settings. * Uses $query variable. * * @param array $arSql Array that gets a SQL query string once imploded * * @return mixed Anything ADOConnection::Execute() may return * @throws Exception If Database query does not work */ function queryDb($arSql, $nOffset, $nLimit) { $strSql = SparqlEngineDb_SqlMerger::getSelect($this->query, $arSql); if ($strSql == '()') { return new ADORecordSet(false); } // I want associative arrays. $oldmode = $this->dbConn->SetFetchMode(ADODB_FETCH_ASSOC); if (isset($GLOBALS['debugSparql']) && $GLOBALS['debugSparql']) { echo 'SQL query: ' . $strSql . "\n"; } if ($nLimit === null && $nOffset == 0) { $ret = $this->dbConn->execute($strSql); } else { if ($nLimit === null) { $ret = $this->dbConn->SelectLimit($strSql, -1, $nOffset); } else { $ret = $this->dbConn->SelectLimit($strSql, $nLimit, $nOffset); } } //... but others maybe not $this->dbConn->SetFetchMode($oldmode); if (!$ret) { //Error occured throw new Exception('ADOdb error: ' . $this->dbConn->ErrorMsg() . "\n" . $strSql); } return $ret; }
public function PrepareSP($sql) { if (!$this->_has_mssql_init) { ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0"); return $sql; } if (is_string($sql)) $sql = str_replace('||','+',$sql); $stmt = mssql_init($sql,$this->_connectionID); if (!$stmt) return $sql; return array($sql,$stmt); }
/** * Fonction static permettant d'obtenir la séquence suivante * * @name DbSequence::next() * * @access public * @static * @param ADOConnection $conn Connexion valide à une base de données * @param string $table Table sur laquelle on doit obtenir la sequence suivante * @param string $column Nom de la colonne Primary Key de type numerique * * @return int Numero de séquence suivante */ public static function next(ADOConnection $conn, $table, $column) { try { $sql = "SELECT {$column} FROM {$table} ORDER BY 1 DESC"; $rs = $conn->SelectLimit($sql, 1); // Si il n'y a aucun enregistrement : insertion du premier if ($rs->RecordCount() == 0) { $id = 1; } else { while (!$rs->EOF) { $id = $rs->fields[0]; break; } $id++; } } catch (exception $e) { return null; } return $id; }
/** * Remove right * * @param array $params * @return void */ public function removeRight(array $params) { $rightId = (int) $params['right_id']; // get permission $sql = 'SELECT right_define_name FROM ' . self::RIGHTS . "\n WHERE right_id = {$rightId}"; $permission = $this->db->GetOne($sql); // remove acl rules try { list($resource, ) = PermissionToAcl::translate($permission); } catch (\InvalidArgumentException $e) { return; } $sql = 'DELETE FROM ' . self::RULES . "\n WHERE resource = '{$resource}'"; $this->db->Execute($sql); // remove right $sql = 'DELETE FROM ' . self::RIGHTS . "\n WHERE right_id = {$rightId}"; $this->db->Execute($sql); }
function MetaTables($ttype = false, $showSchema = false, $mask = false) { if ($mask) { $save = $this->metaTablesSQL; $mask = $this->qstr(strtoupper($mask)); $this->metaTablesSQL .= " AND table_name like {$mask}"; } $ret = ADOConnection::MetaTables($ttype, $showSchema); if ($mask) { $this->metaTablesSQL = $save; } return $ret; }
function &MetaTables($ttype = false, $showSchema = false, $mask = false) { if ($mask) { $save = $this->metaTablesSQL; $mask = $this->qstr($mask); $this->metaTablesSQL .= " like {$mask}"; } $ret =& ADOConnection::MetaTables($ttype, $showSchema); if ($mask) { $this->metaTablesSQL = $save; } return $ret; }
function MetaTables($ttype = false, $showSchema = false, $mask = false) { $save = $this->metaTablesSQL; if ($showSchema && is_string($showSchema)) { $this->metaTablesSQL .= " from {$showSchema}"; } if ($mask) { $mask = $this->qstr($mask); $this->metaTablesSQL .= " like {$mask}"; } $ret = ADOConnection::MetaTables($ttype, $showSchema); $this->metaTablesSQL = $save; return $ret; }
function ServerInfo() { $arr['dialect'] = $this->dialect; switch($arr['dialect']) { case '': case '1': $s = 'Firebird Dialect 1'; break; case '2': $s = 'Firebird Dialect 2'; break; default: case '3': $s = 'Firebird Dialect 3'; break; } $arr['version'] = ADOConnection::_findvers($s); $arr['description'] = $s; return $arr; }
function MetaTables($ttype = false, $showSchema = false, $mask = false) { $save = $this->metaTablesSQL; if ($showSchema && is_string($showSchema)) { $this->metaTablesSQL .= $this->qstr($showSchema); } else { $this->metaTablesSQL .= "schema()"; } if ($mask) { $mask = $this->qstr($mask); $this->metaTablesSQL .= " AND table_name LIKE {$mask}"; } $ret = ADOConnection::MetaTables($ttype, $showSchema); $this->metaTablesSQL = $save; return $ret; }
function ErrorNo() { if ($this->_haserrorfunctions) { if (empty($this->_connectionID)) { $e = @odbc_error(); } else { $e = @odbc_error($this->_connectionID); } // bug in 4.0.6, error number can be corrupted string (should be 6 digits) // so we check and patch if (strlen($e) <= 2) { return 0; } return $e; } else { return ADOConnection::ErrorNo(); } }
function _connect($host, $username, $password, $ldapbase) { global $LDAP_CONNECT_OPTIONS; if (!function_exists('ldap_connect')) { return null; } if (strpos($host, 'ldap://') === 0 || strpos($host, 'ldaps://') === 0) { $this->_connectionID = @ldap_connect($host); } else { $conn_info = array($host, $this->port); if (strstr($host, ':')) { $conn_info = explode(':', $host); } $this->_connectionID = @ldap_connect($conn_info[0], $conn_info[1]); } if (!$this->_connectionID) { $e = 'Could not connect to ' . $conn_info[0]; $this->_errorMsg = $e; if ($this->debug) { ADOConnection::outp($e); } return false; } if (count($LDAP_CONNECT_OPTIONS) > 0) { $this->_inject_bind_options($LDAP_CONNECT_OPTIONS); } if ($username) { $bind = @ldap_bind($this->_connectionID, $username, $password); } else { $username = '******'; $bind = @ldap_bind($this->_connectionID); } if (!$bind) { $e = sprintf($this->_bind_errmsg, ldap_error($this->_connectionID)); $this->_errorMsg = $e; if ($this->debug) { ADOConnection::outp($e); } return false; } $this->_errorMsg = ''; $this->database = $ldapbase; return $this->_connectionID; }
function SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { // seems that oracle only supports 1 hint comment in 8i if (strpos($sql, '/*+') !== false) { $sql = str_replace('/*+ ', '/*+FIRST_ROWS ', $sql); } else { $sql = preg_replace('/^[ \\t\\n]*select/i', 'SELECT /*+FIRST_ROWS*/', $sql); } /* The following is only available from 8.1.5 because order by in inline views not available before then... http://www.jlcomp.demon.co.uk/faq/top_sql.html if ($nrows > 0) { if ($offset > 0) $nrows += $offset; $sql = "select * from ($sql) where rownum <= $nrows"; $nrows = -1; } */ return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); }
public function _connect( $host, $username, $password, $ldapbase) { global $LDAP_CONNECT_OPTIONS; if ( !function_exists( 'ldap_connect' ) ) return null; $conn_info = array( $host,$this->port); if ( strstr( $host, ':' ) ) { $conn_info = split( ':', $host ); } $this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] ); if (!$this->_connectionID) { $e = 'Could not connect to ' . $conn_info[0]; $this->_errorMsg = $e; if ($this->debug) ADOConnection::outp($e); return false; } if( count( $LDAP_CONNECT_OPTIONS ) > 0 ) { $this->_inject_bind_options( $LDAP_CONNECT_OPTIONS ); } if ($username) { $bind = ldap_bind( $this->_connectionID, $username, $password ); } else { $username = '******'; $bind = ldap_bind( $this->_connectionID ); } if (!$bind) { $e = 'Could not bind to ' . $conn_info[0] . " as ".$username; $this->_errorMsg = $e; if ($this->debug) ADOConnection::outp($e); return false; } $this->_errorMsg = ''; $this->database = $ldapbase; return $this->_connectionID; }
/** * Метод получения коннекта к БД * * @return ADOConnection */ protected final function getConnection() { if ($this->CONNECTION != null) { return $this->CONNECTION; //--- } if (!$this->isConfigured()) { PsUtil::raise('Cannot get DB connection, {} is not configured.', get_called_class()); } $this->LOGGER->info(); $this->LOGGER->info('? Connection for [{}] is requested', $this->CONNECTION_PARAMS); $URL = $this->CONNECTION_PARAMS->url(); //Посмотрим, есть ли у нас нужный коннект if (array_key_exists($URL, $this->CONNECTIONS)) { $this->LOGGER->info('< Fast returned from cache'); return $this->CONNECTION = $this->CONNECTIONS[$URL]; } //Отлогируем $this->LOGGER->info('+ Establishing connection {}', $this->CONNECTION_PARAMS); //Подключаем adodb PsLibs::inst()->AdoDb(); //Подключаемся $this->CONNECTION = ADONewConnection($URL); if (!is_object($this->CONNECTION)) { PsUtil::raise("Unable to connect to [{}]", $this->CONNECTION_PARAMS); } //Зададим некоторые настройки $this->CONNECTION->debug = ADODB_DEBUG; $this->CONNECTION->SetFetchMode(ADODB_FETCH_ASSOC); $this->CONNECTION->query("SET NAMES 'utf8'"); $this->CONNECTION->query("SET CHARACTER SET 'utf8'"); //Положим соединение в пул if (array_key_exists($URL, $this->CONNECTIONS)) { raise_error('Double trying to register db connection'); } $this->LOGGER->info('< Established connection returned'); return $this->CONNECTIONS[$URL] = $this->CONNECTION; }
/** * @see adodb_perf#optimizeTable */ function optimizeTable($table, $mode = ADODB_OPT_LOW) { if (!is_string($table)) { return false; } $conn = $this->conn; if (!$conn) { return false; } $sql = ''; switch ($mode) { case ADODB_OPT_LOW: $sql = $this->optimizeTableLow; break; case ADODB_OPT_HIGH: $sql = $this->optimizeTableHigh; break; default: ADOConnection::outp(sprintf("<p>%s: '%s' using of undefined mode '%s'</p>", __CLASS__, 'optimizeTable', $mode)); return false; } $sql = sprintf($sql, $table); return $conn->Execute($sql) !== false; }
function ServerInfo() { global $ADODB_FETCH_MODE; $this->debug = 1; $stmt = $this->PrepareSP('sp_server_info'); $val = 2; if ($this->fetchMode === false) { $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; } else { $savem = $this->SetFetchMode(ADODB_FETCH_NUM); } $this->Parameter($stmt, $val, 'attribute_id'); $row = $this->GetRow($stmt); //$row = $this->GetRow("execute sp_server_info 2"); if ($this->fetchMode === false) { $ADODB_FETCH_MODE = $savem; } else { $this->SetFetchMode($savem); } $arr['description'] = $row[2]; $arr['version'] = ADOConnection::_findvers($arr['description']); return $arr; }
/** * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format * * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format */ function UnixTimeStamp($v) { return ADOConnection::UnixTimeStamp($v); }
function _fetch() { $rs = $this->_queryID; if (!$rs or $rs->EOF) { $this->fields = false; return false; } $this->fields = array(); if (!$this->_tarr) { $tarr = array(); $flds = array(); for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) { $f = $rs->Fields($i); $flds[] = $f; $tarr[] = $f->Type; } // bind types and flds only once $this->_tarr = $tarr; $this->_flds = $flds; } $t = reset($this->_tarr); $f = reset($this->_flds); if ($this->hideErrors) { $olde = error_reporting(E_ERROR | E_CORE_ERROR); } // sometimes $f->value be null for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) { //echo "<p>",$t,' ';var_dump($f->value); echo '</p>'; switch ($t) { case 135: // timestamp if (!strlen((string) $f->value)) { $this->fields[] = false; } else { if (!is_numeric($f->value)) { $val = variant_date_to_timestamp($f->value); } else { $val = $f->value; } $this->fields[] = adodb_date('Y-m-d H:i:s', $val); } break; case 133: // A date value (yyyymmdd) if ($val = $f->value) { $this->fields[] = substr($val, 0, 4) . '-' . substr($val, 4, 2) . '-' . substr($val, 6, 2); } else { $this->fields[] = false; } break; case 7: // adDate if (!strlen((string) $f->value)) { $this->fields[] = false; } else { if (!is_numeric($f->value)) { $val = variant_date_to_timestamp($f->value); } else { $val = $f->value; } if ($val % 86400 == 0) { $this->fields[] = adodb_date('Y-m-d', $val); } else { $this->fields[] = adodb_date('Y-m-d H:i:s', $val); } } break; case 1: // null $this->fields[] = false; break; case 6: // currency is not supported properly; ADOConnection::outp('<b>' . $f->Name . ': currency type not supported by PHP</b>'); $this->fields[] = (double) $f->value; break; default: $this->fields[] = $f->value; break; } //print " $f->value $t, "; $f = next($this->_flds); $t = next($this->_tarr); } // for if ($this->hideErrors) { error_reporting($olde); } @$rs->MoveNext(); // @ needed for some versions of PHP! if ($this->fetchMode & ADODB_FETCH_ASSOC) { $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE); } return true; }
function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { if ($nrows > 0 && $offset <= 0) { $sql = preg_replace('/(^\\s*select\\s+(distinctrow|distinct)?)/i', '\\1 ' . $this->hasTop . " {$nrows} ", $sql); $rs =& $this->Execute($sql, $inputarr); } else { $rs =& ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); } return $rs; }
function ErrorNo() { $e = $this->ErrorMsg(); if (strlen($e)) { return ADOConnection::MetaError($e); } return 0; }
/** * Save a file $filename and its $contents (normally for caching) with file locking */ function adodb_write_file($filename, $contents, $debug = false) { # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows # So to simulate locking, we assume that rename is an atomic operation. # First we delete $filename, then we create a $tempfile write to it and # rename to the desired $filename. If the rename works, then we successfully # modified the file exclusively. # What a stupid need - having to simulate locking. # Risks: # 1. $tempfile name is not unique -- very very low # 2. unlink($filename) fails -- ok, rename will fail # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated if (strncmp(PHP_OS, 'WIN', 3) === 0) { // skip the decimal place $mtime = substr(str_replace(' ', '_', microtime()), 2); // getmypid() actually returns 0 on Win98 - never mind! $tmpname = $filename . uniqid($mtime) . getmypid(); if (!($fd = @fopen($tmpname, 'a'))) { return false; } $ok = ftruncate($fd, 0); if (!fwrite($fd, $contents)) { $ok = false; } fclose($fd); chmod($tmpname, 0644); // the tricky moment @unlink($filename); if (!@rename($tmpname, $filename)) { unlink($tmpname); $ok = false; } if (!$ok) { if ($debug) { ADOConnection::outp(" Rename {$tmpname} " . ($ok ? 'ok' : 'failed')); } } return $ok; } if (!($fd = @fopen($filename, 'a'))) { return false; } if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) { $ok = fwrite($fd, $contents); fclose($fd); chmod($filename, 0644); } else { fclose($fd); if ($debug) { ADOConnection::outp(" Failed acquiring lock for {$filename}<br>\n"); } $ok = false; } return $ok; }
function Error($err, $fn) { global $_ADODB_ACTIVE_DBS; $fn = get_class($this) . '::' . $fn; $this->_lasterr = $fn . ': ' . $err; if ($this->_dbat < 0) { $db = false; } else { $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat]; $db = $activedb->db; } if (function_exists('adodb_throw')) { if (!$db) { adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false); } else { adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db); } } else { if (!$db || $db->debug) { ADOConnection::outp($this->_lasterr); } } }