Completed
Push — master ( c45ea4...665550 )
by Daniel
02:25
created

MySQLiByDanielGPstructures::getMySQLStatistics()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
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
 * Usefull functions to get quick MySQL content
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiByDanielGPstructures
37
{
38
39
    use MySQLiByDanielGP;
40
41
    /**
42
     * Ensures table has special quoes and DOT as final char
43
     * (if not empty, of course)
44
     *
45
     * @param string $referenceTable
46
     * @return string
47
     */
48
    private function correctTableWithQuotesAsFieldPrefix($referenceTable)
49
    {
50
        if ($referenceTable != '') {
51
            return '`' . str_replace('`', '', $referenceTable) . '`.';
52
        }
53
        return '';
54
    }
55
56
    /**
57
     * Return the list of Tables from the MySQL server
58
     *
59
     * @return string
60
     */
61
    protected function getMySQLStatistics($filterArray = null)
62
    {
63
        return $this->getMySQLlistMultiple('Statistics', 'full_array_key_numbered', $filterArray);
64
    }
65
66
    /**
67
     * returns a list of MySQL databases
68
     *
69
     * @return array
70
     */
71
    protected function getMySQLactiveDatabases()
72
    {
73
        return $this->getMySQLlistDatabases(true);
74
    }
75
76
    /**
77
     * returns a list of active MySQL engines
78
     *
79
     * @return array
80
     */
81
    protected function getMySQLactiveEngines()
82
    {
83
        return $this->getMySQLlistEngines(true);
84
    }
85
86
    /**
87
     * returns the list of all MySQL generic informations
88
     *
89
     * @return array
90
     */
91
    protected function getMySQLgenericInformations()
92
    {
93
        if (is_null($this->mySQLconnection)) {
94
            return [];
95
        }
96
        return ['Info' => $this->mySQLconnection->server_info, 'Version' => $this->mySQLconnection->server_version];
97
    }
98
99
    /**
100
     * returns the list of all MySQL global variables
101
     *
102
     * @return array
103
     */
104
    protected function getMySQLglobalVariables()
105
    {
106
        return $this->getMySQLlistMultiple('VariablesGlobal', 'array_key_value');
107
    }
108
109
    /**
110
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
111
     *
112
     * @return array
113
     */
114
    protected function getMySQLlistColumns($filterArray = null)
115
    {
116
        return $this->getMySQLlistMultiple('Columns', 'full_array_key_numbered', $filterArray);
117
    }
118
119
    /**
120
     * returns a list of MySQL databases (w. choice of exclude/include the system ones)
121
     *
122
     * @return array
123
     */
124
    protected function getMySQLlistDatabases($excludeSystemDbs = true)
125
    {
126
        return $this->getMySQLlistMultiple('Databases', 'array_first_key_rest_values', $excludeSystemDbs);
127
    }
128
129
    /**
130
     * returns a list of MySQL engines (w. choice of return only the active ones)
131
     *
132
     * @return array
133
     */
134
    protected function getMySQLlistEngines($onlyActiveOnes = true)
135
    {
136
        return $this->getMySQLlistMultiple('Engines', 'array_first_key_rest_values', $onlyActiveOnes);
137
    }
138
139
    /**
140
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
141
     *
142
     * @return array
143
     */
144
    protected function getMySQLlistIndexes($filterArray = null)
145
    {
146
        return $this->getMySQLlistMultiple('Indexes', 'full_array_key_numbered', $filterArray);
147
    }
148
149
    /**
150
     * Return the list of Tables from the MySQL server
151
     *
152
     * @return string
153
     */
154
    protected function getMySQLlistTables($filterArray = null)
155
    {
156
        return $this->getMySQLlistMultiple('Tables', 'full_array_key_numbered', $filterArray);
157
    }
158
159
    /**
160
     * Return the time from the MySQL server
161
     *
162
     * @return string
163
     */
164
    protected function getMySQLserverTime()
165
    {
166
        return $this->getMySQLlistMultiple('ServerTime', 'value');
167
    }
168
169
    /**
170
     * Reads data from table into REQUEST super global
171
     *
172
     * @param string $tableName
173
     * @param array $filtersArray
174
     */
175
    protected function getRowDataFromTable($tableName, $filtersArray)
176
    {
177
        $query   = $this->sQueryRowsFromTable([$tableName, $this->setArrayToFilterValues($filtersArray)]);
178
        $rawData = $this->setMySQLquery2Server($query, 'array_pairs_key_value')['result'];
179
        if (!is_null($rawData)) {
180
            $this->initializeSprGlbAndSession();
181
            foreach ($rawData as $key => $value) {
182
                $vToSet = str_replace(['\\\\"', '\\"', "\\\\'", "\\'"], ['"', '"', "'", "'"], $value);
183
                $this->tCmnRequest->request->set($key, $vToSet);
184
            }
185
        }
186
    }
187
188
    /**
189
     * Builds an filter string from pair of key and value, where value is array
190
     *
191
     * @param string $key
192
     * @param array $value
193
     * @param string $referenceTable
194
     * @return string
195
     */
196
    private function setArrayLineArrayToFilter($key, $value, $referenceTable)
197
    {
198
        $filters2 = implode(', ', array_diff($value, ['']));
199
        if ($filters2 != '') {
200
            return '(' . $referenceTable . '`' . $key . '` IN ("'
201
                    . str_replace(',', '","', str_replace(["'", '"'], '', $filters2)) . '"))';
202
        }
203
        return '';
204
    }
205
206
    /**
207
     * Builds an filter string from pair of key and value, none array
208
     *
209
     * @param string $key
210
     * @param int|float|string $value
211
     * @return string
212
     */
213
    private function setArrayLineToFilter($key, $value)
214
    {
215
        $fTemp = '=';
216
        if ((substr($value, 0, 1) == '%') && (substr($value, -1) == '%')) {
217
            $fTemp = 'LIKE';
218
        }
219
        return '(`' . $key . '` ' . $fTemp . '"' . $value . '")';
220
    }
221
222
    /**
223
     * Transforms an array into usable filters
224
     *
225
     * @param array $entryArray
226
     * @param string $referenceTable
227
     * @return array
228
     */
229
    private function setArrayToFilterValues($entryArray, $referenceTable = '')
230
    {
231
        $filters  = [];
232
        $refTable = $this->correctTableWithQuotesAsFieldPrefix($referenceTable);
233
        foreach ($entryArray as $key => $value) {
234
            if (is_array($value)) {
235
                $filters[] = $this->setArrayLineArrayToFilter($key, $value, $refTable);
236
            } elseif (!in_array($value, ['', '%%'])) {
237
                $filters[] = $this->setArrayLineToFilter($key, $value);
238
            }
239
        }
240
        return implode(' AND ', array_diff($filters, ['']));
241
    }
242
243
    /**
244
     * Returns maximum length for a given MySQL field
245
     *
246
     * @param array $fieldDetails
247
     * @param boolean $outputFormated
248
     * @return array
249
     */
250
    protected function setFieldNumbers($fieldDetails, $outputFormated = false)
251
    {
252
        $sRtrn = $this->setFieldSpecific($fieldDetails);
253
        if ($outputFormated) {
254
            if (is_array($sRtrn)) {
255
                foreach ($sRtrn as $key => $value) {
256
                    $sRtrn[$key] = $this->setNumberFormat($value);
257
                }
258
            }
259
        }
260
        return $sRtrn;
261
    }
262
263
    /**
264
     * Establishes numbers of fields
265
     *
266
     * @param array $fieldDetails
267
     * @return array
268
     */
269
    private function setFieldSpecific($fieldDetails)
270
    {
271
        if (in_array($fieldDetails['DATA_TYPE'], ['char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext'])) {
272
            return ['M' => $fieldDetails['CHARACTER_MAXIMUM_LENGTH']];
273
        } elseif (in_array($fieldDetails['DATA_TYPE'], ['decimal', 'numeric'])) {
274
            return ['M' => $fieldDetails['NUMERIC_PRECISION'], 'd' => $fieldDetails['NUMERIC_SCALE']];
275
        } elseif (in_array($fieldDetails['DATA_TYPE'], ['bigint', 'int', 'mediumint', 'smallint', 'tinyint'])) {
276
            return $this->setFldLmtsExact($fieldDetails['DATA_TYPE']);
277
        }
278
        return $this->setFieldSpecificElse($fieldDetails);
279
    }
280
281
    private function setFieldSpecificElse($fieldDetails)
282
    {
283
        $map = ['date' => 10, 'datetime' => 19, 'enum' => 65536, 'set' => 64, 'time' => 8, 'timestamp' => 19];
284
        if (array_key_exists($fieldDetails['DATA_TYPE'], $map)) {
285
            return ['M' => $map[$fieldDetails['DATA_TYPE']]];
286
        }
287
        return ['M' => '???'];
288
    }
289
290
    private function setFldLmtsExact($cTp)
291
    {
292
        $xct     = [
293
            'bigint'    => ['l' => -9223372036854775808, 'L' => 9223372036854775807, 's' => 21, 'sUS' => 20],
294
            'int'       => ['l' => -2147483648, 'L' => 2147483647, 's' => 11, 'sUS' => 10],
295
            'mediumint' => ['l' => -8388608, 'L' => 8388607, 's' => 9, 'sUS' => 8],
296
            'smallint'  => ['l' => -32768, 'L' => 32767, 's' => 6, 'sUS' => 5],
297
            'tinyint'   => ['l' => -128, 'L' => 127, 's' => 4, 'sUS' => 3],
298
        ];
299
        $aReturn = null;
300
        if (array_key_exists($cTp, $xct)) {
301
            $aReturn = ['m' => $xct[$cTp]['l'], 'M' => $xct[$cTp]['L'], 'l' => $xct[$cTp]['s']];
302
            if (strpos($cTp, 'unsigned') !== false) {
303
                $aReturn = ['m' => 0, 'M' => ($xct[$cTp]['L'] - $xct[$cTp]['l']), 'l' => $xct[$cTp]['sUS']];
304
            }
305
        }
306
        return $aReturn;
307
    }
308
}
309