/
QueryCompiler.php
295 lines (273 loc) · 9.33 KB
/
QueryCompiler.php
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Database;
use Cake\Database\Query;
use Cake\Database\ValueBinder;
/**
* Responsible for compiling a Query object into its SQL representation
*
* @internal
*/
class QueryCompiler {
/**
* List of sprintf templates that will be used for compiling the SQL for
* this query. There are some clauses that can be built as just as the
* direct concatenation of the internal parts, those are listed here.
*
* @var array
*/
protected $_templates = [
'delete' => 'DELETE',
'update' => 'UPDATE %s',
'where' => ' WHERE %s',
'group' => ' GROUP BY %s ',
'having' => ' HAVING %s ',
'order' => ' %s',
'limit' => ' LIMIT %s',
'offset' => ' OFFSET %s',
'epilog' => ' %s'
];
/**
* The list of query clauses to traverse for generating a SELECT statment
*
* @var array
*/
protected $_selectParts = [
'select', 'from', 'join', 'where', 'group', 'having', 'order', 'limit',
'offset', 'union', 'epilog'
];
/**
* The list of query clauses to traverse for generating an UPDATE statment
*
* @var array
*/
protected $_updateParts = ['update', 'set', 'where', 'epilog'];
/**
* The list of query clauses to traverse for generating a DELETE statment
*
* @var array
*/
protected $_deleteParts = ['delete', 'from', 'where', 'epilog'];
/**
* The list of query clauses to traverse for generating an INSERT statment
*
* @var array
*/
protected $_insertParts = ['insert', 'values', 'epilog'];
/**
* Returns the SQL representation of the provided query after generating
* the placeholders for the bound values using the provided generator
*
* @return void
*/
public function compile($query, $generator) {
$sql = '';
$type = $query->type();
$query->traverse(
$this->_sqlCompiler($sql, $query, $generator),
$this->{'_' . $type . 'Parts'}
);
return $sql;
}
/**
* Returns a callable object that can be used to compile a SQL string representation
* of this query.
*
* @param string $sql initial sql string to append to
* @param \Cake\Database\ValueBinder The placeholder and value binder object
* @return \Closure
*/
protected function _sqlCompiler(&$sql, $query, $generator) {
return function($parts, $name) use (&$sql, $query, $generator) {
if (!count($parts)) {
return;
}
if ($parts instanceof ExpressionInterface) {
$parts = [$parts->sql($generator)];
}
if (isset($this->_templates[$name])) {
$parts = $this->_stringifyExpressions((array)$parts, $generator);
return $sql .= sprintf($this->_templates[$name], implode(', ', $parts));
}
return $sql .= $this->{'_build' . ucfirst($name) . 'Part'}($parts, $query, $generator);
};
}
/**
* Helper function used to build the string representation of a SELECT clause,
* it constructs the field list taking care of aliasing and
* converting expression objects to string. This function also constructs the
* DISTINCT clause for the query.
*
* @param array $parts list of fields to be transformed to string
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string
*/
protected function _buildSelectPart($parts, $query, $generator) {
$driver = $query->connection()->driver();
$select = 'SELECT %s%s%s';
$distinct = $query->clause('distinct');
$modifiers = $query->clause('modifier') ?: null;
$normalized = [];
$parts = $this->_stringifyExpressions($parts, $generator);
foreach ($parts as $k => $p) {
if (!is_numeric($k)) {
$p = $p . ' AS ' . $driver->quoteIdentifier($k);
}
$normalized[] = $p;
}
if ($distinct === true) {
$distinct = 'DISTINCT ';
}
if (is_array($distinct)) {
$distinct = $this->_stringifyExpressions($distinct, $generator);
$distinct = sprintf('DISTINCT ON (%s) ', implode(', ', $distinct));
}
if ($modifiers !== null) {
$modifiers = $this->_stringifyExpressions($modifiers, $generator);
$modifiers = implode(' ', $modifiers) . ' ';
}
return sprintf($select, $modifiers, $distinct, implode(', ', $normalized));
}
/**
* Helper function used to build the string representation of a FROM clause,
* it constructs the tables list taking care of aliasing and
* converting expression objects to string.
*
* @param array $parts list of tables to be transformed to string
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string
*/
protected function _buildFromPart($parts, $query, $generator) {
$select = ' FROM %s';
$normalized = [];
$parts = $this->_stringifyExpressions($parts, $generator);
foreach ($parts as $k => $p) {
if (!is_numeric($k)) {
$p = $p . ' AS ' . $k;
}
$normalized[] = $p;
}
return sprintf($select, implode(', ', $normalized));
}
/**
* Helper function used to build the string representation of multiple JOIN clauses,
* it constructs the joins list taking care of aliasing and converting
* expression objects to string in both the table to be joined and the conditions
* to be used.
*
* @param array $parts list of joins to be transformed to string
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string
*/
protected function _buildJoinPart($parts, $query, $generator) {
$joins = '';
foreach ($parts as $join) {
if ($join['table'] instanceof ExpressionInterface) {
$join['table'] = '(' . $join['table']->sql($generator) . ')';
}
$joins .= sprintf(' %s JOIN %s %s', $join['type'], $join['table'], $join['alias']);
if (isset($join['conditions']) && count($join['conditions'])) {
$joins .= sprintf(' ON %s', $join['conditions']->sql($generator));
} else {
$joins .= ' ON 1 = 1';
}
}
return $joins;
}
/**
* Helper function to generate SQL for SET expressions.
*
* @param array $parts List of keys & values to set.
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string
*/
protected function _buildSetPart($parts, $query, $generator) {
$set = [];
foreach ($parts as $part) {
if ($part instanceof ExpressionInterface) {
$part = $part->sql($generator);
}
if ($part[0] === '(') {
$part = substr($part, 1, -1);
}
$set[] = $part;
}
return ' SET ' . implode('', $set);
}
/**
* Builds the SQL string for all the UNION clauses in this query, when dealing
* with query objects it will also transform them using their configured SQL
* dialect.
*
* @param array $parts list of queries to be operated with UNION
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string
*/
protected function _buildUnionPart($parts, $query, $generator) {
$parts = array_map(function($p) use ($generator) {
$p['query'] = $p['query']->sql($generator);
$p['query'] = $p['query'][0] === '(' ? trim($p['query'], '()') : $p['query'];
return $p['all'] ? 'ALL ' . $p['query'] : $p['query'];
}, $parts);
return sprintf("\nUNION %s", implode("\nUNION ", $parts));
}
/**
* Builds the SQL fragment for INSERT INTO.
*
* @param array $parts
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string SQL fragment.
*/
protected function _buildInsertPart($parts, $query, $generator) {
$table = $parts[0];
$columns = $this->_stringifyExpressions($parts[1], $generator);
return sprintf('INSERT INTO %s (%s)', $table, implode(', ', $columns));
}
/**
* Builds the SQL fragment for INSERT INTO.
*
* @param array $parts
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string SQL fragment.
*/
protected function _buildValuesPart($parts, $query, $generator) {
return implode('', $this->_stringifyExpressions($parts, $generator));
}
/**
* Helper function used to covert ExpressionInterface objects inside an array
* into their string representation.
*
* @param array $expressions list of strings and ExpressionInterface objects
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return array
*/
protected function _stringifyExpressions(array $expressions, ValueBinder $generator) {
$result = [];
foreach ($expressions as $k => $expression) {
if ($expression instanceof ExpressionInterface) {
$expression = '(' . $expression->sql($generator) . ')';
}
$result[$k] = $expression;
}
return $result;
}
}