Merb/DataMapperをしばらく使っていたのですが、
少なくともバージョン0.9.10, 0.9.11では、
associationの実装にバグがあり、
レコード数が多いテーブルがあると、aggregation系の処理に時間がかかるという問題がある事が分かりました。
例えば、Post.has n, :comments な関係がある時に、
以下のようなコードを実行すると、このようになります。
1 ?> Post.first.comments.count
2 ~ (0.000865) SELECT "id" FROM "posts" ORDER BY "id" LIMIT 1
3 ~ (0.000094) SELECT "id", "post_id" FROM "comments" WHERE ("post_id" IN (1)) ORDER BY "id"
4 ~ (0.000063) SELECT COUNT(*) FROM "comments" WHERE ("post_id" = 1)
2つ目のSQLは不要なのですが、発行されてしまいます。
例えばCommentのレコード数が多かった場合、Commentオブジェクトを大量に生成しようとしてしまうため、致命的な遅さになってしまいます。
目下この問題の解決策を探しているところですが、
Edge-DMのspec/仕様でerrorが出ている状態なので、なかなか手が付けられない感じです。
とりあえず、dm-coreのassociations/relationship.rbの中の、
1
2 def get_children(parent, options = {}, finder = :all, *args)
3 parent_value = parent_key.get(parent)
4 bind_values = [ parent_value ]
5
6 with_repository(child_model) do |r|
7 parent_identity_map = parent.repository.identity_map(parent_model)
8
9 query_values = parent_identity_map.keys
10 bind_values = query_values unless query_values.empty?
11 query = child_key.zip(bind_values.transpose).to_hash
12 collection = child_model.send(finder, *(args.dup << @query.merge(optio
13 ns).merge(query)))
14
15 return collection unless collection.kind_of?(Collection) && collection.any?
の最後の collection.any? で件のSQLが実行されているところまでは分かりました。
DataMapper::CollectionはextlibのLazyArrayを継承しているクラスなのですが、どうもそのへんの仕様が変わったのに追従できてないのかな。
モジュールを過度に分散しすぎるのも、整合性を保つのが大変になるという問題がありますね。
注意深く完全なSpecを書く事を心がけていれば防げる問題かもしれないですが。