This file is indexed.

/usr/share/perl5/Template/Plugin/DBI.pm is in libtemplate-plugin-dbi-perl 2.65-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
#==============================================================================
#
# Template::Plugin::DBI
#
# DESCRIPTION
#   A Template Toolkit plugin to provide access to a DBI data source.
#
# AUTHORS
#   Original version by Simon Matthews <sam@knowledgepool.com>
#   with some reworking by Andy Wardley <abw@kfs.org> and other
#   contributions from Craig Barratt <craig@arraycomm.com>,
#   Dave Hodgkinson <daveh@davehodgkinson.com> and Rafael Kitover
#   <caelum@debian.org>.
#   Since 2010 Jens Rehsack <sno@NetBSD.org> maintains this module.
#
# COPYRIGHT
#   Copyright (C) 1999-2000 Simon Matthews.  All Rights Reserved.
#   Copyright (C) 2006 Andy Wardley.  All Rights Reserved.
#   Copyright (C) 2010 Jens Rehsack.  All Rights Reserved.
#
#   This module is free software; you can redistribute it and/or
#   modify it under the same terms as Perl itself.
#
# REVISION
#   $Id$
#
#==============================================================================

package Template::Plugin::DBI;

use strict;
use warnings;

use Carp qw(croak carp);
use DBI;

use Template::Exception;
use base 'Template::Plugin';

our $VERSION  = 2.65;
our $DEBUG    = 0 unless defined $DEBUG;
our $QUERY    = 'Template::Plugin::DBI::Query';
our $ITERATOR = 'Template::Plugin::DBI::Iterator';

my $threads_enabled = 0;
my $have_tvr        = 0;

BEGIN
{
    $INC{"threads.pm"} and eval {
        ++$threads_enabled;
        require threads::variable::reap;
        ++$have_tvr;
    };

    $have_tvr
      and threads::variable::reap->import(qw(reap reapref));
}

# alias _connect() to connect() for backwards compatability
*_connect = \*connect;

#------------------------------------------------------------------------
# new($context, @params)
#
# Constructor which returns a reference to a new DBI plugin object.
# A connection string (dsn), user name and password may be passed as
# positional arguments or a hash array of connection parameters can be
# passed to initialise a connection.  Otherwise, an unconnected DBI
# plugin object is returned.
#------------------------------------------------------------------------

sub new
{
    my ( $class, $context, @connect_args ) = @_;
    my $self =
      ref $class
      ? $class
      : bless {
                _CONTEXT => $context,
                _STH     => undef,
              }, $class;

    $self->connect(@connect_args) if @connect_args;

    return $self;
}

#------------------------------------------------------------------------
# connect( $data_source, $username, $password, $attributes )
# connect( { data_source => 'dbi:driver:database'
#	     username    => 'foo'
#	     password    => 'bar' } )
#
# Opens a DBI connection for the plugin.
#------------------------------------------------------------------------

