/** * Determine whether an existing installation of MediaWiki is present in * the configured administrative connection. Returns true if there is * such a wiki, false if the database doesn't exist. * * Traditionally, this is done by testing for the existence of either * the revision table or the cur table. * * @return bool */ public function needsUpgrade() { $status = $this->getConnection(); if (!$status->isOK()) { return false; } if (!$this->db->selectDB($this->getVar('wgDBname'))) { return false; } return $this->db->tableExists('cur', __METHOD__) || $this->db->tableExists('revision', __METHOD__); }
/** * Migrate the database up to the greatest defined value */ public static function up() { // check to see if the "migration" table exists if (!Database::tableExists(static::$table_name)) { // if not, create it Database::execute("CREATE TABLE " . static::$table_name . " (id INTEGER PRIMARY KEY ASC, last INTEGER);"); // initialize the value Database::execute("INSERT INTO " . static::$table_name . " VALUES ( 1, 0 );"); } // get the current migration counter $value = Database::query("SELECT last FROM " . static::$table_name . " WHERE id=1;"); $value = $value[0]['last']; // get the list of migration classes from the config $migrations = Config::get('migrations.migrations'); // make a list of classes to rollback, just in case of error $rollback = array(); // do the following in a try/catch block so we can roll back if need be try { while ($value < max(array_keys($migrations))) { // increment the counter $value++; // if a migration exists for the incremented counter, then run it if (array_key_exists($value, $migrations)) { // get the class name $class = $migrations[$value]; if ($class) { // run the migration "up" method $class::up(); // add this class to the list of rollbacks, just in case $rollback[] = $class; } else { throw new Exception("Missing migration class '{$class}' for entry {$value}"); } } else { throw new Exception("Missing migration number: {$value}"); } } } catch (Exception $e) { // we need to rollback // reverse the rollback array, since items were added to the end $rollback = array_reverse($rollback); // step through and roll back foreach ($rollback as $class) { $class::down(); } // and rethrow the exception throw $e; } // if we get here, then everything succeeded // save the last migration counter Database::execute("UPDATE " . static::$table_name . " SET last=:last WHERE id=1;", array(':last' => $value)); }
/** * Enable profiling table when it's turned on */ protected function doEnableProfiling() { global $wgProfiler; if (!$this->doTable('profiling')) { return; } $profileToDb = false; if (isset($wgProfiler['output'])) { $out = $wgProfiler['output']; if ($out === 'db') { $profileToDb = true; } elseif (is_array($out) && in_array('db', $out)) { $profileToDb = true; } } if ($profileToDb && !$this->db->tableExists('profiling', __METHOD__)) { $this->applyPatch('patch-profiling.sql', false, 'Add profiling table'); } }
function checkTables() { if (!parent::tableExists('baseline')) { $text = "CREATE TABLE IF NOT EXISTS `baseline` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `filepath` varchar(255) NOT NULL,\n `hash` varchar(32) NOT NULL,\n `state` tinyint(4) NOT NULL,\n `date_added` datetime NOT NULL,\n `date_checked` datetime NOT NULL,\n PRIMARY KEY (`id`),\n KEY `Filepath` (`filepath`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=8154"; $ok = parent::runQuery($text); if ($ok) { Logfile::writeWhen("Table 'baseline' created"); } else { Logfile::writeError("Table creation 'baseline' FAILED"); } } if (!parent::tableExists('tested')) { $text = "CREATE TABLE `tested` (\n `tested` datetime NOT NULL,\n `total` int(11),\n `new` int(11),\n `changed` int(11),\n `deleted` int(11),\n `emailsent` tinyint(1) DEFAULT NULL\n) ENGINE=MyISAM DEFAULT CHARSET=utf8"; $ok = parent::runQuery($text); if ($ok) { Logfile::writeWhen("Table 'tested' created"); } else { Logfile::writeError("Table creation 'tested' FAILED"); } } }
/** exdoc * This function restores a database (overwriting all data in * any existing tables) from an EQL object dump. Returns true if * the restore was a success and false if something went horribly wrong * (unable to read file, etc.) Even if true is returned, there is a chance * that some errors were encountered. Check $errors to be sure everything * was fine. * * @param Database $db The database to restore to * @param string $file The filename of the EQL file to restore from * @param array $errors A referenced array that stores errors. Whatever * variable is passed in this argument will contain all errors encountered * during the parse/restore. * @param null $force_version * @return bool * @node Model:expFile */ public static function restoreDatabase($db, $file, &$errors, $force_version = null) { $errors = array(); if (is_readable($file)) { $lines = @file($file); // Sanity check if (count($lines) < 2 || trim($lines[0]) != EQL_HEADER) { $errors[] = gt('Not a valid EQL file'); return false; } if ($force_version == null) { $version = explode(':', trim($lines[1])); $eql_version = $version[1] + 0; } else { $eql_version = $force_version; } $current_version = EXPONENT + 0; $clear_function = ''; $fprefix = ''; // Check version and include necessary converters //FIXME We reject v1.0 eql files if ($eql_version != $current_version) { $errors[] = gt('EQL file was Not a valid EQL version'); return false; // $fprefix = 'expFile::'.implode('',explode('.',$eql_version)).'_'; // if (function_exists($fprefix.'clearedTable')) { // $clear_function = $fprefix.'clearedTable'; // } } // make sure the database tables are up to date administrationController::install_dbtables(); $table = ''; $table_function = ''; for ($i = 2; $i < count($lines); $i++) { $line_number = $i; $line = trim($lines[$i]); if ($line != '') { $pair = explode(':', $line); $pair[1] = implode(':', array_slice($pair, 1)); $pair = array_slice($pair, 0, 2); if ($pair[0] == 'TABLE') { $table = $pair[1]; if ($fprefix != '') { $table_function = $fprefix . $table; } if ($db->tableExists($table)) { $db->delete($table); if ($clear_function != '') { $clear_function($db, $table); } } else { // if (!file_exists(BASE.'framework/core/definitions/'.$table.'.php')) { $errors[] = sprintf(gt('Table "%s" not found in the system (line %d)'), $table, $line_number); // } else if (!is_readable(BASE.'framework/core/definitions/'.$table.'.php')) { // $errors[] = sprintf(gt('Data definition file for %s (%s) is not readable (line %d)'),$table,'framework/core/definitions/'.$table.'.php',$line_number); // } else { // $dd = include(BASE.'framework/core/definitions/'.$table.'.php'); // $info = (is_readable(BASE.'framework/core/definitions/'.$table.'.info.php') ? include(BASE.'framework/core/definitions/'.$table.'.info.php') : array()); // $db->createTable($table,$dd,$info); // } } } else { if ($pair[0] == 'RECORD') { // Here we need to check the conversion scripts. $pair[1] = str_replace('\\r\\n', "\r\n", $pair[1]); $object = unserialize($pair[1]); if (function_exists($table_function)) { $table_function($db, $object); } else { $db->insertObject($object, $table); } } else { $errors[] = sprintf(gt('Invalid specifier type "%s" (line %d)'), $pair[0], $line_number); } } } } if ($eql_version != $current_version) { $errors[] = gt('EQL file was Not a valid EQL version'); return false; } return true; } else { $errors[] = gt('Unable to read EQL file'); return false; } }
/** * database connection test. */ public function test_database_connection() { $name = "test_database_connection"; $db = new Database(); test($db->getDatabaseObject()); if ($db->tableExists($name)) { $db->dropTable($name); } // table exists test($db->tableExists($name) == FALSE); $db->createTable($name); test($db->tableExists($name)); // quote // @Attention 반드시 아래의 quote 가 통과를 해야 한다. $ret_str = $db->quote("str"); test($ret_str == "'str'", '', 'Quote failed...'); $ret_str = $db->quote("st'r"); test($ret_str == "'st''r'", '', 'Quote failed...'); // table drop $db->dropTable($name); test($db->tableExists($name) == FALSE); }
public static function createHashColumn($table, $columnName) { // Sanitize $table = Sanitize::variable($table); $columnName = Sanitize::variable($columnName); $prefix = Sanitize::word(substr($table, 0, 4) . ucfirst(substr($columnName, 0, 6))); // Make sure table exists if (Database::tableExists($table)) { $colExists = false; // Add the hash column if it doesn't exist if (!Database::columnExists($table, $columnName)) { $colExists = Database::addColumn($table, $columnName . '_crc', "int(10) unsigned not null", 0); } if ($colExists) { // Create a Trigger self::exec('CREATE TRIGGER ' . $prefix . '_ins BEFORE INSERT ON ' . $table . ' FOR EACH ROW BEGIN SET NEW.' . $columnName . '_crc=crc32(NEW.' . $columnName . '); END;'); return self::exec('CREATE TRIGGER ' . $prefix . '_upd BEFORE UPDATE ON ' . $table . ' FOR EACH ROW BEGIN SET NEW.' . $columnName . '_crc=crc32(NEW.' . $columnName . '); END; '); } } return false; }
/** * @return bool */ public function exists() { return self::$db->tableExists($this->name()); }
public function testUnknownTableCorruptsResults() { $res = $this->db->select('page', '*', ['page_id' => 1]); $this->assertFalse($this->db->tableExists('foobarbaz')); $this->assertInternalType('int', $res->numRows()); }
continue; } $class = substr($i, 0, -10); if ($class == 'DBObject') { continue; } $classes[] = $class; } try { foreach ($classes as $class) { echo 'Checking class ' . $class . "\n"; $datamap = call_user_func($class . '::getDataMap'); $table = call_user_func($class . '::getDBTable'); // Check if table exists echo 'Look for table ' . $table . "\n"; if (Database::tableExists($table)) { echo 'Table found, check columns' . "\n"; $existing_columns = Database::getTableColumns($table); echo 'Found ' . count($existing_columns) . ' columns in existing table : ' . implode(', ', $existing_columns) . "\n"; $required_columns = array_keys($datamap); echo 'Found ' . count($required_columns) . ' columns in required table : ' . implode(', ', $required_columns) . "\n"; $missing = array(); foreach ($required_columns as $c) { if (!in_array($c, $existing_columns)) { $missing[] = $c; } } if (count($missing)) { echo 'Found ' . count($missing) . ' missing columns in existing table : ' . implode(', ', $missing) . "\n"; foreach ($missing as $column) { Database::createTableColumn($table, $column, $datamap[$column]);
/** * Update database */ public static function updateStructure() { $class = static::getClassName(); Logger::info('Updating ' . $class . ' database structure'); $datamap = static::getDataMap(); $table = static::getDBTable(); // Check if table exists Logger::info('Look for table ' . $table); if (Database::tableExists($table)) { Logger::info('Table found, check columns'); $existing_columns = Database::getTableColumns($table); Logger::info('Found ' . count($existing_columns) . ' columns in existing table : ' . implode(', ', $existing_columns)); $required_columns = array_keys($datamap); Logger::info('Found ' . count($required_columns) . ' columns in required table : ' . implode(', ', $required_columns)); $missing = array(); foreach ($required_columns as $c) { if (!in_array($c, $existing_columns)) { $missing[] = $c; } } if (count($missing)) { Logger::info('Found ' . count($missing) . ' missing columns in existing table : ' . implode(', ', $missing)); foreach ($missing as $column) { Database::createTableColumn($table, $column, $datamap[$column]); } } $useless = array(); foreach ($existing_columns as $c) { if (!in_array($c, $required_columns)) { $useless[] = $c; } } if (count($useless)) { Logger::info('Found ' . count($useless) . ' useless columns in existing table : ' . implode(', ', $useless)); foreach ($useless as $column) { Database::removeTableColumn($table, $column); } } Logger::info('Check column format'); foreach ($required_columns as $column) { if (in_array($column, $missing)) { continue; } // Already created with the right format $problems = Database::checkTableColumnFormat($table, $column, $datamap[$column], function ($message) { Logger::info("\t" . $message); }); if ($problems) { Logger::info('Column ' . $column . ' has bad format, updating it'); Database::updateTableColumnFormat($table, $column, $datamap[$column], $problems); } } } else { Logger::info('Table is missing, create it'); Database::createTable($table, $datamap); } Logger::info('Done for ' . $class); }
/** * Check if the tracking tables exist. * @return bool */ public function trackingTablesExist() { return $this->dbms->tableExists('dbtrack_actions') && $this->dbms->tableExists('dbtrack_data'); }
function execute() { $this->dbw = $this->getDB(DB_MASTER); $logging = $this->dbw->tableName('logging'); $logging_1_10 = $this->dbw->tableName('logging_1_10'); $logging_pre_1_10 = $this->dbw->tableName('logging_pre_1_10'); if ($this->dbw->tableExists('logging_pre_1_10') && !$this->dbw->tableExists('logging')) { # Fix previous aborted run echo "Cleaning up from previous aborted run\n"; $this->dbw->query("RENAME TABLE {$logging_pre_1_10} TO {$logging}", __METHOD__); } if ($this->dbw->tableExists('logging_pre_1_10')) { echo "This script has already been run to completion\n"; return; } # Create the target table if (!$this->dbw->tableExists('logging_1_10')) { global $wgDBTableOptions; $sql = <<<EOT CREATE TABLE {$logging_1_10} ( -- Log ID, for referring to this specific log entry, probably for deletion and such. log_id int unsigned NOT NULL auto_increment, -- Symbolic keys for the general log type and the action type -- within the log. The output format will be controlled by the -- action field, but only the type controls categorization. log_type varbinary(10) NOT NULL default '', log_action varbinary(10) NOT NULL default '', -- Timestamp. Duh. log_timestamp binary(14) NOT NULL default '19700101000000', -- The user who performed this action; key to user_id log_user int unsigned NOT NULL default 0, -- Key to the page affected. Where a user is the target, -- this will point to the user page. log_namespace int NOT NULL default 0, log_title varchar(255) binary NOT NULL default '', -- Freeform text. Interpreted as edit history comments. log_comment varchar(255) NOT NULL default '', -- LF separated list of miscellaneous parameters log_params blob NOT NULL, -- rev_deleted for logs log_deleted tinyint unsigned NOT NULL default '0', PRIMARY KEY log_id (log_id), KEY type_time (log_type, log_timestamp), KEY user_time (log_user, log_timestamp), KEY page_time (log_namespace, log_title, log_timestamp), KEY times (log_timestamp) ) {$wgDBTableOptions} EOT; echo "Creating table logging_1_10\n"; $this->dbw->query($sql, __METHOD__); } # Synchronise the tables echo "Doing initial sync...\n"; $this->sync('logging', 'logging_1_10'); echo "Sync done\n\n"; # Rename the old table away echo "Renaming the old table to {$logging_pre_1_10}\n"; $this->dbw->query("RENAME TABLE {$logging} TO {$logging_pre_1_10}", __METHOD__); # Copy remaining old rows # Done before the new table is active so that $copyPos is accurate echo "Doing final sync...\n"; $this->sync('logging_pre_1_10', 'logging_1_10'); # Move the new table in echo "Moving the new table in...\n"; $this->dbw->query("RENAME TABLE {$logging_1_10} TO {$logging}", __METHOD__); echo "Finished.\n"; }