/** * A factory method which returns the currently supported best advisory lock * instance. * * @return OA_DB_AdvisoryLock Reference to an OA_DB_AdvisoryLock object. */ function &factory($sType = null) { if (is_null($sType)) { $oDbh =& OA_DB::singleton(); if (PEAR::isError($oDbh)) { OA::debug('Error connecting to database to obtain locking object. Native error follows:', PEAR_LOG_ERR); OA::debug($oDbh, PEAR_LOG_ERR); OA::debug('Will re-try connection...', PEAR_LOG_ERR); $retryCount = 0; while (PEAR::isError($oDbh) && $retryCount < 6) { $retryCount++; sleep(10); OA::debug('Re-try connection attempt #' . $retryCount, PEAR_LOG_ERR); $oDbh =& OA_DB::singleton(); } if (PEAR::isError($oDbh)) { OA::debug('Failed in re-try attempts to connect to database. Aborting.', PEAR_LOG_CRIT); exit; } } $aDsn = MDB2::parseDSN($oDbh->getDSN()); $sType = $aDsn['phptype']; } include_once MAX_PATH . '/lib/OA/DB/AdvisoryLock/' . $sType . '.php'; $sClass = "OA_DB_AdvisoryLock_" . $sType; $oLock = new $sClass(); if (!$oLock->_isLockingSupported()) { // Fallback to file based locking if the current class won't work $oLock =& OA_DB_AdvisoryLock::factory('file'); } return $oLock; }
static function sanitizeDb($db) { if (is_string($db)) { require_once 'MDB2.php'; // $dsn = MDB2::parseDSN($db); $db = MDB2::connect($db); } else { if (is_object($db) && is_subclass_of($db, 'MDB2_Driver_Common')) { /* MDB2 driver */ } else { if (is_array($db) && count(array_diff(array(0, 1, 2, 3, 4), array_keys($db))) == 0) { $dsnString = $db[0] . '://' . $db[2] . ':' . $db[3] . '@' . $db[1] . '/' . $db[4]; $db = MDB2::connect($dsnString); } else { if (is_array($db) && array_key_exists('phptype', $db)) { $db = MDB2::connect($db); } else { throw new Exception('Invalid database'); } } } } $dsn = MDB2::parseDSN($db->dsn); if (!$dsn['database']) { // sometimes the database name is not set here, so try to recover $dsn['database'] = $db->database_name; } return array($db, $dsn); }
/** * The 'starter' = call this to start the process * * @access public * @return none */ function start() { $options =& PEAR::getStaticProperty('DB_DataObject', 'options'); $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver']; $databases = array(); foreach ($options as $k => $v) { if (substr($k, 0, 9) == 'database_') { $databases[substr($k, 9)] = $v; } } if (isset($options['database'])) { if ($db_driver == 'DB') { require_once 'DB.php'; $dsn = DB::parseDSN($options['database']); } else { require_once 'MDB2.php'; $dsn = MDB2::parseDSN($options['database']); } if (!isset($database[$dsn['database']])) { $databases[$dsn['database']] = $options['database']; } } foreach ($databases as $databasename => $database) { if (!$database) { continue; } $this->debug("CREATING FOR {$databasename}\n"); $class = get_class($this); $t = new $class(); $t->_database_dsn = $database; $t->_database = $databasename; if ($db_driver == 'DB') { require_once 'DB.php'; $dsn = DB::parseDSN($database); } else { require_once 'MDB2.php'; $dsn = MDB2::parseDSN($database); } if ($dsn['phptype'] == 'sqlite' && is_file($databasename)) { $t->_database = basename($t->_database); } $t->_createTableList(); foreach (get_class_methods($class) as $method) { if (substr($method, 0, 8) != 'generate') { continue; } $this->debug("calling {$method}"); $t->{$method}(); } } $this->debug("DONE\n\n"); }
/** * Compare the local database schema with the reference schema * required for this version of Roundcube * * @param boolean True if the schema schould be updated * @return boolean True if the schema is up-to-date, false if not or an error occured */ function mdb2_schema_check($update = false) { if (!$this->configured) { return false; } $options = array('use_transactions' => false, 'log_line_break' => "\n", 'idxname_format' => '%s', 'debug' => false, 'quote_identifier' => true, 'force_defaults' => false, 'portability' => true); $dsnw = $this->config['db_dsnw']; $schema = MDB2_Schema::factory($dsnw, $options); $schema->db->supported['transactions'] = false; if (PEAR::isError($schema)) { $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo())); return false; } else { $definition = $schema->getDefinitionFromDatabase(); $definition['charset'] = 'utf8'; if (PEAR::isError($definition)) { $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo())); return false; } // load reference schema $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']); $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml'; if (is_readable($ref_schema)) { $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']); if (PEAR::isError($reference)) { $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo())); } else { $diff = $schema->compareDefinitions($reference, $definition); if (empty($diff)) { return true; } else { if ($update) { // update database schema with the diff from the above check $success = $schema->alterDatabase($reference, $definition, $diff); if (PEAR::isError($success)) { $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo())); } else { return true; } } } echo '<pre>'; var_dump($diff); echo '</pre>'; return false; } } else { $this->raise_error(array('message' => "Could not find reference schema file ({$ref_schema})")); } return false; } return false; }
/** * DB::parseDSN() */ public static function parseDSN($dsn) { return MDB2::parseDSN($dsn); }
public function addFile($filename) { if ($this->db_type === null) { $dsn_info = MDB2::parseDSN($this->dsn); $this->db_type = $this->db_types[$dsn_info['phptype']]; } $pattern = '/^\\.?[^\\.]+(\\.' . $this->db_type . ')?\\.sql$/'; // use only the files with the specific extension and the generic files if (preg_match($pattern, $filename)) { echo "Adding file ", $filename, "\n"; $file = new CreationFile($filename); $objects = $file->getObjects(); foreach (array_keys($objects) as $object) { echo ' ' . $object . "\n"; } $this->objects = array_merge($this->objects, $objects); } }
/** * A method to return a singleton database connection resource. * * Example usage: * $oDbh = OA_DB::singleton(); * * Warning: In order to work correctly, the singleton method must * be instantiated statically and by reference, as in the above * example. * * @static * @param string $dsn Optional database DSN details - connects to the * database defined by the configuration file otherwise. * See {@link OA_DB::getDsn()} for format. * * @param array $aDriverOptions An optional array of driver options. Currently * supported options are: * - For MySQL: * ['ssl'] = false|true Perform connection over SSL? * ['ca'] = Name of CA file, if "ssl" true * ['capath'] = Path to CA file above, is "ssl" true * ['compress'] = false|true Use client compression? * * @return MDB2_Driver_Common An MDB2 connection resource, or PEAR_Error * on failure to connect. */ static function singleton($dsn = null, $aDriverOptions = array()) { $aConf = $GLOBALS['_MAX']['CONF']; // Get the driver options, if not set if (!is_array($aDriverOptions) || is_null($dsn) && empty($aDriverOptions)) { $aDriverOptions = OA_DB::getDsnOptions(); } // Get the DSN, if not set $dsn = is_null($dsn) ? OA_DB::getDsn() : $dsn; // Check that the parameter is a string, not an array if (is_array($dsn)) { return Max::raiseError('Bad argument: DSN should be a string', MAX_ERROR_INVALIDARGS); } // A hack to allow for installation on pgsql // If the configuration hasn't been defined prevent // loading mysql MDB2 driver. if (strpos($dsn, '//:@') !== false) { // Return a silent error return new PEAR_Error('Bad argument: Empty DSN'); } // Get the database type in use from the DNS, not from the // configuration file $aDSN = MDB2::parseDSN($dsn); $databaseType = $aDSN['phptype']; // Is this a MySQL database connection that should happen via SSL? if (strcasecmp($databaseType, 'mysql') === 0 && @$aDriverOptions['ssl']) { // Modify the DSN string to include the required CA and CAPATH options if (!empty($aDriverOptions['ca']) && !empty($aDriverOptions['capath'])) { $dsn .= "?ca={$aDriverOptions['ca']}&capth={$aDriverOptions['capath']}"; } } // Create an MD5 checksum of the DSN $dsnMd5 = md5($dsn); // Does this database connection already exist? if (isset($GLOBALS['_OA']['CONNECTIONS'])) { $aConnections = array_keys($GLOBALS['_OA']['CONNECTIONS']); } else { $aConnections = array(); } if (!(count($aConnections) > 0) || !in_array($dsnMd5, $aConnections)) { // Prepare options for a new database connection $aOptions = array(); // Sequence column name $aOptions['seqcol_name'] = 'id'; // Set the index name format $aOptions['idxname_format'] = '%s'; // Use 4 decimal places in DECIMAL nativetypes $aOptions['decimal_places'] = 4; // Set the portability options $aOptions['portability'] = OA_DB_MDB2_DEFAULT_OPTIONS; // Set the default table type for MySQL, if appropriate if (strcasecmp($databaseType, 'mysql') === 0) { if (!empty($aConf['table']['type'])) { $aOptions['default_table_type'] = $aConf['table']['type']; // Enable transaction support when using InnoDB tables if (strcasecmp($aOptions['default_table_type'], 'innodb') === 0) { // Enable transaction support $aOptions['use_transactions'] = true; } } } elseif (strcasecmp($databaseType, 'pgsql') === 0) { $aOptions['quote_identifier'] = true; } // Add default charset - custom OpenX if (defined('OA_DB_MDB2_DEFAULT_CHARSET')) { $aOptions['default_charset'] = OA_DB_MDB2_DEFAULT_CHARSET; } else { $aOptions['default_charset'] = 'utf8'; } // this will log select queries to a var/sql.log // currently used for analysis purposes if (isset($aConf['debug']['logSQL']) && $aConf['debug']['logSQL']) { $aOptions['log_statements'] = explode('|', $aConf['debug']['logSQL']); $aOptions['debug'] = true; $aOptions['debug_handler'] = 'logSQL'; } $aOptions += OA_DB::getDatatypeMapOptions(); // Is this a MySQL database connection? if (strcasecmp($databaseType, 'mysql') === 0) { // Should this connection happen over SSL? if (@$aDriverOptions['ssl']) { $aOptions['ssl'] = true; } } // Create the new database connection OA::disableErrorHandling(); $oDbh = MDB2::singleton($dsn, $aOptions); OA::enableErrorHandling(); if (PEAR::isError($oDbh)) { return $oDbh; } // Is this a MySQL database connection? if (strcasecmp($databaseType, 'mysql') === 0) { $client_flags = 0; // Should this connection happen over SSL? if (@$aDriverOptions['ssl']) { $client_flags = $client_flags | MYSQL_CLIENT_SSL; } // Should this connection use compression? if (@$aDriverOptions['compress']) { $client_flags = $client_flags | MYSQL_CLIENT_COMPRESS; } // Are there any MySQL connection flags to set? if ($client_flags != 0) { $oDbh->dsn['client_flags'] = $client_flags; } } OA::disableErrorHandling(); $success = $oDbh->connect(); OA::enableErrorHandling(); if (PEAR::isError($success)) { return $success; } // Set charset if needed $success = OA_DB::setCharset($oDbh); if (PEAR::isError($success)) { return $success; } // Set schema if needed $success = OA_DB::setSchema($oDbh); if (PEAR::isError($success)) { return $success; } // Set the fetchmode to be use used $oDbh->setFetchMode(MDB2_FETCHMODE_ASSOC); // Load modules that are likely to be needed $oDbh->loadModule('Extended'); $oDbh->loadModule('Datatype'); $oDbh->loadModule('Manager'); // Store the database connection $GLOBALS['_OA']['CONNECTIONS'][$dsnMd5] = $oDbh; // Set MySQL 4 compatibility if needed if (strcasecmp($databaseType, 'mysql') === 0 && !empty($aConf['database']['mysql4_compatibility'])) { $oDbh->exec("SET SESSION sql_mode='MYSQL40'"); } } return $GLOBALS['_OA']['CONNECTIONS'][$dsnMd5]; }
function testParseDSN() { $expected = array('phptype' => 'phptype', 'dbsyntax' => 'phptype', 'username' => 'username', 'password' => 'password', 'protocol' => 'protocol', 'hostspec' => false, 'port' => '110', 'socket' => false, 'database' => '/usr/db_file.db', 'mode' => '0644'); $original = 'phptype://*****:*****@protocol+hostspec:110//usr/db_file.db?mode=0644'; $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- $original = 'phptype(dbsyntax)://username:password@hostspec/database_name'; $expected = array('phptype' => 'phptype', 'dbsyntax' => 'dbsyntax', 'username' => 'username', 'password' => 'password', 'protocol' => 'tcp', 'hostspec' => 'hostspec', 'port' => false, 'socket' => false, 'database' => 'database_name', 'mode' => false); $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- $original = 'phptype://*****:*****@hostspec/database_name'; $expected['dbsyntax'] = 'phptype'; $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- $original = 'phptype://*****:*****@hostspec'; $expected['database'] = false; $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- $original = 'phptype://username@hostspec'; $expected['password'] = false; $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- $original = 'phptype://hostspec/database'; $expected['username'] = false; $expected['database'] = 'database'; $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- $original = 'phptype(dbsyntax)'; $expected['database'] = false; $expected['hostspec'] = false; $expected['protocol'] = false; $expected['dbsyntax'] = 'dbsyntax'; $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- //oracle's "Easy Connect" syntax (Oracle 10g, @see Bug #4854) $original = 'oci8://scott:tiger@//localhost/XE'; $expected = array('phptype' => 'oci8', 'dbsyntax' => 'oci8', 'username' => 'scott', 'password' => 'tiger', 'protocol' => 'tcp', 'hostspec' => '//localhost', 'port' => false, 'socket' => false, 'database' => 'XE', 'mode' => false); $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- //ibase dbname+path on windows $original = 'ibase://*****:*****@localhost/C:\\PATH_TO_DB\\TEST.FDB'; $expected = array('phptype' => 'ibase', 'dbsyntax' => 'ibase', 'username' => 'user', 'password' => 'pwd', 'protocol' => 'tcp', 'hostspec' => 'localhost', 'port' => false, 'socket' => false, 'database' => 'C:\\PATH_TO_DB\\TEST.FDB', 'mode' => false); $this->assertEquals($expected, MDB2::parseDSN($original)); // --------------------------------------------------------------------- //sqlite dbname+path on unix $original = 'sqlite:////full/unix/path/to/file.db?mode=0666'; $expected = array('phptype' => 'sqlite', 'dbsyntax' => 'sqlite', 'username' => false, 'password' => false, 'protocol' => 'tcp', 'hostspec' => '', 'port' => false, 'socket' => false, 'database' => '/full/unix/path/to/file.db', 'mode' => '0666'); $this->assertEquals($expected, MDB2::parseDSN($original)); }
/** * set the DSN * * @param mixed $dsn DSN string or array * @return MDB2_OK * @access public */ function setDSN($dsn) { $dsn_default = array('phptype' => false, 'dbsyntax' => false, 'username' => false, 'password' => false, 'protocol' => false, 'hostspec' => false, 'port' => false, 'socket' => false, 'mode' => false); $dsn = MDB2::parseDSN($dsn); if (isset($dsn['database'])) { $this->database_name = $dsn['database']; unset($dsn['database']); } $this->dsn = array_merge($dsn_default, $dsn); return MDB2_OK; }
/** * generate() * @access public * @return DB_DataObject_Advgenerator instance including tables list for $databasename **/ public function generate($database = null, $databasename = null, $db_driver = null) { $this->debug("CREATING FOR {$databasename}\n"); $class = get_class($this); $t = new $class(); $t->_database_dsn = $database; $t->_database = $databasename; if ($db_driver == 'DB') { $dsn = DB::parseDSN($database); } else { $dsn = MDB2::parseDSN($database); } if ($dsn['phptype'] == 'sqlite' && is_file($databasename)) { $t->_database = basename($t->_database); } $t->_createTableList(); return $t; }
public function _dobackup($filename, $db_uri_constant = null) { if (!is_null($db_uri_constant)) { if (!defined($db_uri_constant)) { return $this->error($db_uri_constant . ' not defined as a Database constant'); } $info = MDB2::parseDSN(constant($db_uri_constant)); $h = $info['hostspec']; $u = $info['username']; $p = $info['password']; $dbn = $info['database']; } else { $opt = PEAR::getStaticProperty('DB_DataObject', 'options'); $db = MDB2::singleton($opt['database']); $h = $db->dsn['hostspec']; $u = $db->dsn['username']; $p = $db->dsn['password']; $dbn = $db->database_name; } if (empty($filename)) { $filename = $dbn . "_" . date('Y-m-d'); } $com = "/usr/bin/env mysqldump --host={$h} --user={$u} --password={$p} {$dbn} > " . APP_ROOT . "backups/" . $filename . ".sql;gzip " . APP_ROOT . "backups/" . $filename . ".sql"; $this->line('executing SH:'); $this->line($com); passthru($com); $this->line('Backup done : ' . $filename . '.sql.gz'); }
function get_catalog($reply, &$mdb2) { global $catalog; if (!$catalog) { $res = MDB2::parseDSN($_SESSION['dsn']); handle_pear_error($res, $reply); $catalog = $res['database']; } return $catalog; }
/** * Gets the core system going. * @param string $dsn dsn string to connect to the database * @param string $user_access_init the init string for the user access mechanism * @param string $site_module_file the configttion file for the site module * @returns boolean. True on sucess */ public static function initializeDSN($dsn, $user_access_init, $site_module_file, $bring_up_system = true) { if (empty($dsn)) { self::raiseError("Please set the dsn string", E_USER_ERROR); if (!array_key_exists('HTTP_HOST', $_SERVER)) { //command line exit(11); } else { return false; } } $mdb2 = new MDB2(); $dsn_info = $mdb2->parseDSN($dsn); if (I2CE_Dumper::dumpStaticURL($dsn_info['database'], 'file')) { exit; } if (!self::dbConnect($dsn_info)) { self::raiseError("Could not connect to the database"); if (!array_key_exists('HTTP_HOST', $_SERVER)) { //command line exit(13); } else { return false; } } self::setupSession(); $clear = false; if (!array_key_exists('HTTP_HOST', $_SERVER)) { //command line $clear = self::getRuntimeVariable('clear_cache', '0'); } else { $URL = self::getAccessedBaseURL(false) . 'clear_cache.php'; $clear = substr($_SERVER['REQUEST_URI'], 0, strlen($URL)) == $URL; } if ($clear) { $config = self::setupMagicData(); $config->setIfIsSet(self::$email, "/I2CE/feedback/to"); session_destroy(); if (function_exists('apc_clear_cache')) { apc_clear_cache('user'); I2CE::raiseError("Cleared APC User Cache"); } I2CE::raiseError("Session destroyed"); I2CE::getConfig()->clearCache(); I2CE::raiseError("Magic data cleared -- Execution stopping"); die(0); } $update = false; if (!array_key_exists('HTTP_HOST', $_SERVER)) { //command line $update = self::getRuntimeVariable('update', '0'); } else { $URL = self::getAccessedBaseURL(false) . 'update.php'; $update = substr($_SERVER['REQUEST_URI'], 0, strlen($URL)) == $URL; } if (self::siteInitialized()) { self::raiseError("Already initialized!", E_USER_WARNING); return true; } $db = MDB2::singleton(); //get the instance we just created. if (!$update && $bring_up_system) { // just assume it is until we know otherwise. This error // message to don't dumped to the screen. self::siteInitialized(true); } /* if (I2CE_Dumper::dumpStaticURL($db->database_name, 'file')) { exit(); } */ I2CE_Error::resetStoredMessages(); if (empty($site_module_file)) { self::raiseError("Please set the site module's config file", E_USER_ERROR); if (!array_key_exists('HTTP_HOST', $_SERVER)) { //command line exit(14); } else { return false; } } $config = self::setupMagicData(); $config->setIfIsSet(self::$email, "/I2CE/feedback/to"); $site_module_file = I2CE_FileSearch::absolut($site_module_file, 1); self::setupFileSearch(array('MODULES' => array(dirname(dirname(__FILE__)), dirname($site_module_file)), 'CLASSES' => dirname(__FILE__))); self::setUserAccessInit($user_access_init, null, true); if ($update) { require_once 'I2CE_Updater.php'; if (!I2CE_Updater::updateSite($site_module_file)) { if (array_key_exists('HTTP_HOST', $_SERVER)) { die("<br/>Could not update site"); } else { I2CE::raiseError("\nCould not update site\n"); exit(15); } } else { if (!array_key_exists('HTTP_HOST', $_SERVER)) { //command line exit(0); } } return true; } else { if ($bring_up_system && !self::bringUpSystem($site_module_file)) { self::raiseError("Could not bring up system", E_USER_ERROR); exit(15); } I2CE::$ob_level = ob_get_level(); return true; } }
/** * Test the handling of sequences * * @dataProvider provider */ public function testSequences($ci) { $this->manualSetUp($ci); if (!$this->supported('sequences')) { $this->markTestSkipped('SEQUENCEs not supported'); } $this->db->loadModule('Manager', null, true); for ($start_value = 1; $start_value < 4; $start_value++) { $sequence_name = "test_sequence_{$start_value}"; @$this->db->manager->dropSequence($sequence_name); $result = $this->db->manager->createSequence($sequence_name, $start_value); if (MDB2::isError($result)) { $this->fail("Error creating sequence {$sequence_name} with start value {$start_value}: " . $result->getUserInfo()); } else { for ($sequence_value = $start_value; $sequence_value < $start_value + 4; $sequence_value++) { $value = $this->db->nextID($sequence_name, false); $this->assertEquals($sequence_value, $value, "The returned sequence value for {$sequence_name} is not expected with sequence start value with {$start_value}"); } $result = $this->db->manager->dropSequence($sequence_name); if (MDB2::isError($result)) { $this->fail("Error dropping sequence {$sequence_name} : " . $result->getUserInfo()); } } } // Test ondemand creation of sequences $sequence_name = 'test_ondemand'; $this->db->pushErrorHandling(PEAR_ERROR_RETURN); $this->db->expectError(MDB2_ERROR_NOSUCHTABLE); $this->db->manager->dropSequence($sequence_name); $this->db->popExpect(); $this->db->popErrorHandling(); for ($sequence_value = 1; $sequence_value < 4; $sequence_value++) { $value = $this->db->nextID($sequence_name); if (MDB2::isError($result)) { $this->fail("Error creating with ondemand sequence: " . $result->getUserInfo()); } else { $this->assertEquals($sequence_value, $value, "Error in ondemand sequences. The returned sequence value is not expected value"); } } $result = $this->db->manager->dropSequence($sequence_name); if (MDB2::isError($result)) { $this->fail("Error dropping sequence {$sequence_name} : " . $result->getUserInfo()); } // Test currId() $sequence_name = 'test_currid'; $next = $this->db->nextID($sequence_name); $curr = $this->db->currID($sequence_name); if (MDB2::isError($curr)) { $this->fail("Error getting the current value of sequence {$sequence_name} : " . $curr->getMessage()); } else { if ($next != $curr) { if ($next + 1 != $curr) { $this->assertEquals($next, $curr, "return value if currID() does not match the previous call to nextID()"); } } } $result = $this->db->manager->dropSequence($sequence_name); if (MDB2::isError($result)) { $this->fail("Error dropping sequence {$sequence_name} : " . $result->getUserInfo()); } // Test lastInsertid() if (!$this->db->supports('new_link')) { $this->markTestSkipped('Driver does not support new link.'); } $sequence_name = 'test_lastinsertid'; $dsn = MDB2::parseDSN($this->dsn); $dsn['new_link'] = true; $dsn['database'] = $this->database; $db = MDB2::connect($dsn, $this->options); $next = $this->db->nextID($sequence_name); $next2 = $db->nextID($sequence_name); $last = $this->db->lastInsertID($sequence_name); if (MDB2::isError($last)) { $this->fail("Error getting the last value of sequence {$sequence_name} : " . $last->getMessage()); } else { $this->assertEquals($next, $last, "return value if lastInsertID() does not match the previous call to nextID()"); } $result = $this->db->manager->dropSequence($sequence_name); if (MDB2::isError($result)) { $this->fail("Error dropping sequence {$sequence_name} : " . $result->getUserInfo()); } }
/** * set the DSN * * @param mixed $dsn DSN string or array * @return MDB2_OK * @access public */ function setDSN($dsn) { $dsn_default = $GLOBALS['_MDB2_dsninfo_default']; $dsn = MDB2::parseDSN($dsn); if (isset($dsn['database'])) { $this->database_name = $dsn['database']; unset($dsn['database']); } $this->dsn = array_merge($dsn_default, $dsn); return MDB2_OK; }
/** * set the DSN * * @param mixed DSN string or array * * @return MDB2_OK * * @access public */ function setDSN($dsn) { $dsn_default = $GLOBALS['_MDB2_dsninfo_default']; $dsn = MDB2::parseDSN($dsn); if (array_key_exists('database', $dsn)) { $this->database_name = $dsn['database']; unset($dsn['database']); } $this->dsn = array_merge($dsn_default, $dsn); return $this->disconnect(false); }
<dd> <p>Database settings for read/write operations:</p> <?php require_once 'MDB2.php'; $supported_dbs = array('MySQL' => 'mysql', 'MySQLi' => 'mysqli', 'PgSQL' => 'pgsql', 'SQLite' => 'sqlite'); $select_dbtype = new html_select(array('name' => '_dbtype', 'id' => "cfgdbtype")); foreach ($supported_dbs as $database => $ext) { if (extension_loaded($ext)) { $select_dbtype->add($database, $ext); } } $input_dbhost = new html_inputfield(array('name' => '_dbhost', 'size' => 20, 'id' => "cfgdbhost")); $input_dbname = new html_inputfield(array('name' => '_dbname', 'size' => 20, 'id' => "cfgdbname")); $input_dbuser = new html_inputfield(array('name' => '_dbuser', 'size' => 20, 'id' => "cfgdbuser")); $input_dbpass = new html_passwordfield(array('name' => '_dbpass', 'size' => 20, 'id' => "cfgdbpass")); $dsnw = MDB2::parseDSN($RCI->getprop('db_dsnw')); echo $select_dbtype->show($RCI->is_post ? $_POST['_dbtype'] : $dsnw['phptype']); echo '<label for="cfgdbtype">Database type</label><br />'; echo $input_dbhost->show($RCI->is_post ? $_POST['_dbhost'] : $dsnw['hostspec']); echo '<label for="cfgdbhost">Database server (omit for sqlite)</label><br />'; echo $input_dbname->show($RCI->is_post ? $_POST['_dbname'] : $dsnw['database']); echo '<label for="cfgdbname">Database name (use absolute path and filename for sqlite)</label><br />'; echo $input_dbuser->show($RCI->is_post ? $_POST['_dbuser'] : $dsnw['username']); echo '<label for="cfgdbuser">Database user name (needs write permissions)(omit for sqlite)</label><br />'; echo $input_dbpass->show($RCI->is_post ? $_POST['_dbpass'] : $dsnw['password']); echo '<label for="cfgdbpass">Database password (omit for sqlite)</label><br />'; ?> </dd> </dl> </fieldset>
/** * Test the handling of sequences */ function testSequences() { if (!$this->supported('sequences')) { return; } $this->db->loadModule('Manager', null, true); for ($start_value = 1; $start_value < 4; $start_value++) { $sequence_name = "test_sequence_{$start_value}"; $result = $this->db->manager->createSequence($sequence_name, $start_value); if (PEAR::isError($result)) { $this->assertTrue(false, "Error creating sequence {$sequence_name} with start value {$start_value}: " . $result->getMessage()); } else { for ($sequence_value = $start_value; $sequence_value < $start_value + 4; $sequence_value++) { $value = $this->db->nextId($sequence_name, false); $this->assertEquals($sequence_value, $value, "The returned sequence value is not expected with sequence start value with {$start_value}"); } $result = $this->db->manager->dropSequence($sequence_name); if (PEAR::isError($result)) { $this->assertTrue(false, "Error dropping sequence {$sequence_name} : " . $result->getMessage()); } } } // Test ondemand creation of sequences $sequence_name = 'test_ondemand'; $this->db->expectError(MDB2_ERROR_NOSUCHTABLE); $this->db->manager->dropSequence($sequence_name); $this->db->popExpect(); for ($sequence_value = 1; $sequence_value < 4; $sequence_value++) { $value = $this->db->nextId($sequence_name); if (PEAR::isError($result)) { $this->assertTrue(false, "Error creating with ondemand sequence: " . $result->getMessage()); } else { $this->assertEquals($sequence_value, $value, "Error in ondemand sequences. The returned sequence value is not expected value"); } } $result = $this->db->manager->dropSequence($sequence_name); if (PEAR::isError($result)) { $this->assertTrue(false, "Error dropping sequence {$sequence_name} : " . $result->getMessage()); } // Test currId() $sequence_name = 'test_currid'; $next = $this->db->nextId($sequence_name); $curr = $this->db->currId($sequence_name); if (PEAR::isError($curr)) { $this->assertTrue(false, "Error getting the current value of sequence {$sequence_name} : " . $curr->getMessage()); } else { if ($next != $curr) { if ($next + 1 == $curr) { $this->assertTrue(false, "Warning: currId() is using nextId() instead of a native implementation"); } else { $this->assertEquals($next, $curr, "return value if currId() does not match the previous call to nextId()"); } } } $result = $this->db->manager->dropSequence($sequence_name); if (PEAR::isError($result)) { $this->assertTrue(false, "Error dropping sequence {$sequence_name} : " . $result->getMessage()); } // Test lastInsertid() if (!$this->supported('new_link')) { return; } $sequence_name = 'test_lastinsertid'; $dsn = MDB2::parseDSN($this->dsn); $dsn['new_link'] = true; $dsn['database'] = $this->database; $db =& MDB2::connect($dsn, $this->options); $next = $this->db->nextId($sequence_name); $next2 = $db->nextId($sequence_name); $last = $this->db->lastInsertId($sequence_name); if (PEAR::isError($last)) { $this->assertTrue(false, "Error getting the last value of sequence {$sequence_name} : " . $last->getMessage()); } else { $this->assertEquals($next, $last, "return value if lastInsertId() does not match the previous call to nextId()"); } $result = $this->db->manager->dropSequence($sequence_name); if (PEAR::isError($result)) { $this->assertTrue(false, "Error dropping sequence {$sequence_name} : " . $result->getMessage()); } }
/** * Connect to specific database * * @param string DSN for DB connections * @return object PEAR database handle * @access private */ function dsn_connect($dsn) { // Use persistent connections if available $db_options = array('persistent' => $this->db_pconn, 'emulate_prepared' => $this->debug_mode, 'debug' => $this->debug_mode, 'debug_handler' => 'mdb2_debug_handler', 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL); if ($this->db_provider == 'pgsql') { $db_options['disable_smart_seqname'] = true; $db_options['seqname_format'] = '%s'; } $dbh = MDB2::connect($dsn, $db_options); if (MDB2::isError($dbh)) { $this->db_error = TRUE; $this->db_error_msg = $dbh->getMessage(); raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__, 'message' => $dbh->getUserInfo()), TRUE, FALSE); } else { if ($this->db_provider == 'sqlite') { $dsn_array = MDB2::parseDSN($dsn); if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials)) { $this->_sqlite_create_database($dbh, $this->sqlite_initials); } } else { if ($this->db_provider != 'mssql' && $this->db_provider != 'sqlsrv') { $dbh->setCharset('utf8'); } } } return $dbh; }
/** * Tests that the MDB2::parseDSN() method works. */ function test_parseDSN() { $dsn = $this->dsn; $result = MDB2::parseDSN($dsn); $this->assertEquals($dsn['phptype'], $result['dbsyntax'], 'parseDSN'); $dsn = "mydbms://*****:*****@localhost"; $result = MDB2::parseDSN($dsn); $this->assertEquals('mydbms', $result['phptype'], 'parseDSN'); $this->assertEquals('mydbms', $result['dbsyntax'], 'parseDSN'); $this->assertEquals('tcp', $result['protocol'], 'parseDSN'); $this->assertEquals('localhost', $result['hostspec'], 'parseDSN'); $this->assertEquals(false, $result['port'], 'parseDSN'); $this->assertEquals(false, $result['socket'], 'parseDSN'); $this->assertEquals('myname', $result['username'], 'parseDSN'); $this->assertEquals('mypassword', $result['password'], 'parseDSN'); $this->assertEquals(false, $result['database'], 'parseDSN'); $dsn = "somesql://*****:*****@localhost:1234/mydb"; $result = MDB2::parseDSN($dsn); $this->assertEquals('somesql', $result['phptype'], 'parseDSN'); $this->assertEquals('somesql', $result['dbsyntax'], 'parseDSN'); $this->assertEquals('tcp', $result['protocol'], 'parseDSN'); $this->assertEquals('localhost', $result['hostspec'], 'parseDSN'); $this->assertEquals('1234', $result['port'], 'parseDSN'); $this->assertEquals(false, $result['socket'], 'parseDSN'); $this->assertEquals('myname', $result['username'], 'parseDSN'); $this->assertEquals('mypassword', $result['password'], 'parseDSN'); $this->assertEquals('mydb', $result['database'], 'parseDSN'); $dsn = "dbms1://myname@unix(opts)/mydb?param1=value1"; $result = MDB2::parseDSN($dsn); $this->assertEquals('dbms1', $result['phptype'], 'parseDSN'); $this->assertEquals('dbms1', $result['dbsyntax'], 'parseDSN'); $this->assertEquals('unix', $result['protocol'], 'parseDSN'); $this->assertEquals(false, $result['hostspec'], 'parseDSN'); $this->assertEquals(false, $result['port'], 'parseDSN'); $this->assertEquals('opts', $result['socket'], 'parseDSN'); $this->assertEquals('myname', $result['username'], 'parseDSN'); $this->assertEquals(false, $result['password'], 'parseDSN'); $this->assertEquals('mydb', $result['database'], 'parseDSN'); $this->assertEquals('value1', $result['param1'], 'parseDSN'); }
/** * * Detect values of 'phptype' and 'dbsyntax' keys of DSN. * * @static * * @access public * * @param object &$db A PEAR DB/MDB2 object. * * @return array Values of 'phptype' and 'dbsyntax' keys of DSN. * */ function getPHPTypeAndDBSyntax(&$db) { $phptype = ''; $dbsyntax = ''; if (is_subclass_of($db, 'db_common')) { $phptype = $db->phptype; $dbsyntax = $db->dbsyntax; } elseif (is_subclass_of($db, 'mdb2_driver_common')) { $dsn = MDB2::parseDSN($db->getDSN()); $phptype = $dsn['phptype']; $dbsyntax = $dsn['dbsyntax']; } return array($phptype, $dbsyntax); }
function parseDSN($dsn) { return MDB2::parseDSN($dsn); }
/****************************************************************** Begin sanity checks on arguments ******************************************************************/ if ($dsn == '' || $file == '') { printHelp(); } if (!file_exists($file)) { print "The file {$file} does not exist\n"; exit; } /****************************************************************** End sanity checks on arguments ******************************************************************/ print "\n"; $options = array(); $dsn = MDB2::parseDSN($dsn); $database = $dsn['database']; unset($dsn['database']); $manager =& MDB2_Schema::factory($dsn, $options); if (PEAR::isError($manager)) { print "I could not connect to the database\n"; print " " . $manager->getMessage() . "\n"; print " " . $manager->getUserInfo() . "\n"; exit; } $variables = array('database' => $database, 'create' => (int) $create); $res = $manager->updateDatabase($file, false, $variables); if (PEAR::isError($res)) { print "I could not populate the database, see error below\n"; print " " . $res->getMessage() . "\n"; print " " . $res->getUserInfo() . "\n";