Enforce query max runtime/execution time limits
439855
private void enforceTimeLimits()
    {
        for (T query : queries.values()) {
            if (query.isDone()) {
                continue;
            }
            Duration queryMaxRunTime = getQueryMaxRunTime(query.getSession());
            Duration queryMaxExecutionTime = getQueryMaxExecutionTime(query.getSession());
            Optional<DateTime> executionStartTime = query.getExecutionStartTime();
            DateTime createTime = query.getCreateTime();
            if (executionStartTime.isPresent() && executionStartTime.get().plus(queryMaxExecutionTime.toMillis()).isBeforeNow()) {
                query.fail(new PrestoException(EXCEEDED_TIME_LIMIT, "Query exceeded the maximum execution time limit of " + queryMaxExecutionTime));
            }
            if (createTime.plus(queryMaxRunTime.toMillis()).isBeforeNow()) {
                query.fail(new PrestoException(EXCEEDED_TIME_LIMIT, "Query exceeded maximum time limit of " + queryMaxRunTime));
            }
        }
    }
144649
private int getMaxRowCount(Session session, int rowCount) {

        int limitStart = getLimitStart(session);
        int limitCount = getLimitCount(session, rowCount);

        if (simpleLimit) {
            if (rowCount == 0) {
                rowCount = limitCount;
            }

            // A VoltDB extension to support LIMIT 0
            if (rowCount > Integer.MAX_VALUE - limitStart) {
            /* disable 1 line ...
            if (rowCount == 0 || rowCount > Integer.MAX_VALUE - limitStart) {
            ... disabled 1 line */
            // End of VoltDB extension
                rowCount = Integer.MAX_VALUE;
            } else {
                rowCount += limitStart;
            }
        } else {
            rowCount = Integer.MAX_VALUE;
            // A VoltDB extension to support LIMIT 0
            // limitCount == 0 can be enforced/optimized as rowCount == 0 regardless of offset
            // even in non-simpleLimit cases (SELECT DISTINCT, GROUP BY, and/or ORDER BY).
            // This is an optimal handling of a hard-coded LIMIT 0, but it really shouldn't be the ONLY
            // enforcement for zero LIMITs -- what about "LIMIT ?" with 0 passed later as a parameter?
            // The HSQL executor ("HSQL back end") also needs runtime enforcement of zero limits.
            // The VoltDB executor has such enforcement.
            if (limitCount == 0) {
                rowCount = 0;
            }
            // End of VoltDB extension
        }

        return rowCount;
    }
423852
private function limitQuery()
    {
        $this->query->skip($this->queryConfiguration->start());
        $this->query->limit($this->queryConfiguration->length());
    }
76197
public static String getLimitSQL(String query, long offset, long length, String dbType) {
		if (query == null) {
			return null;
		}
		query = query.trim();
		if (StringUtils.startsWithIgnoreCase(query, "select")) {
			boolean isForUpdate = false;
			if (query.toLowerCase().endsWith(" for update")) {
				query = query.substring(0, query.length() - 11);
				isForUpdate = true;
			}

			StringBuffer pagingSelect = new StringBuffer(query.length() + 100);
			if (dbType.equalsIgnoreCase("oracle")) {
				if (offset > 0) {
					pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
				} else {
					pagingSelect.append("select * from ( ");
				}
				pagingSelect.append(query);
				if (offset > 0) {
					pagingSelect.append(String.format(" ) row_ where rownum <= %d) where rownum_ > %d", length + offset, offset));
				} else {
					pagingSelect.append(String.format(" ) where rownum <= %d", length));
				}
			} else if (dbType.equalsIgnoreCase("mysql")) {
				pagingSelect.append("select * from ( ");
				pagingSelect.append(query);
				pagingSelect.append(String.format(" ) t limit %d, %d", offset, length));
			}

			if (isForUpdate) {
				pagingSelect.append(" for update");
			}

			return pagingSelect.toString();
		}
		return query;
	}
