/** * The constructor method. */ function __construct() { parent::__construct(); $this->oDbh = OA_DB::singleton(); $this->oCache = new OA_DB_XmlCache(); $this->oSchema =& MDB2_Schema::factory($this->oDbh, array('force_defaults' => false)); }
/** * The constructor method. */ function Test_OA_DB_XmlCache() { $this->UnitTestCase(); $this->oDbh = OA_DB::singleton(); $this->oCache = new OA_DB_XmlCache(); $this->oSchema =& MDB2_Schema::factory($this->oDbh, array('force_defaults' => false)); }
function removeDashboardColumns() { $this->oSchema = MDB2_Schema::factory(OA_DB::singleton(OA_DB::getDsn())); $prefix = $GLOBALS['_MAX']['CONF']['table']['prefix']; $table = 'preference'; $aColumns = array('ad_clicks_sum', 'ad_views_sum', 'ad_clicks_per_second', 'ad_views_per_second', 'ad_cs_data_last_sent', 'ad_cs_data_last_sent', 'ad_cs_data_last_received'); OA_DB::setCaseSensitive(); $aDef = $this->oSchema->getDefinitionFromDatabase(array($prefix . $table)); OA_DB::disableCaseSensitive(); if (is_array($aDef) && count($aDef) > 0) { $aTask['remove'] = array(); if (isset($aDef['tables'][$prefix . $table])) { foreach ($aColumns as $column) { if (isset($aDef['tables'][$prefix . $table]['fields'][$column])) { $aTask['remove'][$column] = array(); $this->oUpgrade->oLogger->logOnly("preference.{$column} found"); } } } if (count($aTask['remove'] > 0)) { $result = $this->oSchema->db->manager->alterTable($prefix . $table, $aTask, false); } } $this->oUpgrade->oLogger->logOnly('preference table schema upgrade for dashboard unnecessary'); return true; }
/** * verify the input file * instantiate the schema and table objects * * @param string $datafile * @param string $directory * @return boolean */ function init($datafile = 'fjsdj', $directory = '/tests/datasets/mdb2schema/') { if (!parent::init()) { return false; } if (!$directory) { $directory = '/tests/datasets/mdb2schema/'; } $this->directory = $directory; if (substr_count($this->directory, MAX_PATH) < 1) { $this->directory = MAX_PATH . $this->directory; } $this->datafile = $datafile; if (!file_exists($this->directory . $this->datafile)) { return false; } $this->oSchema =& MDB2_Schema::factory($this->oDbh); if (PEAR::isError($this->oSchema)) { return false; } $this->oTable = new OA_DB_Table(); if (PEAR::isError($this->oTable)) { return false; } return true; }
function alterDatabaseActionTable() { $this->oSchema = MDB2_Schema::factory(OA_DB::singleton(OA_DB::getDsn())); $prefix = $GLOBALS['_MAX']['CONF']['table']['prefix']; OA_DB::setCaseSensitive(); $aPrev = $this->oSchema->getDefinitionFromDatabase(array($prefix . 'database_action')); OA_DB::disableCaseSensitive(); $aCurr = $this->_getLatestDatabaseActionSchema($prefix); $aChanges = $this->oSchema->compareDefinitions($aCurr, $aPrev); if (is_array($aChanges) && count($aChanges) > 0) { if (isset($aChanges['tables']['change'][$prefix . 'database_action'])) { if (isset($aChanges['tables']['change'][$prefix . 'database_action']['indexes']['add']['database_action_pkey'])) { unset($aChanges['tables']['change'][$prefix . 'database_action']['indexes']['add']['database_action_pkey']); unset($aChanges['tables']['change'][$prefix . 'database_action']['indexes']['change']); } if (isset($aChanges['tables']['change'][$prefix . 'database_action']['add']['database_action_id'])) { $result = $this->oSchema->alterDatabase($aCurr, $aPrev, $aChanges); if (PEAR::isError($result)) { $this->oUpgrade->oLogger->logError($result->getUserInfo()); return false; } $this->oUpgrade->oLogger->log('database_action table schema successfully upgraded'); return true; } } } $this->oUpgrade->oLogger->log('database_action table schema upgrade unnecessary'); return true; }
function setUp() { PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'catchErrorHandlerPEAR'); $this->dsn = $GLOBALS['dsn']; $this->options = $GLOBALS['options']; $this->database = $GLOBALS['database']; $this->dsn['database'] = $this->database; $this->schema =& MDB2_Schema::factory($this->dsn, $this->options); if (PEAR::isError($this->schema)) { $this->assertTrue(false, 'Could not connect to manager in setUp'); exit; } }
function setUpDatabase() { // Create a new test table, overwriting old ones. require_once 'MDB2/Schema.php'; $config = $this->getDriverConfig(); $manager = MDB2_Schema::factory($config['params']); $defs = $manager->parseDatabaseDefinition(dirname(dirname(__DIR__)) . '/scripts/sql/test.xml', false, array('name' => $config['params']['database']), false); $result = $manager->createTable('hordetest_turba_objects', $defs['tables']['hordetest_turba_objects'], true); $this->assertOk($result); foreach ($this->_fixtures as $fixture) { $this->assertOk($this->_insert($fixture)); } }
function setUp() { PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'catchErrorHandlerPEAR'); $this->dsn = $GLOBALS['dsn']; $this->options = $GLOBALS['options']; $this->database = $GLOBALS['database']; $this->dsn['database'] = $this->database; $this->schema =& MDB2_Schema::factory($this->dsn, $this->options); if (PEAR::isError($this->schema)) { $this->assertTrue(false, 'Could not connect to manager in setUp'); exit; } $this->aSchemas = array(1 => SCHEMA_PATH . 'schema_1_original.xml', 2 => SCHEMA_PATH . 'schema_2_newfield.xml', 3 => SCHEMA_PATH . 'schema_3_primarykey.xml', 4 => SCHEMA_PATH . 'schema_4_idxfieldorder.xml', 5 => SCHEMA_PATH . 'schema_5_fieldtype.xml', 6 => SCHEMA_PATH . 'schema_6_removefield.xml', 7 => SCHEMA_PATH . 'schema_7_removeindex.xml', 8 => SCHEMA_PATH . 'schema_8_addtable.xml', 9 => SCHEMA_PATH . 'schema_9_removetable.xml', 10 => SCHEMA_PATH . 'schema_10_keyfield.xml'); }
function setUp() { $this->dsn = $GLOBALS['dsn']; $this->options = $GLOBALS['options']; $this->database = $GLOBALS['database']; $backup_file = $this->driver_input_file . $this->backup_extension; if (file_exists($backup_file)) { unlink($backup_file); } $backup_file = $this->lob_input_file . $this->backup_extension; if (file_exists($backup_file)) { unlink($backup_file); } $this->schema =& MDB2_Schema::factory($this->dsn, $this->options); if (PEAR::isError($this->schema)) { $this->assertTrue(false, 'Could not connect to manager in setUp'); exit; } }
function generateXmlCache($xmlFiles, $callback = 'parseDatabaseDefinitionFile') { global $aSkipFiles, $aOptions, $oDbh, $oCache; foreach ($xmlFiles as $fileName) { if (!in_array(baseName($fileName), $aSkipFiles)) { echo " => " . basename($fileName) . ": "; flush(); $oSchema =& MDB2_Schema::factory($oDbh, $aOptions); $result = $oSchema->{$callback}($fileName, true); if (PEAR::isError($result)) { clean_up(); die("Failed\n"); } else { $oCache->save($result, $fileName); echo "Processed"; eol_flush(); } unset($result); } } }
function setUp() { PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'catchErrorHandlerPEAR'); $this->dsn = $GLOBALS['dsn']; $this->options = $GLOBALS['options']; $this->database = $GLOBALS['database']; $this->dsn['database'] = $this->database; $backup_file = SCHEMA_PATH . $this->driver_input_file . $this->backup_extension; if (file_exists($backup_file)) { unlink($backup_file); } $backup_file = SCHEMA_PATH . $this->lob_input_file . $this->backup_extension; if (file_exists($backup_file)) { unlink($backup_file); } $this->schema =& MDB2_Schema::factory($this->dsn, $this->options); if (PEAR::isError($this->schema)) { $this->assertTrue(false, 'Could not connect to manager in setUp'); exit; } }
/** * php5 class constructor * * @param string The XML schema file we are working on */ function __construct($file_schema = 'tables_core.xml', $file_changes = '', $path_schema) { $this->oLogger = new OA_UpgradeLogger(); $this->oLogger->setLogFile('schema.log'); if (empty($path_schema)) { $path_schema = '/etc/'; } if (!empty($path_schema) && substr($path_schema, 0, 1) != '/') { $path_schema = '/' . $path_schema; } if (!empty($path_schema) && substr($path_schema, strlen($path_schema) - 4, 4) != 'etc/') { $path_schema = $path_schema . 'etc/'; } $this->path_schema_final = MAX_PATH . $path_schema; $this->path_schema_trans = MAX_PATH . '/var/'; $this->path_changes_final = MAX_PATH . $path_schema . 'changes/'; $this->path_changes_trans = MAX_PATH . '/var/'; if ($path_schema == '/etc/') { $this->path_dbo = MAX_PATH . '/lib/max/Dal/DataObjects/'; } else { $this->path_dbo = $this->path_schema_final . 'DataObjects/'; } //$this->path_links_final = MAX_PATH.'/lib/max/Dal/DataObjects/'; $this->path_links_final = $this->path_dbo; $this->path_links_trans = MAX_PATH . '/var/'; $file_changes = $file_changes ? $file_changes : 'changes_' . $file_schema; $file_links = 'db_schema.links.ini'; $this->schema_final = $this->path_schema_final . $file_schema; $this->schema_trans = $this->path_schema_trans . $file_schema; $this->oLogger->log($this->schema_final); $this->use_links = $file_schema == 'tables_core.xml'; if ($this->use_links) { $this->links_final = $this->path_links_final . $file_links; $this->links_trans = $this->path_links_trans . $file_links; } $this->changes_final = $this->path_changes_final . $file_changes; $this->changes_trans = $this->path_changes_trans . $file_changes; $this->oLogger->log($this->changes_final); if ($this->use_links) { $this->aFile_perms = array($this->path_schema_trans, $this->path_changes_final, $this->path_changes_trans, $this->path_links_trans, $this->links_final, $this->schema_final, MAX_SCHEMA_LOG, MAX_PATH . '/www/devel/'); } else { $this->aFile_perms = array($this->path_schema_trans, $this->path_changes_final, $this->path_changes_trans, $this->schema_final, MAX_SCHEMA_LOG, MAX_PATH . '/www/devel/'); } $this->aDump_options = array('output_mode' => 'file', 'output' => $this->schema_trans, 'end_of_line' => "\n", 'xsl_file' => "xsl/mdb2_schema.xsl", 'custom_tags' => array('version' => '', 'status' => 'transitional')); $this->oSchema = MDB2_Schema::factory(OA_DB::singleton(OA_DB::getDsn()), $this->aDump_options); $this->dd_file = 'etc/dd.generic.xml'; $this->aDD_definition = $this->oSchema->parseDictionaryDefinitionFile($this->dd_file); ksort($this->aDD_definition); //$this->aXMLRPCServer = array('path'=>'/upms/xmlrpc.php', 'host'=>'localhost','port'=>'80'); }
/** * Installs table(s)/data schema into database * * @access public * @param string $new_schema New schema file path/name * @param array $variables Schema variables * @param string $old_schema Old schema file path/name * @param string $init_data Schema is include initialization data * @param string $create If the database should be created * @return mixed True on success and Jaws_Error on failure */ function installSchema($new_schema, $variables = array(), $old_schema = false, $init_data = false, $create = true) { MDB2::loadFile('Schema'); $dsn = $this->_dsn; unset($dsn['database']); // If the database should be created $variables['create'] = (int) $create; // The database name $variables['database'] = $this->_dsn['database']; // Prefix of all the tables added $variables['table_prefix'] = $this->getPrefix(); // set default charset if (!isset($variables['charset'])) { $variables['charset'] = $this->getUnicodeCharset(); } $options = array('debug' => false, 'log_line_break' => '<br />', 'portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL ^ MDB2_PORTABILITY_FIX_CASE ^ MDB2_PORTABILITY_RTRIM, 'quote_identifier' => true, 'force_defaults' => false); switch ($this->_dsn['phptype']) { case 'ibase': $options['portability'] = $options['portability'] | MDB2_PORTABILITY_FIX_CASE; $options['database_path'] = empty($this->_db_path) ? JAWS_DATA : $this->_db_path; break; case 'oci8': $options['emulate_database'] = false; $options['portability'] = $options['portability'] | MDB2_PORTABILITY_FIX_CASE; break; case 'sqlite': $options['database_path'] = empty($this->_db_path) ? JAWS_DATA : $this->_db_path; break; case 'mssql': $options['multibyte_text_field_type'] = $this->Is_FreeTDS_MSSQL_Driver(); break; } if ($this->_is_dba) { $options['DBA_username'] = $this->_dsn['username']; $options['DBA_password'] = $this->_dsn['password']; } if (!isset($this->schema)) { $this->schema =& MDB2_Schema::factory($this->dbc, $options); if (MDB2::isError($this->schema)) { return $this->schema; } } $method = $init_data === true ? 'writeInitialization' : 'updateDatabase'; $result = $this->schema->{$method}($new_schema, $old_schema, $variables); if (MDB2::isError($result)) { $this->schema->disconnect(); unset($this->schema); $GLOBALS['log']->Log(JAWS_ERROR_ERROR, $result->getUserInfo(), 2); return new Jaws_Error($result->getMessage(), $result->getCode(), JAWS_ERROR_ERROR, 1); } return $result; }
/** * Initializes a database with data * * @param array $args Command line arguments * * @return void */ protected function doInit($args) { list($typeSource, $dsnSource) = $this->getFileOrDsn($args); list($typeDest, $dsnDest) = $this->getFileOrDsn($args); if ($typeSource != 'file') { throw new MDB2_Schema_Tool_ParameterException('Data must come from a source file'); } if ($typeDest != 'dsn') { throw new MDB2_Schema_Tool_ParameterException('A schema can only be loaded into a database, not a file'); } $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions()); $this->throwExceptionOnError($schemaDest, 'connecting to destination database'); $definition = $schemaDest->getDefinitionFromDatabase(); $this->throwExceptionOnError($definition, 'loading definition from database'); $op = $schemaDest->writeInitialization($dsnSource, $definition); $this->throwExceptionOnError($op, 'initializing database'); }
$smarty->assign("site_url", "http://{$_SERVER['HTTP_HOST']}" . path::http()); $smarty->assign("site_root", path::http()); $smarty->assign("site_images", path::http("images")); $smarty->assign("templates_abs", path::http("templates")); $smarty->assign("page_title", $settings['site']['long_name']); $dsn = $settings['dsn']; require_once 'MDB2/Schema.php'; // Using include path (PEAR Class) PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handle_pear_error'); $db =& MDB2::connect($dsn); // With PEAR::isError you can differentiate between an error or // a valid connection. if (PEAR::isError($db)) { die; } $manager =& MDB2_Schema::factory($db); $input_file = path::file("data") . "database/schema"; $schema_mod = $cache->get("schema_modified", 60 * 24); if (!file_exists("{$input_file}.xml") || !$schema_mod || $schema_mod < filemtime("{$input_file}.xml")) { $db_name = $manager->db->database_name; if (!$manager->updateDatabase("{$input_file}.xml", "{$input_file}_current.xml", array('db_name' => $db_name, 'table_prefix' => $db_prefix))) { die("Schema Update Error."); } $cache->set("schema_modified", filemtime("{$input_file}.xml")); } require_once path::file("classes") . "content_class.php"; $content = new content_handling(); require_once path::file("classes") . "page_handling_class.php"; $page_handler = new page_hander(); require_once path::file("classes") . "users_class.php"; // Initiate session handler class
// MDB2::factory will return a PEAR::MDB2 instance on success // or a Pear MDB2 error object on error // You can alternatively build a dsn here // $dsn = "$mdb2_type://$user:$pass@$host/$mdb2_name"; Var_Dump($dsn); $mdb2 =& MDB2::factory($dsn); // With PEAR::isError you can differentiate between an error or // a valid connection. if (PEAR::isError($mdb2)) { die(__LINE__ . $mdb2->getMessage()); } // this loads the MDB2_Schema manager // this is a separate package you must install require_once 'MDB2/Schema.php'; // you can either pass a dsn string, a dsn array or an exisiting mdb2 connection $schema =& MDB2_Schema::factory($mdb2); $input_file = 'metapear_test_db.schema'; // lets create the database using 'metapear_test_db.schema' // if you have allready run this script you should have 'metapear_test_db.schema.before' // in that case MDB2 will just compare the two schemas and make any // necessary modifications to the existing database Var_Dump($schema->updateDatabase($input_file, $input_file . '.before')); echo 'updating database from xml schema file<br>'; echo 'switching to database: ' . $mdb2_name . '<br>'; $mdb2->setDatabase($mdb2_name); // happy query $query = 'SELECT * FROM test'; echo 'query for the following examples:' . $query . '<br>'; // run the query and get a result handler $result = $mdb2->query($query); // lets just get row:0 and free the result
/** * 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; }
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY| // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | // | POSSIBILITY OF SUCH DAMAGE. | // +----------------------------------------------------------------------+ // | Author: Igor Feghali <*****@*****.**> | // +----------------------------------------------------------------------+ // // $Id: parse.php,v 1.4 2006/08/17 10:57:37 lsmith Exp $ // #ini_set('include_path', '../../'.PATH_SEPARATOR.ini_get('include_path')); #ini_set('include_path', '../../../MDB2'.PATH_SEPARATOR.ini_get('include_path')); require_once 'MDB2.php'; $dsn = array('phptype' => 'mysql', 'username' => 'root', 'password' => '', 'hostspec' => 'localhost'); $options = array(); MDB2::loadFile('Schema'); $manager =& MDB2_Schema::factory($dsn, $options); if (MDB2::isError($manager)) { die($manager->getUserinfo()); } $database_definition = $manager->parseDatabaseDefinitionFile('./schema.xml'); $manager->db->setOption('disable_query', true); $manager->db->setOption('debug', true); $manager->writeInitialization($database_definition); ?> <pre> <?php var_dump($database_definition); var_dump($manager->db->getDebugOutput()); ?> </pre>
/** * instantiate the mdb2_schema object */ function initMDB2Schema() { $result = MDB2_Schema::factory(OA_DB::singleton(OA_DB::getDsn())); if (!$this->_isPearError($result, 'failed to instantiate MDB2_Schema')) { $this->oSchema = $result; $this->portability = $this->oSchema->db->getOption('portability'); $this->_setupSQLStatements(); $this->oTable = new OA_DB_Table(); } }
function execute_upgrade_file($folder, $installed_version) { global $db, $page, $conf, $fs; // At first the config file $upgrade_path = BASEDIR . '/upgrade/' . $folder; new ConfUpdater(CONFIG_PATH, $upgrade_path); $upgrade_info = parse_ini_file($upgrade_path . '/upgrade.info', true); $type = 'defaultupgrade'; // global prefs update if (isset($upgrade_info['fsprefs'])) { $existing = $db->x->GetCol('SELECT pref_name FROM {prefs}'); // Add what is missing $stmt = $db->x->autoPrepare('{prefs}', array('pref_name', 'pref_value')); foreach ($upgrade_info['fsprefs'] as $name => $value) { if (!in_array($name, $existing)) { $stmt->execute(array($name, $value)); } } $stmt->free(); // Delete what is too much $stmt = $db->prepare('DELETE FROM {prefs} WHERE pref_name = ?'); foreach ($existing as $name) { if (!isset($upgrade_info['fsprefs'][$name])) { $stmt->execute($name); } } $stmt->free(); } // Now a mix of XML schema files and PHP upgrade scripts if (!isset($upgrade_info[$type])) { die('#1 Bad upgrade.info file.'); } // files which are already done $done = $db->x->GetOne('SELECT pref_value FROM {prefs} WHERE pref_name = ?', null, 'upgrader_done'); $done = $done ? @unserialize($done) : array(); if (!is_array($done)) { $done = array(); } ksort($upgrade_info[$type]); foreach ($upgrade_info[$type] as $file) { // skip all files which have been executed already $hash = md5_file($upgrade_path . '/' . $file); if (isset($done[$file]) && $done[$file] == $hash) { continue; } if (substr($file, -4) == '.php') { require_once $upgrade_path . '/' . $file; $done[$file] = $hash; } if (substr($file, -4) == '.xml') { require_once 'MDB2/Schema.php'; $db->setOption('idxname_format', '%s'); $schema =& MDB2_Schema::factory($db); $schema->setOption('force_defaults', false); // XXX: workaround for MDB2 bug $db->inTransaction() && $db->commit(); $previous_schema = $schema->getDefinitionFromDatabase(); if (PEAR::isError($previous_schema)) { return $previous_schema; } $res = $schema->updateDatabase($upgrade_path . '/' . $file, $previous_schema, array('db_prefix' => $conf['database']['dbprefix'], 'db_name' => $conf['database']['dbname'])); if (PEAR::isError($res)) { return $res; } $done[$file] = $hash; } } $db->x->execParam('UPDATE {prefs} SET pref_value = ? WHERE pref_name = ?', array($folder, 'fs_ver')); $db->x->execParam('UPDATE {prefs} SET pref_value = ? WHERE pref_name = ?', array(serialize($done), 'upgrader_done')); return true; }
<?php // This is just a developer's tool. Needs tables with flyspray_ prefix. error_reporting(E_ALL); define('IN_FS', true); $file = 'exportdb.xml'; require_once dirname(__FILE__) . '/../includes/fix.inc.php'; require_once dirname(__FILE__) . '/../includes/class.database.php'; $conf = @parse_ini_file('../flyspray.conf.php', true) or die('Cannot open config file.'); define('DEBUG_SQL', true); $db = NewDatabase($conf['database']); require_once dirname(__FILE__) . '/../includes/external/MDB2/MDB2/Schema.php'; // Now build schema object based on existing connection $db->setOption('idxname_format', '%s'); $schema =& MDB2_Schema::factory($db); $def = $schema->getDefinitionFromDatabase(); $schema->dumpDatabase($def, array('output_mode' => 'file', 'output' => $file), MDB2_SCHEMA_DUMP_STRUCTURE); // Now make prefix a variable, so that it can be replaced during setup or upgrade $xml = file_get_contents($file); $xml = str_replace('flyspray_', '<variable>db_prefix</variable>', $xml); // workaround for quotes bug $xml = str_replace('"', '"', $xml); // empty default values might cause problems $xml = str_replace("<notnull>true</notnull>\n <default></default>", '<notnull>true</notnull>', $xml); // also make database name variable $xml = str_replace('<name>' . $conf['database']['dbname'] . '</name>', '<name><variable>db_name</variable></name>', $xml); file_put_contents($file, $xml);
/** * @brief connects to a MDB2 database scheme * @returns true/false * * Connects to a MDB2 database scheme */ private static function connectScheme() { // We need a database connection self::connect(); // Connect if this did not happen before if (!self::$schema) { require_once 'MDB2/Schema.php'; self::$schema = MDB2_Schema::factory(self::$DBConnection); } return true; }
/** * Function to populate the database with the sql constructs which is in an sql file * @param array $data The actual database configuration values * @return boolean */ function PopulateDb($data) { // Check available upgrade scripts, use the script of very latest version $folders = glob_compat(BASEDIR . '/upgrade/[0-9]*'); usort($folders, 'version_compare'); // start with lowest version $folders = array_reverse($folders); // start with highest version $sql_file = APPLICATION_PATH . '/setup/upgrade/' . basename(reset($folders)) . '/flyspray-install.xml'; $upgradeInfo = APPLICATION_PATH . '/setup/upgrade/' . basename(reset($folders)) . '/upgrade.info'; $upgradeInfo = parse_ini_file($upgradeInfo, true); // Check if the install/upgrade file exists if (!is_readable($sql_file)) { $_SESSION['page_message'][] = "SQL file required for importing structure and data is missing ({$sql_file})."; return false; } // Extract the variables to local namespace extract($data); if (!isset($db_prefix)) { $db_prefix = ''; } if (is_numeric($db_prefix)) { $_SESSION['page_message'][] = 'Database prefix cannot be numeric only'; return false; } // Set the prefix for database objects ( before parsing ) require 'MDB2/Schema.php'; $this->mDbConnection->setOption('use_transactions', false); $this->mDbConnection->setOption('default_table_type', 'MyISAM'); $this->mXmlSchema =& MDB2_Schema::factory($this->mDbConnection); $def = $this->mXmlSchema->parseDatabaseDefinitionFile($sql_file, array('db_prefix' => $db_prefix, 'db_name' => $data['db_name'])); if (PEAR::isError($def)) { var_dump($def); exit; } $op = $this->mXmlSchema->createDatabase($def); if (PEAR::isError($op)) { var_dump($op); exit; } // global prefs update if (isset($upgradeInfo['fsprefs'])) { $existing = $this->mDbConnection->x->GetCol("SELECT pref_name FROM {$db_prefix}prefs"); // Add what is missing $stmt = $this->mDbConnection->x->autoPrepare("{$db_prefix}prefs", array('pref_name', 'pref_value')); foreach ($upgradeInfo['fsprefs'] as $name => $value) { if (!in_array($name, $existing)) { $stmt->execute(array($name, $value === '' ? '0' : $value)); } } $stmt->free(); // Delete what is too much $stmt = $this->mDbConnection->prepare("DELETE FROM {$db_prefix}prefs WHERE pref_name = ?"); foreach ($existing as $name) { if (!isset($upgradeInfo['fsprefs'][$name])) { $stmt->execute($name); } } $stmt->free(); } $this->mDbConnection->x->execParam("UPDATE {$db_prefix}prefs SET pref_value = ? WHERE pref_name = 'fs_ver'", $this->version); if (PEAR::isError($op)) { $_SESSION['page_heading'] = 'Database Processing'; $_SESSION['page_message'][] = $op->getMessage(); return false; } return true; }
/** * A method to initialise the class by parsing a database XML schema file, so that * the class will be ready to create/drop tables for the supplied schema. * * @todo Better handling of cache files * * @param string $file The name of the database XML schema file to parse for * the table definitions. * @param bool $useCache If true definitions are loaded from the cache file * @return boolean True if the class was initialised correctly, false otherwise. */ function init($file, $useCache = true) { // Ensure that the schema XML file can be read if (!is_readable($file)) { OA::debug('Unable to read the database XML schema file: ' . $file, PEAR_LOG_ERR); return false; } // Create an instance of MDB2_Schema to parse the schema file $options = array('force_defaults' => false); $this->oSchema =& MDB2_Schema::factory($this->oDbh, $options); if ($useCache) { $oCache = new OA_DB_XmlCache(); $this->aDefinition = $oCache->get($file); $this->cached_definition = true; } else { $this->aDefinition = false; } if (!$this->aDefinition) { $this->cached_definition = false; // Parse the schema file $this->aDefinition = $this->oSchema->parseDatabaseDefinitionFile($file); if (PEAR::isError($this->aDefinition)) { OA::debug('Error parsing the database XML schema file: ' . $file, PEAR_LOG_ERR); return false; } // On-the fly cache writing disabled //if ($useCache) { // $oCache->save($this->aDefinition, $file); //} } return true; }
function _getFieldIdName($table) { $dbh =& OA_DB::singleton(); $schema = MDB2_Schema::factory($dbh); $definition = $schema->getDefinitionFromDatabase(array($table)); foreach ($definition['tables'][$table]['fields'] as $fieldname => $dataField) { if (isset($dataField['autoincrement']) && 1 == $dataField['autoincrement']) { return $fieldname; } } return null; }
/** * Create or upgrade the database needed for pearweb * * This helper function scans for previous database versions, * and upgrades the database based on differences between the * previous version's schema and the one distributed with this * version. * * If the database has never been created, then it is created. * * @param array $answers * @return boolean */ function initializeDatabase($answers) { $this->dsn = array('phptype' => $answers['driver'], 'username' => $answers['user'], 'password' => $answers['password'], 'hostspec' => $answers['host'], 'database' => $answers['database']); $a = MDB2_Schema::factory($this->dsn, array('idxname_format' => '%s', 'seqname_format' => 'id', 'quote_identifier' => true)); // for upgrade purposes if (!file_exists('@www-dir@' . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR . '.pearweb-upgrade')) { if (!mkdir('@www-dir@' . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR . '.pearweb-upgrade')) { $this->_ui->outputData('error - make sure we can create directories'); return false; } } PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); $c = $a->parseDatabaseDefinitionFile(realpath('@www-dir@/sql/pearweb_mdb2schema.xml')); PEAR::staticPopErrorHandling(); if (PEAR::isError($c)) { $extra = ''; if (MDB2_Schema::isError($c) || MDB2::isError($c)) { $extra = "\n" . $c->getUserInfo(); } $this->_ui->outputData('ERROR: ' . $c->getMessage() . $extra); return false; } $c['name'] = $answers['database']; $c['create'] = 1; $c['overwrite'] = 0; $dir = opendir('@www-dir@/sql/.pearweb-upgrade'); $oldversion = false; while (false !== ($entry = readdir($dir))) { if ($entry[0] === '.') { continue; } if (strpos($entry, $answers['database']) === 0) { // this is one of ours // strip databasename- $entry = substr($entry, strlen($answers['database']) + 1); // strip ".ser" $entry = substr($entry, 0, strlen($entry) - 4); // ... and we're left with just the version if (!$oldversion) { $oldversion = $entry; continue; } if (version_compare($entry, $oldversion, '>')) { $oldversion = $entry; } } } if (!file_exists('@www-dir@/sql/.pearweb-upgrade/' . $answers['database'] . '-@version@.ser')) { $fp = fopen('@www-dir@/sql/.pearweb-upgrade/' . $answers['database'] . '-@version@.ser', 'w'); fwrite($fp, serialize($c)); fclose($fp); } if ($oldversion == '@version@') { // this is where to change if we need to add a "force upgrade of // structure" option // we would uncomment the following line: //$c['overwrite'] = true; $oldversion = false; } if ($oldversion) { $curdef = unserialize(file_get_contents('@www-dir@/sql/.pearweb-upgrade/' . $answers['database'] . '-' . $oldversion . '.ser')); if (!is_array($curdef)) { $this->_ui->outputData('invalid data returned from previous version'); } // get a database diff (MDB2_Schema is very useful here) PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); $c = $a->compareDefinitions($c, $curdef); if (PEAR::isError($c)) { $this->_ui->outputData($err->getMessage()); $this->_ui->outputData($err->getUserInfo()); $this->_ui->outputData('Unable to automatically update database'); return false; } $err = $a->updateDatabase($curdef, $c); PEAR::staticPopErrorHandling(); } else { PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); $err = $a->createDatabase($c); PEAR::staticPopErrorHandling(); } if (PEAR::isError($err)) { $this->_ui->outputData($err->getUserInfo()); $this->_ui->outputData($err->getMessage()); return false; } return true; }
/** * @brief connects to a MDB2 database scheme * @returns true/false * * Connects to a MDB2 database scheme */ private static function connectScheme() { // We need a mdb2 database connection self::connectMDB2(); self::$MDB2->loadModule('Manager'); self::$MDB2->loadModule('Reverse'); // Connect if this did not happen before if (!self::$schema) { require_once 'MDB2/Schema.php'; self::$schema = MDB2_Schema::factory(self::$MDB2); } return true; }
// MDB2::factory will return a PEAR::MDB2 instance on success // or a Pear MDB2 error object on error // You can alternatively build a dsn here // $dsn = "$mdb2_type://$user:$pass@$host/$mdb2_name"; Var_Dump($dsn); $mdb2 =& MDB2::factory($dsn); // With PEAR::isError you can differentiate between an error or // a valid connection. if (PEAR::isError($mdb2)) { die(__LINE__ . $mdb2->getMessage()); } // this loads the MDB2_Schema manager // this is a separate package you must install require_once 'MDB2/Schema.php'; // you can either pass a dsn string, a dsn array or an exisiting mdb2 connection $manager =& MDB2_Schema::factory($mdb2); $input_file = 'metapear_test_db.schema'; // lets create the database using 'metapear_test_db.schema' // if you have allready run this script you should have 'metapear_test_db.schema.before' // in that case MDB2 will just compare the two schemas and make any // necessary modifications to the existing database Var_Dump($manager->updateDatabase($input_file, $input_file . '.before')); echo 'updating database from xml schema file<br>'; echo 'switching to database: ' . $mdb2_name . '<br>'; $mdb2->setDatabase($mdb2_name); // happy query $query = 'SELECT * FROM test'; echo 'query for the following examples:' . $query . '<br>'; // run the query and get a result handler $result = $mdb2->query($query); // lets just get row:0 and free the result
<?php require_once 'MDB2/Schema.php'; $dsn = array('phptype' => 'mysql', 'username' => 'username', 'password' => 'password', 'hostspec' => 'host'); $db_options = array(); $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'driver_test.schema.xml'; $variables = array('name' => 'driver_test', 'create' => true); $options = array('log_line_break' => '<br />', 'idxname_format' => '%s', 'debug' => true, 'quote_identifier' => true, 'force_defaults' => false, 'portability' => false); $options = array_merge($options, $db_options); $schema =& MDB2_Schema::factory($dsn, $options); if (PEAR::isError($schema)) { echo $schema->getMessage() . ' ' . $schema->getUserInfo(); exit; } $definition = $schema->parseDatabaseDefinitionFile($file, $variables, true, true); if (PEAR::isError($definition)) { echo $definition->getMessage() . ' - ' . $definition->getUserInfo(); } else { $operation = $schema->createDatabase($definition); if (PEAR::isError($operation)) { echo $operation->getMessage() . ' ' . $operation->getUserInfo(); } } ?> DONE!
/** * Install a schema file into the database * * @param object LiveUser storage instance * @param string name of the file into which the xml schema should be written * @param array key-value pairs with keys being variable names and values being the variable values * @param bool determines if the database should be created or not * @param array MDB2_Schema::connect() options * @param bool determines if the database should be created or not * @param bool determines if the old schema file should be unlinked first * @param bool determines if the disable_query option should be set in MDB2 * @return bool|PEAR_Error true on success or a PEAR_Error on error * * @access public */ function installSchema($obj, $file, $variables = array(), $create = true, $options = array(), $overwrite = false, $disable_query = false) { $dsn = array(); if (is_a($obj->dbc, 'DB_Common')) { $dsn = $obj->dbc->dsn; $options['seqcol_name'] = 'id'; } elseif (is_a($obj->dbc, 'PDO')) { $dsn = LiveUser_Misc_Schema_Install::parsePDODSN($obj->dbc->dsn); $dsn['username'] = array_key_exists('username', $obj->dbc->options) ? $obj->dbc->options['username'] : ''; $dsn['password'] = array_key_exists('password', $obj->dbc->options) ? $obj->dbc->options['password'] : ''; $options['seqname_format'] = '%s'; } elseif (MDB2::isConnection($obj->dbc)) { $dsn = $obj->dbc->getDSN('array'); } $file_old = $file.'.'.$dsn['hostspec'].'.'.$dsn['database'].'.old'; $variables['create'] = (int)$create; $variables['overwrite'] = (int)$overwrite; $variables['database'] = $dsn['database']; unset($dsn['database']); $manager =& MDB2_Schema::factory($dsn, $options); if (PEAR::isError($manager)) { return $manager; } if ($overwrite && file_exists($file_old)) { unlink($file_old); } $result = $manager->updateDatabase($file, $file_old, $variables, $disable_query); $debug = $manager->db->getOption('debug'); if ($debug && !PEAR::isError($debug)) { echo('Debug messages<br>'); echo($manager->db->getDebugOutput().'<br>'); } $manager->disconnect(); return $result; }