-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract_keys.php
90 lines (78 loc) · 2.44 KB
/
extract_keys.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
$handle = fopen($argv[1], "r");
$dir_path = dirname($argv[1]);
$table_name = $argv[2];
$line_number = 0;
$query_line_number = 0;
$query = array();
$query_found = false;
$keys = array();
$other = array();
$auto_increment_columns = array();
if ($handle) {
while (($line = fgets($handle)) !== false) {
if($query_found) {
if(preg_match('/^\s+KEY.*(.*)/', $line, $match)) {
if(preg_match('/^\s+KEY.*\(\`([a-zA-Z0-9_-]{1,})\`\)/', $line, $match)) {
if(in_array($match[1], $auto_increment_columns)) {
$query[$query_line_number] = $line;
$query_line_number++;
} else {
$keys[] = 'ADD ' . rtrim(trim($line), ',');
}
} else {
$keys[] = 'ADD ' . rtrim(trim($line), ',');
}
} else {
if(preg_match('/^\s+PRIMARY.*/', $line)) {
$query[$query_line_number] = $line;
} else {
if(preg_match('/^\s+\`(.*)\` .* NOT NULL AUTO_INCREMENT.*/', $line, $match)) {
if($match[1] != "id") {
$auto_increment_columns[] = $match[1];
}
}
$query[$query_line_number] = $line;
}
if(preg_match('/.*ENGINE.*/', $line)) {
$query_found = false;
$query_size = sizeof($query);
$query[$query_size - 2] = rtrim(trim($query[$query_size - 2]), ',') . PHP_EOL;
foreach($query as $query_line) {
$other[] = $query_line;
}
}
$query_line_number++;
}
} elseif(!$query_found && preg_match('/CREATE TABLE.*/', $line, $match)) {
$query[$query_line_number] = $line;
$query_line_number++;
$query_found = true;
} else {
$other[] = $line;
}
$line_number++;
}
} else {
// error opening the file.
}
fclose($handle);
$fp = fopen($dir_path . '/create/' . $table_name . '.sql', 'w');
foreach($other as $other_line) {
fwrite($fp, print_r($other_line, TRUE));
}
fclose($fp);
if(sizeof($keys) > 0) {
$fpk = fopen($dir_path . '/keys/' . $table_name . '.sql', 'w');
$query_for_keys = array();
$query_for_keys[] = "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;";
$query_for_keys[] = "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;";
$query_for_keys[] = "ALTER TABLE " . $table_name;
$query_for_keys[] = implode(',' . PHP_EOL, $keys) . ";";
$query_for_keys[] = "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;";
$query_for_keys[] = "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;";
foreach($query_for_keys as $query_for_key_line) {
fwrite($fpk, print_r($query_for_key_line . PHP_EOL , TRUE));
}
fclose($fpk);
}