2021-08-28 07:54:41 +00:00
|
|
|
def migrate(db, trackers):
|
|
|
|
c = db.cursor()
|
2021-08-28 08:35:29 +00:00
|
|
|
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.")
|
2021-08-28 21:03:12 +00:00
|
|
|
return habits
|
2021-08-28 07:54:41 +00:00
|
|
|
|
|
|
|
|
2021-08-28 08:35:29 +00:00
|
|
|
def trackers_to_habits(trackers):
|
|
|
|
habits = []
|
|
|
|
for tracker_name in trackers.keys():
|
|
|
|
t = trackers[tracker_name]
|
|
|
|
habits.append(
|
|
|
|
{
|
|
|
|
"archived": 0 if t["hidden"] == False else 1,
|
2021-08-28 08:46:57 +00:00
|
|
|
"color": 11 if t.get("score", 0) != "-1" else 0,
|
2021-08-28 21:03:12 +00:00
|
|
|
"description": t["tag"],
|
2021-08-28 08:35:29 +00:00
|
|
|
"freq_den": 1,
|
|
|
|
"freq_num": 1,
|
|
|
|
"highlight": 0,
|
|
|
|
"name": f"{t['emoji']} {t['label']}",
|
|
|
|
"question": "",
|
2021-08-28 08:59:20 +00:00
|
|
|
"position": 0,
|
2021-08-28 08:35:29 +00:00
|
|
|
"unit": "" if t["uom"] == "num" else t["uom"],
|
|
|
|
"uuid": t["id"],
|
|
|
|
}
|
|
|
|
)
|
2021-08-28 20:03:45 +00:00
|
|
|
if t["type"] == "range" and len(habits) > 0:
|
|
|
|
habits[-1]["type"] = "1"
|
|
|
|
habits[-1]["target_value"] = t["max"]
|
2021-08-28 08:35:29 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2021-08-29 08:13:28 +00:00
|
|
|
def add_to_database(cursor, habit):
|
|
|
|
"""Takes a habit in the form of a dictionary and inserts it into the Habits table.
|
|
|
|
Parameters:
|
|
|
|
cursor (db.cursor): SQL executing cursor
|
|
|
|
habit (dict): A Loop habit to be added to the database. Must contain a minimum of
|
|
|
|
'archived','color','description','freq_den','freq_num','highlight','name',
|
|
|
|
'question','position','unit','uuid' as keys.
|
|
|
|
"""
|
|
|
|
|
|
|
|
placeholder = ", ".join("?" * len(habit))
|
|
|
|
columns = ", ".join(habit.keys())
|
2021-08-28 07:54:41 +00:00
|
|
|
sql = "insert into `{table}` ({columns}) values ({values});".format(
|
|
|
|
table="Habits", columns=columns, values=placeholder
|
|
|
|
)
|
2021-08-29 08:13:28 +00:00
|
|
|
values = list(habit.values())
|
2021-08-28 07:54:41 +00:00
|
|
|
cursor.execute(sql, values)
|