├── README.md ├── composer.json ├── license.md ├── screenshot.jpg └── src ├── Config └── config.php ├── Helpers.php ├── Indexer.php ├── IndexerMiddleware.php ├── Outputs ├── Output.php └── Web.php ├── ServiceProvider.php └── Traits └── FetchesStackTrace.php /README.md: -------------------------------------------------------------------------------- 1 | [](license.md) 2 | [![Latest Version on Packagist][ico-version]][link-packagist] 3 | [![Total Downloads][ico-downloads]][link-downloads] 4 | 5 | # Laravel Indexer 6 | 7 | Laravel Indexer monitors `SELECT` queries running on a page and allows to add database indexes to `SELECT` queries on the fly. It then presents results of `EXPLAIN` or MySQL's execution plan right on the page. The results presented by Indexer will help you see which indexes work best for different queries running on a page. 8 | 9 | Indexes *added by Indexer* are automatically removed after results are collected while keeping your existing indexes intact. 10 | 11 | > **CAUTION: PLEASE DO NOT USE THIS PACKAGE ON PRODUCTION!** 12 | Since this package adds indexes to database on the fly, it is strongly recommended NOT to use this package in your production environment. 13 | 14 | > **Note** Since indexes are added and then removed dynamically to generate results, pages will load slow. 15 | 16 | ## Requirements ## 17 | 18 | - PHP >= 7 19 | - Laravel 5.3+ | 6 20 | 21 | ## Installation ## 22 | 23 | Install via composer 24 | 25 | ``` 26 | composer require sarfraznawaz2005/indexer --dev 27 | ``` 28 | 29 | For Laravel < 5.5: 30 | 31 | Add Service Provider to `config/app.php` in `providers` section 32 | ```php 33 | Sarfraznawaz2005\Indexer\ServiceProvider::class, 34 | ``` 35 | 36 | --- 37 | 38 | Publish package's config file by running below command: 39 | 40 | ```bash 41 | php artisan vendor:publish --provider="Sarfraznawaz2005\Indexer\ServiceProvider" 42 | ``` 43 | It should publish `config/indexer.php` config file. 44 | 45 | --- 46 | 47 | ## Screenshot ## 48 | 49 | When enabled, you will see yellow/green/red box on bottom right: 50 | 51 | - Yellow by default or when queries need to be optimized 52 | - Green when total queries count matches optimized queries count. 53 | - Red when one or more slow queries found and need to be optimized. 54 | 55 |  56 | 57 | ## Config ## 58 | 59 | `enabled` : Enable or disable Indexer. By default it is disabled. 60 | 61 | `check_ajax_requests` : Specify whether to check queries in ajax requests. 62 | 63 | `ignore_tables` : When you don't use `watched_tables` option, Indexer watches all tables. Using this option, you can ignore specified tables to be watched. 64 | 65 | `ignore_paths` : These paths/patterns will NOT be handled by Indexer. 66 | 67 | `slow_time` : Time in ms when queries will be considered slow. 68 | 69 | `output_to` : Outputs results to given classes. By default `Web` class is included. 70 | 71 | `watched_tables` : DB tables to be watched by Indexer. Here is example: 72 | 73 | ````php 74 | 'watched_tables' => [ 75 | 'users' => [ 76 | // list of already existing indexes to try 77 | 'try_table_indexes' => ['email'], 78 | // new indexes to try 79 | 'try_indexes' => ['name'], 80 | // new composite indexes to try 81 | 'try_composite_indexes' => [ 82 | ['name', 'email'], 83 | ], 84 | ], 85 | ], 86 | ```` 87 | 88 | - Here queries involving `users` DB table will be watched by Indexer. 89 | - `try_table_indexes` contains index names that you have already applied to your DB table. Indexer will simply try out your existing indexes to show `EXPLAIN` results. In this case, `email` index already exists in `users` table. 90 | - `try_indexes` can be used to add new indexes on the fly to DB table. In this case, `name` index will be added on the fly by Indexer and results will be shown of how that index performed. 91 | - Like `try_indexes` the `try_composite_indexes` can also be used to add composite indexes on the fly to DB table. In this case, composite index consisting of `name` and `email` will be added on the fly by Indexer and results will be shown of how that index performed. 92 | 93 | 94 | ## Modes ## 95 | 96 | Indexer can be used in following ways: 97 | 98 | **All Indexes Added By Indexer** 99 | 100 | Don't put any indexes manually on your tables instead let Indexer add indexes on the fly via `try_indexes` and/or `try_composite_indexes` options. Indexes added via these two options are automatically removed. 101 | 102 | In this mode, you can actually see which indexes work best without actually applying on your tables. You can skip using `try_table_indexes` option in this case. 103 | 104 | **Already Present Indexes + Indexes Added By Indexer** 105 | 106 | You might have some indexes already present on your tables but you want to try out more indexes on the fly without actually adding those to the table. To specify table's existing indexes, use `try_table_indexes` option as mentioned earlier. And to try out new indexes on the fly, use `try_indexes` and/or `try_composite_indexes` options. Table's existing indexes (specified in `try_table_indexes`) will remain intact but indexes added via `try_indexes` and `try_composite_indexes` will be automatically removed. 107 | 108 | **Already Present Indexes** 109 | 110 | When you don't want Indexer to add any indexes on the fly and you have already specified indexes on your tables and you just want to see `EXPLAIN` results for specific tables for your indexes, in this case simply use `try_table_indexes` option only. Example: 111 | 112 | ````php 113 | 'watched_tables' => [ 114 | 'users' => [ 115 | 'try_table_indexes' => ['email'], 116 | ], 117 | 'posts' => [ 118 | 'try_table_indexes' => ['title'], 119 | ] 120 | ], 121 | ```` 122 | 123 | In this case, both `email` and `title` indexes are supposed to be already added to table manually. 124 | 125 | **No Indexes, Just Show EXPLAIN results for all SELECT queries** 126 | 127 | While previous three modes allow you to work with *specific tables and indexes*, you can use this mode to just show EXPLAIN results for all SELECT queries running on a page without adding any indexes on the fly. To use this mode, simply don't specify any tables in `watched_tables` option. If you don't want to include some tables in this mode, use `ignore_tables` option. 128 | 129 | ## Misc ## 130 | 131 | - Color of Indexer box on bottom right or query sections inside results changes to green if it finds query's `EXPLAIN` result has `key` present eg query actually used a key. This can be changed by creating your own function in your codebase called `indexerOptimizedKeyCustom(array $queries)` instead of default one `indexerOptimizedKey` which is present in file `src/Helpers.php`. Similarly, for ajax requests, you should define your own function called `indexerOptimizedKeyCustom(explain_result)`. Here is example of each: 132 | 133 | ````php 134 | // php 135 | function indexerOptimizedKeyCustom(array $query): string 136 | { 137 | return trim($query['explain_result']['key']); 138 | } 139 | ```` 140 | 141 | ````javascript 142 | // javascript 143 | function indexerOptimizedKeyCustom(explain_result) { 144 | return explain_result['key'] && explain_result['key'].trim(); 145 | } 146 | ```` 147 | 148 | *Note: If Indexer has found any slow queries (enabled via `slow_time` option), the color of box on bottom right will always be red until you fix slow queries.* 149 | 150 | ## Limitation ## 151 | 152 | * Indexer tries to find out tables names after `FROM` keyword in queries, therefore it cannot work with complex queries or ones that don't have table name after `FROM` keyword. 153 | 154 | ## Security 155 | 156 | If you discover any security related issues, please email sarfraznawaz2005@gmail.com instead of using the issue tracker. 157 | 158 | ## Credits 159 | 160 | - [Sarfraz Ahmed][link-author] 161 | - [All Contributors][link-contributors] 162 | 163 | ## License 164 | 165 | Please see the [license file](license.md) for more information. 166 | 167 | [ico-version]: https://img.shields.io/packagist/v/sarfraznawaz2005/indexer.svg?style=flat-square 168 | [ico-downloads]: https://img.shields.io/packagist/dt/sarfraznawaz2005/indexer.svg?style=flat-square 169 | 170 | [link-packagist]: https://packagist.org/packages/sarfraznawaz2005/indexer 171 | [link-downloads]: https://packagist.org/packages/sarfraznawaz2005/indexer 172 | [link-author]: https://github.com/sarfraznawaz2005 173 | [link-contributors]: https://github.com/sarfraznawaz2005/indexer/graphs/contributors 174 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sarfraznawaz2005/indexer", 3 | "keywords": [ 4 | "laravel", 5 | "database", 6 | "sql", 7 | "mysql", 8 | "index", 9 | "indexing", 10 | "eloquent", 11 | "querybuilder", 12 | "query", 13 | "queries", 14 | "performance", 15 | "speed", 16 | "boost", 17 | "optimization" 18 | ], 19 | "description": "Laravel package to monitor SELECT queries and offer best possible INDEX fields.", 20 | "type": "library", 21 | "license": "MIT", 22 | "authors": [ 23 | { 24 | "name": "Sarfraz Ahmed", 25 | "email": "sarfraznawaz2005@gmail.com" 26 | } 27 | ], 28 | "require": { 29 | "php": ">=7.0", 30 | "illuminate/support": "~5|~6|~7|~8", 31 | "doctrine/dbal": "^2" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "Sarfraznawaz2005\\Indexer\\": "src/" 36 | }, 37 | "files": [ 38 | "src/Helpers.php" 39 | ] 40 | }, 41 | "extra": { 42 | "laravel": { 43 | "providers": [ 44 | "Sarfraznawaz2005\\Indexer\\ServiceProvider" 45 | ] 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Sarfraz Ahmed 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sarfraznawaz2005/indexer/aa7ec09fa2cafae9ff62a21c9559711839c4f74e/screenshot.jpg -------------------------------------------------------------------------------- /src/Config/config.php: -------------------------------------------------------------------------------- 1 | env('INDEXER_ENABLED', false), 9 | 10 | /* 11 | * Specify whether to check queries in ajax requests. 12 | */ 13 | 'check_ajax_requests' => true, 14 | 15 | /* 16 | * These tables will be watched by Indexer and specified indexes will be tested. 17 | */ 18 | 'watched_tables' => [ 19 | /* 20 | 'users' => [ 21 | // list of already existing indexes to try 22 | 'try_table_indexes' => ['email'], 23 | // new indexes indexes to try 24 | 'try_indexes' => ['name'], 25 | // composite indexes to try 26 | 'try_composite_indexes' => [ 27 | ['name', 'email'], 28 | ], 29 | ], 30 | */ 31 | ], 32 | 33 | /* 34 | * When you don't use "watched_tables" option, Indexer watches all tables. 35 | * Using this option, you can ignore specified tables to be watched. 36 | */ 37 | 'ignore_tables' => [ 38 | // 39 | ], 40 | 41 | /* 42 | * These paths/patterns will NOT be handled by Indexer. 43 | */ 44 | 'ignore_paths' => [ 45 | // 'foo', 46 | // 'foo*', 47 | // '*foo', 48 | // '*foo*', 49 | ], 50 | 51 | /* 52 | * Time in ms when queries will be considered slow (>=). A slow query will 53 | * be highlighted with red color. Value of 0 means no color change. 54 | */ 55 | 'slow_time' => 0, 56 | 57 | /* 58 | * Outputs results class. 59 | */ 60 | 'output_to' => [ 61 | // outputs results into current visited page. 62 | Sarfraznawaz2005\Indexer\Outputs\Web::class, 63 | ], 64 | 65 | /* 66 | * Font size (including unit) in case of Web output class 67 | */ 68 | 'font_size' => '12px', 69 | ]; 70 | -------------------------------------------------------------------------------- /src/Helpers.php: -------------------------------------------------------------------------------- 1 | "; 82 | $output .= "
SELECT *
only if you need all columns from table';
462 | }
463 |
464 | if (preg_match('/ORDER BY RAND()/i', $query)) {
465 | $hints[] = 'ORDER BY RAND()
is slow, try to avoid if you can. You can read this or this';
466 | }
467 |
468 | if (strpos($query, '!=') !== false) {
469 | $hints[] = 'The !=
operator is not standard. Use the <>
operator to test for inequality instead.';
470 | }
471 |
472 | if (stripos($query, 'WHERE') === false && preg_match('/^(SELECT) /i', $query)) {
473 | $hints[] = 'The SELECT
statement has no WHERE
clause and could examine many more rows than intended';
474 | }
475 |
476 | if (preg_match('/LIMIT\\s/i', $query) && stripos($query, 'ORDER BY') === false) {
477 | $hints[] = 'LIMIT
without ORDER BY
causes non-deterministic results, depending on the query execution plan';
478 | }
479 |
480 | if (preg_match('/LIKE\\s[\'"](%.*?)[\'"]/i', $query, $matches)) {
481 | $hints[] = 'An argument has a leading wildcard character: ' . $matches[1] . '
. The predicate with this argument is not sargable and cannot use an index if one exists.';
482 | }
483 |
484 | return $hints;
485 | }
486 |
487 | /**
488 | * Gets composite indexes name based on how Laravel makes those names by default.
489 | *
490 | * @param string|array $index
491 | * @return string
492 | */
493 | protected function getLaravelIndexName($index): string
494 | {
495 | $name[] = $this->table;
496 |
497 | if (!is_array($index)) {
498 | $name[] = $index;
499 | } else {
500 | foreach ($index as $indexItem) {
501 | $name[] = $indexItem;
502 | }
503 | }
504 |
505 | $name[] = 'index';
506 |
507 | return strtolower(implode('_', $name));
508 | }
509 |
510 | /**
511 | * Replace the placeholders with the actual bindings.
512 | *
513 | * @param QueryExecuted $event
514 | * @return string
515 | */
516 | protected function replaceBindings($event): string
517 | {
518 | $sql = $event->sql;
519 |
520 | foreach ($this->formatBindings($event) as $key => $binding) {
521 | $regex = is_numeric($key)
522 | ? "/\?(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/"
523 | : "/:{$key}(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/";
524 |
525 | if ($binding === null) {
526 | $binding = 'null';
527 | } elseif (!is_int($binding) && !is_float($binding)) {
528 | $binding = $event->connection->getPdo()->quote($binding);
529 | }
530 |
531 | $sql = preg_replace($regex, $binding, $sql, 1);
532 | }
533 |
534 | return $sql;
535 | }
536 |
537 | /**
538 | * Format the given bindings to strings.
539 | *
540 | * @param QueryExecuted $event
541 | * @return array
542 | */
543 | protected function formatBindings($event): array
544 | {
545 | return $event->connection->prepareBindings($event->bindings);
546 | }
547 |
548 | /**
549 | * @return array|Repository|mixed
550 | */
551 | protected function getOutputTypes()
552 | {
553 | $outputTypes = config('indexer.output_to', [Web::class]);
554 |
555 | if (!is_array($outputTypes)) {
556 | $outputTypes = [$outputTypes];
557 | }
558 |
559 | return $outputTypes;
560 | }
561 |
562 | /**
563 | * Applies output.
564 | *
565 | * @param Request $request
566 | * @param \Symfony\Component\HttpFoundation\Response $response
567 | */
568 | protected function applyOutput(Request $request, \Symfony\Component\HttpFoundation\Response $response)
569 | {
570 | // sort by time descending
571 | $this->queries = collect($this->queries)->sortByDesc('time')->all();
572 |
573 | foreach ($this->getOutputTypes() as $type) {
574 | app($type)->output($this->queries, $request, $response);
575 | }
576 | }
577 |
578 | /**
579 | * Outputs results.
580 | *
581 | * @param Request $request
582 | * @param $response
583 | * @return Response|void
584 | */
585 | public function outputResults(Request $request, $response)
586 | {
587 | $this->applyOutput($request, $response);
588 |
589 | return $response;
590 | }
591 | }
592 |
--------------------------------------------------------------------------------
/src/IndexerMiddleware.php:
--------------------------------------------------------------------------------
1 | indexer = $indexer;
17 | }
18 |
19 | /**
20 | * Handle an incoming request.
21 | *
22 | * @param Request $request
23 | * @param Closure $next
24 | * @return mixed
25 | */
26 | public function handle($request, Closure $next)
27 | {
28 | if (!$this->canSendResponse($request)) {
29 | return $next($request);
30 | }
31 |
32 | $this->indexer->boot();
33 |
34 | $response = $next($request);
35 |
36 | $this->indexer->outputResults($request, $response);
37 |
38 | return $response;
39 | }
40 |
41 | /**
42 | * See if we can add indexer results to response.
43 | *
44 | * @param Request $request
45 | * @param $response
46 | * @return bool
47 | */
48 | protected function canSendResponse(Request $request): bool
49 | {
50 | if (!$this->indexer->isEnabled()) {
51 | return false;
52 | }
53 |
54 | if (!$request->isMethod('get')) {
55 | if (!$request->ajax() && !$request->expectsJson()) {
56 | return false;
57 | }
58 | }
59 |
60 | if (!$this->isAllowedRequest()) {
61 | return false;
62 | }
63 |
64 | return true;
65 | }
66 |
67 | /**
68 | * Check if we are handling allowed request/page.
69 | *
70 | * @return bool
71 | */
72 | protected function isAllowedRequest(): bool
73 | {
74 | $ignoredPaths = array_merge([
75 | '*indexer*',
76 | '*meter*',
77 | '*debugbar*',
78 | '*_debugbar*',
79 | '*clockwork*',
80 | '*_clockwork*',
81 | '*telescope*',
82 | '*horizon*',
83 | '*vendor/horizon*',
84 | '*nova-api*',
85 | ], config('indexer.ignore_paths', []));
86 |
87 | return !app()->request->is($ignoredPaths);
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/Outputs/Output.php:
--------------------------------------------------------------------------------
1 | headers->get('Content-Type'), 'text/html') !== 0) {
19 | //return;
20 | }
21 |
22 | if ($response instanceof BinaryFileResponse) {
23 | return;
24 | }
25 |
26 | if ($response->isRedirection()) {
27 | return;
28 | }
29 |
30 | if (app()->runningInConsole()) {
31 | return;
32 | }
33 |
34 | if (!$request->acceptsHtml()) {
35 | return;
36 | }
37 |
38 | if ($request->ajax() || $request->expectsJson()) {
39 |
40 | if ($queries && config('indexer.check_ajax_requests', false)) {
41 | $response->headers->set('indexer_ajax_response', json_encode($queries));
42 | }
43 |
44 | return;
45 | }
46 |
47 | $content = $response->getContent();
48 | $outputContent = $this->getOutputContent($queries);
49 | $position = strripos($content, '');
50 |
51 | if (false !== $position) {
52 | $content = substr($content, 0, $position) . $outputContent . substr($content, $position);
53 | } else {
54 | $content .= $outputContent;
55 | }
56 |
57 | // Update the new content and reset the content length
58 | $response->setContent($content);
59 |
60 | $response->headers->remove('Content-Length');
61 | }
62 |
63 | /**
64 | * Sends output
65 | *
66 | * @param array $queries
67 | * @return string
68 | */
69 | protected function getOutputContent(array $queries): string
70 | {
71 | $output = '';
72 |
73 | $fontSize = config('indexer.font_size', '12px');
74 |
75 | $colorYellow = '#fff382';
76 | $colorGreen = '#91e27f';
77 | $colorRed = '#ff7a94';
78 |
79 | $totalCount = count($queries);
80 | $slowCount = (int)indexerGetSlowCount($queries);
81 | $optimizedCount = (int)indexerGetOptimizedCount($queries);
82 |
83 | // default color
84 | $indexerColor = $colorYellow;
85 |
86 | // when all queries are optimized
87 | if ($optimizedCount === $totalCount) {
88 | $indexerColor = $colorGreen;
89 | }
90 |
91 | // when one or more slow queries found
92 | if ($slowCount) {
93 | $indexerColor = $colorRed;
94 | }
95 |
96 | $output .= <<< OUTOUT
97 |
128 | OUTOUT;
129 |
130 |
131 | $output .= 'INDEXER ' . $optimizedCount . '/' . $totalCount . '';
132 | $output .= '';
133 | $output .= ' ';
145 | }
146 | } else {
147 | $output .= '