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 |
my $git = '/tmp/pgsql-git-backup/'; |
12 |
my $verbose = 0; |
13 |
my $database = ''; |
14 |
|
15 |
my $usage = "Usage: $0 --database name < name-dump.sql\n"; |
16 |
|
17 |
GetOptions( |
18 |
'git=s' => \$git, |
19 |
'database=s' => \$database, |
20 |
'verbose+' => \$verbose, |
21 |
) or die $usage; |
22 |
|
23 |
die $usage unless $database; |
24 |
|
25 |
my $nr = 0; |
26 |
my $name = $database; |
27 |
my $d; |
28 |
|
29 |
sub git { |
30 |
my $cmd = shift or die "no cmd?"; |
31 |
system($cmd) == 0 or die "$cmd FAILED $?"; |
32 |
} |
33 |
|
34 |
sub write_chunk { |
35 |
my $path = sprintf("%s/%02d%s.sql", $database, $nr++, $name); |
36 |
open(my $fh, '>', $path) or die "can't open file $path: $!"; |
37 |
print $fh $d; |
38 |
close($fh); |
39 |
warn ">> $path ", -s $path, "\n" if $verbose; |
40 |
git "git-add '$path'"; |
41 |
} |
42 |
|
43 |
if ( ! -e $git ) { |
44 |
mkdir $git or die "can't create $git: $!"; |
45 |
git 'git-init-db'; |
46 |
} |
47 |
|
48 |
chdir($git) or die "can't chdir $git: $!"; |
49 |
|
50 |
if ( ! -e $database ) { |
51 |
mkdir $database or die "can't create $database: $!"; |
52 |
# git "git-add '$database'"; |
53 |
# git "git-commit -m 'added $database directory' $database"; |
54 |
} |
55 |
|
56 |
while(<STDIN>) { |
57 |
if (/-- Name: (.+?);/) { |
58 |
write_chunk; |
59 |
$name = " $1"; |
60 |
$name =~ s/\W+/ /g; |
61 |
undef $d; |
62 |
$d = ''; |
63 |
} |
64 |
$d .= $_; |
65 |
} |
66 |
|
67 |
write_chunk; |
68 |
|
69 |
git "git-commit -m '$database' '$database'"; |