Completed
Push — master ( 2eb9e0...6fec5f )
by Daniel
02:30
created

MySQLiByDanielGPqueries::getForeignKeysQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 1
eloc 6
nc 1
nop 1
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
     * prepares the query to detect FKs
43
     *
44
     * @param array $value
45
     * @return string
46
     */
47
    protected function getForeignKeysQuery($value)
48
    {
49
        $flt = [
50
            'TABLE_SCHEMA' => $value['REFERENCED_TABLE_SCHEMA'],
51
            'TABLE_NAME'   => $value['REFERENCED_TABLE_NAME'],
52
            'DATA_TYPE'    => ['char', 'varchar', 'text'],
53
        ];
54
        return $this->sQueryMySqlColumns($flt);
55
    }
56
57
    /**
58
     * Internal function to manage concatenation for filters
59
     *
60
     * @param type $filterValue
61
     * @return string
62
     */
63
    private function sGlueFilterValueIntoWhereString($filterValue)
64
    {
65
        if (is_array($filterValue)) {
66
            return 'IN ("' . implode('", "', $filterValue) . '")';
67
        }
68
        return $this->sGlueFilterValueIntoWhereStringFinal($filterValue);
69
    }
70
71
    private function sGlueFilterValueIntoWhereStringFinal($filterValue)
72
    {
73
        $kFields = [
74
            'CONNECTION_ID()|CURDATE()|CURRENT_USER|CURRENT_USER()|CURRENT_DATETIME|DATABASE()|NOW()|USER()',
75
            'IS NULL|IS NOT NULL',
76
            'NOT NULL|NULL',
77
        ];
78
        if (in_array($filterValue, explode('|', $kFields[0]))) {
79
            return '= ' . $filterValue;
80
        } elseif (in_array($filterValue, explode('|', $kFields[1]))) {
81
            return $filterValue;
82
        } elseif (in_array($filterValue, explode('|', $kFields[2]))) {
83
            return 'IS ' . $filterValue;
84
        }
85
        return '= "' . $filterValue . '"';
86
    }
87
88
    /**
89
     * Internal function to concatenate filters
90
     *
91
     * @param array $filters
92
     * @return type
93
     */
94
    private function sGlueFiltersIntoWhereArrayFilter($filters)
95
    {
96
        return '(' . implode(') AND (', $filters) . ')';
97
    }
98
99
    /**
100
     * Internal function to manage the filters passed to the query
101
     *
102
     * @param array $filterArray
103
     * @param string $tableToApplyFilterTo
104
     * @return string
105
     */
106
    private function sManageDynamicFilters($filterArray = null, $tableToApplyFilterTo = '')
107
    {
108
        if (is_null($filterArray)) {
109
            return '';
110
        }
111
        $filters = [];
112
        if (is_array($filterArray)) {
113
            foreach ($filterArray as $key => $value) {
114
                $filters[] = '`' . $tableToApplyFilterTo . '`.`' . $key . '` '
115
                        . $this->sGlueFilterValueIntoWhereString($value);
116
            }
117
        }
118
        return $this->sManageDynamicFiltersFinal($filters);
119
    }
120
121
    private function sManageDynamicFiltersFinal($filters)
122
    {
123
        if (count($filters) > 0) {
124
            $sReturn = ['WHERE', $this->sGlueFiltersIntoWhereArrayFilter($filters)];
125
            return implode(' ', $sReturn) . ' ';
126
        }
127
        return '';
128
    }
129
130
    protected function sQueryMySqlColumns($filterArray = null)
131
    {
132
        return 'SELECT '
133
                . '`C`.`TABLE_SCHEMA`, '
134
                . $this->sQueryMySqlColumnsColumns() . ' '
135
                . 'FROM `information_schema`.`COLUMNS` `C` '
136
                . 'LEFT JOIN `information_schema`.`KEY_COLUMN_USAGE` `KCU` ON ((' . implode(') AND (', [
137
                    '`C`.`TABLE_SCHEMA` = `KCU`.`TABLE_SCHEMA`',
138
                    '`C`.`TABLE_NAME` = `KCU`.`TABLE_NAME`',
139
                    '`C`.`COLUMN_NAME` = `KCU`.`COLUMN_NAME`',
140
                ]) . ')) '
141
                . $this->sManageDynamicFilters($filterArray, 'C')
142
                . 'GROUP BY `C`.`TABLE_SCHEMA`, `C`.`TABLE_NAME`, `C`.`COLUMN_NAME` '
143
                . 'ORDER BY `C`.`TABLE_SCHEMA`, `C`.`TABLE_NAME`, `C`.`ORDINAL_POSITION`;';
144
    }
