PMC-596
This commit is contained in:
@@ -1024,4 +1024,75 @@ class database extends database_base
|
||||
{
|
||||
return "DROP TRIGGER IF EXISTS `{$triggerName}`;";
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate alter table with or without adding the indexes
|
||||
*
|
||||
* @param string $tableName
|
||||
* @param array $columns
|
||||
* @param array $indexes
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function generateAddColumnsSql($tableName, $columns, $indexes = [])
|
||||
{
|
||||
$indexesAlreadyAdded = [];
|
||||
$sql = 'ALTER TABLE ' . $this->sQuoteCharacter . $tableName . $this->sQuoteCharacter . ' ';
|
||||
foreach ($columns as $columnName => $parameters) {
|
||||
if (isset($parameters['Type']) && isset($parameters['Null'])) {
|
||||
$sql .= 'ADD COLUMN ' . $this->sQuoteCharacter . $columnName . $this->sQuoteCharacter . ' ' . $parameters['Type'];
|
||||
if ($parameters['Null'] == 'YES') {
|
||||
$sql .= ' NULL';
|
||||
} else {
|
||||
$sql .= ' NOT NULL';
|
||||
}
|
||||
}
|
||||
if (isset($parameters['AutoIncrement']) && $parameters['AutoIncrement']) {
|
||||
$sql .= ' AUTO_INCREMENT';
|
||||
}
|
||||
if (isset($parameters['PrimaryKey']) && $parameters['PrimaryKey']) {
|
||||
$sql .= ' PRIMARY KEY';
|
||||
$indexesAlreadyAdded[] = $columnName;
|
||||
}
|
||||
if (isset($parameters['Unique']) && $parameters['Unique']) {
|
||||
$sql .= ' UNIQUE';
|
||||
}
|
||||
|
||||
// We need to check the property AI
|
||||
if (isset($parameters['AI'])) {
|
||||
if ($parameters['AI'] == 1) {
|
||||
$sql .= ' AUTO_INCREMENT';
|
||||
} else {
|
||||
if ($parameters['Default'] != '') {
|
||||
$sql .= " DEFAULT '" . $parameters['Default'] . "'";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (isset($parameters['Default'])) {
|
||||
$sql .= " DEFAULT '" . $parameters['Default'] . "'";
|
||||
}
|
||||
}
|
||||
$sql .= ', ';
|
||||
}
|
||||
foreach ($indexes as $indexName => $indexColumns) {
|
||||
$indexType = 'INDEX';
|
||||
if ($indexName === 'primaryKey' || $indexName === 'PRIMARY') {
|
||||
$indexType = 'PRIMARY';
|
||||
$indexName = 'KEY';
|
||||
// If is primary key is not needed add a new index, the column already was added like primary key
|
||||
if (count($indexColumns) == 1 && $indexesAlreadyAdded == $indexColumns) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
$sql .= 'ADD ' . $indexType . ' ' . $indexName . ' (';
|
||||
foreach ($indexColumns as $column) {
|
||||
$sql .= $this->sQuoteCharacter . $column . $this->sQuoteCharacter . ', ';
|
||||
}
|
||||
$sql = substr($sql, 0, -2);
|
||||
$sql .= '), ';
|
||||
}
|
||||
$sql = rtrim($sql, ', ');
|
||||
|
||||
return $sql;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user