@@ -168,6 +168,60 @@ def update_schema_sizes_job(
168168 concurrency = concurrency ,
169169 )
170170
171+ @job ("Refresh Database Usage" )
172+ def refresh_database_usage_job (
173+ self ,
174+ private_ip : str ,
175+ mariadb_root_password : str ,
176+ database : str ,
177+ io_ops_limit : int = 200 ,
178+ concurrency : int = 20 ,
179+ ):
180+ self .analyze_tables_of_database (private_ip , mariadb_root_password , database )
181+ self .update_database_schema_size (
182+ private_ip , mariadb_root_password , database , io_ops_limit , concurrency
183+ )
184+
185+ @step ("Analyze Tables of Database" )
186+ def analyze_tables_of_database (self , private_ip : str , mariadb_root_password : str , database : str ):
187+ db = Database (private_ip , self .db_port , "root" , mariadb_root_password , database )
188+ success , output = db .execute_query ("SHOW TABLES;" )
189+ if not success :
190+ raise Exception (f"Failed to fetch tables for { database } : { output } " )
191+
192+ tables = [x [0 ] for x in output [0 ].get ("output" ).get ("data" )]
193+ if not tables :
194+ return
195+
196+ # Batch tables to avoid exceeding server statement-size limits / max_allowed_packet
197+ batch_size = 100
198+ for start in range (0 , len (tables ), batch_size ):
199+ batch = tables [start : start + batch_size ]
200+ tables_str = ", " .join (f"`{ t } `" for t in batch )
201+ query = f"ANALYZE TABLE { tables_str } ;"
202+ success , msg = db .execute_query (query )
203+ if not success :
204+ batch_index = start // batch_size + 1
205+ raise Exception (f"Failed to analyze tables for { database } in batch { batch_index } : { msg } " )
206+
207+ @step ("Update Database Schema Size" )
208+ def update_database_schema_size (
209+ self , private_ip : str , mariadb_root_password : str , database : str , io_ops_limit : int , concurrency : int
210+ ):
211+ result = calculate_table_usage (
212+ database ,
213+ use_sudo = True ,
214+ io_ops_limit = io_ops_limit ,
215+ concurrency = concurrency ,
216+ )
217+ size = max (0 , int (result .data_length + result .index_length ))
218+
219+ db = Database (private_ip , self .db_port , "root" , mariadb_root_password , "press_meta" )
220+ query = f"REPLACE INTO press_meta._schema_sizes_internal (`schema`, `size`) VALUES ('{ database } ', { size } );" # noqa: E501
221+ success , msg = db .execute_query (query , commit = True )
222+ if not success :
223+ raise Exception (f"Failed to update schema size for { database } : { msg } " )
224+
171225 @job ("Flush Tables" )
172226 def flush_tables_job (self , private_ip : str , mariadb_root_password : str ):
173227 self .flush_tables (private_ip , mariadb_root_password )
0 commit comments