File: mysql.pm

package info (click to toggle)
dbishell 0.8.9-7
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 828 kB
  • ctags: 1,423
  • sloc: perl: 13,353; makefile: 138; sh: 15
file content (391 lines) | stat: -rw-r--r-- 11,137 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package DBIShell::dr::mysql;

#  dbishell: A generic database shell based on the Perl DBI layer
#  Copyright (C) 2000  Vivek Dasmohapatra (vivek@etla.org)

#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.

#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

use strict;

use DBI;
use Exporter ();
use DBIShell::dr::DEFAULT qw(TGREP_FN HGREP_FN FGREP_FN);
use DBIShell::UTIL qw/:context :param _NULLS/;

use vars qw($VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS @ISA);

$VERSION     = 0.01_25;
@EXPORT      = ();
@EXPORT_OK   = ();
%EXPORT_TAGS = ();
@ISA         = qw(DBIShell::dr::DEFAULT);

use subs qw(connect);

use constant DBI_ATTRIB => {
			    PrintError  => 0,
			    RaiseError  => 0,
			    AutoCommit  => 1,
			    ChopBlanks  => 0,
			    LongReadLen => 1024,
			    LongTruncOk => 1
			    };

use constant CMNDS =>
  qw(alter
     select
     insert
     update
     delete
     create
     drop
     describe
     replace
     show
     read
     cd
    );

#     commit
#     rollback

use constant KEYWDS => qw^
into          from           where        like   in  and         or     not
null          is             order        group  by  distinct    table  tables
varchar       char           numeric      integer    bit_count   between
isnull        coalesce       interval     regexp     rlike
strcmp        binary         ifnull()     if()       case        when
abs()         sign()  mod()  floor()      ceiling()  round()     least()
greatest()    exp()   log()  log10()      pow()      sqrt()      pi()
cos()         sin()   tan()  acos()       degrees()  radians()   asin()
atan()        atan2() cot()  rand(1)      truncate() ascii()     ord()
bin()         conv()  oct()  hex()        concat()   length()    octet_length()
char()        char_length()  character_length()      locate()    position()
instr()       lpad() rpad()  left()       right()    substring() mid()
substring_index()   ltrim()  rtrim()      trim()     soundex()   space()
replace()     repeat()       reverse()    insert()   elt()       field()
find_in_set() make_set()     export_set() lcase()    lower()     ucase()
upper()       load_file()    dayofweek()  weekday()  dayofmonth()
dayofyear()   month()        dayname()    monthname()            quarter()
week()        year()         yearweek()   hour()     minute()    second()
period_add()  period_diff()  date_add()   date_sub() adddate()   subdate()
to_days()     from_days()    date_format()           time_format()
curdate()     current_date   curtime()    now()      sysdate()   current_time
unix_timestamp()             from_unixtime()         sec_to_time()
time_to_sec() database()     user()       session_user()
system_user() password()     encrypt()    encode()   decode()    md5()
last_insert_id()             format()     version()  get_lock()  release_lock()
benchmark()   count()        avg()        min()      max()       sum()
std()        stddev()        bit_or()     bit_and()  limit
^;

use constant COMPLETION_MAP =>
  (
   select   => [ KEYWDS ],
   from     => TGREP_FN,
   update   => TGREP_FN,
   into     => TGREP_FN,
   index    => [qw(from)],
   describe => TGREP_FN,
   join     => TGREP_FN,
   help     => HGREP_FN,
   read     => FGREP_FN,
   cd       => FGREP_FN,
   create   => [qw(unique table database index)],
   drop     => [qw(table database index)],
   alter    => [qw(table)],
   optimize => [qw(table)],
   check    => [qw(table)],
   lock     => [qw(tables)],
   unlock   => [qw(tables)],
   delete   => [qw(from)],
   insert   => [qw(low_priority delayed ignore into)],
   replace  => [qw(low_priority delayed ignore into)],
   load     => [qw(tables data)],
   data     => [qw(low_priority local infile)],
   flush    => [qw(hosts logs privileges tables status)],
   show     => [qw(databases tables columns processlist
                   index status variables table grants)],
   table    => TGREP_FN,
   tables   => [qw(like)],
   unique   => [qw(index)],
   grants   => [qw(for)]
  );


