Display queries (using Output)

@param array $queries
@param bool $useColor
@param bool $useTemplate
@throws \RuntimeException
171758
public function displayQueries(array $queries = array(), $useColor = false, $useTemplate = false)
    {
        if (!$this->output) {
            throw new \RuntimeException('No output is defined');
        }
        $this->formatQueries($queries, $useColor);

        if ($useTemplate) {
            $content = $this->templateParser->parse($queries)->getContent();
        } else {

            $content = implode('', $queries);
        }

        $this->output->write($content);
    }
966685
public function build($route, $params = null, array $queries = null)
    {
        $base = Base::instance();
        $url = $base["ALIASES.$route"];
        if (empty($url)) {
            throw new RuntimeException(sprintf(static::E_ROUTE, $route));
        }
        $params = (array) $params;

        return $base['BASE'] . $this->replaceToken($url, $params).
            $this->addQueries($queries);
    }
112094
public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
    {
        $stmt = null;
        $attempt = 0;
        $retry = true;
        while ($retry) {
            $retry = false;
            try {
                $stmt = parent::executeQuery($query, $params, $types, $qcp);
            } catch (\Exception $e) {
                if ($this->canTryAgain($attempt) && $this->isRetryableException($e, $query)) {
                    $this->close();
                    ++$attempt;
                    $retry = true;
                } else {
                    throw $e;
                }
            }
        }

        return $stmt;
    }
