private function addCoreDBData() { # disabled for performance #$this->tablesUsed[] = 'page'; #$this->tablesUsed[] = 'revision'; if ($this->db->getType() == 'oracle') { # Insert 0 user to prevent FK violations # Anonymous user $this->db->insert('user', array('user_id' => 0, 'user_name' => 'Anonymous'), __METHOD__, array('IGNORE')); # Insert 0 page to prevent FK violations # Blank page $this->db->insert('page', array('page_id' => 0, 'page_namespace' => 0, 'page_title' => ' ', 'page_restrictions' => NULL, 'page_counter' => 0, 'page_is_redirect' => 0, 'page_is_new' => 0, 'page_random' => 0, 'page_touched' => $this->db->timestamp(), 'page_latest' => 0, 'page_len' => 0), __METHOD__, array('IGNORE')); } User::resetIdByNameCache(); //Make sysop user $user = User::newFromName('UTSysop'); if ($user->idForName() == 0) { $user->addToDatabase(); $user->setPassword('UTSysopPassword'); $user->addGroup('sysop'); $user->addGroup('bureaucrat'); $user->saveSettings(); } //Make 1 page with 1 revision $page = WikiPage::factory(Title::newFromText('UTPage')); if (!$page->getId() == 0) { $page->doEdit('UTContent', 'UTPageSummary', EDIT_NEW, false, User::newFromName('UTSysop')); } }
/** * Batch insert rows * * @param array $info Array with array members that have 'name' and 'wiki' keys */ public function batchInsert(array $info) { $rows = array(); foreach ($info as $row) { $rows[] = array('utr_name' => $row['name'], 'utr_wiki' => $row['wiki']); } $this->db->insert('users_to_rename', $rows, __METHOD__, array('IGNORE')); }
/** * Copy local links to global table * * @param $title Title Title of the file to copy entries from. */ public function copyLocalImagelinks($title) { global $wgContLang; $dbr = wfGetDB(DB_SLAVE); $res = $dbr->select(array('imagelinks', 'page'), array('il_to', 'page_id', 'page_namespace', 'page_title'), array('il_from = page_id', 'il_to' => $title->getDBkey()), __METHOD__); $insert = array(); foreach ($res as $row) { $insert[] = array('gil_wiki' => $this->interwiki, 'gil_page' => $row->page_id, 'gil_page_namespace_id' => $row->page_namespace, 'gil_page_namespace' => $wgContLang->getNsText($row->page_namespace), 'gil_page_title' => $row->page_title, 'gil_to' => $row->il_to); } $this->db->insert('globalimagelinks', $insert, __METHOD__, array('IGNORE')); }
function copyExactMatch($srcTable, $dstTable, $copyPos) { $numRowsCopied = 0; $srcRes = $this->dbw->select($srcTable, '*', array('log_timestamp' => $copyPos), __METHOD__); $dstRes = $this->dbw->select($dstTable, '*', array('log_timestamp' => $copyPos), __METHOD__); if ($srcRes->numRows()) { $srcRow = $srcRes->fetchObject(); $srcFields = array_keys((array) $srcRow); $srcRes->seek(0); $dstRowsSeen = array(); # Make a hashtable of rows that already exist in the destination foreach ($dstRes as $dstRow) { $reducedDstRow = array(); foreach ($srcFields as $field) { $reducedDstRow[$field] = $dstRow->{$field}; } $hash = md5(serialize($reducedDstRow)); $dstRowsSeen[$hash] = true; } # Copy all the source rows that aren't already in the destination foreach ($srcRes as $srcRow) { $hash = md5(serialize((array) $srcRow)); if (!isset($dstRowsSeen[$hash])) { $this->dbw->insert($dstTable, (array) $srcRow, __METHOD__); $numRowsCopied++; } } } return $numRowsCopied; }
private function addCoreDBData() { if ($this->db->getType() == 'oracle') { # Insert 0 user to prevent FK violations # Anonymous user if (!$this->db->selectField('user', '1', ['user_id' => 0])) { $this->db->insert('user', ['user_id' => 0, 'user_name' => 'Anonymous'], __METHOD__, ['IGNORE']); } # Insert 0 page to prevent FK violations # Blank page if (!$this->db->selectField('page', '1', ['page_id' => 0])) { $this->db->insert('page', ['page_id' => 0, 'page_namespace' => 0, 'page_title' => ' ', 'page_restrictions' => null, 'page_is_redirect' => 0, 'page_is_new' => 0, 'page_random' => 0, 'page_touched' => $this->db->timestamp(), 'page_latest' => 0, 'page_len' => 0], __METHOD__, ['IGNORE']); } } User::resetIdByNameCache(); // Make sysop user $user = static::getTestSysop()->getUser(); // Make 1 page with 1 revision $page = WikiPage::factory(Title::newFromText('UTPage')); if ($page->getId() == 0) { $page->doEditContent(new WikitextContent('UTContent'), 'UTPageSummary', EDIT_NEW, false, $user); // doEditContent() probably started the session via // User::loadFromSession(). Close it now. if (session_id() !== '') { session_write_close(); session_id(''); } } }
/** * @param ResultWrapper $res * @param DatabaseBase $dbw * @return null|int */ function convertOptionBatch($res, $dbw) { $id = null; foreach ($res as $row) { $this->mConversionCount++; $insertRows = array(); foreach (explode("\n", $row->user_options) as $s) { $m = array(); if (!preg_match("/^(.[^=]*)=(.*)\$/", $s, $m)) { continue; } // MW < 1.16 would save even default values. Filter them out // here (as in User) to avoid adding many unnecessary rows. $defaultOption = User::getDefaultOption($m[1]); if (is_null($defaultOption) || $m[2] != $defaultOption) { $insertRows[] = array('up_user' => $row->user_id, 'up_property' => $m[1], 'up_value' => $m[2]); } } if (count($insertRows)) { $dbw->insert('user_properties', $insertRows, __METHOD__, array('IGNORE')); } $dbw->update('user', array('user_options' => ''), array('user_id' => $row->user_id), __METHOD__); $id = $row->user_id; } return $id; }
/** * Common function for databases that don't understand the MySQLish syntax of interwiki.sql. * * @return Status */ public function populateInterwikiTable() { $status = $this->getConnection(); if (!$status->isOK()) { return $status; } $this->db->selectDB($this->getVar('wgDBname')); if ($this->db->selectRow('interwiki', '*', array(), __METHOD__)) { $status->warning('config-install-interwiki-exists'); return $status; } global $IP; wfSuppressWarnings(); $rows = file("{$IP}/maintenance/interwiki.list", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); wfRestoreWarnings(); $interwikis = array(); if (!$rows) { return Status::newFatal('config-install-interwiki-list'); } foreach ($rows as $row) { $row = preg_replace('/^\\s*([^#]*?)\\s*(#.*)?$/', '\\1', $row); // strip comments - whee if ($row == "") { continue; } $row .= "||"; $interwikis[] = array_combine(array('iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid'), explode('|', $row)); } $this->db->insert('interwiki', $interwikis, __METHOD__); return Status::newGood(); }
private function addCoreDBData() { if ($this->db->getType() == 'oracle') { # Insert 0 user to prevent FK violations # Anonymous user $this->db->insert('user', array('user_id' => 0, 'user_name' => 'Anonymous'), __METHOD__, array('IGNORE')); # Insert 0 page to prevent FK violations # Blank page $this->db->insert('page', array('page_id' => 0, 'page_namespace' => 0, 'page_title' => ' ', 'page_restrictions' => null, 'page_is_redirect' => 0, 'page_is_new' => 0, 'page_random' => 0, 'page_touched' => $this->db->timestamp(), 'page_latest' => 0, 'page_len' => 0), __METHOD__, array('IGNORE')); } User::resetIdByNameCache(); // Make sysop user $user = User::newFromName('UTSysop'); if ($user->idForName() == 0) { $user->addToDatabase(); TestUser::setPasswordForUser($user, 'UTSysopPassword'); } // Always set groups, because $this->resetDB() wipes them out $user->addGroup('sysop'); $user->addGroup('bureaucrat'); // Make 1 page with 1 revision $page = WikiPage::factory(Title::newFromText('UTPage')); if ($page->getId() == 0) { $page->doEditContent(new WikitextContent('UTContent'), 'UTPageSummary', EDIT_NEW, false, $user); // doEditContent() probably started the session via // User::loadFromSession(). Close it now. if (session_id() !== '') { session_write_close(); session_id(''); } } }
protected function setAppliedUpdates($version, $updates = array()) { if (!$this->canUseNewUpdatelog()) { return; } $key = "updatelist-{$version}-" . time(); $this->db->insert('updatelog', array('ul_key' => $key, 'ul_value' => serialize($updates)), __METHOD__); }
/** * @param DatabaseBase $dbw * @return void */ private function insertData($dbw) { $range = range(0, 1024); $data = array(); foreach ($range as $r) { $data[] = array('text' => $r); } $dbw->insert('test', $data, __METHOD__); }
/** * Helper function: Add a key to the updatelog table * Obviously, only use this for updates that occur after the updatelog table was * created! * @param string $key Name of key to insert * @param string $val [optional] value to insert along with the key */ public function insertUpdateRow( $key, $val = null ) { $this->db->clearFlag( DBO_DDLMODE ); $values = array( 'ul_key' => $key ); if ( $val && $this->canUseNewUpdatelog() ) { $values['ul_value'] = $val; } $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' ); $this->db->setFlag( DBO_DDLMODE ); }
/** * @see PropertyStatisticsStore::insertUsageCount * * @since 1.9 * * @param integer $propertyId * @param integer $value * * @return boolean Success indicator * @throws MWException */ public function insertUsageCount($propertyId, $value) { if (!is_int($value) || $value < 0) { throw new MWException('The value to add must be a positive integer'); } if (!is_int($propertyId) || $propertyId <= 0) { throw new MWException('The property id to add must be a positive integer'); } return $this->dbConnection->insert($this->table, array('usage_count' => $value, 'p_id' => $propertyId), __METHOD__); }
private function initDB() { global $wgDBprefix; if ($wgDBprefix === $this->dbPrefix()) { throw new MWException('Cannot run unit tests, the database prefix is already "unittest_"'); } $dbClone = new CloneDatabase($this->db, $this->listTables(), $this->dbPrefix()); $dbClone->useTemporaryTables($this->useTemporaryTables); $dbClone->cloneTableStructure(); if ($this->db->getType() == 'oracle') { $this->db->query('BEGIN FILL_WIKI_INFO; END;'); # Insert 0 user to prevent FK violations # Anonymous user $this->db->insert('user', array('user_id' => 0, 'user_name' => 'Anonymous')); } }
function tryInsertWiki(DatabaseBase $db, $wikiId) { if (is_string($wikiId)) { $w = WikiFactory::UrlToID($wikiId); if ($w == null) { throw new Exception("Can't resolve " . $wikiId); } $wikiId = $w; } $res = $db->select("webmaster_sitemaps", array('wiki_id'), array("wiki_id" => $wikiId), __METHOD__); if ($res->fetchRow()) { return false; } //echo "insert: " . $wikiId . "\n"; if (!$db->insert("webmaster_sitemaps", array("wiki_id" => $wikiId, "user_id" => null))) { throw new Exception("can't insert wiki id = " . $wikiId); } return true; }
/** * Insert a new empty page record for this article. * This *must* be followed up by creating a revision * and running $this->updateRevisionOn( ... ); * or else the record will be left in a funky state. * Best if all done inside a transaction. * * @param DatabaseBase $dbw * @return int|bool The newly created page_id key; false if the title already existed */ public function insertOn($dbw) { $page_id = $dbw->nextSequenceValue('page_page_id_seq'); $dbw->insert('page', array('page_id' => $page_id, 'page_namespace' => $this->mTitle->getNamespace(), 'page_title' => $this->mTitle->getDBkey(), 'page_restrictions' => '', 'page_is_redirect' => 0, 'page_is_new' => 1, 'page_random' => wfRandom(), 'page_touched' => $dbw->timestamp(), 'page_latest' => 0, 'page_len' => 0), __METHOD__, 'IGNORE'); $affected = $dbw->affectedRows(); if ($affected) { $newid = $dbw->insertId(); $this->mId = $newid; $this->mTitle->resetArticleID($newid); return $newid; } else { return false; } }
/** * Based on generic method (parent) with some prior SQLite-sepcific adjustments */ function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) { if (!count($a)) { return true; } if (!is_array($options)) { $options = array($options); } # SQLite uses OR IGNORE not just IGNORE foreach ($options as $k => $v) { if ($v == 'IGNORE') { $options[$k] = 'OR IGNORE'; } } # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts if (isset($a[0]) && is_array($a[0])) { $ret = true; foreach ($a as $k => $v) { if (!parent::insert($table, $v, "{$fname}/multi-row", $options)) { $ret = false; } } } else { $ret = parent::insert($table, $a, "{$fname}/single-row", $options); } return $ret; }
/** * Quickie protection against huuuuuuuuge batch inserts * * @param DatabaseBase $db * @param String $table * @param Array $data * @param string $method * @param array $options * @return void */ protected static function insertChunks($db, $table, $data, $method = __METHOD__, $options = array()) { $chunkSize = 100; for ($i = 0; $i < count($data); $i += $chunkSize) { $db->insert($table, array_slice($data, $i, $chunkSize), $method, $options); } }
/** * This function should *not* be called outside of JobQueueDB * * @param DatabaseBase $dbw * @param array $jobs * @param int $flags * @param string $method * @return boolean * @throws type */ public function doBatchPushInternal(DatabaseBase $dbw, array $jobs, $flags, $method) { if (!count($jobs)) { return true; } $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated $rowList = array(); // list of jobs for jobs that are are not de-duplicated foreach ($jobs as $job) { $row = $this->insertFields($job); if ($job->ignoreDuplicates()) { $rowSet[$row['job_sha1']] = $row; } else { $rowList[] = $row; } } if ($flags & self::QOS_ATOMIC) { $dbw->begin($method); // wrap all the job additions in one transaction } try { // Strip out any duplicate jobs that are already in the queue... if (count($rowSet)) { $res = $dbw->select('job', 'job_sha1', array('job_sha1' => array_keys($rowSet), 'job_token' => ''), $method); foreach ($res as $row) { wfDebug("Job with hash '{$row->job_sha1}' is a duplicate.\n"); unset($rowSet[$row->job_sha1]); // already enqueued } } // Build the full list of job rows to insert $rows = array_merge($rowList, array_values($rowSet)); // Insert the job rows in chunks to avoid slave lag... foreach (array_chunk($rows, 50) as $rowBatch) { $dbw->insert('job', $rowBatch, $method); } JobQueue::incrStats('job-insert', $this->type, count($rows)); JobQueue::incrStats('job-insert-duplicate', $this->type, count($rowSet) + count($rowList) - count($rows)); } catch (DBError $e) { if ($flags & self::QOS_ATOMIC) { $dbw->rollback($method); } throw $e; } if ($flags & self::QOS_ATOMIC) { $dbw->commit($method); } $this->cache->set($this->getCacheKey('empty'), 'false', JobQueueDB::CACHE_TTL_LONG); return true; }
/** * Helper function to initializeDbForNewAd() * * @param DatabaseBase $db */ protected function initializeDbBasicData($db) { $db->insert('pr_ads', array('ad_name' => $this->name), __METHOD__); $this->id = $db->insertId(); }
/** * Update one property table by inserting or deleting rows, and compute * the changes that this entails for the property usage counts. The * given rows are inserted into the table if $insert is true; otherwise * they are deleted. The property usage counts are recorded in the * call-by-ref parameter $propertyUseIncrements. * * The method assumes that all of the given rows are about the same * subject. This is ensured by callers. * * @since 1.8 * @param array $propertyUseIncrements * @param SMWSQLStore3Table $propertyTable * @param array $rows array of rows to insert/delete * @param boolean $insert * @param DatabaseBase $dbw used for writing */ protected function writePropertyTableRowUpdates(array &$propertyUseIncrements, SMWSQLStore3Table $propertyTable, array $rows, $insert, DatabaseBase $dbw) { if (empty($rows)) { //print "Nothing to " . ( $insert ? 'insert' : 'delete' ) . " for table {$propertyTable->getName()}.\n"; //DEBUG return; } //print ( $insert ? 'Inserting ' : 'Deleting ' ) . count( $rows ) . " row(s) in table {$propertyTable->getName()}.\n"; //DEBUG //print var_export( $rows, true ) . "\n"; //DEBUG if (!$propertyTable->usesIdSubject()) { // does not occur, but let's be strict throw new InvalidArgumentException('Operation not supported for tables without subject IDs.'); } if ($insert) { $dbw->insert($propertyTable->getName(), array_values($rows), "SMW::writePropertyTableRowUpdates-insert-{$propertyTable->getName()}"); } else { $condition = ''; // We build a condition that mentions s_id only once, // since it must be the same for all rows. This should // help the DBMS in selecting the rows (it would not be // easy for to detect that all tuples share one s_id). $sid = false; foreach ($rows as $row) { if ($sid === false) { $sid = $row['s_id']; // 's_id' exists for all tables with $propertyTable->usesIdSubject() } unset($row['s_id']); if ($condition != '') { $condition .= ' OR '; } $condition .= '(' . $dbw->makeList($row, LIST_AND) . ')'; } $condition = "s_id=" . $dbw->addQuotes($sid) . " AND ({$condition})"; $dbw->delete($propertyTable->getName(), array($condition), "SMW::writePropertyTableRowUpdates-delete-{$propertyTable->getName()}"); } if ($propertyTable->isFixedPropertyTable()) { $property = new SMWDIProperty($propertyTable->getFixedProperty()); $pid = $this->store->smwIds->makeSMWPropertyID($property); } foreach ($rows as $row) { if (!$propertyTable->isFixedPropertyTable()) { $pid = $row['p_id']; } if (!array_key_exists($pid, $propertyUseIncrements)) { $propertyUseIncrements[$pid] = 0; } $propertyUseIncrements[$pid] += $insert ? 1 : -1; } }
/** * Insert a new revision into the database, returning the new revision ID * number on success and dies horribly on failure. * * @param DatabaseBase $dbw (master connection) * @throws MWException * @return int */ public function insertOn($dbw) { global $wgDefaultExternalStore, $wgContentHandlerUseDB; $this->checkContentModel(); $data = $this->mText; $flags = self::compressRevisionText($data); # Write to external storage if required if ($wgDefaultExternalStore) { // Store and get the URL $data = ExternalStore::insertToDefault($data); if (!$data) { throw new MWException("Unable to store text to external storage"); } if ($flags) { $flags .= ','; } $flags .= 'external'; } # Record the text (or external storage URL) to the text table if ($this->mTextId === null) { $old_id = $dbw->nextSequenceValue('text_old_id_seq'); $dbw->insert('text', array('old_id' => $old_id, 'old_text' => $data, 'old_flags' => $flags), __METHOD__); $this->mTextId = $dbw->insertId(); } if ($this->mComment === null) { $this->mComment = ""; } # Record the edit in revisions $rev_id = $this->mId !== null ? $this->mId : $dbw->nextSequenceValue('revision_rev_id_seq'); $row = array('rev_id' => $rev_id, 'rev_page' => $this->mPage, 'rev_text_id' => $this->mTextId, 'rev_comment' => $this->mComment, 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0, 'rev_user' => $this->mUser, 'rev_user_text' => $this->mUserText, 'rev_timestamp' => $dbw->timestamp($this->mTimestamp), 'rev_deleted' => $this->mDeleted, 'rev_len' => $this->mSize, 'rev_parent_id' => $this->mParentId === null ? $this->getPreviousRevisionId($dbw) : $this->mParentId, 'rev_sha1' => $this->mSha1 === null ? Revision::base36Sha1($this->mText) : $this->mSha1); if ($wgContentHandlerUseDB) { // NOTE: Store null for the default model and format, to save space. // XXX: Makes the DB sensitive to changed defaults. // Make this behavior optional? Only in miser mode? $model = $this->getContentModel(); $format = $this->getContentFormat(); $title = $this->getTitle(); if ($title === null) { throw new MWException("Insufficient information to determine the title of the " . "revision's page!"); } $defaultModel = ContentHandler::getDefaultModelFor($title); $defaultFormat = ContentHandler::getForModelID($defaultModel)->getDefaultFormat(); $row['rev_content_model'] = $model === $defaultModel ? null : $model; $row['rev_content_format'] = $format === $defaultFormat ? null : $format; } $dbw->insert('revision', $row, __METHOD__); $this->mId = $rev_id !== null ? $rev_id : $dbw->insertId(); // Assertion to try to catch T92046 if ((int) $this->mId === 0) { throw new UnexpectedValueException('After insert, Revision mId is ' . var_export($this->mId, 1) . ': ' . var_export($row, 1)); } Hooks::run('RevisionInsertComplete', array(&$this, $data, $flags)); return $this->mId; }
public function set($key, $value) { if ($this->readOnly) { return; } if (is_null($this->currentLang)) { throw new MWException(__CLASS__ . ': must call startWrite() before calling set()'); } $this->batch[] = array('lc_lang' => $this->currentLang, 'lc_key' => $key, 'lc_value' => $this->dbw->encodeBlob(serialize($value))); if (count($this->batch) >= 100) { $this->dbw->insert('l10n_cache', $this->batch, __METHOD__); $this->batch = array(); } }
public function finishWrite() { if ($this->readOnly) { return; } elseif (is_null($this->currentLang)) { throw new MWException(__CLASS__ . ': must call startWrite() before finishWrite()'); } $this->dbw->begin(__METHOD__); try { $this->dbw->delete('l10n_cache', array('lc_lang' => $this->currentLang), __METHOD__); foreach (array_chunk($this->batch, 500) as $rows) { $this->dbw->insert('l10n_cache', $rows, __METHOD__); } $this->writesDone = true; } catch (DBQueryError $e) { if ($this->dbw->wasReadOnlyError()) { $this->readOnly = true; // just avoid site down time } else { throw $e; } } $this->dbw->commit(__METHOD__); $this->currentLang = null; $this->batch = array(); }
/** * Create some initial DB entries for important built-in properties. Having the DB contents predefined * allows us to safe DB calls when certain data is needed. At the same time, the entries in the DB * make sure that DB-based functions work as with all other properties. */ protected function setupPredefinedProperties($verbose, DatabaseBase $db) { global $wgDBtype; $this->reportProgress("Setting up internal property indices ...\n", $verbose); // Check if we already have this structure $borderiw = $db->selectField(SMWSQLStore3::ID_TABLE, 'smw_iw', 'smw_id=' . $db->addQuotes(\SMWSql3SmwIds::FXD_PROP_BORDER_ID)); if ($borderiw != SMW_SQL3_SMWBORDERIW) { $this->reportProgress(" ... allocating space for internal properties ...\n", $verbose); $this->store->smwIds->moveSMWPageID(\SMWSql3SmwIds::FXD_PROP_BORDER_ID); // make sure position 50 is empty $db->insert(SMWSQLStore3::ID_TABLE, array('smw_id' => \SMWSql3SmwIds::FXD_PROP_BORDER_ID, 'smw_title' => '', 'smw_namespace' => 0, 'smw_iw' => SMW_SQL3_SMWBORDERIW, 'smw_subobject' => '', 'smw_sortkey' => ''), 'SMW::setup'); // put dummy "border element" on index 50 $this->reportProgress(' ', $verbose); for ($i = 0; $i < \SMWSql3SmwIds::FXD_PROP_BORDER_ID; $i++) { // make way for built-in ids $this->store->smwIds->moveSMWPageID($i); $this->reportProgress('.', $verbose); } $this->reportProgress(" done.\n", $verbose); } else { $this->reportProgress(" ... space for internal properties already allocated.\n", $verbose); } // now write actual properties; do that each time, it is cheap enough and we can update sortkeys by current language $this->reportProgress(" ... writing entries for internal properties ...", $verbose); foreach (SMWSql3SmwIds::$special_ids as $prop => $id) { $p = new SMWDIProperty($prop); $db->replace(SMWSQLStore3::ID_TABLE, array('smw_id'), array('smw_id' => $id, 'smw_title' => $p->getKey(), 'smw_namespace' => SMW_NS_PROPERTY, 'smw_iw' => $this->store->smwIds->getPropertyInterwiki($p), 'smw_subobject' => '', 'smw_sortkey' => $p->getLabel()), 'SMW::setup'); } $this->reportProgress(" done.\n", $verbose); if ($wgDBtype == 'postgres') { $sequenceIndex = SMWSQLStore3::ID_TABLE . '_smw_id_seq'; $this->reportProgress(" ... updating {$sequenceIndex} sequence accordingly.\n", $verbose); $max = $db->selectField(SMWSQLStore3::ID_TABLE, 'max(smw_id)', array(), __METHOD__); $max += 1; $db->query("ALTER SEQUENCE {$sequenceIndex} RESTART WITH {$max}", __METHOD__); } $this->reportProgress("Internal properties initialized successfully.\n", $verbose); }
/** * Based on generic method (parent) with some prior SQLite-sepcific adjustments * @return bool */ function insert($table, $a, $fname = __METHOD__, $options = array()) { if (!count($a)) { return true; } # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts if (isset($a[0]) && is_array($a[0])) { $ret = true; foreach ($a as $v) { if (!parent::insert($table, $v, "{$fname}/multi-row", $options)) { $ret = false; } } } else { $ret = parent::insert($table, $a, "{$fname}/single-row", $options); } return $ret; }
/** * Save the user into a centralauth database * @param DatabaseBase $db */ public function save(DatabaseBase $db) { // Setup local wiki user if ($this->createLocal) { $user = User::newFromName($this->username); if ($user->idForName() == 0) { $user->addToDatabase(); $user->setPassword($this->password); $user->saveSettings(); } } // Setup global user $row = array('gu_name' => $this->username, 'gu_id' => $this->guId, 'gu_password' => $this->passHash, 'gu_salt' => $this->salt, 'gu_auth_token' => $this->authToken, 'gu_locked' => $this->locked, 'gu_hidden' => $this->hidden, 'gu_registration' => $this->registration, 'gu_email' => $this->email, 'gu_email_authenticated' => $this->emailAuthenticated, 'gu_home_db' => $this->homeDb, 'gu_enabled' => $this->enabled, 'gu_enabled_method' => $this->enabledMethod); $db->insert('globaluser', $row, __METHOD__); // Attach global to local accounts $db->delete('localuser', array('lu_name' => $this->username), __METHOD__); if (count($this->wikis)) { $db->insert('localuser', $this->wikis, __METHOD__); } }
/** * Update the query cache as needed * * @param DatabaseBase $dbw * @param int $days How many days user must be idle before he is considered inactive * @param int $window Maximum time range of new data to scan (in seconds) * @return int|bool UNIX timestamp the cache is now up-to-date as of (false on error) */ protected static function doQueryCacheUpdate(DatabaseBase $dbw, $days, $window) { $lockKey = wfWikiID() . '-activeusers'; if (!$dbw->lock($lockKey, __METHOD__, 1)) { return false; // exclusive update (avoids duplicate entries) } $now = time(); $cTime = $dbw->selectField('querycache_info', 'qci_timestamp', array('qci_type' => 'activeusers')); $cTimeUnix = $cTime ? wfTimestamp(TS_UNIX, $cTime) : 1; // Pick the date range to fetch from. This is normally from the last // update to till the present time, but has a limited window for sanity. // If the window is limited, multiple runs are need to fully populate it. $sTimestamp = max($cTimeUnix, $now - $days * 86400); $eTimestamp = min($sTimestamp + $window, $now); // Get all the users active since the last update $res = $dbw->select(array('recentchanges'), array('rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)'), array('rc_user > 0', 'rc_type != ' . $dbw->addQuotes(RC_EXTERNAL), 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes('newusers'), 'rc_timestamp >= ' . $dbw->addQuotes($dbw->timestamp($sTimestamp)), 'rc_timestamp <= ' . $dbw->addQuotes($dbw->timestamp($eTimestamp))), __METHOD__, array('GROUP BY' => array('rc_user_text'), 'ORDER BY' => 'NULL')); $names = array(); foreach ($res as $row) { $names[$row->rc_user_text] = $row->lastedittime; } // Rotate out users that have not edited in too long (according to old data set) $dbw->delete('querycachetwo', array('qcc_type' => 'activeusers', 'qcc_value < ' . $dbw->addQuotes($now - $days * 86400)), __METHOD__); // Find which of the recently active users are already accounted for if (count($names)) { $res = $dbw->select('querycachetwo', array('user_name' => 'qcc_title'), array('qcc_type' => 'activeusers', 'qcc_namespace' => NS_USER, 'qcc_title' => array_keys($names)), __METHOD__); foreach ($res as $row) { unset($names[$row->user_name]); } } // Insert the users that need to be added to the list (which their last edit time if (count($names)) { $newRows = array(); foreach ($names as $name => $lastEditTime) { $newRows[] = array('qcc_type' => 'activeusers', 'qcc_namespace' => NS_USER, 'qcc_title' => $name, 'qcc_value' => wfTimestamp(TS_UNIX, $lastEditTime), 'qcc_namespacetwo' => 0, 'qcc_titletwo' => ''); } foreach (array_chunk($newRows, 500) as $rowBatch) { $dbw->insert('querycachetwo', $rowBatch, __METHOD__); if (!$dbw->trxLevel()) { wfWaitForSlaves(); } } } // Touch the data freshness timestamp $dbw->replace('querycache_info', array('qci_type'), array('qci_type' => 'activeusers', 'qci_timestamp' => $dbw->timestamp($eTimestamp)), __METHOD__); $dbw->unlock($lockKey, __METHOD__); return $eTimestamp; }
/** * Write (insert) the properties into the DB. * * @since 1.2 * * @param Database $dbw * * @return boolean Success indicator */ protected function writePropsToDB(DatabaseBase $dbw) { $success = true; if (array_key_exists('defaultOwnWorkLicence', $this->config) && array_key_exists('licensesOwnWork', $this->config) && !in_array($this->config['defaultOwnWorkLicence'], $this->config['licensesOwnWork'])) { $this->config['licensesOwnWork'][] = $this->config['defaultOwnWorkLicence']; } $dbw->begin(); // TODO: it'd be better to serialize() arrays foreach ($this->config as $prop => $value) { $success &= $dbw->insert('uw_campaign_conf', array('cc_campaign_id' => $this->id, 'cc_property' => $prop, 'cc_value' => is_array($value) ? implode('|', $value) : $value), __METHOD__); } $dbw->commit(); return $success; }