/
DBI.pod
2251 lines (1632 loc) · 85.3 KB
/
DBI.pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=encoding euc-jp
=head1 名前
Class::DBI - シンプルなデータベース抽象クラス
=head1 概要
package Music::DBI;
use base 'Class::DBI';
Music::DBI->set_db('Main', 'dbi:mysql:dbname', 'username', 'password');
package Music::Artist;
use base 'Music::DBI';
Music::Artist->table('artist');
Music::Artist->columns(All => qw/artistid name/);
Music::Artist->has_many(cds => 'Music::CD');
package Music::CD;
use base 'Music::DBI';
Music::CD->table('cd');
Music::CD->columns(All => qw/cdid artist title year/);
Music::CD->has_many(tracks => 'Music::Track');
Music::CD->has_a(artist => 'Music::Artist');
Music::CD->has_a(reldate => 'Time::Piece',
inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d") },
deflate => 'ymd',
}
Music::CD->might_have(liner_notes => LinerNotes => qw/notes/);
package Music::Track;
use base 'Music::DBI';
Music::Track->table('track');
Music::Track->columns(All => qw/trackid cd position title/);
#-- Meanwhile, in a nearby piece of code! --#
my $artist = Music::Artist->create({ artistid => 1, name => 'U2' });
my $cd = $artist->add_to_cds({
cdid => 1,
title => 'October',
year => 1980,
});
# Oops, got it wrong.
$cd->year(1981);
$cd->update;
# etc.
foreach my $track ($cd->tracks) {
print $track->position, $track->title
}
$cd->delete; # also deletes the tracks
my $cd = Music::CD->retrieve(1);
my @cds = Music::CD->retrieve_all;
my @cds = Music::CD->search(year => 1980);
my @cds = Music::CD->search_like(title => 'October%');
=head1 イントロダクション
Class::DBI provides a convenient abstraction layer to a database.
Class::DBIはデータベースへの便利な抽象レイヤーを提供する。
It not only provides a simple database to object mapping layer, but can
be used to implement several higher order database functions (triggers,
referential integrity, cascading delete etc.), at the application level,
rather than at the database.
このモジュールは、オブジェクトマッピング層に簡単なデータベースを提供
するだけでなく、データベースレベルよりもアプリケーションレベルで
いくつかのより高レベルな一般的的なデータベース機能(トリガー、参照統合、
波及削除)を実装するために利用される。
This is particularly useful when using a database which doesn't support
these (such as MySQL), or when you would like your code to be portable
across multiple databases which might implement these things in different
ways.
上記の機能をサポートしていないデータベース(MySQLなど)を使う際には
殊のほか便利である。あるいは、こういったことを様々な方法で実装している
複数のデータベースに対して、あなたのコードを移植しようとしている際にも
便利である。
In short, Class::DBI aims to make it simple to introduce 'best
practice' when dealing with data stored in a relational database.
要するに、リレーショナルデータベースに保持されているデータを扱うときに
”最前のやり方”を導入しやすくするのがClass::DBIのねらいなのだ。
=head2 設定の仕方
=over 4
=item I<データベースを準備する>
You must have an existing database set up, have DBI.pm installed and
the necessary DBD:: driver module for that database. See L<DBI> and
the documentation of your particular database and driver for details.
既存のデータベースを準備しなければならない。DBI.pmとそのデータベースに
必要なDBD::ドライバーモジュールがインストールされていなければならない。
詳細については、L<DBI>及び、実際のデータベースとドライバーのドキュメントを
参照のこと。
=item I<オブジェクトが保持するテーブルを設定する>
Class::DBI works on a simple one class/one table model. It is your
responsibility to have your database tables already set up. Automating that
process is outside the scope of Class::DBI.
Class::DBIは、単純な”1クラス1テーブル”モデルで動作する。データベースを
既に準備の出来ている状態にするのはあなたの責任だ。このプロセスを自動化する
のはClass::DBIの範疇外である。
Using our CD example, you might declare a table something like this:
CDを例にとろう。次のようなテーブルを宣言するとする:
CREATE TABLE cd (
cdid INTEGER PRIMARY KEY,
artist INTEGER, # references 'artist'
title VARCHAR(255),
year CHAR(4),
);
=item I<アプリケーションベースクラスを設定する>
It's usually wise to set up a "top level" class for your entire
application to inherit from, rather than have each class inherit
directly from Class::DBI. This gives you a convenient point to
place system-wide overrides and enhancements to Class::DBI's behavior.
通常は各クラスを直接Class::DBIから継承させるよりも、”トップレベル”クラスを
つくり、アプリケーション全体はそれを継承する方が賢いやり方だ。こうすることで
システム全体でオーバーライドしたり、Class::DBIの振る舞いを向上させるといった
利点が得られる。
package Music::DBI;
use base 'Class::DBI';
=item I<データベースへ接続する>
Class::DBI needs to know how to access the database. It does this
through a DBI connection which you set up by calling the set_db()
method.
Class::DBIはデータベースにアクセスする方法を知る必要がある。これは
あなたが用意したDBI接続を通じてなされるのだが、それにはset_db()メソッドを
呼び出す。
Music::DBI->set_db('Main', 'dbi:mysql:dbname', 'user', 'password');
By setting the connection up in your application base class all the
table classes that inherit from it will share the same connection.
アプリケーションベースクラスの接続が確立すると、このクラスを継承している
全てのテーブルクラスが同じ接続を共有する。
The first parameter is the name for this database connection and
it must be 'Main' for Class::DBI to function. See L</set_db> below
and L<Ima::DBI> for more details on set_db().
最初のパラメータはこのデータベース接続のための名前であり、Class::DBIが
機能するには'Main'でなければならない。set_dbの詳細については、下記の
L</set_db>、ならびにL<Ima::DBI>を参照のこと。
=item I<各クラスを用意する>
package Music::CD;
use base 'Music::DBI';
Each class will inherit from your application base class, so you don't
need to repeat the information on how to connect to the database.
各クラスはアプリケーションベースクラスを継承する。よって、データベース
接続方法の情報を繰り返す必要はない。
=item I<テーブル名を宣言する>
Inform Class::DBI what table you are using for this class:
このクラスがどんなテーブルのために用いられるのかをClass::DBIに教える。
Music::CD->table('cd');
=item I<カラムを宣言する>
This is done using the columns() method. In the simplest form, you tell
it the name of all your columns (with the single primary key first):
これはcolumns()メソッドを使って行う。最も単純な形式は、全カラムの名前を
クラスに伝えることだ。
Music::CD->columns(All => qw/cdid artist title year/);
If the primary key of your table spans multiple columns then
declare them using a separate call to columns() like this:
テーブルの主キーが複数のカラムにまたがる場合は、次のようにして
columns()を別々に呼び出して宣言する。
Music::CD->columns(Primary => qw/pk1 pk2/);
Music::CD->columns(Others => qw/foo bar baz/);
For more information about how you can more efficiently use subsets of
your columns, L<"Lazy Population">
カラムのサブセットをより効率的に利用する方法については、L<"Lazy Population">
を参照。
=item I<実行>
That's it! You now have a class with methods to create(), retrieve(),
search() for, update() and delete() objects from your table, as well as
accessors and mutators for each of the columns in that object (row).
これでよし! テーブルから生成されるオブジェクトに対してcreate()、retrieve()、
search()、update()そしてdelete()といったメソッドを持ったクラスを手に入れた。
これはそのオブジェクトの各カラムに対するアクセサとミューテータと同じように
作用する。
=back
Let's look at all that in more detail:
それでは全てについて詳細をみてみよう:
=head1 クラスメソッド
=head2 set_db
__PACKAGE__->set_db('Main', $data_source, $user, $password, \%attr);
For details on this method, L<Ima::DBI>.
このメソッドの詳細についてはL<Ima::DBI>を参照。
The special connection named 'Main' must always be set. Connections
are inherited so it's usual to call set_db() just in your application
base class.
'Main'と名づけられた特別な接続が常にセットされなければならない。
接続は継承されるので、通常はあなたのアプリケーションベースクラスで
set_db()を呼び出す。
package Music::DBI;
use base 'Class::DBI';
Music::DBI->set_db('Main', 'dbi:foo:dbname', 'user', 'password');
package My::Other::Table;
use base 'Music::DBI';
Class::DBI helps you along a bit to set up the database connection.
set_db() provides its own default attributes depending on the driver name
in the data_source parameter. The set_db() method provides defaults for
these attributes:
Class::DBIは、データベース接続を確立するために、少しだけ手伝いをする。
set_db()は、data_sourceパラメータにあるドライバー名に基づいたデフォルトの
属性を手供する。set_db()メソッドはデフォルトで以下の属性を提供する:
FetchHashKeyName => 'NAME_lc',
ShowErrorStatement => 1,
ChopBlanks => 1,
AutoCommit => 1,
(Except for Oracle and Pg, where AutoCommit is set to 0, placing the
database in transactional mode).
(OracleとPgを除いて、AutoCommitに0を設定すると、そのデータベースは
トランザクションモードになる)
The defaults can always be overridden or extended by supplying your own
\%attr parameter. For example:
これらの既定値は\%attrパラメータを用意することで、常にオーバーライドや
拡張を行なえる。例えば:
Music::DBI->set_db('Main','dbi:foo:dbname','user','pass',{ChopBlanks=>0});
=head3 動的なデータベース接続
It is sometimes desirable to generate your database connection information
dynamically, for example, to allow multiple databases with the same
schema to not have to duplicate an entire class hierarchy.
時には、データベース接続の情報を動的に生成したい場合がある。例えば、
同じスキーマを用いる複数のデータベースが完全なクラスヒエラルキーを
重複させないようにする場合。
The preferred method for doing this is to supply your own db_Main()
method rather than calling set_db(). This method should return a valid
database handle.
これを行なうのに好ましい方法は、set_db()を呼び出すよりも、
あなた自身のdb_Main()メソッドを用意することだ。このメソッドは妥当な
データベースハンドルを返す必要がある。
Note however that this is class data, and that changing it may have
unexpected behaviour for instances of the class already in existence.
しかし注意して欲しいのだが、これはクラスデータであり、それを変更すると
既存クラスのインスタンスの振る舞いを予期せぬものにしてしまうかもしれない。
=head2 table
__PACKAGE__->table($table);
$table = Class->table;
$table = $obj->table;
An accessor to get/set the name of the database table in which this
class is stored. It -must- be set.
このクラスが保持するデータベーステーブルの名前を取得・設定する
ためのアクセサ。設定 -しなければ- ならない。
Table information is inherited by subclasses, but can be overridden.
テーブル情報はサブクラスによって継承されるが、オーバーライドは出来ない。
=head2 table_alias
package Shop::Order;
__PACKAGE__->table('orders');
__PACKAGE__->table_alias('orders');
When Class::DBI constructs SQL, it aliases your table name to a name
representing your class. However, if your class's name is an SQL reserved
word (such as 'Order') this will cause SQL errors. In such cases you
should supply your own alias for your table name (which can, of course,
be the same as the actual table name).
Class::DBIがSQLを構築するさい、モジュールはあなたのテーブル名に対して
クラスを表す名前をあてる。しかし、クラス名がSQLの予約している単語(Orderなど)
である場合、SQLエラーが発生する。このような場合に、テーブル名に対して独自の
別名を用意する必要がある(もちろん、これは実際のテーブル名と同じできる)。
This can also be passed as a second argument to 'table':
これはtableメソッドに二つ目の引数を渡すことでも可能だ:
__PACKAGE-->table('orders', 'orders');
As with table, this is inherited but can be overriden.
tableメソッド同様、継承はできるがオーバーライドはできない。
=head2 sequence / auto_increment
__PACKAGE__->sequence($sequence_name);
$sequence_name = Class->sequence;
$sequence_name = $obj->sequence;
If you are using a database which supports sequences and you want to use
a sequence to automatically supply values for the primary key of a table,
then you should declare this using the sequence() method:
もしもあなたがシーケンスをサポートしているデータベースを使っていて、かつ、
シーケンスを利用してテーブルの主キーの値を自動的に供給したいならば、
sequence()メソッドの使用を宣言するとよい:
__PACKAGE__->columns(Primary => 'id');
__PACKAGE__->sequence('class_id_seq');
Class::DBI will use the sequence to generate a primary key value when
objects are created without one.
主キーなしでオブジェクトを生成すると、Class::DBIはシーケンスを利用する。
*NOTE* This method does not work for Oracle. However, Class::DBI::Oracle
(which can be downloaded separately from CPAN) provides a suitable
replacement sequence() method.
*注意* このメソッドはOracleでは動作しない。しかし、Class::DBI::Oracle
(別途CPANからダウンロードできる)がsequence()メソッドのうまい代替手段を
提供している。
If you are using a database with AUTO_INCREMENT (e.g. MySQL) then you do
not need this, and any call to create() without a primary key specified
will fill this in automagically.
あなたの使っているデータベースがAUTO_INCREMENT機能を持っているなら
(例:MySQL)、このメソッドを使う必要はない。主キー指定せずに
create()を呼び出せば、自動的に主キーが生成される。
Sequence and auto-increment mechanisms only apply to tables that have
a single column primary key. For tables with multi-column primary keys
you need to supply the key values manually.
シーケンスと自動インクリメント機能は、主キーカラムが一つだけのテーブルに
のみ適用される。複数の主キーカラムを持つテーブルに対しては、手動でキーの
値を設定してやらねばならない。
=head1 コンストラクタとデストラクタ
The following are methods provided for convenience to create, retrieve
and delete stored objects. It's not entirely one-size fits all and you
might find it necessary to override them.
ここで取り上げるのは、オブジェクトの生成、取り出し、削除の便宜を
図るためのメソッドである。メソッド単体であらゆる事態に対応できるわけでは
ないので、必要に応じてそれらをオーバーライドすること。
=head2 create
my $obj = Class->create(\%data);
This is a constructor to create a new object and store it in the database.
新しいオブジェクトを生成し、データベース内に格納するためのコンストラクタである。
%data consists of the initial information to place in your object and
the database. The keys of %data match up with the columns of your
objects and the values are the initial settings of those fields.
%dataは、オブジェクトとデータベースに入れられる初期情報で構成される。
%dataのキーはオブジェクトのカラムに対応し、%dataの値はそれらのフィールドに
初期状態でセットされる。
my $cd = Music::CD->create({
cdid => 1,
artist => $artist,
title => 'October',
year => 1980,
});
If the table has a single primary key column and that column value
is not defined in %data, create() will assume it is to be generated.
If a sequence() has been specified for this Class, it will use that.
Otherwise, it will assume the primary key can be generated by
AUTO_INCREMENT and attempt to use that.
もしテーブルが単一の主キーカラムを持ち、そのカラム値が%dataにおいて定義
されていないならば、create()は生成されるべき値を仮定する。sequence()が
このクラス用に指定されていれば、それが利用される。そうでなければ、
AUTO_INCREMENTによって生成可能な主キーを仮定し、その利用が試みられる。
The C<before_create>($data) trigger is invoked directly after storing the
supplied values into the new object and before inserting the record into
the database. The object stored in $self is a dummy for the final object,
and will not support many of the normal operations. In particular, adding
default values for columns etc should be done by treating $data purely as
a data hash, rather than a fully fledged object (i.e. you should assign
$data->{column} = $value, rather than calling $data->column($value).
与えられた値が新しいオブジェクトに格納された直後、かつ、そのレコードを
データベースに挿入する前にC<before_create>($data)トリガが発動される。
$selfに格納されているオブジェクトは最終的なオブジェクトにとってダミー
であり、通常の操作の多くをサポートしない。殊に、既定値をカラムその他に
追加する際には、$dataを一人前のオブジェクトとして扱うのではなく、純粋に
データハッシュとして扱うことでなされるべきである(つまり、
$data->column($value)ではなくて $data->{column} = $value とする)。
For tables with multi-column primary keys you need to supply all
the key values, either in the arguments to the create() method, or
by setting the values in a C<before_create> trigger.
複数の主キーカラムを持つテーブルに対しては、全てのキー値をあなたが
提供しなければならない。これはcreate()への引数としてか、あるいは
C<before_create>トリガ内で値をセットすることによって行なう。
If the class has declared relationships with foreign classes via
has_a(), you can pass an object to create() for the value of that key.
Class::DBI will Do The Right Thing.
もしそのクラスがhas_a()を通じて外部キーを持つリレーションシップを
宣言しているなら、そのキーの値のためにオブジェクトをcreate()に渡す
ことができる。Class::DBIは適切に処理をする。
After the new record has been inserted into the database the data
for non-primary key columns is discarded from the object. If those
columns are accessed again they'll simply be fetched as needed.
This ensures that the data in the application is consistant with
what the database I<actually> stored.
新しいレコードがデータベースに挿入された後、主キーカラム以外のデータは
そのオブジェクトから破棄される。これらのカラムに再度アクセスすると
必要に応じてデータベースから取り出される。これにより、アプリケーション内の
データは、データベースがI<実際に>保持しているものと一致することが保証される。
The C<after_create> trigger is invoked after the database insert
has executed.
データベースへの挿入が実行された後、C<after_create>トリガが発動する。
=head2 find_or_create
my $cd = Music::CD->find_or_create({ artist => 'U2', title => 'Boy' });
This checks if a CD can be found to match the information passed, and
if not creates it.
これは、渡された情報にマッチしたCDがあったかどうかを判定し、もしも
存在しないならばデータを作成する。
=head2 delete
$obj->delete;
Music::CD->delete(year => 1980, title => 'Greatest %');
Deletes this object from the database and from memory. If you have set up
any relationships using has_many, this will delete the foreign elements
also, recursively (cascading delete). $obj is no longer usable after
this call.
このオブジェクトをデータベースとメモリから削除する。もしもhas_manyを
使って何らかのリレーションシップを設定しているなら、このメソッドは
外部要素も再帰的に削除する(波及削除)。このメソッドを呼び出した後は
もはや$objは使用不可能である。
If called as a class method, deletes all objects matching the search
criteria given. Each object found will be deleted in turn, so cascading
delete and other triggers will be honoured.
クラスメソッドとして呼び出すと、与えられた規準による検索にマッチした
オブジェクトを全て削除する。見つかったオブジェクトは各々、その都度
削除される。そのため、波及削除とその他のトリガは履行される。
The C<before_delete> trigger is when an object instance is about to be
deleted. It is invoked before any cascaded deletes. The C<after_delete>
trigger is invoked after the record has been deleted from the database
and just before the contents in memory are discarded.
オブジェクトインスタンスが削除され出すときが、C<before_delete>トリガの
発動するときである。このトリガは波及削除の前に発動する。C<after_delete>
トリガはレコードがデータベースから削除された後、かつ、メモリ内の
コンテンツが破棄される直前に発動される。
=head1 オブジェクトの取り出し
We provide a few simple search methods, more to show the potential of
the class than to be serious search methods.
我々はわずかだがシンプルな検索用メソッドを提供する。これは大真面目な検索
メソッドである以上に、このクラスの潜在的能力を示している。
=head2 retrieve
$obj = Class->retrieve( $id );
$obj = Class->retrieve( %key_values );
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.
キーの値を指定すると、データベースからそのキーを持ったオブジェクトを
取り出す。ひとつのカラム主キーを持ったテーブルに対しては、一つの
パラメータが使用できる。そうでなければ、キー名・キー値のペアとなる
ハッシュを指定しなければならない。
my $cd = Music::CD->retrieve(1) or die "No such cd";
=head2 retrieve_all
my @objs = Class->retrieve_all;
my $iterator = Class->retrieve_all;
Retrieves objects for all rows in the database. This is probably a
bad idea if your table is big, unless you use the iterator version.
データベースの全行からオブジェクトを取り出す。テーブルが大きな場合に
イテレータ版を使わないなら、恐らくこの方法はまずいことになるだろう。
=head2 search
@objs = Class->search(column1 => $value, column2 => $value ...);
This is a simple search for all objects where the columns specified are
equal to the values specified e.g.:
このメソッドは単純に、指定したカラムと指定した値が等しい全オブジェクトを
探し出す。例えば:
@cds = Music::CD->search(year => 1990);
@cds = Music::CD->search(title => "Greatest Hits", year => 1990);
You may also specify the sort order of the results by adding a final
hash of arguments with the key 'order_by':
引数の最後に'order_by'というキーのハッシュを加えることで、結果に対して
ソート順も指定できる。
@cds = Music::CD->search(year => 1990, { order_by=>'artist' });
=head2 search_like
@objs = Class->search_like(column1 => $like_pattern, ....);
This is a simple search for all objects where the columns specified are
like the values specified. $like_pattern is a pattern given in SQL LIKE
predicate syntax. '%' means "any one or more characters", '_' means
"any single character".
このメソッドは単純に、指定したカラムが指定した値と似ている全オブジェクトを
探し出す。$like_patternは、SQLのLIKE叙述構文で与えられたパターンである。
'%'は”一つないしはそれ以上の任意のキャラクタ”を、'_'は”任意の一キャラクタ”
を意味している。
@cds = Music::CD->search_like(title => 'October%');
@cds = Music::CD->search_like(title => 'Hits%', artist => 'Various%');
You can also use 'order_by' with these, as with search().
search()同様、これらにも'order_byが使える。'
=head1 イテレータ
my $it = Music::CD->search_like(title => 'October%');
while (my $cd = $it->next) {
print $cd->title;
}
Any of the above searches (as well as those defined by has_many) can also
be used as an iterator. Rather than creating a list of objects matching
your criteria, this will return a Class::DBI::Iterator instance, which
can return the objects required one at a time.
上記の検索メソッドは(has_manyによる定義と同様)イテレータとしても使える。
これは基準に適合したオブジェクトのリストを生成するのではなくて、
Class::DBI::Iteratorインスタンスを返す。このインスタンスは必要な
オブジェクトを一度に返すことができる。
Currently the iterator initially fetches all the matching row data into
memory, and defers only the creation of the objects from that data until
the iterator is asked for the next object. So using an iterator will
only save significant memory if your objects will inflate substantially
when used.
現在のところ、イテレータはまず最初に適合した全ての行データをメモリに
フェッチし、イテレータが次のオブジェクトを要求されるまで、そのデータから
オブジェクトを生成するのを遅延する。よって、実質的には使用の際にオブジェクトが
インフレートする場合にのみ、イテレータの利用でメモリが大幅に節約できる。
In the case of has_many relationships with a mapping method, the mapping
method is not called until each time you call 'next'. This means that
if your mapping is not a one-to-one, the results will probably not be
what you expect.
マッピングメソッドを伴うhas_manyリレーションシップの場合、あなたが'next'を
呼び出すまでマッピングメソッドは呼ばれない。このことは、マッピングが一対一で
ないなら、その結果は恐らくあなたが期待するようなものにはならないということを
意味している。
=head2 イテレータのサブクラス化
Music::CD->iterator_class('Music::CD::Iterator');
You can also subclass the default iterator class to override its
functionality. This is done via class data, and so is inherited into
your subclasses.
デフォルトのイテレータクラスのサブクラスをつくることで、その機能を
オーバーライドすることもできる。これはクラスデータを通じてなされるので
サブクラスへ継承される。
=head2 素早い取り出し
my $obj = Class->construct(\%data);
This is a B<protected> method and can only be called by subclasses of
Class::DBI. It is used to turn data from the database into objects,
and should thus only be used when writing constructors.
これはB<protected>メソッドであり、Class::DBIのサブクラスからのみ
呼び出せる。データベースのデータをオブジェクトに返すのに利用される。
それゆえ、コンストラクタを書くときにだけ使うようにするべきだ。
This is very handy for cheaply setting up lots of objects from data for
without going back to the database.
データベースへ戻りに行かずとも、データから大量のオブジェクトを手軽に
用意できる点が大変便利だ。
For example, instead of doing one SELECT to get a bunch of IDs and then
feeding those individually to retrieve() (and thus doing more SELECT
calls), you can do one SELECT to get the essential data of many objects
and feed that data to construct():
例えばSELECTでIDの束を取り出し、それらのIDを個々retrieve()に与える
(つまり多くのSELECTコールを行なうということ)代わりに、一つのSELECTで
多くのオブジェクトの実質データを取り出し、そのデータをconstruct()に与え
られる。
return map $class->construct($_), $sth->fetchall_hash;
The construct() method creates a new empty object, loads in the column
values, and then invokes the C<select> trigger.
construct()メソッドは新規の空オブジェクトを生成し、そのカラムに値を
ロードする。そしてそれからC<select>トリガを発生させる。
=head1 コピーと移動
=head2 copy
$new_obj = $obj->copy;
$new_obj = $obj->copy($new_id);
$new_obj = $obj->copy({ title => 'new_title', rating => 18 });
This creates a copy of the given $obj, removes the primary key,
sets any supplied column values and called create() to insert a new
record in the database.
このメソッドは、$objのコピーをつくり、主キーを削除し、カラムの値を
セットし、そして新たなレコードをデータベースに挿入するためにcreate()を
呼び出す。
For tables with a single column primary key, copy() can be called
with no parameters and the new object will be assigned a key
automatically. Or a single parameter can be supplied and will be
used as the new key.
主キーが一つだけのテーブルは、copy()をパラメータ無しで呼べる。
この場合新しいオブジェクトには自動的に主キーが割り当てられる。
あるいはパラメータを一つ与えると、それが新しい主キーとして使われる。
For tables with a multi-olumn primary key, copy() must be called with
parameters which supply new values for all primary key columns, unless
a C<before_create> trigger will supply them. The create() method will
fail if any primary key columns are not defined.
複数の主キーを持つテーブルでは、全ての主キー用に新しい値を提供しないといけ
ないので、C<before_create>がそれらの新しい値を提供しない限り、パラメータを
つけてcopy()を呼ばなければならない。主キーを定義しないとcreate()メソッドは
失敗する。
my $blrunner_dc = $blrunner->copy("Bladerunner: Director's Cut");
my $blrunner_unrated = $blrunner->copy({
Title => "Bladerunner: Director's Cut",
Rating => 'Unrated',
});
=head2 move
my $new_obj = Sub::Class->move($old_obj);
my $new_obj = Sub::Class->move($old_obj, $new_id);
my $new_obj = Sub::Class->move($old_obj, \%changes);
For transfering objects from one class to another. Similar to copy(), an
instance of Sub::Class is created using the data in $old_obj (Sub::Class
is a subclass of $old_obj's subclass). Like copy(), you can supply
$new_id as the primary key of $new_obj (otherwise the usual sequence or
autoincrement is used), or a hashref of multiple new values.
あるクラスから別のクラスへとオブジェクトを移動する。copy()と同じように
$old_obj内のデータを使ってSub::Classのインスタンスを生成する(Sub::Classは
$old_objのサブクラスのサブクラス)。copy()同様、$new_objの主キーとして
$new_idを与えるか(与えなければ通常のシーケンス、あるいは自動インクリメントが
用いられる)、複数の新しい値のハッシュリファレンスを与える。
=head1 トリガ
__PACKAGE__->add_trigger(trigger_point_name => \&code_to_execute);
# e.g.
__PACKAGE__->add_trigger(after_create => \&call_after_create);
It is possible to set up triggers that will be called at various
points in the life of an object. Valid trigger points are:
オブジェクトの生成消滅までの様々なポイントで呼び出すトリガを設定できる。
適切なポイントは以下とおり:
before_create (also used for deflation)
after_create
before_set_$column (also used by add_constraint)
after_set_$column (also used for inflation and by has_a)
before_update (also used for deflation and by might_have)
after_update
before_delete
after_delete
select (also used for inflation and by construct and _flesh)
You can create any number of triggers for each point, but you cannot
specify the order in which they will be run. Each will be passed the
object being dealt with (whose values you may change if required),
and return values will be ignored.
各ポイント毎に任意の数のトリガをつくれるが、それらが実行される順番を
指定することはできない。各トリガにはデフォルトでオブジェクトが渡され
(必要ならオブジェクトの値を変更する)、戻り値は無視される。
All triggers are passed the object they are being fired for.
Some triggers are also passed extra parameters as name-value pairs.
The individual triggers are documented with the methods that trigger them.
全てのトリガには、トリガを引き起こしたオブジェクトが渡される。また、
いくつかのトリガには、名前と値のペアによる追加のパラメータが渡される。
個々のトリガに関するドキュメントは、それを起こすメソッドのところで触れている。
=head1 制約
__PACKAGE__->add_constraint('name', column => \&check_sub);
# 例
__PACKAGE__->add_constraint('over18', age => \&check_age);
# シンプルな例
sub check_age {
my ($value) = @_;
return $value >= 18;
}
# クロスフィールドチェック - age < 18 ならSSNがなければならない
sub check_age {
my ($value, $self, $column_name, $changing) = @_;
return 1 if $value >= 18; # 十分な年齢だ
return 1 if $changing->{SSN}; # SSN (社会保障番号) を与えられる
return 0 if !ref($self); # これはcreateなのでSSNを持っていない
return 1 if $self->ssn; # 既にデータベース上にある
return 0; # どこにもSSNを発見できなかった
}
It is also possible to set up constraints on the values that can be set
on a column. The constraint on a column is triggered whenever an object
is created and whenever the value in that column is being changed.
カラムに設定できない値に対しても制約は設定できる。オブジェクトが生成される
ときはいつでも、そしてそのカラムの値が変更されるときはいつでも、カラムに
対する制約が発動される。
The constraint code is called with four parameters:
制約のコードは四つのパラメータを伴って呼び出される。
- The new value to be assigned
- The object it will be assigned to
(or class name when initially creating an object)
- The name of the column
(useful if many constraints share the same code)
- A hash ref of all new column values being assigned
(useful for cross-field validation)
- 代入される新しい値
- 代入されるオブジェクト(最初にオブジェクトがcreateされるときはクラス名)
- カラム名(たくさんの制約が同じコードを共有している場合に便利)
- 代入される新しいカラム値全てのハッシュリファレンス
(クロスフィールドの妥当性チェックに便利)
The constraints are applied to all the columns being set before the
object data is changed. Attempting to create or modify an object
where one or more constraint fail results in an exception and the object
remains unchanged.
制約は、そのオブジェクトデータが変更される前に、設定される全てのカラムに
対して適用される。オブジェクトの生成や変更を試み、一つ以上の制約が
失敗して例外を発生させると、そのオブジェクトは変更されないままである。
Note 1: Constraints are implemented using before_set_$column triggers.
This will only prevent you from setting these values through a
the provided create() or set() methods. It will always be possible to
bypass this if you try hard enough.
注意1:制約はbefore_set_$columnトリガを使って実装されている。このため、
あなたが提供済みのcreate()やset()メソッドを通じてそれらを設定すること
だけはできない。これについては、あなたが十分苦労をすればいつでも抜け道が
ある。
Note 2: When an object is created constraints are currently only
checked for column names included in the parameters to create().
This is probably a bug and is likely to change in future.
注意2:オブジェクトが生成されるとき、現在のところ制約はcreate()に
渡されたパラメータに含まれるカラム名だけをチェックする。これは
恐らくバグであり、将来は変更されるだろう。
=head1 データの正規化
Before an object is assigned data from the application (via create or
a set accessor) the normalize_column_values() method is called with
a reference to a hash containing the column names and the new values
which are to be assigned (after any validation and constraint checking,
as described below).
アプリケーションから(createやsetアクセサを通じて)オブジェクトに
データが割り当てられる前に、ハッシュへのリファレンスを伴って
normalize_column_values()メソッドが呼び出される。ハッシュはカラム名と
割り当てられる新しい値を含む(下記にあるように、妥当性チェックと制約
チェックの後)。
Currently Class::DBI does not offer any per-column mechanism here.
The default method is empty. You can override it in your own classes
to normalize (edit) the data in any way you need. For example the values
in the hash for certain columns could be made lowercase.
現在のところ、Class::DBIはカラム毎のチェックメカニズムを提供していない。
デフォルトのメソッドは空だ。あなた自身のクラス内で、望むやり方で
メソッドをオーバーライドすればデータの正規化(編集)が行える。例えば、
ハッシュ内のあるカラムの値を小文字にするとか。
The method is called as an instance method when the values of an existing
object are being changed, and as a class method when a new object is
being created.
既存のオブジェクトの値が変更されるとき、このメソッドはインスタンスメソッド
として呼び出される。そして新しいオブジェクトが生成されるときには、クラス
メソッドとして呼び出される。
=head1 データの妥当性チェック
Before an object is assigned data from the application (via create or
a set accessor) the validate_column_values() method is called with a
reference to a hash containing the column names and the new values which
are to be assigned.
アプリケーションから(createかsetアクセサを通じて)オブジェクトにデータが
割り当てられる前に、validate_column_values()が呼び出される。このメソッド
には、カラム名と割り当てられる新しい値を含んだハッシュへのリファレンスが
渡される。
The method is called as an instance method when the values of an existing
object are being changed, and as a class method when a new object is
being created.
既存のオブジェクトの値が変更されるとき、このメソッドはインスタンスメソッド
として呼び出される。そして新しいオブジェクトが生成されるときには、クラス
メソッドとして呼び出される。
The default method calls the before_set_$column trigger for each column
name in the hash. Each trigger is called inside an eval. Any failures
result in an exception after all have been checked. The exception data
is a reference to a hash which holds the column name and error text for
each trigger error.
デフォルトのメソッドは、ハッシュ内の各カラムに対するbefore_set_$column
トリガを呼び出す。何か失敗すると、全てチェックし終えた後に例外を発生
させる。この例外データは、各トリガのエラー毎にカラム名とエラーテキストを
含んだハッシュリファレンスである。
When using this mechanism for form data validation, for example,
this exception data can be stored in an exception object, via a
custom _croak() method, and then caught and used to redisplay the
form with error messages next to each field which failed validation.
フォームデータの妥当性チェックにこのメカニズムを使うと、例えば、例外
データをカスタマイズした_croak()を通じて例外オブジェクトに格納してから
捕捉できる。そして妥当性チェックに失敗した各フィールドの横にエラー
メッセージを出しつつ、再度フォームの表示に利用できる。
=head1 例外処理
All errors that are generated, or caught and propagated, by Class::DBI
are handled by calling the _croak() method (as an instance method
if possible, or else as a class method).
エラーが発生、あるいは捕捉されて伝搬すると、Class::DBIは
_croak()メソッドを呼び出して処理を行う(可能ならインスタンス
メソッドとして、さもなければクラスメソッドとして)。
The _croak() method is passed an error message and in some cases
some extra information as described below. The default behaviour
is simply to call Carp::croak($message).
_croak()メソッドにはエラーメッセージが渡されるが、場合によっては
下記に示したように、追加情報が渡される。デフォルトの振る舞いは
単にCarp::croak($message)を呼び出すだけである。
Applications that require custom behaviour should override the
_croak() method in their application base class (or table classes
for table-specific behaviour). For example:
独自の振る舞いを必要とするアプリケーションでは、アプリケーション
ベースクラスにおいて_croak()メソッドをオーバーライドすること
(テーブル独自の振る舞いはテーブルクラスでオーバーライドする)。
use Error;
sub _croak {
my ($self, $message, %info) = @_;
# 無視する予定の二重挿入エラー以外は
# エラーを例外オブジェクトに変換
Error->throw(-text => $message, %info)
unless $message =~ /^Can't insert .* duplicate/;
return;
}
The _croak() method is expected to trigger an exception and not
return. If it does return then it should use C<return;> so that an
undef or empty list is returned as required depending on the calling
context. You should only return other values if you are prepared to
deal with the (unsupported) consequences.
_croak()メソッドは例外を発生させることが期待されるので、returnしない。
もし本当にreturnするなら、C<return;>とすること。こうすれば呼び出された
文脈に応じてundefか空リストが返される。もしも(サポートしていない)結果