habitmove/loop/habits.py

54 lines
1.7 KiB
Python

def migrate(db, trackers):
c = db.cursor()
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.")
return habits
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,
"color": 11 if t.get("score", 0) != "-1" else 0,
"description": t["tag"],
"freq_den": 1,
"freq_num": 1,
"highlight": 0,
"name": f"{t['emoji']} {t['label']}",
"question": "",
"position": 0,
"unit": "" if t["uom"] == "num" else t["uom"],
"uuid": t["id"],
}
)
if t["type"] == "range" and len(habits) > 0:
habits[-1]["type"] = "1"
habits[-1]["target_value"] = t["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())
sql = "insert into `{table}` ({columns}) values ({values});".format(
table="Habits", columns=columns, values=placeholder
)
values = list(habit_dict.values())
cursor.execute(sql, values)