Completed
Pull Request — master (#6417)
by Luís
19:07
created

MultiTableUpdateExecutor::execute()   B

Complexity

Conditions 6
Paths 20

Size

Total Lines 40
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 0
cts 0
cp 0
rs 8.439
c 0
b 0
f 0
cc 6
eloc 20
nc 20
nop 3
crap 42
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ORM\Query\Exec;
21
22
use Doctrine\DBAL\Connection;
23
use Doctrine\DBAL\Types\Type;
24
use Doctrine\ORM\Query\ParameterTypeInferer;
25
use Doctrine\ORM\Query\AST;
26
use Doctrine\ORM\Utility\PersisterHelper;
27
28
/**
29
 * Executes the SQL statements for bulk DQL UPDATE statements on classes in
30
 * Class Table Inheritance (JOINED).
31
 *
32
 * @author Roman Borschel <[email protected]>
33
 * @since 2.0
34
 */
35
class MultiTableUpdateExecutor extends AbstractSqlExecutor
36
{
37
    /**
38
     * @var string
39
     */
40
    private $_createTempTableSql;
41
42
    /**
43
     * @var string
44
     */
45
    private $_dropTempTableSql;
46
47
    /**
48
     * @var string
49
     */
50
    private $_insertSql;
51
52
    /**
53
     * @var array
54
     */
55
    private $_sqlParameters = [];
56
57
    /**
58
     * @var int
59
     */
60
    private $_numParametersInUpdateClause = 0;
61
62
    /**
63
     * Initializes a new <tt>MultiTableUpdateExecutor</tt>.
64
     *
65
     * Internal note: Any SQL construction and preparation takes place in the constructor for
66
     *                best performance. With a query cache the executor will be cached.
67
     *
68
     * @param \Doctrine\ORM\Query\AST\Node  $AST The root AST node of the DQL query.
69
     * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker The walker used for SQL generation from the AST.
70
     */
71
    public function __construct(AST\Node $AST, $sqlWalker)
72
    {
73
        $em             = $sqlWalker->getEntityManager();
74
        $conn           = $em->getConnection();
75
        $platform       = $conn->getDatabasePlatform();
76
        $quoteStrategy  = $em->getConfiguration()->getQuoteStrategy();
77
78
        $updateClause   = $AST->updateClause;
0 ignored issues
show
Bug introduced by
The property updateClause does not seem to exist in Doctrine\ORM\Query\AST\Node.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
79
        $primaryClass   = $sqlWalker->getEntityManager()->getClassMetadata($updateClause->abstractSchemaName);
80
        $rootClass      = $em->getClassMetadata($primaryClass->rootEntityName);
81
82
        $updateItems    = $updateClause->updateItems;
83
84
        $tempTable      = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName());
85
        $idColumnNames  = $rootClass->getIdentifierColumnNames();
86
        $idColumnList   = implode(', ', $idColumnNames);
87
88
        // 1. Create an INSERT INTO temptable ... SELECT identifiers WHERE $AST->getWhereClause()
89
        $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 't0', $updateClause->aliasIdentificationVariable);
90
91
        $this->_insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnList . ')'
92
                . ' SELECT t0.' . implode(', t0.', $idColumnNames);
93
94
        $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $updateClause->aliasIdentificationVariable);
95
        $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]);
96
97
        $this->_insertSql .= $sqlWalker->walkFromClause($fromClause);
98
99
        // 2. Create ID subselect statement used in UPDATE ... WHERE ... IN (subselect)
100
        $idSubselect = 'SELECT ' . $idColumnList . ' FROM ' . $tempTable;
101
102
        // 3. Create and store UPDATE statements
103
        $classNames = array_merge($primaryClass->parentClasses, [$primaryClass->name], $primaryClass->subClasses);
104
        $i = -1;
