diff --git a/share/patch_postgresql_db_zonemaster_backend_ver_7.0.0.pl b/share/patch_postgresql_db_zonemaster_backend_ver_7.0.0.pl index 67571864c..147e1394f 100644 --- a/share/patch_postgresql_db_zonemaster_backend_ver_7.0.0.pl +++ b/share/patch_postgresql_db_zonemaster_backend_ver_7.0.0.pl @@ -1,5 +1,7 @@ use strict; use warnings; +use JSON::PP; +use Encode; use DBI qw(:utils); @@ -10,69 +12,29 @@ if ( $config->DB_engine ne 'PostgreSQL' ) { die "The configuration file does not contain the PostgreSQL backend"; } -my $dbh = Zonemaster::Backend::DB::PostgreSQL->from_config( $config )->dbh; +my $db = Zonemaster::Backend::DB::PostgreSQL->from_config( $config ); +my $dbh = $db->dbh; + sub patch_db { + my $sth1 = $dbh->prepare('SELECT id, params from test_results', undef); + $sth1->execute; + while ( my $row = $sth1->fetchrow_hashref ) { + my $id = $row->{id}; + my $raw_params; - #################################################################### - # TEST RESULTS - #################################################################### - eval { - $dbh->do( 'ALTER TABLE test_results ADD COLUMN undelegated integer NOT NULL DEFAULT 0' ); - }; - if ($@) { - print "Error while changing DB schema: " . $@; - } + if (utf8::is_utf8($row->{params}) ) { + $raw_params = decode_json( encode_utf8 ( $row->{params} ) ); + } else { + $raw_params = decode_json( $row->{params} ); + } - $dbh->do( qq[ -update test_results set undelegated = test_results_undelegated.undelegated_bool::int -from ( - select - test_results.id, - ( - case when ds_filled.ds_filled is null then false else ds_filled.ds_filled end - or - case when ns_filled.ns_filled is null then false else ns_filled.ns_filled end - ) as undelegated_bool - from test_results - left join ( - select - count(*) > 0 as ds_filled, - id - from ( - select - jd.value, - id - from - ( - select json_array_elements(params->'ds_info') as ja, id - from test_results - ) as s1, - json_each_text(ja) as jd - ) as s2 - where value is not null and value::text != ''::text - group by id - ) as ds_filled on ds_filled.id = test_results.id - left join ( - select - count(*) > 0 as ns_filled, - id - from ( - select - jd.value, - id - from - ( - select json_array_elements(params->'nameservers') as ja, id - from test_results - ) as s1, - json_each_text(ja) as jd - ) as s2 - where value is not null and value::text != ''::text - group by id - ) as ns_filled on ns_filled.id = test_results.id -) as test_results_undelegated where test_results.id = test_results_undelegated.id; - ] ); + my $ds_info_values = scalar grep !/^$/, map { values %$_ } @{$raw_params->{ds_info}}; + my $nameservers_values = scalar grep !/^$/, map { values %$_ } @{$raw_params->{nameservers}}; + my $undelegated = $ds_info_values > 0 || $nameservers_values > 0 || 0; + + $dbh->do('UPDATE test_results SET undelegated = ? where id = ?', undef, $undelegated, $id); + } } patch_db();