-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres-to-mysql.php
311 lines (254 loc) · 7.93 KB
/
postgres-to-mysql.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
<?php
$create_table = true; // false to skip create table statements
$insert_into = true; // false to skip insert statements
$line_limit = null; // null for no limit
$merge_inserts = true; // true to merge two inserts into one statement (to speedup import)
$limit_insert_columns = false; // trim number of columns in insert statement (to speedup import)
$verbose_comments = false;
$verbose_set = false;
$verbose_ignored = false;
$verbose_column_definitions = false;
$verbose_insert_into_keyword = false; // false to skip INTO keyword
$verbose_insert_values_keyword = false; // false to save 1 byte per insert statement
$explicit_column_list = false;
$storage_engines = [ // storage engines to use for CREATE TABLE statements, actually unused in the code for time being
'InnoDB',
'MyISAM',
'MEMORY',
'CSV',
];
$default_table_engine = 'MEMORY';
// if no input file path is provided then exit
if (!isset($argv[1])) {
echo "Please provide input file path as first argument\n";
exit;
}
$ignore_lines_starting_with = array(
"SELECT",
"ALTER",
"COMMENT",
"CREATE TRIGGER",
"CREATE INDEX",
"CREATE UNIQUE INDEX",
"CREATE SEQUENCE",
"GRANT",
);
// create regex pattern to match lines starting with above strings
$ignore_lines_starting_with_regex = "/^(" . implode("|", $ignore_lines_starting_with) . ")/";
// read input file path from command line
$input_file = $argv[1];
$command_string = implode(" ", $argv);
echo "-- GENERATED WITH: $command_string\n\n";
// read input file line by line
// files will be very large so we can't read whole file in memory
$handle = fopen($input_file, "r");
// open output file
//$output_file = fopen("output.sql", "w");
// read file line by line till end of file
// ignore blank lines
// echo lines starting with -- as comments
// parse lines starting with SET as key = value and save to array $set
// ignore lines starting with ALTER and COMMENT
$set = array();
$state = null;
$terminator = null;
$target_table = null;
$first_line = true;
$columns_list = [];
$sql = '';
$line_count = 0;
if ($verbose_insert_into_keyword) {
$into = 'INTO ';
} else {
$into = '';
}
if ($verbose_insert_values_keyword) {
$values = 'VALUES ';
} else {
$values = 'VALUE ';
}
?>
SET NAMES utf8;
SET CHARACTER SET utf8;
<?php
// start loop
while (($line = fgets($handle)) !== false) {
if ($line_limit && $line_count++ > $line_limit) {
echo "-- LIMIT REACHED\n";
break;
}
if ($state == 'CREATE TABLE' && $terminator) {
if (str_starts_with($line, $terminator)) {
//echo "\n$terminator\n";
if ($create_table) {
echo ") ENGINE=$default_table_engine DEFAULT CHARACTER SET = utf8;\n";
echo "-- END OF TABLE DEFINITION\n\n";
}
$state = null;
$terminator = null;
continue;
}
if (!$create_table) {
continue;
}
// remove trailing comma
$line = rtrim($line, ",\n");
// remove leading and trailing spaces
$line = trim($line);
if ($verbose_column_definitions) {
echo "# COLUMN DEFINITION: $line";
}
if (str_starts_with($line, 'CONSTRAINT')) {
continue;
}
$mysql_line = strtr(strtolower($line), [
'boolean' => 'char(1)',
'character' => 'char',
'timestamp without time zone' => 'timestamp',
'timestamp with time zone' => 'timestamp',
'double precision' => 'double',
'real' => 'float',
'bytea' => 'blob',
'::bpchar' => '',
'::character varying' => '',
]);
if ($first_line) {
$first_line = false;
} else {
echo ",";
}
echo "\t$mysql_line\n";
continue;
}
if ($state == 'COPY' && $terminator) {
if (str_starts_with($line, $terminator)) {
if ($first_line === false) {
// remove "),(" from end of sql
$sql = substr($sql, 0, -3);
$sql .= ");\n";
}
echo $sql;
$state = null;
$terminator = null;
continue;
} else {
echo $sql;
}
if (!$insert_into) {
continue;
}
// convert line to array as CSV delimited by tab
$parts = explode("\t", trim($line));
// convert to MySQL insert statement
if ($first_line) {
if ($explicit_column_list) {
$sql = "INSERT $into$target_table $columns_list $values(";
} else {
$sql = "INSERT $into$target_table $values(";
}
} else {
$sql = '';
}
for ($i = 0; $i < ($limit_insert_columns ? min($limit_insert_columns, count($parts)) : count($parts)); $i++) {
$cell = $parts[$i];
if ($cell == "\\N") {
$cell = "NULL";
} elseif (preg_match('/(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)/', $cell, $matches)) {
$cell = "'" . $matches[1] . "'";
} else {
$cell = strtr($cell, [
"'" => "\\'",
"\n" => "\\n",
"\r" => "\\r",
"\t" => "\\t",
'\\' => '\\\\',
]);
$cell = "'$cell'";
}
if ($i > 0) {
$sql .= ',';
}
$sql .= $cell;
}
if ($merge_inserts === false) {
$first_line = false;
}
if ($first_line) {
$sql .= "),(";
} else {
$sql .= ");\n";
}
$first_line = !$first_line;
//echo $sql;
continue;
}
// ignore blank lines
if (trim($line) == "") {
continue;
}
// echo lines starting with -- as comments
if (str_starts_with($line, "--")) {
if ($verbose_comments) {
echo $line;
}
continue;
}
// parse lines starting with SET as key = value and save to array $set
if (substr($line, 0, 3) == "SET") {
$rest = substr(trim($line, ';'), 4);
$parts = explode("=", $rest);
$key = trim($parts[0]);
$value = trim($parts[1]);
if ($verbose_set) {
echo $key . " = " . $value . "\n";
}
continue;
}
// ignore lines starting with ALTER and COMMENT
if (
str_starts_with($line, " ")
|| preg_match($ignore_lines_starting_with_regex, $line)
) {
if ($verbose_ignored) {
echo "IGNORED: $line";
}
continue;
}
if (str_starts_with($line, 'CREATE TABLE')) {
$state = "CREATE TABLE";
$terminator = ');';
$first_line = true;
// extract target table name
$parts = explode(" ", $line);
$target_table = $parts[2];
// explode target_table by . and get last part
$parts = explode(".", $target_table);
$target_table = $parts[count($parts) - 1];
if ($create_table) {
echo "CREATE TABLE $target_table (\n";
}
continue;
}
if (str_starts_with($line, 'COPY')) {
$state = "COPY";
$terminator = '\.';
$first_line = true;
$sql = '';
// extract target table name
$parts = explode(" ", $line);
$target_table = $parts[1];
// make column list by discarding first two elements and two last elements
$columns_list = join(' ', array_slice($parts, 2, count($parts) - 4));
// explode target_table by . and get last part
$parts = explode(".", $target_table);
$target_table = $parts[count($parts) - 1];
continue;
}
// replace ` with "
$line = str_replace("`", '"', $line);
// replace ' with "
$line = str_replace("'", '"', $line);
echo "UNRECOGNIZED: $line";
}
fclose($handle);
//fclose($output_file);