Completed
Branch feature/pre-split (a521a3)
by Anton
03:28
created

SQLiteIndex::sqlStatement()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 4
nop 2
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Database\Drivers\SQLite\Schemas;
10
11
use Spiral\Database\Entities\Driver;
12
use Spiral\Database\Schemas\Prototypes\AbstractIndex;
13
14
class SQLiteIndex extends AbstractIndex
15
{
16
    /**
17
     * @param string $table
18
     * @param array  $schema
19
     * @param array  $columns
20
     *
21
     * @return SQLiteIndex
22
     */
23
    public static function createInstance(string $table, array $schema, array $columns): self
24
    {
25
        $index = new self($table, $schema['name']);
26
        $index->type = $schema['unique'] ? self::UNIQUE : self::NORMAL;
27
28
        foreach ($columns as $column) {
29
            $index->columns[] = $column['name'];
30
        }
31
32
        return $index;
33
    }
34
35
    /**
36
     * Index sql creation syntax.
37
     *
38
     * @param Driver $driver
39
     * @param bool   $includeTable Include table ON statement (not required for inline index
40
     *                             creation).
41
     *
42
     * @return string
43
     */
44
    public function sqlStatement(Driver $driver, bool $includeTable = true): string
45
    {
46
        $statement = [$this->type == self::UNIQUE ? 'UNIQUE INDEX' : 'INDEX'];
47
48
        //SQLite love to add indexes without being asked for that
49
        $statement[] = 'IF NOT EXISTS';
50
        $statement[] = $driver->identifier($this->name);
51
52
        if ($includeTable) {
53
            $statement[] = "ON {$driver->identifier($this->table)}";
54
        }
55
56
        //Wrapping column names
57
        $columns = implode(', ', array_map([$driver, 'identifier'], $this->columns));
58
59
        $statement[] = "({$columns})";
60
61
        return implode(' ', $statement);
62
    }
63
}
64