· 9 years ago · Nov 25, 2016, 02:50 PM
1#!/usr/bin/php
2<?php
3
4if (empty($argv['1']) || empty($argv['2']) ) {
5 echo "use: <dump file sqlite3> <dump file mysql>\n";
6 exit(0);
7}
8
9$sqlite3_dump = file_get_contents($argv['1']);
10$mysql_dump = $argv['2'];
11$data_out = ''; $fix_datetime = []; $fix_int = []; $fix_real = [];
12$patterns = array("/PRAGMA.*|BEGIN TRANSACTION.*|COMMIT;|.*sqlite_sequence.*;/", "/\"/", "/'t'/", "/'f'/", "/CREATE TABLE (`\w+`)/", "/datetime/", "/`amaflags` int\(.*\)/", "/TEXT NOT NULL default ''/", "/real NOT NULL default -1.0/");
13$replacements = array("", "`", "1", "0", "DROP TABLE IF EXISTS $1;\nCREATE TABLE $1", "datetime DEFAULT NULL", "`amaflags` varchar(32)", "text", "double NOT NULL DEFAULT '-1'");
14
15preg_match_all("/`.*` varchar.*|`.*` int.*|`.*` datetime.*|`.*` real.*|`.*` text.*/i", $sqlite3_dump, $tables_value);
16
17foreach ($tables_value['0'] as $key => $value) {
18 if (preg_match('/int/i',$value)) {
19 array_push($fix_int, $key);
20 }
21 if (preg_match('/real/i',$value)) {
22 array_push($fix_real, $key);
23 }
24 if (preg_match('/datetime/i',$value)) {
25 array_push($fix_datetime, $key);
26 }
27}
28
29$sqlite3_array = explode("\n", $sqlite3_dump);
30
31foreach ($sqlite3_array as $line) {
32 if (preg_match('/insert into/i',$line)) {
33 $line = preg_replace ("/\"/", "`", $line);
34 $line_array = explode(",", $line);
35 foreach ($line_array as $key => $value) {
36 if (in_array($key, $fix_datetime) && preg_match('/\'\'/',$value)) {
37 $line_array[$key] = "NULL";
38 }
39 if (in_array($key, $fix_int) && preg_match('/\'\'/',$value)) {
40 $line_array[$key] = "0";
41 }
42 if (in_array($key, $fix_real) && preg_match('/\'\'/',$value)) {
43 $line_array[$key] = "-1";
44 }
45 }
46 $line = implode(",", $line_array);
47 }else{
48 $line = preg_replace ($patterns, $replacements, $line);
49 }
50 $data_out .= $line."\n";
51}
52
53file_put_contents($mysql_dump, $data_out);