@@ -146,15 +146,24 @@ pub(super) async fn run_csv_import(
146146 csv_import : & CsvImport ,
147147 request : & RequestInfo ,
148148) -> anyhow:: Result < ( ) > {
149- let file_path = request
149+ let named_temp_file = & request
150150 . uploaded_files
151151 . get ( & csv_import. uploaded_file )
152- . ok_or_else ( || anyhow:: anyhow!( "File not found" ) ) ?
153- . file
154- . path ( ) ;
155- let file = tokio:: fs:: File :: open ( file_path)
156- . await
157- . with_context ( || "opening csv" ) ?;
152+ . ok_or_else ( || {
153+ anyhow:: anyhow!(
154+ "The request does not contain a field named {:?} with an uploaded file.\n \
155+ Please check that :\n \
156+ - you have selected a file to upload, \n \
157+ - the form field name is correct.",
158+ csv_import. uploaded_file
159+ )
160+ } ) ?
161+ . file ;
162+ let file_path = named_temp_file. path ( ) ;
163+ let file_name = file_path. file_name ( ) . unwrap_or_default ( ) ;
164+ let file = tokio:: fs:: File :: open ( file_path) . await . with_context ( || {
165+ format ! ( "The CSV file {file_name:?} was uploaded correctly, but could not be opened" , )
166+ } ) ?;
158167 let buffered = tokio:: io:: BufReader :: new ( file) ;
159168 // private_get_mut is not supposed to be used outside of sqlx, but it is the only way to
160169 // access the underlying connection
@@ -165,9 +174,9 @@ pub(super) async fn run_csv_import(
165174 _ => run_csv_import_insert ( db, csv_import, buffered) . await ,
166175 }
167176 . with_context ( || {
177+ let table_name = & csv_import. table_name ;
168178 format ! (
169- "running CSV import from {} to {}" ,
170- csv_import. uploaded_file, csv_import. table_name
179+ "{file_name:?} was uploaded correctly, but its records could not be imported into the table {table_name}"
171180 )
172181 } )
173182}
@@ -179,13 +188,26 @@ async fn run_csv_import_postgres(
179188 csv_import : & CsvImport ,
180189 file : impl AsyncRead + Unpin + Send ,
181190) -> anyhow:: Result < ( ) > {
191+ log:: debug!( "Running CSV import with postgres" ) ;
182192 let mut copy_transact = db
183193 . copy_in_raw ( csv_import. query . as_str ( ) )
184194 . await
185- . with_context ( || "running COPY IN" ) ?;
186- copy_transact. read_from ( file) . await ?;
187- copy_transact. finish ( ) . await ?;
188- Ok ( ( ) )
195+ . with_context ( || "The postgres COPY FROM STDIN command failed." ) ?;
196+ log:: debug!( "Copy transaction created" ) ;
197+ match copy_transact. read_from ( file) . await {
198+ Ok ( _) => {
199+ log:: debug!( "Copy transaction finished successfully" ) ;
200+ copy_transact. finish ( ) . await ?;
201+ Ok ( ( ) )
202+ }
203+ Err ( e) => {
204+ log:: debug!( "Copy transaction failed with error: {e}" ) ;
205+ copy_transact
206+ . abort ( "The COPY FROM STDIN command failed." )
207+ . await ?;
208+ Err ( e. into ( ) )
209+ }
210+ }
189211}
190212
191213async fn run_csv_import_insert (
0 commit comments