• 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
  • ActiveRecord の TC/TT アダプタ
  • AR 上で動作するので全てのAPIが利用可能

インストール

   1  % gem install activetokyocabinet

サーバの起動

   1  % ttserver -port 11114 db.tct &

  • ポート(11114)は何でもよい
  • ファイル名も何でもよい (拡張子はtct)

セットアップ

   1  require 'active_tokyocabinet/tdb'
   2  
   3  ActiveRecord::Base.establish_connection(
   4    :adapter  => 'tokyotyrant',
   5    :database => {
   6      :englishes => {:host => 'localhost', :port => 11114},
   7    }
   8  );

  • adapter 名は 'tokyotyrant'
  • database で利用するテーブル名と参照するTTの設定を指定する
  • 以下で Englishモデルを使うので "englishes" を定義している
  • 複数のモデルを使うときはやっぱりTTが複数必要?

使い方

   1  class English < ActiveRecord::Base
   2    include ActiveTokyoCabinet::TDB
   3  
   4    string :word
   5    int    :length
   6  
   7    validates_presence_of :word, :length
   8  
   9    def validate
  10      self[:length] ||= word.to_s.size
  11    end
  12  end

  • ARなので validate でも何でも思い通り
  • カラム定義は string, int, float (date/datetimeはない?)

   1  # /usr/share/dict/words を流し込み
   2  buf = File.read("/usr/share/dict/words")
   3  buf.scan(/^([a-z]+)$/) {
   4    English.create!(:word=>$1)
   5  }
   6  
   7  English.count
   8  => 64024
   9  
  10  English.all(:conditions=>["word regexp ? and length > ?", '^mai', 12])
  11  [#<English id: 33247, word: "mainstreaming", length: "13">,
  12   #<English id: 33250, word: "maintainability", length: "15">]

  • 正規表現の検索も可能

   1  e = English.first
   2  e.delete
   3  ActiveRecord::StatementInvalid: NoMethodError: undefined method `values_at' for 1:Fixnum: DELETE FROM englishes WHERE (id IN (1))
   4          from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract_adapter.rb:219:in `log'

あれ!?あれ?

まとめ

  • ARで稼動する上に正規表現による検索も可能
  • 削除(delete, destroy)ができないのはご愛嬌

で、一番驚いたのは、実装方法。 普通なら、ARの各メソッドをTT化していきそうなものだが、

  1. ARにSQLを作成させて
  2. そのSQLをパーズして
  3. TTに翻訳する

その発想はなかった。目から鱗です。 というか、SQLのparserは実用性が高いのでまず、 それをgem化希望!激しく希望!!

参考

posted by Png maiha on Fri 26 Feb 2010 at 01:35 with 2 comments

Comments:

Face winebarrel about 14 years ago.

レポートありがとうございます。 削除できない件は修正しました。

SQLのparserはTC/TTに特化していていい加減なところが多いので(ORが使えない・JOINが使えない・サブクエリが使えない等々)、正直、あんまり汎用性はないと思います

Png maiha about 14 years ago.

なるほど。rails のログから実行したクエリを抜き出したいと思うことがよくありまして。

あ、削除は確認できましたっ!!あざーす♪

or Preview
Social Bookmarks
  • Delicious
  • B_entry1723
  • Clip_16_12_w
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