2f10670c459618a0556a404040b50bbbb5a304ef
[kivitendo-erp.git] / sql / Pg-upgrade2 / contacts_convert_cp_birthday_to_date.pl
1 # @tag: contacts_convert_cp_birthday_to_date
2 # @description: Umstellung cp_birthday von Freitext auf Datumsfeld
3 # @depends: release_2_7_0
4 package contacts_convert_cp_birthday_to_date;
5 use strict;
6
7 die 'This script cannot be run from the command line.' if !$::form;
8
9 sub convert_to_date {
10   my ($str) = @_;
11
12   return '' if !$str;
13
14   my $sth = $dbh->prepare('SELECT ?::date AS date') or return undef;
15   $sth->execute($str)                               or return undef;
16
17   return $sth->fetchrow_hashref->{date};
18 }
19
20 sub update {
21   my @data      = ();
22   my @auto_data = ();
23   my $sql       = <<SQL;
24     SELECT
25       cp_id,
26       cp_givenname,
27       cp_name,
28       cp_birthday AS cp_birthday_old
29     FROM contacts
30     ORDER BY cp_id;
31 SQL
32
33   my $sth = $dbh->prepare($sql) or die $dbh->errstr;
34   $sth->execute or die $dbh->errstr;
35
36   my $i = -1;
37   while (my $row = $sth->fetchrow_hashref) {
38     $i++;
39     $row->{cp_birthday} = convert_to_date($::form->{form_submitted} ? $::form->{'cp_birthday_'. $i} : $row->{cp_birthday_old});
40     $row->{row_index}   = $i;
41
42     if ( defined($row->{cp_birthday}) ) {
43        push(@auto_data, $row);
44     } else {
45        push(@data,      $row);
46     }
47   }
48
49   $::form->{data}       = \@data;
50   $::form->{auto_data}  = \@auto_data;
51   $::form->{row_length} = $i;
52
53   if (@data) {
54     print $::form->parse_html_template('dbupgrade/contacts_convert_cp_birthday_to_date_form');
55     return 2;
56   } else {
57     $sql = <<SQL;
58       ALTER TABLE contacts DROP COLUMN cp_birthday;
59       ALTER TABLE contacts ADD COLUMN cp_birthday date;
60 SQL
61
62     $dbh->do($sql);
63
64     $sql = <<SQL;
65       UPDATE contacts
66       SET   cp_birthday = ?
67       WHERE cp_id = ?
68 SQL
69
70     $sth = $dbh->prepare($sql) or die $dbh->errstr;
71
72     foreach (grep { $_->{cp_birthday} ne '' } @auto_data) {
73       $sth->execute($_->{cp_birthday}, $_->{cp_id}) or die $dbh->errstr;
74     }
75
76     return 1;
77   }
78 }
79
80 return update();