Completed
Branch feature/pre-split (42159e)
by Anton
05:36
created

SQLServerTable::save()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 4
nop 3
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework, Core Components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\Database\Drivers\SQLServer\Schemas;
8
9
use Psr\Log\LoggerInterface;
10
use Spiral\Database\Entities\AbstractHandler as Behaviour;
11
use Spiral\Database\Schemas\Prototypes\AbstractColumn;
12
use Spiral\Database\Schemas\Prototypes\AbstractIndex;
13
use Spiral\Database\Schemas\Prototypes\AbstractReference;
14
use Spiral\Database\Schemas\Prototypes\AbstractTable;
15
16
class SQLServerTable extends AbstractTable
17
{
18
    /**
19
     * {@inheritdoc}
20
     *
21
     * SQLServer will reload schemas after successful savw.
22
     */
23
    public function save(
24
        int $behaviour = Behaviour::DO_ALL,
25
        LoggerInterface $logger = null,
26
        bool $reset = true
27
    ) {
28
        parent::save($behaviour, $logger, $reset);
29
30
        if ($reset) {
31
            foreach ($this->fetchColumns() as $column) {
32
                if ($column->compare($this->current->findColumn($column->getName()))) {
0 ignored issues
show
Bug introduced by
It seems like $this->current->findColumn($column->getName()) can be null; however, compare() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
33
                    //SQLServer is going to add some automatic constrains, let's handle them
34
                    $this->current->registerColumn($column);
35
                }
36
            }
37
38
            $this->initial->syncState($this->current);
39
        }
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    protected function fetchColumns(): array
46
    {
47
        $query = 'SELECT * FROM [information_schema].[columns] INNER JOIN [sys].[columns] AS [sysColumns] '
48
            . 'ON (object_name([object_id]) = [table_name] AND [sysColumns].[name] = [COLUMN_NAME]) '
49
            . 'WHERE [table_name] = ?';
50
51
        $result = [];
52
        foreach ($this->driver->query($query, [$this->getName()]) as $schema) {
53
            //Column initialization needs driver to properly resolve enum type
54
            $result[] = SQLServerColumn::createInstance(
55
                $this->getName(),
56
                $schema,
57
                $this->driver
58
            );
59
        }
60
61
        return $result;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    protected function fetchIndexes(): array
68
    {
69
        $query = 'SELECT [indexes].[name] AS [indexName], [cl].[name] AS [columnName], '
70
            . "[is_primary_key] AS [isPrimary], [is_unique] AS [isUnique]\n"
71
            . "FROM [sys].[indexes] AS [indexes]\n"
72
            . "INNER JOIN [sys].[index_columns] as [columns]\n"
73
            . "  ON [indexes].[object_id] = [columns].[object_id] AND [indexes].[index_id] = [columns].[index_id]\n"
74
            . "INNER JOIN [sys].[columns] AS [cl]\n"
75
            . "  ON [columns].[object_id] = [cl].[object_id] AND [columns].[column_id] = [cl].[column_id]\n"
76
            . "INNER JOIN [sys].[tables] AS [t]\n"
77
            . "  ON [indexes].[object_id] = [t].[object_id]\n"
78
            . 'WHERE [t].[name] = ? AND [is_primary_key] = 0 ORDER BY [indexes].[name], [indexes].[index_id], [columns].[index_column_id]';
79
80
        $result = $indexes = [];
81
        foreach ($this->driver->query($query, [$this->getName()]) as $index) {
82
            //Collecting schemas first
83
            $indexes[$index['indexName']][] = $index;
84
        }
85
86
        foreach ($indexes as $name => $schema) {
87
            //Once all columns are aggregated we can finally create an index
88
            $result[] = SQLServerIndex::createInstance($this->getName(), $schema);
89
        }
90
91
        return $result;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 View Code Duplication
    protected function fetchReferences(): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
    {
99
        $references = $this->driver->query('sp_fkeys @fktable_name = ?', [$this->getName()]);
100
101
        $result = [];
102
        foreach ($references as $schema) {
103
            $result[] = SQlServerReference::createInstance(
104
                $this->getName(),
105
                $this->getPrefix(),
106
                $schema
107
            );
108
        }
109
110
        return $result;
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116
    protected function fetchPrimaryKeys(): array
117
    {
118
        $query = "SELECT [indexes].[name] AS [indexName], [cl].[name] AS [columnName]\n"
119
            . "FROM [sys].[indexes] AS [indexes]\n"
120
            . "INNER JOIN [sys].[index_columns] as [columns]\n"
121
            . "  ON [indexes].[object_id] = [columns].[object_id] AND [indexes].[index_id] = [columns].[index_id]\n"
122
            . "INNER JOIN [sys].[columns] AS [cl]\n"
123
            . "  ON [columns].[object_id] = [cl].[object_id] AND [columns].[column_id] = [cl].[column_id]\n"
124
            . "INNER JOIN [sys].[tables] AS [t]\n"
125
            . "  ON [indexes].[object_id] = [t].[object_id]\n"
126
            . 'WHERE [t].[name] = ? AND [is_primary_key] = 1 ORDER BY [indexes].[name], [indexes].[index_id], [columns].[index_column_id]';
127
128
        $result = [];
129
        foreach ($this->driver->query($query, [$this->getName()]) as $schema) {
130
            $result[] = $schema['columnName'];
131
        }
132
133
        return $result;
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    protected function createColumn(string $name): AbstractColumn
140
    {
141
        return new SQLServerColumn($this->getName(), $name, $this->driver->getTimezone());
142
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147
    protected function createIndex(string $name): AbstractIndex
148
    {
149
        return new SQLServerIndex($this->getName(), $name);
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155
    protected function createForeign(string $name): AbstractReference
156
    {
157
        return new SQlServerReference($this->getName(), $this->getPrefix(), $name);
158
    }
159
}