shooting from the hip - perl at the command line for dbas

188
Shooting from the hip. Perl at the command line for DBAs Giuseppe Maxia MySQL Community Team Lead @datacharmer $_ @ @ #! :-) This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License. 1 Friday, 06 August 2010

Post on 18-Oct-2014

2.635 views

Category:

Technology


2 download

DESCRIPTION

There are many GUI applications to deal with databases and with MySQL in particular. But for die hard command line enthusiasts, who grew up with Linux, the shell prompt is still prince. You would be surprised at the vast amount of operations that you can do from the command line, and then many would surely marvel at the amount of work that a Perl one-liner can do. By combining shell and Perl, you get the kind of power that all DBAs dream, but few achieve. Running commands on several databases at once, filtering users, getting detailed metadata, transferring data from the operating system to a database and the other way around, creating scripts from database data, creating SQL commands from database data. That, and more, you can learn by attending this session. Learn the art of the command line as a shortcut to quick and efficient administration, and as help for demanding developers.

TRANSCRIPT

Page 1: Shooting from the hip - Perl at the command line for DBAs

Shooting from the hip.Perl at the command line for DBAs

Giuseppe MaxiaMySQL Community Team Lead

@datacharmer

$_

@ @

#!

:-)

This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License. 1Friday, 06 August 2010

Page 3: Shooting from the hip - Perl at the command line for DBAs

Updated presentation slides

you will find an up to date copy of these slides at: http://tinyurl.com/shoot-cl-2010

http://tinyurl.com/shoot-cl-full-2010

3Friday, 06 August 2010

Page 4: Shooting from the hip - Perl at the command line for DBAs

I love your feedback! Tell it to the Twitter community

#yapc_eu "your feedback here" Twitter me

@datacharmer "your feedback here" Blog about it

4Friday, 06 August 2010

Page 5: Shooting from the hip - Perl at the command line for DBAs

This is a story about languages

5Friday, 06 August 2010

Page 6: Shooting from the hip - Perl at the command line for DBAs

you got to understand, Bernie, it's not personal.

It's just that you are obsolete

We use language to talk to computers

6Friday, 06 August 2010

Page 7: Shooting from the hip - Perl at the command line for DBAs

10 print "hello"20 goto 10We use

languages to talk to computers

7Friday, 06 August 2010

Page 8: Shooting from the hip - Perl at the command line for DBAs

I am a polyglot

8Friday, 06 August 2010

Page 9: Shooting from the hip - Perl at the command line for DBAs

An imperfect polyglot, actually

9Friday, 06 August 2010

Page 10: Shooting from the hip - Perl at the command line for DBAs

I speak Italian

10Friday, 06 August 2010

Page 11: Shooting from the hip - Perl at the command line for DBAs

I speak Italian

with a clear Sardinian accent

10Friday, 06 August 2010

Page 12: Shooting from the hip - Perl at the command line for DBAs

I speak English

11Friday, 06 August 2010

Page 13: Shooting from the hip - Perl at the command line for DBAs

I speak English

with a distinct Italian accent

11Friday, 06 August 2010

Page 14: Shooting from the hip - Perl at the command line for DBAs

I speak Perl

12Friday, 06 August 2010

Page 15: Shooting from the hip - Perl at the command line for DBAs

I speak Perl

with a hint of a C accent

12Friday, 06 August 2010

Page 16: Shooting from the hip - Perl at the command line for DBAs

I speak French and Spanish

13Friday, 06 August 2010

Page 17: Shooting from the hip - Perl at the command line for DBAs

I speak French and Spanishbut since I use them very little, they have melted with Italian and

English13Friday, 06 August 2010

Page 18: Shooting from the hip - Perl at the command line for DBAs

I speak Bash #!/bin/bash

14Friday, 06 August 2010

Page 19: Shooting from the hip - Perl at the command line for DBAs

I speak Bash #!/bin/bash

with a strong Perl accent

14Friday, 06 August 2010

Page 20: Shooting from the hip - Perl at the command line for DBAs

I speak fluent Italian

La donzelletta vien dallacampagna, in sul calar delsole, col suo fascio dell'erbae reca in mano un mazzolino di rose e viole, onde, siccome suole, ornare ella si appresta ...

15Friday, 06 August 2010

Page 21: Shooting from the hip - Perl at the command line for DBAs

However, Sardinian comes handy sometimes

Maissavidati frimisti! (*)

(*) May you never stop16Friday, 06 August 2010

Page 22: Shooting from the hip - Perl at the command line for DBAs

I speak fluent English

When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.

17Friday, 06 August 2010

Page 23: Shooting from the hip - Perl at the command line for DBAs

I speak fluent English

When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.

hmm.wrong flag

17Friday, 06 August 2010

Page 24: Shooting from the hip - Perl at the command line for DBAs

I speak fluent English

When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.

17Friday, 06 August 2010

Page 25: Shooting from the hip - Perl at the command line for DBAs

But sometimes Italian is still necessary

maestro

virtuoso

al fresco

presto

spaghettibravo

tempo

dilettantefiasco

studio

stucco

barista

cappuccino

espresso

lasagnapizza

pasta

stanza

finale

lottostiletto

vendetta soprano piano

18Friday, 06 August 2010

Page 26: Shooting from the hip - Perl at the command line for DBAs

And sometimes Italian is needed

I tuoi perversidefunti!(*)

(*) Your wicked ancestors!19Friday, 06 August 2010

Page 27: Shooting from the hip - Perl at the command line for DBAs

Although Sardinian is still effective here

Ancu ti currullidisa giustizia (*)

(*) May the rule of law chase you20Friday, 06 August 2010

