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; }
/** * 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)); }
/** * 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; }
/** * 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; }
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; } }
/** * remove all tables defined in a database structure xml file * @param string $file the xml file describing the tables */ public static function removeDBStructure($file) { $CONFIG_DBNAME = OC_Config::getValue("dbname", "owncloud"); $CONFIG_DBTABLEPREFIX = OC_Config::getValue("dbtableprefix", "oc_"); self::connectScheme(); // read file $content = file_get_contents($file); // Make changes and save them to a temporary file $file2 = tempnam(get_temp_dir(), 'oc_db_scheme_'); $content = str_replace('*dbname*', $CONFIG_DBNAME, $content); $content = str_replace('*dbprefix*', $CONFIG_DBTABLEPREFIX, $content); file_put_contents($file2, $content); // get the tables $definition = self::$schema->parseDatabaseDefinitionFile($file2); // Delete our temporary file unlink($file2); $tables = array_keys($definition['tables']); foreach ($tables as $table) { self::dropTable($table); } }
/** * @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; }
/** * 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'); }
/** * 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; }
/** * 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'); }
/** * 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; }
// 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
function &raiseError($msg = null, $ecode = MDB2_SCHEMA_ERROR_PARSE) { if (is_null($this->error)) { $error = 'Parser error: ' . $msg . "\n"; $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error); } return $this->error; }
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; }
/** * 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; }
// 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 // 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);
/** * MDB2_Schema_Error constructor. * * @param mixed $code error code, or string with error message. * @param int $mode what 'error mode' to operate in * @param int $level what error level to use for $mode & PEAR_ERROR_TRIGGER * @param mixed $debuginfo additional debug info, such as the last query * * @access public */ function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null) { $this->PEAR_Error('MDB2_Schema Error: ' . MDB2_Schema::errorMessage($code), $code, $mode, $level, $debuginfo); }
/** * 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; }
/** * MDB2_Schema_Error constructor. * * @param mixed error code, or string with error message. * @param int what 'error mode' to operate in * @param int what error level to use for $mode & PEAR_ERROR_TRIGGER * @param mixed additional debug info, such as the last query * @access public */ function __construct($code = MDB2_SCHEMA_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null) { parent::__construct('MDB2_Schema Error: ' . MDB2_Schema::errorMessage($code), $code, $mode, $level, $debuginfo); }
function &raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE) { if (is_null($this->error)) { $error = ''; if (is_resource($msg)) { $error .= 'Parser error: ' . xml_error_string(xml_get_error_code($msg)); $xp = $msg; } else { $error .= 'Parser error: ' . $msg; if (!is_resource($xp)) { $xp = $this->parser; } } if ($error_string = xml_error_string($xmlecode)) { $error .= ' - ' . $error_string; } if (is_resource($xp)) { $byte = @xml_get_current_byte_index($xp); $line = @xml_get_current_line_number($xp); $column = @xml_get_current_column_number($xp); $error .= " - Byte: {$byte}; Line: {$line}; Col: {$column}"; } $error .= "\n"; $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error); } return $this->error; }
/** * This method is used to communicate an error and invoke error * callbacks etc. Basically a wrapper for PEAR::raiseError * without the message string. * * @param int|PEAR_Error integer error code or and PEAR_Error instance * @param int error mode, see PEAR_Error docs * * error level (E_USER_NOTICE etc). If error mode is * PEAR_ERROR_CALLBACK, this is the callback function, * either as a function name, or as an array of an * object and method name. For other error modes this * parameter is ignored. * @param string Extra debug information. Defaults to the last * query and native error code. * @return object a PEAR error object * @access public * @see PEAR_Error */ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null) { $error =& MDB2_Schema::raiseError($code, $mode, $options, $userinfo); return $error; }
<?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!
function &raiseError($ecode, $msg = null) { $error =& MDB2_Schema::raiseError($ecode, null, null, $msg); return $error; }