105
106
        foreach (array_reverse($classNames) as $className) {
107
            $affected = false;
108
            $class = $em->getClassMetadata($className);
109
            $updateSql = 'UPDATE ' . $quoteStrategy->getTableName($class, $platform) . ' SET ';
110
111
            foreach ($updateItems as $updateItem) {
112
                $field = $updateItem->pathExpression->field;
113
114
                if ((isset($class->fieldMappings[$field]) && ! isset($class->fieldMappings[$field]['inherited'])) ||
115
                    (isset($class->associationMappings[$field]) && ! isset($class->associationMappings[$field]['inherited']))) {
116
                    $newValue = $updateItem->newValue;
117
118
                    if ( ! $affected) {
119
                        $affected = true;
120
                        ++$i;
121
                    } else {
122
                        $updateSql .= ', ';
123
                    }
124
125
                    $updateSql .= $sqlWalker->walkUpdateItem($updateItem);
126
127
                    if ($newValue instanceof AST\InputParameter) {
128
                        $this->_sqlParameters[$i][] = $newValue->name;
129
130
                        ++$this->_numParametersInUpdateClause;
131
                    }
132
                }
133
            }
134
135
            if ($affected) {
136
                $this->_sqlStatements[$i] = $updateSql . ' WHERE (' . $idColumnList . ') IN (' . $idSubselect . ')';
137
            }
138
        }
139
140
        // Append WHERE clause to insertSql, if there is one.
141
        if ($AST->whereClause) {
142
            $this->_insertSql .= $sqlWalker->walkWhereClause($AST->whereClause);
0 ignored issues
show
Bug introduced by
The property whereClause does not seem to exist in Doctrine\ORM\Query\AST\Node.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
143
        }
144
145
        // 4. Store DDL for temporary identifier table.
146
        $columnDefinitions = [];
147
148
        foreach ($idColumnNames as $idColumnName) {
149
            $columnDefinitions[$idColumnName] = [
150
                'notnull' => true,
151
                'type'    => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $em)),
152
            ];
153
        }
154
155
        $this->_createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' ('
156
                . $platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
157
158
        $this->_dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable);
159
    }
160
161
    /**
162
     * {@inheritDoc}
163
     */
164
    public function execute(Connection $conn, array $params, array $types)
165
    {
166
        // Create temporary id table
167
        $conn->executeUpdate($this->_createTempTableSql);
168
169
        try {
170
            // Insert identifiers. Parameters from the update clause are cut off.
171
            $numUpdated = $conn->executeUpdate(
172
                $this->_insertSql,
173
                array_slice($params, $this->_numParametersInUpdateClause),
174
                array_slice($types, $this->_numParametersInUpdateClause)
175
            );
176
177
            // Execute UPDATE statements
178
            foreach ($this->_sqlStatements as $key => $statement) {
179
                $paramValues = [];
180
                $paramTypes  = [];
181
182
                if (isset($this->_sqlParameters[$key])) {
183
                    foreach ($this->_sqlParameters[$key] as $parameterKey => $parameterName) {
184
                        $paramValues[] = $params[$parameterKey];
185
                        $paramTypes[]  = isset($types[$parameterKey]) ? $types[$parameterKey] : ParameterTypeInferer::inferType($params[$parameterKey]);
186
                    }
187
                }
188
189
                $conn->executeUpdate($statement, $paramValues, $paramTypes);
190
            }
191
        } catch (\Exception $exception) {
192
            // FAILURE! Drop temporary table to avoid possible collisions
193
            $conn->executeUpdate($this->_dropTempTableSql);
194
195
            // Re-throw exception
196
            throw $exception;
197
        }
198
199
        // Drop temporary table
200
        $conn->executeUpdate($this->_dropTempTableSql);
201
202
        return $numUpdated;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $numUpdated; (integer) is incompatible with the return type declared by the abstract method Doctrine\ORM\Query\Exec\...actSqlExecutor::execute of type Doctrine\DBAL\Driver\Statement.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
203
    }
204
}
205