333859
def execute_sql_statement(sql_statement, query, user_name, session, cursor):
    """"""
    database = query.database
    db_engine_spec = database.db_engine_spec
    parsed_query = ParsedQuery(sql_statement)
    sql = parsed_query.stripped()
    SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW')

    if not parsed_query.is_readonly() and not database.allow_dml:
        raise SqlLabSecurityException(
            _('Only `SELECT` statements are allowed against this database'))
    if query.select_as_cta:
        if not parsed_query.is_select():
            raise SqlLabException(_(
                'Only `SELECT` statements can be used with the CREATE TABLE '
                'feature.'))
        if not query.tmp_table_name:
            start_dttm = datetime.fromtimestamp(query.start_time)
            query.tmp_table_name = 'tmp_{}_table_{}'.format(
                query.user_id, start_dttm.strftime('%Y_%m_%d_%H_%M_%S'))
        sql = parsed_query.as_create_table(query.tmp_table_name)
        query.select_as_cta_used = True
    if parsed_query.is_select():
        if SQL_MAX_ROWS and (not query.limit or query.limit > SQL_MAX_ROWS):
            query.limit = SQL_MAX_ROWS
        if query.limit:
            sql = database.apply_limit_to_sql(sql, query.limit)

    # Hook to allow environment-specific mutation (usually comments) to the SQL
    SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR')
    if SQL_QUERY_MUTATOR:
        sql = SQL_QUERY_MUTATOR(sql, user_name, security_manager, database)

    try:
        if log_query:
            log_query(
                query.database.sqlalchemy_uri,
                query.executed_sql,
                query.schema,
                user_name,
                __name__,
                security_manager,
            )
        query.executed_sql = sql
        with stats_timing('sqllab.query.time_executing_query', stats_logger):
            logging.info('Running query: \n{}'.format(sql))
            db_engine_spec.execute(cursor, sql, async_=True)
            logging.info('Handling cursor')
            db_engine_spec.handle_cursor(cursor, query, session)

        with stats_timing('sqllab.query.time_fetching_results', stats_logger):
            logging.debug('Fetching data for query object: {}'.format(query.to_dict()))
            data = db_engine_spec.fetch_data(cursor, query.limit)

    except SoftTimeLimitExceeded as e:
        logging.exception(e)
        raise SqlLabTimeoutException(
            "SQL Lab timeout. This environment's policy is to kill queries "
            'after {} seconds.'.format(SQLLAB_TIMEOUT))
    except Exception as e:
        logging.exception(e)
        raise SqlLabException(db_engine_spec.extract_error_message(e))

    logging.debug('Fetching cursor description')
    cursor_description = cursor.description
    return dataframe.SupersetDataFrame(data, cursor_description, db_engine_spec)
159486
private void onLimit(StringBuilder builder)
    {
        builder.append(CQLTranslator.LIMIT);
        builder.append(this.maxResult);
    }
310827
def query_all(**kwargs):
        '''
        
        '''
        kind = kwargs.get('kind', '1')
        limit = kwargs.get('limit', 10)

        return TabPost.select().where(
            (TabPost.kind == kind) &
            (TabPost.valid == 1)
        ).order_by(
            TabPost.time_update.desc()
        ).limit(limit)
731342
function SelectLimit($sql, $nrows=-1, $offset=-1, $inputarr=false, $secs=0)
	{
		$offsetStr =($offset>=0) ? "$offset," : '';
		// jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
		if ($nrows < 0) {
			$nrows = '18446744073709551615';
		}

		if ($secs) {
			$rs = $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows", $inputarr);
		} else {
			$rs = $this->Execute($sql . " LIMIT $offsetStr$nrows", $inputarr);
		}
		return $rs;
	}
362525
def get_query_with_new_limit(self, new_limit):
        """does not change the underlying query"""
        if not self._limit:
            return self.sql + ' LIMIT ' + str(new_limit)
        limit_pos = None
        tokens = self._parsed[0].tokens
        # Add all items to before_str until there is a limit
        for pos, item in enumerate(tokens):
            if item.ttype in Keyword and item.value.lower() == 'limit':
                limit_pos = pos
                break
        limit = tokens[limit_pos + 2]
        if limit.ttype == sqlparse.tokens.Literal.Number.Integer:
            tokens[limit_pos + 2].value = new_limit
        elif limit.is_group:
            tokens[limit_pos + 2].value = (
                '{}, {}'.format(next(limit.get_identifiers()), new_limit)
            )

        str_res = ''
        for i in tokens:
            str_res += str(i.value)
        return str_res
527726
function runQuery(query, connection) {
  let incomplete = false;
  const rows = [];
  const port = connection.port || 8080;
  const prestoConfig = {
    url: `http://${connection.host}:${port}`,
    user: connection.username,
    catalog: connection.prestoCatalog,
    schema: connection.prestoSchema
  };
  return presto.send(prestoConfig, query).then(result => {
    if (!result) {
      throw new Error('No result returned');
    }
    let { data, columns } = result;
    if (data.length > connection.maxRows) {
      incomplete = true;
      data = data.slice(0, connection.maxRows);
    }
    for (let r = 0; r < data.length; r++) {
      const row = {};
      for (let c = 0; c < columns.length; c++) {
        row[columns[c].name] = data[r][c];
      }
      rows.push(row);
    }
    return { rows, incomplete };
  });
}
360420
@Override
    public void setQueryTimeout(int seconds) throws SQLException
    {
        checkClosed();
        if (seconds < 0) {
            throw SQLError.get(SQLError.ILLEGAL_ARGUMENT, seconds);
        }
        if (seconds == 0) {
            this.m_timeout = Integer.MAX_VALUE;
        } else {
            this.m_timeout = seconds;
        }
    }