145
146
    private function sQueryMySqlColumnsColumns()
147
    {
148
        return '`C`.`TABLE_NAME`, `C`.`COLUMN_NAME`, `C`.`ORDINAL_POSITION` '
149
                . ', `C`.`COLUMN_DEFAULT`, `C`.`IS_NULLABLE`, `C`.`DATA_TYPE`, `C`.`CHARACTER_MAXIMUM_LENGTH` '
150
                . ', `C`.`NUMERIC_PRECISION`, `C`.`NUMERIC_SCALE`, `C`.`DATETIME_PRECISION` '
151
                . ', `C`.`CHARACTER_SET_NAME`, `C`.`COLLATION_NAME`, `C`.`COLUMN_TYPE` '
152
                . ', `C`.`COLUMN_KEY`, `C`.`COLUMN_COMMENT`, `C`.`EXTRA`';
153
    }
154
155
    /**
156
     * Query
157
     *
158
     * @param array $filterArray
159
     * @return string
160
     */
161
    protected function sQueryMySqlIndexes($filterArray = null)
162
    {
163
        return 'SELECT '
164
                . '`KCU`.`CONSTRAINT_SCHEMA`, '
165
                . $this->sQueryMySqlIndexesColumns() . ' '
166
                . 'FROM `information_schema`.`KEY_COLUMN_USAGE` `KCU` '
167
                . 'INNER JOIN `information_schema`.`COLUMNS` `C` ON ((' . implode(') AND (', [
168
                    '`C`.`TABLE_SCHEMA` = `KCU`.`TABLE_SCHEMA`',
169
                    '`C`.`TABLE_NAME` = `KCU`.`TABLE_NAME`',
170
                    '`C`.`COLUMN_NAME` = `KCU`.`COLUMN_NAME`',
171
                ]) . ')) '
172
                . 'LEFT JOIN `information_schema`.`REFERENTIAL_CONSTRAINTS` `RC` ON ((' . implode(') AND (', [
173
                    '`KCU`.`CONSTRAINT_SCHEMA` = `RC`.`CONSTRAINT_SCHEMA`',
174
                    '`KCU`.`CONSTRAINT_NAME` = `RC`.`CONSTRAINT_NAME`',
175
                ]) . ')) '
176
                . $this->sManageDynamicFilters($filterArray, 'KCU')
177
                . 'ORDER BY `KCU`.`TABLE_SCHEMA`, `KCU`.`TABLE_NAME`'
178
                . $this->xtraSoring($filterArray, 'COLUMN_NAME') . ';';
179
    }
180
181
    private function sQueryMySqlIndexesColumns()
182
    {
183
        return '`KCU`.`CONSTRAINT_NAME`, `KCU`.`TABLE_SCHEMA`, `KCU`.`TABLE_NAME`, '
184
                . '`KCU`.`COLUMN_NAME`, `C`.`ORDINAL_POSITION` AS `COLUMN_POSITION`, `KCU`.`ORDINAL_POSITION`, '
185
                . '`KCU`.`POSITION_IN_UNIQUE_CONSTRAINT`, `KCU`.`REFERENCED_TABLE_SCHEMA`, '
186
                . '`KCU`.`REFERENCED_TABLE_NAME`, `KCU`.`REFERENCED_COLUMN_NAME`, '
187
                . '`RC`.`UPDATE_RULE`, `RC`.`DELETE_RULE`';
188
    }
189
190
    private function sQueryMySqlStatisticPattern($tblName, $lnkDbCol, $adtnlCol = null, $adtnlFltr = null)