sub connect
{
    my $self = shift;
    my $params = ref $_[-1] eq 'HASH' ? pop(@_) : {};
    my ( $dbh, $dsn, $user, $pass, $klobs );

    # set debug flag
    exists $params->{debug} and $DEBUG = $params->{debug};
    $self->{_DEBUG} = $params->{debug} || 0;

    # fetch 'dbh' named paramater or use positional arguments or named
    # parameters to specify 'dsn', 'user' and 'pass'

    if ( $dbh = $params->{dbh} )
    {
        # disconnect any existing database handle that we previously opened
        $self->{_DBH}->disconnect()
          if $self->{_DBH} && $self->{_DBH_CONNECT};

        # store new dbh but leave _DBH_CONNECT false to prevent us
        # from automatically closing it in the future
        $self->{_DBH}         = $dbh;
        $self->{_DBH_CONNECT} = 0;
    }
    else
    {
        # certain Perl programmers are known to have problems with short
        # term memory loss (see Tie::Hash::Cannabinol) so we let the poor
        # blighters fumble any kind of argument that looks like it might
        # identify the database

        $dsn =
             shift
          || delete $params->{data_source}
          || delete $params->{database}
          || delete $params->{connect}
          || delete $params->{dsn}
          || delete $params->{db}
          || delete $self->{_DSN}
          || $ENV{DBI_DSN}
          || return $self->_throw('data source not defined');

        # add 'dbi:' prefix if it's not there
        $dsn = "dbi:$dsn" unless $dsn =~ /^dbi:/i;

        $user =
             shift
          || delete $params->{username}
          || delete $params->{user}
          || delete $self->{_USER};

        $pass =
             shift
          || delete $params->{password}
          || delete $params->{pass}
          || delete $self->{_PASS};

        $user ||= '';
        $pass ||= '';

        # save connection data because we might need it later to do a tie()
        @$self{qw( _DSN _USER _PASS )} = ( $dsn, $user, $pass );

        # reuse existing database handle if connection params match
        my $connect = join( ':', $dsn, $user, $pass );
        return ''
          if $self->connected() && $self->{_DBH_CONNECT} eq $connect;

        # otherwise disconnect any existing database handle that we opened
        $self->disconnect();

        # don't need DBI to automatically print errors because all calls go
        # via this plugin interface and we always check return values
        $params->{PrintError} = 0
          unless defined $params->{PrintError};
        $params->{RaiseError} = 0
          unless defined $params->{RaiseError};

        $self->{_DBH} = DBI->connect_cached( $dsn, $user, $pass, $params )
          || return $self->_throw("DBI connect failed: $DBI::errstr");

        # store the connection parameters
        $self->{_DBH_CONNECT} = $connect;
    }

    $have_tvr
      and reap( $self->{_DBH} )
      and reap( $self->{_STH} );

    return '';
}

sub connected
{
    my $self = $_[0];
    return $self->{_DBH} && $self->{_DBH}->isa('DBI::db');
}

#------------------------------------------------------------------------
# disconnect()
#
# Disconnects the current active database connection.
#------------------------------------------------------------------------

sub disconnect
{
    my $self = $_[0];
    delete( $self->{_STH} );    # first DESTROY any queries
    $self->connected() and $self->{_DBH}->disconnect();
    delete $self->{_DBH};
    delete $self->{_DSN};
    delete $self->{_USER};
    delete $self->{_PASS};
    delete $self->{_DBH_CONNECT};
    return '';
}

#------------------------------------------------------------------------
# tie( $table, $key )
#
# Return a hash tied to a table in the database, indexed by the specified
# key.
#------------------------------------------------------------------------

sub tie
{
    my $self = shift;
    my $params = ref $_[-1] eq 'HASH' ? pop(@_) : {};
    my ( $table, $key, $klobs, $debug, %hash );

    eval { require Tie::DBI };
    $self->_throw("failed to load Tie::DBI module: $@") if $@;

    $table =
         shift
      || $params->{table}
      || $self->_throw('table not defined');

    $key =
         shift
      || $params->{key}
      || $self->_throw('key not defined');

    # Achtung der Klobberman!
    $klobs = $params->{clobber};
    $klobs = $params->{CLOBBER} unless defined $klobs;

    # going the extra mile to allow user to use UPPER or lower case or
    # inherit internel debug flag set by connect()
    $debug = $params->{debug};
    $debug = $params->{DEBUG} unless defined $debug;
    $debug = $self->{_DEBUG} unless defined $debug;

    tie %hash, 'Tie::DBI', {
        %$params,    # any other Tie::DBI options like DEBUG, WARN, etc
        db => $self->{_DBH} || $self->{_DSN},
        user     => $self->{_USER},
        password => $self->{_PASS},
        table    => $table,
        key      => $key,
        CLOBBER  => $klobs || 0,
        DEBUG    => $debug || 0,
                           };

    return \%hash;
}

