Python Forum
Using SQLAlchemy, prevent SQLite3 table update by multiple program instances
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using SQLAlchemy, prevent SQLite3 table update by multiple program instances
#1
Question 
I have a python program that is using SQLAlchemy to work with an SQLite3 database.

One function I have will read a counter from a table from a specific row, increment the counter, and write/commit the updated value back to the table.

My issue is that the counter is not incrementing consistently. There are multiple instances of my Python program running, so I am thinking that multiple instances are reading the table and incrementing at the same time, basically corrupting the counter.

My table is simple. Column "chassis" holds a device name, and column "counter" holds the number of active connections on that device.

How can I write this so that only one instance at a time can update the counter?

This is the function I am using to increment the connection counter:
    def _add_new_connection(self):
        """ Ensure we don't have too many connections on a device """

        hostname = self.get_host_name()

        loop = 300   # How many seconds to wait for an opening to be free for an agent.
        retry_time = 10   # How many seconds between tries
        while loop > 0:
            loop -= retry_time

            with self.__get_db() as db:

                # Find an entry for this chassis
                record = db.query(models.Agents).filter(models.Agents.chassis == hostname).first()

                # If no entry was found, we will make one
                if not record:
                    record = models.Agents()
                    record.chassis = hostname
                    record.counter = 1

                    db.add(record)
                    db.commit()

                    break

                # Max of 3 connections
                elif record.counter < 3:
                    record.counter = record.counter + 1

                    db.add(record)
                    db.commit()

                    break

            time.sleep(retry_time)

            print(f"{hostname} has {record.counter} connections and is waiting", flush=True)
        
        else:
            # Loop timed out
            return False

            print(f"{hostname} has {record.counter} connections and is connected", flush=True)
        
        return True
Reply
#2
can you use autoincrement?
see https://www.sqlite.org/autoinc.html
Reply
#3
# Max of 3 connections
elif record.counter < 3:
record.counter = record.counter + 1

db.add(record)
db.commit()
Reply
#4
I found the bug causing my issue. It wasn't with the code I shared. It was a fault in how I was cleaning up the connections when I was done with them.

When my code was finished with a connection, it would make a call to agent.disconnect(), which decremented the connection counter. Later, Python would delete the agent object and part of that process was also to call agent.disconnect(). This resulted in my counter going down by two instead of one when I was finished with the connection.

I now ensure that I have a connection before I do a disconnect.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Rows not adding to sqlite3 database using SQLAlchemy Calab 11 1,713 Jun-02-2023, 05:53 PM
Last Post: bowlofred
  extract table from multiple pages sshree43 8 5,327 Dec-12-2022, 10:34 AM
Last Post: arvin
  Multiprocessing Pool Multiple Instances How to Kill by Pool ID sunny9495 0 766 Nov-16-2022, 05:57 AM
Last Post: sunny9495
  Python: re.findall to find multiple instances don't work but search worked Secret 1 1,228 Aug-30-2022, 08:40 PM
Last Post: deanhystad
Smile How we can prevent screen recording murad_ali 3 1,845 Jul-29-2022, 10:29 AM
Last Post: DeaD_EyE
  sqlalchemy could not find table 3lnyn0 4 6,684 Mar-30-2022, 12:36 PM
Last Post: Larz60+
  How to prevent python from going to new line in for loop? idknuttin 3 4,948 Feb-11-2022, 05:40 AM
Last Post: deanhystad
  How do you format Update statement with multiple conditions hammer 4 2,110 Dec-16-2021, 10:49 PM
Last Post: hammer
  SQLALCHEMY - Not selecting data from table jamesaarr 4 2,244 Nov-02-2021, 03:02 PM
Last Post: Larz60+
  Slittping table into Multiple tables by rows drunkenneo 1 2,068 Oct-06-2021, 03:17 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020