-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPg.pm
4222 lines (3212 loc) · 160 KB
/
Pg.pm
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*-cperl-*-
# $Id: Pg.pm 13172 2009-08-07 14:38:45Z turnstep $
#
# Copyright (c) 2002-2009 Greg Sabino Mullane and others: see the Changes file
# Portions Copyright (c) 2002 Jeffrey W. Baker
# Portions Copyright (c) 1997-2001 Edmund Mergl
# Portions Copyright (c) 1994-1997 Tim Bunce
#
# You may distribute under the terms of either the GNU General Public
# License or the Artistic License, as specified in the Perl README file.
use strict;
use warnings;
use 5.006001;
{
package DBD::Pg;
use version; our $VERSION = qv('2.15.1');
use DBI ();
use DynaLoader ();
use Exporter ();
use vars qw(@ISA %EXPORT_TAGS $err $errstr $sqlstate $drh $dbh $DBDPG_DEFAULT @EXPORT);
@ISA = qw(DynaLoader Exporter);
%EXPORT_TAGS =
(
async => [qw(PG_ASYNC PG_OLDQUERY_CANCEL PG_OLDQUERY_WAIT)],
pg_types => [qw(
PG_ABSTIME PG_ABSTIMEARRAY PG_ACLITEM PG_ACLITEMARRAY PG_ANY
PG_ANYARRAY PG_ANYELEMENT PG_ANYENUM PG_ANYNONARRAY PG_BIT
PG_BITARRAY PG_BOOL PG_BOOLARRAY PG_BOX PG_BOXARRAY
PG_BPCHAR PG_BPCHARARRAY PG_BYTEA PG_BYTEAARRAY PG_CHAR
PG_CHARARRAY PG_CID PG_CIDARRAY PG_CIDR PG_CIDRARRAY
PG_CIRCLE PG_CIRCLEARRAY PG_CSTRING PG_CSTRINGARRAY PG_DATE
PG_DATEARRAY PG_FLOAT4 PG_FLOAT4ARRAY PG_FLOAT8 PG_FLOAT8ARRAY
PG_GTSVECTOR PG_GTSVECTORARRAY PG_INET PG_INETARRAY PG_INT2
PG_INT2ARRAY PG_INT2VECTOR PG_INT2VECTORARRAY PG_INT4 PG_INT4ARRAY
PG_INT8 PG_INT8ARRAY PG_INTERNAL PG_INTERVAL PG_INTERVALARRAY
PG_LANGUAGE_HANDLER PG_LINE PG_LINEARRAY PG_LSEG PG_LSEGARRAY
PG_MACADDR PG_MACADDRARRAY PG_MONEY PG_MONEYARRAY PG_NAME
PG_NAMEARRAY PG_NUMERIC PG_NUMERICARRAY PG_OID PG_OIDARRAY
PG_OIDVECTOR PG_OIDVECTORARRAY PG_OPAQUE PG_PATH PG_PATHARRAY
PG_PG_ATTRIBUTE PG_PG_CLASS PG_PG_PROC PG_PG_TYPE PG_POINT
PG_POINTARRAY PG_POLYGON PG_POLYGONARRAY PG_RECORD PG_RECORDARRAY
PG_REFCURSOR PG_REFCURSORARRAY PG_REGCLASS PG_REGCLASSARRAY PG_REGCONFIG
PG_REGCONFIGARRAY PG_REGDICTIONARY PG_REGDICTIONARYARRAY PG_REGOPER PG_REGOPERARRAY
PG_REGOPERATOR PG_REGOPERATORARRAY PG_REGPROC PG_REGPROCARRAY PG_REGPROCEDURE
PG_REGPROCEDUREARRAY PG_REGTYPE PG_REGTYPEARRAY PG_RELTIME PG_RELTIMEARRAY
PG_SMGR PG_TEXT PG_TEXTARRAY PG_TID PG_TIDARRAY
PG_TIME PG_TIMEARRAY PG_TIMESTAMP PG_TIMESTAMPARRAY PG_TIMESTAMPTZ
PG_TIMESTAMPTZARRAY PG_TIMETZ PG_TIMETZARRAY PG_TINTERVAL PG_TINTERVALARRAY
PG_TRIGGER PG_TSQUERY PG_TSQUERYARRAY PG_TSVECTOR PG_TSVECTORARRAY
PG_TXID_SNAPSHOT PG_TXID_SNAPSHOTARRAY PG_UNKNOWN PG_UUID PG_UUIDARRAY
PG_VARBIT PG_VARBITARRAY PG_VARCHAR PG_VARCHARARRAY PG_VOID
PG_XID PG_XIDARRAY PG_XML PG_XMLARRAY
)]
);
{
package DBD::Pg::DefaultValue;
sub new { my $self = {}; return bless $self, shift; }
}
$DBDPG_DEFAULT = DBD::Pg::DefaultValue->new();
Exporter::export_ok_tags('pg_types', 'async');
@EXPORT = qw($DBDPG_DEFAULT PG_ASYNC PG_OLDQUERY_CANCEL PG_OLDQUERY_WAIT PG_BYTEA);
require_version DBI 1.52;
bootstrap DBD::Pg $VERSION;
$err = 0; # holds error code for DBI::err
$errstr = ''; # holds error string for DBI::errstr
$sqlstate = ''; # holds five character SQLSTATE code
$drh = undef; # holds driver handle once initialized
## These two methods are here to allow calling before connect()
sub parse_trace_flag {
my ($class, $flag) = @_;
return (0x7FFFFF00 - 0x08000000) if $flag eq 'DBD'; ## all but the prefix
return 0x01000000 if $flag eq 'pglibpq';
return 0x02000000 if $flag eq 'pgstart';
return 0x04000000 if $flag eq 'pgend';
return 0x08000000 if $flag eq 'pgprefix';
return 0x10000000 if $flag eq 'pglogin';
return 0x20000000 if $flag eq 'pgquote';
return 0x20000000 if $flag eq 'pgcoro'; # XXX: pgquote seems to be unused
return DBI::parse_trace_flag($class, $flag);
}
sub parse_trace_flags {
my ($class, $flags) = @_;
return DBI::parse_trace_flags($class, $flags);
}
sub CLONE {
$drh = undef;
return;
}
## Deprecated
sub _pg_use_catalog {
return 'pg_catalog.';
}
sub driver {
return $drh if defined $drh;
my($class, $attr) = @_;
$class .= '::dr';
$drh = DBI::_new_drh($class, {
'Name' => 'Pg',
'Version' => $VERSION,
'Err' => \$DBD::Pg::err,
'Errstr' => \$DBD::Pg::errstr,
'State' => \$DBD::Pg::sqlstate,
'Attribution' => "DBD::Pg $VERSION by Greg Sabino Mullane and others",
});
DBD::Pg::db->install_method('pg_cancel');
DBD::Pg::db->install_method('pg_endcopy');
DBD::Pg::db->install_method('pg_getline');
DBD::Pg::db->install_method('pg_getcopydata');
DBD::Pg::db->install_method('pg_getcopydata_async');
DBD::Pg::db->install_method('pg_notifies');
DBD::Pg::db->install_method('pg_putcopydata');
DBD::Pg::db->install_method('pg_putcopyend');
DBD::Pg::db->install_method('pg_ping');
DBD::Pg::db->install_method('pg_putline');
DBD::Pg::db->install_method('pg_ready');
DBD::Pg::db->install_method('pg_release');
DBD::Pg::db->install_method('pg_result');
DBD::Pg::db->install_method('pg_rollback_to');
DBD::Pg::db->install_method('pg_savepoint');
DBD::Pg::db->install_method('pg_server_trace');
DBD::Pg::db->install_method('pg_server_untrace');
DBD::Pg::db->install_method('pg_type_info');
DBD::Pg::st->install_method('pg_cancel');
DBD::Pg::st->install_method('pg_result');
DBD::Pg::st->install_method('pg_ready');
DBD::Pg::db->install_method('pg_lo_creat');
DBD::Pg::db->install_method('pg_lo_open');
DBD::Pg::db->install_method('pg_lo_write');
DBD::Pg::db->install_method('pg_lo_read');
DBD::Pg::db->install_method('pg_lo_lseek');
DBD::Pg::db->install_method('pg_lo_tell');
DBD::Pg::db->install_method('pg_lo_close');
DBD::Pg::db->install_method('pg_lo_unlink');
DBD::Pg::db->install_method('pg_lo_import');
DBD::Pg::db->install_method('pg_lo_export');
return $drh;
} ## end of driver
1;
} ## end of package DBD::Pg
{
package DBD::Pg::dr;
use strict;
use Coro ();
use AnyEvent ();
use Coro::AnyEvent ();
use Coro::Handle ();
## Returns an array of formatted database names from the pg_database table
sub data_sources {
my $drh = shift;
my $attr = shift || '';
## Future: connect to "postgres" when the minimum version we support is 8.0
my $connstring = 'dbname=template1';
if ($ENV{DBI_DSN}) {
($connstring = $ENV{DBI_DSN}) =~ s/dbi:Pg://;
}
if (length $attr) {
$connstring .= ";$attr";
}
my $dbh = DBD::Pg::dr::connect($drh, $connstring) or return undef;
$dbh->{AutoCommit}=1;
my $SQL = 'SELECT pg_catalog.quote_ident(datname) FROM pg_catalog.pg_database ORDER BY 1';
my $sth = $dbh->prepare($SQL);
$sth->execute() or die $DBI::errstr;
$attr and $attr = ";$attr";
my @sources = map { "dbi:Pg:dbname=$_->[0]$attr" } @{$sth->fetchall_arrayref()};
$dbh->disconnect;
return @sources;
}
sub connect { ## no critic (ProhibitBuiltinHomonyms)
my ($drh, $dbname, $user, $pass, $attr) = @_;
## Allow "db" and "database" as synonyms for "dbname"
$dbname =~ s/\b(?:db|database)\s*=/dbname=/;
my $name = $dbname;
if ($dbname =~ m{dbname\s*=\s*[\"\']([^\"\']+)}) {
$name = "'$1'";
$dbname =~ s/\"/\'/g;
}
elsif ($dbname =~ m{dbname\s*=\s*([^;]+)}) {
$name = $1;
}
$user = defined($user) ? $user : defined $ENV{DBI_USER} ? $ENV{DBI_USER} : '';
$pass = defined($pass) ? $pass : defined $ENV{DBI_PASS} ? $ENV{DBI_PASS} : '';
my ($dbh) = DBI::_new_dbh($drh, {
'Name' => $dbname,
'Username' => $user,
'CURRENT_USER' => $user,
});
# Connect to the database..
DBD::Pg::db::_login($dbh, $dbname, $user, $pass) or return undef;
my $version = $dbh->{pg_server_version};
$dbh->{private_dbdpg}{version} = $version;
if ($attr) {
if ($attr->{dbd_verbose}) {
$dbh->trace('DBD');
}
}
return $dbh;
}
sub private_attribute_info {
return {
};
}
sub _coro_init {
my $fd = shift;
# create a perl filehandle from the file descriptor number
open my $fh, "+>&".$fd
or die "Coro::DBD::Pg unable to clone postgres fd";
my $cfh = Coro::Handle->new_from_fh($fh);
return $cfh;
}
} ## end of package DBD::Pg::dr
{
package DBD::Pg::db;
use DBI qw(:sql_types);
use strict;
sub parse_trace_flag {
my ($h, $flag) = @_;
return DBD::Pg->parse_trace_flag($flag);
}
sub prepare {
my($dbh, $statement, @attribs) = @_;
return undef if ! defined $statement;
# Create a 'blank' statement handle:
my $sth = DBI::_new_sth($dbh, {
'Statement' => $statement,
});
DBD::Pg::st::_prepare($sth, $statement, @attribs) || 0;
return $sth;
}
sub last_insert_id {
my ($dbh, $catalog, $schema, $table, $col, $attr) = @_;
## Our ultimate goal is to get a sequence
my ($sth, $count, $SQL, $sequence);
## Cache all of our table lookups? Default is yes
my $cache = 1;
## Catalog and col are not used
$schema = '' if ! defined $schema;
$table = '' if ! defined $table;
my $cachename = "lii$table$schema";
if (defined $attr and length $attr) {
## If not a hash, assume it is a sequence name
if (! ref $attr) {
$attr = {sequence => $attr};
}
elsif (ref $attr ne 'HASH') {
$dbh->set_err(1, 'last_insert_id must be passed a hashref as the final argument');
return undef;
}
## Named sequence overrides any table or schema settings
if (exists $attr->{sequence} and length $attr->{sequence}) {
$sequence = $attr->{sequence};
}
if (exists $attr->{pg_cache}) {
$cache = $attr->{pg_cache};
}
}
if (! defined $sequence and exists $dbh->{private_dbdpg}{$cachename} and $cache) {
$sequence = $dbh->{private_dbdpg}{$cachename};
}
elsif (! defined $sequence) {
## At this point, we must have a valid table name
if (! length $table) {
$dbh->set_err(1, 'last_insert_id needs at least a sequence or table name');
return undef;
}
my @args = ($table);
## Make sure the table in question exists and grab its oid
my ($schemajoin,$schemawhere) = ('','');
if (length $schema) {
$schemajoin = "\n JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)";
$schemawhere = "\n AND n.nspname = ?";
push @args, $schema;
}
$SQL = "SELECT c.oid FROM pg_catalog.pg_class c $schemajoin\n WHERE relname = ?$schemawhere";
if (! length $schema) {
$SQL .= ' AND pg_catalog.pg_table_is_visible(c.oid)';
}
$sth = $dbh->prepare_cached($SQL);
$count = $sth->execute(@args);
if (!defined $count or $count eq '0E0') {
$sth->finish();
my $message = qq{Could not find the table "$table"};
length $schema and $message .= qq{ in the schema "$schema"};
$dbh->set_err(1, $message);
return undef;
}
my $oid = $sth->fetchall_arrayref()->[0][0];
$oid =~ /(\d+)/ or die qq{OID was not numeric?!?\n};
$oid = $1;
## This table has a primary key. Is there a sequence associated with it via a unique, indexed column?
$SQL = "SELECT a.attname, i.indisprimary, pg_catalog.pg_get_expr(adbin,adrelid)\n".
"FROM pg_catalog.pg_index i, pg_catalog.pg_attribute a, pg_catalog.pg_attrdef d\n ".
"WHERE i.indrelid = $oid AND d.adrelid=a.attrelid AND d.adnum=a.attnum\n".
" AND a.attrelid = $oid AND i.indisunique IS TRUE\n".
" AND a.atthasdef IS TRUE AND i.indkey[0]=a.attnum\n".
q{ AND d.adsrc ~ '^nextval'};
$sth = $dbh->prepare($SQL);
$count = $sth->execute();
if (!defined $count or $count eq '0E0') {
$sth->finish();
$dbh->set_err(1, qq{No suitable column found for last_insert_id of table "$table"});
return undef;
}
my $info = $sth->fetchall_arrayref();
## We have at least one with a default value. See if we can determine sequences
my @def;
for (@$info) {
next unless $_->[2] =~ /^nextval\(+'([^']+)'::/o;
push @$_, $1;
push @def, $_;
}
if (!@def) {
$dbh->set_err(1, qq{No suitable column found for last_insert_id of table "$table"\n});
}
## Tiebreaker goes to the primary keys
if (@def > 1) {
my @pri = grep { $_->[1] } @def;
if (1 != @pri) {
$dbh->set_err(1, qq{No suitable column found for last_insert_id of table "$table"\n});
}
@def = @pri;
}
$sequence = $def[0]->[3];
## Cache this information for subsequent calls
$dbh->{private_dbdpg}{$cachename} = $sequence;
}
$sth = $dbh->prepare_cached('SELECT currval(?)');
$count = $sth->execute($sequence);
return undef if ! defined $count;
return $sth->fetchall_arrayref()->[0][0];
} ## end of last_insert_id
sub ping {
my $dbh = shift;
local $SIG{__WARN__} = sub { } if $dbh->FETCH('PrintError');
my $ret = DBD::Pg::db::_ping($dbh);
return $ret < 1 ? 0 : $ret;
}
sub pg_ping {
my $dbh = shift;
local $SIG{__WARN__} = sub { } if $dbh->FETCH('PrintError');
return DBD::Pg::db::_ping($dbh);
}
sub pg_type_info {
my($dbh,$pg_type) = @_;
local $SIG{__WARN__} = sub { } if $dbh->FETCH('PrintError');
my $ret = DBD::Pg::db::_pg_type_info($pg_type);
return $ret;
}
# Column expected in statement handle returned.
# table_cat, table_schem, table_name, column_name, data_type, type_name,
# column_size, buffer_length, DECIMAL_DIGITS, NUM_PREC_RADIX, NULLABLE,
# REMARKS, COLUMN_DEF, SQL_DATA_TYPE, SQL_DATETIME_SUB, CHAR_OCTET_LENGTH,
# ORDINAL_POSITION, IS_NULLABLE
# The result set is ordered by TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION.
sub column_info {
my $dbh = shift;
my ($catalog, $schema, $table, $column) = @_;
my @search;
## If the schema or table has an underscore or a %, use a LIKE comparison
if (defined $schema and length $schema) {
push @search, 'n.nspname ' . ($schema =~ /[_%]/ ? 'LIKE ' : '= ') .
$dbh->quote($schema);
}
if (defined $table and length $table) {
push @search, 'c.relname ' . ($table =~ /[_%]/ ? 'LIKE ' : '= ') .
$dbh->quote($table);
}
if (defined $column and length $column) {
push @search, 'a.attname ' . ($column =~ /[_%]/ ? 'LIKE ' : '= ') .
$dbh->quote($column);
}
my $whereclause = join "\n\t\t\t\tAND ", '', @search;
my $schemajoin = 'JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)';
my $remarks = 'pg_catalog.col_description(a.attrelid, a.attnum)';
my $column_def = $dbh->{private_dbdpg}{version} >= 80000
? 'pg_catalog.pg_get_expr(af.adbin, af.adrelid)'
: 'af.adsrc';
my $col_info_sql = qq!
SELECT
NULL::text AS "TABLE_CAT"
, quote_ident(n.nspname) AS "TABLE_SCHEM"
, quote_ident(c.relname) AS "TABLE_NAME"
, quote_ident(a.attname) AS "COLUMN_NAME"
, a.atttypid AS "DATA_TYPE"
, pg_catalog.format_type(a.atttypid, NULL) AS "TYPE_NAME"
, a.attlen AS "COLUMN_SIZE"
, NULL::text AS "BUFFER_LENGTH"
, NULL::text AS "DECIMAL_DIGITS"
, NULL::text AS "NUM_PREC_RADIX"
, CASE a.attnotnull WHEN 't' THEN 0 ELSE 1 END AS "NULLABLE"
, $remarks AS "REMARKS"
, $column_def AS "COLUMN_DEF"
, NULL::text AS "SQL_DATA_TYPE"
, NULL::text AS "SQL_DATETIME_SUB"
, NULL::text AS "CHAR_OCTET_LENGTH"
, a.attnum AS "ORDINAL_POSITION"
, CASE a.attnotnull WHEN 't' THEN 'NO' ELSE 'YES' END AS "IS_NULLABLE"
, pg_catalog.format_type(a.atttypid, a.atttypmod) AS "pg_type"
, '?' AS "pg_constraint"
, n.nspname AS "pg_schema"
, c.relname AS "pg_table"
, a.attname AS "pg_column"
, a.attrelid AS "pg_attrelid"
, a.attnum AS "pg_attnum"
, a.atttypmod AS "pg_atttypmod"
, t.typtype AS "_pg_type_typtype"
, t.oid AS "_pg_type_oid"
FROM
pg_catalog.pg_type t
JOIN pg_catalog.pg_attribute a ON (t.oid = a.atttypid)
JOIN pg_catalog.pg_class c ON (a.attrelid = c.oid)
LEFT JOIN pg_catalog.pg_attrdef af ON (a.attnum = af.adnum AND a.attrelid = af.adrelid)
$schemajoin
WHERE
a.attnum >= 0
AND c.relkind IN ('r','v')
$whereclause
ORDER BY "TABLE_SCHEM", "TABLE_NAME", "ORDINAL_POSITION"
!;
my $data = $dbh->selectall_arrayref($col_info_sql) or return undef;
# To turn the data back into a statement handle, we need
# to fetch the data as an array of arrays, and also have a
# a matching array of all the column names
my %col_map = (qw/
TABLE_CAT 0
TABLE_SCHEM 1
TABLE_NAME 2
COLUMN_NAME 3
DATA_TYPE 4
TYPE_NAME 5
COLUMN_SIZE 6
BUFFER_LENGTH 7
DECIMAL_DIGITS 8
NUM_PREC_RADIX 9
NULLABLE 10
REMARKS 11
COLUMN_DEF 12
SQL_DATA_TYPE 13
SQL_DATETIME_SUB 14
CHAR_OCTET_LENGTH 15
ORDINAL_POSITION 16
IS_NULLABLE 17
pg_type 18
pg_constraint 19
pg_schema 20
pg_table 21
pg_column 22
pg_enum_values 23
/);
for my $row (@$data) {
my $typoid = pop @$row;
my $typtype = pop @$row;
my $typmod = pop @$row;
my $attnum = pop @$row;
my $aid = pop @$row;
$row->[$col_map{COLUMN_SIZE}] =
_calc_col_size($typmod,$row->[$col_map{COLUMN_SIZE}]);
# Replace the Pg type with the SQL_ type
$row->[$col_map{DATA_TYPE}] = DBD::Pg::db::pg_type_info($dbh,$row->[$col_map{DATA_TYPE}]);
# Add pg_constraint
my $SQL = q{SELECT consrc FROM pg_catalog.pg_constraint WHERE contype = 'c' AND }.
qq{conrelid = $aid AND conkey = '{$attnum}'};
my $info = $dbh->selectall_arrayref($SQL);
if (@$info) {
$row->[19] = $info->[0][0];
}
else {
$row->[19] = undef;
}
if ( $typtype eq 'e' ) {
$SQL = "SELECT enumlabel FROM pg_catalog.pg_enum WHERE enumtypid = $typoid ORDER BY oid";
$row->[23] = $dbh->selectcol_arrayref($SQL);
}
else {
$row->[23] = undef;
}
}
# Since we've processed the data in Perl, we have to jump through a hoop
# To turn it back into a statement handle
#
return _prepare_from_data
(
'column_info',
$data,
[ sort { $col_map{$a} <=> $col_map{$b} } keys %col_map]
);
}
sub _prepare_from_data {
my ($statement, $data, $names, %attr) = @_;
my $sponge = DBI->connect('dbi:Sponge:', '', '', { RaiseError => 1 });
my $sth = $sponge->prepare($statement, { rows=>$data, NAME=>$names, %attr });
return $sth;
}
sub statistics_info {
my $dbh = shift;
my ($catalog, $schema, $table, $unique_only, $quick, $attr) = @_;
## Catalog is ignored, but table is mandatory
return undef unless defined $table and length $table;
my $schema_where = '';
my @exe_args = ($table);
my $input_schema = (defined $schema and length $schema) ? 1 : 0;
if ($input_schema) {
$schema_where = 'AND n.nspname = ? AND n.oid = d.relnamespace';
push(@exe_args, $schema);
}
else {
$schema_where = 'AND n.oid = d.relnamespace';
}
my $table_stats_sql = qq{
SELECT d.relpages, d.reltuples, n.nspname
FROM pg_catalog.pg_class d, pg_catalog.pg_namespace n
WHERE d.relname = ? $schema_where
};
my $colnames_sql = qq{
SELECT
a.attnum, a.attname
FROM
pg_catalog.pg_attribute a, pg_catalog.pg_class d, pg_catalog.pg_namespace n
WHERE
a.attrelid = d.oid AND d.relname = ? $schema_where
};
my $stats_sql = qq{
SELECT
c.relname, i.indkey, i.indisunique, i.indisclustered, a.amname,
n.nspname, c.relpages, c.reltuples, i.indexprs,
pg_get_expr(i.indpred,i.indrelid) as predicate
FROM
pg_catalog.pg_index i, pg_catalog.pg_class c,
pg_catalog.pg_class d, pg_catalog.pg_am a,
pg_catalog.pg_namespace n
WHERE
d.relname = ? $schema_where AND d.oid = i.indrelid
AND i.indexrelid = c.oid AND c.relam = a.oid
ORDER BY
i.indisunique desc, a.amname, c.relname
};
my @output_rows;
# Table-level stats
if (!$unique_only) {
my $table_stats_sth = $dbh->prepare($table_stats_sql);
$table_stats_sth->execute(@exe_args) or return undef;
my $tst = $table_stats_sth->fetchrow_hashref or return undef;
push(@output_rows, [
undef, # TABLE_CAT
$tst->{nspname}, # TABLE_SCHEM
$table, # TABLE_NAME
undef, # NON_UNIQUE
undef, # INDEX_QUALIFIER
undef, # INDEX_NAME
'table', # TYPE
undef, # ORDINAL_POSITION
undef, # COLUMN_NAME
undef, # ASC_OR_DESC
$tst->{reltuples},# CARDINALITY
$tst->{relpages}, # PAGES
undef, # FILTER_CONDITION
]);
}
# Fetch the column names for later use
my $colnames_sth = $dbh->prepare($colnames_sql);
$colnames_sth->execute(@exe_args) or return undef;
my $colnames = $colnames_sth->fetchall_hashref('attnum');
# Fetch the index definitions
my $sth = $dbh->prepare($stats_sql);
$sth->execute(@exe_args) or return undef;
STAT_ROW:
#use Data::Dumper;
#warn Dumper $stats_sql;
while (my $row = $sth->fetchrow_hashref) {
#warn Dumper $row;
next if $row->{indexprs}; # We can't return these accurately via this interface ...
next if $unique_only and !$row->{indisunique};
my $indtype = $row->{indisclustered}
? 'clustered'
: ( $row->{amname} eq 'btree' )
? 'btree'
: ($row->{amname} eq 'hash' )
? 'hashed' : 'other';
my $nonunique = $row->{indisunique} ? 0 : 1;
my @index_row = (
undef, # TABLE_CAT
$row->{nspname}, # TABLE_SCHEM
$table, # TABLE_NAME
$nonunique, # NON_UNIQUE
undef, # INDEX_QUALIFIER
$row->{relname}, # INDEX_NAME
$indtype, # TYPE
undef, # ORDINAL_POSITION
undef, # COLUMN_NAME
'A', # ASC_OR_DESC
$row->{reltuples}, # CARDINALITY
$row->{relpages}, # PAGES
$row->{predicate}, # FILTER_CONDITION
);
my $col_nums = $row->{indkey};
$col_nums =~ s/^\s+//;
my @col_nums = split(/\s+/, $col_nums);
my $ord_pos = 1;
for my $col_num (@col_nums) {
my @copy = @index_row;
$copy[7] = $ord_pos++; # ORDINAL_POSITION
$copy[8] = $colnames->{$col_num}->{attname}; # COLUMN_NAME
push(@output_rows, \@copy);
}
}
my @output_colnames = qw/ TABLE_CAT TABLE_SCHEM TABLE_NAME NON_UNIQUE INDEX_QUALIFIER
INDEX_NAME TYPE ORDINAL_POSITION COLUMN_NAME ASC_OR_DESC
CARDINALITY PAGES FILTER_CONDITION /;
return _prepare_from_data('statistics_info', \@output_rows, \@output_colnames);
}
sub primary_key_info {
my $dbh = shift;
my ($catalog, $schema, $table, $attr) = @_;
## Catalog is ignored, but table is mandatory
return undef unless defined $table and length $table;
my $whereclause = 'AND c.relname = ' . $dbh->quote($table);
if (defined $schema and length $schema) {
$whereclause .= "\n\t\t\tAND n.nspname = " . $dbh->quote($schema);
}
my $TSJOIN = 'pg_catalog.pg_tablespace t ON (t.oid = c.reltablespace)';
if ($dbh->{private_dbdpg}{version} < 80000) {
$TSJOIN = '(SELECT 0 AS oid, 0 AS spcname, 0 AS spclocation LIMIT 0) AS t ON (t.oid=1)';
}
my $pri_key_sql = qq{
SELECT
c.oid
, quote_ident(n.nspname)
, quote_ident(c.relname)
, quote_ident(c2.relname)
, i.indkey, quote_ident(t.spcname), quote_ident(t.spclocation)
, n.nspname, c.relname, c2.relname
FROM
pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON (i.indrelid = c.oid)
JOIN pg_catalog.pg_class c2 ON (c2.oid = i.indexrelid)
LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)
LEFT JOIN $TSJOIN
WHERE
i.indisprimary IS TRUE
$whereclause
};
my $sth = $dbh->prepare($pri_key_sql) or return undef;
$sth->execute();
my $info = $sth->fetchall_arrayref()->[0];
return undef if ! defined $info;
# Get the attribute information
my $indkey = join ',', split /\s+/, $info->[4];
my $sql = qq{
SELECT a.attnum, pg_catalog.quote_ident(a.attname) AS colname,
pg_catalog.quote_ident(t.typname) AS typename
FROM pg_catalog.pg_attribute a, pg_catalog.pg_type t
WHERE a.attrelid = '$info->[0]'
AND a.atttypid = t.oid
AND attnum IN ($indkey);
};
$sth = $dbh->prepare($sql) or return undef;
$sth->execute();
my $attribs = $sth->fetchall_hashref('attnum');
my $pkinfo = [];
## Normal way: complete "row" per column in the primary key
if (!exists $attr->{'pg_onerow'}) {
my $x=0;
my @key_seq = split/\s+/, $info->[4];
for (@key_seq) {
# TABLE_CAT
$pkinfo->[$x][0] = undef;
# SCHEMA_NAME
$pkinfo->[$x][1] = $info->[1];
# TABLE_NAME
$pkinfo->[$x][2] = $info->[2];
# COLUMN_NAME
$pkinfo->[$x][3] = $attribs->{$_}{colname};
# KEY_SEQ
$pkinfo->[$x][4] = $_;
# PK_NAME
$pkinfo->[$x][5] = $info->[3];
# DATA_TYPE
$pkinfo->[$x][6] = $attribs->{$_}{typename};
$pkinfo->[$x][7] = $info->[5];
$pkinfo->[$x][8] = $info->[6];
$pkinfo->[$x][9] = $info->[7];
$pkinfo->[$x][10] = $info->[8];
$pkinfo->[$x][11] = $info->[9];
$x++;
}
}
else { ## Nicer way: return only one row
# TABLE_CAT
$info->[0] = undef;
# TABLESPACES
$info->[7] = $info->[5];
$info->[8] = $info->[6];
# Unquoted names
$info->[9] = $info->[7];
$info->[10] = $info->[8];
$info->[11] = $info->[9];
# PK_NAME
$info->[5] = $info->[3];
# COLUMN_NAME
$info->[3] = 2==$attr->{'pg_onerow'} ?
[ map { $attribs->{$_}{colname} } split /\s+/, $info->[4] ] :
join ', ', map { $attribs->{$_}{colname} } split /\s+/, $info->[4];
# DATA_TYPE
$info->[6] = 2==$attr->{'pg_onerow'} ?
[ map { $attribs->{$_}{typename} } split /\s+/, $info->[4] ] :
join ', ', map { $attribs->{$_}{typename} } split /\s+/, $info->[4];
# KEY_SEQ
$info->[4] = 2==$attr->{'pg_onerow'} ?
[ split /\s+/, $info->[4] ] :
join ', ', split /\s+/, $info->[4];
$pkinfo = [$info];
}
my @cols = (qw(TABLE_CAT TABLE_SCHEM TABLE_NAME COLUMN_NAME
KEY_SEQ PK_NAME DATA_TYPE));
push @cols, 'pg_tablespace_name', 'pg_tablespace_location';
push @cols, 'pg_schema', 'pg_table', 'pg_column';
return _prepare_from_data('primary_key_info', $pkinfo, \@cols);
}
sub primary_key {
my $sth = primary_key_info(@_[0..3], {pg_onerow => 2});
return defined $sth ? @{$sth->fetchall_arrayref()->[0][3]} : ();
}
sub foreign_key_info {
my $dbh = shift;
## PK: catalog, schema, table, FK: catalog, schema, table, attr
my $oldname = $dbh->{FetchHashKeyName};
local $dbh->{FetchHashKeyName} = 'NAME_lc';
## Each of these may be undef or empty
my $pschema = $_[1] || '';
my $ptable = $_[2] || '';
my $fschema = $_[4] || '';
my $ftable = $_[5] || '';
my $args = $_[6];
## No way to currently specify it, but we are ready when there is
my $odbc = 0;
## Must have at least one named table
return undef if !$ptable and !$ftable;
## If only the primary table is given, we return only those columns
## that are used as foreign keys, even if that means that we return
## unique keys but not primary one. We also return all the foreign
## tables/columns that are referencing them, of course.
## The first step is to find the oid of each specific table in the args:
## Return undef if no matching relation found
my %oid;
for ([$ptable, $pschema, 'P'], [$ftable, $fschema, 'F']) {
if (length $_->[0]) {
my $SQL = "SELECT c.oid AS schema FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n\n".
'WHERE c.relnamespace = n.oid AND c.relname = ' . $dbh->quote($_->[0]);
if (length $_->[1]) {
$SQL .= ' AND n.nspname = ' . $dbh->quote($_->[1]);
}
my $info = $dbh->selectall_arrayref($SQL);
return undef if ! @$info;
$oid{$_->[2]} = $info->[0][0];
}
}
## We now need information about each constraint we care about.
## Foreign table: only 'f' / Primary table: only 'p' or 'u'
my $WHERE = $odbc ? q{((contype = 'p'} : q{((contype IN ('p','u')};
if (length $ptable) {
$WHERE .= " AND conrelid=$oid{'P'}::oid";
}
else {
$WHERE .= " AND conrelid IN (SELECT DISTINCT confrelid FROM pg_catalog.pg_constraint WHERE conrelid=$oid{'F'}::oid)";
if (length $pschema) {
$WHERE .= ' AND n2.nspname = ' . $dbh->quote($pschema);
}
}
$WHERE .= ")\n \t\t\t\tOR \n \t\t\t\t(contype = 'f'";
if (length $ftable) {
$WHERE .= " AND conrelid=$oid{'F'}::oid";
if (length $ptable) {
$WHERE .= " AND confrelid=$oid{'P'}::oid";
}
}
else {
$WHERE .= " AND confrelid = $oid{'P'}::oid";
if (length $fschema) {
$WHERE .= ' AND n2.nspname = ' . $dbh->quote($fschema);
}
}
$WHERE .= '))';
## Grab everything except specific column names:
my $fk_sql = qq{
SELECT conrelid, confrelid, contype, conkey, confkey,
pg_catalog.quote_ident(c.relname) AS t_name, pg_catalog.quote_ident(n2.nspname) AS t_schema,
pg_catalog.quote_ident(n.nspname) AS c_schema, pg_catalog.quote_ident(conname) AS c_name,
CASE
WHEN confupdtype = 'c' THEN 0
WHEN confupdtype = 'r' THEN 1
WHEN confupdtype = 'n' THEN 2
WHEN confupdtype = 'a' THEN 3
WHEN confupdtype = 'd' THEN 4
ELSE -1
END AS update,
CASE
WHEN confdeltype = 'c' THEN 0
WHEN confdeltype = 'r' THEN 1
WHEN confdeltype = 'n' THEN 2
WHEN confdeltype = 'a' THEN 3
WHEN confdeltype = 'd' THEN 4
ELSE -1
END AS delete,
CASE
WHEN condeferrable = 'f' THEN 7
WHEN condeferred = 't' THEN 6
WHEN condeferred = 'f' THEN 5
ELSE -1
END AS defer
FROM pg_catalog.pg_constraint k, pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_namespace n2
WHERE $WHERE
AND k.connamespace = n.oid
AND k.conrelid = c.oid
AND c.relnamespace = n2.oid
ORDER BY conrelid ASC
};
my $sth = $dbh->prepare($fk_sql);
$sth->execute();
my $info = $sth->fetchall_arrayref({});
return undef if ! defined $info or ! @$info;
## Return undef if just ptable given but no fk found
return undef if ! length $ftable and ! grep { $_->{'contype'} eq 'f'} @$info;
## Figure out which columns we need information about
my %colnum;
for my $row (@$info) {
for (@{$row->{'conkey'}}) {
$colnum{$row->{'conrelid'}}{$_}++;
}
if ($row->{'contype'} eq 'f') {
for (@{$row->{'confkey'}}) {
$colnum{$row->{'confrelid'}}{$_}++;
}
}
}
## Get the information about the columns computed above
my $SQL = qq{
SELECT a.attrelid, a.attnum, pg_catalog.quote_ident(a.attname) AS colname,
pg_catalog.quote_ident(t.typname) AS typename
FROM pg_catalog.pg_attribute a, pg_catalog.pg_type t
WHERE a.atttypid = t.oid
AND (\n};
$SQL .= join "\n\t\t\t\tOR\n" => map {
my $cols = join ',' => keys %{$colnum{$_}};
"\t\t\t\t( a.attrelid = '$_' AND a.attnum IN ($cols) )"
} sort keys %colnum;
$sth = $dbh->prepare(qq{$SQL \)});
$sth->execute();
my $attribs = $sth->fetchall_arrayref({});
## Make a lookup hash
my %attinfo;
for (@$attribs) {
$attinfo{"$_->{'attrelid'}"}{"$_->{'attnum'}"} = $_;
}
## This is an array in case we have identical oid/column combos. Lowest oid wins
my %ukey;
for my $c (grep { $_->{'contype'} ne 'f' } @$info) {