#------------------------------------------------------------------------
# prepare($sql)
#
# Prepare a query and store the live statement handle internally for
# subsequent execute() calls.
#------------------------------------------------------------------------

sub prepare
{
    my ($self,@args) = @_;
    unless( @args and $args[0] and "" eq ref($args[0]) )
    {
	return $self->_throw("prepare called without statement");
    }

    my $sth = $self->dbh()->prepare(@args)
      || return $self->_throw( "DBI prepare failed: " . $self->dbh()->errstr );

    # create wrapper object around handle to return to template client
    $sth = $QUERY->new($sth);
    $self->{_STH} = $sth;

    return $sth;
}

#------------------------------------------------------------------------
# execute()
#
# Calls execute() on the most recent statement created via prepare().
#------------------------------------------------------------------------

sub execute
{
    my $self = shift;
    my @args = @_ == 1 && ref $_[0] eq 'ARRAY' ? @{ $_[0] } : @_;

    my $sth = $self->{_STH}
      || return $self->_throw('no query prepared');

    $sth->execute(@args);
}

#------------------------------------------------------------------------
# query($sql, @params)
#
# Prepares and executes a SQL query.
#------------------------------------------------------------------------

sub query
{
    my ( $self, $sql, @args ) = @_;
    my @prep = ($sql);

    if( @args and $args[0] and ref($args[0]) eq 'HASH' )
    {
	push(@prep, shift @args);
    }

    return $self->prepare(@prep)->execute(@args);
}

#------------------------------------------------------------------------
# do($sql, \%attr, @bind)
#
# Prepares and executes a SQL statement.
#------------------------------------------------------------------------

sub do
{
    my $self = shift;
    my @args = @_ == 1 && ref $_[0] eq 'ARRAY' ? @{ $_[0] } : @_;

    return $self->dbh()->do(@args)
      || $self->_throw( "DBI do failed: " . $self->dbh()->errstr );
}

#------------------------------------------------------------------------
# quote($value [, $data_type ])
#
# Returns a quoted string (correct for the connected database) from the
# value passed in.
#------------------------------------------------------------------------

sub quote
{
    my ( $self, @quote_args ) = @_;
    return $self->dbh()->quote(@quote_args);
}

#------------------------------------------------------------------------
# dbh()
#
# Internal method to retrieve the database handle belonging to the
# instance or attempt to create a new one using connect.
#------------------------------------------------------------------------

sub dbh
{
    my $self = $_[0];

    $self->{_DBH} or $self->connect;

    return $self->{_DBH};
}

#------------------------------------------------------------------------
# DESTROY
#
# Called automatically when the plugin object goes out of scope to
# disconnect the database handle cleanly
#------------------------------------------------------------------------

sub DESTROY
{
    my $self = $_[0];
    delete( $self->{_STH} );    # first DESTROY any queries
    $self->{_DBH}->disconnect()
      if ( $self->connected() && $self->{_DBH_CONNECT} );
}

#------------------------------------------------------------------------
# _throw($error)
#
# Raise an error by throwing it via die() as a Template::Exception
# object of type 'DBI'.
#------------------------------------------------------------------------

sub _throw
{
    my $self = shift;
    my $error = shift || croak "DBI throw() called without an error string";

    # throw error as DBI exception
    die( Template::Exception->new( 'DBI', $error ) );
}

sub fetch
{
    my ( $self, $attr ) = @_;

    return $self->_throw("Cannot fetch attribute on not connected \$dbh") unless ( $self->connected() );

    my $dbh = $_[0]->{_DBH};
    local $@ = undef;
    my $value;
    eval { $value = $dbh->{$attr}; };
    return $self->_throw($@) if ($@);

    return $value;
}

sub store
{
    my ( $self, $attr, $value ) = @_;

    return $self->_throw("Cannot store attribute on not connected \$dbh") unless ( $self->connected() );

    my $dbh = $_[0]->{_DBH};
    local $@ = undef;
    eval { $dbh->{$attr} = $value; };
    return $self->_throw($@) if ($@);

    return 1;
}

