/** * Wrapper for the mysqli::query method. * * @throws MpmMalformedQueryException * * @param string $query the SQL query to send to MySQL * @param int $resultMode Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior * @param bool $is_internal set to true for internal SQL calls which won't each SQL back when in dry run mode * * @return mysqli_result */ public function query($query, $resultMode = MYSQLI_STORE_RESULT, $is_internal = false) { if (!$is_internal) { // Log to sql log file MpmSqlLogger::log_to_file($query); } if ($this->dryrun) { if (!$is_internal) { echo "\nSQL: " . $query . "\n"; } return true; } else { // not dry-run $result = parent::query($query, $resultMode); if ($this->errno) { throw new MpmMalformedQueryException($this->error); } return $result; } }
/** * @static * @param object $obj a simple object with migration information (from a migration list) * @param string $method * @param array $options * @return mixed */ public static function runMigration(&$obj, $method = 'up', array $options = array()) { // if true, exceptions will not cause the script to exit $forced = isset($options['forced']) ? $options['forced'] : false; // if true, only echo back the SQL to be run $dryrun = isset($options['dryrun']) ? $options['dryrun'] : false; $db_config = MpmDbHelper::get_db_config(); $migrations_table = $db_config->migrations_table; $filename = MpmStringHelper::getFilenameFromTimestamp($obj->timestamp); $classname = 'Migration_' . str_replace('.php', '', $filename); // make sure the file exists; if it doesn't, skip it but display a message $migration_file = MpmListHelper::get_migration_file(MPM_DB_PATH . $filename); if (!$migration_file) { echo "\n\tMigration " . $obj->timestamp . ' (ID ' . $obj->id . ') skipped - file missing.'; return; } // file exists -- run the migration require_once $migration_file; $migration = new $classname(); $msg = "# Performing " . strtoupper($method) . " migration " . $obj->timestamp . ' (ID ' . $obj->id . ')'; if (!empty($migration->info)) { $msg .= "\n# {$migration->info}"; } echo "\n" . $msg . " ... "; MpmSqlLogger::log_to_file("\n" . $msg . "\n"); if ($migration instanceof MpmMigration) { $dbObj = MpmDbHelper::getPdoObj(); } else { $dbObj = MpmDbHelper::getMysqliObj(); } if ($dryrun) { $dbObj->dryrun = true; } $dbObj->beginTransaction(); if ($method == 'down') { $active = 0; } else { $active = 1; } try { $migration->{$method}($dbObj); $sql = "UPDATE `{$migrations_table}` SET `active` = '{$active}' WHERE `id` = {$obj->id}"; $dbObj->internal_exec($sql); } catch (Exception $e) { $dbObj->rollback(); echo "failed!"; echo "\n"; $clw = MpmCommandLineWriter::getInstance(); $clw->writeLine($e->getMessage(), 12); if (!$forced) { echo "\n\n"; // Return with non-0 error code to notify external caller to stop the deployment exit(1); } else { return; } } $dbObj->commit(); echo "done."; }