sub new ($$$)
{
    my $package = ref($_[0]) ? ref(shift()) : shift();
    my $driver  = shift()   || 'mysql';
    my $sh      = $_[0];
    my $engine  = $package->DBIShell::dr::DEFAULT::new($driver, @_);

    $engine->_var(COMP_MAP => { COMPLETION_MAP() }) || warn($engine->{ERROR});
    $engine->_var(KEYWORDS => [ KEYWDS()         ]) || warn($engine->{ERROR});
    $engine->_var(COMMANDS => [ CMNDS()          ]) || warn($engine->{ERROR});
    $engine->_var(DBI_ATTRIB => DBI_ATTRIB)         || warn($engine->{ERROR});

    return $engine;
}

sub set_initvars ($)
{
    my $engine = shift(@_);
    my $sh     = shift(@_);
    $sh->setvar("CASE_SENSITIVE=1");
}

sub connect			#($$)
{
    my $title;
    my $engine = shift(@_);
    my $opt    = shift(@_);
    my $attrib = shift(@_) || $engine->{DBI_ATTRIB};

   # warn("engine  = $engine\n");
   # warn("attr    = ",stringify(' ','',$opt),    "\n");
   # warn("attr    = ",stringify(' ','',$attrib), "\n");

    my $dbh;

    $dbh = $engine->DBIShell::dr::DEFAULT::connect($opt,$attrib)
      || return undef;

    $engine->{DR_DATA}{dsn} ||= {};

    foreach my $pv (split(/;/,$opt->{dsn}))
    {
	my($k,$v) = split(/=/,$pv);
	$engine->{DR_DATA}{dsn}{$k} = $v;
    }

    $engine->title($engine->_title());
    $engine->prompt(join('',$engine->title(),'>'));

    return $dbh;
}