#========================================================================
# Template::Plugin::DBI::Query
#========================================================================

package Template::Plugin::DBI::Query;
use vars qw( $DEBUG $ITERATOR $AUTOLOAD );

use Scalar::Util qw(blessed);

*DEBUG    = \$Template::Plugin::DBI::DEBUG;
*ITERATOR = \$Template::Plugin::DBI::ITERATOR;

sub new
{
    my ( $class, $sth ) = @_;
    my $self = bless( { _STH => $sth }, $class );
}

sub execute
{
    my $self = shift;
    my @args = @_ == 1 && ref $_[0] eq 'ARRAY' ? @{ $_[0] } : @_;

    $self->{_STH}->execute(@args)
      || return Template::Plugin::DBI->_throw( "execute failed: " . $self->{_STH}->errstr );

    $ITERATOR->new($self);
}

sub DESTROY
{
    undef $_[0]->{_STH};
}

sub AUTOLOAD
{
    my ( $self, @args ) = @_;

    die Template::Exception->new( 'DBI', "$self is not an object" ) unless ( blessed($self) );
    die Template::Exception->new( 'DBI', "No statement handle" ) unless ( defined( $self->{_STH} ) );

    ( my $name = $AUTOLOAD ) =~ s/.*://;
    return $self->{_STH}->$name(@args);
}

#========================================================================
# Template::Plugin::DBI::Iterator;
#========================================================================

package Template::Plugin::DBI::Iterator;

use Template::Iterator;
use base qw( Template::Iterator );
use vars qw( $DEBUG );

*DEBUG = \$Template::Plugin::DBI::DEBUG;

sub new
{
    my ( $class, $sth, $params ) = @_;

    my $rows = $sth->rows();

    my $self = bless {
                       _STH => $sth,
                       SIZE => $rows,
                       MAX  => $rows - 1,
                     }, $class;

    return $self;
}

#------------------------------------------------------------------------
# get_first()
#
# Initialises iterator to read from statement handle.  We maintain a
# one-record lookahead buffer to allow us to detect if the current
# record is the last in the series.
#------------------------------------------------------------------------

sub get_first
{
    my $self = shift;
    $self->{_STARTED} = 1;

    # set some status variables into $self
    @$self{qw(  PREV   ITEM FIRST LAST COUNT INDEX )} = ( undef, undef, 2, 0, 0, -1 );

    # support 'number' as an alias for 'count' for backwards compatability
    $self->{NUMBER} = 0;

    print STDERR "get_first() called\n" if $DEBUG;

    # get the first row
    $self->_fetchrow();

    print STDERR "get_first() calling get_next()\n" if $DEBUG;

    return $self->get_next();
}

#------------------------------------------------------------------------
# get_next()
#
# Called to read remaining result records from statement handle.
#------------------------------------------------------------------------

sub get_next
{
    my $self = shift;
    my ( $data, $fixup );

    # increment the 'index' and 'count' counts
    $self->{INDEX}++;
    $self->{COUNT}++;
    $self->{NUMBER}++;    # 'number' is old name for 'count'

    # decrement the 'first-record' flag
    $self->{FIRST}-- if $self->{FIRST};

    # we should have a row already cache in NEXT
    return ( undef, Template::Constants::STATUS_DONE )
      unless $data = $self->{NEXT};

    # set PREV to be current ITEM from last iteration
    $self->{PREV} = $self->{ITEM};

    # look ahead to the next row so that the rowcache is refilled
    $self->_fetchrow();

    $self->{ITEM} = $data;
    return ( $data, Template::Constants::STATUS_OK );
}

sub get
{
    my $self = shift;
    my ( $data, $error );

    ( $data, $error ) = $self->{_STARTED} ? $self->get_next() : $self->get_first();

    return $data;
}

