File: Pg.pm

package info (click to toggle)
dbishell 0.8.9-7.2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 788 kB
  • ctags: 1,423
  • sloc: perl: 13,353; makefile: 138; sh: 10
file content (575 lines) | stat: -rw-r--r-- 14,820 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package DBIShell::dr::Pg;

#  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 OGREP_FN SGREP_FN FGREP_FN);
use DBIShell::UTIL qw/:context :sql_types _NULLS/;

use vars qw^@EXPORT @EXPORT_OK @ISA $VERSION %EXPORT_TAGS^;
use constant VARHDRSZ => 4;

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

use constant TABLES_QUERY => <<TableQuery;
select tablename as OBJ_NAME from pg_tables
TableQuery

use constant VIEWS_QUERY => <<ViewQuery;
select viewname as OBJ_NAME from pg_views
ViewQuery

use constant PROCS_QUERY => <<ProcsQuery;
select proname as OBJ_NAME from pg_proc
ProcsQuery

use constant TRIGGERS_QUERY => <<TrigQuery;
select tgname as OBJ_NAME from pg_trigger
TrigQuery

use constant USERS_QUERY => <<UserQuery;
select usename as OBJ_NAME from pg_user
UserQuery

use constant KEYWDS =>
  qw(
     abort absolute access action add after aggregate all allocate analyze and
     any are as asc assertion at authorization avg backward before begin
     between binary bit bit_length both by cache cascade cascaded case cast
     catalog char char_length character character_length check close cluster
     coalesce collate collation column comment committed connect connection
     constraint constraints continue convert copy corresponding count createdb
     createuser cross current current_date current_session current_time
     current_timestamp current_user cursor cycle database date day deallocate
     dec decimal declare default deferrable deferred delimiters desc descriptor
     diagnostics disconnect distinct do domain each else encoding end escape
     except exception exclusive exec execute exists extend external extract
     false fetch first float for force foreign forward found from full function
     get global go goto group handler having hour identity immediate in
     increment index indicator inherits initially inner input insensitive
     instead intersect interval into is isnull isolation join key lancompiler
     language last leading left level like listen load local location lower
     match max maxvalue min minute minvalue mode module month move names
     national natural nchar new next no nocreatedb nocreateuser none not
     nothing notify notnull null nullif numeric octet_length of offset oids on
     only open operator option or order outer output overlaps partial password
     pendant position precision prepare preserve primary prior privileges
     procedural procedure public recipe references reindex relative reset
     restrict returns right row rows rule schema scroll second section sequence
     serial serializable session session_user set setof share size some sql
     sqlcode sqlerror sqlstate start statement stdin stdout substring sum
     system_user table temp temporary then time timestamp timezone_hour
     timezone_minute to trailing transaction translate translation trigger
     trim true trusted type union unique unknown unlisten until upper usage
     user using vacuum valid value values varchar varying verbose version view
     when whenever where with work write year zone
    );

use constant DBI_ATTRIB => DBIShell::dr::DEFAULT::DBI_ATTRIB;

use constant CMNDS =>
  qw(alter
     cd
     commit
     create
     delete
     describe
     drop
     explain
     grant
     insert
     lock
     noaudit
     optimize
     read
     rename
     revoke
     rollback
     select
     show
     truncate
     unlock
     update
    );

use constant CREATABLE =>
  qw(aggregate
     constraint
     database
     function
     group
     index
     operator
     procedural
     rule
     sequence
     table
     temp
     temporary
     trigger
     trusted
     type
     unique
     user
     view
    );

use constant TRANSACTION => qw(work transaction);

use constant PRIVILEGES => qw(select insert update delete rule all);

