This file is indexed.

/usr/share/perl5/DBIx/SearchBuilder.pm is in libdbix-searchbuilder-perl 1.61-1.

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
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
package DBIx::SearchBuilder;

use strict;
use warnings;

our $VERSION = "1.61";

use Clone qw();
use Encode qw();

=head1 NAME

DBIx::SearchBuilder - Encapsulate SQL queries and rows in simple perl objects

=head1 SYNOPSIS

  use DBIx::SearchBuilder;
  
  package My::Things;
  use base qw/DBIx::SearchBuilder/;
  
  sub _Init {
      my $self = shift;
      $self->Table('Things');
      return $self->SUPER::_Init(@_);
  }
  
  sub NewItem {
      my $self = shift;
      # MyThing is a subclass of DBIx::SearchBuilder::Record
      return(MyThing->new);
  }
  
  package main;

  use DBIx::SearchBuilder::Handle;
  my $handle = DBIx::SearchBuilder::Handle->new();
  $handle->Connect( Driver => 'SQLite', Database => "my_test_db" );

  my $sb = My::Things->new( Handle => $handle );

  $sb->Limit( FIELD => "column_1", VALUE => "matchstring" );

  while ( my $record = $sb->Next ) {
      print $record->my_column_name();
  }

=head1 DESCRIPTION

This module provides an object-oriented mechanism for retrieving and updating data in a DBI-accesible database. 

In order to use this module, you should create a subclass of C<DBIx::SearchBuilder> and a 
subclass of C<DBIx::SearchBuilder::Record> for each table that you wish to access.  (See
the documentation of C<DBIx::SearchBuilder::Record> for more information on subclassing it.)

Your C<DBIx::SearchBuilder> subclass must override C<NewItem>, and probably should override
at least C<_Init> also; at the very least, C<_Init> should probably call C<_Handle> and C<_Table>
to set the database handle (a C<DBIx::SearchBuilder::Handle> object) and table name for the class.
You can try to override just about every other method here, as long as you think you know what you
are doing.

=head1 METHOD NAMING

Each method has a lower case alias; '_' is used to separate words.
For example, the method C<RedoSearch> has the alias C<redo_search>.

=head1 METHODS

=cut


=head2 new

Creates a new SearchBuilder object and immediately calls C<_Init> with the same parameters
that were passed to C<new>.  If you haven't overridden C<_Init> in your subclass, this means
that you should pass in a C<DBIx::SearchBuilder::Handle> (or one of its subclasses) like this:

   my $sb = My::DBIx::SearchBuilder::Subclass->new( Handle => $handle );

However, if your subclass overrides _Init you do not need to take a Handle argument, as long
as your subclass returns an appropriate handle object from the C<_Handle> method.  This is
useful if you want all of your SearchBuilder objects to use a shared global handle and don't want
to have to explicitly pass it in each time, for example.

=cut

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self  = {};
    bless( $self, $class );
    $self->_Init(@_);
    return ($self);
}



=head2 _Init

This method is called by C<new> with whatever arguments were passed to C<new>.  
By default, it takes a C<DBIx::SearchBuilder::Handle> object as a C<Handle>
argument, although this is not necessary if your subclass overrides C<_Handle>.

=cut

sub _Init {
    my $self = shift;
    my %args = ( Handle => undef,
                 @_ );
    $self->_Handle( $args{'Handle'} );

    $self->CleanSlate();
}



=head2 CleanSlate

This completely erases all the data in the SearchBuilder object. It's
useful if a subclass is doing funky stuff to keep track of a search and
wants to reset the SearchBuilder data without losing its own data;
it's probably cleaner to accomplish that in a different way, though.

=cut

sub CleanSlate {
    my $self = shift;
    $self->RedoSearch();
    $self->{'itemscount'}       = 0;
    $self->{'limit_clause'}     = "";
    $self->{'order'}            = "";
    $self->{'alias_count'}      = 0;
    $self->{'first_row'}        = 0;
    $self->{'must_redo_search'} = 1;
    $self->{'show_rows'}        = 0;
    @{ $self->{'aliases'} } = ();

    delete $self->{$_} for qw(
	items
	left_joins
	raw_rows
	count_all
	subclauses
	restrictions
	_open_parens
	_close_parens
    group_by
    columns
    );

    #we have no limit statements. DoSearch won't work.
    $self->_isLimited(0);
}

=head2 Clone

Returns copy of the current object with all search restrictions.

=cut

sub Clone
{
    my $self = shift;

    my $obj = bless {}, ref($self);
    %$obj = %$self;

    delete $obj->{$_} for qw(
        items
    );
    $obj->{'must_redo_search'} = 1;
    $obj->{'itemscount'}       = 0;
    
    $obj->{ $_ } = Clone::clone( $obj->{ $_ } )
        foreach grep exists $self->{ $_ }, $self->_ClonedAttributes;
    return $obj;
}

=head2 _ClonedAttributes

Returns list of the object's fields that should be copied.

If your subclass store references in the object that should be copied while
clonning then you probably want override this method and add own values to
the list.

=cut

sub _ClonedAttributes
{
    return qw(
        aliases
        left_joins
        subclauses
        restrictions
        order_by
        group_by
        columns
    );
}



=head2 _Handle  [DBH]

Get or set this object's DBIx::SearchBuilder::Handle object.

=cut

sub _Handle {
    my $self = shift;
    if (@_) {
        $self->{'DBIxHandle'} = shift;
    }
    return ( $self->{'DBIxHandle'} );
}

=head2 _DoSearch

