Issues (6)

src/Helper/QueryBuilderHelper.php (1 issue)

1
<?php
2
3
namespace Socialblue\LaravelQueryAdviser\Helper;
4
5
use Illuminate\Support\Facades\DB;
6
7
class QueryBuilderHelper
8
{
9
    public static function infoByBuilder($builder)
10
    {
11
        return [
12
            'toSql' => $builder->toSql(),
13
            'bindings' => $builder->getBindings(),
14
            'query' => self::addBindingsToQueryByBuilder($builder),
15
            'optimizeQuery' => self::showOptimizedQueryByBuilder($builder),
16
        ];
17
    }
18
19
    /**
20
     * @param $builder
21
     * @return mixed
22
     */
23
    public static function getQueryByBuilder($builder)
24
    {
25
        return self::addBindingsToQueryByBuilder($builder);
26
    }
27
28
    /**
29
     * @param $sql
30
     * @param $bindings
31
     * @return string|string[]|null
32
     */
33
    public static function combineQueryAndBindings($sql, $bindings)
34
    {
35
        $pdo = DB::connection()->getPdo();
36
37
        while (strpos($sql, '?') !== false) {
38
            $value = array_shift($bindings);
39
            if ($value instanceof \DateTime) {
40
                $value = $value->format('Y-m-d H:i:s');
41
            }
42
43
            $sql = preg_replace('/\?/', $pdo->quote(addslashes(addslashes($value))), $sql, 1);
44
        }
45
        return $sql;
46
    }
47
48
    public static function getServerInfo(): array
49
    {
50
        return [
51
            'info' =>
52
                DB::connection()
53
                    ->getPdo()
54
                    ->getAttribute(\PDO::ATTR_SERVER_INFO),
55
            'version' =>
56
                DB::connection()
57
                    ->getPdo()
58
                    ->getAttribute(\PDO::ATTR_SERVER_VERSION),
59
            'client' =>
60
                DB::connection()
61
                    ->getPdo()
62
                    ->getAttribute(\PDO::ATTR_CLIENT_VERSION),
63
            'status' =>
64
                DB::connection()
65
                    ->getPdo()
66
                    ->getAttribute(\PDO::ATTR_CONNECTION_STATUS),
67
        ];
68
    }
69
70
    /**
71
    id – a sequential identifier for each SELECT within the query (for when you have nested subqueries)
72
    select_type – the type of SELECT query. Possible values are:
73
    table – the table referred to by the row
74
    type – how MySQL joins the tables used. This is one of the most insightful fields in the output because it can indicate missing indexes or how the query is written should be reconsidered. Possible values are:
75
    possible_keys – shows the keys that can be used by MySQL to find rows from the table, though they may or may not be used in practice. In fact, this column can often help in optimizing queries since if the column is NULL, it indicates no relevant indexes could be found.
76
    key – indicates the actual index used by MySQL. This column may contain an index that is not listed in the possible_key column. MySQL optimizer always look for an optimal key that can be used for the query. While joining many tables, it may figure out some other keys which is not listed in possible_key but are more optimal.
77
    key_len – indicates the length of the index the Query Optimizer chose to use. For example, a key_len value of 4 means it requires memory to store four characters. Check out MySQL’s data type storage requirements to know more about this.
78
    ref – Shows the columns or constants that are compared to the index named in the key column. MySQL will either pick a constant value to be compared or a column itself based on the query execution plan. You can see this in the example given below.
79
    rows – lists the number of records that were examined to produce the output. This Is another important column worth focusing on optimizing queries, especially for queries that use JOIN and subqueries.
80
    Extra – contains additional information regarding the query execution plan. Values such as “Using temporary”, “Using filesort”, etc. in this column may indicate a troublesome query. For a complete list of possible values and their meaning, check out the MySQL documentation.
81
     *
82
     *
83
     *
84
     *
85
     * @param $builder
86
     */
87
    public static function analyzeByBuilder($builder)
88
    {
89
        //todo fix to use
90
        return self::analyze($builder->toSql(), $builder->getBindings());
91
    }
92
93
    /**
94
     * @param $sql
95
     * @param $bindings
96
     * @return array
97
     */
98
    public static function analyze($rawSql, $bindings)
99
    {
100
        $query = [
101
            'sql' => $rawSql,
102
            'bindings' => $bindings,
103
        ];
104
        $queryData = DB::connection()->select('EXPLAIN ' . $rawSql, $bindings);
105
106
        DB::connection()->getPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
107
        $showWarnings = DB::connection()->getPdo()->query("SHOW WARNINGS");
108
        $sqlOptimized = $showWarnings->fetchColumn(2);
109
        DB::connection()->getPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
110
111
        return [
112
            'queryParts' => $queryData,
113
            'query' => $query,
114
            'optimized' => $sqlOptimized,
115
        ];
116
    }
117
118
    /**
119
     * @param $builder
120
     * @return mixed
121
     * @throws \Exception
122
     */
123
    public static function showOptimizedQueryByBuilder($builder)
124
    {
125
        return self::analyzeByBuilder($builder)['optimized'];
126
    }
127
128
    /**
129
     * @param $builder
130
     */
131
    protected static function addBindingsToQueryByBuilder($builder): string
132
    {
133
        return self::combineQueryAndBindings($builder->toSql(), $builder->getBindings());
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::combineQuer...builder->getBindings()) could return the type null|string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
134
    }
135
}
136