commit after each table upgrade, helps with getting huge dbs upgraded, RT#4679
[freeside.git] / FS / FS / Upgrade.pm
1 package FS::Upgrade;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $DEBUG );
5 use Exporter;
6 use Tie::IxHash;
7 use FS::UID qw( dbh driver_name );
8 use FS::Conf;
9 use FS::Record qw(qsearchs str2time_sql);
10
11 use FS::svc_domain;
12 $FS::svc_domain::whois_hack = 1;
13
14 @ISA = qw( Exporter );
15 @EXPORT_OK = qw( upgrade upgrade_sqlradius );
16
17 $DEBUG = 1;
18
19 =head1 NAME
20
21 FS::Upgrade - Database upgrade routines
22
23 =head1 SYNOPSIS
24
25   use FS::Upgrade;
26
27 =head1 DESCRIPTION
28
29 Currently this module simply provides a place to store common subroutines for
30 database upgrades.
31
32 =head1 SUBROUTINES
33
34 =over 4
35
36 =item
37
38 =cut
39
40 sub upgrade {
41   my %opt = @_;
42
43   my $data = upgrade_data(%opt);
44
45   foreach my $table ( keys %$data ) {
46
47     my $class = "FS::$table";
48     eval "use $class;";
49     die $@ if $@;
50
51     if ( $class->can('_upgrade_data') ) {
52       warn "Upgrading $table...\n";
53
54       my $oldAutoCommit = $FS::UID::AutoCommit;
55       local $FS::UID::AutoCommit = 0;
56       $FS::UID::AutoCommit = 0;
57
58       $class->_upgrade_data(%opt);
59
60       if ( $oldAutoCommit ) {
61         dbh->commit or die dbh->errstr;
62       }
63
64     } else {
65       warn "WARNING: asked for upgrade of $table,".
66            " but FS::$table has no _upgrade_data method\n";
67     }
68
69 #    my @records = @{ $data->{$table} };
70 #
71 #    foreach my $record ( @records ) {
72 #      my $args = delete($record->{'_upgrade_args'}) || [];
73 #      my $object = $class->new( $record );
74 #      my $error = $object->insert( @$args );
75 #      die "error inserting record into $table: $error\n"
76 #        if $error;
77 #    }
78
79   }
80
81 }
82
83
84 sub upgrade_data {
85   my %opt = @_;
86
87   tie my %hash, 'Tie::IxHash', 
88
89     #msgcat
90     'msgcat' => [],
91
92     #reason type and reasons
93     'reason_type'     => [],
94     'reason'          => [],
95     'cust_pkg_reason' => [],
96
97     #need part_pkg before cust_credit...
98     'part_pkg' => [],
99
100     #customer credits
101     'cust_credit' => [],
102
103     #duplicate history records
104     'h_cust_svc'  => [],
105
106     #populate cust_pay.otaker
107     'cust_pay'    => [],
108
109     #populate part_pkg_taxclass for starters
110     'part_pkg_taxclass' => [],
111
112     #remove bad pending records
113     'cust_pay_pending' => [],
114
115     #replace invnum and pkgnum with billpkgnum
116     'cust_bill_pkg_detail' => [],
117
118     #usage_classes if we have none
119     'usage_class' => [],
120
121     #fixup access rights
122     'access_right' => [],
123
124   ;
125
126   \%hash;
127
128 }
129
130 sub upgrade_sqlradius {
131   #my %opt = @_;
132
133   my $conf = new FS::Conf;
134
135   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
136
137   foreach my $part_export ( @part_export ) {
138
139     my $errmsg = 'Error adding FreesideStatus to '.
140                  $part_export->option('datasrc'). ': ';
141
142     my $dbh = DBI->connect(
143       ( map $part_export->option($_), qw ( datasrc username password ) ),
144       { PrintError => 0, PrintWarn => 0 }
145     ) or do {
146       warn $errmsg.$DBI::errstr;
147       next;
148     };
149
150     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
151     my $group = "UserName";
152     $group .= ",Realm"
153       if ( ref($part_export) =~ /withdomain/ );
154
155     my $sth_alter = $dbh->prepare(
156       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
157     );
158     if ( $sth_alter ) {
159       if ( $sth_alter->execute ) {
160         my $sth_update = $dbh->prepare(
161          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
162         ) or die $errmsg.$dbh->errstr;
163         $sth_update->execute or die $errmsg.$sth_update->errstr;
164       } else {
165         my $error = $sth_alter->errstr;
166         warn $errmsg.$error unless $error =~ /Duplicate column name/i;
167       }
168     } else {
169       my $error = $dbh->errstr;
170       warn $errmsg.$error; #unless $error =~ /exists/i;
171     }
172
173     my $sth_index = $dbh->prepare(
174       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
175     );
176     if ( $sth_index ) {
177       unless ( $sth_index->execute ) {
178         my $error = $sth_index->errstr;
179         warn $errmsg.$error unless $error =~ /Duplicate key name/i;
180       }
181     } else {
182       my $error = $dbh->errstr;
183       warn $errmsg.$error; #unless $error =~ /exists/i;
184     }
185
186     my $sth = $dbh->prepare("SELECT UserName,
187                                     Realm,
188                                     $str2time max(AcctStartTime)),
189                                     $str2time max(AcctStopTime))
190                               FROM radacct
191                               WHERE FreesideStatus = 'done'
192                                 AND AcctStartTime != 0
193                                 AND AcctStopTime  != 0
194                               GROUP BY $group
195                             ")
196       or die $errmsg.$dbh->errstr;
197     $sth->execute() or die $errmsg.$sth->errstr;
198   
199     while (my $row = $sth->fetchrow_arrayref ) {
200       my ($username, $realm, $start, $stop) = @$row;
201   
202       $username = lc($username) unless $conf->exists('username-uppercase');
203
204       my $exportnum = $part_export->exportnum;
205       my $extra_sql = " AND exportnum = $exportnum ".
206                       " AND exportsvcnum IS NOT NULL ";
207
208       if ( ref($part_export) =~ /withdomain/ ) {
209         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
210                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
211       }
212   
213       my $svc_acct = qsearchs({
214         'select'    => 'svc_acct.*',
215         'table'     => 'svc_acct',
216         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
217                        'LEFT JOIN export_svc USING ( svcpart )',
218         'hashref'   => { 'username' => $username },
219         'extra_sql' => $extra_sql,
220       });
221
222       if ($svc_acct) {
223         $svc_acct->last_login($start)
224           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
225         $svc_acct->last_logout($stop)
226           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
227       }
228     }
229   }
230
231 }
232
233 =back
234
235 =head1 BUGS
236
237 Sure.
238
239 =head1 SEE ALSO
240
241 =cut
242
243 1;
244