summaryrefslogtreecommitdiff
path: root/bin/fix-sequences
blob: dc4abd7513cbf7eca6c471f0fce948a95bb706d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/perl -Tw

# run dbdef-create first!

use strict;
use DBI;
use DBIx::DBSchema 0.26;
use DBIx::DBSchema::Table;
use DBIx::DBSchema::Column;
use DBIx::DBSchema::ColGroup::Unique;
use DBIx::DBSchema::ColGroup::Index;
use FS::UID qw(adminsuidsetup driver_name);
use FS::Record qw(dbdef);

my $user = shift or die &usage;
my $dbh = adminsuidsetup $user;

my $schema = dbdef();

#false laziness w/fs-setup
my @tables = scalar(@ARGV)
               ? @ARGV
               : grep { ! /^h_/ } $schema->tables;
foreach my $table ( @tables ) {
  my $tableobj = $schema->table($table)
    or die "unknown table $table (did you run dbdef-create?)\n";

  my $primary_key = $tableobj->primary_key;
  next unless $primary_key;

  my $col = $tableobj->column($primary_key);


  next unless uc($col->type) eq 'SERIAL'
              || ( driver_name eq 'Pg'
                     && defined($col->default)
                     && $col->default =~ /^nextval\(/i
                 )
              || ( driver_name eq 'mysql'
                     && defined($col->local)
                     && $col->local =~ /AUTO_INCREMENT/i
                 );

  my $seq = "${table}_${primary_key}_seq";
  if ( driver_name eq 'Pg'
       && defined($col->default) 
       && $col->default =~ /^nextval\('"(public\.)?(\w+_seq)"'::text\)$/
     ) {
    $seq = $2;
  }

  warn "fixing sequence for $table\n";


  my $sql = "SELECT setval( '$seq',
                            ( SELECT max($primary_key) FROM $table ) );";

  #warn $col->default. " $seq\n$sql\n";
  $dbh->do( $sql ) or die $dbh->errstr;

}

$dbh->commit or die $dbh->errstr;
$dbh->disconnect or die $dbh->errstr;

sub usage {
  die "Usage:\n  fix-sequences user [ table table ... ] \n";
}