Skip to content

Commit 9e653ee

Browse files
committed
list and add zipfile
1 parent b5e7919 commit 9e653ee

File tree

6 files changed

+416
-232
lines changed

6 files changed

+416
-232
lines changed

CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ if(NOT TEST)
167167
${CMAKE_SOURCE_DIR}/database/scrape_trle.py
168168
${CMAKE_SOURCE_DIR}/database/scrape_trle_download.py
169169
${CMAKE_SOURCE_DIR}/database/tombll_add_data.py
170+
${CMAKE_SOURCE_DIR}/database/tombll_common.py
170171
${CMAKE_SOURCE_DIR}/database/tombll_get_data.py
171172
${CMAKE_SOURCE_DIR}/database/tombll_manage_data.py
172173
${CMAKE_SOURCE_DIR}/database/make_tombll_database.py

database/data_factory.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
"""Index dictionary data definitions"""
1+
"""Index dictionary data definitions."""
22

33

44
def make_trle_page_data():
5-
"""trle.net page, represents the same data as a page on the site"""
5+
"""trle.net page, represents the same data as a page on the site."""
66
return {
77
"offset": 0,
88
"records_total": 0,
@@ -11,7 +11,7 @@ def make_trle_page_data():
1111

1212

1313
def make_trle_level_data():
14-
"""trle.net record data"""
14+
"""trle.net record data."""
1515
return {
1616
"trle_id": 0,
1717
"author": "",
@@ -25,7 +25,7 @@ def make_trle_level_data():
2525

2626

2727
def make_trle_tombll_data():
28-
"""This is the app data at the moment"""
28+
"""Level data the app uses at the moment."""
2929
return {
3030
"title": "",
3131
"authors": [],
@@ -47,7 +47,7 @@ def make_trle_tombll_data():
4747

4848

4949
def make_trcustoms_page_data():
50-
"""trcustoms.org page, represents the same data as a page on the site"""
50+
"""trcustoms.org page, represents the same data as a page on the site."""
5151
return {
5252
"current_page": 0,
5353
"total_pages": 0,
@@ -57,7 +57,7 @@ def make_trcustoms_page_data():
5757

5858

5959
def make_trcustoms_level_data():
60-
"""trcustoms.org record data"""
60+
"""trcustoms.org record data."""
6161
return {
6262
"trcustoms_id": 0,
6363
"authors": [],
@@ -74,7 +74,7 @@ def make_trcustoms_level_data():
7474

7575

7676
def make_zip_file():
77-
"""trcustoms.org or TRLE zipfile"""
77+
"""trcustoms.org or TRLE zipfile."""
7878
return {
7979
"name": "",
8080
"size": 0.0,

database/setup_env.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ rm -fr .env
44
python3 -m venv .env
55
source .env/bin/activate
66
pip install pycurl types-pycurl tqdm types-tqdm cryptography types-cryptography \
7-
beautifulsoup4 types-beautifulsoup4 pillow types-pillow debugpy
7+
beautifulsoup4 types-beautifulsoup4 pillow types-pillow debugpy mypy

database/tombll_add_data.py

Lines changed: 30 additions & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,11 @@
1-
"""
2-
Take tombll json file and add it to the database
3-
"""
1+
"""Take tombll json file and add it to the database."""
42
import os
53
import sys
64
import sqlite3
7-
import json
85
import logging
96

107
import scrape_trle
11-
12-
13-
def get_tombll_json(path):
14-
"""Load and parse a JSON file from a specified path.
15-
16-
Attempts to open and read a JSON file, parsing its content into a dictionary.
17-
Handles errors for file not found, JSON decoding issues, and other I/O problems.
18-
19-
Args:
20-
path (str): The path to the JSON file.
21-
22-
Returns:
23-
dict: Parsed content of the JSON file.
24-
25-
Exits:
26-
Logs an error and exits the program if the file cannot be read or parsed.
27-
"""
28-
try:
29-
# Open the file with UTF-8 encoding
30-
with open(path, mode='r', encoding='utf-8') as json_file:
31-
try:
32-
# Parse and return JSON content
33-
return json.load(json_file)
34-
except json.JSONDecodeError as json_error:
35-
# Log and exit if JSON content is invalid
36-
logging.error("Error decoding JSON from file '%s': %s", path, json_error)
37-
sys.exit(1)
38-
except FileNotFoundError:
39-
# Log and exit if file is not found
40-
logging.error("File not found: '%s'", path)
41-
sys.exit(1)
42-
except IOError as file_error:
43-
# Log and exit if any other I/O error occurs
44-
logging.error("I/O error occurred while opening file '%s': %s", path, file_error)
45-
sys.exit(1)
46-
47-
48-
def query_return_id(query, params, con):
49-
"""Execute a SQL query and return an ID.
50-
51-
If the query is an INSERT, this function returns the last inserted row ID.
52-
For other queries, it fetches and returns the first integer result, if it exists and is
53-
non-negative.
54-
55-
Args:
56-
query (str): SQL query to execute.
57-
params (tuple): Parameters for the query.
58-
con (sqlite3.Connection): SQLite database connection.
59-
60-
Returns:
61-
int or None: The ID from the query result, or None if not found.
62-
63-
Exits:
64-
Logs an error and exits if a database error occurs.
65-
"""
66-
cursor = con.cursor()
67-
try:
68-
# Execute the query with provided parameters
69-
cursor.execute(query, params)
70-
71-
# Check if it's an INSERT query to return the last inserted row ID
72-
if query.strip().upper().startswith("INSERT"):
73-
return cursor.lastrowid
74-
75-
# For non-INSERT queries, fetch and validate the first result
76-
result = cursor.fetchone()
77-
if result and isinstance(result[0], int) and result[0] >= 0:
78-
return result[0]
79-
80-
return None # Return None if no valid ID is found
81-
82-
except sqlite3.DatabaseError as db_error:
83-
# Log the database error and exit
84-
logging.error("Database error occurred: %s", db_error)
85-
sys.exit(1)
86-
87-
88-
def query_run(query, params, con):
89-
"""Execute a SQL query with the provided parameters.
90-
91-
Args:
92-
query (str): The SQL query to execute.
93-
params (tuple): Parameters to substitute in the SQL query.
94-
con (sqlite3.Connection): SQLite database connection.
95-
96-
Exits:
97-
Logs an error and exits if a database error occurs.
98-
"""
99-
cursor = con.cursor()
100-
try:
101-
# Execute the query with provided parameters
102-
cursor.execute(query, params)
103-
except sqlite3.DatabaseError as db_error:
104-
# Log the database error and exit the program
105-
logging.error("Database error occurred: %s", db_error)
106-
sys.exit(1)
8+
import tombll_common
1079

10810

10911
def make_empty_null(value):
@@ -139,12 +41,12 @@ def add_authors_to_database(authors_array, level_id, con):
13941
query_insert_middle = "INSERT INTO AuthorList (authorID, levelID) VALUES (?, ?)"
14042

14143
# Try to get the existing author ID; if none, insert a new author and get its ID
142-
author_id = query_return_id(query_select_id, (author,), con)
44+
author_id = tombll_common.query_return_id(query_select_id, (author,), con)
14345
if author_id is None:
144-
author_id = query_return_id(query_insert, (author,), con)
46+
author_id = tombll_common.query_return_id(query_insert, (author,), con)
14547

14648
# Link the author with the level in AuthorList table
147-
query_run(query_insert_middle, (author_id, level_id), con)
49+
tombll_common.query_run(query_insert_middle, (author_id, level_id), con)
14850

14951

15052
def add_genres_to_database(genres_array, level_id, con):
@@ -166,12 +68,12 @@ def add_genres_to_database(genres_array, level_id, con):
16668
query_insert_middle = "INSERT INTO GenreList (genreID, levelID) VALUES (?, ?)"
16769

16870
# Try to get the existing genre ID; if none, insert a new genre and get its ID
169-
genre_id = query_return_id(query_select_id, (genre,), con)
71+
genre_id = tombll_common.query_return_id(query_select_id, (genre,), con)
17072
if genre_id is None:
171-
genre_id = query_return_id(query_insert, (genre,), con)
73+
genre_id = tombll_common.query_return_id(query_insert, (genre,), con)
17274

17375
# Link the genre with the level in GenreList table
174-
query_run(query_insert_middle, (genre_id, level_id), con)
76+
tombll_common.query_run(query_insert_middle, (genre_id, level_id), con)
17577

17678

17779
def add_tags_to_database(tags_array, level_id, con):
@@ -193,12 +95,12 @@ def add_tags_to_database(tags_array, level_id, con):
19395
query_insert_middle = "INSERT INTO TagList (tagID, levelID) VALUES (?, ?)"
19496

19597
# Try to get the existing tag ID; if not found, insert a new tag and get its ID
196-
tag_id = query_return_id(query_select_id, (tag,), con)
98+
tag_id = tombll_common.query_return_id(query_select_id, (tag,), con)
19799
if tag_id is None:
198-
tag_id = query_return_id(query_insert, (tag,), con)
100+
tag_id = tombll_common.query_return_id(query_insert, (tag,), con)
199101

200102
# Link the tag with the level in TagList table
201-
query_run(query_insert_middle, (tag_id, level_id), con)
103+
tombll_common.query_run(query_insert_middle, (tag_id, level_id), con)
202104

203105

204106
def add_zip_files_to_database(zip_files_array, level_id, con):
@@ -232,12 +134,12 @@ def add_zip_files_to_database(zip_files_array, level_id, con):
232134
)
233135

234136
# Insert the ZIP file and get its ID
235-
zip_id = query_return_id(query_insert, insert_args, con)
137+
zip_id = tombll_common.query_return_id(query_insert, insert_args, con)
236138

237139
# Link the ZIP file to the level in ZipList table
238140
query_insert_middle = "INSERT INTO ZipList (zipID, levelID) VALUES (?, ?)"
239141
middle_args = (zip_id, level_id)
240-
query_run(query_insert_middle, middle_args, con)
142+
tombll_common.query_run(query_insert_middle, middle_args, con)
241143

242144

243145
def add_screen_to_database(screen, level_id, con):
@@ -255,15 +157,16 @@ def add_screen_to_database(screen, level_id, con):
255157
# Ensure the screen URL matches the TRLE.net screens directory
256158
if screen.startswith("https://www.trle.net/screens/"):
257159
# Fetch the .webp image data for the screen
258-
webp_image_data = scrape_trle.get_trle_cover(screen.replace("https://www.trle.net/screens/", ""))
160+
webp_image_data = \
161+
scrape_trle.get_trle_cover(screen.replace("https://www.trle.net/screens/", ""))
259162

260163
# Insert the .webp image data into the Picture table and retrieve its ID
261164
query_insert_picture = "INSERT INTO Picture (data) VALUES (?)"
262-
picture_id = query_return_id(query_insert_picture, (webp_image_data,), con)
165+
picture_id = tombll_common.query_return_id(query_insert_picture, (webp_image_data,), con)
263166

264167
# Link the inserted picture to the specified level in the Screens table
265168
query_insert_screen = "INSERT INTO Screens (pictureID, levelID) VALUES (?, ?)"
266-
query_run(query_insert_screen, (picture_id, level_id), con)
169+
tombll_common.query_run(query_insert_screen, (picture_id, level_id), con)
267170

268171

269172
def add_screens_to_database(large_screens_array, level_id, con):
@@ -308,7 +211,7 @@ def add_level_to_database(data, con):
308211
)
309212

310213
# Execute the query and get the ID of the inserted level
311-
level_id = query_return_id(query, arg, con)
214+
level_id = tombll_common.query_return_id(query, arg, con)
312215

313216
# Log the current level ID for debugging or tracking purposes
314217
logging.info("Current tombll level_id: %s", level_id)
@@ -334,24 +237,24 @@ def add_info_to_database(data, con):
334237
info_difficulty_id = None
335238
if info_difficulty:
336239
query = "SELECT InfoDifficultyID FROM InfoDifficulty WHERE value = ?"
337-
info_difficulty_id = query_return_id(query, (info_difficulty,), con)
240+
info_difficulty_id = tombll_common.query_return_id(query, (info_difficulty,), con)
338241

339242
# Retrieve or assign InfoDurationID, or set to None if not specified
340243
info_duration = data.get('duration')
341244
info_duration_id = None
342245
if info_duration:
343246
query = "SELECT InfoDurationID FROM InfoDuration WHERE value = ?"
344-
info_duration_id = query_return_id(query, (info_duration,), con)
247+
info_duration_id = tombll_common.query_return_id(query, (info_duration,), con)
345248

346249
# Retrieve or assign InfoTypeID, allowing None if not specified
347250
info_type = data.get('type') or None
348251
query = "SELECT InfoTypeID FROM InfoType WHERE value = ?"
349-
info_type_id = query_return_id(query, (info_type,), con)
252+
info_type_id = tombll_common.query_return_id(query, (info_type,), con)
350253

351254
# Retrieve or assign InfoClassID, allowing None if not specified
352255
info_class = data.get('class') or None
353256
query = "SELECT InfoClassID FROM InfoClass WHERE value = ?"
354-
info_class_id = query_return_id(query, (info_class,), con)
257+
info_class_id = tombll_common.query_return_id(query, (info_class,), con)
355258

356259
# Insert a new Info record with the retrieved or default IDs
357260
query = (
@@ -369,7 +272,7 @@ def add_info_to_database(data, con):
369272
data.get('trcustoms_id') # TRCustoms ID if available
370273
)
371274

372-
return query_return_id(query, arg, con)
275+
return tombll_common.query_return_id(query, arg, con)
373276

374277

375278
def add_tombll_json_to_database(data, con):
@@ -407,8 +310,10 @@ def add_tombll_json_to_database(data, con):
407310
if len(sys.argv) != 2:
408311
logging.error("Usage: python3 addData.py FILE.json")
409312
sys.exit(1)
410-
DATA = get_tombll_json(sys.argv[1])
411-
CON = sqlite3.connect(os.path.dirname(os.path.abspath(__file__)) + '/tombll.db')
412-
add_tombll_json_to_database(DATA, CON)
413-
CON.commit()
414-
CON.close()
313+
main_data = tombll_common.get_tombll_json(sys.argv[1])
314+
main_con = sqlite3.connect(os.path.dirname(os.path.abspath(__file__)) + '/tombll.db')
315+
main_cur = main_con.cursor()
316+
main_cur.execute("BEGIN;")
317+
add_tombll_json_to_database(main_data, main_con)
318+
main_con.commit()
319+
main_con.close()

0 commit comments

Comments
 (0)