Falls der Datenbestand des jeweiligen Mandanten keine NULL-Buchungen besitzt: alter...
[kivitendo-erp.git] / sql / Pg-upgrade2 / add_more_constraints_fibu_projekt_xplace.pl
1 # @tag: add_more_constraints_fibu_projekt_xplace3
2 # @description: Falls der Datenbestand es unproblematisch hergibt, ein paar 'schärfere' Constraints für die acc_trans gesetzt. Keine acc_trans-Eintrag ohne trans_id oder chart_id. Ferner project_id in acc_trans als Fremdschlüssel für project definiert.
3 # @depends: release_2_6_0 fix_acc_trans_ap_taxkey_bug
4 # @charset: utf-8
5
6 use strict;
7 use Data::Dumper;
8 die("This script cannot be run from the command line.") unless ($main::form);
9
10 sub mydberror {
11   my ($msg) = @_;
12   die($dbup_locale->text("Database update error:") .
13       "<br>$msg<br>" . $DBI::errstr);
14 }
15
16 sub do_query {
17   my ($query, $may_fail) = @_;
18
19   if (!$dbh->do($query)) {
20     mydberror($query) unless ($may_fail);
21     $dbh->rollback();
22     $dbh->begin_work();
23   }
24 }
25
26 sub do_update {
27   my @queries;
28
29   # die project_id in der acc_trans ist auch zwingend fremdschlüssel in project 
30   push @queries, "ALTER TABLE acc_trans ADD FOREIGN KEY (project_id) REFERENCES project(id)";
31
32   my $query = qq|select count(*) from acc_trans where chart_id is NULL|;
33   my $sth_all_groups = prepare_execute_query($form, $dbh, $query);
34   while (my $hash_ref = $sth_all_groups->fetchrow_hashref()) {  # Schleife
35     if ($hash_ref->{count} eq 0){
36       # Falls wir keine alte buggy Installation haben, ist es super die 
37       # Gewissheit zu haben, dass kein acc_trans-Eintrag ohne chart_id vorhanden ist
38       push @queries, "ALTER TABLE acc_trans ALTER COLUMN chart_id SET NOT NULL";
39     }
40   }
41   $sth_all_groups->finish();
42   my $query = qq|select count(*) from acc_trans where trans_id is NULL|;
43   my $sth_all_groups = prepare_execute_query($form, $dbh, $query);
44   while (my $hash_ref = $sth_all_groups->fetchrow_hashref()) {  # Schleife
45     if ($hash_ref->{count} eq 0){
46       # Falls wir keine alte buggy Installation haben, ist es super die 
47       # Gewissheit zu haben, dass kein acc_trans-Eintrag ohne trans_id vorhanden ist
48       push @queries, "ALTER TABLE acc_trans ALTER COLUMN trans_id SET NOT NULL";
49     }
50   }
51   $sth_all_groups->finish();
52
53   # if in doubt use brute force ;-) jb
54   foreach my $query (@queries){
55     my $sth   = prepare_query($form, $dbh, $query);
56     do_statement($form,$sth,$query);
57     $sth->finish();
58   }
59   $dbh ->commit();
60   return 1;
61 }
62
63 return do_update();
64