Page 28: Shooting from the hip - Perl at the command line for DBAs

I speak Perl fluently

#!/usr/bin/perluse strict;use warnings;use File::Find;

while (my $line = <stdin>){ # …

21Friday, 06 August 2010

Page 29: Shooting from the hip - Perl at the command line for DBAs

Sometimes, I need help from C

use Inline C;print "9 + 16 = ", add(9, 16), "\n";

__END____C__int add(int x, int y) { return x + y;}

22Friday, 06 August 2010

Page 30: Shooting from the hip - Perl at the command line for DBAs

Most of my work at the command line is Bash

$ for D in $HOME/*/; do du -sh $D;> done > /tmp/occupancy

#!/bin/bash

23Friday, 06 August 2010

Page 31: Shooting from the hip - Perl at the command line for DBAs

And sometimes, a pinch of Perl can help

$ perl -pe 's{(\d\d)-(\d\d)-(\d\d\d\d)}{$3-$1-$2}g' \ < rawfile.txt > betterfile.txt

#!/bin/bash

24Friday, 06 August 2010

Page 32: Shooting from the hip - Perl at the command line for DBAs

And then on top of all this, I need to speak SQL

$ mysql -e 'SELECT COUNT(*) FROM dbname.tbl_name WHERE col_name = 1 and other_col="A" '

25Friday, 06 August 2010

Page 33: Shooting from the hip - Perl at the command line for DBAs

I wish I could say that my SQL has a Perlish accent

$ mysql -e 'SELECT COUNT(*) FROM dbname.tbl_name WHERE col_name = 1 and other_col="A" '

use strict;use DBI;?

26Friday, 06 August 2010

Page 34: Shooting from the hip - Perl at the command line for DBAs

I wish I could say that my SQL has a Perlish accent

$ mysql -e 'SELECT COUNT(*) FROM dbname.tbl_name WHERE col_name = 1 and other_col="A" '

but it wouldn't be true

27Friday, 06 August 2010

Page 35: Shooting from the hip - Perl at the command line for DBAs

I could curse in Perl

$ perl -pe 's{(\d\d)-(\d\d)-(\d\d\d\d)}{$3-$1-$2}g' \ < rawfile.txt > betterfile.txt (*)

(*) already translated

But it would not get me far.

28Friday, 06 August 2010

Page 36: Shooting from the hip - Perl at the command line for DBAs

Then

29Friday, 06 August 2010

Page 37: Shooting from the hip - Perl at the command line for DBAs

Then

I will need to mix languages.

29Friday, 06 August 2010

Page 38: Shooting from the hip - Perl at the command line for DBAs

Then

I will need to mix languages.

This talk will show exactly that.

29Friday, 06 August 2010

Page 39: Shooting from the hip - Perl at the command line for DBAs

Then

I will need to mix languages.

This talk will show exactly that.

Mixing languages.

29Friday, 06 August 2010

Page 40: Shooting from the hip - Perl at the command line for DBAs

Then

I will need to mix languages.

This talk will show exactly that.

Mixing languages.Yes.

29Friday, 06 August 2010

Page 41: Shooting from the hip - Perl at the command line for DBAs

Then

I will need to mix languages.

This talk will show exactly that.

Mixing languages.

$ at the command line

Yes.

29Friday, 06 August 2010

Page 42: Shooting from the hip - Perl at the command line for DBAs

What this tutorial is about Providing tools and tips for command line users; Learn a few tricks to make you achieve more and type

less.

30Friday, 06 August 2010

Page 43: Shooting from the hip - Perl at the command line for DBAs

What this tutorial is about Providing tools and tips for command line users; Learn a few tricks to make you achieve more and type

less. Making GUI enthusiasts green with envy;

bar

foo

baz

30Friday, 06 August 2010

Page 44: Shooting from the hip - Perl at the command line for DBAs

the command line (for rookies)

BASICS

31

31Friday, 06 August 2010

Page 45: Shooting from the hip - Perl at the command line for DBAs

The shell• It's a command interpreter• There are many flavors

> bash > zsh> ksh

32

32Friday, 06 August 2010

Page 46: Shooting from the hip - Perl at the command line for DBAs

MySQL command line client• called "mysql"

> Takes SQL commands> sends them to the server> gets results

• but it can do much more ...

33

33Friday, 06 August 2010

Page 47: Shooting from the hip - Perl at the command line for DBAs

other tools• Shell scripts• Aliases• Perl• awk• sort• …. and a lot of Unix little helper

34

34Friday, 06 August 2010

Page 48: Shooting from the hip - Perl at the command line for DBAs

other tools• Shell scripts• Aliases• Perl• awk• sort• …. and a lot of Unix little helper

34

which could replace everything else, of course

34Friday, 06 August 2010

Page 49: Shooting from the hip - Perl at the command line for DBAs

in case it wasn't clear (yeah, for rookies)

35

35Friday, 06 August 2010

Page 50: Shooting from the hip - Perl at the command line for DBAs

in case it wasn't clear (yeah, for rookies)

• command line actions are

35

35Friday, 06 August 2010

Page 51: Shooting from the hip - Perl at the command line for DBAs

in case it wasn't clear (yeah, for rookies)

• command line actions are> commands (the name of the application to invoke)

35

35Friday, 06 August 2010

Page 52: Shooting from the hip - Perl at the command line for DBAs

in case it wasn't clear (yeah, for rookies)

• command line actions are> commands (the name of the application to invoke)> parameters (optional arguments for the application)

35

35Friday, 06 August 2010

Page 53: Shooting from the hip - Perl at the command line for DBAs

in case it wasn't clear (yeah, for rookies)

• command line actions are> commands (the name of the application to invoke)> parameters (optional arguments for the application)> and the ENTER key

35

35Friday, 06 August 2010

Page 54: Shooting from the hip - Perl at the command line for DBAs

in case it wasn't clear (yeah, for rookies)

• command line actions are> commands (the name of the application to invoke)> parameters (optional arguments for the application)> and the ENTER key

35

Enter

35Friday, 06 August 2010

Page 55: Shooting from the hip - Perl at the command line for DBAs

The Unix philosophy (1)• One tool for every feature

> make one tool that does one thing well> for many features, make many tools> make them work together (see next slide)

36

36Friday, 06 August 2010

Page 56: Shooting from the hip - Perl at the command line for DBAs

The Unix philosophy (2)• To make several tool cooperate:

> pipe the output of one tool to the input of another one.> for more actions, pipe more tools

$ sort < filename | uniq | nl

37

37Friday, 06 August 2010

Page 57: Shooting from the hip - Perl at the command line for DBAs

Unix pipes

38

38Friday, 06 August 2010

Page 58: Shooting from the hip - Perl at the command line for DBAs

Unix pipes

38

inputapplication <

38Friday, 06 August 2010

Page 59: Shooting from the hip - Perl at the command line for DBAs

Unix pipes

38

outputapplication >

inputapplication <

38Friday, 06 August 2010

Page 60: Shooting from the hip - Perl at the command line for DBAs

Unix pipes

38

outputapplication >

inputapplication <

outputapplication >input<

38Friday, 06 August 2010

Page 61: Shooting from the hip - Perl at the command line for DBAs

Unix pipes

38

outputapplication >

inputapplication <

outputapplication >input<

application | application

38Friday, 06 August 2010

Page 62: Shooting from the hip - Perl at the command line for DBAs

Unix pipes

38

outputapplication >

inputapplication <

outputapplication >input<

application | application

input output

38Friday, 06 August 2010

Page 63: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

39Friday, 06 August 2010

Page 64: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

application | application

39Friday, 06 August 2010

Page 65: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

application | application

39Friday, 06 August 2010

Page 66: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

application | application

output

39Friday, 06 August 2010

Page 67: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

application | application

input output

39Friday, 06 August 2010

Page 68: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

application | application

input output

39Friday, 06 August 2010

Page 69: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

application | application

input output output

39Friday, 06 August 2010

Page 70: Shooting from the hip - Perl at the command line for DBAs

Unix pipes = parallel processing

39

application | application

input output output input

39Friday, 06 August 2010

Page 71: Shooting from the hip - Perl at the command line for DBAs

Who gets what• shell• application• database server• pager

40

40Friday, 06 August 2010

Page 72: Shooting from the hip - Perl at the command line for DBAs

who gets what

41

shell prompt $ mysql

mysql client

mysql server

41Friday, 06 August 2010

Page 73: Shooting from the hip - Perl at the command line for DBAs

any hostwho gets what

42

shellmysql client

mysql server

42Friday, 06 August 2010

Page 74: Shooting from the hip - Perl at the command line for DBAs

who gets what$ mysql -u username -ppassword

43

First the applicationthen the server

43Friday, 06 August 2010

Page 75: Shooting from the hip - Perl at the command line for DBAs

who gets what$ mysql -u username -ppassword \ -e "select VERSION()"

44

goes to the server

goes to the client, then the server

44Friday, 06 August 2010

Page 76: Shooting from the hip - Perl at the command line for DBAs

who gets whatmysql> helpmysql> pager lessmysql> select 1;

45

goes to the server

goes to the client onlygoes to the client only

45Friday, 06 August 2010

Page 77: Shooting from the hip - Perl at the command line for DBAs

the command line

readline46

46Friday, 06 August 2010

Page 78: Shooting from the hip - Perl at the command line for DBAs

readline• Common component

> shell> mysql client> many CLI applications

47

47Friday, 06 August 2010

Page 79: Shooting from the hip - Perl at the command line for DBAs

Main cursor movements

48

Ctrl A Ctrl E

Start/End of line

Meta B Meta F

Back/Forward one word

previous/next command

Ctrl L clear screen and take current line on top

48Friday, 06 August 2010

Page 80: Shooting from the hip - Perl at the command line for DBAs

Changing text

49

Meta U Uppercase word

Meta L Lowercase word

Ctrl D delete word

Ctrl K delete to end of line

Ctrl - undo

for more tips:$ man readline

49Friday, 06 August 2010

Page 81: Shooting from the hip - Perl at the command line for DBAs

Some conventions in this talk

$ commandat the shell

mysql> command at the mysql prompt

50

50Friday, 06 August 2010

Page 82: Shooting from the hip - Perl at the command line for DBAs

the Bash shell

bash51

#!

51Friday, 06 August 2010

Page 83: Shooting from the hip - Perl at the command line for DBAs

components• commands• aliases• variables• functions

52

52Friday, 06 August 2010

Page 84: Shooting from the hip - Perl at the command line for DBAs

commands$ echo "something"something

53

53Friday, 06 August 2010

Page 85: Shooting from the hip - Perl at the command line for DBAs

aliases$ alias mydate='mysql -e "select NOW()"'$ mydate+---------------------+| now() |+---------------------+| 2010-04-12 07:14:19 |+---------------------+

54

54Friday, 06 August 2010

Page 86: Shooting from the hip - Perl at the command line for DBAs

aliases$ alias myself='mysql' $ myself -e "select NOW()"'+---------------------+| now() |+---------------------+| 2010-04-12 07:14:19 |+---------------------+

55

55Friday, 06 August 2010

Page 87: Shooting from the hip - Perl at the command line for DBAs

variables$ MYBATCH='mysql -N -B'$ MYQUERY='select curdate()' $ $MYBATCH -e "$MYQUERY"2010-04-12

56

56Friday, 06 August 2010

Page 88: Shooting from the hip - Perl at the command line for DBAs

nesting variables# t.sh CMD="SELECT TABLE_NAME" TBL='information_schema.tables' WHC1="TABLE_SCHEMA='mysql'" WHC2="TABLE_NAME like 'u%' " Q1="$CMD FROM $TBL" Q2="WHERE $WHC1 AND $WHC2" Q="$Q1 $Q2" echo $Q echo $Q | mysql

57

57Friday, 06 August 2010

Page 89: Shooting from the hip - Perl at the command line for DBAs

nesting variables$ sh t.shSELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA='mysql' AND TABLE_NAME like 'u%'TABLE_NAMEuser

58

58Friday, 06 August 2010

Page 90: Shooting from the hip - Perl at the command line for DBAs

the mysql command line client

59

mysql>

59Friday, 06 August 2010

Page 91: Shooting from the hip - Perl at the command line for DBAs

SQL commands from a file$ mysql < filename.sqlmysql> source filename.sql

• executes the commands contained in filename.sql

• commands can be queries understood by the server

• and commands for the client

60

60Friday, 06 August 2010

Page 92: Shooting from the hip - Perl at the command line for DBAs

SQL commands at the command line$ application | mysql$ echo "SELECT 1" | mysql$ mysql -e "SELECT 1"

• executes the commands from standard input

• commands can be queries understood by the server

• and commands for the client

61

61Friday, 06 August 2010

Page 93: Shooting from the hip - Perl at the command line for DBAs

batch mode$ echo "select curdate()" | mysqlcurdate()2010-04-12

62

62Friday, 06 August 2010

Page 94: Shooting from the hip - Perl at the command line for DBAs

table mode$ echo "select curdate()" | mysql -t+------------+| curdate() |+------------+| 2010-04-12 |+------------+

63

63Friday, 06 August 2010

Page 95: Shooting from the hip - Perl at the command line for DBAs

table mode$ mysql -e "select curdate()"+------------+| curdate() |+------------+| 2010-04-12 |+------------+

64

64Friday, 06 August 2010

Page 96: Shooting from the hip - Perl at the command line for DBAs

Forcing batch modemysql -B -e 'select curdate()'curdate()2010-04-12

65

65Friday, 06 August 2010

Page 97: Shooting from the hip - Perl at the command line for DBAs

Forcing batch mode - no headermysql -N -B -e 'select curdate()'2010-04-12

66

IMPORTANT!

66Friday, 06 August 2010

Page 98: Shooting from the hip - Perl at the command line for DBAs

Shell + mysql$ echo "The current server's date is `mysql -N -B -e 'select curdate()'`."

$ echo "The current server's date is $(mysql -N -B -e 'select curdate()')."

67

67Friday, 06 August 2010

Page 99: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

loops68

$_

(-:((((((

@@

68Friday, 06 August 2010

Page 100: Shooting from the hip - Perl at the command line for DBAs

loops basics$ for N in 1 2 3> do> echo $N> done123

69

69Friday, 06 August 2010

Page 101: Shooting from the hip - Perl at the command line for DBAs

loops basics$ for N in 1 2 3 ; do echo $N ; done123

70

70Friday, 06 August 2010

Page 102: Shooting from the hip - Perl at the command line for DBAs

loops basics$ for N in $(seq 1 3) ;\ do echo "this is number $N" ;\ done

this is number 1this is number 2this is number 3

71

71Friday, 06 August 2010

Page 103: Shooting from the hip - Perl at the command line for DBAs

loops from file$ head /usr/share/dict/words AaaaaalaaliiaamAaniaardvarkaardwolf

72

72Friday, 06 August 2010

Page 104: Shooting from the hip - Perl at the command line for DBAs

loops from file$ for U in \$(head /usr/share/dict/words ) ; do perl -le 'print uc shift' $U ; doneAAAAAALAALIIAAMAANI

73

73Friday, 06 August 2010

Page 105: Shooting from the hip - Perl at the command line for DBAs

loops from mysql results$ mysql -B -N -e 'show tables from world'CityCountryCountryLanguage

74

74Friday, 06 August 2010

Page 106: Shooting from the hip - Perl at the command line for DBAs

loops from mysql results$ for T in $(mysql -B -N -e 'show tables from world') ;\> do echo "CREATE TABLE world2.$T LIKE world.$T;" ; done

CREATE TABLE world2.City LIKE world.City;CREATE TABLE world2.Country LIKE world.Country;CREATE TABLE world2.CountryLanguage LIKE world.CountryLanguage;

75

75Friday, 06 August 2010

Page 107: Shooting from the hip - Perl at the command line for DBAs

piping loops back into mysql$ for T in $(mysql -B -N -e 'show tables from world') ;\> do echo "CREATE TABLE world2.$T LIKE world.$T;" ; done \> | mysql -vv

76

76Friday, 06 August 2010

Page 108: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

nested

77

$_

@ @

#!

:-)

#!#!#!#!#!

loops77Friday, 06 August 2010

Page 109: Shooting from the hip - Perl at the command line for DBAs

doing something for every tablein every database$ mysql -e "show databases"+--------------------+| Database |+--------------------+| information_schema || mysql || sakila || world |+--------------------+

78

78Friday, 06 August 2010

Page 110: Shooting from the hip - Perl at the command line for DBAs

doing something for every tablein every database$ mysql -e "show tables from world"+-----------------+| Tables_in_world |+-----------------+| City || Country || CountryLanguage |+-----------------+

79

79Friday, 06 August 2010

Page 111: Shooting from the hip - Perl at the command line for DBAs

pseudocodefor each database do for each table do print the table name

80

80Friday, 06 August 2010

Page 112: Shooting from the hip - Perl at the command line for DBAs

actual codealias mybatch='mysql -B -N'for D in $(mybatch -e "SHOW SCHEMAS")do for T in \ $(mybatch -e "SHOW TABLES FROM $D") do echo "$D.$T" donedone

81

81Friday, 06 August 2010

Page 113: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

options files

82

$HOME

82Friday, 06 August 2010

Page 114: Shooting from the hip - Perl at the command line for DBAs

Default option files/etc/my.cnf/etc/mysql/my.cnf (Debian, Ubuntu)$BASEDIR/my.cnf$HOME/.my.cnf

83

83Friday, 06 August 2010

Page 115: Shooting from the hip - Perl at the command line for DBAs

Custom option files$ mysql --no-defaults$ mysql --defaults-file=filename$ mysql --defaults-extra-file=filename

84

84Friday, 06 August 2010

Page 116: Shooting from the hip - Perl at the command line for DBAs

Option files sections[mysqld]# option for server

[client]# option for any mysql client

[mysql]# options specific to 'mysql' CLI app

85

85Friday, 06 August 2010

Page 117: Shooting from the hip - Perl at the command line for DBAs

Option files example

[client]user=mynamepassword=mypassword

[mysql]prompt="mysql (\h) {\u} [\d] > "

86

86Friday, 06 August 2010

Page 118: Shooting from the hip - Perl at the command line for DBAs

Option files: caution# protect your option files!

$ chmod 600 $HOME/.my.cnf

$ ls -l .my.cnf-rw------- 1 [...] 10:04 .my.cnf

87

87Friday, 06 August 2010

Page 119: Shooting from the hip - Perl at the command line for DBAs

promptmysql> prompt gm (\h) {\u} [\d] > PROMPT set to 'gm (\h) {\u} [\d] > 'gm (localhost) {root} [(none)] > use testDatabase changedgm (localhost) {root} [test] >

# \h -> host# \u -> user# \d -> database

88

88Friday, 06 August 2010

Page 120: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

aliases89

#!

(-:

((((((@@

89Friday, 06 August 2010

Page 121: Shooting from the hip - Perl at the command line for DBAs

An useful alias$ alias mysql_as_root=\'mysql --defaults_file=~/.my_as_root.cnf'

mysql_as_root -e "select user()"+----------------+| user() |+----------------+| root@localhost |+----------------+

90

90Friday, 06 August 2010

Page 122: Shooting from the hip - Perl at the command line for DBAs

An useful alias#.my_as_root.cnf'[client]user=rootpassword=your_mysql_root_password

[mysql]prompt="### [\h] {\u} (\d) > "

91

91Friday, 06 August 2010

Page 123: Shooting from the hip - Perl at the command line for DBAs

Another useful aliasalias mybatch='mysql -B -N '

mybatch -e "select version()"5.1.45-log

92

92Friday, 06 August 2010

Page 124: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

functions93

#!

(-:

((((((@@( )

93Friday, 06 August 2010

Page 125: Shooting from the hip - Perl at the command line for DBAs

functions• like aliases, but with parameters

94

94Friday, 06 August 2010

Page 126: Shooting from the hip - Perl at the command line for DBAs

sample functionfunction grant_new { mysql_as_root -e \ "GRANT $1 on $2 to $3 identified by \"$4\" "}

$ grant_new SELECT "world.*" john \ john_secret

95

95Friday, 06 August 2010

Page 127: Shooting from the hip - Perl at the command line for DBAs

sample function$ mysql_as_root \ -e 'show grants for john\G'*** 1. row ***Grants for john@%: GRANT USAGE ON *.* TO 'john'@'%' IDENTIFIED BY PASSWORD '*73A88CE13374128844E3ABB500F439A9C02C53A3'*** 2. row ***Grants for john@%: GRANT SELECT ON `world`.* TO 'john'@'%'

96

96Friday, 06 August 2010

Page 128: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

getting query

details97

$_

97Friday, 06 August 2010

Page 129: Shooting from the hip - Perl at the command line for DBAs

which query is being executed?# wrong.sql# this script has one erroruse test ;drop table if exists t1 ;create table t1 (id int);insert into t1 values (a);

98

98Friday, 06 August 2010

Page 130: Shooting from the hip - Perl at the command line for DBAs

which query is being executed?$ mysql < wrong.sqlERROR 1054 (42S22) at line 4: Unknown column 'a' in 'field list'

# WHERE IS THE ERROR?

99

99Friday, 06 August 2010

Page 131: Shooting from the hip - Perl at the command line for DBAs

which query is being executed?$ mysql -v < wrong.sql--------------drop table if exists t1----------------------------create table t1 (id int)----------------------------insert into t1 values (a)--------------ERROR 1054 (42S22) at line 4: Unknown column 'a' in 'field list'

100

100Friday, 06 August 2010

Page 132: Shooting from the hip - Perl at the command line for DBAs

getting execution times$ mysql -vv -e \'select rating,count(*) from sakila.film group by rating'+--------+----------+| rating | count(*) |+--------+----------+| G | 178 || PG | 194 || PG-13 | 223 || R | 195 || NC-17 | 210 |+--------+----------+5 rows in set (0.00 sec) 101

101Friday, 06 August 2010

Page 133: Shooting from the hip - Perl at the command line for DBAs

$echo 'select rating,count(*) from sakila.film group by rating' | mysql -vv--------------select rating,count(*) from sakila.film group by rating--------------

rating count(*)G 178PG 194PG-13 223R 195NC-17 2105 rows in set

102

getting execution times (batch mode)

102Friday, 06 August 2010

Page 134: Shooting from the hip - Perl at the command line for DBAs

getting execution times (batch mode)$ echo 'select rating,count(*) from sakila.film group by rating' | mysql -vvv --------------select rating,count(*) from sakila.film group by rating--------------+--------+----------+| rating | count(*) |+--------+----------+| G | 178 || PG | 194 || PG-13 | 223 || R | 195 || NC-17 | 210 |+--------+----------+5 rows in set (0.00 sec) 103

103Friday, 06 August 2010

Page 135: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

getting distinct results

104

$_

104Friday, 06 August 2010

Page 136: Shooting from the hip - Perl at the command line for DBAs

getting a single value$ mysql -e "show variables like 'port'"+---------------+-------+| Variable_name | Value |+---------------+-------+| port | 3306 |+---------------+-------+

# Here, we only want the port number

105

105Friday, 06 August 2010

Page 137: Shooting from the hip - Perl at the command line for DBAs

getting a single value$ mysql -NB -e "show variables like 'port'" port 3306

# no header, batch mode# still two values

106

106Friday, 06 August 2010

Page 138: Shooting from the hip - Perl at the command line for DBAs

getting a single value$ mysql -NB \ -e "show variables like 'port'" \ | awk '{print $2}'

3306

$ mysql -NB \ -e "show variables like 'port'" \ | perl -lane 'print $F[1]'

3306 # filtering the wanted value

107

107Friday, 06 August 2010

Page 139: Shooting from the hip - Perl at the command line for DBAs

getting a single value: is replication working?

$ mysql \ -e "show slave status \G" \ | grep -i slave_io_running

Slave_IO_Running: Yes

# too many things. # We only want a 'yes' or 'no'

108

108Friday, 06 August 2010

Page 140: Shooting from the hip - Perl at the command line for DBAs

getting a single value: is replication working?

$ mysql \ -e "show slave status \G" \ | grep -i "slave_io_running" \ | perl -lane 'print $F[1]'

Yes

# yes!

109

109Friday, 06 August 2010

Page 141: Shooting from the hip - Perl at the command line for DBAs

What's perl -lane?

110

110Friday, 06 August 2010

Page 142: Shooting from the hip - Perl at the command line for DBAs

What's perl -lane?

110

perl -lane must turn perl

110Friday, 06 August 2010

Page 143: Shooting from the hip - Perl at the command line for DBAs

Perl command line must-know facts (1)perl -e 'print "hello\n"'# executes perl code

111

111Friday, 06 August 2010

Page 144: Shooting from the hip - Perl at the command line for DBAs

Perl command line must-know facts (2)perl -ne 'print if /^a/'# starts a loop from standard input# and executes the perl code for each# iteration

perl -MO=Deparse -ne 'print if /^a/'LINE: while (defined($_ = <ARGV>)) { print $_ if /^a/;}

112

112Friday, 06 August 2010

Page 145: Shooting from the hip - Perl at the command line for DBAs

Perl command line must-know facts (3)perl -pe 's/(^a\w+)/$1/'# like -ne, but prints each line

$ perl -MO=Deparse -pe 's/(^a\w+)/$1/'LINE: while (defined($_ = <ARGV>)) { s/(^a\w+)/$1/;}continue { print $_;}

113

113Friday, 06 August 2010

Page 146: Shooting from the hip - Perl at the command line for DBAs

Perl command line must-know facts (4)perl -le 'print "hello"'# strips newlines from input and adds # them to output

$ perl -e 'print "hello"'hello$ $ perl -le 'print "hello"'hello$ 114

114Friday, 06 August 2010

Page 147: Shooting from the hip - Perl at the command line for DBAs

Perl command line must-know facts (5)perl -lane 'print $F[0]'# splits input into @F array

$ echo "a b c" | \ perl -lane 'print $F[1]'b $ echo "a b c" | \ perl -lane 'print $F[2]'c 115

115Friday, 06 August 2010

Page 148: Shooting from the hip - Perl at the command line for DBAs

Perl and shell contention for $

116

Take the $$$ and run

Perl command line must-know facts (6)

#!/bin/bash

116Friday, 06 August 2010

Page 149: Shooting from the hip - Perl at the command line for DBAs

Beware of $VARIABLES on the command line$ perl -le "$x=1; print $x" syntax error at -e line 1, near "="Execution of -e aborted due to compilation errors.

117

117Friday, 06 August 2010

Page 150: Shooting from the hip - Perl at the command line for DBAs

Beware of $VARIABLES on the command line$ perl -le "$x=1; print $x" syntax error at -e line 1, near "="Execution of -e aborted due to compilation errors.

117

consumed by the shell, before Perl can see it

double quotes allow the shell to interpolate variables

117Friday, 06 August 2010

Page 151: Shooting from the hip - Perl at the command line for DBAs

Beware of $VARIABLES on the command line$ perl -le "$x=1; print $x" syntax error at -e line 1, near "="Execution of -e aborted due to compilation errors.

117

consumed by the shell, before Perl can see it

consumed by the shell, before Perl can see it

consumed by the shell, before Perl can see it

double quotes allow the shell to interpolate variables

117Friday, 06 August 2010

Page 152: Shooting from the hip - Perl at the command line for DBAs

Beware of $VARIABLES on the command line$ perl -le "$x=1; print $x" syntax error at -e line 1, near "="Execution of -e aborted due to compilation errors.

117

consumed by the shell, before Perl can see it

consumed by the shell, before Perl can see it$ perl -le '$x=1; print $x'

1

consumed by the shell, before Perl can see it

double quotes allow the shell to interpolate variables

117Friday, 06 August 2010

Page 153: Shooting from the hip - Perl at the command line for DBAs

Beware of $VARIABLES on the command line$ perl -le "$x=1; print $x" syntax error at -e line 1, near "="Execution of -e aborted due to compilation errors.

117

consumed by the shell, before Perl can see it

consumed by the shell, before Perl can see it$ perl -le '$x=1; print $x'

1

consumed by the shell, before Perl can see it

single quotes prevent variable consumption by the shell

consumed by the shell, before Perl can see it

double quotes allow the shell to interpolate variables

117Friday, 06 August 2010

Page 154: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

combining column names

118

118Friday, 06 August 2010

Page 155: Shooting from the hip - Perl at the command line for DBAs

combining column names$ mysql -N -e 'desc world.City'+-------------+----------+----+-----+| ID | int(11) | NO | PRI || Name | char(35) | NO | | | CountryCode | char(3) | NO | | | District | char(20) | NO | | | Population | int(11) | NO | | +-------------+----------+----+-----+

119

119Friday, 06 August 2010

Page 156: Shooting from the hip - Perl at the command line for DBAs

combining column names# Expected result:# SELECT CONCAT_WS('|', # ID,Name,CountryCode,District, # Population) from City

120

120Friday, 06 August 2010

Page 157: Shooting from the hip - Perl at the command line for DBAs

combining column names (I)echo "select concat_ws('|', $(mysql -N -e 'desc world.City' | \ perl -lane 'push @f, $F[0];' \ -e 'END{print join ",", @f}')) from world.City" select concat_ws('|', ID,Name,CountryCode,District,Population) from world.City

121

121Friday, 06 August 2010

Page 158: Shooting from the hip - Perl at the command line for DBAs

combining column names (II)echo "select concat_ws('|', $( mysql -NB -e 'select group_concat(column_name) from information_schema.columns where table_name="City" and table_schema="world"')) from world.City" select concat_ws('|', ID,Name,CountryCode,District,Population) from world.City

122

122Friday, 06 August 2010

Page 159: Shooting from the hip - Perl at the command line for DBAs

combining column names (IIa)echo "select concat_ws('|', $( mysql -NB -e 'select group_concat(column_name) from information_schema.columns where table_name="Country" and table_schema="world"')) from world.Country"select concat_ws('|', Code,Name,Continent,Region,SurfaceArea,IndepYear,Population,LifeExpectancy,GNP,GNPOld,LocalName,GovernmentForm,HeadOfState,Capital,Code2) from world.Country

123

123Friday, 06 August 2010

Page 160: Shooting from the hip - Perl at the command line for DBAs

piping the result back to mysqlecho "select concat_ws('|', $( mysql -NB -e 'select group_concat(column_name) from information_schema.columns where table_name="Country" and table_schema="world"')) as line from world.Country" | mysql | head -n 4lineAFG|Afghanistan|Asia|Southern and Central Asia|652090.00|1919|22720000|45.9|5976.00|Afganistan/Afqanestan|Islamic Emirate|Mohammad Omar|1|AFNLD|Netherlands|Europe|Western Europe|41526.00|1581|15864000|78.3|371362.00|360478.00|Nederland|Constitutional Monarchy|Beatrix|5|NLANT|Netherlands Antilles|North America|Caribbean|800.00|217000|74.7|1941.00|Nederlandse Antillen|Nonmetropolitan Territory of The Netherlands|Beatrix|33|AN

124

124Friday, 06 August 2010

Page 161: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

dumping data

125

$_

125Friday, 06 August 2010

Page 162: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

dumping data

125

$_

125Friday, 06 August 2010

Page 163: Shooting from the hip - Perl at the command line for DBAs

dumping a tab delimited data set # the naive way$ mysql \ -e "SELECT * into outfile '/tmp/city_data' from world.City"

# it works only if:# - /tmp/city_data does not exist# - /tmp is world writable

126

126Friday, 06 August 2010

Page 164: Shooting from the hip - Perl at the command line for DBAs

dumping a tab delimited data set $ mysql -B -N \ -e "SELECT * from world.City" \ > /tmp/city_data

# it works always

# if you omit the "-N" it also # includes a header

127

127Friday, 06 August 2010

Page 165: Shooting from the hip - Perl at the command line for DBAs

dumping a CSV $ mysql -B \ -e "SELECT * from world.City" \ | perl -F"\t" -lane \ 'print join ",", map {s/"/""/g; /^[\d.]+$/ ? $_ : qq("$_")} @F ' \ > /tmp/city_data

128

128Friday, 06 August 2010

Page 166: Shooting from the hip - Perl at the command line for DBAs

dumping a CSV $ mysql -B \ -e "SELECT * from world.City" \ | perl -F"\t" -lane \ 'print join ",", map {s/"/""/g; /^[\d.]+$/ ? $_ : qq("$_")} @F ' \ > /tmp/city_data

128

splits the line by tabs, instead of the default whitespace

128Friday, 06 August 2010

Page 167: Shooting from the hip - Perl at the command line for DBAs

advanced command line techniques

scriptit

129

129Friday, 06 August 2010

Page 168: Shooting from the hip - Perl at the command line for DBAs

use the mysql.sh script The companion code for this tutorial http://tinyurl.com/cli-tut-code-2010

It will save you much typing But use it at your own risk!

130

130Friday, 06 August 2010

Page 169: Shooting from the hip - Perl at the command line for DBAs

Usage• download the script• load it

131

$ source mysql.sh

131Friday, 06 August 2010

Page 170: Shooting from the hip - Perl at the command line for DBAs

mysql.sh functions• my_batch "query"• returns the result of the query. • Without header • Without box

132

$ my_batch "SELECT * FROM test.t1"1 aaa2 bbb3 ccc

132Friday, 06 August 2010

Page 171: Shooting from the hip - Perl at the command line for DBAs

mysql.sh functions• my_value "what"• returns a single value

• e.g.

133

$ my_value "version()"5.1.49

$ my_value "@@server_id"1

133Friday, 06 August 2010

Page 172: Shooting from the hip - Perl at the command line for DBAs

mysql.sh functions• my_var "what"• returns the value of a given variable

• e.g.

134

$ my_var port3306

$ my_var datadir/usr/local/mysql/data

134Friday, 06 August 2010

Page 173: Shooting from the hip - Perl at the command line for DBAs

mysql.sh functions• my_status "what"• returns the value of a given status item

• e.g.

135

$ my_status com_select2653

$ my_status connections452

135Friday, 06 August 2010

Page 174: Shooting from the hip - Perl at the command line for DBAs

mysql.sh functions• my_dump_dataset "query" [header]• returns the values of a given query separated by tabs• if a header is requested, it will be part of the result• e.g.

136

$ my_dump_dataset "select * from world.City" | head -n 51 Kabul AFG Kabol 17800002 Qandahar AFG Qandahar 2375003 Herat AFG Herat 1868004 Mazar-e-Sharif AFG Balkh 1278005 Amsterdam NLD Noord-Holland 731200

136Friday, 06 August 2010

Page 175: Shooting from the hip - Perl at the command line for DBAs

mysql.sh functions• my_csv "query" [separator]• returns the values of a given query separated by

commas, or by a given separator• e.g.

137

$ my_csv 'select * from world.City' |head -n 3"ID","Name","CountryCode","District","Population"1,"Kabul","AFG","Kabol",17800002,"Qandahar","AFG","Qandahar",237500

137Friday, 06 August 2010

Page 176: Shooting from the hip - Perl at the command line for DBAs

inside the command line client

handling

output138

$_

@ @

:-)

138Friday, 06 August 2010

Page 177: Shooting from the hip - Perl at the command line for DBAs

pagermysql> SELECT * FROM world.City;

rec …rec …rec …

4000 + recordsunreadable

139

139Friday, 06 August 2010

Page 178: Shooting from the hip - Perl at the command line for DBAs

pagermysql> pager lessPAGER set to 'less'mysql> SELECT * FROM world.City;

# [ records in a manageable window ]

mysql> nopagerPAGER set to stdout

# back to normal140

140Friday, 06 August 2010

Page 179: Shooting from the hip - Perl at the command line for DBAs

More pager tricksmysql> pager vim -# like 'less', but you can also edit# the results and eventually save # them

141

141Friday, 06 August 2010

Page 180: Shooting from the hip - Perl at the command line for DBAs

More pager tricksmysql> pager md5sumPAGER set to 'md5sum'mysql> select * from City;5d17ffa50d6da200dee621823ade2543 -4079 rows in set (0.01 sec)

# produce a CRC for the result set# instead of displaying it.# Useful for data comparison.# (Thanks to Baron Schwartz

142

142Friday, 06 August 2010

Page 181: Shooting from the hip - Perl at the command line for DBAs

Comparing data sets with md5summysql> select * from City;5d17ffa50d6da200dee621823ade2543 -

mysql> select * from City order by ID;5d17ffa50d6da200dee621823ade2543 -

mysql> select * from City order by name;5ab980f5b69a6e65d3b8cd5a95ec94e0 -

mysql> select * from City order by District;2bf37cbe91b3ffeaebc8c4b6084b8784 -

143

143Friday, 06 August 2010

Page 182: Shooting from the hip - Perl at the command line for DBAs

Comparing data sets with md5summysql> select * from City;5d17ffa50d6da200dee621823ade2543 -

mysql> select * from City order by ID;5d17ffa50d6da200dee621823ade2543 -

mysql> select * from City order by name;5ab980f5b69a6e65d3b8cd5a95ec94e0 -

mysql> select * from City order by District;2bf37cbe91b3ffeaebc8c4b6084b8784 -

143

143Friday, 06 August 2010

Page 183: Shooting from the hip - Perl at the command line for DBAs

More pager tricksmysql> pager cat > /tmp/t1.txtmysql> select "one" union select "two";mysql> pager cat > /tmp/t2.txtmysql> select "one" union select "TWO";mysql> nopagermysql> \! vimdiff -o /tmp/t[12].txt

# see the difference between two # datasets

144

144Friday, 06 August 2010

Page 184: Shooting from the hip - Perl at the command line for DBAs

145

145Friday, 06 August 2010

Page 185: Shooting from the hip - Perl at the command line for DBAs

logging sessionsmysql> tee mylog.txt

# logs everything that you see on# the screen.# your commands, the results,# warnings, error messages, and so on.

mysql> notee

# back to normal146

146Friday, 06 August 2010

Page 186: Shooting from the hip - Perl at the command line for DBAs

Updated presentation slides

you will find an up to date copy of these slides at: http://tinyurl.com/shoot-cl-2010

http://tinyurl.com/shoot-cl-full-2010

147Friday, 06 August 2010

Page 187: Shooting from the hip - Perl at the command line for DBAs

read more http://datacharmer.blogspot.com

148Friday, 06 August 2010

Page 188: Shooting from the hip - Perl at the command line for DBAs

THANKS!Questiontime

Comments on Twitter: @datacharmer

?

This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License.

149Friday, 06 August 2010