agent_custid bugfix (1746) (backport)
[freeside.git] / FS / bin / freeside-upgrade
1 #!/usr/bin/perl -w
2
3 use strict;
4 use vars qw($opt_d $opt_q $opt_v);
5 use vars qw($DEBUG $DRY_RUN);
6 use Getopt::Std;
7 use DBIx::DBSchema 0.31;
8 use FS::UID qw(adminsuidsetup checkeuid datasrc );  #getsecrets);
9 use FS::CurrentUser;
10 use FS::Schema qw( dbdef dbdef_dist reload_dbdef );
11 use FS::Misc::prune qw(prune_applications);
12
13 die "Not running uid freeside!" unless checkeuid();
14
15 getopts("dq");
16
17 $DEBUG = !$opt_q;
18 #$DEBUG = $opt_v;
19
20 $DRY_RUN = $opt_d;
21
22 my $user = shift or die &usage;
23 $FS::CurrentUser::upgrade_hack = 1;
24 my $dbh = adminsuidsetup($user);
25
26 #needs to match FS::Schema...
27 my $dbdef_file = "%%%FREESIDE_CONF%%%/dbdef.". datasrc;
28
29 dbdef_create($dbh, $dbdef_file);
30
31 delete $FS::Schema::dbdef_cache{$dbdef_file}; #force an actual reload
32 reload_dbdef($dbdef_file);
33
34 $DBIx::DBSchema::DEBUG = $DEBUG;
35 $DBIx::DBSchema::Table::DEBUG = $DEBUG;
36
37 my @bugfix = ();
38
39 if (dbdef->table('cust_main')->column('agent_custid')) { 
40   push @bugfix,
41     "UPDATE cust_main SET agent_custid = NULL where agent_custid = ''";
42
43   push @bugfix,
44     "UPDATE h_cust_main SET agent_custid = NULL where agent_custid = ''"
45       if (dbdef->table('h_cust_main')); 
46 }
47
48 if ( $DRY_RUN ) {
49   print
50     join(";\n", @bugfix, dbdef->sql_update_schema( dbdef_dist, $dbh ) ). ";\n";
51   exit;
52 } else {
53   foreach my $statement ( @bugfix ) {
54     $dbh->do( $statement )
55       or die "Error: ". $dbh->errstr. "\n executing: $statement";
56   }
57
58   dbdef->update_schema( dbdef_dist, $dbh );
59 }
60
61 my $hashref = {};
62 $hashref->{dry_run} = 1 if $DRY_RUN;
63 $hashref->{debug} = 1 if $DEBUG;
64 print join "\n", prune_applications($hashref);
65 print "\n" if $DRY_RUN;
66
67
68 $dbh->commit or die $dbh->errstr;
69
70 dbdef_create($dbh, $dbdef_file);
71
72 $dbh->disconnect or die $dbh->errstr;
73
74 ###
75
76 sub dbdef_create { # reverse engineer the schema from the DB and save to file
77   my( $dbh, $file ) = @_;
78   my $dbdef = new_native DBIx::DBSchema $dbh;
79   $dbdef->save($file);
80 }
81
82 sub usage {
83   die "Usage:\n  freeside-upgrade [ -d ] [ -q | -v ] user\n"; 
84 }
85
86 =head1 NAME
87
88 freeside-upgrade - Upgrades database schema for new freeside verisons.
89
90 =head1 SYNOPSIS
91
92   freeside-upgrade [ -d ] [ -q | -v ]
93
94 =head1 DESCRIPTION
95
96 Reads your existing database schema and updates it to match the current schema,
97 adding any columns or tables necessary.
98
99   [ -d ]: Dry run; output SQL statements (to STDOUT) only, but do not execute
100           them.
101
102   [ -q ]: Run quietly.  This may become the default at some point.
103
104   [ -v ]: Run verbosely, sending debugging information to STDERR.  This is the
105           current default.
106
107 =head1 SEE ALSO
108
109 =cut
110