191
    {
192
        $tblAls = substr($tblName, 0, 1);
193
        return '(SELECT COUNT(*) AS `No. of records` FROM `information_schema`.`' . $tblName . '` `' . $tblAls . '` '
194
                . 'WHERE (`' . $tblAls . '`.`' . $lnkDbCol . '` = `S`.`SCHEMA_NAME`)'
195
                . (!is_null($adtnlCol) ? ' AND (`' . $tblAls . '`.`' . $adtnlCol . '` = "' . $adtnlFltr . '")' : '')
196
                . ') AS `' . ucwords(strtolower((is_null($adtnlCol) ? $tblName : $adtnlFltr))) . '`';
197
    }
198
199
    protected function sQueryMySqlStatistics($filterArray = null)
200
    {
201
        return 'SELECT '
202
                . '`S`.`SCHEMA_NAME`, '
203
                . $this->sQueryMySqlStatisticPattern('TABLES', 'TABLE_SCHEMA', 'TABLE_TYPE', 'BASE TABLE') . ', '
204
                . $this->sQueryMySqlStatisticPattern('TABLES', 'TABLE_SCHEMA', 'TABLE_TYPE', 'VIEW') . ', '
205
                . $this->sQueryMySqlStatisticPattern('COLUMNS', 'TABLE_SCHEMA') . ', '
206
                . $this->sQueryMySqlStatisticPattern('TRIGGERS', 'EVENT_OBJECT_SCHEMA') . ', '
207
                . $this->sQueryMySqlStatisticPattern('ROUTINES', 'ROUTINE_SCHEMA', 'ROUTINE_TYPE', 'Function') . ', '
208
                . $this->sQueryMySqlStatisticPattern('ROUTINES', 'ROUTINE_SCHEMA', 'ROUTINE_TYPE', 'Procedure') . ', '
209
                . $this->sQueryMySqlStatisticPattern('EVENTS', 'EVENT_SCHEMA') . ' '
210
                . 'FROM `information_schema`.`SCHEMATA` `S` '
211
                . 'WHERE (`S`.`SCHEMA_NAME` NOT IN ("information_schema", "mysql", "performance_schema", "sys")) '
212
                . str_replace('WHERE', 'AND', $this->sManageDynamicFilters($filterArray, 'S'))
213
                . 'ORDER BY `S`.`SCHEMA_NAME`;';
214
    }
215
216
    /**
217
     * Query to get list of tables
218
     *
219
     * @param type $filterArray
220
     * @return string
221
     */
222
    protected function sQueryMySqlTables($filterArray = null)
223
    {
224
        return 'SELECT '
225
                . '`T`.`TABLE_SCHEMA`, `T`.`TABLE_NAME`, `T`.`TABLE_TYPE`, `T`.`ENGINE`, `T`.`VERSION` '
226
                . ', `T`.`ROW_FORMAT`, `T`.`AUTO_INCREMENT`, `T`.`TABLE_COLLATION`, `T`.`CREATE_TIME` '
227
                . ', `T`.`CREATE_OPTIONS`, `T`.`TABLE_COMMENT` '
228
                . 'FROM `information_schema`.`TABLES` `T` '
229
                . $this->sManageDynamicFilters($filterArray, 'T')
230
                . $this->xtraSoring($filterArray, 'TABLE_SCHEMA') . ';';
231
    }
232
233
    private function xtraSoring($filterArray, $filterValueToDecide)
234
    {
235
        $defaults = [
236
            'COLUMN_NAME'  => [
237
                ', `C`.`ORDINAL_POSITION`, `KCU`.`CONSTRAINT_NAME`',
238
                '',
239
            ],
240
            'TABLE_SCHEMA' => [
241
                'ORDER BY `T`.`TABLE_SCHEMA`, `T`.`TABLE_NAME`',
242
                'ORDER BY `T`.`TABLE_NAME`',
243
            ],
244
        ];
245
        if (!is_null($filterArray) && is_array($filterArray) && array_key_exists($filterValueToDecide, $filterArray)) {
246
            return $defaults[$filterValueToDecide][1];
247
        }
248
        return $defaults[$filterValueToDecide][0];
249
    }
250
}
251