diff --git a/lib/Travelynx/Command/maintenance.pm b/lib/Travelynx/Command/maintenance.pm index ddd8345..961106d 100644 --- a/lib/Travelynx/Command/maintenance.pm +++ b/lib/Travelynx/Command/maintenance.pm @@ -143,27 +143,13 @@ sub run { for my $uid (@uids_to_delete) { say "Deleting uid ${uid}..."; - my $tokens_res = $db->delete( 'tokens', { user_id => $uid } ); - my $stats_res = $db->delete( 'journey_stats', { user_id => $uid } ); - my $journeys_res = $db->delete( 'journeys', { user_id => $uid } ); - my $transit_res = $db->delete( 'in_transit', { user_id => $uid } ); - my $hooks_res = $db->delete( 'webhooks', { user_id => $uid } ); - my $trwl_res = $db->delete( 'traewelling', { user_id => $uid } ); - my $lt_res = $db->delete( 'localtransit', { user_id => $uid } ); - my $password_res - = $db->delete( 'pending_passwords', { user_id => $uid } ); - my $user_res = $db->delete( 'users', { id => $uid } ); - + my $count = $self->app->users->delete( + uid => $uid, + db => $db, + in_transaction => 1 + ); printf( " %d tokens, %d monthly stats, %d journeys\n", - $tokens_res->rows, $stats_res->rows, $journeys_res->rows ); - - if ( $user_res->rows != 1 ) { - printf STDERR ( - "Deleted %d rows from users, expected 1. Rollback and abort.\n", - $user_res->rows - ); - exit(1); - } + $count->{tokens}, $count->{stats}, $count->{journeys} ); } $tx->commit; diff --git a/lib/Travelynx/Model/Users.pm b/lib/Travelynx/Model/Users.pm index c162f30..d52fd7e 100644 --- a/lib/Travelynx/Model/Users.pm +++ b/lib/Travelynx/Model/Users.pm @@ -451,6 +451,44 @@ sub unflag_deletion { ); } +sub delete { + my ( $self, %opt ) = @_; + + my $db = $opt{db} // $self->{pg}->db; + my $uid = $opt{uid}; + my $tx; + + if ( not $opt{in_transaction} ) { + $tx = $db->begin; + } + + my %res; + + $res{tokens} = $db->delete( 'tokens', { user_id => $uid } ); + $res{stats} = $db->delete( 'journey_stats', { user_id => $uid } ); + $res{journeys} = $db->delete( 'journeys', { user_id => $uid } ); + $res{transit} = $db->delete( 'in_transit', { user_id => $uid } ); + $res{hooks} = $db->delete( 'webhooks', { user_id => $uid } ); + $res{trwl} = $db->delete( 'traewelling', { user_id => $uid } ); + $res{lt} = $db->delete( 'localtransit', { user_id => $uid } ); + $res{password} = $db->delete( 'pending_passwords', { user_id => $uid } ); + $res{users} = $db->delete( 'users', { id => $uid } ); + + for my $key ( keys %res ) { + $res{$key} = $res{$key}->rows; + } + + if ( $res{users} != 1 ) { + die("Deleted $res{users} rows from users, expected 1. Rolling back.\n"); + } + + if ( not $opt{in_transaction} ) { + $tx->commit; + } + + return \%res; +} + sub set_password_hash { my ( $self, %opt ) = @_; my $db = $opt{db} // $self->{pg}->db;