1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102:
<?php
namespace CzProject\SqlGenerator\Statements;
use CzProject\SqlGenerator\OutOfRangeException;
use CzProject\SqlGenerator\Helpers;
use CzProject\SqlGenerator\IDriver;
use CzProject\SqlGenerator\IStatement;
class IndexDefinition implements IStatement
{
const TYPE_INDEX = 'INDEX';
const TYPE_PRIMARY = 'PRIMARY';
const TYPE_UNIQUE = 'UNIQUE';
const TYPE_FULLTEXT = 'FULLTEXT';
private $name;
private $type;
private $columns = array();
public function __construct($name = NULL, $type)
{
$this->name = $name;
$this->setType($type);
}
public function addColumn($column, $order = IndexColumnDefinition::ASC, $length = NULL)
{
$this->columns[] = new IndexColumnDefinition($column, $order, $length);
return $this;
}
private function setType($type)
{
$type = (string) $type;
$exists = $type === self::TYPE_INDEX
|| $type === self::TYPE_PRIMARY
|| $type === self::TYPE_UNIQUE
|| $type === self::TYPE_FULLTEXT;
if (!$exists) {
throw new OutOfRangeException("Index type '$type' not found.");
}
$this->type = $type;
}
public function toSql(IDriver $driver)
{
$output = $this->type !== self::TYPE_INDEX ? ($this->type . ' ') : '';
$output .= 'KEY';
if ($this->name !== NULL) {
$output .= ' ' . $driver->escapeIdentifier($this->name);
}
$output .= ' (';
$isFirst = TRUE;
foreach ($this->columns as $column) {
if ($isFirst) {
$isFirst = FALSE;
} else {
$output .= ', ';
}
$output .= $column->toSql($driver);
}
$output .= ')';
return $output;
}
}