use constant COMPLETION_MAP =>
  (
   from        => TGREP_FN,
   help        => HGREP_FN,
   into        => TGREP_FN,
   join        => TGREP_FN,
   read        => FGREP_FN,
   show        => qw(tables procs views triggers users), #SGREP_FN,
   table       => TGREP_FN,
   update      => TGREP_FN,
   cd          => FGREP_FN,
   describe    => OGREP_FN,
   unlock      => [ qw(table) ],
   select      => [ KEYWDS    ],
   delete      => [ qw(from)  ],
   create      => [ CREATABLE ],
   drop        => [ CREATABLE ],
   insert      => [ qw(into)  ],
   not         => [ qw(null)  ],
   is          => [ qw(null not) ],
   alter       => [ qw(table group user)],
   abort       => [ TRANSACTION ],
   begin       => [ TRANSACTION ],
   commit      => [ TRANSACTION ],
   end         => [ TRANSACTION ],
   rollback    => [ TRANSACTION ],
   constraint  => [ qw(trigger) ],
   grant       => [ PRIVILEGES  ],
   revoke      => [ PRIVILEGES  ],
   procedural  => [ qw(language) ],
   reindex     => [ qw(table database index)],
   temporary   => [ qw(table) ],
   unique      => [ qw(index) ],
   vacuum      => [ qw(analyze verbose) ],
  );

<<'PIQT_COMPLETION_MAP';
    analyze     => [qw(&cmpl_dbs)],
    copy        => [qw(binary &cmpl_tables)],
    database    => ['&cmpl_dbs'],
    describe    => ['&cmpl_tables'],
    from        => ['&cmpl_tables'],
    group       => ['&cmpl_groups'],
    index       => ['&cmpl_indexes'],
    into        => ['&cmpl_tables'],
    join        => ['&cmpl_tables'],
    select      => ['@sqlkeywords'],
    sequence    => ['&cmpl_sequences'],
    show        => ['&cmpl_tables'],
    table       => ['&cmpl_tables'],
    update      => ['&cmpl_tables'],
    user        => ['&cmpl_users'],
    vacuum      => [qw(verbose analyze &cmpl_dbs)],
    verbose     => [qw(analyze &cmpl_dbs)],
    view        => ['&cmpl_views'],
PIQT_COMPLETION_MAP

sub DEBUG (@) {warn(@_)}

sub new ($$$)
{
    my $package = ref($_[0]) ? ref(shift()) : shift();
    my $driver  = shift() || 'Pg';
    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});

    #bless($engine, $package);

    #use Data::Dumper;
    #DEBUG(Data::Dumper->Dump([$engine],["*OBJ"]),"\n");

    return $engine;
}

sub showables ($)
{
    return (qw(tables procs views triggers users),
	    $_[0]->procs(),
	    $_[0]->views()
	   )
}

sub _tables ($)
{
    my @tables;
    my $engine = $_[0];
    my $dbh    = $engine->dbh();

    eval
    {
	my %data;
	my $sth = $dbh->prepare(TABLES_QUERY)
	  || die("prepare(TABLES_QUERY) failed: ",$dbh->errstr(),"\n");
	$sth->execute()
	  || die("execute(TABLES_QUERY) failed: ",$sth->errstr(),"\n");
	$sth->bind_columns(undef, \@data{ @{ $sth->{NAME_uc} } })
	  || die("bind_cols(TABLES_QUERY) failed: ",$sth->errstr(),"\n");
	while($sth->fetchrow_arrayref())
	{
	    #
	    #warn('KEYS: ',join(',',keys(%data)),"\n");
	    push(@tables, $data{OBJ_NAME});
	}
	$sth->finish();
    };

    if($@)
    {
	chomp($engine->{ERROR} = $@);
	return ();
    }

    return @tables;
}

sub _views ($)
{
    my @views;
    my $engine = $_[0];
    my $dbh    = $engine->dbh();

    eval
    {
	my %data;
	my $sth = $dbh->prepare(VIEWS_QUERY)
	  || die("prepare(VIEWS_QUERY) failed: ",$dbh->errstr(),"\n");

	$sth->execute()
	  || die("execute(VIEWS_QUERY) failed: ",$sth->errstr(),"\n");
	$sth->bind_columns(undef, \@data{ @{ $sth->{NAME_uc} } })
	  || die("bind_cols(VIEWS_QUERY) failed: ",$sth->errstr(),"\n");
	while($sth->fetchrow_arrayref()) { push(@views, $data{OBJ_NAME}) }
	$sth->finish();
    };

    if($@)
    {
	chomp($engine->{ERROR} = $@);
	return ();
    }

    return @views;
}

