diff --git a/app.py b/app.py index c59f2a1..fb2af18 100644 --- a/app.py +++ b/app.py @@ -384,6 +384,11 @@ def get_workout_note(person_id, workout_id): return render_template('partials/workout_note.html', person_id=person_id, workout_id=workout_id, note=workout['Note']) +@app.teardown_appcontext +def closeConnection(exception): + db.close_connection() + + @app.template_filter('list_to_string') def list_to_string(list): return [str(i) for i in list] diff --git a/db.py b/db.py index 5823470..734b8b4 100644 --- a/db.py +++ b/db.py @@ -3,6 +3,8 @@ import psycopg2 from psycopg2.extras import RealDictCursor from datetime import datetime from urllib.parse import urlparse +from flask import g + from utils import get_all_exercises_from_topsets, get_stats_from_topsets, get_workouts @@ -10,26 +12,41 @@ from utils import get_all_exercises_from_topsets, get_stats_from_topsets, get_wo class DataBase(): def __init__(self, app): db_url = urlparse(os.environ['DATABASE_URL']) + # if db_url is null then throw error + if not db_url: + raise Exception("No DATABASE_URL environment variable set") - self.conn = psycopg2.connect( - database=db_url.path[1:], - user=db_url.username, - password=db_url.password, - host=db_url.hostname, - port=db_url.port - ) + def getDB(self): + db = getattr(g, 'database', None) + if db is None: + db_url = urlparse(os.environ['DATABASE_URL']) + g.database = psycopg2.connect( + database=db_url.path[1:], + user=db_url.username, + password=db_url.password, + host=db_url.hostname, + port=db_url.port + ) + db = g.database + return db + + def close_connection(exception): + db = getattr(g, 'database', None) + if db is not None: + db.close() def execute(self, query, args=(), one=False, commit=False): - cur = self.conn.cursor(cursor_factory=RealDictCursor) + conn = self.getDB() + cur = conn.cursor(cursor_factory=RealDictCursor) cur.execute(query, args) rv = None if cur.description is not None: rv = cur.fetchall() if commit: try: - self.conn.commit() + conn.commit() except: - self.conn.rollback() + conn.rollback() cur.close() return (rv[0] if rv else None) if one else rv @@ -119,6 +136,14 @@ class DataBase(): def create_workout(self, person_id): now = datetime.now() date_string = now.strftime('%Y-%m-%d') + # check if a workout has already been created for this person today that doesnt contain any topsets and if so return the WorkoutId + workout = self.execute('SELECT workout_id AS "WorkoutId" FROM workout WHERE person_id=%s AND start_date=%s AND workout_id NOT IN (SELECT workout_id FROM topset)', [ + person_id, date_string], one=True) + if workout: + print( + f'Workout already created for PersonId {person_id} starting at {date_string} so returning WorkoutId {workout["WorkoutId"]} rather then creating new workout') + return workout['WorkoutId'] + print( f'Creating workout for PersonId {person_id} starting at {date_string}') new_workout = self.execute('INSERT INTO workout (person_id, start_date) VALUES (%s, %s) RETURNING workout_id AS "WorkoutId"', [