pythonsqlitesqlite3-python

How to toggle sometimes one and sometimes more than one item in Sqlite3?


def toggle_status_of_item(self, item_id: str):
    sql = """UPDATE table
             SET status = CASE status
                          WHEN 0 THEN 1 
                          ELSE 0 END
             WHERE item_id = ?"""
    self.cur.execute(sql, (item_id,))
    self.con.commit()

The above method toggles the boolean value in column status of a given item_id. However, item_id can sometimes be plural, i.e. it may contain more than one value, which I have no control of.

How should I rewrite the sqlite3 doc-string to toggle sometimes one and sometimes more than one item_id? Other than changing item_id: str to item_id: list, how do I write the SQLite commands to apply the CASE statement to a list of item ids? Thank you in advance.

Below method will do what I want. However, it is not a pure SQLITE approach. I would like to know the SQL commands to achieve the below.

def toggle_status_of_item(self, item_ids: list):
    sql = """UPDATE table
            SET status = CASE status
                         WHEN 0 THEN 1 
                         ELSE 0 END
            WHERE item_id = ?"""
    for id in item_ids:
        self.cur.execute(sql, (id,))
    self.con.commit()

Solution

  • (Answering assuming item_id uses a comma (,) to delineate between distinct item_ids for which this query should be run.)

    Create a List[Tuple] of item_ids, then use cur.executemany():

    def toggle_status_of_item(self, item_id: str):
        item_ids = list(map(lambda x: (x,), item_id.split(",")))
        sql = """UPDATE table
                 SET status = CASE status
                              WHEN 0 THEN 1 
                              ELSE 0 END
                 WHERE item_id = ?"""
        self.cur.executemany(sql, item_ids)
        self.con.commit()