-
Notifications
You must be signed in to change notification settings - Fork 43
/
QueryBuilder.php
440 lines (381 loc) · 13.8 KB
/
QueryBuilder.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<?php
namespace kak\clickhouse;
use yii\db\Expression;
use yii\db\ExpressionInterface;
use yii\helpers\StringHelper;
class QueryBuilder extends \yii\db\QueryBuilder
{
/**
* Constructor.
* @param Connection $connection the database connection.
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($connection, $config = [])
{
$this->db = $connection;
parent::__construct($connection, $config);
}
/**
* Clickhouse data types
*/
public $typeMap = [
Schema::TYPE_CHAR => 'FixedString(1)',
Schema::TYPE_STRING => 'String',
Schema::TYPE_TEXT => 'String',
Schema::TYPE_SMALLINT => 'Int8',
Schema::TYPE_INTEGER => 'Int32',
Schema::TYPE_BIGINT => 'Int64',
Schema::TYPE_FLOAT => 'Float32',
Schema::TYPE_DOUBLE => 'Float64',
Schema::TYPE_DECIMAL => 'Float32',
Schema::TYPE_DATETIME => 'DateTime',
Schema::TYPE_TIME => 'DateTime',
Schema::TYPE_DATE => 'Date',
Schema::TYPE_BINARY => 'String',
Schema::TYPE_BOOLEAN => 'Int8',
Schema::TYPE_MONEY => 'Float32',
];
private function prepareFromByModel($query)
{
if(empty($query->from) && $query instanceof ActiveQuery && !empty($query->modelClass)){
$modelClass = $query->modelClass;
$query->from = [ call_user_func($modelClass . '::tableName') ];
}
}
/**
* @inheritdoc
*/
public function delete($table, $condition, &$params)
{
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table). ' DELETE';
$where = $this->buildWhere($condition, $params);
return $where === '' ? $sql : $sql . ' ' . $where;
}
/**
* Generates a SELECT SQL statement from a [[Query]] object.
* @param Query $query the [[Query]] object from which the SQL statement will be generated.
* @param array $params the parameters to be bound to the generated SQL statement. These parameters will
* be included in the result with the additional parameters generated during the query building process.
* @return array the generated SQL statement (the first array element) and the corresponding
* parameters to be bound to the SQL statement (the second array element). The parameters returned
* include those provided in `$params`.
*/
public function build($query, $params = [])
{
$query = $query->prepare($this);
$params = empty($params) ? $query->params : array_merge($params, $query->params);
$this->prepareFromByModel($query);
$clauses = [
$this->buildWithQueries($query->withQueries, $params),
$this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
$this->buildFrom($query->from, $params),
$this->buildSample($query->sample),
$this->buildJoin($query->join, $params),
$this->buildPreWhere($query->preWhere, $params),
$this->buildWhere($query->where, $params),
$this->buildGroupBy($query->groupBy),
$this->buildWithRollup($query->withGroup),
$this->buildWithCube($query->withGroup),
$this->buildWithTotals($query->withGroup),
$this->buildHaving($query->having, $params),
];
$sql = implode($this->separator, array_filter($clauses));
$orderBy = $this->buildOrderBy($query->orderBy);
if ($orderBy !== '') {
$sql .= $this->separator . $orderBy;
}
$limitBy = $this->buildLimitBy($query->limitBy);
if($limitBy !==''){
$sql .= $this->separator . $limitBy;
}
$limit = $this->buildLimit($query->limit, $query->offset);
if ($limit !== '') {
$sql .= $this->separator . $limit;
}
if (!empty($query->orderBy)) {
foreach ($query->orderBy as $expression) {
if ($expression instanceof Expression) {
$params = array_merge($params, $expression->params);
}
}
}
if (!empty($query->groupBy)) {
foreach ($query->groupBy as $expression) {
if ($expression instanceof Expression) {
$params = array_merge($params, $expression->params);
}
}
}
$union = $this->buildUnion($query->union, $params);
if ($union !== '') {
$sql = "$sql{$this->separator}$union";
}
return [$sql, $params];
}
/**
* @param string|null $condition
* @return string the WITH TOTALS
*/
public function buildWithTotals($condition)
{
return !empty($condition) && $condition === 'TOTALS' ? 'WITH TOTALS' : '';
}
/**
* @param string|null $condition
* @return string the WITH CUBE
*/
public function buildWithCube($condition)
{
return !empty($condition) && $condition === 'CUBE' ? 'WITH CUBE' : '';
}
/**
* @param string|null $condition
* @return string the WITH CUBE
*/
public function buildWithRollup($condition)
{
return !empty($condition) && $condition === 'ROLLUP' ? 'WITH ROLLUP' : '';
}
/**
* @param string|array $condition
* @param array $params the binding parameters to be populated
* @return string the PREWHERE clause built from [[Query::$preWhere]].
*/
public function buildPreWhere($condition, &$params)
{
$where = $this->buildCondition($condition, $params);
return $where === '' ? '' : 'PREWHERE ' . $where;
}
/**
* @param array $withs of configurations for each WITH query
* @param array $params the binding parameters to be populated
* @return string compiled WITH prefix of query including nested queries
* @see Query::withQuery()
* @since 2.0.35
*/
public function buildWithQueries($withs, &$params)
{
if (empty($withs)) {
return '';
}
$result = [];
foreach ($withs as $i => $with) {
$query = $with['query'];
// is <identifier oe alias> AS <subquery expression>
if ($query instanceof Query) {
list($with['query'], $params) = $this->build($query, $params);
$result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
continue;
}
// is <expression> AS <identifier or alias>
if (is_scalar($with['query'])) {
$result[] = $with['query'] . ' AS ' . $with['alias'];
}
}
if (count($result)) {
return 'WITH ' . implode(', ', $result);
}
return '';
}
/**
* @param string|array $condition
* @return string the SAMPLE clause built from [[Query::$sample]].
*/
public function buildSample($condition)
{
return $condition !== null ? ' SAMPLE ' . $condition : '';
}
/**
* Set default engine option if don't set
*
* @param $table
* @param $columns
* @param null $options
* @return mixed
*/
public function createTable($table, $columns, $options = null)
{
if ($options === null) {
throw new \yii\db\Exception('Need set specific settings for engine table');
}
return parent::createTable($table, $columns, $options);
}
/**
* @param string|\yii\db\ColumnSchemaBuilder $type
* @return mixed|string|\yii\db\ColumnSchemaBuilder
*/
public function getColumnType($type)
{
if ($type instanceof ColumnSchemaBuilder) {
$type = $type->__toString();
}
if (isset($this->typeMap[$type])) {
return $this->typeMap[$type];
} elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
if (isset($this->typeMap[$matches[1]])) {
return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
}
} elseif (preg_match('/^U(\w+)/', $type, $matches)) {
if (isset($this->typeMap[$matches[1]])) {
return 'U' . $this->typeMap[$matches[1]];
}
}
return $type;
}
/**
* @param integer $limit
* @param integer $offset
* @return string the LIMIT and OFFSET clauses
*/
public function buildLimit($limit, $offset)
{
$sql = '';
if ($this->hasOffset($offset)) {
$sql .= 'LIMIT ' . $offset . ' , ' . $limit;
}
else if ($this->hasLimit($limit)) {
$sql = 'LIMIT ' . $limit;
}
return ltrim($sql);
}
public function buildLimitBy($limitBy)
{
if (empty($limitBy)) {
return '';
}
$n = $limitBy[0];
$columns = is_array($limitBy[1]) ? implode(',', $limitBy[1]) : $limitBy[1];
return 'LIMIT ' . $n . ' BY ' . $columns;
}
/**
* @param array $unions
* @param array $params the binding parameters to be populated
* @return string the UNION clause built from [[Query::$union]].
*/
public function buildUnion($unions, &$params)
{
if (empty($unions)) {
return '';
}
$result = [];
foreach ($unions as $i => $union) {
$query = $union['query'];
if ($query instanceof Query) {
list($unions[$i]['query'], $params) = $this->build($query, $params);
}
$unionType = $union['all'];
$unionCondition = '';
if (is_string($unionType) && strtolower($unionType) === 'distinct') {
$unionCondition = 'DISTINCT ';
}
if ($unionType === true || (is_string($unionType) && strtolower($unionType) === 'all')) {
$unionCondition = 'ALL ';
}
$result[] = sprintf('UNION %s%s' ,
$unionCondition,
$unions[$i]['query']
);
}
return implode(" ", $result);
}
/**
* Creates a SELECT EXISTS() SQL statement.
* @param string $rawSql the subquery in a raw form to select from.
* @return string the SELECT EXISTS() SQL statement.
* @since 2.0.8
*/
public function selectExists($rawSql)
{
return 'SELECT count(*) FROM (' . $rawSql . ')';
}
/**
* @inheritdoc
*/
public function addColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD COLUMN ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
protected function prepareInsertValues($table, $columns, $params = [])
{
$schema = $this->db->getSchema();
$tableSchema = $schema->getTableSchema($table);
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
$names = [];
$placeholders = [];
$values = ' DEFAULT VALUES';
if ($columns instanceof Query) {
list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
} else {
foreach ($columns as $name => $value) {
$names[] = $schema->quoteColumnName($name);
if(isset($columnSchemas[$name]) && $columnSchemas[$name]->type === 'bigint'){
$value = new Expression($value);
} else{
$value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
}
if ($value instanceof ExpressionInterface) {
$placeholders[] = $this->buildExpression($value, $params);
} elseif ($value instanceof \yii\db\Query) {
list($sql, $params) = $this->build($value, $params);
$placeholders[] = "($sql)";
} else {
$placeholders[] = $this->bindParam($value, $params);
}
}
}
return [$names, $placeholders, $values, $params];
}
/**
* @param string $table
* @param array $columns
* @param array|\Generator $rows
* @param array $params
* @return string
* @throws \yii\base\InvalidConfigException
*/
public function batchInsert($table, $columns, $rows, &$params = [])
{
if (empty($rows)) {
return '';
}
$schema = $this->db->getSchema();
if (($tableSchema = $schema->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
} else {
$columnSchemas = [];
}
$values = [];
foreach ($rows as $row) {
$vs = [];
foreach ($row as $i => $value) {
if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
if(in_array($columnSchemas[$columns[$i]]->type, ['bigint'])){
$value = new Expression($value);
}
}
if (is_string($value)) {
$value = $schema->quoteValue($value);
} elseif ($value === false) {
$value = 0;
} elseif ($value === null) {
$value = 'NULL';
} elseif ($value instanceof ExpressionInterface) {
$value = $this->buildExpression($value, $params);
}
$vs[] = $value;
}
$values[] = '(' . implode(', ', $vs) . ')';
}
if (empty($values)) {
return '';
}
foreach ($columns as $i => $name) {
$columns[$i] = $schema->quoteColumnName($name);
}
return 'INSERT INTO ' . $schema->quoteTableName($table)
. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
}
}