401230
private static void addTable(Connection conn, PageContext pc, String name, Query query, boolean doSimpleTypes, ArrayList<String> usedTables)
	    throws SQLException, PageException {
	Statement stat;
	usedTables.add(name);
	stat = conn.createStatement();
	Key[] keys = CollectionUtil.keys(query);
	int[] types = query.getTypes();
	int[] innerTypes = toInnerTypes(types);
	// CREATE STATEMENT
	String comma = "";
	StringBuilder create = new StringBuilder("CREATE TABLE " + name + " (");
	StringBuilder insert = new StringBuilder("INSERT INTO  " + name + " (");
	StringBuilder values = new StringBuilder("VALUES (");
	for (int i = 0; i < keys.length; i++) {
	    String key = keys[i].getString();
	    String type = (doSimpleTypes) ? "VARCHAR_IGNORECASE" : toUsableType(types[i]);

	    create.append(comma + key);
	    create.append(" ");
	    create.append(type);
	    insert.append(comma + key);
	    values.append(comma + "?");
	    comma = ",";
	}
	create.append(")");
	insert.append(")");
	values.append(")");
	stat.execute(create.toString());
	PreparedStatement prepStat = conn.prepareStatement(insert.toString() + values.toString());

	// INSERT STATEMENT
	// HashMap integerTypes=getIntegerTypes(types);

	int count = query.getRecordcount();
	QueryColumn[] columns = new QueryColumn[keys.length];
	for (int i = 0; i < keys.length; i++) {
	    columns[i] = query.getColumn(keys[i]);
	}
	for (int y = 0; y < count; y++) {
	    for (int i = 0; i < keys.length; i++) {
		int type = innerTypes[i];
		Object value = columns[i].get(y + 1, null);

		// print.out("*** "+type+":"+Caster.toString(value));
		if (doSimpleTypes) {

		    prepStat.setObject(i + 1, Caster.toString(value));
		}
		else {
		    if (value == null) prepStat.setNull(i + 1, types[i]);
		    else if (type == BINARY) prepStat.setBytes(i + 1, Caster.toBinary(value));
		    else if (type == DATE) {
			// print.out(new java.util.Date(new
			// Date(DateCaster.toDateAdvanced(value,pc.getTimeZone()).getTime()).getTime()));

			prepStat.setTimestamp(i + 1, (value.equals("")) ? null : new Timestamp(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
			// prepStat.setObject(i+1,Caster.toDate(value,null));
			// prepStat.setDate(i+1,(value==null || value.equals(""))?null:new
			// Date(DateCaster.toDateAdvanced(value,pc.getTimeZone()).getTime()));
		    }
		    else if (type == TIME)
			prepStat.setTime(i + 1, (value.equals("")) ? null : new Time(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
		    else if (type == TIMESTAMP)
			prepStat.setTimestamp(i + 1, (value.equals("")) ? null : new Timestamp(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
		    else if (type == DOUBLE) prepStat.setDouble(i + 1, (value.equals("")) ? 0 : Caster.toDoubleValue(query.getAt(keys[i], y + 1)));
		    else if (type == INT) prepStat.setLong(i + 1, (value.equals("")) ? 0 : Caster.toLongValue(query.getAt(keys[i], y + 1)));
		    else if (type == STRING) prepStat.setObject(i + 1, Caster.toString(value));
		}

	    }
	    prepStat.execute();
	}

    }
858972
private function executeQueries(array $queries)
    {
        foreach ($queries as $query) {
            $this->connection->prepare($query)->execute();
        }
    }
132738
public static function getQueryTemplate($template, ...$arguments)
    {
        $strQuery = $template;
        foreach ($arguments as $i => &$argument) {
            $strQuery = str_replace('%' . $i, $argument, $strQuery);
        }

        return $strQuery;
    }
572167
public void usersCountByTemplateIdAndPermission(DbSession dbSession, List<Long> templateIds, ResultHandler<CountByTemplateAndPermissionDto> resultHandler) {
    Map<String, Object> parameters = new HashMap<>(1);

    executeLargeInputsWithoutOutput(
      templateIds,
      partitionedTemplateIds -> {
        parameters.put("templateIds", partitionedTemplateIds);
        mapper(dbSession).usersCountByTemplateIdAndPermission(parameters, resultHandler);
      });
  }
161385
public function query(DataStructure\Query\Query $queries)
    {
        $logicFunc = 'andWhere';
        if ($queries instanceof DataStructure\OrQuery) {
            $logicFunc = 'orWhere';
        }

        foreach ($queries as $query) {

            if ($this->isExcludedProperty($query->getProperty())) {
                continue;
            }

            $value = $this->unlockSpecialProperty($query->getProperty(), $query->getValue());

            if ($query instanceof Expression\Equal) {

                $this->criteria->{$logicFunc}(Criteria::expr()->eq($query->getProperty(), $value));

            } elseif ($query instanceof Expression\NotEqual) {

                $this->criteria->{$logicFunc}(Criteria::expr()->neq($query->getProperty(), $value));

            } elseif ($query instanceof Expression\GreaterThan) {

                $this->criteria->{$logicFunc}(Criteria::expr()->gt($query->getProperty(), $value));

            } elseif ($query instanceof Expression\GreaterThanEqual) {

                $this->criteria->{$logicFunc}(Criteria::expr()->gte($query->getProperty(), $value));

            } elseif ($query instanceof Expression\LesserThan) {

                $this->criteria->{$logicFunc}(Criteria::expr()->lt($query->getProperty(), $value));

            } elseif ($query instanceof Expression\LesserThanEqual) {

                $this->criteria->{$logicFunc}(Criteria::expr()->lte($query->getProperty(), $value));

            } elseif ($query instanceof Expression\In) {

                $this->criteria->{$logicFunc}(Criteria::expr()->in($query->getProperty(), $value));

            } elseif ($query instanceof Expression\NotIn) {

                $this->criteria->{$logicFunc}(Criteria::expr()->notIn($query->getProperty(), $query->getValue()));

            }

        }
    }
56449
protected List<User> executePaginatedQuery(UserQuery query, Integer firstResult, Integer maxResults) {
    if (firstResult == null) {
      firstResult = 0;
    }
    if (maxResults == null) {
      maxResults = Integer.MAX_VALUE;
    }
    return query.listPage(firstResult, maxResults);
  }
1090648
public function display(string $template)
    {
        if ($this->context && is_callable([$this->context, 'end'])) {
            $this->context->end($this->fetch($template));
        } else {
            echo $this->fetch($template);
        }
    }
293419
public function query_db($pagesize, $useinitialsbar = true) {

        $total = \tool_monitor\rule_manager::count_rules_by_courseid($this->courseid);
        $this->pagesize($pagesize, $total);
        $rules = \tool_monitor\rule_manager::get_rules_by_courseid($this->courseid, $this->get_page_start(),
                $this->get_page_size());
        $this->rawdata = $rules;
        // Set initial bars.
        if ($useinitialsbar) {
            $this->initialbars($total > $pagesize);
        }
    }
89003
function &MetaTables($ttype = false, $showSchema = false, $mask = false)
  {
          $recordSet1 = $this->Execute("select * from system.tables");
                if(!$recordSet1){
                        print $this->ErrorMsg();
                        return false;
                }
                $recordSet2 = $this->Execute("select * from system.views");
                if(!$recordSet2){
                        print $this->ErrorMsg();
                        return false;
                }
                $i=0;
                while (!$recordSet1->EOF){
                                 $arr["$i"] = $recordSet1->fields[0];
                                 $recordSet1->MoveNext();
                                 $i=$i+1;
                }
                if($ttype=='FALSE'){
                        while (!$recordSet2->EOF){
                                $arr["$i"] = $recordSet2->fields[0];
                                $recordSet2->MoveNext();
                                $i=$i+1;
                        }
                        return $arr;
                }
                elseif($ttype=='VIEWS'){
                        while (!$recordSet2->EOF){
                                $arrV["$i"] = $recordSet2->fields[0];
                                $recordSet2->MoveNext();
                                $i=$i+1;
                        }
                        return $arrV;
                }
                else{
                        return $arr;
                }

  }
456013
public function map($results, array $eagerLoads = [], $useCache = false) : Collection
    {
        $builder = $this->newResultBuilder(!$useCache);

        if ($results instanceof Collection) {
            // Get underlying collection array
            $results = $results->all();
        }

        if (!is_array($results)) {
            throw new InvalidArgumentException("Parameter 'results' should be an array or a collection.");
        }

        // First, we'll cast every single result to array
        $results = array_map(function ($item) {
            return (array) $item;
        }, $results);

        // Then, we'll pass the results to the Driver's provided transformer, so
        // any DB specific value can be casted before hydration
        $results = $this->adapter->fromDatabase($results);

        $entities = $builder->build($results, $eagerLoads);

        return $this->entityMap->newCollection($entities);
    }
684234
public function render(OutputInterface $output, ResultCollection $results)
    {
        $output->write($this->getHeader());

        $table = new Table($output);
        $table->setHeaders(['File', 'Times Changed', 'Complexity', 'Score']);
        $table->addRows($results->toArray());
        $table->render();

        $output->write("\n");
    }
1213148
public function query_db($pagesize, $useinitialsbar = true) {
        global $DB;

        $joins = array();
        $params = array();

        // If we filter by userid and module id we also need to filter by crud and edulevel to ensure DB index is engaged.
        $useextendeddbindex = !($this->filterparams->logreader instanceof logstore_legacy\log\store)
                && !empty($this->filterparams->userid) && !empty($this->filterparams->modid);

        $groupid = 0;
        if (!empty($this->filterparams->courseid) && $this->filterparams->courseid != SITEID) {
            if (!empty($this->filterparams->groupid)) {
                $groupid = $this->filterparams->groupid;
            }

            $joins[] = "courseid = :courseid";
            $params['courseid'] = $this->filterparams->courseid;
        }

        if (!empty($this->filterparams->siteerrors)) {
            $joins[] = "( action='error' OR action='infected' OR action='failed' )";
        }

        if (!empty($this->filterparams->modid)) {
            list($actionsql, $actionparams) = $this->get_cm_sql();
            $joins[] = $actionsql;
            $params = array_merge($params, $actionparams);
        }

        if (!empty($this->filterparams->action) || $useextendeddbindex) {
            list($actionsql, $actionparams) = $this->get_action_sql();
            $joins[] = $actionsql;
            $params = array_merge($params, $actionparams);
        }

        // Getting all members of a group.
        if ($groupid and empty($this->filterparams->userid)) {
            if ($gusers = groups_get_members($groupid)) {
                $gusers = array_keys($gusers);
                $joins[] = 'userid IN (' . implode(',', $gusers) . ')';
            } else {
                $joins[] = 'userid = 0'; // No users in groups, so we want something that will always be false.
            }
        } else if (!empty($this->filterparams->userid)) {
            $joins[] = "userid = :userid";
            $params['userid'] = $this->filterparams->userid;
        }

        if (!empty($this->filterparams->date)) {
            $joins[] = "timecreated > :date AND timecreated < :enddate";
            $params['date'] = $this->filterparams->date;
            $params['enddate'] = $this->filterparams->date + DAYSECS; // Show logs only for the selected date.
        }

        if (isset($this->filterparams->edulevel) && ($this->filterparams->edulevel >= 0)) {
            $joins[] = "edulevel = :edulevel";
            $params['edulevel'] = $this->filterparams->edulevel;
        } else if ($useextendeddbindex) {
            list($edulevelsql, $edulevelparams) = $DB->get_in_or_equal(array(\core\event\base::LEVEL_OTHER,
                \core\event\base::LEVEL_PARTICIPATING, \core\event\base::LEVEL_TEACHING), SQL_PARAMS_NAMED, 'edulevel');
            $joins[] = "edulevel ".$edulevelsql;
            $params = array_merge($params, $edulevelparams);
        }

        // Origin.
        if (isset($this->filterparams->origin) && ($this->filterparams->origin != '')) {
            if ($this->filterparams->origin !== '---') {
                // Filter by a single origin.
                $joins[] = "origin = :origin";
                $params['origin'] = $this->filterparams->origin;
            } else {
                // Filter by everything else.
                list($originsql, $originparams) = $DB->get_in_or_equal(array('cli', 'restore', 'ws', 'web'),
                    SQL_PARAMS_NAMED, 'origin', false);
                $joins[] = "origin " . $originsql;
                $params = array_merge($params, $originparams);
            }
        }

        if (!($this->filterparams->logreader instanceof logstore_legacy\log\store)) {
            // Filter out anonymous actions, this is N/A for legacy log because it never stores them.
            $joins[] = "anonymous = 0";
        }

        $selector = implode(' AND ', $joins);

        if (!$this->is_downloading()) {
            $total = $this->filterparams->logreader->get_events_select_count($selector, $params);
            $this->pagesize($pagesize, $total);
        } else {
            $this->pageable(false);
        }

        // Get the users and course data.
        $this->rawdata = $this->filterparams->logreader->get_events_select_iterator($selector, $params,
            $this->filterparams->orderby, $this->get_page_start(), $this->get_page_size());

        // Update list of users which will be displayed on log page.
        $this->update_users_used();

        // Get the events. Same query than before; even if it is not likely, logs from new users
        // may be added since last query so we will need to work around later to prevent problems.
        // In almost most of the cases this will be better than having two opened recordsets.
        $this->rawdata = $this->filterparams->logreader->get_events_select_iterator($selector, $params,
            $this->filterparams->orderby, $this->get_page_start(), $this->get_page_size());

        // Set initial bars.
        if ($useinitialsbar && !$this->is_downloading()) {
            $this->initialbars($total > $pagesize);
        }

    }
1088994
public function statement($query, $bindings = array(), $rawResults = false)
    {
        return $this->run($query, $bindings, function(self $me, $query, array $bindings) use($rawResults)
        {
            if ($me->pretending()) return true;

            $statement = $me->getCypherQuery($query, $bindings);

            $result = $statement->getResultSet();

            return ($rawResults === true) ? $result : $result instanceof ResultSet;
        });
    }
478512
protected function renderPage($datasourceId, $template, array $baseQuery = [], $sortField = null, $sortOrder = Query::SORT_DESC, $limit = 10)
    {
        $datasource = $this->viewFactory->getDatasource($datasourceId);

        $inputDefinition = new InputDefinition($datasource, [
            'base_query'          => $baseQuery,
            'limit_default'       => $limit,
            'pager_enable'        => false,
            'search_enable'       => false,
            'sort_default_field'  => $sortField ? $sortField : '',
            'sort_default_order'  => $sortOrder,
        ]);
        $viewDefinition = new ViewDefinition([
            'enabled_filters'   => [],
            'properties'        => [],
            'show_filters'      => false,
            'show_pager'        => false,
            'show_search'       => false,
            'show_sort'         => false,
            'templates'         => ['default' => $template],
            'view_type'         => 'twig_page',
        ]);
        $query = $inputDefinition->createQueryFromArray([]);
        $items = $datasource->getItems($query);

        return $this->viewFactory->getView('twig_page')->render($viewDefinition, $items, $query);
    }