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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
|
# File 'lib/dorm/repository.rb', line 8
def for(data_class, table_name: nil, validations: {})
table_name ||= pluralize(data_class.name.downcase)
Module.new do
extend self
define_singleton_method(:data_class) { data_class }
define_singleton_method(:table_name) { table_name }
define_singleton_method(:validations) { validations }
define_singleton_method(:columns) { data_class.members }
define_singleton_method(:db_columns) { columns - [:id] }
define_singleton_method(:placeholder) do |index|
case Database.adapter
when :postgresql
"$#{index}"
when :sqlite3
'?'
else
'?'
end
end
define_singleton_method(:placeholders) do |count, start_index: 1|
case Database.adapter
when :postgresql
(start_index...(start_index + count)).map { |i| "$#{i}" }
when :sqlite3
Array.new(count, '?')
else
Array.new(count, '?')
end
end
define_singleton_method(:returning_clause) do |column = 'id'|
case Database.adapter
when :postgresql
"RETURNING #{column}"
when :sqlite3
"RETURNING #{column}"
else
"RETURNING #{column}"
end
end
define_singleton_method(:result_empty?) do |result|
case Database.adapter
when :postgresql
result.ntuples == 0
when :sqlite3
result.empty?
else
result.empty?
end
end
define_singleton_method(:find) do |id|
Result.try do
result = Database.query("SELECT * FROM #{table_name} WHERE id = #{placeholder(1)}", [id])
raise 'Record not found' if result_empty?(result)
row_to_data(result[0])
end
end
define_singleton_method(:find_all) do
Result.try do
result = Database.query("SELECT * FROM #{table_name} ORDER BY id")
result.map { |row| row_to_data(row) }
end
end
define_singleton_method(:create) do |attrs|
Result.try do
validate_attrs(attrs)
now = Time.now
attrs_with_timestamps = attrs.merge(created_at: now, updated_at: now)
attrs_with_timestamps.delete(:id) if attrs_with_timestamps.key?(:id)
record = data_class.new(id: nil, **attrs_with_timestamps)
columns_list = db_columns.join(', ')
placeholder_list = placeholders(db_columns.length).join(', ')
values = db_columns.map { |col| serialize_value(record.send(col)) }
result = Database.query(
"INSERT INTO #{table_name} (#{columns_list}) VALUES (#{placeholder_list}) #{returning_clause}",
values
)
id_value = case Database.adapter
when :postgresql
result[0]['id'].to_i
when :sqlite3
result[0]['id'].to_i
else
result[0]['id'].to_i
end
record.with(id: id_value)
end
end
define_singleton_method(:update) do |record|
Result.try do
raise 'Cannot update record without id' unless record.id
updated_record = record.with(updated_at: Time.now)
set_clauses = db_columns.map.with_index(1) { |col, i| "#{col} = #{placeholder(i)}" }.join(', ')
values = db_columns.map { |col| serialize_value(updated_record.send(col)) }
values << updated_record.id
id_placeholder = placeholder(db_columns.length + 1)
result = Database.query(
"UPDATE #{table_name} SET #{set_clauses} WHERE id = #{id_placeholder} #{returning_clause}",
values
)
raise 'Record not found' if result_empty?(result)
updated_record
end
end
define_singleton_method(:save) do |record|
if record.id
update(record)
else
attrs = record.to_h
attrs.delete(:id) create(attrs)
end
end
define_singleton_method(:delete) do |record|
Result.try do
raise 'Cannot delete record without id' unless record.id
result = Database.query(
"DELETE FROM #{table_name} WHERE id = #{placeholder(1)} #{returning_clause}",
[record.id]
)
raise 'Record not found' if result_empty?(result)
record
end
end
define_singleton_method(:where) do |predicate|
find_all.map { |records| records.select(&predicate) }
end
define_singleton_method(:find_by) do |**attrs|
Result.try do
conditions = attrs.keys.map.with_index(1) { |key, i| "#{key} = #{placeholder(i)}" }.join(' AND ')
values = attrs.values.map { |val| serialize_value(val) }
result = Database.query("SELECT * FROM #{table_name} WHERE #{conditions}", values)
raise 'Record not found' if result_empty?(result)
row_to_data(result[0])
end
end
define_singleton_method(:find_all_by) do |**attrs|
Result.try do
conditions = attrs.keys.map.with_index(1) { |key, i| "#{key} = #{placeholder(i)}" }.join(' AND ')
values = attrs.values.map { |val| serialize_value(val) }
result = Database.query("SELECT * FROM #{table_name} WHERE #{conditions}", values)
result.map { |row| row_to_data(row) }
end
end
define_singleton_method(:count) do
Result.try do
result = Database.query("SELECT COUNT(*) as count FROM #{table_name}")
case Database.adapter
when :postgresql
result[0]['count'].to_i
when :sqlite3
result[0]['count'].to_i
else
result[0]['count'].to_i
end
end
end
define_singleton_method(:validate_attrs) do |attrs|
validations.each do |field, rules|
value = attrs[field]
if rules[:required] && (value.nil? || (value.respond_to?(:empty?) && value.empty?) || (value.respond_to?(:strip) && value.strip.empty?))
raise ValidationError, "#{field} is required"
end
if rules[:format] && value && !value.match?(rules[:format])
raise ValidationError, "#{field} has invalid format"
end
if rules[:length] && value && !rules[:length].include?(value.length)
raise ValidationError, "#{field} length must be #{rules[:length]}"
end
if rules[:range] && value && !rules[:range].include?(value)
raise ValidationError, "#{field} must be in range #{rules[:range]}"
end
end
end
define_singleton_method(:row_to_data) do |row|
attrs = {}
columns.each do |col|
attrs[col] = deserialize_value(col, row[col.to_s])
end
data_class.new(**attrs)
end
define_singleton_method(:serialize_value) do |value|
case value
when Time
case Database.adapter
when :postgresql
value when :sqlite3
value.to_s else
value.to_s
end
when true, false
case Database.adapter
when :postgresql
value when :sqlite3
value ? 1 : 0 else
value
end
else
value
end
end
define_singleton_method(:deserialize_value) do |column, value|
return nil if value.nil?
case column
when :id, :user_id, :post_id, :comment_id
value.to_i
when :created_at, :updated_at
case Database.adapter
when :postgresql
value.is_a?(Time) ? value : Time.parse(value.to_s)
when :sqlite3
Time.parse(value.to_s)
else
Time.parse(value.to_s)
end
when /.*_id$/
value.to_i
when :published, :active, :approved
case Database.adapter
when :postgresql
case value
when true, 't', 'true', '1', 1
true
when false, 'f', 'false', '0', 0
false
else
!!value
end
when :sqlite3
case value
when 1, '1', 'true', true
true
when 0, '0', 'false', false
false
else
!!value
end
else
!!value
end
else
value
end
end
end
end
|