=encoding utf-8
=pod
=head1 NAME
POD2::JA::KiokuDB::Tutorial - L<KiokuDB>を始めよう
=begin original
KiokuDB::Tutorial - Getting started with L<KiokuDB>
=end original
=head1 Install
(インストール)
=begin original
The easiest way to install L<KiokuDB> along with a number of backends is
L<Task::KiokuDB>.
=end original
L<KiokuDB>とバックエンドと一緒にインストールするには、L<Task::KiokuDB>をインストールするのが一番簡単です。
=begin original
L<KiokuDB> depends on L<Moose> and a few other modules out of the box, but no
specific storage module.
=end original
L<KiokuDB>はL<Moose>と、いくつかのすぐに使えるモジュールに依存していますが、
特定のストレージモジュールには依存していません。
=begin original
L<KiokuDB> is a frontend to several backends, much like L<DBI> uses DBDs to
connect to actual databases.
=end original
L<KiokuDB>は複数のバックエンドのフロントエンドです。
L<DBI>が実際のデータベースへの接続にDBDを使っているのに似ています。
=begin original
For development and testing you can use the L<KiokuDB::Backend::Hash> backend,
which is an in memory store, but for production use L<KiokuDB::Backend::DBI> or
L<KiokuDB::Backend::BDB> are the recommended backends.
=end original
開発用やテストとして、メモリに保存するL<KiokuDB::Backend::Hash>バックエンドを使うことができます。
プロダクションには、L<KiokuDB::Backend::DBD>かL<KiokuDB::Backend::DBI>かL<KiokuDB::Backend::BDB>
をバックエンドとして推奨します。
=begin original
See below for instructions on getting L<KiokuDB::Backend::BDB> installed.
=end original
L<KiokuDB::Backend::DBD>をインストールして、以下のインストラクションを見てください。
=head1 CREATING A DIRECTORY HANDLE
(ディレクトリハンドルの作成)
=begin original
A KiokuDB directory is the main object through which all work is done.
=end original
KiokuDBディレクトリは、すべての仕事がされるメインのオブジェクトです。
=begin original
The simplest directory that is ready for use can be created like this:
=end original
すぐに使えるもっとも単純なディレクトリは次のように作れます:
my $dir = KiokuDB->new(
backend => KiokuDB::Backend::Hash->new
);
=begin original
We will revisit other more interesting backend configuration later in this
document, but for now this will do.
=end original
このドキュメントの最後に、他のもっと面白いバックエンドの設定を紹介しますが、
とりあえず、やってみます。
=begin original
You can also use DSN strings to connect to the various backends:
=end original
いろいろなバックエンドに接続するためのDSN文字列を使うこともできます。
KiokuDB->connect("hash");
KiokuDB->connect("dbi:SQLite:dbname=foo", create => 1);
KiokuDB->connect("bdb:dir=foo", create => 1);
=begin original
You can also use a configuration file:
=end original
設定ファイルを使うこともできます。
KiokuDB->connect("/path/to/my_db.yml");
=begin original
Which is just a YAML file:
=end original
設定YAMLファイルです:
---
# these are basically the arguments for 'new'
backend:
class: KiokuDB::Backend::DBI
dsn: dbi:SQLite:dbname=/tmp/test.db
create: 1
=head1 USING THE DBI BACKEND
(DBIバックエンドを使う)
=begin original
During this tutorial we will be using the DBI backend for two reasons. The
first is L<DBI>'s ubiquity. The second is the possibility of easily looking
behind the scenes, to more clearly demonstrate what L<KiokuDB> is doing.
=end original
2つの理由で、このチュートリアルではDBIバックエンドを使います。
1つ目の理由は、L<DBI>がどこにでもあるからです。
2つ目の理由は、簡単に裏舞台を見ることが出来るからです。
L<KiokuDB>が何をしているかをよりわかりやすくデモンストレーションできるからです。
=begin original
That said, the examples will work with all backends exactly the same.
=end original
この例ですべてのバックエンドがまったく同じように動きます。
=begin original
The C<$dir> variable used below is created like this:
=end original
以下で使うC<$dir>変数は下記のように作られます:
my $dir = KiokuDB->connect(
"dbi:SQLite:dbname=kiokudb_tutorial.db",
create => 1, # this causes the tables to be created
);
=begin original
Note that if you are connecting with a username and password you need to
specify these as named arguments:
=end original
ユーザー名とパスワードで接続する場合、名前付きの引数を指定しないといけません:
my $dir = KiokuDB->connect(
$dsn,
user => $user,
password => $password,
);
=head1 INSERTING OBJECTS
(オブジェクトのインサート)
=begin original
Let's start by defining a simple class using L<Moose>:
=end original
L<Moose>を使った簡単なクラスを定義してみましょう:
package Person;
use Moose;
has name => (
isa => "Str",
is => "rw",
);
=begin original
We can instantiate it:
=end original
それをインスタント化します:
my $obj = Person->new( name => "Homer Simpson" );
=begin original
and insert the object to the database as follows:
=end original
下記のようにオブジェクトをデータベースに入れます:
my $scope = $dir->new_scope;
my $homer_id = $dir->store($obj);
=begin original
This is very trivial use of L<KiokuDB>, but it illustrates a few important
things.
=end original
これは、L<KiokuDB>のとても普通の使い方です。ですが、いくつか重要なことを示しています。
=begin original
First, no schema is necessary. L<KiokuDB> uses L<Moose> to introspect your
object without needing to predefine anything like tables.
=end original
1番目に、スキーマは必要ありません。L<KiokuDB>はテーブルのような何かを事前に定義する必要はありません。
オブジェクトの情報を取り出すために、L<Moose>を使うことができます。
=begin original
Second, every object in the database has an ID. If you don't choose an ID for
an object, L<KiokuDB> will assign a UUID instead.
=end original
2番目に、データベースに入っているすべてのオブジェクトにはIDがあります。
オブジェクトにIDを選ばなけれあば、L<KiokuDB>が代わりにUUIDを割り当てます。
=begin original
This ID is like a primary key in a relational database.
You can also specify an ID instead of letting one be generated:
=end original
IDはリレーショナルデータベースのプライマリーキーのようなものです。
自分でオブジェクトにIDを振りたければ、次のようにすることができます:
$dir->store( homer => $obj );
=begin original
Third, all L<KiokuDB> operations need to be performed within a B<scope>. The
scope is not really doing anything important in this simple example, but
becomes necessary when cycles and weak references are in use. We will look into
that in more detail later.
=end original
3番目に、すべてのL<KiokuDB>操作はB<scope>内で行う必要があります。
スコープは上のような簡単な例では大して重要ではありませんが、
循環参照やweakリファレンスが使われるようになると、必要になります。
後でより詳細に見ていきます。
=head1 LOADING OBJECTS
(オブジェクトの読み出し)
=begin original
So now that Homer has been inserted into the database, we can fetch him out of
there using the ID we got from C<store>.
=end original
さて、データベースにHomerが入りました。C<store>から得たIDで取り出せます。
my $homer = $dir->lookup($homer_id);
=begin original
Assuming that C<$scope> and C<$obj> are still in scope, C<$homer> and C<$obj>
will actually be the same object:
=end original
C<$scope>とC<$obj>は、スコープ内にあるとします。C<$homer>とC<$obj>は実際に、同じオブジェクトになります。
# this is true:
refaddr($homer) == refaddr($obj)
=begin original
This is because L<KiokuDB> tracks which objects are "live" in the
B<live object set> (L<KiokuDB::LiveObjects>).
=end original
B<生存しているオブジェクトセット> (L<KiokuDB::LiveObjects>)内のオブジェクトが
"生存"しているかをL<KiokuDB>が追跡しているからです。
=begin original
If the object wasn't already in memory then L<KiokuDB> would have fetched it
from the backend instead.
=end original
オブジェクト既にメモリにあるなら、L<KiokuDB>はインスタンスを
バックエンドから取得します。
=head1 WHAT WAS STORED
(何が保存されたか)
=begin original
Let's peek into the database:
=end original
データベースを覗いてみましょう:
% sqlite3 kiokudb_tutorial.db
SQLite version 3.4.0
Enter ".help" for instructions
sqlite>
=begin original
The database schema has two tables, C<entries> and C<gin_index>:
=end original
データベースのスキーマには2つのテーブルがあります。C<entries>とC<gin_index>です:
sqlite> .tables
entries gin_index
=begin original
C<gin_index> is used for more complex queries, and we'll get back to it at the
end of the tutorial.
=end original
C<gin_index>はより複雑なクエリに使われます。チュートリアルの最後に扱います。
=begin original
For now let's just have a closer look at C<entries>:
=end original
さて、C<entries>に近付いてよく見ましょう:
sqlite> .schema entries
CREATE TABLE entries (
id varchar NOT NULL,
data blob NOT NULL,
class varchar,
root boolean NOT NULL,
tied char(1),
PRIMARY KEY (id)
);
=begin original
The main columns are C<id> and C<data>. In L<KiokuDB> every object has an ID
which serves as a primary key and a BLOB of data associated with it.
=end original
メインのカラムはC<id>とC<data>です。L<KiokuDB>にある、すべてのオブジェクトにはIDがあり、
プライマリキーとBLOBデータが関連付けられています。
=begin original
Since the default serializer for the DBI backend is
L<KiokuDB::Serializer::JSON>, we examine the data.
=end original
DBIバックエンドのデフォルトのシリアライザーはL<KiokuDB::Serializer::JSON>ですので、
データを調査できます。
=begin original
First let's set C<sqlite>'s output mode to C<line>. This is easier to read with
large columns:
=end original
最初に、C<sqlite>の出力モードをC<line>にセットしましょう。大きいカラムでも
見やすくなります:
sqlite> .mode line
=begin original
And select the data from the table:
=end original
テーブルからデータを取得します:
sqlite> select id, data from entries;
id = 201C5B55-E759-492F-8F20-A529C7C02C8B
data = {"__CLASS__":"Person","data":{"name":"Homer Simpson"},"id":"201C5B55-E759-492F-8F20-A529C7C02C8B","root":true}
=begin original
As you can see the C<name> attribute is stored under the C<data> key inside the
blob, as is the object's class.
=end original
上記のように、C<name>属性はblob内のC<data>キーにオブジェクトのクラスとして保存されています。
=begin original
The C<data> column contains all of the data necessary to recreate the object.
=end original
C<data>カラムはオブジェクトを再作成するのに必要なすべてのデータを含んでいます。
=begin original
All the other columns are only for searches. Later on you'll also see how to
create user defined columns.
=end original
他のすべてのカラムは検索のためだけに使われます。後で、どのようにユーザー定義のカラムを
作るのかを見せます。
=begin original
When using L<KiokuDB::Backend::BDB> the on-disk format is just a hash of C<id>
to C<data> with no additional columns.
=end original
L<KiokuDB::Backend::DBD>を使った場合は、ディスク上のフォーマットは、C<id>からC<data>のハッシュになり、
他の追加のカラムはありません。
=head1 OBJECT RELATIONSHIPS
(オブジェクトのリレーションシップ)
=begin original
Let's extend the C<Person> class to hold some more interesting data than just a
C<name>:
=end original
C<Person>クラスにC<name>よりも、もっと面白いデータを追加してみましょう:
package Person;
has spouse => (
isa => "Person",
is => "rw",
weak_ref => 1,
);
=begin original
This new C<spouse> attribute will hold a reference to another person object.
=end original
C<spouse>属性は他のPersonオブジェクトのリファレンスを持ちます。
=begin original
Let's first create and insert another object:
=end original
まずは、他のオブジェクトを作りましょう:
my $marge_id = $dir->store(
Person->new( name => "Marge Simpson" ),
);
=begin original
Now that we have both objects in the database, let's link them together:
=end original
データベースに両方のオブジェクトを持たせます。2つを一緒にリンクしましょう:
{
my $scope = $dir->new_scope;
my ( $marge, $homer ) = $dir->lookup( $marge_id, $homer_id );
$marge->spouse($homer);
$homer->spouse($marge);
$dir->store( $marge, $homer );
}
=begin original
Now we have created a persistent B<object graph>, that is several objects which
point to each other.
=end original
今、永続的なB<オブジェクトグラフ>を作りました。これは、複数のオブジェクトが
お互いに参照しています。
=begin original
The reason C<spouse> had the C<weak_ref> option was so that this circular
structure will not leak.
=end original
C<spouse>にはC<weak_ref>オプションがありましたので、この循環構造はリークしません。
=begin original
When then objects are updated in the database, L<KiokuDB> sees that their
C<spouse> attribute contains references, and this relationship will be encoded
using their unique ID in storage.
=end original
データベースでオブジェクトが更新されたら、L<LinkDB>はC<spouse>属性を含むリファレンスを見て、
この関係はストレージ内でユニークなIDを使ってエンコードされます。
=begin original
To load the graph, we can do something like this:
=end original
このグラフをロードするために、次のようにできます:
{
my $scope = $dir->new_scope;
my $homer = $dir->lookup($homer_id);
print $homer->spouse->name; # Marge Simpson
}
{
my $scope = $dir->new_scope;
my $marge = $dir->lookup($marge_id);
print $marge->spouse->name; # Homer Simpson
refaddr($marge) == refaddr($marge->spouse->spouse); # true
}
=begin original
When L<KiokuDB> is loading the initial object, all the objects the object
depends on will also be loaded. The C<spouse> attribute contains a
reference to another object (by ID), and this link is resolved at inflation
time.
=end original
L<KiokuDB>が最初のオブジェクトをロードしたら、そのオブジェクトが依存している
すべてのオブジェクトがロードされます。C<spouse>属性は他のオブジェクトを(IDで)
持っているので、インフレーション時にそのリンクを解決します。
=head2 The purpose of C<new_scope>
(C<new_scope>の目的)
=begin original
This is where C<new_scope> becomes important. As objects are inflated from the
database, they are pushed onto the live object scope, in order to increase
their reference count.
=end original
C<new_scope>が重要になるところです。オブジェクトはデータベースからインフレートされ、
リファレンスカウントを増やすために、生存しているオブジェクトスコープに追加されます。
=begin original
If this was not done, by the time C<$homer> was returned from C<lookup> his
C<spouse> attribute would have been cleared because there is no other reference
to Marge.
=end original
これがされていなければ、C<lookup>からC<$homer>が戻ってくる時までに、
C<spouse>属性がクリアされます。マージする他のリファレンスがないからです。
=begin original
This demonstrates why:
=end original
次のコードが理由をデモンストレートします:
sub get_homer {
my $homer = Person->new( name => "Homer Simpson" );
my $marge = Person->new( name => "Marge Simpson" );
$homer->spouse($marge);
$marge->spouse($homer);
return $homer;
# at this point $homer and $marge go out of scope
# $homer has a refcount of 1 because it's the return value
# $marge has a refcount of 0, and gets destroyed
# the weak reference in $homer->spouse is cleared
}
my $homer = get_homer();
$homer->spouse; # this returns undef
=begin original
By using this idiom:
=end original
次のイディオムを使って:
{
my $scope = $dir->new_scope;
# do all KiokuDB work in here
}
=begin original
You are ensuring that the objects live at least as long as is necessary.
=end original
少なくとも必要である時間はオブジェクトが生きていることを確保できます。
=begin original
In a web application context you usually create one new scope per request. In
fact, L<Catalyst::Model::KiokuDB> does this automatically.
=end original
Webアプリケーションのコンテキストでは、普通リクエストごとに新しいスコープを作ります。
実際、L<Catalyst::Model::KiokuDB>は、自動的にそうしています。
=head1 REFERENCES IN THE DATABASE
(データベース内のリファレンス)
=begin original
Now that we have an object graph in the database let's have another look at
what's inside.
=end original
さて、データベースにオブジェクトグラフがあります。内部がどうなっているか見てみましょう。
sqlite> select id, data from entries;
id = 201C5B55-E759-492F-8F20-A529C7C02C8B
data = {"__CLASS__":"Person","data":{"name":"Homer Simpson","spouse":{"$ref":"05A8D61C-6139-4F51-A748-101010CC8B02.data"}},"id":"201C5B55-E759-492F-8F20-A529C7C02C8B","root":true}
id = 05A8D61C-6139-4F51-A748-101010CC8B02
data = {"__CLASS__":"Person","data":{"name":"Marge Simpson","spouse":{"$ref":"201C5B55-E759-492F-8F20-A529C7C02C8B.data"}},"id":"05A8D61C-6139-4F51-A748-101010CC8B02","root":true}
=begin original
You'll notice the C<spouse> field has a JSON object with a C<$ref> field inside
it holding the UUID of the target object.
=end original
C<spouse>フィールドがJSONオブジェクトということに気づくでしょう。
そして、その内部のC<$ref>フィールドには、対象のオブジェクトのUUIDがあります。
=begin original
When data is loaded L<KiokuDB> queues up references to unloaded objects and
then loads them in order to materialize the memory resident object graph.
=end original
データがロードされると、L<KiokuDB>はロードさえていないオブジェクトへのリファレンスを
キューに入れて、オブジェクトグラフをメモリに常駐させるために、それらをロードします。
=begin original
If you're curious about why the data is represented this way, this format is
called C<JSPON>, or JavaScript Persistent Object Notation
(L<http://www.jspon.org/>). When using L<KiokuDB::Backend::Storable> the
L<KiokuDB::Entry> and L<KiokuDB::Reference> objects are serialized with their
storable hooks instead.
=end original
データがこのような方法で表現されている理由について知りたければ、
このフォーマットは、C<JPSON>か JavaScript Persistent Object notation(L<http://www.jpson.org>)と呼ばれています。
L<KiokuDB::Backend::Storable>を使うと、L<KiokuDB::Entry>とL<KiokuDB::Reference>オブジェクトは、
代わりに、storableフックでシリアライズされます。
=head1 OBJECT SETS
(オブジェクトセット)
=begin original
More complex relationships (not necessarily 1 to 1) are usually easy to model
with L<Set::Object>.
=end original
より複雑なリレーションシップ(1対1に限らない)は、L<Set::Object>でふつう簡単にモデル化できます。
=begin original
Let's extend the C<Person> class to add such a relationship:
=end original
C<Person>クラスを拡張してそのようなリレーションシップを足してみましょう:
package Person;
has children => (
does => "KiokuDB::Set",
is => "rw",
);
=begin original
L<KiokuDB::Set> objects are L<KiokuDB> specific wrappers for L<Set::Object>.
=end original
L<KiokuDB::Set>オブジェクトは、L<Set::Object>のL<KiokuDB>用のラッパーです。
my @kids = map { Person->new( name => $_ ) } qw(maggie lisa bart);
use KiokuDB::Util qw(set);
my $set = set(@kids);
$homer->children($set);
$dir->store($homer);
=begin original
The C<set> convenience function creates a new L<KiokuDB::Set::Transient>
object. A transient set is one which started its life in memory space (as
opposed to a set that was loaded from the database).
=end original
C<set>という便利な関数は新しいL<KiokuDB::Set::Transient>オブジェクトを作ります。
一時的なセットはメモリスペースに存在するものです
(データベースからロードされたセットとは反対に)。
=begin original
The C<weak_set> convenience function also exists, creating a transient set with
L<Set::Object::Weak> used internally to help avoid circular structures (for
instance if setting a C<parent> attribute in our example).
=end original
C<weak_set>という便利な関数もあります。
循環構造(例えば、今の例にC<parent>属性を追加する)を避けるために内部で使われている、
L<Set::Object::Weak>で一時的なセットを作ります。
=begin original
The set object behaves pretty much like a normal L<Set::Object>:
=end original
このオブジェクトは普通のL<Set::Object>とほとんど同じように振る舞います。
my @kids = $dir->lookup($homer_id)->children->members;
=begin original
The main difference is that sets coming from the database are deferred by
default, that is the objects in C<@kids> are not loaded until they are actually
needed.
=end original
主な違いは、セットがデータベースから来るのがデフォルトで遅延されていることです。
C<@kids>にあるオブジェクトは、実際に必要になるときまでロードされません。
=begin original
This allows large object graphs to exist in the database, while only being
partially loaded, without breaking the encapsulation of user objects. This
behavior is implemented in L<KiokuDB::Set::Deferred> and
L<KiokuDB::Set::Loaded>.
=end original
このことにより、ユーザーのオブジェクトのカプセル化を壊すこと無しに、
部分的にロードされるので、データベースに巨大なオブジェクトグラフがあっても問題になりません。
この振る舞いはL<KiokuDB::Set::Deffered>とL<KiokuDB::Set::Loaded>で実装されています。
=begin original
This set object is optimized to make most operations defer loading. For
instance, if you intersect two deferred sets, only the members of the
intersection set will need to be loaded.
=end original
このセットオブジェクトは、遅延ロードの操作に最適化されています。
例えば、2つの遅延セットを横断するなら、横断するセットのみがロードされる必要があります。
=head1 THE TYPEMAP
=begin original
Storing an object with L<KiokuDB> involves passing it to L<KiokuDB::Collapser>,
the object that "flattens" objects into L<KiokuDB::Entry> before the entries
are inserted into the backend.
=end original
L<KiokuDB>にオブジェクトが保存される際に、L<KiokuDB::Collapser>を通過します。
エントリーがバックエンドにインサートされる前に、L<KiokuDB::Entry>に、
"平たく"されたオブジェクトを入れます。
=begin original
The collapser uses a L<KiokuDB::TypeMap> object that tells it how objects of
each type should be collapsed.
=end original
collapserには、L<KiokuDB::TypeMap>オブジェクトを使います。このオブジェクトは、
それぞれのタイプのオブジェクトがどのように破壊するかを教えます。
=begin original
During retrieval of objects the same typemap is used to reinflate objects back
into working objects.
=end original
オブジェクトを取ってくる間、オブジェクトを再インフレートして、
ワーキングオブジェクトにするのに、同じtypemapが使われます。
=begin original
Trying to store an object that is not in the typemap is an error. The reason
behind this is that it doesn't make sense to store every type of object (for
instance C<DBI> handles need a socket, objects based on XS modules have an
internal pointer as an integer, whose address won't be valid the next time it's
loaded), and even though the majority of objects are safe to serialize, even a
small bit of unreported fragility is usually enough to create large, hard to
debug problems.
=end original
typemapにないオブジェクトを保存しようとするとエラーになります。その理由は
すべてのタイプのオブジェクトを保存できるか分からないからです。(例えば、
C<DBI>はソケット、オブジェクト。XSベースのモジュールは数値のような内部的な
ポインタを持ちます。そのアドレスは次回のロード時には正しくなくなっています)。
大半のオブジェクトは安全にシリアライズできるにもかかわらず、
わずかな報告されないもろさが、大きなデバッグの難しい問題を作るのはありがちなことです。
=begin original
An exception to this rule is L<Moose> based objects, because they have
sufficient meta information available through L<Moose>'s powerful reflection
support in order to be safely serialized.
=end original
このルールの例外は、L<Moose>ベースのオブジェクトです。L<Moose>の強大な
リフレクションサポートを通して、十分なメタ情報が利用できるので、
安全にシリアライズ出来ます。
=begin original
Additionally, the standard backends provide a default typemap for common
objects (L<DateTime>, L<Path::Class>, etc), which by default is merged with any
custom typemap you pass to L<KiokuDB>.
=end original
加えて、標準のバックエンドは共通のオブジェクト(L<DateTime>, L<Path::Class>など>)用に
デフォルトのtypemapを提供しています。L<KiokuDB>にどんなカスタムのtypemapが渡されても、
デフォルトとマージされます。
=begin original
So, in order to actually get L<KiokuDB> to store things like L<Class::Accessor>
based objects, you can do something like this:
=end original
それで、実際にL<KiokuDB>にL<Class::Accessor>ベースのオブジェクトのようなものを保存させるには、
次のようにします:
KiokuDB->new(
backend => $backend,
allow_classes => [qw(My::Object)],
);
=begin original
Which is shorthand for:
=end original
これは次の省略形です:
my $dir = KiokuDB->new(
backend => $backend,
typemap => KiokuDB::TypeMap->new(
entries => {
"My::Object" => KiokuDB::TypeMap::Entry::Naive->new,
},
),
);
=begin original
L<KiokuDB::TypeMap::Entry::Naive> is a type map entry that performs naive
collapsing of the object, by simply walking it recursively.
=end original
L<KiokuDB::TypeMap::Entry::Naive>は単純に再帰的にたどることで、
オブジェクトのナイーブな破壊を行います。
=begin original
When the collapser encounters an object it will ask
L<KiokuDB::TypeMap::Resolver> for a collapsing routine based on the class of
the object.
=end original
collapser は、オブジェクトを見つけると、L<KiokuDB::TypeMap::Resolver>に、
オブジェクトのクラスに応じた、破壊ルーチンを尋ねます。
=begin original
This lookup is typically performed by C<ref $object>, not using inheritance,
because a typemap entry that is safe to use with a superclass isn't necessarily
safe to use with a subclass. If you B<do> want inherited entries, specify
C<isa_entries>:
=end original
この検索は、典型的には、C<ref $object>で行われ、継承を使いません。
スーパークラスで安全に使われているtypemapエントリーは、
必ずしもサブクラスで安全に使えるとは限らないからです。
継承されたエントリーにB<したい>なら、C<isa_entries>を指定してください。
KiokuDB::TypeMap->new(
isa_entries => {
"My::Object" => KiokuDB::TypeMap::Entry::Naive->new,
},
);
=begin original
If no normal (C<ref> keyed) entry is found for an object, the isa entries are
searched for a superclass of that object. Subclass entries are tried before
superclass entries. The result of this lookup is cached, so it only happens
once per class.
=end original
オブジェクトに通常の(C<ref> keyed)エントリーが見つからなければ、
isaエントリーがオブジェクトスーパークラスのために探されます。
サブクラスエントリーはスーパークラスエントリーより前に試されます。
この検索の結果はキャッシュされるので、クラスごとに一回しか起こりません。
=head2 Typemap Entries
=begin original
If you want to do custom serialization hooks, you can specify hooks to collapse
your object:
=end original
カスタムのシリアライズのフックが欲しければ、自分のオブジェクトを破壊するための
フックを指定できます。
KiokuDB::TypeMap::Entry::Callback->new(
collapse => sub {
my $object = shift;
...
return @some_args;
},
expand => sub {
my ( $class, @some_args ) = @_;
...
return $object;
},
);
=begin original
These hooks are called as methods on the object to be collapsed.
=end original
これらのフックはオブジェクトを破壊するときに、メソッドとして呼ばれます。
=begin original
For instance the L<Path::Class> related typemap ISA entry is:
=end original
例えば、typemapのISAに関連するL<Path::Class>は:
'Path::Class::Entity' => KiokuDB::TypeMap::Entry::Callback->new(
intrinsic => 1,
collapse => "stringify",
expand => "new",
);
=begin original
The C<intrinsic> flag is discussed in the next section.
=end original
C<intrinsic>フラグは次のセクションで述べます。
=begin original
Another option for typemap entries is L<KiokuDB::TypeMap::Entry::Passthrough>,
which is appropriate when you know the backend's serialization can handle that
data type natively.
=end original
typemapエントリのもう一つの選択はL<KiokuDB::Typemap::Entry::Passthrough>です。
バックエンドのシリアライズがネイティブにデータタイプを扱うことができると分かっていれば、
これは適切です。
=begin original
For example, if your object has a L<Storable> hook which you know is
appropriate (e.g. contains no sub objects that need to be collapsible) and your
backend uses L<KiokuDB::Backend::Serialize::Storable>. L<DateTime> is an
example of a class with such storable hopes:
=end original
例えば、オブジェクトに適切なL<Storable>フックがあり(破壊する必要のあるサブオブジェクトを含まない)、
バックエンドには、L<KiokuDB::Backend::Serialize::Storable>を使う場合です。
L<DateTime>はそのようにstorableが望むクラスの例です:
'DateTime' => KiokuDB::Backend::Entry::Passthrough->new( intrinsic => 1 )
=head2 Intrinsic vs. First Class
=begin original
In L<KiokuDB> every object is normally assigned an ID, and if the object is
shared by several objects this relationship will be preserved.
=end original
L<KiokuDB>では、すべてのオブジェクトに、通常、IDが割り当てられます。
オブジェクトが複数のオブジェクトに共有されている場合、このリレーションは維持されます。
=begin original
However, for some objects this is not the desired behavior. These are objects
that represent values, like L<DateTime>, L<Path::Class> entries, L<URI>
objects, etc.
=end original
しかし、いくつかのオブジェクトは望ましい振る舞いをしません。
それらは、L<DateTime>や、L<Path::Class>エントリ、L<URI>オブジェクトのようなもので、
値を表現します。
=begin original
L<KiokuDB> can be asked to collapse such objects B<intrinsicly>, that is
instead of creating a new L<KiokuDB::Entry> with its own ID for the object, the
object gets collapsed directly into its parent's structures.
=end original
L<KiokuDB>はB<intrinsicly>に、そのようなオブジェクトを、
そのオブジェクトにそれ自身のIDと新しいL<KiokuDB::Entry>を作る代わりに、
破壊するよう要求できます。オブジェクトが直接破壊できれば、親の構造の中に入ります。
=begin original
This means that shared references that are collapsed intrinsically will be
loaded back from the database as two distinct copies, so updates to one will
not affect the other.
=end original
破壊され、共有されたリファレンスは、もともと2つの区別されたコピーとして
データーベースからロードされます。ですので、一つをアップデートしても、
もう一方には影響がありません。
=begin original
For instance, when we run the following code:
=end original
例えば、下記のようなコードを動かしたとして:
use Path::Class;
my $path = file(qw(path to foo));
$obj_1->file($path);
$obj_2->file($path);
$dir->store( $obj_1, $obj_2 );
=begin original
While the following is true when the data is being inserted, it will no longer
be true when C<$obj_1> and C<$obj_2> are loaded from the database:
=end original
データがインサートされるときには、下記は真ですが、
C<$obj_1>とC<$obj_2>がデーターベースからロードされると、もはや真ではありません:
refaddr($obj_1->file) == refaddr($obj_2->file)
=begin original
This is because both C<$obj_1> and C<$obj_2> each got its own copy of C<$path>.
=end original
C<$obj_1>とC<$obj_2>の両方がC<$path>のコピーだからです。
=begin original
This behavior is usually more appropriate for objects that aren't mutated, but
are instead cloned and replaced, and for which creating a first class entry in
the backend with its own ID is undesired.
=end original
この現象は、通常、変異されず、複製されたり置き換えられたりするオブジェクトに適しています。
そのようなオブジェクトのためには、最初のクラスエントリが独自のIDでバックエンドに作られるのは、
望まれていないからです。
=head2 The Default Typemap
=begin original
Each backend comes with a default typemap, with some built in entries for
common CPAN modules' objects. L<KiokuDB::TypeMap::Default> contains more
details.
=end original
それぞれのバックエンドには、デフォルトのtypemapがついています。
それには、共通のCPANモジュールオブジェクトのために、いくつか共通のビルトインのエントリもあります。
L<KiokuDB::TypeMap::Default>により詳細があります。
=head1 SIMPLE SEARCHES
(単純な検索)
=begin original
Most backends support an inefficient but convenient simple search, which scans
the entries and matches fields.
=end original
ほとんどのバックエンドが効率的ではないものの、便利な単純な検索があります。
これは、エントリをスキャンして、フィールドにマッチさせます。
=begin original
If you want to make use of this API we suggest using L<KiokuDB::Backend::DBI>
since simple searching is implemented using an SQL where clause, which is much
more efficient (you do have to set up the column manually though).
=end original
このAPIを使いたいなら、L<KiokuDB::Backend::DBI>を使うことをおすすめします。
単純亜検索はSQLのwhere節を使って実装でき、より効率的だからです。
(ただし、手でカラムをセットアップしないといけませんが)
=begin original
Calling the C<search> method with a hash reference as the only argument invokes
the simple search functionality, returning a L<Data::Stream::Bulk> with the
results:
=end original
C<search>メソッドに引数としてハッシュリファレンスのみを渡して呼びます。
単純な検索機能が呼び出され、L<Data::Stream::Bulk>が結果と一緒に戻ってきます:
my $stream = $dir->search({ name => "Homer Simpson" });
while ( my $block = $stream->next ) {
foreach my $object ( @$block ) {
# $object->name eq "Homer Simpson"
}
}
=begin original
This exact API is intentionally still underdefined. In the future it will be
compatible with L<DBIx::Class> 0.09's syntax.
=end original
正確なAPIはまだ決められていません。将来的に、L<DBIx::Class> 0.09のシンタックスと
互換にするつもりです。
=head2 DBI SEARCH COLUMNS
=begin original
In order to make use of the simple search API we need to configure columns for
our DBI backend.
=end original
この簡単な検索APIを使うには、DBIバックエンドにカラムを設定しなければいけません。
=begin original
Let's create a 'name' column to search by:
=end original
検索するために、'name'カラムを作りましょう:
my $dir = KiokuDB->connect(
"dbi:SQLite:dbname=foo",
columns => [
# specify extra columns for the 'entries' table
# in the same format you pass to DBIC's add_columns
name => {
data_type => "varchar",
is_nullable => 1, # probably important
},
],
);
=begin original
You can either alter the schema manually, or use C<kioku dump> to back up your
data, delete the database, connect with C<< create => 1 >> and then use
C<kioku load>.
=end original
スキーマを手で変更することもできますし、また、データをバックアップするのに、C<kioku dump>を使い、
データベースを削除し、C<< create => 1 >>で接続し、C<kioku load>を使うことも出来ます。
=begin original
To populate this column we'll need to load Homer and update him:
=end original
このカラムを埋め込むために、Homerをロードして、更新する必要があります:
{
my $s = $dir->new_scope;
$dir->update( $dir->lookup( $homer_id ) );
}
=begin original
And this is what it looks in the database:
=end original
データベースでは次のようになります:
id = 201C5B55-E759-492F-8F20-A529C7C02C8B
name = Homer Simpson
=head1 GETTING STARTED WITH BDB
(BDBを始めよう)
=begin original
The most mature backend for L<KiokuDB> is L<KiokuDB::Backend::BDB>. It performs
very well, and supports many features, like L<Search::GIN> integration to
provide customized indexing of your objects and transactions.
=end original
L<KiokuDB>でもっとも成熟したバックエンドは、L<KiokuDB::Backend::DBD>です(訳注:DBIのほうが安定しているとYAPC::Asia 2009で聞きました)。
十分に動きますし、多くの機能をサポートします。
オブジェクトのインデックスのカスタマイズやトランザクションを提供する
L<Search::GIN>のようなインテグレーションもあります。
=begin original
L<KiokuDB::Backend::DBI> is newer and not as tested, but also supports
transactions and L<Search::GIN> based queries. It performs quite well too, but
isn't as fast as L<KiokuDB::Backend::BDB>.
=end original
L<KiokuDB::Backend::DBI>はより新しいですが、そこまでテストされていません。
ですが、トランザクションもサポートしますし、クエリベースのL<Search::GIN>もあります。
これも、なかなかよく動きます。ですが、L<KiokuDB::Backend::BDB>と同じくらい速くはありません
(訳注:YAPC::Asia 2009では、ほぼ変わらないと聞きました)
=head2 Installing L<KiokuDB::Backend::BDB>
=begin original
L<KiokuDB::Backend::BDB> needs the L<BerkeleyDB> module, and a recent version
of Berkeley DB itself, which can be found here:
L<http://www.oracle.com/technology/software/products/berkeley-db/db/index.html>.
=end original
L<KiokuDB::Backend::BDB>は、L<BerkeleyDB>モジュールが必要です。
また、最近のバージョンのBerkeley DB自身も必要です。Berkeley DBは、以下のURLにあります。
L<http://www.oracle.com/technology/software/products/berkeley-db/db/index.html>.
=begin original
BerkeleyDB (the library) normally installs into C</usr/local/BerkeleyDB.4.7>,
while L<BerkeleyDB> (the module) looks for it in C</usr/local/BerkeleyDB>, so
adding a symbolic link should make installation easy.
=end original
BerkeleyDB(ライブラリ)は通常、C</usr/local/BerkeleyDB.4.7>にインストールされます。
ですが、L<BerkeleyDB>(モジュール)は、C</usr/local/BerkeleyDB>を見ようとします。
ですので、シンボリックリンクを作っておけば、インストールが簡単になります。
=begin original
Once you have L<BerkeleyDB> installed, L<KiokuDB::Backend::BDB> should install
without problem and you can use it with L<KiokuDB>.
=end original
L<BerkeleyDB>がインストールできれば、L<KiokuDB::Backend::BDB>は問題なくインストールできるはずです。
L<KiokuDB>と一緒に使うことができます。
=head2 Using L<KiokuDB::Backend::BDB>
=begin original
To use the BDB backend we must first create the storage. To do this the
C<create> flag must be passed:
=end original
BDBバックエンドを使うために、ストレージを作らなければいけません。
このために、C<create>フラグを渡さなければいけません。
my $backend = KiokuDB::Backend::BDB->new(
manager => {
home => Path::Class::Dir->new(qw(path to storage)),
create => 1,
},
);
=begin original
The BDB backend uses L<BerkeleyDB::Manager> to do a lot of the L<BerkeleyDB>
gruntwork. The L<BerkeleyDB::Manager> object will be instantiated using the
arguments provided in the C<manager> attribute.
=end original
BDBバックエンドは、L<BerkeleyDB::Manager>を使って、たくさんのL<BerkeleyDB>の下働きを行います。
L<BerkeleyDB::Manager>オブジェクトはC<manager>属性で提供される引数を使って、インスタンス化されます。
=begin original
Now that the storage is created we can make use of this backend, much like before:
=end original
これで、ストレージがつくられました。このバックエンドを、以前と同様に使います。
my $dir = KiokuDB->new( backend => $backend );
=begin original
Subsequent opens will not require the C<create> argument to be true, but it
doesn't hurt.
=end original
その後のオープンには、C<create>属性が真である必要はありませんが、真であっても特に害はありません。
=begin original
This C<connect> call is equivalent to the above:
=end original
このC<connect>は上記のものと同じです:
my $dir = KiokuDB->connect( "bdb:dir=path/to/storage", create => 1 );
=head1 TRANSACTIONS
(トランザクション)
=begin original
Some backends (ones which do the L<KiokuDB::Backend::Role::TXN> role) can be used
with transactions.
=end original
いくつかのバックエンド(L<KiokuDB::Backend::Role::TXN>ロールをするもの)は、トランザクションが使えるものがあります。
=begin original
If you are familiar with L<DBIx::Class> this should be very familiar:
=end original
L<DBIx::Class>に慣れているなら、すぐわかるでしょう:
$dir->txn_do(sub {
$dir->store($obj);
});
=begin original
This will create a L<BerkeleyDB> level transaction, and all changes to the
database are committed if the block was executed cleanly.
=end original
L<BerkeleyDB>レベルのトランザクションを作ります。データベースへのすべての変更は
ブロックが綺麗に実行されたら、コミットされます。
=begin original
If any error occurred the transaction will be rolled back, and the changes will
not be visible to subsequent reads.
=end original
何らかのエラーが起きれば、トランザクションはロールバックされます。
変更は次の読み込みでは、見えません。
=begin original
Note that L<KiokuDB> does B<not> touch live instances, so if you do something
like
=end original
L<KiokuDB>生きているインスタンスには触れません。ですので、次のようにすると
$dir->txn_do(sub {
my $scope = $dir->new_scope;
$obj->name("Dancing Hippy");
$dir->store($obj);
die "an error";
});
=begin original
the C<name> attribute is B<not> rolled back, it is simply the C<store>
operation that gets reverted.
=end original
C<name>属性はロールバックB<されません>。C<store>オペレーションだけが、元に戻ります。
=begin original
Transactions will nest properly, and with most backends they generally increase
write performance as well.
=end original
トランザクションは適切にネストできます。また、ほとんどのバックエンドで、一般的に
書き込みのパフォーマンスが良くなります。
=head1 QUERIES
(クエリ)
=begin original
L<KiokuDB::Backend::BDB::GIN> is a subclass of L<KiokuDB::Backend::BDB> that
provides L<Search::GIN> integration.
=end original
L<KiokuDB::Backend::BDB::GIN>はL<KiokuDB::Backend::BDB>のサブクラスで、
L<Serach::GIN>インテグレーションを提供しています。
=begin original
L<Search::GIN> is a framework to index and query objects, inspired by Postgres'
internal GIN api. GIN stands for Generalized Inverted Indexes.
=end original
L<Search::GIN>はインデックスとクエリーオブジェクトのフレームワークです。
Postgresの内部GIN apiにインスパイアされました。
GINは、Generalized Inverted Indexes(訳注:汎用転置索引)の略です。
=begin original
Using L<Search::GIN> arbitrary search keys can be indexed for your objects, and
these objects can then be looked up using queries.
=end original
L<Search::GIN>を使うと、任意の検索キーをオブジェクトにタイしてインデックスできます。
そして、それらのオブジェクトをクエリで検索できます。
=begin original
For instance, one of the pre canned searches L<Search::GIN> supports out of the
box is class indexing. Let's use L<Search::GIN::Extract::Callback> to do custom
indexing of our objects:
=end original
例えば、L<Search::GIN>がサポートする、すぐに使える、予めある検索の一つに、クラスインデックスがあります。
L<Search::GIN::Extract::Callback> を使って、オブジェクトにカスタムのインデックスを作りましょう:
my $dir = KiokuDB->new(
backend => KiokuDB::Backend::BDB::GIN->new(
extract => Search::GIN::Extract::Callback->new(
extract => sub {
my ( $obj, $extractor, @args ) = @_;
if ( $obj->isa("Person") ) {
return {
type => "user",
name => $obj->name,
};
}
return;
},
),
),
);
$dir->store( @random_objects );
=begin original
To look up the objects, we use the a manual key lookup query:
=end original
オブジェクトを検索するために、マニュアルキー検索クエリを使います:
my $query = Search::GIN::Query::Manual->new(
values => {
type => "person",
},
);
my $stream = $dir->search($query);
=begin original
The result is L<Data::Stream::Bulk> object that represents the search results.
It can be iterated as follows:
=end original
結果として、検索結果を表すL<Data::Stream::Bulk>オブジェクトが返ります。
次のようにイテレートできます。
while ( my $block = $stream->next ) {
foreach my $person ( @$block ) {
print "found a person: ", $person->name;
}
}
=begin original
Or even more simply, if you don't mind loading the whole resultset into memory:
=end original
また、より単純に、メモリに全結果をロードしてもかまわないなら:
my @people = $stream->all;
=begin original
L<Search::GIN> is very much in its infancy, and is very under documented.
However it does work for simple searches such as this and contains pre canned
solutions like L<Search::GIN::Extract::Class>.
=end original
L<Search::GIN>はまだ未成熟です。ドキュメントも書いているところです。
ですが、このような単純な検索は動きますし、L<Search::GIN::Extract::Class>のような
予めある解決を含んでいます。
=begin original
In short, it works today, but watch this space for new developments.
=end original
つまり、現在は動きますが、新しく開発をするときには、これに注意してください。
=head1 翻訳について
翻訳者:加藤敦 (ktat@cpan.org)
Perlドキュメント日本語訳 Project にて、
Perlモジュール、ドキュメントの翻訳を行っております。
http://perldocjp.sourceforge.jp/
http://sourceforge.jp/projects/perldocjp/
http://www.freeml.com/ctrl/html/MLInfoForm/perldocjp@freeml.com
http://www.perldoc.jp/