Writes debug information/query to 'sql' log file

@param string $query SQL query
481706
protected function debug($query)
    {
        if ($this->options['debug_mode']) {
            if (($len = strlen($query)) > self::DEBUG_LINE_LENGTH) {
                $diff  = $len - self::DEBUG_LINE_LENGTH;
                $query = substr($query, 0, self::DEBUG_LINE_LENGTH)
                    . "... [truncated $diff bytes]";
            }
            rcube::write_log('sql', '[' . (++$this->db_index) . '] ' . $query . ';');
        }
    }
479962
public function logQuery($query, $bindings, $time = null)
    {
        if (isset($this->events)) {
            $this->events->dispatch('nova.query', array($query, $bindings, $time, $this->getName()));
        }

        if (! $this->loggingQueries) return;

        $this->queryLog[] = compact('query', 'bindings', 'time');
    }
597523
protected function performQueryAnalysis($query)
    {
        $hints = [];
        if (preg_match('/^\\s*SELECT\\s*`?[a-zA-Z0-9]*`?\\.?\\*/i', $query)) {
            $hints[] = 'Use <code>SELECT *</code> only if you need all columns from table';
        }
        if (preg_match('/ORDER BY RAND()/i', $query)) {
            $hints[] = '<code>ORDER BY RAND()</code> is slow, try to avoid if you can.
				You can <a href="http://stackoverflow.com/questions/2663710/how-does-mysqls-order-by-rand-work" target="_blank">read this</a>
				or <a href="http://stackoverflow.com/questions/1244555/how-can-i-optimize-mysqls-order-by-rand-function" target="_blank">this</a>';
        }
        if (strpos($query, '!=') !== false) {
            $hints[] = 'The <code>!=</code> operator is not standard. Use the <code>&lt;&gt;</code> operator to test for inequality instead.';
        }
        if (stripos($query, 'WHERE') === false && preg_match('/^(SELECT) /i', $query)) {
            $hints[] = 'The <code>SELECT</code> statement has no <code>WHERE</code> clause and could examine many more rows than intended';
        }
        if (preg_match('/LIMIT\\s/i', $query) && stripos($query, 'ORDER BY') === false) {
            $hints[] = '<code>LIMIT</code> without <code>ORDER BY</code> causes non-deterministic results, depending on the query execution plan';
        }
        if (preg_match('/LIKE\\s[\'"](%.*?)[\'"]/i', $query, $matches)) {
            $hints[] = 	'An argument has a leading wildcard character: <code>' . $matches[1]. '</code>.
								The predicate with this argument is not sargable and cannot use an index if one exists.';
        }
        return $hints;
    }
27239
public function logAction($query) {
        $interval = Configure::read('Admin.logActions.interval') ?: '-6 hours';

        $conditions = $query;
        $conditions['created >='] = date('Y-m-d H:i:s', strtotime($interval));

        $count = $this->find('count', array(
            'conditions' => $conditions
        ));

        if ($count) {
            return true;
        }

        $this->create();

        return $this->save($query, false);
    }
843564
protected function logQuery()
    {
        $info = $this->info();

        if (!$info['started_iterating']) {
            if (!is_array($info['query'])) {
                $info['query'] = array();
            } else if (!isset($info['query']['$query'])) {
                $info['query'] = array('$query' => $info['query']);
            }

            // explain cursor
            $this->explainCursor->fields($info['fields']);
            $this->explainCursor->limit($info['limit']);
            $this->explainCursor->skip($info['skip']);
            if (isset($info['batchSize'])) {
                $this->explainCursor->batchSize($info['batchSize']);
            }
            if (isset($info['query']['$orderby'])) {
                $this->explainCursor->sort($info['query']['$orderby']);
            }
            if (isset($info['query']['$hint'])) {
                $this->explainCursor->hint($info['query']['$hint']);
            }
            if (isset($info['query']['$snapshot'])) {
                $this->explainCursor->snapshot();
            }
            $explain = $this->explainCursor->explain();

            // log
            $log = array(
                'type'   => $this->type,
                'query'  => isset($info['query']['$query']) && is_array($info['query']['$query']) ? $info['query']['$query'] : array(),
                'fields' => $info['fields'],
            );
            if (isset($info['query']['$orderby'])) {
                $log['sort'] = $info['query']['$orderby'];
            }
            if ($info['limit']) {
                $log['limit'] = $info['limit'];
            }
            if ($info['skip']) {
                $log['skip'] = $info['skip'];
            }
            if ($info['batchSize']) {
                $log['batchSize'] = $info['batchSize'];
            }
            if (isset($info['query']['$hint'])) {
                $log['hint'] = $info['query']['$hint'];
            }
            if (isset($info['query']['$snapshot'])) {
                $log['snapshot'] = 1;
            }
            $log['explain'] = array(
                'nscanned'        => $explain['nscanned'],
                'nscannedObjects' => $explain['nscannedObjects'],
                'n'               => $explain['n'],
                'indexBounds'     => $explain['indexBounds'],
            );
            $log['time'] = $explain['millis'];

            $this->log($log);
        }
    }
