SQLite 資料一覧
[ツール]SQLiteでテーブル毎にデータを抽出する
2009/7/9更新
対応バージョン: 3.5.7
SQLiteの「.dump」を使い、テーブル毎にCREATE TABLE文を含むそのテーブルの全ての構成要素を抽出する。
使用方法
-a
指定したDBに対して全テーブル抽出
-f
% unload usage: unload [-a|-f conf_file] db -a : unload all tables -f conf_file : unload specified tables
(*1) エラー処理はきちんとやっていない(指定DBが本当にDBかどうか、ディスクに空きがない場合の対応など)
(*2) 純粋にデータだけ抽出する場合と違い、CREATE TABLE文なども含まれるのでテーブル自体を再作成する必要が出てきた時など便利である。
ソース
#!/bin/sh ############################################################################### # Unload SQLite table ############################################################################### # # Init # LANG=C LC_ALL=C toolName=`basename $0` # # Get now date/time # nowDate=`date '+%Y%m%d'` nowTime=`date '+%H%M'` now="${nowDate}-${nowTime}" # # Check parameter # opt=$1 case ${opt} in "-a") existConf="OFF" db=$2 ;; "-f") existConf="ON" confFile=$2 db=$3 if [ ! -f ${confFile} ]; then echo "${confFile} : no such file" exit 1 fi ;; *) db="" ;; esac if [ -z ${db} ]; then echo "usage: ${toolName} [-a|-f conf_file] db" echo " -a : unload all tables" echo " -f conf_file : unload specified tables" exit 1 fi if [ ! -f $db ]; then echo "${db} : no such database" exit 1 fi # # Decide target tables # if [ ${existConf} = "ON" ]; then targetTables=`awk '$0 !~ /^#/ {print $1}' ${confFile}` else targetTables=`echo .tables | sqlite3 ${db}` fi # # Unload table # echo "Unload tables to \"${db}-<table>-${now}.dump\"" set $targetTables numTargets=$# cnt=1 for target in ${targetTables} do echo $cnt $numTargets $target | awk '{printf(" [%04d/%04d] %s ... ",$1,$2,$3)}' backupFile="${db}-${target}-${now}.dump" echo ".dump ${target}" | sqlite3 ${db} > ${backupFile} echo "done" cnt=`expr ${cnt} + 1` done
使用例
% sqlite3 test.db sqlite> .tables customer purpose test sqlite> .q % unload -a test.db Unload tables to "test.db-<table>-20090709-1409.dump" [0001/0003] customer ... done [0002/0003] purpose ... done [0003/0003] test ... done % ls -1 *.dump test.db-customer-20090709-1409.dump test.db-purpose-20090709-1409.dump test.db-test-20090709-1409.dump % more test.db-customer-20090709-1409.dump BEGIN TRANSACTION; CREATE TABLE customer( id integer, name text, tel text, address text); INSERT INTO "customer" VALUES(1,'foo','01-234-5789','park'); INSERT INTO "customer" VALUES(2,'bar','99-999-9999','apart'); INSERT INTO "customer" VALUES(3,'baz',NULL,NULL); COMMIT; % cat <<END > conf customer purpose END % unload -f conf test.db Unload tables to "test.db-<table>-20090709-1412.dump" [0001/0002] customer ... done [0002/0002] purpose ... done