Skip to content

Commit

Permalink
feat(TestRuns): create initial runs from existing alerts
Browse files Browse the repository at this point in the history
  • Loading branch information
domtra committed Oct 2, 2024
1 parent 5ff2347 commit e4c6156
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
4 changes: 2 additions & 2 deletions includes/features/class-service.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use Vrts\Services\Test_Service;

class Service {
const DB_VERSION = '1.1';
const DB_VERSION = '1.2';
const SERVICE = 'vrts_service';
const BASE_URL = VRTS_SERVICE_ENDPOINT;

Expand All @@ -27,7 +27,7 @@ public static function connect_service() {
if ( self::is_connected() && ! self::has_secret() ) {
self::create_secret();
}
if ( $installed_version && version_compare( $installed_version, '1.1', '<' ) ) {
if ( $installed_version && version_compare( $installed_version, '1.2', '<' ) ) {
$service_project_id = get_option( 'vrts_project_id' );
$service_api_route = 'sites/' . $service_project_id;

Expand Down
46 changes: 46 additions & 0 deletions includes/tables/class-test-runs-table.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ public static function install_table() {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );

if ( empty( $installed_version ) ) {
static::create_runs_from_alerts();
}

update_option( $option_name, self::DB_VERSION );
}//end if
}
Expand All @@ -60,4 +64,46 @@ public static function uninstall_table() {

delete_option( self::TABLE_NAME . '_db_version' );
}

/**
* Migrate alerts from the old table.
*/
public static function create_runs_from_alerts() {
global $wpdb;
$alerts_table = Alerts_Table::get_table_name();
$tests_table = Tests_Table::get_table_name();
$runs_table = self::get_table_name();

$sql = "SELECT
a.id as id,
a.target_screenshot_finish_date as finished_at,
t.id as test_id
FROM {$alerts_table} a
JOIN {$tests_table} t
ON t.post_id = a.post_id
WHERE a.test_run_id IS NULL;
";

$alerts = $wpdb->get_results( $sql );

$test_runs = array_map(function ($alert) {
return [
'tests' => maybe_serialize( [ $alert->test_id ] ),
'alerts' => maybe_serialize( [ $alert->id ] ),
'trigger' => 'legacy',
'started_at' => $alert->finished_at,
'finished_at' => $alert->finished_at,
];
}, $alerts);

$test_runs_values = implode( ',', array_map(function ($run) {
return "('" . implode( "','", array_map('esc_sql', $run)) . "')";
}, $test_runs));

// insert all test runs with single query
$wpdb->query( "INSERT INTO {$runs_table} (tests, alerts, `trigger`, started_at, finished_at) VALUES " . $test_runs_values . ';' );

// update test_run_id in alerts table from newly created test runs based on alerts column
$wpdb->query( "UPDATE {$alerts_table} a JOIN {$runs_table} r ON r.alerts LIKE CONCAT('%\"', a.id, '\"%') SET a.test_run_id = r.id;" );
}
}

0 comments on commit e4c6156

Please sign in to comment.