This internal private method actually executes the search on the database;
it is called automatically the first time that you actually need results
(such as a call to C<Next>).

=cut

sub _DoSearch {
    my $self = shift;

    my $QueryString = $self->BuildSelectQuery();

    # If we're about to redo the search, we need an empty set of items
    delete $self->{'items'};

    my $records = $self->_Handle->SimpleQuery($QueryString);
    return 0 unless $records;

    while ( my $row = $records->fetchrow_hashref() ) {
	my $item = $self->NewItem();
	$item->LoadFromHash($row);
	$self->AddRecord($item);
    }
    return $self->_RecordCount if $records->err;

    $self->{'must_redo_search'} = 0;

    return $self->_RecordCount;
}


=head2 AddRecord RECORD

Adds a record object to this collection.

=cut

sub AddRecord {
    my $self = shift;
    my $record = shift;
    push @{$self->{'items'}}, $record;
}

=head2 _RecordCount

This private internal method returns the number of Record objects saved
as a result of the last query.

=cut

sub _RecordCount {
    my $self = shift;
    return 0 unless defined $self->{'items'};
    return scalar @{ $self->{'items'} };
}



=head2 _DoCount

This internal private method actually executes a counting operation on the database;
it is used by C<Count> and C<CountAll>.

=cut


sub _DoCount {
    my $self = shift;
    my $all  = shift || 0;

    my $QueryString = $self->BuildSelectCountQuery();
    my $records     = $self->_Handle->SimpleQuery($QueryString);
    return 0 unless $records;

    my @row = $records->fetchrow_array();
    return 0 if $records->err;

    $self->{ $all ? 'count_all' : 'raw_rows' } = $row[0];

    return ( $row[0] );
}



=head2 _ApplyLimits STATEMENTREF

This routine takes a reference to a scalar containing an SQL statement. 
It massages the statement to limit the returned rows to only C<< $self->RowsPerPage >>
rows, skipping C<< $self->FirstRow >> rows.  (That is, if rows are numbered
starting from 0, row number C<< $self->FirstRow >> will be the first row returned.)
Note that it probably makes no sense to set these variables unless you are also
enforcing an ordering on the rows (with C<OrderByCols>, say).

=cut


sub _ApplyLimits {
    my $self = shift;
    my $statementref = shift;
    $self->_Handle->ApplyLimits($statementref, $self->RowsPerPage, $self->FirstRow);
    $$statementref =~ s/main\.\*/join(', ', @{$self->{columns}})/eg
	    if $self->{columns} and @{$self->{columns}};
}


=head2 _DistinctQuery STATEMENTREF

This routine takes a reference to a scalar containing an SQL statement. 
It massages the statement to ensure a distinct result set is returned.

=cut

sub _DistinctQuery {
    my $self = shift;
    my $statementref = shift;

    # XXX - Postgres gets unhappy with distinct and OrderBy aliases
    $self->_Handle->DistinctQuery($statementref, $self)
}

=head2 _BuildJoins

Build up all of the joins we need to perform this query.

=cut


sub _BuildJoins {
    my $self = shift;

        return ( $self->_Handle->_BuildJoins($self) );

}


=head2 _isJoined 

Returns true if this SearchBuilder will be joining multiple tables together.

=cut

sub _isJoined {
    my $self = shift;
    if ( keys %{ $self->{'left_joins'} } ) {
        return (1);
    } else {
        return (@{ $self->{'aliases'} });
    }

}




# LIMIT clauses are used for restricting ourselves to subsets of the search.



sub _LimitClause {
    my $self = shift;
    my $limit_clause;

    if ( $self->RowsPerPage ) {
        $limit_clause = " LIMIT ";
        if ( $self->FirstRow != 0 ) {
            $limit_clause .= $self->FirstRow . ", ";
        }
        $limit_clause .= $self->RowsPerPage;
    }
    else {
        $limit_clause = "";
    }
    return $limit_clause;
}



=head2 _isLimited

If we've limited down this search, return true. Otherwise, return false.

=cut

sub _isLimited {
    my $self = shift;
    if (@_) {
        $self->{'is_limited'} = shift;
    }
    else {
        return ( $self->{'is_limited'} );
    }
}




=head2 BuildSelectQuery

Builds a query string for a "SELECT rows from Tables" statement for this SearchBuilder object

=cut

sub BuildSelectQuery {
    my $self = shift;

    # The initial SELECT or SELECT DISTINCT is decided later

    my $QueryString = $self->_BuildJoins . " ";
    $QueryString .= $self->_WhereClause . " "
      if ( $self->_isLimited > 0 );

    # DISTINCT query only required for multi-table selects
    # when we have group by clause then the result set is distinct as
    # it must contain only columns we group by or results of aggregate
    # functions which give one result per group, so we can skip DISTINCTing
    if ( my $clause = $self->_GroupClause ) {
        $QueryString = "SELECT main.* FROM $QueryString";
        $QueryString .= $clause;
        $QueryString .= $self->_OrderClause;
    }
    elsif ($self->_isJoined) {
        $self->_DistinctQuery(\$QueryString);
    }
    else {
        $QueryString = "SELECT main.* FROM $QueryString";
        $QueryString .= $self->_OrderClause;
    }

    $self->_ApplyLimits(\$QueryString);

    return($QueryString)

}



=head2 BuildSelectCountQuery

Builds a SELECT statement to find the number of rows this SearchBuilder object would find.

=cut

