epic-ts
[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 # @encoding: utf-8
5 package SL::DBUpgrade2::invoice_positions;
6
7 use strict;
8 use utf8;
9
10 use parent qw(SL::DBUpgrade2::Base);
11
12 sub run {
13   my ($self) = @_;
14
15   my $query = qq|ALTER TABLE invoice ADD position INTEGER|;
16   $self->db_query($query);
17
18
19   $query = qq|SELECT * FROM invoice ORDER BY trans_id, id|;
20
21   my $sth = $self->dbh->prepare($query);
22   $sth->execute || $::form->dberror($query);
23
24   # set new position field in order of ids, starting by one for each invoice
25   my $last_invoice_id;
26   my $position;
27   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
28     if ($ref->{trans_id} != $last_invoice_id) {
29       $position = 1;
30     } else {
31       $position++;
32     }
33     $last_invoice_id = $ref->{trans_id};
34
35     $query = qq|UPDATE invoice SET position = ? WHERE id = ?|;
36     $self->db_query($query, bind => [ $position, $ref->{id} ]);
37   }
38   $sth->finish;
39
40   $query = qq|ALTER TABLE invoice ALTER COLUMN position SET NOT NULL|;
41   $self->db_query($query);
42
43   return 1;
44 }
45
46 1;