- #assuming mysql 4.1 w/subqueries now
- #my $nodepend = driver_name eq 'mysql'
- # ? ''
- # : 'AND 0 = ( SELECT COUNT(*) FROM queue_depend'.
- # ' WHERE queue_depend.jobnum = queue.jobnum ) ';
- my $nodepend = 'AND 0 = ( SELECT COUNT(*) FROM queue_depend'.
- ' WHERE queue_depend.jobnum = queue.jobnum ) ';
-
- my $job = qsearchs(
- 'queue',
- { 'status' => 'new' },
- '',
- driver_name eq 'mysql'
- ? "$nodepend ORDER BY jobnum LIMIT 1 FOR UPDATE"
- : "$nodepend ORDER BY jobnum FOR UPDATE LIMIT 1"
- ) or do {
- # if $oldAutoCommit {
+ my $nodepend = 'AND NOT EXISTS( SELECT 1 FROM queue_depend'.
+ ' WHERE queue_depend.jobnum = queue.jobnum )';
+
+ #anything with a priority goes after stuff without one
+ my $order_by = ' ORDER BY COALESCE(priority,0) ASC, jobnum ASC ';
+
+ my $limit = $max_kids - $kids;
+
+ $order_by .= ( driver_name eq 'mysql'
+ ? " LIMIT $limit FOR UPDATE "
+ : " FOR UPDATE LIMIT $limit " );
+
+ my $hashref = { 'status' => 'new' };
+ if ( $opt{'s'} ) {
+ $hashref->{'secure'} = 'Y';
+ } elsif ( $opt{'n'} ) {
+ $hashref->{'secure'} = '';
+ }
+
+ #qsearch dies when the db goes away
+ my @jobs = eval {
+ qsearch({
+ 'table' => 'queue',
+ 'hashref' => $hashref,
+ 'extra_sql' => $nodepend,
+ 'order_by' => $order_by,
+ });
+ };
+ if ( $@ ) {
+ warn "WARNING: error searching for jobs, closing connection: $@";
+ undef $FS::UID::dbh;
+ next;
+ }
+
+ unless ( @jobs ) {