Class: Bdb::Database

Inherits:
Base show all
Defined in:
lib/bdb/database.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#indexes

Instance Method Summary collapse

Methods inherited from Base

#checkpoint, #config, #environment, #index_by, #master?, #path, #synchronize, #transaction

Constructor Details

#initialize(name, opts = {}) ⇒ Database

Returns a new instance of Database.



4
5
6
7
# File 'lib/bdb/database.rb', line 4

def initialize(name, opts = {})
  @name = name
  super(opts)
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/bdb/database.rb', line 8

def name
  @name
end

Instance Method Details

#[](key) ⇒ Object



148
149
150
# File 'lib/bdb/database.rb', line 148

def [](key)
  get(key).first
end

#closeObject



53
54
55
56
57
58
59
# File 'lib/bdb/database.rb', line 53

def close
  return unless @db
  synchronize do
    @db.each {|field, db| db.close(0)}
    @db = nil
  end
end

#close_environmentObject



61
62
63
# File 'lib/bdb/database.rb', line 61

def close_environment
  environment.close
end

#count(field, key) ⇒ Object



65
66
67
68
69
70
# File 'lib/bdb/database.rb', line 65

def count(field, key)
  with_cursor(db(field)) do |cursor|
    k, v = cursor.get(Tuple.dump(key), nil, Bdb::DB_SET)
    k ? cursor.count : 0
  end
end

#db(index = nil) ⇒ Object



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
# File 'lib/bdb/database.rb', line 10

def db(index = nil)
  if @db.nil?
    @db = {}
    open_flags = master? ? Bdb::DB_CREATE : Bdb::DB_RDONLY
    transaction(false) do
      primary_db = environment.env.db
      primary_db.pagesize = config[:page_size] if config[:page_size]
      primary_db.open(transaction, name, nil, Bdb::Db::BTREE, open_flags, 0)
      @db[:primary_key] = primary_db

      indexes.each do |field, opts|
        index_callback = lambda do |db, key, data|
          value = Marshal.load(data)
          index_key = value.kind_of?(Hash) ? value[:field] : value.send(field)
          if opts[:multi_key] and index_key.kind_of?(Array)
            # Index multiple keys. If the key is an array, you must wrap it with an outer array.
            index_key.collect {|k| Tuple.dump(k)}
          elsif index_key
            # Index a single key.
            Tuple.dump(index_key)
          end
        end
        index_db = environment.env.db
        index_db.flags = Bdb::DB_DUPSORT unless opts[:unique]
        index_db.pagesize = config[:page_size] if config[:page_size]
        index_db.open(transaction, "#{name}_by_#{field}", nil, Bdb::Db::BTREE, open_flags, 0)
        primary_db.associate(transaction, index_db, open_flags, index_callback)
        @db[field] = index_db
      end
    end
  end
  @db[index || :primary_key]
rescue Bdb::DbError => e
  # Retry if the database doesn't exist and we are a replication client.
  if not master? and e.code == Errno::ENOENT::Errno
    close
    sleep 1
    retry
  else
    raise(e)
  end
end

#delete(key) ⇒ Object



162
163
164
165
166
167
# File 'lib/bdb/database.rb', line 162

def delete(key)
  synchronize do
    key = Tuple.dump(key)
    db.del(transaction, key, 0)
  end
end

#get(*keys, &block) ⇒ Object



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
# File 'lib/bdb/database.rb', line 72

def get(*keys, &block)
  opts  = keys.last.kind_of?(Hash) ? keys.pop : {}
  db    = db(opts[:field])
  set   = Bdb::ResultSet.new(opts, &block)
  flags = opts[:modify] ? Bdb::DB_RMW : 0
  flags = 0 if environment.disable_transactions?

  keys.each do |key|
    key = get_key(key, opts)
    if key == :all
      with_cursor(db) do |cursor|          
        if opts[:reverse]
          k,v  = cursor.get(nil, nil, Bdb::DB_LAST | flags)          # Start at the last item.
          iter = lambda {cursor.get(nil, nil, Bdb::DB_PREV | flags)} # Move backward.
        else
          k,v  = cursor.get(nil, nil, Bdb::DB_FIRST | flags)         # Start at the first item.
          iter = lambda {cursor.get(nil, nil, Bdb::DB_NEXT | flags)} # Move forward.
        end

        while k
          set << unmarshal(v, :tuple => k)
          k,v = iter.call
        end
      end
    elsif key.kind_of?(Range)
      # Fetch a range of keys.
      with_cursor(db) do |cursor|
        first = Tuple.dump(key.first)
        last  = Tuple.dump(key.last)

        # Return false once we pass the end of the range.
        cond = key.exclude_end? ? lambda {|k| k < last} : lambda {|k| k <= last}
        if opts[:reverse]
          iter = lambda {cursor.get(nil, nil, Bdb::DB_PREV | flags)} # Move backward.
          
          # Position the cursor at the end of the range.
          k,v = cursor.get(last, nil, Bdb::DB_SET_RANGE | flags) || cursor.get(nil, nil, Bdb::DB_LAST | flags)
          while k and not cond.call(k)
            k,v = iter.call
          end
          
          cond = lambda {|k| k >= first} # Change the condition to stop when we move past the start.
        else
          k,v  = cursor.get(first, nil, Bdb::DB_SET_RANGE | flags)   # Start at the beginning of the range.
          iter = lambda {cursor.get(nil, nil, Bdb::DB_NEXT | flags)} # Move forward.
        end
        
        while k and cond.call(k)
          set << unmarshal(v, :tuple => k)
          k,v = iter.call
        end
      end
    else
      if (db.flags & Bdb::DB_DUPSORT) == 0
        synchronize do
          # There can only be one item for each key.
          data = db.get(transaction, Tuple.dump(key), nil, flags)
          set << unmarshal(data, :key => key) if data
        end
      else
        # Have to use a cursor because there may be multiple items with each key.
        with_cursor(db) do |cursor|
          k,v = cursor.get(Tuple.dump(key), nil, Bdb::DB_SET | flags)
          while k
            set << unmarshal(v, :tuple => k)
            k,v = cursor.get(nil, nil, Bdb::DB_NEXT_DUP | flags)
          end
        end
      end
    end
  end
  set.results
rescue Bdb::ResultSet::LimitReached
  set.results
end

#set(key, value, opts = {}) ⇒ Object



152
153
154
155
156
157
158
159
160
# File 'lib/bdb/database.rb', line 152

def set(key, value, opts = {})
  synchronize do
    key   = Tuple.dump(key)
    value = Marshal.dump(value)
    flags = opts[:create] ? Bdb::DB_NOOVERWRITE : 0
    db.put(transaction, key, value, flags)
    value
 end
end

#syncObject



176
177
178
# File 'lib/bdb/database.rb', line 176

def sync
  db.sync
end

#truncate!Object

Deletes all records in the database. Beware!



170
171
172
173
174
# File 'lib/bdb/database.rb', line 170

def truncate!
  synchronize do
    db.truncate(transaction)
  end
end