forked from sferik/twitter-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite_identity_map.rb
46 lines (38 loc) · 1.27 KB
/
sqlite_identity_map.rb
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
require 'sqlite3'
module Twitter
class SqliteIdentityMap
include SQLite3
# It should be painfully obvious that this code is purely experimental and
# should never be used in a production environment.
GC.disable
def initialize
@database = Database.new(":memory:")
end
# @param id
# @return [Object]
def fetch(id)
create_table
@select ||= @database.prepare("SELECT object_id FROM identity_map WHERE id = :id")
row = @select.execute!(:id => id).first
ObjectSpace._id2ref(row.first) unless row.nil?
end
# @param id
# @param object
# @return [Object]
def store(id, object)
create_table
@insert ||= @database.prepare("INSERT INTO identity_map(id, object_id) VALUES (:id, :object_id)")
@insert.execute(:id => id, :object_id => object.object_id)
object
rescue SQLite3::ConstraintException
@delete ||= @database.prepare("DELETE FROM identity_map WHERE id = :id")
@delete.execute(:id => id)
retry
end
private
def create_table
@database.execute("CREATE TABLE IF NOT EXISTS identity_map(id VARCHAR NOT NULL, object_id INTEGER)")
@database.execute("CREATE UNIQUE INDEX IF NOT EXISTS index_identity_map_on_id ON identity_map(id)")
end
end
end