• 追加された行はこの色です。
  • 削除された行はこの色です。
* DBIx::Class 基本 [#k203f830]
** テーブル構成 [#vad6e51f]
テーブル t1
- id int (PK)
- num int
* 構成例 [#k203f830]

** データベーススキーマ [#vad6e51f]
-テーブル t1
-- num int (PK)
-テーブル t2
-- num int (PK)
-- str text

*** シェルから実行 [#k958e5e4]
 cat > test.sql
 create table t1 ( num int primary key );
 create table t2 ( num int primary key, str text );
 insert into t1 values ( 1 );
 insert into t1 values ( 100 );
 insert into t1 values ( 20 );
 insert into t2 values ( 10, 'abc' );
 insert into t2 values ( 1, 'xyz' );
 (CTRL+D)
 
 sqlite3 test.db < test.sql

** ファイル構成 [#va03ff47]
 main.pl
 lib/
 |-- DB
 |   `-- T1.pm
 `-- DB.pm
 |-- lib
 |   |-- DB
 |   |   |-- T1.pm
 |   |   `-- T2.pm
 |   `-- DB.pm
 |-- main.pl
 `-- test.db

- DB.pm スキーマクラス
- T1.pm テーブルクラス
- T2.pm テーブルクラス

** ファイル詳細 [#e63ee31a]
*** main.pl [#ff6fd8d6]
 #!/usr/bin/perl
 #!/usr/local/bin/perl
 
 use strict;
 use warnings;
 use lib 'lib';
 use DB;
 use Data::Dumper;
 
 my $schema = DB->connect('dbi:SQLite:dbname=test.db', '', '');
 my $rs = $schema->resultset('T1');
 my $rs = $schema->resultset('T2');
 my @rows = $rs->all;
 foreach my $r (@rows) {
    print $r->id,": ",$r->num,"\n";
    print $r->num," : ",$r->str,"\n";
 }

*** lib/DB.pm [#b34898d5]
 package DB;
 
 use strict;
 use warnings;
 use base qw/DBIx::Class::Schema/;
 
 __PACKAGE__->load_classes(qw/T1/);
 __PACKAGE__->load_classes(qw/T1 T2/);
 
 1;

*** lib/DB/T1.pm [#h5c5b30c]
 package DB::T1;
 
 use strict;
 use warnings;
 use base qw/DBIx::Class/;
 
 __PACKAGE__->load_components(qw/PK::Auto Core/);
 __PACKAGE__->table('t1');
 __PACKAGE__->add_columns(qw/ id num /);
 __PACKAGE__->set_primary_key('id');
 __PACKAGE__->add_columns(qw/ num /);
 __PACKAGE__->set_primary_key('num');
 
 1;

*** lib/DB/T2.pm [#x97ca8e4]
 package DB::T2;
 
 use strict;
 use warnings;
 use base qw/DBIx::Class/;
 
 __PACKAGE__->load_components(qw/PK::Auto Core/);
 __PACKAGE__->table('t2');
 __PACKAGE__->add_columns(qw/ num str /);
 __PACKAGE__->set_primary_key('num');
 
 1;
*** 注意 [#p70892a0]
スキーマクラスで、load_classes()ではなく、load_namespaces()を使う場合、DBディレクトリ内にResultディレクトリを作成し、その中にT1.pmとT2.pmを置く。現在はResultディレクトリを使う構成の方が推奨されているようだ。

詳しくは、http://search.cpan.org/perldoc?DBIx::Class::Schema 。


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS