function quotes_update_7 in Quotes 5
Implementation of hook_update_N(). Convert authors to separate table.
File
- ./
quotes.install, line 265 - Handles installation and updates for the quotes module.
Code
function quotes_update_7() {
global $db_type;
$items = $create = array();
switch ($GLOBALS['db_type']) {
case 'mysql':
case 'mysqli':
$create[] = 'CREATE TABLE {quotes_authors} (
aid INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
bio TEXT NULL,
UNIQUE (`name`)
) /*!40100 DEFAULT CHARACTER SET utf8 */';
break;
case 'pgsql':
$create[] = 'CREATE TABLE {quotes_authors} (
aid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
bio TEXT NULL,
UNIQUE (name)
) /*!40100 DEFAULT CHARACTER SET utf8 */';
db_query('CREATE INDEX {quotes_authors}_name ON {quotes_authors} (name)');
}
foreach ($create as $query) {
$result = db_query($query);
$items[] = array(
'success' => $result !== FALSE,
'query' => check_plain($query),
);
}
$items = array();
// Add the aid column after the vid column.
db_add_column($items, 'quotes', 'aid', 'INT UNSIGNED NOT NULL AFTER vid');
$add = $items[count($items) - 1]['success'];
if (!$add) {
drupal_set_message(t('Add column "aid" failed.'), 'error');
return;
}
// Add an index for the aid.
$items[] = update_sql("ALTER TABLE {quotes} ADD INDEX quotes_aid (aid) ");
$add = $items[count($items) - 1]['success'];
if (!$add) {
drupal_set_message(t('Add index for "aid" failed.'), 'error');
return;
}
// Get all the authors.
$rows = array();
$result = db_query("SELECT DISTINCT(author) FROM {quotes} ORDER BY author");
while ($q = db_fetch_array($result)) {
$author = $q['author'];
// If the current author field has a mini-bio, split it off.
$paren = strpos($author, '(');
$comma = strpos($author, ',');
$sub = min($paren === FALSE ? drupal_strlen($author) : $paren, $comma === FALSE ? drupal_strlen($author) : $comma);
if ($sub === FALSE) {
$bio = NULL;
}
else {
$bio = trim(drupal_substr($author, $sub));
$author = trim(drupal_substr($author, 0, $sub));
}
// Add the row to the new table.
$items[] = update_sql("INSERT INTO {quotes_authors} (name, bio) VALUES ('" . db_escape_string($author) . "', '" . db_escape_string($bio) . "')");
$add = $items[count($items) - 1]['success'];
if ($add === FALSE) {
$aid = 'failed';
$upd = 'bypassed';
}
else {
$aid = db_result(db_query("SELECT LAST_INSERT_ID()"));
if ($aid < 1) {
drupal_set_message(t('Invalid aid returned: ') . $aid, 'error');
}
$query = 'UPDATE {quotes} SET aid=' . $aid . " WHERE author='" . db_escape_string($q['author']) . "'";
$items[] = update_sql($query);
}
}
$items[] = update_sql("ALTER TABLE {quotes} DROP author");
$del = $items[count($items) - 1]['success'];
if (!$del) {
drupal_set_message(t('Drop column "author" failed.'), 'error');
}
drupal_set_message(t('Update 7 for Quotes complete.'), 'status');
return $items;
}