sub BuildSelectCountQuery {
    my $self = shift;

    #TODO refactor DoSearch and DoCount such that we only have
    # one place where we build most of the querystring
    my $QueryString = $self->_BuildJoins . " ";

    $QueryString .= $self->_WhereClause . " "
      if ( $self->_isLimited > 0 );



    # DISTINCT query only required for multi-table selects
    if ($self->_isJoined) {
        $QueryString = $self->_Handle->DistinctCount(\$QueryString);
    } else {
        $QueryString = "SELECT count(main.id) FROM " . $QueryString;
    }

    return ($QueryString);
}




=head2 Next

Returns the next row from the set as an object of the type defined by sub NewItem.
When the complete set has been iterated through, returns undef and resets the search
such that the following call to Next will start over with the first item retrieved from the database.

=cut



sub Next {
    my $self = shift;
    my @row;

    return (undef) unless ( $self->_isLimited );

    $self->_DoSearch() if $self->{'must_redo_search'};

    if ( $self->{'itemscount'} < $self->_RecordCount ) {    #return the next item
        my $item = ( $self->{'items'}[ $self->{'itemscount'} ] );
        $self->{'itemscount'}++;
        return ($item);
    }
    else {    #we've gone through the whole list. reset the count.
        $self->GotoFirstItem();
        return (undef);
    }
}



=head2 GotoFirstItem

Starts the recordset counter over from the first item. The next time you call Next,
you'll get the first item returned by the database, as if you'd just started iterating
through the result set.

=cut


sub GotoFirstItem {
    my $self = shift;
    $self->GotoItem(0);
}




=head2 GotoItem

Takes an integer, n.
Sets the record counter to n. the next time you call Next,
you'll get the nth item.

=cut

sub GotoItem {
    my $self = shift;
    my $item = shift;
    $self->{'itemscount'} = $item;
}



=head2 First

Returns the first item

=cut

sub First {
    my $self = shift;
    $self->GotoFirstItem();
    return ( $self->Next );
}



=head2 Last

Returns the last item

=cut

sub Last {
    my $self = shift;
    $self->GotoItem( ( $self->Count ) - 1 );
    return ( $self->Next );
}

=head2 DistinctFieldValues

Returns list with distinct values of field. Limits on collection
are accounted, so collection should be L</UnLimit>ed to get values
from the whole table.

Takes paramhash with the following keys:

=over 4

=item Field

Field name. Can be first argument without key.

=item Order

'ASC', 'DESC' or undef. Defines whether results should
be sorted or not. By default results are not sorted.

=item Max

Maximum number of elements to fetch.

=back

=cut

sub DistinctFieldValues {
    my $self = shift;
    my %args = (
        Field  => undef,
        Order  => undef,
        Max    => undef,
        @_%2 ? (Field => @_) : (@_)
    );

    my $query_string = $self->_BuildJoins;
    $query_string .= ' '. $self->_WhereClause
        if $self->_isLimited > 0;

    my $column = 'main.'. $args{'Field'};
    $query_string = 'SELECT DISTINCT '. $column .' FROM '. $query_string;

    if ( $args{'Order'} ) {
        $query_string .= ' ORDER BY '. $column
            .' '. ($args{'Order'} =~ /^des/i ? 'DESC' : 'ASC');
    }

    my $dbh = $self->_Handle->dbh;
    my $list = $dbh->selectcol_arrayref( $query_string, { MaxRows => $args{'Max'} } );
    return $list? @$list : ();
}



=head2 ItemsArrayRef

Return a refernece to an array containing all objects found by this search.

=cut

sub ItemsArrayRef {
    my $self = shift;

    #If we're not limited, return an empty array
    return [] unless $self->_isLimited;

    #Do a search if we need to.
    $self->_DoSearch() if $self->{'must_redo_search'};

    #If we've got any items in the array, return them.
    # Otherwise, return an empty array
    return ( $self->{'items'} || [] );
}




=head2 NewItem

NewItem must be subclassed. It is used by DBIx::SearchBuilder to create record 
objects for each row returned from the database.

=cut

sub NewItem {
    my $self = shift;

    die
"DBIx::SearchBuilder needs to be subclassed. you can't use it directly.\n";
}



=head2 RedoSearch

Takes no arguments.  Tells DBIx::SearchBuilder that the next time it's asked
for a record, it should requery the database

=cut

sub RedoSearch {
    my $self = shift;
    $self->{'must_redo_search'} = 1;
}




=head2 UnLimit

UnLimit clears all restrictions and causes this object to return all
rows in the primary table.

=cut

sub UnLimit {
    my $self = shift;
    $self->_isLimited(-1);
}



=head2 Limit

Limit takes a hash of parameters with the following keys:

=over 4

=item TABLE 

