4 use vars qw($DEBUG $buffer);
5 use FS::Record qw(dbh);
6 use Scalar::Util qw(refaddr);
10 # this might become a parameter at some point, but right now, you can
11 # "local $FS::Cursor::buffer = X;"
16 FS::Cursor - Iterator for querying large data sets
22 my $search = FS::Cursor->new('table', { field => 'value' ... });
23 while ( my $row = $search->fetch ) {
33 Constructs a cursored search. Accepts all the same arguments as qsearch,
34 and returns an FS::Cursor object to fetch the rows one at a time.
40 my $q = FS::Record::_query(@_); # builds the statement and parameter list
44 class => 'FS::' . ($q->{table} || 'Record'),
49 # the class of record object to return
50 $self->{class} = "FS::".($q->{table} || 'Record');
52 $self->{id} = sprintf('cursor%08x', refaddr($self));
53 my $statement = "DECLARE ".$self->{id}." CURSOR FOR ".$q->{statement};
55 my $sth = dbh->prepare($statement)
58 foreach my $value ( @{ $q->{value} } ) {
59 my $bind_type = shift @{ $q->{bind_type} };
60 $sth->bind_param($bind++, $value, $bind_type );
63 $sth->execute or die $sth->errstr;
65 $self->{fetch} = dbh->prepare("FETCH FORWARD $buffer FROM ".$self->{id});
78 Fetch the next row from the search results.
83 # might be a little more efficient to do a FETCH NEXT 1000 or something
84 # and buffer them locally, but the semantics are simpler this way
86 if (@{ $self->{buffer} } == 0) {
87 my $rows = $self->refill;
88 return undef if !$rows;
90 $self->{class}->new(shift @{ $self->{buffer} });
95 my $sth = $self->{fetch};
96 $sth->execute or die $sth->errstr;
97 my $result = $self->{fetch}->fetchall_arrayref( {} );
98 $self->{buffer} = $result;
104 dbh->do('CLOSE '. $self->{id}) or die dbh->errstr; # clean-up the cursor in Pg
111 Replace all uses of qsearch with this.
115 Doesn't support MySQL.