Index.php 8.62 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Schema;

5
use Doctrine\DBAL\Platforms\AbstractPlatform;
6
use InvalidArgumentException;
7

8
use function array_filter;
9 10 11
use function array_keys;
use function array_map;
use function array_search;
12
use function array_shift;
13 14 15
use function count;
use function is_string;
use function strtolower;
16

17
class Index extends AbstractAsset implements Constraint
18 19
{
    /**
20 21 22 23
     * Asset identifier instances of the column names the index is associated with.
     * array($columnName => Identifier)
     *
     * @var Identifier[]
24
     */
25
    protected $_columns = [];
26

27
    /** @var bool */
28 29
    protected $_isUnique = false;

30
    /** @var bool */
31 32
    protected $_isPrimary = false;

33 34
    /**
     * Platform specific flags for indexes.
35
     * array($flagName => true)
36
     *
37
     * @var true[]
38
     */
39
    protected $_flags = [];
40

41
    /**
42
     * Platform specific options
43
     *
44
     * @todo $_flags should eventually be refactored into options
45
     * @var mixed[]
46
     */
47
    private $options = [];
48

49
    /**
50 51
     * @param string   $indexName
     * @param string[] $columns
52 53
     * @param bool     $isUnique
     * @param bool     $isPrimary
54
     * @param string[] $flags
55
     * @param mixed[]  $options
56
     */
57
    public function __construct($indexName, array $columns, $isUnique = false, $isPrimary = false, array $flags = [], array $options = [])
58
    {
59
        $isUnique = $isUnique || $isPrimary;
60

61
        $this->_setName($indexName);
62
        $this->_isUnique  = $isUnique;
63
        $this->_isPrimary = $isPrimary;
64
        $this->options    = $options;
65

66
        foreach ($columns as $column) {
67 68
            $this->_addColumn($column);
        }
Grégoire Paris's avatar
Grégoire Paris committed
69

70 71 72
        foreach ($flags as $flag) {
            $this->addFlag($flag);
        }
73 74 75 76
    }

    /**
     * @param string $column
Benjamin Morel's avatar
Benjamin Morel committed
77 78 79
     *
     * @return void
     *
80
     * @throws InvalidArgumentException
81 82 83
     */
    protected function _addColumn($column)
    {
84 85
        if (! is_string($column)) {
            throw new InvalidArgumentException('Expecting a string as Index Column');
86
        }
87 88

        $this->_columns[$column] = new Identifier($column);
89 90 91
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
92
     * {@inheritdoc}
93 94 95
     */
    public function getColumns()
    {
96 97 98 99
        return array_keys($this->_columns);
    }

    /**
100
     * {@inheritdoc}
101 102 103
     */
    public function getQuotedColumns(AbstractPlatform $platform)
    {
104 105 106
        $subParts = $platform->supportsColumnLengthIndexes() && $this->hasOption('lengths')
            ? $this->getOption('lengths') : [];

107
        $columns = [];
108 109

        foreach ($this->_columns as $column) {
110 111 112 113 114 115 116 117 118
            $length = array_shift($subParts);

            $quotedColumn = $column->getQuotedName($platform);

            if ($length !== null) {
                $quotedColumn .= '(' . $length . ')';
            }

            $columns[] = $quotedColumn;
119 120 121
        }

        return $columns;
122
    }
123

124
    /**
125
     * @return string[]
126 127 128
     */
    public function getUnquotedColumns()
    {
129
        return array_map([$this, 'trimQuotes'], $this->getColumns());
130 131
    }

132 133
    /**
     * Is the index neither unique nor primary key?
134
     *
135
     * @return bool
136 137 138
     */
    public function isSimpleIndex()
    {
139
        return ! $this->_isPrimary && ! $this->_isUnique;
140
    }
141 142

    /**
143
     * @return bool
144 145 146 147 148 149 150
     */
    public function isUnique()
    {
        return $this->_isUnique;
    }

    /**
151
     * @return bool
152 153 154 155 156
     */
    public function isPrimary()
    {
        return $this->_isPrimary;
    }
157 158

    /**
159 160
     * @param string $columnName
     * @param int    $pos
Benjamin Morel's avatar
Benjamin Morel committed
161
     *
162
     * @return bool
163
     */
164
    public function hasColumnAtPosition($columnName, $pos = 0)
165
    {
166 167
        $columnName   = $this->trimQuotes(strtolower($columnName));
        $indexColumns = array_map('strtolower', $this->getUnquotedColumns());
Benjamin Morel's avatar
Benjamin Morel committed
168

169
        return array_search($columnName, $indexColumns, true) === $pos;
170
    }
171 172

    /**
Benjamin Morel's avatar
Benjamin Morel committed
173
     * Checks if this index exactly spans the given column names in the correct order.
174
     *
175
     * @param string[] $columnNames
Benjamin Morel's avatar
Benjamin Morel committed
176
     *
177
     * @return bool
178 179 180
     */
    public function spansColumns(array $columnNames)
    {
Steve Müller's avatar
Steve Müller committed
181
        $columns         = $this->getColumns();
182
        $numberOfColumns = count($columns);
Steve Müller's avatar
Steve Müller committed
183 184
        $sameColumns     = true;

185
        for ($i = 0; $i < $numberOfColumns; $i++) {
186 187
            if (isset($columnNames[$i]) && $this->trimQuotes(strtolower($columns[$i])) === $this->trimQuotes(strtolower($columnNames[$i]))) {
                continue;
188
            }
189 190

            $sameColumns = false;
191
        }
Steve Müller's avatar
Steve Müller committed
192

193 194 195 196
        return $sameColumns;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
197 198
     * Checks if the other index already fulfills all the indexing and constraint needs of the current one.
     *
199
     * @return bool
200 201 202 203 204
     */
    public function isFullfilledBy(Index $other)
    {
        // allow the other index to be equally large only. It being larger is an option
        // but it creates a problem with scenarios of the kind PRIMARY KEY(foo,bar) UNIQUE(foo)
205
        if (count($other->getColumns()) !== count($this->getColumns())) {
206 207 208 209 210 211 212
            return false;
        }

        // Check if columns are the same, and even in the same order
        $sameColumns = $this->spansColumns($other->getColumns());

        if ($sameColumns) {
213
            if (! $this->samePartialIndex($other)) {
214
                return false;
215 216
            }

217 218 219 220
            if (! $this->hasSameColumnLengths($other)) {
                return false;
            }

221
            if (! $this->isUnique() && ! $this->isPrimary()) {
Possum's avatar
Possum committed
222
                // this is a special case: If the current key is neither primary or unique, any unique or
223
                // primary key will always have the same effect for the index and there cannot be any constraint
Pascal Borreli's avatar
Pascal Borreli committed
224
                // overlaps. This means a primary or unique index can always fulfill the requirements of just an
225 226
                // index that has no constraints.
                return true;
227 228
            }

229
            if ($other->isPrimary() !== $this->isPrimary()) {
230
                return false;
231 232
            }

Gabriel Caruso's avatar
Gabriel Caruso committed
233
            return $other->isUnique() === $this->isUnique();
234
        }
Benjamin Morel's avatar
Benjamin Morel committed
235

236 237 238 239
        return false;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
240 241
     * Detects if the other index is a non-unique, non primary index that can be overwritten by this one.
     *
242
     * @return bool
243 244 245
     */
    public function overrules(Index $other)
    {
246 247
        if ($other->isPrimary()) {
            return false;
248 249 250
        }

        if ($this->isSimpleIndex() && $other->isUnique()) {
251 252 253
            return false;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
254
        return $this->spansColumns($other->getColumns()) && ($this->isPrimary() || $this->isUnique()) && $this->samePartialIndex($other);
255
    }
256

257 258 259
    /**
     * Returns platform specific flags for indexes.
     *
260
     * @return string[]
261 262 263 264 265 266
     */
    public function getFlags()
    {
        return array_keys($this->_flags);
    }

267
    /**
Benjamin Morel's avatar
Benjamin Morel committed
268
     * Adds Flag for an index that translates to platform specific handling.
269 270
     *
     * @param string $flag
Benjamin Morel's avatar
Benjamin Morel committed
271
     *
272
     * @return Index
273 274
     *
     * @example $index->addFlag('CLUSTERED')
275 276 277
     */
    public function addFlag($flag)
    {
Steve Müller's avatar
Steve Müller committed
278
        $this->_flags[strtolower($flag)] = true;
Benjamin Morel's avatar
Benjamin Morel committed
279

280 281 282 283 284 285 286
        return $this;
    }

    /**
     * Does this index have a specific flag?
     *
     * @param string $flag
Benjamin Morel's avatar
Benjamin Morel committed
287
     *
288
     * @return bool
289 290 291
     */
    public function hasFlag($flag)
    {
Steve Müller's avatar
Steve Müller committed
292
        return isset($this->_flags[strtolower($flag)]);
293 294 295
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
296
     * Removes a flag.
297 298
     *
     * @param string $flag
Benjamin Morel's avatar
Benjamin Morel committed
299
     *
300 301 302 303
     * @return void
     */
    public function removeFlag($flag)
    {
Steve Müller's avatar
Steve Müller committed
304
        unset($this->_flags[strtolower($flag)]);
305
    }
306 307

    /**
308 309
     * @param string $name
     *
310
     * @return bool
311 312 313
     */
    public function hasOption($name)
    {
314
        return isset($this->options[strtolower($name)]);
315 316 317 318 319 320
    }

    /**
     * @param string $name
     *
     * @return mixed
321
     */
322
    public function getOption($name)
323
    {
324
        return $this->options[strtolower($name)];
325
    }
326 327

    /**
328
     * @return mixed[]
329 330 331 332 333 334 335 336
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Return whether the two indexes have the same partial index
337
     *
338
     * @return bool
339 340 341
     */
    private function samePartialIndex(Index $other)
    {
342
        if ($this->hasOption('where') && $other->hasOption('where') && $this->getOption('where') === $other->getOption('where')) {
343
            return true;
344 345
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
346
        return ! $this->hasOption('where') && ! $other->hasOption('where');
347
    }
348 349 350 351

    /**
     * Returns whether the index has the same column lengths as the other
     */
352
    private function hasSameColumnLengths(self $other): bool
353
    {
354
        $filter = static function (?int $length): bool {
355 356 357 358 359 360
            return $length !== null;
        };

        return array_filter($this->options['lengths'] ?? [], $filter)
            === array_filter($other->options['lengths'] ?? [], $filter);
    }
361
}