sub _procs ($)
{
    my @procs;
    my $engine = $_[0];
    my $dbh    = $engine->dbh();

    eval
    {
	my %data;
	my $sth = $dbh->prepare(PROCS_QUERY)
	  || die("prepare(PROCS_QUERY) failed: ",$dbh->errstr(),"\n");
	$sth->execute()
	  || die("execute(PROCS_QUERY) failed: ",$sth->errstr(),"\n");
	$sth->bind_columns(undef, \@data{ @{ $sth->{NAME_uc} } })
	  || die("bind_cols(PROCS_QUERY) failed: ",$sth->errstr(),"\n");
	while($sth->fetchrow_arrayref()) { push(@procs, $data{OBJ_NAME}) }
	$sth->finish();
    };

    if($@)
    {
	chomp($engine->{ERROR} = $@);
	return ();
    }

    return @procs;
}

#::

sub _triggers ($)
{
    my @triggers;
    my $engine = $_[0];
    my $dbh    = $engine->dbh();

    eval
    {
	my %data;
	my $sth = $dbh->prepare(TRIGGERS_QUERY)
	  || die("prepare(TRIGGERS_QUERY) failed: ",$dbh->errstr(),"\n");
	$sth->execute()
	  || die("execute(TRIGGERS_QUERY) failed: ",$sth->errstr(),"\n");
	$sth->bind_columns(undef, \@data{ @{ $sth->{NAME_uc} } })
	  || die("bind_cols(TRIGGERS_QUERY) failed: ",$sth->errstr(),"\n");
	while($sth->fetchrow_arrayref()) { push(@triggers, $data{OBJ_NAME}) }
	$sth->finish();
    };

    if($@)
    {
	chomp($engine->{ERROR} = $@);
	return ();
    }

    return @triggers;
}

sub _users ($)
{
    my @users;
    my $engine = $_[0];
    my $dbh    = $engine->dbh();

    eval
    {
	my %data;
	my $sth = $dbh->prepare(USERS_QUERY)
	  || die("prepare(USERS_QUERY) failed: ",$dbh->errstr(),"\n");
	$sth->execute()
	  || die("execute(USERS_QUERY) failed: ",$sth->errstr(),"\n");
	$sth->bind_columns(undef, \@data{ @{ $sth->{NAME_uc} } })
	  || die("bind_cols(USERS_QUERY) failed: ",$sth->errstr(),"\n");
	while($sth->fetchrow_arrayref()) { push(@users, $data{OBJ_NAME}) }
	$sth->finish();
    };

    if($@)
    {
	chomp($engine->{ERROR} = $@);
	return ();
    }

    return @users;
}



sub show ($$$)
{
    my $rv;
    my $engine = shift(@_);
    my $sh     = shift(@_);
    my $target = shift(@_);

    #warn("0: $engine\-\>($sh, $target)\n");

    if(0)
    {
	# any Pg specific showables should be intercepted here
    }
    else
    {
	return $engine->DBIShell::dr::DEFAULT::show($sh, $target);
    }
}