sub get_all
{
    my $self = shift;
    my $sth  = $self->{_STH};

    my $data = $sth->fetchall_arrayref( {} );
    $self->throw( $sth->errstr ) if ( $sth->err() );
    unshift( @$data, $self->{NEXT} ) if $self->{NEXT};
    $self->{LAST} = 1;
    $self->{NEXT} = undef;

    return $data;
}

sub get_colnames
{
    my $self = shift;
    my $sth  = $self->{_STH};
    my $error;

    my $data = $sth->{_STH}->{NAME_lc};
    $self->throw( $sth->errstr ) if ( $sth->err() );

    return $data;
}

sub get_COLnames
{
    my $self = shift;
    my $sth  = $self->{_STH};

    my $data = $sth->{_STH}->{NAME_uc};
    $self->throw( $sth->errstr ) if ( $sth->err() );

    return $data;
}

sub get_all_list
{
    my $self = shift;
    my $sth  = $self->{_STH};

    my $data = $sth->fetchall_arrayref();
    $self->throw( $sth->errstr ) if ( $sth->err() );
    if ( $self->{NEXT} )
    {
        my $fetch_hash_key_name = $self->{_STH}->{FetchHashKeyName};
        my @cols                = @{ $self->{_STH}->{$fetch_hash_key_name} };
        my @row                 = @{ $self->{NEXT} }[@cols];
        unshift( @$data, \@row );
    }
    $self->{LAST} = 1;
    $self->{NEXT} = undef;

    return $data;
}

sub rows
{
    return $_[0]->{SIZE};
}

sub fetch
{
    my ( $self, $attr ) = @_;
    $self->{_STH}->FETCH($attr);
}

sub store
{
    my ( $self, $attr, $value ) = @_;
    return $self->{_STH}->STORE( $attr, $value );
}

#------------------------------------------------------------------------
# _fetchrow()
#
# Retrieve a record from the statement handle and store in row cache.
#------------------------------------------------------------------------

sub _fetchrow
{
    my $self = shift;
    my $sth  = $self->{_STH};

    my $data = $sth->fetchrow_hashref() || do
    {
        $self->{LAST} = 1;
        $self->{NEXT} = undef;
        return;
    };
    $self->{NEXT} = $data;
    return;
}

1;

__END__

=head1 NAME

Template::Plugin::DBI - Template interface to the DBI module

=head1 SYNOPSIS

Making an implicit database connection:

    # ...using positional arguments
    [% USE DBI('dbi:driver:dbname', 'user', 'pass') %]

    # ...using named parameters
    [% USE DBI( database = 'dbi:driver:dbname',
                username = 'user', 
                password = 'pass' )
    %]

    # ...using short named parameters (4 lzy ppl and bad typsits)
    [% USE DBI( db   = 'driver:dbname',
                user = 'user', 
                pass = 'pass' )
    %]

    # ...or an existing DBI database handle
    [% USE DBI( dbh = my_dbh_ref ) %]

Making explicit database connections:

    [% USE DBI %]

    [% DBI.connect(db, user, pass) %]
       ...

    [% DBI.connect(new_db, new_user, new_pass) %]
       ...

    [% DBI.disconnect %]      # final disconnect is optional

Making an automagical database connection using DBI_DSN environment variable:

    [% USE DBI %]

Making database queries:

    # single step query
    [% FOREACH user = DBI.query('SELECT * FROM users') %]
       [% user.uid %] blah blah [% user.name %] etc. etc.
    [% END %]

    # two stage prepare/execute
    [% query = DBI.prepare('SELECT * FROM users WHERE uid = ?') %]

    [% FOREACH user = query.execute('sam') %]
       ...
    [% END %]

    [% FOREACH user = query.execute('abw') %]
       ...
    [% END %]

Making non-SELECT statements:

    [% IF DBI.do("DELETE FROM users WHERE uid = '$uid'") %]
       The user '[% uid %]' was successfully deleted.
    [% END %]

