This repository was archived by the owner on Sep 27, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp_table.rb
More file actions
81 lines (64 loc) · 1.53 KB
/
temp_table.rb
File metadata and controls
81 lines (64 loc) · 1.53 KB
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
# frozen_string_literal: true
require_relative '../db'
class TempTableStrategy
def self.import(data:, ids:)
new(data, ids).import
end
def initialize(data, ids)
@data = data
@ids = ids
end
def import
return if @data.empty? || @ids.empty?
create_main_table
create_temp_table
import_data
set_updated_at
update_main_table
end
private
def import_data
DB[temp_table_name.to_sym].import(columns_to_import, flattened_data)
end
def set_updated_at
DB[temp_table_name.to_sym].update(updated_at: DateTime.now)
end
def columns_to_import
@data.first.keys.map(&:to_sym)
end
def flattened_data
@data.map(&:values)
end
def create_temp_table
create_table(temp_table_name)
rescue Sequel::DatabaseDisconnectError
retry
end
def create_main_table
create_table(main_table_name)
rescue Sequel::DatabaseDisconnectError
retry
end
def update_main_table
inserted_columns = [*columns_to_import, :updated_at].join(',')
DB.transaction do
DB.run("delete from #{main_table_name} where #{id_name} in (#{@ids.join(',')})")
DB.run("insert into #{main_table_name} (#{inserted_columns})
(select #{inserted_columns} from #{temp_table_name})")
end
ensure
DB.drop_table(temp_table_name)
end
def temp_table_name
"#{main_table_name}_temp"
end
def create_table(table_name)
raise NotImplementedError
end
def id_name
raise NotImplementedError
end
def main_table_name
raise NotImplementedError
end
end