From 8d4c32a652f10069a823ee1ab629dd6739d905f0 Mon Sep 17 00:00:00 2001 From: Marty Oehme Date: Sat, 28 Aug 2021 10:35:29 +0200 Subject: [PATCH] Add habit duplicate checking --- loop/habits.py | 54 ++++++++++++++++++++++++++++++++++++-------------- migrate.py | 3 ++- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/loop/habits.py b/loop/habits.py index d0ad05d..f2cf70d 100644 --- a/loop/habits.py +++ b/loop/habits.py @@ -1,32 +1,56 @@ def migrate(db, trackers): c = db.cursor() - tracker = trackers["cigarette"] - habit_dict = { - "archived": 0, - "color": 11, - "name": tracker["label"], - "description": "smoking", - "freq_den": 1, - "freq_num": 1, - "highlight": 0, - "position": 4, - "question": "Did you smoke today punk?", - "uuid": tracker["id"], - } - add_to_database(c, habit_dict) + habits = trackers_to_habits(trackers) + for habit in habits: + existing_habit = check_habit_duplicate(c, habit) + if not existing_habit: + add_to_database(c, habit) + else: + print(f"Found duplicate Habit: {existing_habit} - skipping.") # DEBUGGING c.execute("""select * from Habits""") print(c.fetchall()) +def trackers_to_habits(trackers): + habits = [] + # for each list entry tracker dict transform to habit dict + for tracker_name in trackers.keys(): + t = trackers[tracker_name] + habits.append( + { + "archived": 0 if t["hidden"] == False else 1, + "color": 11, + "description": t["label"], + "freq_den": 1, + "freq_num": 1, + "highlight": 0, + "name": f"{t['emoji']} {t['label']}", + "question": "", + "unit": "" if t["uom"] == "num" else t["uom"], + "uuid": t["id"], + } + # FIXME conditional for ranges (if type = range > habits[-1]['type'] = intforrangetype; habits[-1]['max'] =) + ) + return habits + + +def check_habit_duplicate(cursor, habit): + cursor.execute("select name from Habits where uuid = ?", [habit["uuid"]]) + name = cursor.fetchone() + if name: + return name[0] + return False + + def add_to_database(cursor, habit_dict): placeholder = ", ".join("?" * len(habit_dict)) columns = ", ".join(habit_dict.keys()) - values = list(habit_dict.values()) sql = "insert into `{table}` ({columns}) values ({values});".format( table="Habits", columns=columns, values=placeholder ) + values = list(habit_dict.values()) cursor.execute(sql, values) diff --git a/migrate.py b/migrate.py index 5ff8ef8..5dd77e2 100755 --- a/migrate.py +++ b/migrate.py @@ -2,6 +2,8 @@ import json import sys + +# TODO is pandas necessary? should only be for csv, not built for now import pandas as pd import loop.migration as loop @@ -45,7 +47,6 @@ def verify_continue(data): if __name__ == "__main__": # load nomie json nomie_data = load_file(sys.argv[1]) - # DISABLED FOR DEBUGGING verify_continue(nomie_data) trackers = nomie_data["trackers"] events = nomie_data["events"]