From 99441c02de13a62d880fe6e535020ed9d22b85d1 Mon Sep 17 00:00:00 2001 From: Erick Hitter Date: Mon, 30 Sep 2024 13:53:24 -0700 Subject: [PATCH] Improve error handling for trimming process If the trimming process fails, the database is left in an unknown and, often, unusable state. It may be too large, or may contain data that would've been removed in the post-trim cleanup. For safety, when the trim fails, discard the entire database. --- classes/class-init.php | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/classes/class-init.php b/classes/class-init.php index 52dc181..dc4c15b 100644 --- a/classes/class-init.php +++ b/classes/class-init.php @@ -42,22 +42,26 @@ final class Init extends PMC_WP_CLI { * @return void */ public function start(): void { - WP_CLI::line( 'Starting local-data process.' ); + try { + WP_CLI::line( 'Starting local-data process.' ); - do_action( 'pmc_wp_cli_local_data_before_processing' ); + do_action( 'pmc_wp_cli_local_data_before_processing' ); - $this->_drop_table(); - $this->_create_table(); + $this->_drop_table(); + $this->_create_table(); - $this->_query_for_ids_to_keep(); + $this->_query_for_ids_to_keep(); - new Clean_DB(); + new Clean_DB(); - do_action( 'pmc_wp_cli_local_data_after_processing' ); + do_action( 'pmc_wp_cli_local_data_after_processing' ); - $this->_drop_table(); + $this->_drop_table(); - WP_CLI::line( 'Process complete.' ); + WP_CLI::line( 'Process complete.' ); + } catch ( Throwable $throwable ) { + $this->_handle_error( $throwable ); + } } /** @@ -230,4 +234,18 @@ private function _get_query_args_instances(): array { $instance instanceof Query_Args ); } + + /** + * Handle errors during trimming process. + * + * @param Throwable $throwable Error details. + * @return void + */ + private function _handle_error( Throwable $throwable ): void { + global $wpdb; + + $wpdb->query( 'DROP DATABASE ' . DB_NAME ); + + WP_CLI::error( $throwable->getMessage() ); + } }