Using named DBI connections:

    [% USE one = DBI(...) %]
    [% USE two = DBI(...) %]

    [% FOREACH item = one.query("SELECT ...etc...") %]
       ...
    [% END %]

    [% FOREACH item = two.query("SELECT ...etc...") %]
       ...
    [% END %]

Tieing to a database table (via Tie::DBI):

    [% people = DBI.tie('users', 'uid') %]

    [% me = people.abw %]   # => SELECT * FROM users WHERE uid='abw'

    I am [% me.name %]

    # clobber option allows table updates (see Tie::DBI)
    [% people = DBI.tie('users', 'uid', clobber=1) %]

    [% people.abw.name = 'not a number' %]

    I am [% people.abw.name %]   # I am a free man!

=head1 DESCRIPTION

This Template Toolkit plugin module provides an interface to the Perl
DBI/DBD modules, allowing you to integrate SQL queries into your
template documents.  It also provides an interface via the Tie::DBI
module (if installed on your system) so that you can access database
records without having to embed any SQL in your templates.

A DBI plugin object can be created as follows:

    [% USE DBI %]

This creates an uninitialised DBI object.  You can then open a connection
to a database using the connect() method.

    [% DBI.connect('dbi:driver:dbname', 'user', 'pass') %]

The DBI connection can be opened when the plugin is created by passing
arguments to the constructor, called from the USE directive.

    [% USE DBI('dbi:driver:dbname', 'user', 'pass') %]

You can also use named parameters to provide the data source connection 
string, user name and password.

    [% USE DBI(database => 'dbi:driver:dbname',
               username => 'user',
               password => 'pass')  %]

For backwards compatability with previous versions of this plugin, you can
also spell 'database' as 'data_source'.

    [% USE DBI(data_source => 'dbi:driver:dbname',
               username    => 'user',
               password    => 'pass')  %]

Lazy Template hackers may prefer to use 'db', 'dsn' or 'connect' as a
shorthand form of the 'database' parameter, and 'user' and 'pass' as
shorthand forms of 'username' and 'password', respectively.  You can
also drop the 'dbi:' prefix from the database connect string because
the plugin will add it on for you automagically.

    [% USE DBI(db   => 'driver:dbname',
               user => 'user',
               pass => 'pass')  %]

Any additional DBI attributes can be specified as named parameters.
The 'PrintError' attribute defaults to 0 unless explicitly set true.

    [% USE DBI(db, user, pass, ChopBlanks=1) %]

An alternate variable name can be provided for the plugin as per regular
Template Toolkit syntax:

    [% USE mydb = DBI('dbi:driver:dbname', 'user', 'pass') %]

    [% FOREACH item = mydb.query('SELECT * FROM users') %]
       ...
    [% END %]

You can also specify the DBI plugin name in lower case if you prefer:

    [% USE dbi(dsn, user, pass) %]

    [% FOREACH item = dbi.query('SELECT * FROM users') %]
       ...
    [% END %]

The disconnect() method can be called to explicitly disconnect the
current database, but this generally shouldn't be necessary as it is
called automatically when the plugin goes out of scope.  You can call
connect() at any time to open a connection to another database.  The
previous connection will be closed automatically.

Internally, the DBI connect_cached() method is used instead of the
connect() method.  This allows for connection caching in a server
environment, such as when the Template Toolkit is used from an Apache
mod_perl handler.  In such a case, simply enable the mod_env module
and put in a line such as:

    SetEnv DBI_DSN "dbi:mysql:dbname;host=dbhost; 
                              user=uname;password=pword"

(NOTE: the string shown here is split across 2 lines for the sake of
reasonable page formatting, but you should specify it all as one long
string with no spaces or newlines).

You can then use the DBI plugin without any parameters or the need
to explicitly call connect().

