Skip to content
Newer
Older
100755 80 lines (68 sloc) 1.93 KB
00d4052 @kazuho add file
authored Dec 3, 2009
1 #! /usr/bin/perl
2
3 use 5.008;
4 use strict;
5 use warnings;
6
7 use DBI;
8 use Getopt::Long;
9 use POSIX qw(WIFEXITED WEXITSTATUS);
10
11 sub usage {
12 my $exit_code = shift;
13 printf <<"EOT";
14 Usage: $0 [options] cmd
15 Options: --user=db_user username (default: current user)
16 --password=pass password (default: none)
17 --host=db_host db host (default: 127.0.0.1)
18 --port=db_port db port (default: 3306)
19 --db=db_name database name (default: "mysql")
20 --before=stmt statement to execute before running the command
21 (default: "FLUSH TABLES WITH READ LOCK")
22 --after=stmt statement to execute after running the command
23 (default: "UNLOCK TABLES")
24 EOT
25 exit $exit_code;
26 }
27
28 my $user = $ENV{USER} || 'root';
29 my $password = '';
30 my $host = 'localhost';
31 my $port = 3306;
32 my $db = 'mysql';
33 my $before = 'FLUSH TABLES WITH READ LOCK';
34 my $after = 'UNLOCK TABLES';
35 my $help;
36
37 GetOptions(
38 'user=s' => \$user,
39 'password=s' => \$password,
40 'host=s' => \$host,
41 'port=i' => \$port,
42 'db=s' => \$db,
43 'before' => \$before,
44 'after' => \$after,
45 help => \$help,
46 ) or exit 1;
47
48 usage(0)
49 if $help;
50 die "no command (see --help)\n"
51 if @ARGV == 0;
52
53 # connect (with no auto-reconnect)
54 my $dsn = "DBI:mysql:db_name=$db;host=$host;port=$port";
55 my $dbh = DBI->connect($dsn, $user, $password)
56 or die $DBI::errstr;
57 $dbh->{mysql_auto_reconnect} = 0;
58
59 # prepare
fb985be make mysqlock verbose
Kazuho Oku authored Dec 3, 2009
60 print STDERR "issuing lock statement: $before\n";
00d4052 @kazuho add file
authored Dec 3, 2009
61 $dbh->do($before)
62 or die $dbh->errstr;
63
64 # run given command as child process
65 unless (my $pid = fork) {
66 die "fork failed:$!"
67 unless defined $pid;
68 exec @ARGV;
69 die "failed to execute given command:$!";
70 }
71 while (! wait) {}
72 my $code = $?;
73
74 # cleanup
fb985be make mysqlock verbose
Kazuho Oku authored Dec 3, 2009
75 print STDERR "issuing unlock statement: $after\n";
00d4052 @kazuho add file
authored Dec 3, 2009
76 $dbh->do($after)
77 or die $dbh->errstr;
78
79 exit(WIFEXITED($code) ? WEXITSTATUS($code) : 255);
Something went wrong with that request. Please try again.