-
-
Notifications
You must be signed in to change notification settings - Fork 858
/
Copy pathQueryDataTable.php
757 lines (662 loc) · 19.4 KB
/
QueryDataTable.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
<?php
namespace Yajra\DataTables;
use Illuminate\Support\Str;
use Illuminate\Database\Query\Builder;
use Yajra\DataTables\Utilities\Helper;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
class QueryDataTable extends DataTableAbstract
{
/**
* Builder object.
*
* @var \Illuminate\Database\Query\Builder
*/
protected $query;
/**
* Database connection used.
*
* @var \Illuminate\Database\Connection
*/
protected $connection;
/**
* Flag for ordering NULLS LAST option.
*
* @var bool
*/
protected $nullsLast = false;
/**
* Flag to check if query preparation was already done.
*
* @var bool
*/
protected $prepared = false;
/**
* Query callback for custom pagination using limit without offset.
*
* @var callable
*/
protected $limitCallback;
/**
* Flag to skip total records count query.
*
* @var bool
*/
protected $skipTotalRecords = false;
/**
* Flag to keep the select bindings.
*
* @var bool
*/
protected $keepSelectBindings = false;
/**
* Can the DataTable engine be created with these parameters.
*
* @param mixed $source
* @return bool
*/
public static function canCreate($source)
{
return $source instanceof Builder;
}
/**
* @param \Illuminate\Database\Query\Builder $builder
*/
public function __construct(Builder $builder)
{
$this->query = $builder;
$this->request = app('datatables.request');
$this->config = app('datatables.config');
$this->columns = $builder->columns;
$this->connection = $builder->getConnection();
if ($this->config->isDebugging()) {
$this->connection->enableQueryLog();
}
}
/**
* Organizes works.
*
* @param bool $mDataSupport
* @return \Illuminate\Http\JsonResponse
* @throws \Exception
*/
public function make($mDataSupport = true)
{
try {
$this->prepareQuery();
$results = $this->results();
$processed = $this->processResults($results, $mDataSupport);
$data = $this->transform($results, $processed);
return $this->render($data);
} catch (\Exception $exception) {
return $this->errorResponse($exception);
}
}
/**
* Prepare query by executing count, filter, order and paginate.
*/
protected function prepareQuery()
{
if (! $this->prepared) {
$this->totalRecords = $this->totalCount();
if ($this->totalRecords) {
$this->filterRecords();
$this->ordering();
$this->paginate();
}
}
$this->prepared = true;
}
/**
* Skip total records and set the recordsTotal equals to recordsFiltered.
* This will improve the performance by skipping the total count query.
*
* @return $this
*/
public function skipTotalRecords()
{
$this->skipTotalRecords = true;
return $this;
}
/**
* Keep the select bindings.
*
* @return $this
*/
public function keepSelectBindings()
{
$this->keepSelectBindings = true;
return $this;
}
/**
* Count total items.
*
* @return int
*/
public function totalCount()
{
if ($this->skipTotalRecords) {
return true;
}
return $this->totalRecords ? $this->totalRecords : $this->count();
}
/**
* Count filtered items.
*
* @return int
*/
protected function filteredCount()
{
$this->filteredRecords = $this->filteredRecords ?: $this->count();
if ($this->skipTotalRecords) {
$this->totalRecords = $this->filteredRecords;
}
return $this->filteredRecords;
}
/**
* Counts current query.
*
* @return int
*/
public function count()
{
$builder = $this->prepareCountQuery();
$table = $this->connection->raw('(' . $builder->toSql() . ') count_row_table');
return $this->connection->table($table)
->setBindings($builder->getBindings())
->count();
}
/**
* Prepare count query builder.
*
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
*/
protected function prepareCountQuery()
{
$builder = clone $this->query;
if (! $this->isComplexQuery($builder)) {
$row_count = $this->wrap('row_count');
$builder->select($this->connection->raw("'1' as {$row_count}"));
if (! $this->keepSelectBindings) {
$builder->setBindings([], 'select');
}
}
return $builder;
}
/**
* Check if builder query uses complex sql.
*
* @param \Illuminate\Database\Query\Builder $builder
* @return bool
*/
protected function isComplexQuery($builder)
{
return Str::contains(Str::lower($builder->toSql()), ['union', 'having', 'distinct', 'order by', 'group by']);
}
/**
* Wrap column with DB grammar.
*
* @param string $column
* @return string
*/
protected function wrap($column)
{
return $this->connection->getQueryGrammar()->wrap($column);
}
/**
* Get paginated results.
*
* @return \Illuminate\Support\Collection
*/
public function results()
{
return $this->query->get();
}
/**
* Get filtered, ordered and paginated query.
*
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
*/
public function getFilteredQuery()
{
$this->prepareQuery();
return $this->getQuery();
}
/**
* Get query builder instance.
*
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
*/
public function getQuery()
{
return $this->query;
}
/**
* Perform column search.
*
* @return void
*/
public function columnSearch()
{
$columns = $this->request->columns();
foreach ($columns as $index => $column) {
$column = $this->getColumnName($index);
if (! $this->request->isColumnSearchable($index) || $this->isBlacklisted($column) && ! $this->hasFilterColumn($column)) {
continue;
}
if ($this->hasFilterColumn($column)) {
$keyword = $this->getColumnSearchKeyword($index, $raw = true);
$this->applyFilterColumn($this->getBaseQueryBuilder(), $column, $keyword);
} else {
$column = $this->resolveRelationColumn($column);
$keyword = $this->getColumnSearchKeyword($index);
$this->compileColumnSearch($index, $column, $keyword);
}
$this->isFilterApplied = true;
}
}
/**
* Check if column has custom filter handler.
*
* @param string $columnName
* @return bool
*/
public function hasFilterColumn($columnName)
{
return isset($this->columnDef['filter'][$columnName]);
}
/**
* Get column keyword to use for search.
*
* @param int $i
* @param bool $raw
* @return string
*/
protected function getColumnSearchKeyword($i, $raw = false)
{
$keyword = $this->request->columnKeyword($i);
if ($raw || $this->request->isRegex($i)) {
return $keyword;
}
return $this->setupKeyword($keyword);
}
/**
* Apply filterColumn api search.
*
* @param mixed $query
* @param string $columnName
* @param string $keyword
* @param string $boolean
*/
protected function applyFilterColumn($query, $columnName, $keyword, $boolean = 'and')
{
$query = $this->getBaseQueryBuilder($query);
$callback = $this->columnDef['filter'][$columnName]['method'];
if ($this->query instanceof EloquentBuilder) {
$builder = $this->query->newModelInstance()->newQuery();
} else {
$builder = $this->query->newQuery();
}
$callback($builder, $keyword);
$query->addNestedWhereQuery($this->getBaseQueryBuilder($builder), $boolean);
}
/**
* Get the base query builder instance.
*
* @param mixed $instance
* @return \Illuminate\Database\Query\Builder
*/
protected function getBaseQueryBuilder($instance = null)
{
if (! $instance) {
$instance = $this->query;
}
if ($instance instanceof EloquentBuilder) {
return $instance->getQuery();
}
return $instance;
}
/**
* Resolve the proper column name be used.
*
* @param string $column
* @return string
*/
protected function resolveRelationColumn($column)
{
return $column;
}
/**
* Compile queries for column search.
*
* @param int $i
* @param string $column
* @param string $keyword
*/
protected function compileColumnSearch($i, $column, $keyword)
{
if ($this->request->isRegex($i)) {
$column = strstr($column, '(') ? $this->connection->raw($column) : $column;
$this->regexColumnSearch($column, $keyword);
} else {
$this->compileQuerySearch($this->query, $column, $keyword, '');
}
}
/**
* Compile regex query column search.
*
* @param mixed $column
* @param string $keyword
*/
protected function regexColumnSearch($column, $keyword)
{
switch ($this->connection->getDriverName()) {
case 'oracle':
$sql = ! $this->config->isCaseInsensitive()
? 'REGEXP_LIKE( ' . $column . ' , ? )'
: 'REGEXP_LIKE( LOWER(' . $column . ') , ?, \'i\' )';
break;
case 'pgsql':
$column = $this->castColumn($column);
$sql = ! $this->config->isCaseInsensitive() ? $column . ' ~ ?' : $column . ' ~* ? ';
break;
default:
$sql = ! $this->config->isCaseInsensitive()
? $column . ' REGEXP ?'
: 'LOWER(' . $column . ') REGEXP ?';
$keyword = Str::lower($keyword);
}
$this->query->whereRaw($sql, [$keyword]);
}
/**
* Wrap a column and cast based on database driver.
*
* @param string $column
* @return string
*/
protected function castColumn($column)
{
switch ($this->connection->getDriverName()) {
case 'pgsql':
return 'CAST(' . $column . ' as TEXT)';
case 'firebird':
return 'CAST(' . $column . ' as VARCHAR(255))';
default:
return $column;
}
}
/**
* Compile query builder where clause depending on configurations.
*
* @param mixed $query
* @param string $column
* @param string $keyword
* @param string $boolean
*/
protected function compileQuerySearch($query, $column, $keyword, $boolean = 'or')
{
$column = $this->addTablePrefix($query, $column);
$column = $this->castColumn($column);
$sql = $column . ' LIKE ?';
if ($this->config->isCaseInsensitive()) {
$sql = 'LOWER(' . $column . ') LIKE ?';
}
$query->{$boolean . 'WhereRaw'}($sql, [$this->prepareKeyword($keyword)]);
}
/**
* Patch for fix about ambiguous field.
* Ambiguous field error will appear when query use join table and search with keyword.
*
* @param mixed $query
* @param string $column
* @return string
*/
protected function addTablePrefix($query, $column)
{
if (strpos($column, '.') === false) {
$q = $this->getBaseQueryBuilder($query);
if (! $q->from instanceof Expression) {
$column = $q->from . '.' . $column;
}
}
return $this->wrap($column);
}
/**
* Prepare search keyword based on configurations.
*
* @param string $keyword
* @return string
*/
protected function prepareKeyword($keyword)
{
if ($this->config->isCaseInsensitive()) {
$keyword = Str::lower($keyword);
}
if ($this->config->isWildcard()) {
$keyword = Helper::wildcardLikeString($keyword);
}
if ($this->config->isSmartSearch()) {
$keyword = "%$keyword%";
}
return $keyword;
}
/**
* Add custom filter handler for the give column.
*
* @param string $column
* @param callable $callback
* @return $this
*/
public function filterColumn($column, callable $callback)
{
$this->columnDef['filter'][$column] = ['method' => $callback];
return $this;
}
/**
* Order each given columns versus the given custom sql.
*
* @param array $columns
* @param string $sql
* @param array $bindings
* @return $this
*/
public function orderColumns(array $columns, $sql, $bindings = [])
{
foreach ($columns as $column) {
$this->orderColumn($column, str_replace(':column', $column, $sql), $bindings);
}
return $this;
}
/**
* Override default column ordering.
*
* @param string $column
* @param string $sql
* @param array $bindings
* @return $this
* @internal string $1 Special variable that returns the requested order direction of the column.
*/
public function orderColumn($column, $sql, $bindings = [])
{
$this->columnDef['order'][$column] = compact('sql', 'bindings');
return $this;
}
/**
* Set datatables to do ordering with NULLS LAST option.
*
* @return $this
*/
public function orderByNullsLast()
{
$this->nullsLast = true;
return $this;
}
/**
* Paginate dataTable using limit without offset
* with additional where clause via callback.
*
* @param callable $callback
* @return $this
*/
public function limit(callable $callback)
{
$this->limitCallback = $callback;
return $this;
}
/**
* Perform pagination.
*
* @return void
*/
public function paging()
{
$limit = (int) $this->request->input('length') > 0 ? $this->request->input('length') : 10;
if (is_callable($this->limitCallback)) {
$this->query->limit($limit);
call_user_func_array($this->limitCallback, [$this->query]);
} else {
$this->query->skip($this->request->input('start'))->take($limit);
}
}
/**
* Add column in collection.
*
* @param string $name
* @param string|callable $content
* @param bool|int $order
* @return $this
*/
public function addColumn($name, $content, $order = false)
{
$this->pushToBlacklist($name);
return parent::addColumn($name, $content, $order);
}
/**
* Resolve callback parameter instance.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function resolveCallbackParameter()
{
return $this->query;
}
/**
* Perform default query orderBy clause.
*/
protected function defaultOrdering()
{
collect($this->request->orderableColumns())
->map(function ($orderable) {
$orderable['name'] = $this->getColumnName($orderable['column'], true);
return $orderable;
})
->reject(function ($orderable) {
return $this->isBlacklisted($orderable['name']) && ! $this->hasOrderColumn($orderable['name']);
})
->each(function ($orderable) {
$column = $this->resolveRelationColumn($orderable['name']);
if ($this->hasOrderColumn($column)) {
$this->applyOrderColumn($column, $orderable);
} else {
$nullsLastSql = $this->getNullsLastSql($column, $orderable['direction']);
$normalSql = $this->wrap($column) . ' ' . $orderable['direction'];
$sql = $this->nullsLast ? $nullsLastSql : $normalSql;
$this->query->orderByRaw($sql);
}
});
}
/**
* Check if column has custom sort handler.
*
* @param string $column
* @return bool
*/
protected function hasOrderColumn($column)
{
return isset($this->columnDef['order'][$column]);
}
/**
* Apply orderColumn custom query.
*
* @param string $column
* @param array $orderable
*/
protected function applyOrderColumn($column, $orderable)
{
$sql = $this->columnDef['order'][$column]['sql'];
$sql = str_replace('$1', $orderable['direction'], $sql);
$bindings = $this->columnDef['order'][$column]['bindings'];
$this->query->orderByRaw($sql, $bindings);
}
/**
* Get NULLS LAST SQL.
*
* @param string $column
* @param string $direction
* @return string
*/
protected function getNullsLastSql($column, $direction)
{
$sql = $this->config->get('datatables.nulls_last_sql', '%s %s NULLS LAST');
return sprintf($sql, $column, $direction);
}
/**
* Perform global search for the given keyword.
*
* @param string $keyword
*/
protected function globalSearch($keyword)
{
$this->query->where(function ($query) use ($keyword) {
collect($this->request->searchableColumnIndex())
->map(function ($index) {
return $this->getColumnName($index);
})
->reject(function ($column) {
return $this->isBlacklisted($column) && ! $this->hasFilterColumn($column);
})
->each(function ($column) use ($keyword, $query) {
if ($this->hasFilterColumn($column)) {
$this->applyFilterColumn($query, $column, $keyword, 'or');
} else {
$this->compileQuerySearch($query, $column, $keyword);
}
$this->isFilterApplied = true;
});
});
}
/**
* Append debug parameters on output.
*
* @param array $output
* @return array
*/
protected function showDebugger(array $output)
{
$query_log = $this->connection->getQueryLog();
array_walk_recursive($query_log, function (&$item, $key) {
$item = utf8_encode($item);
});
$output['queries'] = $query_log;
$output['input'] = $this->request->all();
return $output;
}
/**
* Attach custom with meta on response.
*
* @param array $data
* @return array
*/
protected function attachAppends(array $data)
{
$appends = [];
foreach ($this->appends as $key => $value) {
if (is_callable($value)) {
$appends[$key] = value($value($this->getFilteredQuery()));
} else {
$appends[$key] = $value;
}
}
return array_merge($data, $appends);
}
}