MySQL からのテーブルとデータを含むエクスポート SQL ファイルがあり、それを Sqlite 3 DB にインポートしたいと考えています。
それを行う最善の方法は何ですか?
sqlite3 ツールを使用してファイルをインポートするだけでは機能しません。
このシェルスクリプトはあなたを助けます
#!/bin/sh
if [ "x$1" == "x" ]; then
echo "Usage: $0 <dumpname>"
exit
fi
cat $1 |
grep -v ' KEY "' |
grep -v ' UNIQUE KEY "' |
grep -v ' PRIMARY KEY ' |
sed '/^SET/d' |
sed 's/ unsigned / /g' |
sed 's/ auto_increment/ primary key autoincrement/g' |
sed 's/ smallint([0-9]*) / integer /g' |
sed 's/ tinyint([0-9]*) / integer /g' |
sed 's/ int([0-9]*) / integer /g' |
sed 's/ character set [^ ]* / /g' |
sed 's/ enum([^)]*) / varchar(255) /g' |
sed 's/ on update [^,]*//g' |
perl -e 'local $/;$_=<>;s/,\n\)/\n\)/gs;print "begin;\n";print;print "commit;\n"' |
perl -pe '
if (/^(INSERT.+?)\(/) {
$a=$1;
s/\\'\''/'\'\''/g;
s/\\n/\n/g;
s/\),\(/\);\n$a\(/g;
}
' > $1.sql
cat $1.sql | sqlite3 $1.db > $1.err
ERRORS=`cat $1.err | wc -l`
if [ $ERRORS == 0 ]; then
echo "Conversion completed without error. Output file: $1.db"
rm $1.sql
rm $1.err
rm tmp
else
echo "There were errors during conversion. Please review $1.err and $1.sql for details."
fi
上記のスクリプトを機能させるために、次の変更を加えました。
私のmysqldumpコマンドは次のようになりました。
$ mysqldump -u usernmae -h host --compatible = ansi --skip-opt -p database_name> dump_file
それからそれはうまくいきました...スクリプトに感謝します。
sed または awk を使用するこれらのスクリプトのいくつかを試してみましたが、おそらく MySQL データベースのインデックスと外部キー、および必要な mysqldump オプションが原因で、常にエラーが発生します。
次に、 「ベンダー固有の SQL テーブル定義を他の形式に変換する...」Perl モジュールSQL::Translator
を見つけました。
このモジュールはすべての外部キーを作成し、必要に応じて名前を変更してインデックスを修正します。
そこで、MySQL db のダンプを含め、シェル スクリプトを書き直します。スクリプト「sqlt」は構造のみを生成し、ダンプにデータがない場合は高速に動作するため、2 つのダンプがあります。SQL::Translator によってサポートされている他の変換に適応できることに注意してください。
このシェル スクリプトを投稿した後、質問が MySQL ダンプファイルを変換しようとしていることに気付いたので、モジュール SQL::Translator を使用してそれを行う Perl スクリプトを作成しました。私のテストでは、オプションなしで生成されたダンプファイルを使用しました ( mysqldump -u user --password database > dumpfile )。文字セットに問題はありませんでした。
他のテストでは、mysql トリガーに問題があったため、スクリプトを変更してスキップしました。
#!/bin/sh
#===============================================================================
# USAGE: ./mysql2sqlite.sh <MySQL_database> <user>
# DESCRIPTION: Converts MySQL databases to SQLite
# Triggers are not converted
# REQUIREMENTS: mysqldump, Perl and module SQL::Translator, SQLite
#===============================================================================
if [ "$#" = 2 ]; then
USER="$2"
else
echo "Usage: $0 <MySQL_database> <user>"
exit
fi
if [ -s $1.db ]; then
read -p "File <$1.db> exists. Overwrite? [y|n] " ANS
if [ "$ANS" = "y" ] || [ "$ANS" = "Y" ] ; then
rm $1.db
else
echo "*** Aborting..."
exit
fi
fi
# extracts the necessary structure for SQLite:
mysqldump --skip-triggers --skip-add-locks --routines --no-data --compatible=ansi \
--compact -u $USER --password $1 > /tmp/$1_$$_str.sql
# verify
if [ ! -s /tmp/$1_$$_str.sql ]; then
echo "*** There are some problem with the dump. Exiting."
exit
fi
# translates MySQL syntax structure to SQLite using the script "sqlt" of the
# perl module SQL::Translator (that corrects the foreign keys, indexes, etc.)
sqlt -f MySQL -t SQLite --show-warnings /tmp/$1_$$_str.sql \
1> /tmp/$1_$$.sqlite 2> /tmp/$1_$$_sqlt.log
# verify
if [ ! -s /tmp/$1_$$.sqlite ]; then
echo "*** There are some problem with the sql translation. Exiting."
exit
fi
# adds statements to allow to load tables with foreign keys:
echo "PRAGMA foreign_keys=OFF;" >> /tmp/$1_$$.sqlite
echo "BEGIN TRANSACTION;" >> /tmp/$1_$$.sqlite
# extracts the data (simple inserts) without locks/disable keys,
# to be read in versions of SQLite that do not support multiples inserts:
mysqldump --skip-triggers --no-create-db --no-create-info --skip-add-locks \
--skip-extended-insert --compatible=ansi --compact -u $USER \
--password $1 >> /tmp/$1_$$.sqlite
# adds statements to finish the transaction:
echo "COMMIT;" >> /tmp/$1_$$.sqlite
echo "PRAGMA foreign_keys=ON;" >> /tmp/$1_$$.sqlite
# correct single quotes in inserts
perl -pi -e ' if (/^INSERT INTO/) { s/\\'\''/'\'\''/g; } ' /tmp/$1_$$.sqlite
# load the sql file and generate the SQLite db with the same name
# of the MySQL database
sqlite3 $1.db < /tmp/$1_$$.sqlite 2> /tmp/$1_$$sqlite.errlog
# verify
ERRORS=`cat /tmp/$1_$$sqlite.errlog | wc -l`
if [ $ERRORS = 0 ]; then
echo "* Conversion complete. Verify the file < $1.db >"
rm /tmp/$1_$$*
else
echo "*** There are some problem. Verify the files < /tmp/$1_$$* >"
fi
SQLite データベース ファイルのダンプファイルを変換する Perl スクリプトを次に示します。
#!/usr/bin/perl
#===============================================================================
# USAGE: ./mysql2sqlite.pl <MySQL_dumpfile>
# DESCRIPTION: Converts MySQL dumpfile to SQLite database
# Triggers are not converted
# The dump must be done with
# > mysqldump --skip-triggers -u [user] --p [database] > dumpfile
# REQUIREMENTS: Perl and module SQL::Translator, SQLite
#===============================================================================
use strict;
use warnings;
use Carp;
use English qw( -no_match_vars );
use SQL::Translator;
use 5.012;
my $file = $ARGV[0];
my $filedb = $file;
$filedb =~ s/\.*[^.]*$/.db/;
if ( -s $filedb ) {
say "*** Ja existe o arquivo < $filedb >. Abandonando...";
exit;
}
my @stru;
my @data;
open( my $SQLFILE, "<", $file )
or croak "Can't open $file: $OS_ERROR";
while (<$SQLFILE>) {
# nao considera linhas com comentarios e lock/unlock/drop
next if ( /^--/ || /^\/\*/ || /^lock/i || /^unlock/i || /^drop/i );
# processa os inserts
if (/^(INSERT.+?)[(]/) {
my $ins = $1; # captura o nome da tabela
s/\\[']/''/g; # substitue aspas simples - \'
s/[)],[(]/);\n$ins(/g; # divide multiplos inserts
push( @data, $_ );
}
# processa a estrutura
else { push( @stru, $_ ); }
}
close($SQLFILE);
my $strusql = join( '', @stru );
my $datasql = join( '', @data );
#open( my $STRU, ">", "stru.sql" ); # to verify the results
#open( my $DATA, ">", "data.sql" );
#print $STRU $strusql;
#print $DATA $datasql;
# here the conversion
my $translator = SQL::Translator->new(
no_comments => 0,
show_warnings => 0,
quote_table_names => 1,
quote_field_names => 1,
validate => 1,
);
my $struout = $translator->translate(
from => 'MySQL',
to => 'SQLite',
data => \$strusql,
# filename => $file,
) or croak "Error: " . $translator->error;
# define inicio e final da transacao de inserts
my $prgini = "PRAGMA foreign_keys=OFF;\n";
my $traini = "BEGIN TRANSACTION;\n";
my $trafin = "COMMIT;\n";
my $prgfin = "PRAGMA foreign_keys=ON;\n";
#gera o arquivo final sqlite
my $sqlout = join( "\n", $struout, $prgini, $traini, $datasql, $trafin, $prgfin);
open( my $FINAL, ">", "/tmp/final.sql" );
print $FINAL $sqlout;
# Monta o SQLite database
my $log = "/tmp/sqlite.errlog";
my $command = "sqlite3 $filedb < /tmp/final.sql 2> $log";
system($command) == 0 or die "system $command failed: $?";
if ( -s $log ) {
say "*** Houve algum problema. Verifique o arquivo < /tmp/sqlite.errlog > ";
}
else {
say "*** Conversao completa. Verifique o arquivo < $filedb > ";
}
mysql db が ISO-8859-1 (Latin-1) であるという問題がありました。sqlite3 への変換で、データが UTF-8 であると想定されたのはいつで、デコード エラーが発生しました。
これで簡単に修正できました:
iconv -f ISO-8859-1 -t UTF-8 mysql_dump_file > mysql_dump_file_utf8
これが誰かを助ける場合。
BLOBを含むデータベースを変換するために、mysqldumpコマンドに--hex-blobを追加し、パイプライン化されたsedのリストに以下を追加しました。-
sed -e "s/,0x\([0-9A-Z]*\),/,X'\L\1',/g" |
これは、mysqlの16進ダンプ文字列(例:0x010A…)を置き換えます。sqliteでインポートするためのX'010a…'を使用します。
sqlite3 データベースを ruby で使用する場合は、次のように変更する必要があります。
tinyint([0-9]*)
に:
sed 's/ tinyint(1*) / boolean/g ' |
sed 's/ tinyint([0|2-9]*) / integer /g' |
残念ながら、ブール値とマークされたフィールドに 1 と 0 を挿入していても、sqlite3 はそれらを 1 と 0 として保存するため、これは半分しか機能しません。
Table.find(:all, :conditions => {:column => 1 }).each { |t| t.column = true }.each(&:save)
Table.find(:all, :conditions => {:column => 0 }).each { |t| t.column = false}.each(&:save)
しかし、すべてのブール値を見つけるために見る SQL ファイルがあると役に立ちました。
これは、ssql を .db に変換するための、最もよく書かれ、十分に文書化されたシェル スクリプトです。
https://gist.github.com/esperlu/943776
または、このツールを使用することをお勧めします。驚くほど高速な ESF Database Migration Toolkitです。
ここですべてのスクリプトを試した後、esf ツールを使用するまで機能しませんでした。
ノート :
Trial version add a 'T' to the begingn of each text value you have But the pro version worked like a charm :)
Centos 5.3 64 ビットで正常に動作します。出力ファイルをロードしたら、次のようにします。
shell> sqlite3 file_name.db SQLite バージョン 3.3.6 手順については「.help」と入力してください sqlite> .databases seq name file
0 main /current_directory/file_name.db
sqlite> select * from table; . . . . . 結果... sqlite>.quit