forked from brynary/arel
-
Notifications
You must be signed in to change notification settings - Fork 390
/
Copy pathfake_record.rb
135 lines (113 loc) · 2.6 KB
/
fake_record.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
module FakeRecord
class Column < Struct.new(:name, :type)
end
class Connection
attr_reader :tables
attr_accessor :visitor
def initialize(visitor = nil)
@tables = %w{ users photos developers products}
@columns = {
'users' => [
Column.new('id', :integer),
Column.new('name', :string),
Column.new('bool', :boolean),
Column.new('created_at', :date)
],
'products' => [
Column.new('id', :integer),
Column.new('price', :decimal)
]
}
@columns_hash = {
'users' => Hash[@columns['users'].map { |x| [x.name, x] }],
'products' => Hash[@columns['products'].map { |x| [x.name, x] }]
}
@primary_keys = {
'users' => 'id',
'products' => 'id'
}
@visitor = visitor
end
def columns_hash table_name
@columns_hash[table_name]
end
def primary_key name
@primary_keys[name.to_s]
end
def table_exists? name
@tables.include? name.to_s
end
def columns name, message = nil
@columns[name.to_s]
end
def quote_table_name name
"\"#{name.to_s}\""
end
def quote_column_name name
"\"#{name.to_s}\""
end
def schema_cache
self
end
def quote thing, column = nil
if column && !thing.nil?
case column.type
when :integer
thing = thing.to_i
when :string
thing = thing.to_s
end
end
case thing
when DateTime
"'#{thing.strftime("%Y-%m-%d %H:%M:%S")}'"
when Date
"'#{thing.strftime("%Y-%m-%d")}'"
when true
"'t'"
when false
"'f'"
when nil
'NULL'
when Numeric
thing
else
"'#{thing.to_s.gsub("'", "\\\\'")}'"
end
end
end
class ConnectionPool
class Spec < Struct.new(:config)
end
attr_reader :spec, :connection
def initialize
@spec = Spec.new(:adapter => 'america')
@connection = Connection.new
@connection.visitor = Arel::Visitors::ToSql.new(connection)
end
def with_connection
yield connection
end
def table_exists? name
connection.tables.include? name.to_s
end
def columns_hash
connection.columns_hash
end
def schema_cache
connection
end
def quote thing, column = nil
connection.quote thing, column
end
end
class Base
attr_accessor :connection_pool
def initialize
@connection_pool = ConnectionPool.new
end
def connection
connection_pool.connection
end
end
end