-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_compound.py
More file actions
61 lines (50 loc) · 2.1 KB
/
Copy pathremove_compound.py
File metadata and controls
61 lines (50 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import sqlite3
import os
import argparse
# Configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATABASE_PATH = os.path.join(BASE_DIR, 'database.db')
def remove_compound(name: str):
"""
Removes a compound from the database by its common or IUPAC name.
The search is case-insensitive.
"""
if not os.path.exists(DATABASE_PATH):
print(f"Error: Database file not found at {DATABASE_PATH}")
return
conn = None
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
# Find matching compounds before deleting to provide feedback
# Using COLLATE NOCASE for case-insensitive comparison, as used elsewhere in the app
find_sql = "SELECT compound_id, common_name, iupac_name FROM compounds WHERE common_name = ? COLLATE NOCASE OR iupac_name = ? COLLATE NOCASE"
cursor.execute(find_sql, (name, name))
matches = cursor.fetchall()
if not matches:
print(f"No compound matching '{name}' found in the database.")
return
print(f"Found {len(matches)} record(s) matching '{name}':")
for match in matches:
print(f" - ID: {match[0]}, Common Name: {match[1]}, IUPAC Name: {match[2]}")
# Delete the records
delete_sql = "DELETE FROM compounds WHERE common_name = ? COLLATE NOCASE OR iupac_name = ? COLLATE NOCASE"
cursor.execute(delete_sql, (name, name))
deleted_count = cursor.rowcount
conn.commit()
print(f"\nSuccessfully deleted {deleted_count} record(s) for '{name}'.")
except sqlite3.Error as e:
print(f"A database error occurred: {e}")
if conn:
conn.rollback()
finally:
if conn:
conn.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Remove a compound from the database by name.",
epilog="Example usage:\n python remove_compound.py \"Polymyxin E\""
)
parser.add_argument("name", type=str, help="The common or IUPAC name of the compound to remove.")
args = parser.parse_args()
remove_compound(args.name)