649292
public function execute( $query, $debug = 1 )
	{
		if( !$this->dbc )
			$this->openConnection();
		return parent::execute( $query, $debug );
	}
729162
public function query_log($error=false) {
        // Logging disabled by the driver.
        if ($this->skiplogging) {
            return;
        }

        $logall    = !empty($this->dboptions['logall']);
        $logslow   = !empty($this->dboptions['logslow']) ? $this->dboptions['logslow'] : false;
        $logerrors = !empty($this->dboptions['logerrors']);
        $iserror   = ($error !== false);

        $time = $this->query_time();

        // Will be shown or not depending on MDL_PERF values rather than in dboptions['log*].
        $this->queriestime = $this->queriestime + $time;

        if ($logall or ($logslow and ($logslow < ($time+0.00001))) or ($iserror and $logerrors)) {
            $this->loggingquery = true;
            try {
                $backtrace = debug_backtrace();
                if ($backtrace) {
                    //remove query_log()
                    array_shift($backtrace);
                }
                if ($backtrace) {
                    //remove query_end()
                    array_shift($backtrace);
                }
                $log = new stdClass();
                $log->qtype      = $this->last_type;
                $log->sqltext    = $this->last_sql;
                $log->sqlparams  = var_export((array)$this->last_params, true);
                $log->error      = (int)$iserror;
                $log->info       = $iserror ? $error : null;
                $log->backtrace  = format_backtrace($backtrace, true);
                $log->exectime   = $time;
                $log->timelogged = time();
                $this->insert_record('log_queries', $log);
            } catch (Exception $ignored) {
            }
            $this->loggingquery = false;
        }
    }
22342
public function execute( $query, $debug = 1 )
	{
		if( !$this->dbc )
			throw new RuntimeException( 'Database not conntected' );

		$result = FALSE;
		if( $query )
		{
			if( $debug > 0 )
			{
				$bits = $this->getBits( $debug, 5 );
				if( $bits[0] )
				{
					$this->countQueries++;
					$start = $this->getMicroTime();
				}
				if( $bits[1] )
					echo $query;
				if( $bits[2] )
					remark( $query );
				if( $bits[3] )
					die();
			}
			if( preg_match( '/^INSERT/i', ltrim( $query ) ) )
			{
				if( mysql_query( $query, $this->dbc ) )
				{
					$this->insertId = (int) mysql_insert_Id( $this->dbc );
					$result	= $this->insertId;
				}
			}
			else if( preg_match( '/^(SELECT|SHOW)/i', ltrim( $query ) ) )
			{
				$result = new DB_Result();
				if( $q = mysql_query( $query, $this->dbc ) )
				{
					while( $d = mysql_fetch_array( $q ) )
					{
						$row = new DB_Row();
						foreach( $d as $key => $value )
							$row->$key = $value;
						$result->rows[] = $row;
					}
				}
			}
			else
			{
				$result = mysql_query( $query, $this->dbc );
			}
			if( mysql_errno() )
				$this->handleError( mysql_errno(), mysql_error(), $query );
			if( $debug > 0 )
			{
				if( $bits[0] )
					$this->countTime += $this->getTimeDifference( $start );
				if( $bits[4] )
					die();
			}
			return $result;
		}
	}
561713
protected function log(string $query, array $params, float $start): void
	{
		$time = microtime(true) - $start;

		$query = $this->prepareQueryForLog($query, $params);

		$this->log[] = ['query' => $query, 'time' => $time];
	}
