-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.py
60 lines (49 loc) · 1.7 KB
/
db.py
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
import sqlite3
from pathlib import Path
from .classes import CLASSES
user_home_directory = Path.home()
DIR = user_home_directory / ".qgis"
DATABASE = DIR / "classes.db"
# Check if directory exists, if not, create it
if not DIR.exists():
DIR.mkdir(parents=True)
def setup_database():
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
# Check if the table exists already
cursor.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name='classes' ''')
if not cursor.fetchone():
# Create the table
cursor.execute('''
CREATE TABLE classes (
id INTEGER PRIMARY KEY,
class_id INTEGER,
class TEXT NOT NULL,
rgba TEXT NOT NULL
)
''')
# Pre-populate the table with data from CLASSES
for item in CLASSES:
cursor.execute('''
INSERT INTO classes (class_id, class, rgba)
VALUES (?, ?, ?)
''', (item['class_id'], item['class'], item['rgba']))
conn.commit()
conn.close()
def get_classes_from_db():
"""
Retrieve the 'classes' table data from SQLite database and return as a list of dictionaries.
Returns:
- List[dict]: List containing dictionaries for each record in the 'classes' table.
"""
# Connect to the database
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
# Execute the SELECT query
cursor.execute("SELECT class, rgba, class_id FROM classes")
rows = cursor.fetchall()
# Transform rows into a list of dictionaries
classes_list = [{"class": row[0], "rgba": row[1], "class_id": row[2]} for row in rows]
# Close the database connection
conn.close()
return classes_list