sub interpret ($$$)
{
    my $i      = undef;

    my $nparam;
    my $engine = shift(@_);
    my $sh     = shift(@_);
    my $query  = shift(@_);

    if ($query =~ /^\s*help\s+(.*)/i)
    {
	#warn("CALLING HELP MODULE\n");
	my $thing = $1;
	$thing =~ s/\s+$//g;
	$thing =~ s/ /_/g;
	#warn("REQUESTING HELP FOR $thing\n");
	return $engine->help($sh,$thing);
    }

    if ($query =~ /^\s*load\s/si)
    {
	# we can attempt to use the H->tables functionality,
	# wrapped in an eval, just in case the DBD driver
	# implements something: SQL9X is no use - it [as usual]
	# specifies no standards or behaviours for this:
	if ($query =~ /tables/i) { $i = $engine->load_tables() }

	# we can use describe functionality to accomplish this one:
	# as DBI will allow us to describe tables by doing a select
	# that will never return rows [where 1 = 0 clause, for example]
	if ($query =~ /fields(?:\s+(.*))?/i)
	{
	    my $tbl = $1;
	    my @tbl = split(/\s+/, $tbl);

	    unless (@tbl) { @tbl = $engine->tables() }
	    $i = $engine->_load_columns(@tbl);
	}
    }
    else
    {
	my(@cols,@parm,%row,$sth);
	my $dbh = $engine->dbh();

	#xwarn("Attempting to INTERPRET SQL [$dbh]\n");

	$query = $engine->map_inout_parameters($sh,$query);

	unless($sth = $dbh->prepare($query))
	{
	    $engine->{ERROR} = $dbh->errstr;
	    return 0;
	}

	if ($nparam = $sth->{NUM_OF_PARAMS})
	{
	    $engine->bind_parameters($sh, $sth);
	}

	unless($sth->execute())
	{
	    $engine->{ERROR} = $sth->errstr;
	    return 0;
	}

	#xwarn("QUERY executed");

	# are we in a select type query?
	# NB: Unlike other SQL engines, mysql explicitly implements describe
	# as part of it's SQL syntax, so we don't need to do anything special
	# with it, other than ensure we use the space stripped 'rescan_format'
	# since the fields it returns are potentially very large, and almost
	# always only a few bytes are used:
	if ($sth->{NUM_OF_FIELDS})
	{
	    if($query =~ /^\s*describe\s|^\s*show\s|^\s*explain\s/i
	       || $sh->getvar('PRESCAN_ROWS'))
	    {
		# fetchall arrayref seems to invalidate a whole bunch of
		# handle attributes, so we have to precache them:
		my $dummy_sth = DBIShell::UTIL::cache_sth_attr($sth);
		my $data      = $sth->fetchall_arrayref();
		my $fmt  =
		  $engine->prescan_format($sh,$dummy_sth,$data);

		$sh->start_pager($#{$data}+1);
		$sh->outputf(CONTEXT_HEAD, $fmt, @{ $dummy_sth->{NAME} });
		for (my $x = 0; $x <= $#{$data}; $x++)
		{
		    $sh->outputf(CONTEXT_DATA, $fmt, _NULLS(@{ $data->[$x] }));
		}
		$sh->stop_pager();
	    }
	    else
	    {
		my @fmt;

		unless($sth->bind_columns(undef, \@row{@{ $sth->{NAME} }}))
		{
		    $engine->{ERROR} = $sth->errstr();
		    return 0;
		}

		my $fmt = $engine->noscan_format($sh,$sth);

		$sh->start_pager($sth->rows());
		$sh->outputf(CONTEXT_HEAD, $fmt, @{ $sth->{NAME} });
		while ($sth->fetchrow_arrayref())
		{
		    $sh->outputf(CONTEXT_DATA,
				 $fmt,
				 _NULLS(@row{@{ $sth->{NAME} }})
				);
		}
		$sh->stop_pager();
	    }
	    $i++;
	}
	else			# or is this a non-row returning thing?
	{
	    my $n = $sth->rows();
	    my $nstr =
	      (defined($n) && ($n >= 0))?
		(($n == 1)?"$n row":"$n rows"):
		  'unknown number of rows';

	    # again. mysql implements database reconnection as
	    # an implicit part of it's SQL syntax, [at least within the
	    # same mysql instance], so we need to catch instances when
	    # we've done this and reset the DBIShell prompt:
	    if ($query =~ /^\s*use\s+(\S+)/si)
	    {
		$engine->title($engine->_title());
		$engine->prompt(join('',$engine->title(),'>'));
	    }

	    $sh->errputf(CONTEXT_META, "Ok - [%s] affected\n", $nstr);
	    $i++;
	}

	# mysql doesn't do io parameters [or o parameters, for that matter]
	# but this does no harm, and if it ever does support it, this will
	# automagically start working...
	for (my $x = 0; $x < $nparam; $x++)
	{
	    ($sh->get_parameter_io($x) == PARAM_OUT) || next;

	    my $pname = $sh->get_parameter_name($x);
	    $sh->outputf(CONTEXT_META,
			 "Parameter [%s] == %s\n",
			 $pname,
			 _NULLS($sh->getvar($pname))
			);
	}

	$sth->finish();
    }

    return $i;
}

sub _title ($)
{
    use constant WHAT_DB_QUERY => <<'WhatDB';
select
CONCAT('mysql:',
       IF(LENGTH(USER()),
          SUBSTRING(USER(), 1, locate('@', user())),
          '-'
         )
       ),
IF(LENGTH(DATABASE()),DATABASE(),'-')
WhatDB

    my $sth;
    my @idstr;
    my $idstr;
    my $engine = shift(@_);
    my $dbh    = $engine->dbh();

    eval
    {
	$sth = $dbh->prepare(WHAT_DB_QUERY)
	  || die("Error retrieving database name: ",  $dbh->errstr(),"\n");
	$sth->execute()
	  || die("Error retrieving database name: ",  $sth->errstr(),"\n");
	$sth->bind_columns(undef, \@idstr[ 0 .. $#{$sth->{NAME}} ])
	  || die("Error retrieving database name: ",  $sth->errstr(),"\n");
	$sth->fetchrow_arrayref()
	  || die("Unable to retrieve user/db names: ",$sth->errstr(),"\n");
	$idstr = join('%s:', (map { s/%/%%/g; $_ } @idstr));
	$sth->finish();
    };

    if($@)
    {
	$engine->{ERRNO} = -1;
	$engine->{ERROR} = $@;
	return 'mysql:{ERROR!}';
    }

    return sprintf($idstr, $engine->{DR_DATA}{dsn}{hostname});
}


__END__

# TLF: Nikola Tesla died for you....