]> git.sesse.net Git - wloh/blob - sync.pl
Convert index.pl to templates.
[wloh] / sync.pl
1 #! /usr/bin/perl
2 use DBI;
3 use strict;
4 use warnings;
5 no warnings qw(once);
6 use Encode;
7 use Time::HiRes;
8 require './config.pm';
9
10 sub copy_escape {
11         my $x = shift;
12         if (!defined($x)) {
13                 return '\N';
14         }
15         $x = Encode::decode('iso8859-1', $x);
16         $x =~ s/\\/\\\\/g;
17         $x =~ s/\r/\\r/g;
18         $x =~ s/\n/\\n/g;
19         $x =~ s/\t/\\t/g;
20         return $x;
21 }
22
23 sub sync_table {
24         my ($mdbh, $sdbh, $table) = @_;
25         my $start = [ Time::HiRes::gettimeofday ];
26         my $data = $mdbh->selectall_arrayref("SELECT * FROM $table");
27         my $elapsed = Time::HiRes::tv_interval($start);
28         #printf "MySQL $table time used: $elapsed\n";
29
30         $start = [ Time::HiRes::gettimeofday ];
31         $sdbh->do("DELETE FROM $table");
32         $sdbh->do("COPY $table FROM STDIN");
33         
34         for my $row (@$data) {
35                 $sdbh->pg_putcopydata(join("\t", map { copy_escape($_) } (@$row)) . "\n");
36         }
37         $sdbh->pg_putcopyend();
38         $elapsed = Time::HiRes::tv_interval($start);
39         #printf "PostgreSQL $table time used: $elapsed\n";
40 }
41
42 my $mdbh = DBI->connect($config::master_connstr, $config::master_username, $config::master_password)
43         or die "PostgreSQL connect: " . $DBI::errstr;
44 $mdbh->{AutoCommit} = 0;
45 $mdbh->{RaiseError} = 1;
46
47 my $sdbh = DBI->connect($config::local_connstr, $config::local_username, $config::local_password)
48         or die "PostgreSQL connect: " . $DBI::errstr;
49 $sdbh->{AutoCommit} = 0;
50 $sdbh->{RaiseError} = 1;
51
52 # For our own enjoyment.
53 sync_table($mdbh, $sdbh, "Fotballbrukere");
54 sync_table($mdbh, $sdbh, "Fotballdeltagere");
55 sync_table($mdbh, $sdbh, "Fotballresultater");
56 sync_table($mdbh, $sdbh, "Fotballresultater_2123");
57 sync_table($mdbh, $sdbh, "Fotballserier");
58
59 # Just for backup.
60 sync_table($mdbh, $sdbh, 'Fotballjuks');
61 sync_table($mdbh, $sdbh, 'FotballKaffeklubb');
62 sync_table($mdbh, $sdbh, 'Fotballkommentarer');
63 sync_table($mdbh, $sdbh, 'Fotballkommentartema');
64 sync_table($mdbh, $sdbh, 'FotballLogin');
65 sync_table($mdbh, $sdbh, 'Fotballspraak');
66 sync_table($mdbh, $sdbh, 'Fotballtoppti');
67 sync_table($mdbh, $sdbh, 'Fotballvariabler');
68
69 $sdbh->do('DELETE FROM last_sync');
70 $sdbh->do('INSERT INTO last_sync VALUES ( CURRENT_TIMESTAMP );');
71
72 $mdbh->rollback();
73 $sdbh->commit();