Skip to content

Commit

Permalink
added update functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Xeferis committed Jul 24, 2024
1 parent dadf1fe commit a2c28a8
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
20 changes: 20 additions & 0 deletions main/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,26 @@ def add_content(self, tbl_name: str, cntnt: dict | list[dict],
raise errors[1]
self.db.commit()

def update_content(self, tbl_name: str, search: dict, cntnt: dict) -> None:
"""Update a dataset in a table
Args:
tbl_name (str): Table to update
search (dict): search term - see documentation for explaination
cntnt (dict): content you want to add. Single - see docs
"""
cur = self.db.cursor()
if self._check_tbl(tbl_name):
if not self._compare_cols(tbl_name, list(cntnt.keys())):
raise LookupError("Columns do not match destination table!")
sql_stmnt = f"""
UPDATE {tbl_name}
SET {list(cntnt.keys())[0]} = ?
WHERE {list(search.keys())[0]} = ?;
"""
cur.execute(sql_stmnt, [list(cntnt.values())[0], list(search.values())[0]])
self.db.commit()

def _compare_cols(self, tbl_name: str, clmns: list) -> bool:
"""Comparing input columns with the destination Table
Expand Down
18 changes: 18 additions & 0 deletions tests/basic_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,24 @@ def test_foreign_key_assignment_multiple(db):
assert test_table_content[0]["T_name"] == f"Foreignkeyrelation{i}", f"\
T_name Wert für Eintrag {i} stimmt nicht überein."

def test_update_content(db):
cur = db["op"].db.cursor()
cur.execute('CREATE TABLE test_tbl (id INTEGER PRIMARY KEY, name TEXT)')

cur.executemany('INSERT INTO test_tbl (name) VALUES (?)',
[('Alice',), ('Bob',), ('Charlie',)])
db["op"].db.commit()

db["op"].update_content('test_tbl', {'name': 'Bob'}, {'name': 'Robert'})
cur.execute('SELECT * FROM test_tbl WHERE name = ?', ('Bob',))
assert cur.fetchone() is None, "The entry was not updated."

cur.execute('SELECT * FROM test_tbl WHERE name = ?', ('Robert',))
assert cur.fetchone() is not None, "The entry was not updated."

cur.execute('SELECT COUNT(*) FROM test_tbl')
count = cur.fetchone()[0]
assert count == 3, "The number of entries is not correct."

if __name__ == "__main__":
pytest.main([r"./tests/basic_test.py", '-v'])

0 comments on commit a2c28a8

Please sign in to comment.