[Help needed] Why the function I created inserts the value in the database multiple times? How to solve it?

TLDR: I created a function that gets the difference between the current time and the time the Editor (Add Card) window was opened then insert this value into a database every time a card is added. The problem is that it inserts the value multiple times (the number of insertions starts with two and increases by one every time I close and reopen the Editor window). How to solve this? (code and print screen below).

P.s. I’ve tried to set the “timeStamp” row to be UNIQUE but it returns the following error: sqlite3.IntegrityError: UNIQUE constraint failed: time.timeStamp. Then returns this error if I try to add another card: sqlite3.OperationalError: database is locked

Here’s the code:

from aqt import editor, gui_hooks, mw
from aqt.addcards import AddCards
from aqt.utils import tooltip
from aqt.utils import *
from aqt.forms import addcards
from datetime import datetime, timedelta
from time import *
import math
import sqlite3
import sys
import pathlib

__here__ = pathlib.Path(__file__).resolve().parent
db_file = str(__here__ / 'user_files' / "time.db")
db = sqlite3.connect(db_file)
cursor = db.cursor()
cursor.execute(
    '''CREATE TABLE IF NOT EXISTS time (
	id	INTEGER UNIQUE,
    timeStamp INTEGER,
	registro_de_valores INTEGER,
    nome TEXT,
	PRIMARY KEY(id AUTOINCREMENT)
)''')

class ProgressBar(object):
    
    def __init__(self):

        gui_hooks.editor_did_init.append(self.editor_init_hook)
        
    def editor_init_hook(self, ed: editor.Editor):
        
        gui_hooks.add_cards_did_init.append(lambda o: self.inject_pBar(ed))
        gui_hooks.add_cards_did_init.append(lambda o: self.startTimebox())
        gui_hooks.add_cards_did_init.append(lambda o: self.startTime())
        gui_hooks.add_cards_did_add_note.append(lambda o: self.timeDifference())
        gui_hooks.add_cards_did_add_note.append(lambda o: self.insertValuesToDatabase())
        gui_hooks.add_cards_did_add_note.append(lambda o: self.selectLastValue())
        gui_hooks.add_cards_did_add_note.append(lambda o: self.update_pBar())
        gui_hooks.add_cards_did_add_note.append(lambda o: self.check_timebox())

    def startTime(self) -> None:
            self.start_time = round(monotonic())
            return self.start_time
    
    def timeDifference(self):
            now = round(monotonic()) 
            self.str_now = gmtime(now)
            str_start_time = gmtime(self.start_time)
            self.now_formatted = strftime('%H:%M:%S', self.str_now)
            self.start_time_formatted = strftime('%H:%M:%S', str_start_time)
            
            self.time_difference = round(now) - round(self.start_time) 
            self.time_difference_formatted = strftime('%H:%M:%S', gmtime(self.time_difference)) 
            
            return self.time_difference
    
    def insertValuesToDatabase(self):
            __here__ = pathlib.Path(__file__).resolve().parent
            db_file = str(__here__ / 'user_files' / "time.db")
            db = sqlite3.connect(db_file)
            cursor = db.cursor()
            timestamp = round(time())
    
            self.insert_value = cursor.execute('''INSERT INTO time(timeStamp, registro_de_valores) VALUES (?, ?)''', [timestamp, self.time_difference])
            db.commit()

      def selectLastValue(self):
              __here__ = pathlib.Path(__file__).resolve().parent
              db_file = str(__here__ / 'user_files' / "time.db")
              db = sqlite3.connect(db_file)
              cursor = db.cursor()
              self.select_last_value = cursor.execute('''SELECT registro_de_valores FROM time ASC''').fetchall()
              self.last_value = self.resgatar_valores_da_planilha[0][0]
              return self.last_value

Picture of the database:

My guess is that this is caused by the fact that you’re not unregistering the functions when the editor is closed. Try something like gui_hooks.add_cards_did_init.remove(func) somewhere. Note that you’ll need to first save the lambda references you’re creating when registering the hooks to be able to remove them later.

4 Likes

Thank you @abdo, your answer helped me to solve it.
I moved the gui_hooks.add_cards_did_add_note.append(lambda o: self.insertValuesToDatabase()) from def editor_init_hook(self, ed: editor.Editor): to def __init__(self): and the problem was gone.