1+ """Insert or update all index data"""
12import os
23import sys
34import sqlite3
4-
55import data_factory
6- os .chdir (os .path .dirname (os .path .abspath (__file__ )))
76
7+ # Set the working directory to the script's location to ensure relative paths work correctly
8+ os .chdir (os .path .dirname (os .path .abspath (__file__ )))
89
910def check_trle_doubles ():
11+ """
12+ Checks for duplicate entries in the Trle table.
13+
14+ This function connects to the 'index.db' SQLite database and queries the Trle table
15+ to identify any duplicate records based on certain fields (trleExternId, author,
16+ title, difficulty, duration, class, type, and release). It groups the results by
17+ these fields and counts occurrences. If any grouped records appear more than once,
18+ they are considered duplicates, and those entries are returned and printed.
19+ """
20+ # Connect to the SQLite database
1021 connection = sqlite3 .connect ('index.db' )
1122 cursor = connection .cursor ()
23+
24+ # Execute query to find duplicates
1225 result = query_return_fetchall ("""
1326 SELECT
14- tr.trleExternId,
15- tr.author,
16- tr.title,
17- tr.difficulty,
18- tr.duration,
19- tr.class,
20- tr.type,
21- tr.release,
22- COUNT(*) as record_count
23- FROM Trle AS tr
24- GROUP BY
25- tr.trleExternId,
26- tr.author,
27- tr.title,
28- tr.difficulty,
29- tr.duration,
30- tr.class,
31- tr.type,
32- tr.release
33- HAVING COUNT(*) > 1
34- ORDER BY record_count DESC;""" , None , cursor )
27+ tr.trleExternId,
28+ tr.author,
29+ tr.title,
30+ tr.difficulty,
31+ tr.duration,
32+ tr.class,
33+ tr.type,
34+ tr.release,
35+ COUNT(*) AS record_count
36+ FROM Trle AS tr
37+ GROUP BY
38+ tr.trleExternId,
39+ tr.author,
40+ tr.title,
41+ tr.difficulty,
42+ tr.duration,
43+ tr.class,
44+ tr.type,
45+ tr.release
46+ HAVING COUNT(*) > 1 -- Only include groups with more than one record
47+ ORDER BY record_count DESC;
48+ """ , None , cursor )
49+
50+ # Print the results, which includes any duplicate records found
3551 print (result )
52+
53+ # Close the database connection
3654 connection .close ()
3755
3856
3957def query_return_fetchall (query , params , cursor ):
58+ """
59+ Executes a SELECT query and fetches all results from the database.
60+
61+ Parameters:
62+ - query (str): The SQL query string to execute. Must be a SELECT query.
63+ - params (tuple or None): Parameters to bind to the query, or None if there are no parameters.
64+ - cursor (sqlite3.Cursor): The database cursor used to execute the query.
65+
66+ Returns:
67+ - list: The result set from the query as a list of tuples.
68+
69+ Raises:
70+ - Exits the program if the query is not a SELECT statement or if a database error occurs.
71+ """
4072 try :
73+ # Check if the query is a SELECT statement
4174 if not query .strip ().upper ().startswith ("SELECT" ):
4275 print ("You need to use SELECT with this function" )
4376 sys .exit (1 )
77+
78+ # Execute the query with or without parameters
4479 if not params :
4580 cursor .execute (query )
4681 else :
4782 cursor .execute (query , params )
83+
84+ # Fetch and return all rows from the executed query
4885 return cursor .fetchall ()
86+
4987 except sqlite3 .DatabaseError as db_error :
88+ # Handle database errors by printing an error message and exiting
5089 print (f"Database error occurred: { db_error } " )
5190 sys .exit (1 )
5291
5392
5493def query_return_id (query , params , cursor ):
94+ """
95+ Executes a query and returns an ID if available.
96+
97+ Parameters:
98+ - query (str): The SQL query to execute.
99+ - params (tuple): Parameters to bind to the query.
100+ - cursor (sqlite3.Cursor): The database cursor used to execute the query.
101+
102+ Returns:
103+ - int or None: The last inserted row ID if an INSERT query was run,
104+ or the first integer result from a SELECT query, if available.
105+ Returns None if no valid result is found.
106+
107+ Raises:
108+ - Exits the program if an integrity or other database error occurs.
109+ """
55110 try :
111+ # Execute the query with parameters
56112 cursor .execute (query , params )
113+
114+ # If the query is an INSERT statement, return the last inserted row ID
57115 if query .strip ().upper ().startswith ("INSERT" ):
58116 return cursor .lastrowid
117+
118+ # Fetch one result for non-INSERT queries
59119 result = cursor .fetchone ()
120+
121+ # Return the first element of the result if it's a non-negative integer
60122 if result and isinstance (result [0 ], int ) and result [0 ] >= 0 :
61123 return result [0 ]
124+
125+ # Return None if no valid result is found
62126 return None
127+
63128 except sqlite3 .IntegrityError as integrity_error :
129+ # Handle integrity errors (e.g., unique constraint violations)
64130 print (f"Integrity error occurred with parameters: { params } \n { integrity_error } " )
65131 sys .exit (1 )
132+
66133 except sqlite3 .DatabaseError as db_error :
134+ # Handle general database errors
67135 print (f"Database error occurred: { db_error } " )
68136 sys .exit (1 )
69137
70138
71139def query_run (query , params , cursor ):
140+ """
141+ Executes a query that does not return results (e.g., UPDATE, DELETE, or non-returning INSERT).
142+
143+ Parameters:
144+ - query (str): The SQL query to execute.
145+ - params (tuple): Parameters to bind to the query.
146+ - cursor (sqlite3.Cursor): The database cursor used to execute the query.
147+
148+ Raises:
149+ - Exits the program if an integrity or other database error occurs.
150+ """
72151 try :
152+ # Execute the query with parameters
73153 cursor .execute (query , params )
154+
155+ # Handle specific database errors
74156 except sqlite3 .IntegrityError as integrity_error :
157+ # Catch integrity-related issues, such as unique constraint violations
75158 print (f"Integrity error occurred with parameters: { params } \n { integrity_error } " )
76159 sys .exit (1 )
160+
77161 except sqlite3 .DatabaseError as db_error :
162+ # Catch any other database errors
78163 print (f"Database error occurred: { db_error } " )
79164 sys .exit (1 )
80165
@@ -197,6 +282,7 @@ def insert_trle_page(page):
197282
198283
199284def insert_trcustoms_page (page ):
285+ """Take the defined trcustom page data and insert every record in the database."""
200286 if not page .get ('levels' ):
201287 print ("Empty page!" )
202288 return
@@ -343,6 +429,7 @@ def get_or_insert(query_select, query_insert, value):
343429
344430
345431def get_trle_level_local_by_id (trle_id ):
432+ """Return trle level by id."""
346433 connection = sqlite3 .connect ('index.db' )
347434 cursor = connection .cursor ()
348435 if not isinstance (trle_id , int ) and trle_id > 0 :
@@ -388,6 +475,7 @@ def get_trle_level_local_by_id(trle_id):
388475
389476
390477def get_trcustoms_level_local_by_id (trcustoms_id ):
478+ """Return trcustoms level by id."""
391479 connection = sqlite3 .connect ('index.db' )
392480 cursor = connection .cursor ()
393481 if not isinstance (trcustoms_id , int ) and trcustoms_id > 0 :
@@ -439,7 +527,8 @@ def get_trcustoms_level_local_by_id(trcustoms_id):
439527 return level
440528
441529
442- def get_trle_page_local (offset , sortCreatedFirst = False ):
530+ def get_trle_page_local (offset , sort_latest_first = False ):
531+ """Get a trle page."""
443532 connection = sqlite3 .connect ('index.db' )
444533 cursor = connection .cursor ()
445534
@@ -458,6 +547,8 @@ def get_trle_page_local(offset, sortCreatedFirst=False):
458547 page ['offset' ] = offset
459548 page ['records_total' ] = rec
460549
550+ order_direction = 1 if sort_latest_first else 0
551+
461552 result = query_return_fetchall ("""
462553 SELECT
463554 tr.trleExternId,
@@ -476,11 +567,15 @@ def get_trle_page_local(offset, sortCreatedFirst=False):
476567 LEFT JOIN Class ON (Class.ClassID = tr.class)
477568 INNER JOIN Type ON (Type.TypeID = tr.type)
478569 GROUP BY tr.TrleID -- Group by the TrleID to get unique records
479- ORDER BY tr.release DESC, tr.trleExternId DESC
570+ ORDER BY
571+ CASE WHEN ? = 0 THEN tr.release END ASC,
572+ CASE WHEN ? = 0 THEN tr.trleExternId END ASC,
573+ CASE WHEN ? = 1 THEN tr.release END DESC,
574+ CASE WHEN ? = 1 THEN tr.trleExternId END DESC
480575 LIMIT ? OFFSET ?;
481- """ , (limit , offset ), cursor
482- )
483- # Process result to format the output as needed
576+ """ , (order_direction , order_direction , order_direction , order_direction , limit , offset ),
577+ cursor )
578+
484579 for row in result :
485580 level = data_factory .make_trle_level_data ()
486581 level ['trle_id' ] = row [0 ]
@@ -498,7 +593,8 @@ def get_trle_page_local(offset, sortCreatedFirst=False):
498593 return page
499594
500595
501- def get_trcustoms_page_local (page_number , sortCreatedFirst = False ):
596+ def get_trcustoms_page_local (page_number , sort_latest_first = False ):
597+ """Get a trcustoms page."""
502598 connection = sqlite3 .connect ('index.db' )
503599 cursor = connection .cursor ()
504600
@@ -519,10 +615,12 @@ def get_trcustoms_page_local(page_number, sortCreatedFirst=False):
519615 page ['total_pages' ] = total
520616 page ['records_total' ] = rec
521617
618+ order_direction = 1 if sort_latest_first else 0
619+
522620 result = query_return_fetchall ("""
523621 SELECT
524- tc.TrcustomsID ,
525- GROUP_CONCAT(DISTINCT Author.value) AS authors, -- Concatenate
622+ tc.trcustomsExternId ,
623+ GROUP_CONCAT(DISTINCT Author.value) AS authors,
526624 Title.value,
527625 GROUP_CONCAT(DISTINCT Tag.value) AS tags,
528626 GROUP_CONCAT(DISTINCT Genre.value) AS genres,
@@ -543,12 +641,16 @@ def get_trcustoms_page_local(page_number, sortCreatedFirst=False):
543641 LEFT JOIN Genre ON tgl.genreID = Genre.GenreID
544642 LEFT JOIN TrcustomsTagsList AS ttl ON ttl.trcustomsID = tc.TrcustomsID
545643 LEFT JOIN Tag ON ttl.tagID = Tag.TagID
546- GROUP BY tc.TrcustomsID -- Group by the TrcustomsID to get unique records
547- ORDER BY tc.release DESC, tc.TrcustomsID DESC
644+ GROUP BY tc.TrcustomsID
645+ ORDER BY
646+ CASE WHEN ? = 0 THEN tc.release END ASC,
647+ CASE WHEN ? = 0 THEN tc.trcustomsExternId END ASC,
648+ CASE WHEN ? = 1 THEN tc.release END DESC,
649+ CASE WHEN ? = 1 THEN tc.trcustomsExternId END DESC
548650 LIMIT ? OFFSET ?;
549- """ , (limit , offset ), cursor
550- )
551- # Process result to format the output as needed
651+ """ , (order_direction , order_direction , order_direction , order_direction , limit , offset ),
652+ cursor )
653+
552654 for row in result :
553655 level = data_factory .make_trcustoms_level_data ()
554656 level ['trcustoms_id' ] = row [0 ]
0 commit comments