Completed
Push — master ( 8dbe44...7cd8ac )
by Daniel
03:24
created

MySQLiByDanielGPqueries   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 196
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 24
Bugs 0 Features 3
Metric Value
wmc 26
c 24
b 0
f 3
lcom 1
cbo 1
dl 0
loc 196
rs 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
A sGlueFilterValueIntoWhereString() 0 7 2
A sGlueFilterValueIntoWhereStringFinal() 0 16 4
A sGlueFiltersIntoWhereArrayFilter() 0 4 1
A sManageDynamicFilters() 0 11 4
A sManageDynamicFiltersFinal() 0 8 2
A sQueryMySqlColumns() 0 15 1
A sQueryMySqlColumnsColumns() 0 8 1
A sQueryMySqlIndexes() 0 19 1
A sQueryMySqlIndexesColumns() 0 8 1
A sQueryMySqlStatisticPattern() 0 8 3
A sQueryMySqlStatistics() 0 16 1
A sQueryMySqlTables() 0 10 1
A xtraSoring() 0 17 4
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * Queries for the MySQL module
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiByDanielGPqueries
37
{
38
39
    use MySQLiByDanielGPqueriesBasic;
40
41
    /**
42
     * Internal function to manage concatenation for filters
43
     *
44
     * @param type $filterValue
45
     * @return string
46
     */
47
    private function sGlueFilterValueIntoWhereString($filterValue)
48
    {
49
        if (is_array($filterValue)) {
50
            return 'IN ("' . implode('", "', $filterValue) . '")';
51
        }
52
        return $this->sGlueFilterValueIntoWhereStringFinal($filterValue);
53
    }
54
55
    private function sGlueFilterValueIntoWhereStringFinal($filterValue)
56
    {
57
        $kFields = [
58
            'CONNECTION_ID()|CURDATE()|CURRENT_USER|CURRENT_USER()|CURRENT_DATETIME|DATABASE()|NOW()|USER()',
59
            'IS NULL|IS NOT NULL',
60
            'NOT NULL|NULL',
61
        ];
62
        if (in_array($filterValue, explode('|', $kFields[0]))) {
63
            return '= ' . $filterValue;
64
        } elseif (in_array($filterValue, explode('|', $kFields[1]))) {
65
            return $filterValue;
66
        } elseif (in_array($filterValue, explode('|', $kFields[2]))) {
67
            return 'IS ' . $filterValue;
68
        }
69
        return '= "' . $filterValue . '"';
70
    }
71
72
    /**
73
     * Internal function to concatenate filters
74
     *
75
     * @param array $filters
76
     * @return type
77
     */
78
    private function sGlueFiltersIntoWhereArrayFilter($filters)
79
    {
80
        return '(' . implode(') AND (', $filters) . ')';
81
    }
82
83
    /**
84
     * Internal function to manage the filters passed to the query
85
     *
86
     * @param array $filterArray
87
     * @param string $tableToApplyFilterTo
88
     * @return string
89
     */
90
    private function sManageDynamicFilters($filterArray = null, $tableToApplyFilterTo = '')
91
    {
92
        $filters = [];
93
        if (!is_null($filterArray) && is_array($filterArray)) {
94
            foreach ($filterArray as $key => $value) {
95
                $filters[] = '`' . $tableToApplyFilterTo . '`.`' . $key . '` '
96
                        . $this->sGlueFilterValueIntoWhereString($value);
97
            }
98
        }
99
        return $this->sManageDynamicFiltersFinal($filters);
100
    }
101
102
    private function sManageDynamicFiltersFinal($filters)
103
    {
104
        if (count($filters) > 0) {
105
            $sReturn = ['WHERE', $this->sGlueFiltersIntoWhereArrayFilter($filters)];
106
            return implode(' ', $sReturn) . ' ';
107
        }
108
        return '';
109
    }
110
111
    protected function sQueryMySqlColumns($filterArray = null)
112
    {
113
        return 'SELECT '
114
                . '`C`.`TABLE_SCHEMA`, '
115
                . $this->sQueryMySqlColumnsColumns() . ' '
116
                . 'FROM `information_schema`.`COLUMNS` `C` '
117
                . 'LEFT JOIN `information_schema`.`KEY_COLUMN_USAGE` `KCU` ON ((' . implode(') AND (', [
118
                    '`C`.`TABLE_SCHEMA` = `KCU`.`TABLE_SCHEMA`',
119
                    '`C`.`TABLE_NAME` = `KCU`.`TABLE_NAME`',
120
                    '`C`.`COLUMN_NAME` = `KCU`.`COLUMN_NAME`',
121
                ]) . ')) '
122
                . $this->sManageDynamicFilters($filterArray, 'C')
123
                . 'GROUP BY `C`.`TABLE_SCHEMA`, `C`.`TABLE_NAME`, `C`.`COLUMN_NAME` '
124
                . 'ORDER BY `C`.`TABLE_SCHEMA`, `C`.`TABLE_NAME`, `C`.`ORDINAL_POSITION`;';
125
    }
126
127
    private function sQueryMySqlColumnsColumns()
128
    {
129
        return '`C`.`TABLE_NAME`, `C`.`COLUMN_NAME`, `C`.`ORDINAL_POSITION` '
130
                . ', `C`.`COLUMN_DEFAULT`, `C`.`IS_NULLABLE`, `C`.`DATA_TYPE`, `C`.`CHARACTER_MAXIMUM_LENGTH` '
131
                . ', `C`.`NUMERIC_PRECISION`, `C`.`NUMERIC_SCALE`, `C`.`DATETIME_PRECISION` '
132
                . ', `C`.`CHARACTER_SET_NAME`, `C`.`COLLATION_NAME`, `C`.`COLUMN_TYPE` '
133
                . ', `C`.`COLUMN_KEY`, `C`.`COLUMN_COMMENT`, `C`.`EXTRA`';
134
    }
135
136
    /**
137
     * Query
138
     *
139
     * @param array $filterArray
140
     * @return string
141
     */
142
    protected function sQueryMySqlIndexes($filterArray = null)
143
    {
144
        return 'SELECT '
145
                . '`KCU`.`CONSTRAINT_SCHEMA`, '
146
                . $this->sQueryMySqlIndexesColumns() . ' '
147
                . 'FROM `information_schema`.`KEY_COLUMN_USAGE` `KCU` '
148
                . 'INNER JOIN `information_schema`.`COLUMNS` `C` ON ((' . implode(') AND (', [
149
                    '`C`.`TABLE_SCHEMA` = `KCU`.`TABLE_SCHEMA`',
150
                    '`C`.`TABLE_NAME` = `KCU`.`TABLE_NAME`',
151
                    '`C`.`COLUMN_NAME` = `KCU`.`COLUMN_NAME`',
152
                ]) . ')) '
153
                . 'LEFT JOIN `information_schema`.`REFERENTIAL_CONSTRAINTS` `RC` ON ((' . implode(') AND (', [
154
                    '`KCU`.`CONSTRAINT_SCHEMA` = `RC`.`CONSTRAINT_SCHEMA`',
155
                    '`KCU`.`CONSTRAINT_NAME` = `RC`.`CONSTRAINT_NAME`',
156
                ]) . ')) '
157
                . $this->sManageDynamicFilters($filterArray, 'KCU')
158
                . 'ORDER BY `KCU`.`TABLE_SCHEMA`, `KCU`.`TABLE_NAME`'
159
                . $this->xtraSoring($filterArray, 'COLUMN_NAME') . ';';
160
    }
161
162
    private function sQueryMySqlIndexesColumns()
163
    {
164
        return '`KCU`.`CONSTRAINT_NAME`, `KCU`.`TABLE_SCHEMA`, `KCU`.`TABLE_NAME`, '
165
                . '`KCU`.`COLUMN_NAME`, `C`.`ORDINAL_POSITION` AS `COLUMN_POSITION`, `KCU`.`ORDINAL_POSITION`, '
166
                . '`KCU`.`POSITION_IN_UNIQUE_CONSTRAINT`, `KCU`.`REFERENCED_TABLE_SCHEMA`, '
167
                . '`KCU`.`REFERENCED_TABLE_NAME`, `KCU`.`REFERENCED_COLUMN_NAME`, '
168
                . '`RC`.`UPDATE_RULE`, `RC`.`DELETE_RULE`';
169
    }
170
171
    private function sQueryMySqlStatisticPattern($tblName, $lnkDbCol, $adtnlCol = null, $adtnlFltr = null)
172
    {
173
        $tblAls = substr($tblName, 0, 1);
174
        return '(SELECT COUNT(*) AS `No. of records` FROM `information_schema`.`' . $tblName . '` `' . $tblAls . '` '
175
                . 'WHERE (`' . $tblAls . '`.`' . $lnkDbCol . '` = `S`.`SCHEMA_NAME`)'
176
                . (!is_null($adtnlCol) ? ' AND (`' . $tblAls . '`.`' . $adtnlCol . '` = "' . $adtnlFltr . '")' : '')
177
                . ') AS `' . ucwords(strtolower((is_null($adtnlCol) ? $tblName : $adtnlFltr))) . '`';
178
    }
179
180
    protected function sQueryMySqlStatistics($filterArray = null)
181
    {
182
        return 'SELECT '
183
                . '`S`.`SCHEMA_NAME`, '
184
                . $this->sQueryMySqlStatisticPattern('TABLES', 'TABLE_SCHEMA', 'TABLE_TYPE', 'BASE TABLE') . ', '
185
                . $this->sQueryMySqlStatisticPattern('TABLES', 'TABLE_SCHEMA', 'TABLE_TYPE', 'VIEW') . ', '
186
                . $this->sQueryMySqlStatisticPattern('COLUMNS', 'TABLE_SCHEMA') . ', '
187
                . $this->sQueryMySqlStatisticPattern('TRIGGERS', 'EVENT_OBJECT_SCHEMA') . ', '
188
                . $this->sQueryMySqlStatisticPattern('ROUTINES', 'ROUTINE_SCHEMA', 'ROUTINE_TYPE', 'Function') . ', '
189
                . $this->sQueryMySqlStatisticPattern('ROUTINES', 'ROUTINE_SCHEMA', 'ROUTINE_TYPE', 'Procedure') . ', '
190
                . $this->sQueryMySqlStatisticPattern('EVENTS', 'EVENT_SCHEMA') . ' '
191
                . 'FROM `information_schema`.`SCHEMATA` `S` '
192
                . 'WHERE (`S`.`SCHEMA_NAME` NOT IN ("information_schema", "mysql", "performance_schema", "sys")) '
193
                . str_replace('WHERE|AND', $this->sManageDynamicFilters($filterArray, 'S'))
194
                . 'ORDER BY `S`.`SCHEMA_NAME`;';
195
    }
196
197
    /**
198
     * Query to get list of tables
199
     *
200
     * @param type $filterArray
201
     * @return string
202
     */
203
    protected function sQueryMySqlTables($filterArray = null)
204
    {
205
        return 'SELECT '
206
                . '`T`.`TABLE_SCHEMA`, `T`.`TABLE_NAME`, `T`.`TABLE_TYPE`, `T`.`ENGINE`, `T`.`VERSION` '
207
                . ', `T`.`ROW_FORMAT`, `T`.`AUTO_INCREMENT`, `T`.`TABLE_COLLATION`, `T`.`CREATE_TIME` '
208
                . ', `T`.`CREATE_OPTIONS`, `T`.`TABLE_COMMENT` '
209
                . 'FROM `information_schema`.`TABLES` `T` '
210
                . $this->sManageDynamicFilters($filterArray, 'T')
211
                . $this->xtraSoring($filterArray, 'TABLE_SCHEMA') . ';';
212
    }
213
214
    private function xtraSoring($filterArray, $filterValueToDecide)
215
    {
216
        $defaults = [
217
            'COLUMN_NAME'  => [
218
                ', `C`.`ORDINAL_POSITION`, `KCU`.`CONSTRAINT_NAME`',
219
                '',
220
            ],
221
            'TABLE_SCHEMA' => [
222
                'ORDER BY `T`.`TABLE_SCHEMA`, `T`.`TABLE_NAME`',
223
                'ORDER BY `T`.`TABLE_NAME`',
224
            ],
225
        ];
226
        if (!is_null($filterArray) && is_array($filterArray) && array_key_exists($filterValueToDecide, $filterArray)) {
227
            return $defaults[$filterValueToDecide][1];
228
        }
229
        return $defaults[$filterValueToDecide][0];
230
    }
231
}
232