-
Notifications
You must be signed in to change notification settings - Fork 34
/
sqlite_to_mysql.php
366 lines (304 loc) · 9.66 KB
/
sqlite_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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<?php
/**
* This file has a single job - database backup.
*
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.1 Alpha 1
*/
require_once('SSI.php');
if ($user_info['is_admin'])
DumpDatabase2();
/**
* Dumps the database.
* It writes all of the database to standard output.
* It uses gzip compression if compress is set in the URL/post data.
* It may possibly time out, and mess up badly if you were relying on it. :P
* The data dumped depends on whether "struct" and "data" are passed.
* It requires an administrator and the session hash by post.
* It is called from ManageMaintenance.php.
*/
function DumpDatabase2()
{
global $db_name, $scripturl, $context, $modSettings, $crlf, $smcFunc, $db_prefix, $db_show_debug;
// Administrators only!
if (!allowedTo('admin_forum'))
fatal_lang_error('no_dump_database', 'critical');
// We don't need debug when dumping the database
$modSettings['disableQueryCheck'] = true;
$db_show_debug = false;
// You can't dump nothing!
// if (!isset($_REQUEST['struct']) && !isset($_REQUEST['data']))
$_REQUEST['data'] = true;
//$_REQUEST['struct'] = false;
// checkSession('post');
// We will need this, badly!
db_extend();
$smcFunc['db_table_sql'] = 'exp_db_table_sql';
$smcFunc['db_insert_sql'] = 'exp_db_insert_sql';
$smcFunc['db_escape_string'] = 'addslashes';
// Attempt to stop from dying...
@set_time_limit(600);
$time_limit = ini_get('max_execution_time');
$start_time = time();
// @todo ... fail on not getting the requested memory?
@set_time_limit(600);
if (@ini_get('memory_limit') < 256)
@ini_set('memory_limit', '256M');
$memory_limit = @ini_get('memory_limit');
$memory_limit = (empty($memory_limit) ? 4 : $memory_limit) * 1024 * 1024 / 4;
$current_used_memory = 0;
$db_backup = '';
$output_function = 'un_compressed';
@ob_end_clean();
// Get rid of the gzipping alreading being done.
if (!empty($modSettings['enableCompressedOutput']))
@ob_end_clean();
// If we can, clean anything already sent from the output buffer...
elseif (ob_get_length() != 0)
ob_clean();
// Tell the client to save this file, even though it's text.
header('Content-Type: ' . ($context['browser']['is_ie'] || $context['browser']['is_opera'] ? 'application/octetstream' : 'application/octet-stream'));
header('Content-Encoding: none');
// This time the extension should just be .sql.
$extension = '.sql';
// This should turn off the session URL parser.
$scripturl = '';
// Send the proper headers to let them download this file.
header('Content-Disposition: filename="' . $db_name . '-' . (empty($_REQUEST['struct']) ? 'data' : (empty($_REQUEST['data']) ? 'structure' : 'complete')) . '_' . strftime('%Y-%m-%d') . $extension . '"');
header('Cache-Control: private');
header('Connection: close');
// This makes things simpler when using it so very very often.
$crlf = "\r\n";
// SQL Dump Header.
$db_chunks =
'-- ==========================================================' . $crlf .
'--' . $crlf .
'-- Database dump of tables in `' . $db_name . '`' . $crlf .
'-- ' . timeformat(time(), false) . $crlf .
'--' . $crlf .
'-- ==========================================================' . $crlf .
$crlf;
// Get all tables in the database....
if (preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) != 0)
{
$db = strtr($match[1], array('`' => ''));
$dbp = str_replace('_', '\_', $match[2]);
}
else
{
$db = false;
$dbp = $db_prefix;
}
// Dump each table.
$tables = $smcFunc['db_list_tables'](false, $db_prefix . '%');
foreach ($tables as $tableName)
{
// Are we dumping the structures?
if (isset($_REQUEST['struct']))
{
$db_chunks .=
$crlf .
'--' . $crlf .
'-- Table structure for table `' . $tableName . '`' . $crlf .
'--' . $crlf .
$crlf .
$smcFunc['db_table_sql']($tableName) . ';' . $crlf;
}
else
// This is needed to speedup things later
$smcFunc['db_table_sql']($tableName);
// How about the data?
if (substr($tableName, -10) == 'log_errors')
continue;
$first_round = true;
$close_table = false;
// Are there any rows in this table?
while ($get_rows = $smcFunc['db_insert_sql']($tableName, $first_round))
{
if (empty($get_rows))
break;
// Time is what we need here!
if (function_exists('apache_reset_timeout'))
@apache_reset_timeout();
elseif (!empty($time_limit) && ($start_time + $time_limit - 20 > time()))
{
$start_time = time();
@set_time_limit(150);
}
if ($first_round)
{
$db_chunks .=
$crlf .
'--' . $crlf .
'-- Dumping data in `' . $tableName . '`' . $crlf .
'--' . $crlf .
$crlf;
$first_round = false;
}
$db_chunks .=
$get_rows;
$current_used_memory += $smcFunc['strlen']($db_chunks);
$db_backup .= $db_chunks;
unset($db_chunks);
$db_chunks = '';
if ($current_used_memory > $memory_limit)
{
echo $output_function($db_backup);
$current_used_memory = 0;
// This is probably redundant
unset($db_backup);
$db_backup = '';
}
$close_table = true;
}
// No rows to get - skip it.
if ($close_table)
$db_backup .=
'-- --------------------------------------------------------' . $crlf;
}
$db_backup .=
$crlf .
'-- Done' . $crlf;
echo $output_function($db_backup);
exit;
}
/**
* Dummy/helper function, it simply returns the string passed as argument
* @param $string, a string
* @return the string passed
*/
function un_compressed($string = '')
{
return $string;
}
/**
* Gets all the necessary INSERTs for the table named table_name.
* It goes in 250 row segments.
* @param string $tableName - the table to create the inserts for.
* @return string, the query to insert the data back in, or an empty
* string if the table was empty.
*/
function exp_db_insert_sql($tableName, $new_table = false)
{
global $smcFunc, $db_prefix, $detected_id;
static $start = 0, $num_rows, $fields, $limit, $last_id;
if ($new_table)
{
$limit = strstr($tableName, 'log_') !== false ? 500 : 250;
$start = 0;
$last_id = 0;
}
$data = '';
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
// This will be handy...
$crlf = "\r\n";
// This is done this way because retrieve data only with LIMIT will become slower after each query
// and for long tables (e.g. {db_prefix}messages) it could be a pain...
// Instead using WHERE speeds up thing *a lot* (especially after the first 50'000 records)
$result = $smcFunc['db_query']('', '
SELECT /*!40001 SQL_NO_CACHE */ *
FROM ' . $tableName . '' .
(!empty($last_id) && !empty($detected_id) ? '
WHERE ' . $detected_id . ' > ' . $last_id : '') . '
LIMIT ' . (empty($last_id) ? $start . ', ' : '') . $limit,
array(
'security_override' => true,
)
);
// The number of rows, just for record keeping and breaking INSERTs up.
$num_rows = $smcFunc['db_num_rows']($result);
if ($num_rows == 0)
return false;
if ($new_table)
{
$fields = array_keys($smcFunc['db_fetch_assoc']($result));
// SQLite fetches an array so we need to filter out the numberic index for the columns.
foreach ($fields as $key => $name)
if (is_numeric($name))
unset($fields[$key]);
$smcFunc['db_data_seek']($result, 0);
}
// Start it off with the basic INSERT INTO.
$data = 'INSERT INTO `' . $tableName . '`' . $crlf . "\t" . '(`' . implode('`, `', $fields) . '`)' . $crlf . 'VALUES ';
// Loop through each row.
while ($row = $smcFunc['db_fetch_assoc']($result))
{
// Get the fields in this row...
$field_list = array();
foreach ($row as $key => $item)
{
if (is_numeric($key))
continue;
// Try to figure out the type of each field. (NULL, number, or 'string'.)
if (!isset($item))
$field_list[] = 'NULL';
elseif (is_numeric($item) && (int) $item == $item)
$field_list[] = $item;
else
$field_list[] = '\'' . str_replace("\r", '', str_replace("\n", '\n', $smcFunc['db_escape_string']($item))) . '\'';
}
if (!empty($detected_id) && isset($row[$detected_id]))
$last_id = $row[$detected_id];
$data .= '(' . implode(', ', $field_list) . ')' . ',' . $crlf . "\t";
}
$smcFunc['db_free_result']($result);
$data = substr(trim($data), 0, -1) . ';' . $crlf;
$start += $limit;
return $data;
}
/**
* Dumps the schema (CREATE) for a table.
* @todo why is this needed for?
* @param string $tableName - the table
* @return string - the CREATE statement as string
*/
function exp_db_table_sql($tableName)
{
global $smcFunc, $db_prefix, $detected_id;
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
$detected_id = '';
// This will be needed...
$crlf = "\r\n";
// Start the create table...
$schema_create = '';
$index_create = '';
// Let's get the create statement directly from SQLite.
$result = $smcFunc['db_query']('', '
SELECT sql
FROM sqlite_master
WHERE type = {string:type}
AND name = {string:table_name}',
array(
'type' => 'table',
'table_name' => $tableName,
)
);
list ($schema_create) = $smcFunc['db_fetch_row']($result);
$smcFunc['db_free_result']($result);
// Now the indexes.
$result = $smcFunc['db_query']('', '
SELECT sql
FROM sqlite_master
WHERE type = {string:type}
AND tbl_name = {string:table_name}',
array(
'type' => 'index',
'table_name' => $tableName,
)
);
$indexes = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
if (trim($row['sql']) != '')
$indexes[] = $row['sql'];
$smcFunc['db_free_result']($result);
$index_create .= implode(';' . $crlf, $indexes);
$schema_create = empty($indexes) ? rtrim($schema_create) : $schema_create . ';' . $crlf . $crlf;
return $schema_create . $index_create;
}
?>