0

This script was running perfectly until I wrapped it in a function definition. I'm attempting to create a database for each player, and for some reason my database is saying it's locked immediately after I create it. Code is below.

Attempting to run this script returns True for the is_open() function, and I receive a sqlite3.OperationalError: database is locked exception after the sleep(5) call.

import sqlite3 as sq, os, sys, re, psutil
from time import sleep
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
#
def create_db(player):
    player = re.sub(' ','%20',player)
    if not os.path.exists(os.path.join(currentdir,'Players',player)):
        os.mkdir(os.path.join(currentdir,'Players',player))
    dbcon = sq.connect(os.path.join(currentdir,'Players',player,f'{player}-API.sqlite'))
    dbcur = dbcon.cursor()
    def is_open(path):
        for proc in psutil.process_iter():
            try:
                files = proc.open_files()
                if files:
                    for _file in files:
                        if _file.path == path:
                            return True
            except psutil.NoSuchProcess as err:
                print(err)
        return False
    print(is_open(os.path.join(currentdir,'Players',player,f'{player}-API.sqlite')))
    try:
        dbcur.execute("""CREATE TABLE IF NOT EXISTS "activities" (
            "date"  TEXT,
            "details"   TEXT,
            "text"  TEXT
        , "datetime"    INTEGER)""")
    except sq.OperationalError:
        print(f'Database error, waiting')
        sleep(5)
        dbcur.execute("""CREATE TABLE IF NOT EXISTS "activities" (
            "date"  TEXT,
            "details"   TEXT,
            "text"  TEXT
        , "datetime"    INTEGER)""")
    dbcon.commit()
    dbcon.close()
#
player = input(f'input player name to create files for> ')
create_db(player)

2 Answers2

0

Wrap your execute statements in with like so:

with dbcur:
    dbcur.execute("""CREATE TABLE IF NOT EXISTS...""")

You can also try setting WAL mode dbcur.execute("PRAGMA journal_mode=WAL")

More information here:

Treyten Carey
  • 641
  • 7
  • 17
0

I found the likely culprit. I do most of my coding on a Samba share, and the drives are accessed by a total of 4 machines. When coding on my code-server install, the databases are locked immediately by one of the machines. However, when coding on my desktop using my local Git folder, I have no problems whatsoever.