Project

General

Profile

Feature #38965 » convert-columns.php

Xavier Perseguers, 2012-07-16 10:43

 
<?php
define('SIMULATION', TRUE); // if TRUE, will output SQL instead
define('DROP_ORIG_DATA', FALSE); // if TRUE, will drop original (timestamp) column and rename the converted one

$migrationConfig = array(
'tx_myext_domain_model_person' => array(
'birthday' => 'date',
),
);

// ---- NO NEED TO MODIFY CODE BELOW ----

define('TYPO3_MODE', 'CLI');
require_once('typo3conf/localconf.php');

$link = mysql_connect($typo_db_host, $typo_db_username, $typo_db_password);
if (!$link) die('Could not connect: ' . mysql_error());
if (!mysql_select_db($typo_db, $link)) {
mysql_close($link);
die ('Could not select DB: ' . mysql_error());
}

foreach ($migrationConfig as $table => $columns) {
$sqlEnd = array();
foreach ($columns as $column => $type) {
if ($type === 'date') {
$columnDefinition = " date DEFAULT '0000-00-00'";
} else {
$columnDefinition = " datetime DEFAULT '0000-00-00 00:00:00'";
}
$sql = 'ALTER TABLE ' . $table . ' ADD ___' . $column . $columnDefinition . ' AFTER ' . $column;
if (SIMULATION) {
echo $sql . "\n";
} else {
mysql_query($sql, $link);
}
$sqlEnd[] = 'ALTER TABLE ' . $table . ' DROP ' . $column;
$sqlEnd[] = 'ALTER TABLE ' . $table . ' CHANGE ___' . $column . ' ' . $column . $columnDefinition;
}

$sql = 'SELECT uid,' . implode(',', array_keys($columns)) . ' FROM ' . $table;
$res = mysql_query($sql, $link);
if ($res) {
$updateData = array();
while (($row = mysql_fetch_assoc($res)) !== FALSE) {
if (!SIMULATION) echo 'converting record #' . $row['uid'] . "\n";
foreach ($columns as $column => $type) {
if ($type === 'date') {
$emptyValue = '0000-00-00';
$format = 'Y-m-d';
} else {
$emptyValue = '0000-00-00 00:00:00';
$format = 'Y-m-d H:i:s';
}
$convertedValue = $row[$column] ? date($format, $row[$column]) : $emptyValue;
$updateData[] = '___' . $column . '=\'' . $convertedValue . '\'';
}
$sql = 'UPDATE ' . $table . ' SET ' . implode(',', $updateData) . ' WHERE uid=' . $row['uid'];
if (SIMULATION) {
echo $sql . "\n";
} else {
mysql_query($sql, $link);
}
}
mysql_free_result($res);
}
if (DROP_ORIG_DATA) {
foreach ($sqlEnd as $sql) {
if (SIMULATION) {
echo $sql . "\n";
} else {
mysql_query($sql, $link);
}
}
}

}

mysql_close($link);
?>
(3-3/3)