@@ -378,14 +378,14 @@ def set_metadata_via_service(request: Request) -> MetaDataSetResponse:
378
378
.options (joinedload (Service .users ))\
379
379
.one_or_none ()
380
380
381
- service_metadata = { mdatum .name : mdatum for mdatum in service .target_metadata }
382
-
383
- service_records = { rec .metadatum .name : rec for rec in metadataset .metadatumrecords if rec .metadatum .name in service_metadata }
384
-
385
381
# Return 404 if a resource could not be found
386
382
if metadataset is None or service is None :
387
383
raise HTTPNotFound ()
388
384
385
+ service_metadata = { mdatum .name : mdatum for mdatum in service .target_metadata }
386
+
387
+ service_records = { rec .metadatum .name : rec for rec in metadataset .metadatumrecords if rec .metadatum .name in service_metadata }
388
+
389
389
# Return 403 if the user has no permission to execute this service or the
390
390
# service has already been executed for this metadataset
391
391
if service .id in (sexec .service_id for sexec in metadataset .service_executions ):
@@ -413,9 +413,6 @@ def set_metadata_via_service(request: Request) -> MetaDataSetResponse:
413
413
# Validate submission access to the specified files
414
414
validation .validate_submission_access (db , db_files , {}, auth_user )
415
415
416
- # Validate the associations between files and records
417
- fnames , ref_fnames , val_errors = validation .validate_submission_association (db_files , { metadataset .site_id : metadataset })
418
-
419
416
# Validate the provided records
420
417
validate_metadataset_record (service_metadata , records , return_err_message = False , rendered = False )
421
418
@@ -426,9 +423,21 @@ def set_metadata_via_service(request: Request) -> MetaDataSetResponse:
426
423
db_rec .value = record_value
427
424
db .add (db_rec )
428
425
426
+ # Validate the associations between files and records
427
+ fnames , ref_fnames , val_errors = validation .validate_submission_association (db_files , { metadataset .site_id : metadataset }, ignore_submitted_metadatasets = True )
428
+
429
+ # If there were any validation errors, return 400
430
+ if val_errors :
431
+ entities , fields , messages = zip (* val_errors )
432
+ raise errors .get_validation_error (messages = messages , fields = fields , entities = entities )
433
+
434
+ # Given that validation hasn't failed, we know that file names are unique. Flatten the dict.
435
+ fnames = { k : v [0 ] for k , v in fnames .items () }
436
+
429
437
# Associate the files with the metadata
430
438
for fname , mdatrec in ref_fnames .items ():
431
439
mdatrec .file = fnames [fname ]
440
+ db .add (mdatrec )
432
441
433
442
# Create a service execution
434
443
sexec = ServiceExecution (
0 commit comments