113299
def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0):
        

        # run the raw query and get total
        # we want to exclude layers which are not valid, as it is done in the search engine
        if 'where' in constraint:  # GetRecords with constraint
            query = self._get_repo_filter(Layer.objects).filter(
                is_valid=True).extra(where=[constraint['where']], params=constraint['values'])
        else:  # GetRecords sans constraint
            query = self._get_repo_filter(Layer.objects).filter(is_valid=True)

        total = query.count()

        # apply sorting, limit and offset
        if sortby is not None:
            if 'spatial' in sortby and sortby['spatial']:  # spatial sort
                desc = False
                if sortby['order'] == 'DESC':
                    desc = True
                query = query.all()
                return [str(total),
                        sorted(query,
                               key=lambda x: float(util.get_geometry_area(getattr(x, sortby['propertyname']))),
                               reverse=desc,
                               )[startposition:startposition+int(maxrecords)]]
            else:
                if sortby['order'] == 'DESC':
                    pname = '-%s' % sortby['propertyname']
                else:
                    pname = sortby['propertyname']
                return [str(total),
                        query.order_by(pname)[startposition:startposition+int(maxrecords)]]
        else:  # no sort
            return [str(total), query.all()[startposition:startposition+int(maxrecords)]]
175048
def query_expired(cls, dt, bucket=None):
        """"""
        q = cls.query.filter(cls.created < dt).filter_by(completed=True)
        if bucket:
            q = q.filter(cls.bucket_id == as_bucket_id(bucket))
        return q
1100981
def getMaxTimeAllowed(self):
        
        tat = self.Schema().getField("MaxTimeAllowed").get(self)
        return tat or self.bika_setup.getDefaultTurnaroundTime()
568192
private void pruneExpiredQueries()
    {
        if (expirationQueue.size() <= maxQueryHistory) {
            return;
        }

        int count = 0;
        // we're willing to keep full info for up to maxQueryHistory queries
        for (T query : expirationQueue) {
            if (expirationQueue.size() - count <= maxQueryHistory) {
                break;
            }
            query.pruneInfo();
            count++;
        }
    }
1299374
def query(self,
              startTime=None,
              endTime=None,
              sinceServerStart=False,
              level="WARNING",
              services="*",
              machines="*",
              server="*",
              codes=[],
              processIds=[],
              export=False,
              exportType="CSV", #CSV or TAB
              out_path=None
              ):
        
        allowed_levels = ("SEVERE", "WARNING", "INFO",
                          "FINE", "VERBOSE", "DEBUG")
        qFilter = {
            "services": "*",
            "machines": "*",
            "server" : "*"
        }
        if len(processIds) > 0:
            qFilter['processIds'] = processIds
        if len(codes) > 0:
            qFilter['codes'] = codes
        params = {
            "f" : "json",
            "sinceServerStart" : sinceServerStart,
            "pageSize" : 10000
        }
        if startTime is not None and \
           isinstance(startTime, datetime):
            params['startTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")
        if endTime is not None and \
           isinstance(endTime, datetime):
            params['endTime'] = endTime.strftime("%Y-%m-%dT%H:%M:%S")
        if level.upper() in allowed_levels:
            params['level'] = level
        if server != "*":
            qFilter['server'] = server.split(',')
        if services != "*":
            qFilter['services'] = services.split(',')
        if machines != "*":
            qFilter['machines'] = machines.split(",")
        params['filter'] = qFilter
        if export == True and \
           out_path is not None:
            messages = self._post(self._url + "/query", params,
                                     securityHandler=self._securityHandler,
                                     proxy_url=self._proxy_url,
                                     proxy_port=self._proxy_port)

            with open(name=out_path, mode='wb') as f:
                hasKeys = False
                if exportType == "TAB":
                    csvwriter = csv.writer(f, delimiter='\t')
                else:
                    csvwriter = csv.writer(f)
                for message in messages['logMessages']:
                    if hasKeys == False:
                        csvwriter.writerow(message.keys())
                        hasKeys = True
                    csvwriter.writerow(message.values())
                    del message
            del messages
            return out_path
        else:
            return self._post(self._url + "/query", params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
638810
public void setQueryTimeoutMs(long millis) throws SQLException {
    checkClosed();

    if (millis < 0) {
      throw new PSQLException(GT.tr("Query timeout must be a value greater than or equals to 0."),
          PSQLState.INVALID_PARAMETER_VALUE);
    }
    timeout = millis;
  }