| 1 | package MySQL::Warmer::CLI; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use utf8; | ||
| 5 | |||
| 6 | use MySQL::Warmer; | ||
| 7 | |||
| 8 | use Getopt::Long (); | ||
| 9 | use Pod::Usage; | ||
| 10 | use Term::ReadKey; | ||
| 11 | |||
| 12 | sub run { | ||
| 13 | my ($class, @argv) = @_; | ||
| 14 | |||
| 15 | my ($opt, ) = $class->parse_options(@argv); | ||
| 16 | MySQL::Warmer->new($opt)->run; | ||
| 17 | } | ||
| 18 | |||
| 19 | sub parse_options { | ||
| 20 | my ($class, @argv) = @_; | ||
| 21 | |||
| 22 | my $parser = Getopt::Long::Parser->new( | ||
| 23 | config => [qw/posix_default no_ignore_case bundling permute pass_through auto_help/], | ||
| 24 | ); | ||
| 25 | local @ARGV = @argv; | ||
| 26 | $parser->getoptions(\my %opt, qw/ | ||
| 27 | host|h=s | ||
| 28 | user|u=s | ||
| 29 | password|p:s | ||
| 30 | port|P=i | ||
| 31 | socket|S=s | ||
| 32 | dry-run | ||
| 33 | /) or pod2usage(1); | ||
| 34 | |||
| 35 | if (exists $opt{password} && $opt{password} eq '') { | ||
| 36 | ReadMode 'noecho'; | ||
| 37 | print 'Enter password: '; | ||
| 38 | chomp ($opt{password} = ReadLine); | ||
| 39 | } | ||
| 40 | $opt{database} = shift @ARGV; | ||
| 41 | unless (defined $opt{database}) { | ||
| 42 | pod2usage(1); | ||
| 43 | } | ||
| 44 | |||
| 45 | my $dry_run = delete $opt{'dry-run'}; | ||
| 46 | |||
| 47 | my $user = | ||
| 48 | exists $opt{user} ? delete $opt{user} : | ||
| 49 | exists $ENV{USER} ? $ENV{USER} : ''; | ||
| 50 | my $password = exists $opt{password} ? delete $opt{password} : ''; | ||
| 51 | my $dsn = $class->_build_dsn(%opt); | ||
| 52 | my @dsn = ($dsn, $user, $password, { | ||
| 53 | RaiseError => 1, | ||
| 54 | PrintError => 0, | ||
| 55 | ShowErrorStatement => 1, | ||
| 56 | AutoInactiveDestroy => 1, | ||
| 57 | mysql_enable_utf8 => 1, | ||
| 58 | }); | ||
| 59 | |||
| 60 | (+{ | ||
| 61 | dsn => \@dsn, | ||
| 62 | $dry_run ? (dry_run => 1) : (), | ||
| 63 | }, \@ARGV); | ||
| 64 | } | ||
| 65 | |||
| 66 | sub _build_dsn { | ||
| 67 | my ($self, %args) = @_; | ||
| 68 | if (exists $args{socket}) { | ||
| 69 | $args{mysql_socket} ||= delete $args{socket}; | ||
| 70 | } | ||
| 71 | 'DBI:mysql:' . join(';', map { "$_=$args{$_}" } sort keys %args); | ||
| 72 | } | ||
| 73 | |||
| 74 | 1; |