Class::DBI

O/Rマッパーといえば、DBIx::Classがファーストチョイスなのかもしれないが、そもそもperlでO/Rマッパーを使ったことがないので、古きを知るという意味でClass::DBIにトライ。MySQLが手元に入ってなかったので、そこから。データはMySQLのworldデータベースを使う。

MySQLセットアップ

sudo yum -y install mysql-server
mysql -uroot
grant all on *.* to mysql@localhost;
create database world
wget http://downloads.mysql.com/docs/world.sql.gz
gunzip world.sql.gz
cat world.sql | mysql -umysql world
Class::DBIセットアップ
cpanm Class::DBI
mkdir pm script

pmにモジュールを入れ、scriptからuse lib '/home/kotaro/pm';する。

実装

Class::DBIを継承し、オブジェクトとテーブルのマッピングをする。

package City;
use strict;
use base qw(Class::DBI);

__PACKAGE__->connection('dbi:mysql:world', 'mysql', undef,
                        +{ RaiseError => 1, AutoCommit => 0 });

__PACKAGE__->table('City');
__PACKAGE__->columns(Primary => qw(ID));
__PACKAGE__->columns(All     => qw(Name CountryCode));

1;
primary keyでのselect

retrieveを使う

Given key values it will retrieve the object with that key from the database. For tables with a single column primary key a single parameter can be used, otherwise a hash of key-name key-value pairs must be given.

単一のプライマリーキーだったらscalar、そうでなければkey-valueでhashで指定してね、と。

#!/usr/bin/perl
use strict;

use lib '/home/kotaro/pm';
use City;

my $city = City->retrieve(1); # ID=1の行を取得
print join(qq{\t}, $city->Name, $city->CountryCode, $city->District, $city->Population), "\n";

Kabul AFG Kabol 1780000

primary使わない、select

searchを使う。

@cities = City->search(Name=>'Tokyo');
for my $city (@cities) {
        print join(qq{\t}, $city->Name, $city->CountryCode, $city->District, $city->Population), "\n";
}

Tokyo JPN Tokyo-to 7980230

insert

insertメソッドか、find_or_createメソッドを使う

$city = City->find_or_create(+{
        Name     => 'Hoge', CountryCode =>'XXX',
        District => 'none', Population  => 1000,
});
$city->dbi_commit();

@cities = City->search(Name=>'Hoge');
for my $city (@cities) {
        print join(qq{\t}, $city->Name, $city->CountryCode, $city->District, $city->Population), "\n";
}

Hoge XXX none 1000

まとめ

ざっとしか触ってないけども、OOPスタイルならO/Rマッパー使っておいたほうがよさそう。
ハイパフォーマンスが要求される環境で使えるかは、現時点で知ってることじゃ判断できないけどノウハウは探せばありそう。