Perl - CPAN - DBD::CSVパッケージ

ここに掲載するものは、塚本さんにパッケージ化して頂いているZaurus用Perl 5.6.1に追加でインストールするPerlライブラリのDBD::CSVである。
ソースはここからダウンロードし、dev-img-1.3でセルフコンパイルした。

download:lib-perl-dbd-csv_0.22-1_arm.ipk

このパッケージとDBIパッケージText::CSV_XSSQL::StatementZaurusにインストールすれば、DBIを経由してCSVファイルをデータベースのように扱うことが可能になる。
手始めの使い方は以下の通りである。

# "ID<TAB>名前<TAB>年齢"のテキストをデータベースに登録
use DBI;
$dir = ".";
$dbh = DBI->connect("dbi:CSV:f_dir=$dir");
$tbl_name = "test.csv";
$create_tbl =<<__CREATE_TBL__;
    create table $tbl_name (
        id int,
        name varchar(40),
        age int
    )
__CREATE_TBL__
@tables = $dbh->tables;
$exist = 0;
foreach $name (@tables) {
    if ($name =~ /\.$tbl_name$/) {
        $exist = 1;
        last;
    }
}
if (!$exist) {
    $dbh->do($create_tbl) or die;
}
while (<>) {
    chomp;
    ($id, $name, $age) = split(/\t/);
    $id = int($id);
    $name = substr($name, 0, 40);
    $age = int($age);
    $insert = "insert into $tbl_name values ('$id', '$name', '$age')";
    $dbh->do($insert) or die;
}
END {
    $dbh->disconnect if $dbh;
}

SQL文の最後に「;」があると何故かエラーが発生したり、整数にマイナスの値を渡すとエラーが発生したりと、実際のデータベースとは異なる部分がある。
考えてみれば、CSVファイルに値の種類など存在しないのだから、全てが文字列だと捉えて置くべきだろう。
CSVファイル相手にpsqlコマンドは存在しないので、以下に簡易的なものを用意して置く。

# DBD::CSV用のpsqlもどき
use DBI;
$dir = ".";
$dbh = DBI->connect("dbi:CSV:f_dir=$dir");
$line = "";
for ( ; ; ) {
    print "\$ ";
    if (!defined($s = <STDIN>)) {
        print "\n";
        last;
    }
    chomp($s);
    $line .= $s;
    while ($line =~ /;/o) {
        $sql = $`;
        $line = $';
        $sth = $dbh->prepare($sql) or next;
        if ($sth->execute()) {
            if ($sql =~ /\s*select\s/io) {
                $i = 0;
                foreach $s (@{$sth->{NAME}}) {
                    $i += length($s);
                    $j = 8 - $i % 8;
                    print $s . " " x $j;
                    $i += $j;
                }
                print "\n";
                print "-" x $i . "\n";
                while (@items = $sth->fetchrow) {
                    print join("\t", @items) . "\n";
                }
            }
        }
        $sth->finish;
    }
}
END {
    $dbh->disconnect if $dbh;
}


DBD::CSVの詳細は以下をご覧頂きたい。

英語:http://search.cpan.org/~jzucker/DBD-CSV-0.22/lib/DBD/CSV.pm