Once you've loaded a DBI plugin and opened a database connection using 
one of the techniques shown above, you can then make queries on the database
using the familiar dotted notation:

    [% FOREACH user = DBI.query('SELECT * FROM users') %]
       [% user.uid %] blah blah [% user.name %] etc. etc.
    [% END %]

The query() method prepares a query and executes it all in one go.
If you want to repeat a query with different parameters then you 
can use a separate prepare/execute cycle.

    [% query = DBI.prepare('SELECT * FROM users WHERE uid = ?') %]

    [% FOREACH user = query.execute('sam') %]
       ...
    [% END %]

    [% FOREACH user = query.execute('abw') %]
       ...
    [% END %]

The query() and execute() methods return an iterator object which
manages the result set returned.  You can save a reference to the
iterator and access methods like size() to determine the number of
rows returned by a query.

    [% users = DBI.query('SELECT * FROM users') %]
    [% users.size %] records returned

or even

    [% DBI.query('SELECT * FROM users').size %]

When used within a FOREACH loop, the iterator is always aliased to the 
special C<loop> variable.  This makes it possible to do things like this:

    [% FOREACH user = DBI.query('SELECT * FROM users') %]
       [% loop.count %]/[% loop.size %]: [% user.name %]
    [% END %]

to generate a result set of the form:

    1/3: Jerry Garcia
    2/3: Kurt Cobain
    3/3: Freddie Mercury

See L<Template::Iterator> for further details on iterators and the
methods that they implement.

The DBI plugin also provides the do() method to execute non-SELECT
statements like this:

    [% IF DBI.do("DELETE FROM users WHERE uid = '$uid'") %]
       The user '[% uid %]' was successfully deleted.
    [% END %]

The plugin also allows you to create a tie to a table in the database
using the Tie::DBI module.  Simply call the tie() method, passing the
name of the table and the primary key as arguments.

    [% people = DBI.tie('person', 'uid') %]

You can then access records in the database table as if they were
entries in the 'people' hash.

    My name is [% people.abw.name %]

IMPORTANT NOTE: the XS Stash (Template::Stash::XS) does not currently
support access to tied hashes.  If you are using the XS stash and having
problems then you should try enabling the regular stash instead.  You 
can do this by setting $Template::Config::STASH to 'Template::Stash' 
before instantiating the Template object.

=head1 OBJECT METHODS

=head2 connect($database, $username, $password)

Establishes a database connection.  This method accepts both positional 
and named parameter syntax.  e.g. 

    [% DBI.connect( 'dbi:driver:dbname', 'timmy', 'sk8D00Dz' ) %]

    [% DBI.connect( database = 'dbi:driver:dbname'
                    username = 'timmy' 
                    password = 'sk8D00Dz' ) %]

The connect method allows you to connect to a data source explicitly.
It can also be used to reconnect an exisiting object to a different
data source.  

If you already have a database handle then you can instruct the plugin
to reuse it by passing it as the 'dbh' parameter.

    [% DBI.connect( dbh = my_dbh_ref ) %]

=head2 query($sql,[\%args],[@bind_values])

This method submits an SQL query to the database and creates an iterator 
object to return the results.  This may be used directly in a FOREACH 
directive as shown below.  Data is automatically fetched a row at a time
from the query result set as required for memory efficiency.

    [% FOREACH user = DBI.query('SELECT * FROM users') %]
       Each [% user.field %] can be printed here
    [% END %]

=head2 prepare($sql,[\%args])

Prepare a query for later execution.  This returns a compiled query
object (of the Template::Plugin::DBI::Query class) on which the
execute() method can subsequently be called.

    [% query = DBI.prepare('SELECT * FROM users WHERE id = ?') %]

=head2 execute(@bind_values)

Execute a previously prepared query.  This method should be called on
the query object returned by the prepare() method.  Returns an
iterator object which can be used directly in a FOREACH directive.

    [% query = DBI.prepare('SELECT * FROM users WHERE manager = ?') %]

    [% FOREACH minion = query.execute('abw') %]
       [% minion.name %]
    [% END %]

    [% FOREACH minion = query.execute('sam') %]
       [% minion.name %]
    [% END %]

