4 use vars qw($DEBUG $buffer);
5 use base qw( Exporter );
6 use FS::Record qw(qsearch dbdef dbh);
8 use Scalar::Util qw(refaddr);
11 # this might become a parameter at some point, but right now, you can
12 # "local $FS::Cursor::buffer = X;"
17 FS::Cursor - Iterator for querying large data sets
23 my $search = FS::Cursor->new('table', { field => 'value' ... });
24 while ( my $row = $search->fetch ) {
34 Constructs a cursored search. Accepts all the same arguments as qsearch,
35 and returns an FS::Cursor object to fetch the rows one at a time.
41 my $q = FS::Record::_query(@_); # builds the statement and parameter list
45 class => 'FS::' . ($q->{table} || 'Record'),
50 # the class of record object to return
51 $self->{class} = "FS::".($q->{table} || 'Record');
53 $self->{id} = sprintf('cursor%08x', refaddr($self));
54 my $statement = "DECLARE ".$self->{id}." CURSOR FOR ".$q->{statement};
57 my $sth = $dbh->prepare($statement)
60 foreach my $value ( @{ $q->{value} } ) {
61 my $bind_type = shift @{ $q->{bind_type} };
62 $sth->bind_param($bind++, $value, $bind_type );
65 $sth->execute or die $sth->errstr;
67 $self->{fetch} = $dbh->prepare("FETCH FORWARD $buffer FROM ".$self->{id});
80 Fetch the next row from the search results.
85 # might be a little more efficient to do a FETCH NEXT 1000 or something
86 # and buffer them locally, but the semantics are simpler this way
88 if (@{ $self->{buffer} } == 0) {
89 my $rows = $self->refill;
90 return undef if !$rows;
92 $self->{class}->new(shift @{ $self->{buffer} });
97 my $sth = $self->{fetch};
98 $sth->execute or die $sth->errstr;
99 my $result = $self->{fetch}->fetchall_arrayref( {} );
100 $self->{buffer} = $result;
108 Replace all uses of qsearch with this.
112 Doesn't support MySQL.