1 |
#!/usr/bin/perl |
2 |
|
3 |
# split PostgreSQL dump into individual files for backup with git |
4 |
# |
5 |
# 09/11/08 20:10:39 CEST Dobrica Pavlinusic <dpavlin@rot13.org> |
6 |
|
7 |
use warnings; |
8 |
use strict; |
9 |
|
10 |
use Getopt::Long; |
11 |
use Fatal qw/:void open close mkdir chdir/; |
12 |
my $git = '/tmp/pgsql-git-backup/'; |
13 |
my $verbose = 0; |
14 |
my $database = ''; |
15 |
|
16 |
my $usage = "Usage: $0 --database name < name-dump.sql\n"; |
17 |
|
18 |
GetOptions( |
19 |
'git=s' => \$git, |
20 |
'database=s' => \$database, |
21 |
'verbose+' => \$verbose, |
22 |
) or die $usage; |
23 |
|
24 |
die $usage unless $database; |
25 |
|
26 |
my $nr = 0; |
27 |
my $name = $database; |
28 |
my $d; |
29 |
|
30 |
sub git { |
31 |
my $cmd = shift or die "no cmd?"; |
32 |
system($cmd) == 0 or die "$cmd FAILED $?"; |
33 |
} |
34 |
|
35 |
sub write_chunk { |
36 |
my $path = sprintf("%s/%04d%s.sql", $database, $nr++, $name); |
37 |
open(my $fh, '>', $path) or die "can't open file $path: $!"; |
38 |
print $fh $d; |
39 |
close($fh); |
40 |
warn ">> $path ", -s $path, "\n" if $verbose; |
41 |
git "git-add '$path'"; |
42 |
} |
43 |
|
44 |
mkdir $git if ! -e $git; |
45 |
|
46 |
chdir $git; |
47 |
warn "## using $git\n" if $verbose; |
48 |
|
49 |
git 'git-init-db' if ! -e "$git/.git"; |
50 |
|
51 |
if ( ! -e $database ) { |
52 |
mkdir $database; |
53 |
# git "git-add '$database'"; |
54 |
# git "git-commit -m 'added $database directory' $database"; |
55 |
} |
56 |
|
57 |
while(<STDIN>) { |
58 |
if (/-- Name: (.+?);/) { |
59 |
write_chunk; |
60 |
$name = " $1"; |
61 |
$name =~ s/\W+/ /g; |
62 |
undef $d; |
63 |
$d = ''; |
64 |
} |
65 |
$d .= $_; |
66 |
} |
67 |
|
68 |
write_chunk; |
69 |
|
70 |
git "git-commit -m '$database' '$database'"; |