=head2 do($sql,[\%attr,[@bind_values]])

The do() method executes a sql statement from which no records are
returned.  It will return true if the statement was successful

    [% IF DBI.do("DELETE FROM users WHERE uid = 'sam'") %]
       The user was successfully deleted.
    [% END %]

=head2 tie($table, $key, \%args)

Returns a reference to a hash array tied to a table in the database,
implemented using the Tie::DBI module.  You should pass the name of
the table and the key field as arguments.

    [% people = DBI.tie('users', 'uid') %]

Or if you prefer, you can use the 'table' and 'key' named parameters.

    [% people = DBI.tie(table='users', key='uid') %]

In this example, the Tie::DBI module will convert the accesses into
the 'people' hash into SQL queries of the form:

    SELECT * FROM users WHERE uid=?

For example:

    [% me = people.abw %]

The record returned can then be accessed just like a normal hash.

    I am [% me.name %]

You can also do things like this to iterate through all the records
in a table.

    [% FOREACH uid = people.keys.sort;
            person = people.$uid 
    %] 
        * [% person.id %] : [% person.name %]
    [% END %]

With the 'clobber' (or 'CLOBBER') option set you can update the record
and have those changes automatically permeated back into the database.

    [% people = DBI.tie('users', 'uid', clobber=1) %]

    [% people.abw.name = 'not a number' %]

    I am [% people.abw.name %]  # I am a free man!

And you can also add new records.
 
    [% people.newguy = {
           name = 'Nobby Newguy'
	   ...other fields...
       }
    %]

See L<Tie::DBI> for further information on the 'CLOBBER' option.

=head2 quote($value, $type)

Calls the quote() method on the underlying DBI handle to quote the value
specified in the appropriate manner for its type.

=head2 dbh

  [% DBI.dbh() %]

Return the database handle currently in use by the plugin.

=head2 disconnect

  [% DBI.disconnect() %]

Disconnects the current database.

=head2 fetch

  [% DBI.fetch('Name') %]

Fetches an attribute from the connected database handle.
Throws an exception when not connected.

=head2 store

  [% DBI.store('RowCacheSize',0) %]

Stores an attribute in the connected database handle.
Throws an exception when not connected.

=head1 ITERATOR METHODS

=head2 get_all

  [% allhash = result.get_all() %]

Returns all (remaining) rows as a hash.

=head2 get_all_list

  [% allhash = result.get_all_list() %]

Returns all (remaining) rows as a list.

=head2 rows

Returns the number of affected rows of the executed statement.

=head2 get_colnames

Returns the lowercase column names (C<$sth> attribute C<< ->{NAME_lc} >>).

=head2 get_COLnames

Returns the uppercase column names (C<$sth> attribute C<< ->{NAME_uc} >>).

=head2 fetch

Fetches an attribute from the statement handle.

  [% result.fetch('FetchHashKeyName') %]

=head2 store

Stores an attribute to the statement handle.

  [% result.store('FetchHashKeyName','NAME_lc') %]

=head1 AUTHORS

The DBI plugin was originally written by Simon A Matthews, and
distributed as a separate module.  It was integrated into the Template
Toolkit distribution for version 2.00 and includes contributions from
Andy Wardley, Craig Barratt, Dave Hodgkinson and Rafael Kitover. Andy
Wardley extracted it back into a separate distribution in May 2006.
After that, in 2010 Jens Rehsack maintains this distribution.

=head1 COPYRIGHT

  Copyright (C) 1999-2006 Simon Matthews, Andy Wardley.  All Rights Reserved.
  Copyright (C) 2010 Jens Rehsack.  All Rights Reserved

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=head1 SEE ALSO

L<Template> L<Template::Plugins>, L<DBI>, L<Tie::DBI>