sub describe ($$$)
{
    use constant DESCRIBE_QUERY => <<DQ_SQL;
select a.attnum      as ATTR_NUM,
       a.attname     as ATTR_NAME,
       t.typname     as ATTR_TYPE,
       a.attlen      as ATTR_LEN,
       a.atttypmod   as ATTR_MOD,
       a.attnotnull  as ATTR_NNL,
       a.atthasdef   as ATTR_DEF,
       d.adsrc       as ATTR_DVAL
FROM   pg_class     c,
       pg_type      t,
       pg_attribute a,
       pg_attrdef   d
WHERE  c.relname   = ?
and    a.attnum    > 0
and    a.atthasdef
and    a.attrelid  = c.oid
and    d.adrelid   = c.oid
and    a.atttypid  = t.oid
and    d.adnum     = a.attnum

UNION

select a.attnum      as ATTR_NUM,
       a.attname     as ATTR_NAME,
       t.typname     as ATTR_TYPE,
       a.attlen      as ATTR_LEN,
       a.atttypmod   as ATTR_MOD,
       a.attnotnull  as ATTR_NNL,
       a.atthasdef   as ATTR_DEF,
       NULL::text    as ATTR_DVAL
FROM   pg_class     c,
       pg_type      t,
       pg_attribute a
WHERE  c.relname  = ?
and    a.attnum   > 0
and    a.attrelid  = c.oid
and    a.atttypid  = t.oid
and    not a.atthasdef
DQ_SQL

    use constant D_POS   => 0;
    use constant D_NAM   => 1;
    use constant D_TYP   => 2;
    use constant D_LEN   => 3;
    use constant D_MOD   => 4;
    use constant D_NNL   => 5;
    use constant D_DEF   => 6;
    use constant D_DVL   => 7;
    use constant D_PLIST => (D_NAM, D_TYP, D_DEF, D_NNL);

    my($i,$dbh,$dqd);
    my $engine = shift(@_);
    my $sh     = shift(@_);
    my $target = shift(@_);
    my @desc;
    my @l;
    my $sth;
    my $csep;
    $csep = $sh->getvar('FIELD_SEPARATOR');
    $csep = defined($csep) ? $csep : '|';

    $i = 0;
    $dbh = $engine->dbh();

    eval
    {
	$sth = $dbh->prepare(DESCRIBE_QUERY)
	  || die($dbh->errstr,"\n");

	$sth->bind_param(1, $target,   SQL_VARCHAR_T)
	  || die($sth->errstr,"\n");

	$sth->bind_param(2, $target,   SQL_VARCHAR_T)
	  || die($sth->errstr,"\n");

	$sth->execute()
	  || die($sth->errstr,"\n");

	$dqd = $sth->fetchall_arrayref()
	  || die($sth->errstr,"\n");

	$sth->finish();
    };

    if ($@)
    {
	$engine->{ERRNO} = $!;
	$engine->{ERROR} = $@;
	chomp($engine->{ERROR});
	$sth && $sth->finish();
	return 0;
    }

    unless (@$dqd)
    {
	$engine->{ERRNO} = 0;
	$engine->{ERROR} = "No such object [$target] found";
	$sth && $sth->finish();
	return 0;
    }

    foreach my $row (@{$dqd})
    {
	use integer;

	my @rdsc;
	$rdsc[D_NAM] = $row->[D_NAM];
	$rdsc[D_TYP] = $engine->_type2str($row);
	$rdsc[D_DEF] = $row->[D_DEF] ? $row->[D_DVL] : '';
	$rdsc[D_NNL] = $row->[D_NNL] ? 'not null' : 'null';

	push(@desc, \@rdsc);

	for my $p (D_PLIST)
	{
	    my $s = length($rdsc[$p]) || 4;
	    ($l[$p] < $s) && ($l[$p] = $s);
	}
    }

    my $format =
      join($csep, (map { sprintf("%%-%d.%ds", $_, $_) } (@l[D_PLIST])), "\n");

    $sh->errputf(CONTEXT_NIL, " \n");
    $sh->start_pager(scalar($#{$dqd}+2));
    $sh->outputf(CONTEXT_NIL, "Table/View: %s:\n", $target);
    $sh->outputf(CONTEXT_NIL, $format, qw(NAME TYPE DEFAULT NULL));
    foreach my $r (@desc)
    {
	$sh->outputf(CONTEXT_NIL, $format, _NULLS(@{$r}[D_PLIST]));
    }
    $sh->stop_pager();
    $sth->finish();
    return 1;
}

sub _type2str ($$)
{
    my $engine = $_[0];
    my $row    = $_[1];
    my $type_spec;
    my $type_prec;
    my $type_xtra;

    $type_spec = $row->[D_TYP];
    $type_prec = '';
    $type_xtra = '';
    # following the logic in psql.c:

    $type_spec =~ s/bpchar/char/;

    if ($type_spec =~ s/^_//) { $type_xtra .= '[]' }

    if($row->[D_TYP] =~ /^_?(?:bp|var)char$/)
    {
	$type_prec =
	  ($row->[D_MOD] == -1) ?
	    '' :
	      sprintf('(%d)', $row->[D_MOD] - VARHDRSZ);
    }
    elsif ($row->[D_TYP] eq 'numeric')
    {
	use integer;
	my $mod    = int($row->[D_MOD] - VARHDRSZ);
	$type_prec =
	  sprintf("(%d.%d)", ($mod >> 16) & 0xffff, $mod & 0xffff);
    }

    return join('', $type_spec, $type_prec, $type_xtra);
}

__END__