enclose db ops in a transaction

This commit is contained in:
Riccardo Berto 2021-03-01 15:14:05 +01:00
parent 841fac5634
commit 228a4e64f4

View File

@ -72,7 +72,7 @@ def process_gpx_files(tx: Connection):
owner = os.path.split(filepath)[-1].split('_workout-')[0] owner = os.path.split(filepath)[-1].split('_workout-')[0]
filename = f'workout-{os.path.split(filepath)[-1].split("_workout-")[1]}' filename = f'workout-{os.path.split(filepath)[-1].split("_workout-")[1]}'
print(f'Processing {filename}') print(f'Processing {filename}')
if list(db.execute(text('select exists(select from training where owner = :owner and filename = :filename)'), if list(tx.execute(text('select exists(select from training where owner = :owner and filename = :filename)'),
dict(owner=owner, filename=filename,),),)[0][0]: dict(owner=owner, filename=filename,),),)[0][0]:
os.remove(filepath) os.remove(filepath)
continue continue
@ -80,7 +80,7 @@ def process_gpx_files(tx: Connection):
gpx_file = gpxpy.parse(f) gpx_file = gpxpy.parse(f)
if gpx_file.creator != 'FitoTrack': if gpx_file.creator != 'FitoTrack':
raise ValueError('gpx file not generated by the FitoTrack app') raise ValueError('gpx file not generated by the FitoTrack app')
training_id = list(db.execute( training_id = list(tx.execute(
text(""" text("""
insert into training(owner, filename, type, description, moving_time, stopped_time, moving_distance, stopped_distance) values insert into training(owner, filename, type, description, moving_time, stopped_time, moving_distance, stopped_distance) values
(:owner, :filename, :type, :description, :moving_time, :stopped_time, :moving_distance, :stopped_distance) returning id (:owner, :filename, :type, :description, :moving_time, :stopped_time, :moving_distance, :stopped_distance) returning id
@ -97,7 +97,7 @@ def process_gpx_files(tx: Connection):
for track in gpx_file.tracks: for track in gpx_file.tracks:
for segment in track.segments: for segment in track.segments:
for point in segment.points: for point in segment.points:
db.execute(text(""" tx.execute(text("""
insert into training_data(training_id, t, geog, speed, elevation) insert into training_data(training_id, t, geog, speed, elevation)
values (:training_id, :t, :geog, :speed, :elevation) values (:training_id, :t, :geog, :speed, :elevation)
"""), """),