1
|
|
|
<?php |
2
|
|
|
namespace Maphper\Optimiser; |
3
|
|
|
|
4
|
|
|
class MySql { |
5
|
|
|
public function optimiseColumns($table) { |
|
|
|
|
6
|
|
|
//Buggy, disabled for now! |
7
|
|
|
return; |
8
|
|
|
|
9
|
|
|
$runAgain = false; |
|
|
|
|
10
|
|
|
$columns = $this->pdo->query('SELECT * FROM '. $this->quote($table) . ' PROCEDURE ANALYSE(1,1)')->fetchAll(\PDO::FETCH_OBJ); |
11
|
|
|
foreach ($columns as $column) { |
12
|
|
|
$parts = explode('.', $column->Field_name); |
13
|
|
|
$name = $this->quote(end($parts)); |
14
|
|
|
if ($column->Min_value === null && $column->Max_value === null) $this->pdo->query('ALTER TABLE ' . $this->quote($table) . ' DROP COLUMN ' . $name); |
15
|
|
|
else { |
16
|
|
|
$type = $column->Optimal_fieldtype; |
17
|
|
|
if ($column->Max_length < 11) { |
18
|
|
|
//Check for dates |
19
|
|
|
$count = $this->pdo->query('SELECT count(*) as `count` FROM ' . $this->quote($table) . ' WHERE STR_TO_DATE(' . $name . ',\'%Y-%m-%d %H:%i:s\') IS NULL OR STR_TO_DATE(' . $name . ',\'%Y-%m-%d %H:%i:s\') != ' . $name . ' LIMIT 1')->fetch(\PDO::FETCH_OBJ)->count; |
20
|
|
|
if ($count == 0) $type = 'DATETIME'; |
21
|
|
|
|
22
|
|
|
$count = $this->pdo->query('SELECT count(*) as `count` FROM ' . $this->quote($table) . ' WHERE STR_TO_DATE(' . $name . ',\'%Y-%m-%d\') IS NULL OR STR_TO_DATE(' . $name . ',\'%Y-%m-%d\') != ' . $name . ' LIMIT 1')->fetch(\PDO::FETCH_OBJ)->count; |
23
|
|
|
if ($count == 0) $type = 'DATE'; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
//If it's text, work out if it would be better to be something else |
27
|
|
|
if (strpos($type, 'VARCHAR') !== false || strpos($type, 'CHAR') !== false || strpos($type, 'BINARY') !== false || strpos($type, 'BLOB') !== false || strpos($type, 'TEXT') !== false) { |
28
|
|
|
//See if it's an int |
29
|
|
|
$count = $this->pdo->query('SELECT count(*) FROM ' . $table . ' WHERE concat(\'\', ' . $name . ' * 1) != ABS(' . $name . ')) LIMIT 1')->fetch(\PDO::FETCH_OBJ)->count; |
30
|
|
|
if ($count == 0) { |
31
|
|
|
$type = 'INT(11)'; |
32
|
|
|
$runAgain = true; |
33
|
|
|
} |
34
|
|
|
else { |
35
|
|
|
//See if it's decimal |
36
|
|
|
$count = $this->pdo->query('SELECT count(*) FROM ' . $table . ' WHERE concat(\'\', ' . $name . ' * 1) != ' . $name . ')')->fetch(\PDO::FETCH_OBJ)->count; |
37
|
|
|
if ($count == 0) { |
38
|
|
|
$type = 'DECIMAL(64,64)'; |
39
|
|
|
$runAgain = true; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$this->pdo->query('ALTER TABLE ' . $this->quote($table) . ' MODIFY '. $name . ' ' . $type); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
//Sometimes a second pass is needed, if a column has gone from varchar -> int(11) a better int type may be needed |
48
|
|
|
if ($runAgain) $this->optimiseColumns($table); |
49
|
|
|
} |
50
|
|
|
} |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.