fea63da26e8d6a500d06e9a036dfc58d80bb52c5
[kivitendo-erp.git] / sql / Pg-upgrade2 / invoice_positions.pl
1 # @tag: invoice_positions
2 # @description: Spalte für Positionen der Einträge in Rechnungen
3 # @depends: release_3_1_0
4 package SL::DBUpgrade2::invoice_positions;
5
6 use strict;
7 use utf8;
8
9 use parent qw(SL::DBUpgrade2::Base);
10
11 sub run {
12   my ($self) = @_;
13
14   my $query = qq|ALTER TABLE invoice ADD position INTEGER|;
15   $self->db_query($query);
16
17
18   $query = qq|SELECT * FROM invoice ORDER BY trans_id, id|;
19   my $query2 = qq|UPDATE invoice SET position = ? WHERE id = ?|;
20
21   my $sth = $self->dbh->prepare($query);
22   my $sth2 = $self->dbh->prepare($query2);
23   $sth->execute || $::form->dberror($query);
24
25   # set new position field in order of ids, starting by one for each invoice
26   my $last_invoice_id;
27   my $position;
28   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
29     if ($ref->{trans_id} != $last_invoice_id) {
30       $position = 1;
31     } else {
32       $position++;
33     }
34     $last_invoice_id = $ref->{trans_id};
35
36     $sth2->execute($position, $ref->{id});
37   }
38   $sth->finish;
39   $sth2->finish;
40
41   $query = qq|ALTER TABLE invoice ALTER COLUMN position SET NOT NULL|;
42   $self->db_query($query);
43
44   return 1;
45 }
46
47 1;