@@ -8,8 +8,11 @@ def setup_db
88 uploaded_file = params [ :file ]
99
1010 if uploaded_file . present?
11- save_path = upload_db ( uploaded_file )
12- redirect_to segments_dashboard_path , notice : "DB uploaded successfully to #{ save_path } ."
11+ if ( save_path = upload_db ( uploaded_file ) )
12+ redirect_to segments_dashboard_path , notice : "DB uploaded successfully to #{ save_path } ."
13+ else
14+ redirect_to segments_setup_db_path , alert : "Failed to upload the database. Please ensure the file is a valid zip containing a .db file."
15+ end
1316 else
1417 redirect_to segments_setup_db_path , alert : "Please select a file."
1518 end
@@ -95,7 +98,7 @@ def authorize_access!
9598 end
9699
97100 def check_segments_database
98- models = segment_modals
101+ models = segment_models
99102 missing_models = models . reject { |model | model . table_exists? }
100103
101104 if missing_models . any?
@@ -106,7 +109,7 @@ def check_segments_database
106109 redirect_to segments_setup_db_path , alert : "Segments database is missing" and return
107110 end
108111
109- def segment_modals
112+ def segment_models
110113 [
111114 SegmentStats ::DetectionStat ,
112115 SegmentStats ::FailureStat ,
@@ -117,13 +120,37 @@ def segment_modals
117120 end
118121
119122 def upload_db ( uploaded_file )
120- save_path = Rails . root . join ( "tmp" , "segments_database.db" )
123+ require "zip"
124+ tmp_dir = Rails . root . join ( "tmp" )
125+ db_output_path = tmp_dir . join ( "segments_database.db" )
126+ zip_temp_path = tmp_dir . join ( "segments_upload.zip" )
127+
128+ File . open ( zip_temp_path , "wb" ) { |f | f . write ( uploaded_file . read ) }
129+
130+ db_file = nil
131+ Zip ::File . open ( zip_temp_path ) do |zip_file |
132+ zip_file . each do |entry |
133+ if entry . name . ends_with? ( ".db" )
134+ entry . extract ( db_output_path ) { true }
135+ db_file = db_output_path
136+ break
137+ end
138+ end
139+ end
140+
141+ File . delete ( zip_temp_path ) if File . exist? ( zip_temp_path )
142+
143+ if db_file . present?
144+ SegmentStats ::Base . establish_connection (
145+ adapter : 'sqlite3' ,
146+ database : db_file . to_s
147+ )
121148
122- File . open ( save_path , "wb" ) do |file |
123- file . write ( uploaded_file . read )
149+ segment_models . each ( &:reset_column_information )
124150 end
125151
126- segment_modals . each ( &:reset_column_information )
127- save_path
152+ db_file
153+ rescue StandardError => e
154+ # Do nothing
128155 end
129156end
0 commit comments