Can be set to something different than this table if a join is
wanted (that means we can't do recursive joins as for now).  

=item ALIAS

Unless ALIAS is set, the join criterias will be taken from EXT_LINKFIELD
and INT_LINKFIELD and added to the criterias.  If ALIAS is set, new
criterias about the foreign table will be added.

=item LEFTJOIN

To apply the Limit inside the ON clause of a previously created left
join, pass this option along with the alias returned from creating
the left join. ( This is similar to using the EXPRESSION option when
creating a left join but this allows you to refer to the join alias
in the expression. )

=item FIELD

Column to be checked against.

=item VALUE

Should always be set and will always be quoted. 

=item OPERATOR

OPERATOR is the SQL operator to use for this phrase.  Possible choices include:

=over 4

=item "="

=item "!="

=item "LIKE"

In the case of LIKE, the string is surrounded in % signs.  Yes. this is a bug.

=item "NOT LIKE"

=item "STARTSWITH"

STARTSWITH is like LIKE, except it only appends a % at the end of the string

=item "ENDSWITH"

ENDSWITH is like LIKE, except it prepends a % to the beginning of the string

=item "MATCHES"

MATCHES is equivalent to the database's LIKE -- that is, it's actually LIKE, but
doesn't surround the string in % signs as LIKE does.

=back

=item ENTRYAGGREGATOR 

Can be C<AND> or C<OR> (or anything else valid to aggregate two clauses in SQL).
Special value is C<none> which means that no entry aggregator should be used.
The default value is C<OR>.

=item CASESENSITIVE

on some databases, such as postgres, setting CASESENSITIVE to 1 will make
this search case sensitive

=item SUBCLAUSE

Subclause allows you to assign tags to Limit statements.  Statements with
matching SUBCLAUSE tags will be grouped together in the final SQL statement.

Example:

Suppose you want to create Limit statments which would produce results
the same as the following SQL:

   SELECT * FROM Users WHERE EmailAddress OR Name OR RealName OR Email LIKE $query;

You would use the following Limit statements:

    $folks->Limit( FIELD => 'EmailAddress', OPERATOR => 'LIKE', VALUE => "$query", SUBCLAUSE => 'groupsearch');
    $folks->Limit( FIELD => 'Name', OPERATOR => 'LIKE', VALUE => "$query", SUBCLAUSE => 'groupsearch');
    $folks->Limit( FIELD => 'RealName', OPERATOR => 'LIKE', VALUE => "$query", SUBCLAUSE => 'groupsearch');

=back

=cut

sub Limit {
    my $self = shift;
    my %args = (
        TABLE           => $self->Table,
        FIELD           => undef,
        VALUE           => undef,
        ALIAS           => undef,
        QUOTEVALUE      => 1,
        ENTRYAGGREGATOR => undef,
        CASESENSITIVE   => undef,
        OPERATOR        => '=',
        SUBCLAUSE       => undef,
        LEFTJOIN        => undef,
        @_    # get the real argumentlist
    );

    unless ( $args{'ENTRYAGGREGATOR'} ) {
        if ( $args{'LEFTJOIN'} ) {
            $args{'ENTRYAGGREGATOR'} = 'AND';
            } else {

            $args{'ENTRYAGGREGATOR'} = 'OR';
            }
    }


    #since we're changing the search criteria, we need to redo the search
    $self->RedoSearch();

    if ( $args{'FIELD'} ) {

        #If it's a like, we supply the %s around the search term
        if ( $args{'OPERATOR'} =~ /LIKE/i ) {
            $args{'VALUE'} = "%" . $args{'VALUE'} . "%";
        }
        elsif ( $args{'OPERATOR'} =~ /STARTSWITH/i ) {
            $args{'VALUE'}    = $args{'VALUE'} . "%";
        }
        elsif ( $args{'OPERATOR'} =~ /ENDSWITH/i ) {
            $args{'VALUE'}    = "%" . $args{'VALUE'};
        }
        $args{'OPERATOR'} =~ s/(?:MATCHES|ENDSWITH|STARTSWITH)/LIKE/i;

        #if we're explicitly told not to to quote the value or
        # we're doing an IS or IS NOT (null), don't quote the operator.

        if ( $args{'QUOTEVALUE'} && $args{'OPERATOR'} !~ /IS/i ) {
            $args{'VALUE'} = $self->_Handle->dbh->quote( $args{'VALUE'} );
        }
    }

    my $Alias = $self->_GenericRestriction(%args);

    warn "No table alias set!"
      unless $Alias;

    # We're now limited. people can do searches.

    $self->_isLimited(1);

    if ( defined($Alias) ) {
        return ($Alias);
    }
    else {
        return (1);
    }
}



sub _GenericRestriction {
    my $self = shift;
    my %args = ( TABLE           => $self->Table,
                 FIELD           => undef,
                 VALUE           => undef,
                 ALIAS           => undef,
                 LEFTJOIN        => undef,
                 ENTRYAGGREGATOR => undef,
                 OPERATOR        => '=',
                 SUBCLAUSE       => undef,
                 CASESENSITIVE   => undef,
                 QUOTEVALUE     => undef,
                 @_ );

    #TODO: $args{'VALUE'} should take an array of values and generate
    # the proper where clause.

    #If we're performing a left join, we really want the alias to be the
    #left join criterion.

    if ( defined $args{'LEFTJOIN'} && !defined $args{'ALIAS'} ) {
        $args{'ALIAS'} = $args{'LEFTJOIN'};
    }

    # {{{ if there's no alias set, we need to set it

    unless ( $args{'ALIAS'} ) {

        #if the table we're looking at is the same as the main table
        if ( $args{'TABLE'} eq $self->Table ) {

            # TODO this code assumes no self joins on that table.
            # if someone can name a case where we'd want to do that,
            # I'll change it.

            $args{'ALIAS'} = 'main';
        }

        # {{{ if we're joining, we need to work out the table alias

        else {
            $args{'ALIAS'} = $self->NewAlias( $args{'TABLE'} );
        }

        # }}}
    }

    # }}}

    # Set this to the name of the field and the alias, unless we've been
    # handed a subclause name

    my $QualifiedField = $args{'ALIAS'} . "." . $args{'FIELD'};
    my $ClauseId = $args{'SUBCLAUSE'} || $QualifiedField;

    # If we're trying to get a leftjoin restriction, lets set
    # $restriction to point htere. otherwise, lets construct normally

    my $restriction;
    if ( $args{'LEFTJOIN'} ) {
        if ( $args{'ENTRYAGGREGATOR'} ) {
            $self->{'left_joins'}{ $args{'LEFTJOIN'} }{'entry_aggregator'} = 
                $args{'ENTRYAGGREGATOR'};
        }
        $restriction = $self->{'left_joins'}{ $args{'LEFTJOIN'} }{'criteria'}{ $ClauseId } ||= [];
    }
    else {
        $restriction = $self->{'restrictions'}{ $ClauseId } ||= [];
    }

    # If it's a new value or we're overwriting this sort of restriction,

    if ( $self->_Handle->CaseSensitive && defined $args{'VALUE'} && $args{'VALUE'} ne ''  && $args{'VALUE'} ne "''" && ($args{'OPERATOR'} !~/IS/ && $args{'VALUE'} !~ /^null$/i)) {

        unless ( $args{'CASESENSITIVE'} || !$args{'QUOTEVALUE'} ) {
               ( $QualifiedField, $args{'OPERATOR'}, $args{'VALUE'} ) =
                 $self->_Handle->_MakeClauseCaseInsensitive( $QualifiedField,
                $args{'OPERATOR'}, $args{'VALUE'} );
        }

    }

    my $clause = {
        field => $QualifiedField,
        op => $args{'OPERATOR'},
        value => $args{'VALUE'},
    };

    # Juju because this should come _AFTER_ the EA
    my @prefix;
    if ( $self->{_open_parens}{ $ClauseId } ) {
        @prefix = ('(') x delete $self->{_open_parens}{ $ClauseId };
    }

    if ( lc( $args{'ENTRYAGGREGATOR'} || "" ) eq 'none' || !@$restriction ) {
        @$restriction = (@prefix, $clause);
    }
    else {
        push @$restriction, $args{'ENTRYAGGREGATOR'}, @prefix, $clause;
    }

    return ( $args{'ALIAS'} );

}


sub _OpenParen {
    my ($self, $clause) = @_;
    $self->{_open_parens}{ $clause }++;
}

# Immediate Action
sub _CloseParen {
    my ( $self, $clause ) = @_;
    my $restriction = ($self->{'restrictions'}{ $clause } ||= []);
    push @$restriction, ')';
}


sub _AddSubClause {
    my $self      = shift;
    my $clauseid  = shift;
    my $subclause = shift;

    $self->{'subclauses'}{ $clauseid } = $subclause;

}



sub _WhereClause {
    my $self = shift;

    #Go through all the generic restrictions and build up the "generic_restrictions" subclause
    # That's the only one that SearchBuilder builds itself.
    # Arguably, the abstraction should be better, but I don't really see where to put it.
    $self->_CompileGenericRestrictions();

    #Go through all restriction types. Build the where clause from the
    #Various subclauses.
    my $where_clause = '';
    foreach my $subclause ( grep $_, values %{ $self->{'subclauses'} } ) {
        $where_clause .= " AND " if $where_clause;
        $where_clause .= $subclause;
    }

    $where_clause = " WHERE " . $where_clause if $where_clause;

    return ($where_clause);
}


#Compile the restrictions to a WHERE Clause

sub _CompileGenericRestrictions {
    my $self = shift;

    my $result = '';
    #Go through all the restrictions of this type. Buld up the generic subclause
    foreach my $restriction ( grep @$_, values %{ $self->{'restrictions'} } ) {
        $result .= " AND " if $result;
        $result .= '(';
        foreach my $entry ( @$restriction ) {
            unless ( ref $entry ) {
                $result .= ' '. $entry . ' ';
            }
            else {
                $result .= join ' ', @{$entry}{qw(field op value)};
            }
        }
        $result .= ')';
    }
    return ($self->{'subclauses'}{'generic_restrictions'} = $result);
}


=head2 OrderBy PARAMHASH

Orders the returned results by ALIAS.FIELD ORDER.

Takes a paramhash of ALIAS, FIELD and ORDER.  
ALIAS defaults to C<main>.
FIELD has no default value.
ORDER defaults to ASC(ending). DESC(ending) is also a valid value for OrderBy.

FIELD also accepts C<FUNCTION(FIELD)> format.

=cut

sub OrderBy {
    my $self = shift;
    $self->OrderByCols( { @_ } );
}

=head2 OrderByCols ARRAY

OrderByCols takes an array of paramhashes of the form passed to OrderBy.
The result set is ordered by the items in the array.

=cut

sub OrderByCols {
    my $self = shift;
    my @args = @_;

    $self->{'order_by'} = \@args;
    $self->RedoSearch();
}

=head2 _OrderClause

returns the ORDER BY clause for the search.

=cut

sub _OrderClause {
    my $self = shift;

    return '' unless $self->{'order_by'};

    my $clause = '';
    foreach my $row ( @{$self->{'order_by'}} ) {

        my %rowhash = ( ALIAS => 'main',
			FIELD => undef,
			ORDER => 'ASC',
			%$row
		      );
        if ($rowhash{'ORDER'} && $rowhash{'ORDER'} =~ /^des/i) {
	    $rowhash{'ORDER'} = "DESC";
        }
        else {
	    $rowhash{'ORDER'} = "ASC";
        }
        $rowhash{'ALIAS'} = 'main' unless defined $rowhash{'ALIAS'};

        if ( defined $rowhash{'ALIAS'} and
	     $rowhash{'FIELD'} and
             $rowhash{'ORDER'} ) {

	    if ( length $rowhash{'ALIAS'} && $rowhash{'FIELD'} =~ /^(\w+\()(.*\))$/ ) {
		# handle 'FUNCTION(FIELD)' formatted fields
		$rowhash{'ALIAS'} = $1 . $rowhash{'ALIAS'};
		$rowhash{'FIELD'} = $2;
	    }

            $clause .= ($clause ? ", " : " ");
            $clause .= $rowhash{'ALIAS'} . "." if length $rowhash{'ALIAS'};
            $clause .= $rowhash{'FIELD'} . " ";
            $clause .= $rowhash{'ORDER'};
        }
    }
    $clause = " ORDER BY$clause " if $clause;

    return $clause;
}

=head2 GroupByCols ARRAY_OF_HASHES

Each hash contains the keys ALIAS and FIELD. ALIAS defaults to 'main' if ignored.

=cut

sub GroupByCols {
    my $self = shift;
    my @args = @_;

    $self->{'group_by'} = \@args;
    $self->RedoSearch();
}

=head2 _GroupClause

Private function to return the "GROUP BY" clause for this query.

=cut

sub _GroupClause {
    my $self = shift;
    return '' unless $self->{'group_by'};

    my $row;
    my $clause;

    foreach $row ( @{$self->{'group_by'}} ) {
        my %rowhash = ( ALIAS => 'main',
			FIELD => undef,
			%$row
		      );
        if ($rowhash{'FUNCTION'} ) {
            $clause .= ($clause ? ", " : " ");
            $clause .= $rowhash{'FUNCTION'};

        }
        elsif ( ($rowhash{'ALIAS'}) and
             ($rowhash{'FIELD'}) ) {

            $clause .= ($clause ? ", " : " ");
            $clause .= $rowhash{'ALIAS'} . ".";
            $clause .= $rowhash{'FIELD'};
        }
    }

    if ($clause) {
	return " GROUP BY" . $clause . " ";
    }
    else {
	return '';
    }
}

=head2 NewAlias

Takes the name of a table.
Returns the string of a new Alias for that table, which can be used to Join tables
or to Limit what gets found by a search.

=cut

sub NewAlias {
    my $self  = shift;
    my $table = shift || die "Missing parameter";
    my $type = shift;

    my $alias = $self->_GetAlias($table);

    unless ( $type ) {
        push @{ $self->{'aliases'} }, "$table $alias";
    } elsif ( lc $type eq 'left' ) {
        my $meta = $self->{'left_joins'}{"$alias"} ||= {};
        $meta->{'alias_string'} = " LEFT JOIN $table $alias ";
        $meta->{'type'} = 'LEFT';
        $meta->{'depends_on'} = '';
    } else {
        die "Unsupported alias(join) type";
    }

    return $alias;
}



# _GetAlias is a private function which takes an tablename and
# returns a new alias for that table without adding something
# to self->{'aliases'}.  This function is used by NewAlias
# and the as-yet-unnamed left join code

sub _GetAlias {
    my $self  = shift;
    my $table = shift;

    $self->{'alias_count'}++;
    my $alias = $table . "_" . $self->{'alias_count'};

    return ($alias);

}



=head2 Join

Join instructs DBIx::SearchBuilder to join two tables.  

The standard form takes a param hash with keys ALIAS1, FIELD1, ALIAS2 and 
FIELD2. ALIAS1 and ALIAS2 are column aliases obtained from $self->NewAlias or
a $self->Limit. FIELD1 and FIELD2 are the fields in ALIAS1 and ALIAS2 that 
should be linked, respectively.  For this type of join, this method
has no return value.

Supplying the parameter TYPE => 'left' causes Join to preform a left join.
in this case, it takes ALIAS1, FIELD1, TABLE2 and FIELD2. Because of the way
that left joins work, this method needs a TABLE for the second field
rather than merely an alias.  For this type of join, it will return
the alias generated by the join.

Instead of ALIAS1/FIELD1, it's possible to specify EXPRESSION, to join
ALIAS2/TABLE2 on an arbitrary expression.

It is also possible to join to a pre-existing, already-limited
L<DBIx::SearchBuilder> object, by passing it as COLLECTION2, instead
of providing an ALIAS2 or TABLE2.

=cut

sub Join {
    my $self = shift;
    my %args = (
        TYPE        => 'normal',
        FIELD1      => undef,
        ALIAS1      => 'main',
        TABLE2      => undef,
        COLLECTION2 => undef,
        FIELD2      => undef,
        ALIAS2      => undef,
        @_
    );

    $self->_Handle->Join( SearchBuilder => $self, %args );

}

=head2 Pages: size and changing

Use L</RowsPerPage> to set size of pages. L</NextPage>,
L</PrevPage>, L</FirstPage> or L</GotoPage> to change
pages. L</FirstRow> to do tricky stuff.

=head3 RowsPerPage

Get or set the number of rows returned by the database.

Takes an optional integer which restricts the # of rows returned
in a result. Zero or undef argument flush back to "return all
records matching current conditions".

Returns the current page size.

=cut

sub RowsPerPage {
    my $self = shift;

    if ( @_ && ($_[0]||0) != $self->{'show_rows'} ) {
        $self->{'show_rows'} = shift || 0;
        $self->RedoSearch;
    }

    return ( $self->{'show_rows'} );
}

=head3 NextPage

Turns one page forward.

=cut

sub NextPage {
    my $self = shift;
    $self->FirstRow( $self->FirstRow + 1 + $self->RowsPerPage );
}

=head3 PrevPage

Turns one page backwards.

=cut

sub PrevPage {
    my $self = shift;
    if ( ( $self->FirstRow - $self->RowsPerPage ) > 0 ) {
        $self->FirstRow( 1 + $self->FirstRow - $self->RowsPerPage );
    }
    else {
        $self->FirstRow(1);
    }
}

=head3 FirstPage

Jumps to the first page.

=cut

sub FirstPage {
    my $self = shift;
    $self->FirstRow(1);
}

=head3 GotoPage

Takes an integer number and jumps to that page or first page if
number omitted. Numbering starts from zero.

=cut

sub GotoPage {
    my $self = shift;
    my $page = shift || 0;

    $self->FirstRow( 1 + $self->RowsPerPage * $page );
}

=head3 FirstRow

Get or set the first row of the result set the database should return.
Takes an optional single integer argrument. Returns the currently set integer
minus one (this is historical issue).

Usually you don't need this method. Use L</RowsPerPage>, L</NextPage> and other
methods to walk pages. It only may be helpful to get 10 records starting from
5th.

=cut

sub FirstRow {
    my $self = shift;
    if (@_ && ($_[0]||1) != ($self->{'first_row'}+1) ) {
        $self->{'first_row'} = shift;

        #SQL starts counting at 0
        $self->{'first_row'}--;

        #gotta redo the search if changing pages
        $self->RedoSearch();
    }
    return ( $self->{'first_row'} );
}


=head2 _ItemsCounter

Returns the current position in the record set.

=cut

sub _ItemsCounter {
    my $self = shift;
    return $self->{'itemscount'};
}


=head2 Count

Returns the number of records in the set.

=cut

sub Count {
    my $self = shift;

    # An unlimited search returns no tickets    
    return 0 unless ($self->_isLimited);


    # If we haven't actually got all objects loaded in memory, we
    # really just want to do a quick count from the database.
    if ( $self->{'must_redo_search'} ) {

        # If we haven't already asked the database for the row count, do that
        $self->_DoCount unless ( $self->{'raw_rows'} );

        #Report back the raw # of rows in the database
        return ( $self->{'raw_rows'} );
    }

    # If we have loaded everything from the DB we have an
    # accurate count already.
    else {
        return $self->_RecordCount;
    }
}



=head2 CountAll

Returns the total number of potential records in the set, ignoring any
L</RowsPerPage> settings.

=cut

# 22:24 [Robrt(500@outer.space)] It has to do with Caching.
# 22:25 [Robrt(500@outer.space)] The documentation says it ignores the limit.
# 22:25 [Robrt(500@outer.space)] But I don't believe thats true.
# 22:26 [msg(Robrt)] yeah. I
# 22:26 [msg(Robrt)] yeah. I'm not convinced it does anything useful right now
# 22:26 [msg(Robrt)] especially since until a week ago, it was setting one variable and returning another
# 22:27 [Robrt(500@outer.space)] I remember.
# 22:27 [Robrt(500@outer.space)] It had to do with which Cached value was returned.
# 22:27 [msg(Robrt)] (given that every time we try to explain it, we get it Wrong)
# 22:27 [Robrt(500@outer.space)] Because Count can return a different number than actual NumberOfResults
# 22:28 [msg(Robrt)] in what case?
# 22:28 [Robrt(500@outer.space)] CountAll _always_ used the return value of _DoCount(), as opposed to Count which would return the cached number of 
#           results returned.
# 22:28 [Robrt(500@outer.space)] IIRC, if you do a search with a Limit, then raw_rows will == Limit.
# 22:31 [msg(Robrt)] ah.
# 22:31 [msg(Robrt)] that actually makes sense
# 22:31 [Robrt(500@outer.space)] You should paste this conversation into the CountAll docs.
# 22:31 [msg(Robrt)] perhaps I'll create a new method that _actually_ do that.
# 22:32 [msg(Robrt)] since I'm not convinced it's been doing that correctly


sub CountAll {
    my $self = shift;

    # An unlimited search returns no tickets    
    return 0 unless ($self->_isLimited);

    # If we haven't actually got all objects loaded in memory, we
    # really just want to do a quick count from the database.
    # or if we have paging enabled then we count as well and store it in count_all
    if ( $self->{'must_redo_search'} || ( $self->RowsPerPage && !$self->{'count_all'} ) ) {
        # If we haven't already asked the database for the row count, do that
        $self->_DoCount(1);

        #Report back the raw # of rows in the database
        return ( $self->{'count_all'} );
    }
    
    # if we have paging enabled and have count_all then return it
    elsif ( $self->RowsPerPage ) {
        return ( $self->{'count_all'} );
    }

    # If we have loaded everything from the DB we have an
    # accurate count already.
    else {
        return $self->_RecordCount;
    }
}


=head2 IsLast

Returns true if the current row is the last record in the set.

=cut

sub IsLast {
    my $self = shift;

    return undef unless $self->Count;

    if ( $self->_ItemsCounter == $self->Count ) {
        return (1);
    }
    else {
        return (0);
    }
}


=head2 Column

Call to specify which columns should be loaded from the table. Each
calls adds one column to the set.  Takes a hash with the following named
arguments:

=over 4

=item FIELD

Column name to fetch or apply function to.  This can be omitted if a
FUNCTION is given which is not a function of a field.

=item ALIAS

Alias of a table the field is in; defaults to C<main>

=item FUNCTION

A SQL function that should be selected as the result.  If a FIELD is
provided, then it is inserted into the function according to the
following rules:

=over 4

=item *

If the text of the function contains a '?' (question mark), then it is
replaced with qualified FIELD.

=item *

If the text of the function has no '(' (opening parenthesis), then the
qualified FIELD is appended in parentheses to the text.

=item *

Otherwise, the function is inserted verbatim, with no substitution.

=back

=back

If a FIELD is provided and it is in this table (ALIAS is 'main'), then
the column named FIELD and can be accessed as usual by accessors:

    $articles->Column(FIELD => 'id');
    $articles->Column(FIELD => 'Subject', FUNCTION => 'SUBSTR(?, 1, 20)');
    my $article = $articles->First;
    my $aid = $article->id;
    my $subject_prefix = $article->Subject;

Returns the alias used for the column. If FIELD was not provided, or was
from another table, then the returned column alias should be passed to
the L<DBIx::SearchBuilder::Record/_Value> method to retrieve the
column's result:

    my $time_alias = $articles->Column(FUNCTION => 'NOW()');
    my $article = $articles->First;
    my $now = $article->_Value( $time_alias );

=cut

sub Column {
    my $self = shift;
    my %args = ( TABLE => undef,
               ALIAS => undef,
               FIELD => undef,
               FUNCTION => undef,
               @_);

    $args{'ALIAS'} ||= 'main';

    my $name;
    if ( $args{FIELD} && $args{FUNCTION} ) {
        $name = $args{'ALIAS'} .'.'. $args{'FIELD'};

        my $func = $args{FUNCTION};
        if ( $func =~ /^DISTINCT\s*COUNT$/i ) {
            $name = "COUNT(DISTINCT $name)";
        }
        # If we want to substitute 
        elsif ($func =~ s/\?/$name/g) {
            $name = $func;
        }
        # If we want to call a simple function on the column
        elsif ($func !~ /\(/)  {
            $name = "\U$func\E($name)";
        } else {
            $name = $func;
        }
    }
    elsif ( $args{FUNCTION} ) {
        $name = $args{FUNCTION};
    }
    elsif ( $args{FIELD} ) {
        $name = $args{'ALIAS'} .'.'. $args{'FIELD'};
    }
    else {
        $name = 'NULL';
    }

    my $column;
    if (
        $args{FIELD} && $args{ALIAS} eq 'main'
        && (!$args{'TABLE'} || $args{'TABLE'} eq $self->Table )
    ) {
        $column = $args{FIELD};

        # make sure we don't fetch columns with duplicate aliases
        if ( $self->{columns} ) {
            my $suffix = " AS \L$column";
            if ( grep index($_, $suffix, -length $suffix) >= 0, @{ $self->{columns} } ) {
                $column .= scalar @{ $self->{columns} };
            }
        }
    }
    else {
        $column = "col" . @{ $self->{columns} ||= [] };
    }
    push @{ $self->{columns} ||= [] }, "$name AS \L$column";
    return $column;
}




=head2 Columns LIST

Specify that we want to load only the columns in LIST

=cut

sub Columns {
    my $self = shift;
    $self->Column( FIELD => $_ ) for @_;
}


=head2 Fields TABLE

Return a list of fields in TABLE, lowercased.

TODO: Why are they lowercased?

=cut

sub Fields {
    return (shift)->_Handle->Fields( @_ );
}


=head2 HasField  { TABLE => undef, FIELD => undef }

Returns true if TABLE has field FIELD.
Return false otherwise

=cut

sub HasField {
    my $self = shift;
    my %args = ( FIELD => undef,
                 TABLE => undef,
                 @_);

    my $table = $args{TABLE} or die;
    my $field = $args{FIELD} or die;
    return grep { $_ eq $field } $self->Fields($table);
}


=head2 Table [TABLE]

If called with an argument, sets this collection's table.

Always returns this collection's table.

=cut

sub Table {
    my $self = shift;
    $self->{table} = shift if (@_);
    return $self->{table};
}

=head1 DEPRECATED METHODS

=head2 GroupBy

DEPRECATED. Alias for the L</GroupByCols> method.

=cut

sub GroupBy { (shift)->GroupByCols( @_ ) }

=head2 SetTable

DEPRECATED. Alias for the L</Table> method.

=cut

sub SetTable {
    my $self = shift;
    return $self->Table(@_);
}

=head2 ShowRestrictions

DEPRECATED AND DOES NOTHING.

=cut

sub ShowRestrictions { }

=head2 ImportRestrictions

DEPRECATED AND DOES NOTHING.

=cut

sub ImportRestrictions { }

# not even documented
sub DEBUG { warn "DEBUG is deprecated" }


if( eval { require capitalization } ) {
	capitalization->unimport( __PACKAGE__ );
}

1;
__END__



=head1 TESTING

In order to test most of the features of C<DBIx::SearchBuilder>, you need
to provide C<make test> with a test database.  For each DBI driver that you
would like to test, set the environment variables C<SB_TEST_FOO>, C<SB_TEST_FOO_USER>,
and C<SB_TEST_FOO_PASS> to a database name, database username, and database password,
where "FOO" is the driver name in all uppercase.  You can test as many drivers
as you like.  (The appropriate C<DBD::> module needs to be installed in order for
the test to work.)  Note that the C<SQLite> driver will automatically be tested if C<DBD::Sqlite>
is installed, using a temporary file as the database.  For example:

  SB_TEST_MYSQL=test SB_TEST_MYSQL_USER=root SB_TEST_MYSQL_PASS=foo \
    SB_TEST_PG=test SB_TEST_PG_USER=postgres  make test


=head1 AUTHOR

Copyright (c) 2001-2006 Jesse Vincent, jesse@bestpractical.com.

All rights reserved.

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


=head1 SEE ALSO

DBIx::SearchBuilder::Handle, DBIx::SearchBuilder::Record.

=cut