232047
public function processReportQueryFilter(& $query) {
		$where = [];
		foreach ($this->fields as $k => $v) {
			// filter by value
			if (!empty($v['options']['query_builder']) && isset($this->values[$k])) {
				if (is_array($this->values[$k]) && empty($this->values[$k])) continue;
				$where[$v['options']['query_builder']] = $this->values[$k];
			}
			// subquery - fetch data
			if (!empty($v['options']['subquery'])) {
				$on = [];
				foreach ($v['options']['subquery']['on'] as $v2) {
					$v2[3] = true;
					$on[] = ['AND', $v2, false];
				}
				$query->join('LEFT', function (& $query) use ($v) {
					$model = new $v['options']['subquery']['model']();
					$query = $model->queryBuilder(['skip_acl' => true, 'alias' => $v['options']['subquery']['alias'] . '_inner'])->select();
					$columns = [];
					if (is_array($v['options']['subquery']['groupby'])) {
						$columns = $v['options']['subquery']['groupby'];
					} else {
						$columns[] = $v['options']['subquery']['groupby'];
					}
					$columns[$v['name']] = $query->db_object->sqlHelper('string_agg', ['expression' => $query->db_object->cast($v['name'], 'varchar'), 'delimiter' => ';;']);
					$query->columns($columns);
					$query->groupby(is_array($v['options']['subquery']['groupby']) ? $v['options']['subquery']['groupby'] : [$v['options']['subquery']['groupby']]);
				}, $v['options']['subquery']['alias'], 'ON', $on);
				// special constants to fix
				$this->misc_settings['list']['subquery'][$v['name']] = ['delimiter' => ';;'];
			}
			// subquery - filter
			if (!empty($v['options']['subquery_builder'])) {
				if (is_array($this->values[$k]) && empty($this->values[$k])) continue;
				$on = [];
				foreach ($v['options']['subquery_builder']['on'] as $v2) {
					$v2[3] = true;
					$on[] = $v2;
				}
				$values = $this->values[$k];
				$query->where('AND', function (& $query) use ($values, $on, $v) {
					$model = new $v['options']['subquery_builder']['model']();
					$query = $model->queryBuilder(['alias' => $v['options']['subquery_builder']['alias']])->select();
					$query->columns(1);
					foreach ($on as $v2) {
						$query->where('AND', $v2);
					}
					$query->where('AND', [$v['options']['subquery_builder']['column'], '=', $values, false]);
				}, 'EXISTS');
			}
		}
		if (isset($this->values['full_text_search'])) {
			$where['full_text_search;FTS'] = [
				'fields' => $this->fields['full_text_search']['options']['full_text_search_columns'],
				'str' => $this->values['full_text_search']
			];
		}
		if (!empty($where)) {
			$query->whereMultiple('AND', $where);
		}
	}
1150810
public function save(SqlQuery $query)
    {
        $this->createDirectoryIfNotExists($query->number());

        $line = $this->formatter->getLine($query);

        if ($this->shouldLogQuery($query)) {
            $this->saveLine($line, $this->fileName->getForAllQueries(), $this->shouldOverrideFile($query));
        }

        if ($this->shouldLogSlowQuery($query)) {
            $this->saveLine($line, $this->fileName->getForSlowQueries());
        }
    }
80251
public static function QueryAsync(string $query)
        {
            if (!$query) {
                return false;
            }

            self::$queriesCnt++;
            $res = pg_send_query(self::GetConnection(), $query);

            if (!$res) {
                $backtrace = debug_backtrace();

                Log::Write('db',
                           "Error occurred while performing PostgreSQL asynchronous query." .
                           "\n\tError: " . pg_last_error(self::GetConnection()) .
                           "\n\tCalled in {$backtrace[1]['file']} at line {$backtrace[1]['line']}",
                           'PostgreSQL',
                           Log::LEVEL_CRITICAL);
            }

            return $res;
        }
459998
protected function executeDatabaseQuery($query)
    {
        $database = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        $database->execute($query);
    }
116044
public static function exec($query)
    {
        $ret = false;

        $res = self::query($query);

        if ($res) {
            $ret = self::connection()->sql_affected_rows();
            self::free($res);
        }

        return $ret;
    }
1356617
public static function db($query)
    {
        if (is_null($query->params)) {
            $query->params = [];
        }
        $text = $query->createCommand()->sql;
        $values = array_values($query->params);
        array_walk($values, function (&$value) { $value = Yii::$app->db->quoteValue($value); });
        $text = str_replace(array_keys($query->params), $values, $text);
        echo '<pre>';
        echo $text;
        echo '</pre>';
    }
384015
public static function execInsert($query)
    {
        $ret = false;

        $res = self::query($query);

        if ($res) {
            $ret = self::connection()->sql_insert_id();
            self::free($res);
        }

        return $ret;
    }
609377
protected function print_debug($sql, array $params=null, $obj=null) {
        if (!$this->get_debug()) {
            return;
        }
        if (CLI_SCRIPT) {
            $separator = "--------------------------------\n";
            echo $separator;
            echo "{$sql}\n";
            if (!is_null($params)) {
                echo "[" . var_export($params, true) . "]\n";
            }
            echo $separator;
        } else if (AJAX_SCRIPT) {
            $separator = "--------------------------------";
            error_log($separator);
            error_log($sql);
            if (!is_null($params)) {
                error_log("[" . var_export($params, true) . "]");
            }
            error_log($separator);
        } else {
            $separator = "<hr />\n";
            echo $separator;
            echo s($sql) . "\n";
            if (!is_null($params)) {
                echo "[" . s(var_export($params, true)) . "]\n";
            }
            echo $separator;
        }
    }