Formats the data for transmission	echo $sql;
12545
private function getQueryString()
    {
        foreach ($_SERVER as $key => $value) {
            if (!in_array($key, $this->ignore)) {
                if ($key == 'REMOTE_ADDR') {
                    $this->comment[$key] = $this->comment['user_ip'];
                } else {
                    $this->comment[$key] = $value;
                }
            }
        }

        $query_string = '';

        foreach ($this->comment as $key => $data) {
            @$query_string .= $key . '=' . urlencode(stripslashes($data)) . '&';
        }

        return $query_string;
    }
1221001
function formatSql(sqlText, options = {}) {
    let command = buildCommand(options);
    // Pass sqlText in as stdin and run pgFormatter
    let formatted = child_process_1.execSync(command, {
        encoding: "utf8",
        input: sqlText
    });
    return formatted;
}
786906
protected function formatData($data=null)
    {
        if (!is_null($data)) {
            if (is_scalar($data)) {
                $data = ['id' => $data];
            }
        } else {
            $data = (array) $data;
        }
        
        foreach ($data as $k => $v) {
            if ($v == "" || is_bool($v)) {
                $data[$k] = intval($v);
            } elseif (is_numeric($v)) {
                $data[$k] = (strpos($v, '.') !== false) ? floatval($v) : intval($v);
            }
        }
        
        $data && ksort($data);
        
        return $data;
    }
665165
private function tokenizeSQL($sql): array
    {
        $token = '\\(|\\)|\[|\]|[\']|"|\140|<>|<=|>=|:=|[*\/<>,+=-]';
        $terminal = $token.'|;| |\\n';
        $result = [];
        $string = $sql;
        $string = ltrim($string);
        $string = rtrim($string, ';').';'; // always ends with a terminal
        $string = preg_replace("/[\n\r]/s", ' ', $string);
        while (
            preg_match("/^($token)($terminal)/s", $string, $matches) ||
            preg_match("/^({$token})./s", $string, $matches) ||
            preg_match("/^(@?[a-zA-Z0-9_.]+?)($terminal)/s", $string, $matches)
        ) {
            $t = $matches[1];
            if ($t == '\'') {
                // it's a string
                $t = $this->tokSingleQuoteString($string);
                array_push($result, $t);
            }
            elseif ($t == "\140") {
                // it's a backtick string (a name)
                $t = $this->tokBackQuoteString($string);
                array_push($result, $t);
            }
            elseif ($t == '"') {
                // it's a double quoted string (a name in normal sql)
                $t = $this->tokDoubleQuoteString($string);
                array_push($result, $t);
            }
            else {
                array_push($result, $t);
            }
            $string = substr($string, strlen($t));
            $string = ltrim($string);
        }
        return $result;
    }
301453
private function formatValues()
    {
        array_walk($this->parameters, function (&$value, $key) {
            $parameterValue = $value;

            if (is_bool($parameterValue)) {
                $parameterValue = var_export($parameterValue, true);
            }

            $formattedValue = sprintf(self::DEFAULT_PAIR_FORMAT, $key, $parameterValue);

            if (isset($this->pairFormats[$key])) {
                $formattedValue = sprintf($this->pairFormats[$key], $key, $parameterValue);
            }

            $value = $formattedValue;
        });
    }
676435
public function toSql()
    {
        if ($this->isEmpty()) {
            return '';
        }

        $params = $this->getParams();

        $sql = array('SET');
        $set = array();

        foreach ($params as $column => $value) {
            $set[] = implode(' = ', array(
                $column, $this->getBuilder()->getHelper()->toDbValue($value)
            ));
        }

        $sql[] = implode(', ', $set);

        return implode(' ', $sql);
    }
415860
public function formatQuery($sql, $highlightOnly = false)
    {
        SqlFormatter::$pre_attributes            = 'class="highlight highlight-sql"';
        SqlFormatter::$quote_attributes          = 'class="string"';
        SqlFormatter::$backtick_quote_attributes = 'class="string"';
        SqlFormatter::$reserved_attributes       = 'class="keyword"';
        SqlFormatter::$boundary_attributes       = 'class="symbol"';
        SqlFormatter::$number_attributes         = 'class="number"';
        SqlFormatter::$word_attributes           = 'class="word"';
        SqlFormatter::$error_attributes          = 'class="error"';
        SqlFormatter::$comment_attributes        = 'class="comment"';
        SqlFormatter::$variable_attributes       = 'class="variable"';

        if ($highlightOnly) {
            $html = SqlFormatter::highlight($sql);
            $html = preg_replace('/<pre class=".*">([^"]*+)<\/pre>/Us', '\1', $html);
        } else {
            $html = SqlFormatter::format($sql);
            $html = preg_replace('/<pre class="(.*)">([^"]*+)<\/pre>/Us', '<div class="\1"><pre>\2</pre></div>', $html);
        }

        return $html;
    }
257460
public function charsetEncodeDbToOutput()
    {
        if ($this->db_charset && $this->output_charset) {
            if ($this->db_charset != $this->output_charset) {
                foreach ($this->columns as $col) {
                    $col->column_value = iconv($this->db_charset, $this->output_charset, $col->column_value);
                }
            }
        }

    }
65409
public function encoding() {
		$db = $this->_getConnection();
		$config = $db->config();
		$database = $config['database'];
		$prefix = ''; //$config['prefix'];
		$encoding = 'utf8mb4';
		$collate = 'utf8mb4_unicode_ci';

		try {
			$script = "ALTER DATABASE $database CHARACTER SET $encoding COLLATE $collate;";
			if (!$this->params['dry-run']) {
				$db->query($script);
			} else {
				$this->out($script);
			}
		} catch (Exception $e) {
			$this->err('Could not alter database: ' . $e->getMessage() . ' - Skipping.');
		}

		$script = <<<SQL
SELECT  CONCAT('ALTER TABLE `', table_name, '` CONVERT TO CHARACTER SET $encoding COLLATE $collate;') AS statement
FROM    information_schema.tables AS tb
WHERE   table_schema = '$database'
AND     table_name LIKE '$prefix%'
AND     `TABLE_TYPE` = 'BASE TABLE';
SQL;
		/** @var \Cake\Database\Statement\StatementDecorator $res */
		$res = $db->query($script);
		if (!$res) {
			$this->abort('Nothing to do...');
		}

		$script = [];
		foreach ($res as $r) {
			$script[] = $r['statement'];
		}

		if (!$this->param('dry-run')) {
			$continue = $this->in(count($res) . ' tables will be altered.', ['Y', 'N'], 'N');
			if (strtoupper($continue) !== 'Y') {
				$this->abort('Aborted!');
			}
		}

		foreach ($script as $row) {
			preg_match('/`(.+)`/', $row, $matches);
			$table = $matches[1];
			$sql = "ALTER TABLE `$table` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;";

			if ($this->params['interactive']) {
				$in = $this->in('Fix table ' . $table . '?', ['y', 'n'], 'y');
				if ($in !== 'y') {
					$this->out(' - skipping ' . $table);
					continue;
				}
			}

			if (!$this->params['dry-run']) {
				$this->out(' - fixing table ' . $table, 1, Shell::VERBOSE);
				$db->query($row);
				$db->query($sql);
			} else {
				$this->out($row);
				$this->out($sql);
			}
		}
		$this->out('Done :)');
	}
1249186
protected function format($data, $file_handle)
    {
        $header = false;
        foreach ($data as $idx => $row)
        {
            $row = WF::cast_array($row);
            $this->validateRow($row);

            if ($this->write_bom && ftell($file_handle) === 0)
                fwrite($file_handle, Encoding::getBOM('UTF8'));

            if (!$header && $this->write_header)
            {
                $keys = array_keys($row);
                fputcsv($file_handle, $keys, $this->delimiter, $this->enclosure, $this->escape_char);
                $header = true;
            }
            fputcsv($file_handle, $row, $this->delimiter, $this->enclosure, $this->escape_char);
        }
    }
659996
function Execute($sql,$inputarr=false)
	{
		if ($this->fnExecute) {
			$fn = $this->fnExecute;
			$ret = $fn($this,$sql,$inputarr);
			if (isset($ret)) {
				return $ret;
			}
		}
		if ($inputarr !== false) {
			if (!is_array($inputarr)) {
				$inputarr = array($inputarr);
			}

			$element0 = reset($inputarr);
			$array2d =  $this->bulkBind && is_array($element0) && !is_object(reset($element0));

			# see http://phplens.com/lens/lensforum/msgs.php?id=18786
			if ($array2d || !$this->_bindInputArray) {

				# is_object check because oci8 descriptors can be passed in
				if ($array2d && $this->_bindInputArray) {
					if (is_string($sql)) {
						$stmt = $this->Prepare($sql);
					} else {
						$stmt = $sql;
					}

					foreach($inputarr as $arr) {
						$ret = $this->_Execute($stmt,$arr);
						if (!$ret) {
							return $ret;
						}
					}
					return $ret;
				} else {
					$sqlarr = explode(':', $sql);
					$sql = '';
					$lastnomatch = -2;
					#var_dump($sqlarr);echo "<hr>";var_dump($inputarr);echo"<hr>";
					foreach($sqlarr as $k => $str) {
						if ($k == 0) {
							$sql = $str;
							continue;
						}
						// we need $lastnomatch because of the following datetime,
						// eg. '10:10:01', which causes code to think that there is bind param :10 and :1
						$ok = preg_match('/^([0-9]*)/', $str, $arr);

						if (!$ok) {
							$sql .= $str;
						} else {
							$at = $arr[1];
							if (isset($inputarr[$at]) || is_null($inputarr[$at])) {
								if ((strlen($at) == strlen($str) && $k < sizeof($arr)-1)) {
									$sql .= ':'.$str;
									$lastnomatch = $k;
								} else if ($lastnomatch == $k-1) {
									$sql .= ':'.$str;
								} else {
									if (is_null($inputarr[$at])) {
										$sql .= 'null';
									}
									else {
										$sql .= $this->qstr($inputarr[$at]);
									}
									$sql .= substr($str, strlen($at));
								}
							} else {
								$sql .= ':'.$str;
							}
						}
					}
					$inputarr = false;
				}
			}
			$ret = $this->_Execute($sql,$inputarr);

		} else {
			$ret = $this->_Execute($sql,false);
		}

		return $ret;
	}
478951
public function formatSql($sql, $tabOffset = 3)
    {
        $tab = Formatter::$tab;
        $indent = '';

        for ($i = 0; $i < $tabOffset; ++$i) {
            $indent .= $tab;
        }

        $sql = explode("\n", Formatter::format($sql, false));
        $indentedLines = array();

        foreach ($sql as $line) {
            $indentedLines[] = $indent.str_replace('"', '\"', $line);
        }

        return implode("\n", $indentedLines);
    }
734693
private function _format($data) {
        $output_callback_function = '';
        
        // If data is in array format then set content-type
        // to application/json
        if (is_array($data) || is_object($data)) {
            $this->header('Content-type: application/json');
            // Convert to json
            $output_callback_function = json_encode($data);
        } else {
            // Default
            $output_callback_function = $data;
        }
        
        $output = $output_callback_function;
        
        // GZIP output compression
        if ($this->_compress) {
            // Set Content coding a gzip
            $this->header('Content-Encoding: gzip');
            
            // Set headers for gzip
            $output = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
            $output .= gzcompress($output_callback_function);
        }
        
        return $output;
    }
454336
public function export()
    {
        $rows = [];
        foreach ($this->messages as $message) {
            list($text, $level, $category, $timestamp) = $message;
            if (!is_string($text)) {
                // exceptions may not be serializable if in the call stack somewhere is a Closure
                if ($text instanceof \Throwable || $text instanceof \Exception) {
                    $text = (string) $text;
                } else {
                    $text = VarDumper::export($text);
                }
            }
            $rows[] = [
                'level' => $level,
                'category' => $category,
                'log_time' => $timestamp,
                'prefix' => $this->getMessagePrefix($message),
                'message' => $text,
            ];
        }

        $this->db->getCollection($this->logCollection)->batchInsert($rows);
    }
1325317
protected function interpolateQuery()
    {
        $sql = $this->STH->queryString;
        // handle insert batch data
        if (!$this->batch) {
            $params = ((is_array($this->data)) && (count($this->data) > 0)) ? $this->data : $this->sql;
            if (is_array($params)) {
                // build a regular expression for each parameter
                $keys = [];
                foreach ($params as $key => $value) {
                    if (strstr($key, ' ')) {
                        $real_key = $this->getFieldFromArrayKey($key);
                        // update param value with quotes, if string value
                        $params[$key] = is_string($value) ? '"' . $value . '"' : $value;
                        // make replace array
                        $keys[] = is_string($real_key) ? '/:s_' . $real_key . '/' : '/[?]/';
                    } else {
                        // update param value with quotes, if string value
                        $params[$key] = is_string($value) ? '"' . $value . '"' : $value;
                        // make replace array
                        $keys[] = is_string($key) ? '/:s_' . $key . '/' : '/[?]/';
                    }
                }
                $sql = preg_replace($keys, $params, $sql, 1, $count);

                if (strstr($sql, ':s_')) {
                    foreach ($this->arrayWhere as $key => $value) {
                        if (strstr($key, ' ')) {
                            $real_key = $this->getFieldFromArrayKey($key);
                            // update param value with quotes, if string value
                            $params[$key] = is_string($value) ? '"' . $value . '"' : $value;
                            // make replace array
                            $keys[] = is_string($real_key) ? '/:s_' . $real_key . '/' : '/[?]/';
                        } else {
                            // update param value with quotes, if string value
                            $params[$key] = is_string($value) ? '"' . $value . '"' : $value;
                            // make replace array
                            $keys[] = is_string($key) ? '/:s_' . $key . '/' : '/[?]/';
                        }
                    }
                    $sql = preg_replace($keys, $params, $sql, 1, $count);
                }

                return $sql;
                // trigger_error('replaced '.$count.' keys');
            }

            return $params;
        } else {
            $params_batch = ((is_array($this->data)) && (count($this->data) > 0)) ? $this->data : $this->sql;
            $batch_query = '';

            if (is_array($params_batch)) {
                // build a regular expression for each parameter
                $array_keys = [];
                foreach ($params_batch as $keys => $params) {
                    echo $params;
                    foreach ($params as $key => $value) {
                        if (strstr($key, ' ')) {
                            $real_key = $this->getFieldFromArrayKey($key);
                            // update param value with quotes, if string value
                            $params[$key] = is_string($value) ? '"' . $value . '"' : $value;
                            // make replace array
                            $array_keys[] = is_string($real_key) ? '/:s_' . $real_key . '/' : '/[?]/';
                        } else {
                            // update param value with quotes, if string value
                            $params[$key] = is_string($value) ? '"' . $value . '"' : $value;
                            // make replace array
                            $array_keys[] = is_string($key) ? '/:s_' . $key . '/' : '/[?]/';
                        }
                    }
                    $batch_query .= '<br />' . preg_replace($array_keys, $params, $sql, 1, $count);
                }

                return $batch_query;
                // trigger_error('replaced '.$count.' keys');
            }

            return $params_batch;
        }
    }
1039303
public function load($sql)
    {
        $query = '';
        $delimiter = '//';
        $delimiterLength = 2;

        foreach ($sql as $sqlLine) {
            if (preg_match('/DELIMITER ([\;\$\|\\\\]+)/i', $sqlLine, $match)) {
                $delimiter = $match[1];
                $delimiterLength = strlen($delimiter);
                continue;
            }

            $parsed = $this->sqlLine($sqlLine);
            if ($parsed) {
                continue;
            }

            $query .= "\n" . rtrim($sqlLine);

            if (substr($query, -1 * $delimiterLength, $delimiterLength) == $delimiter) {
                $this->sqlQuery(substr($query, 0, -1 * $delimiterLength));
                $query = "";
            }
        }

        if ($query !== '') {
            $this->sqlQuery($query);
        }
    }
1001889
public function import($sql)
    {
        $queries   = [];
        $query     = [];
        $delimiter = '';
        
        foreach (explode("\n", $sql) as $line) {
            if ($delimiter) {
                if ($line == $delimiter) {
                    $queries[] = implode("\n", $query);
                    $query = [];
                } else {
                    $query[] = $line;
                }
            } elseif (preg_match('/^\s*DELIMITER ([^\;].*?)$/m', $line, $m)) {
                $queries[] = implode("\n", $query);
                $query = [];
                $delimiter = $m[1];
            } elseif ($line == 'DELIMITER ;') {
                $delimiter = '';
            } else {
                $query[] = $line;
                
                if (substr($line, -1) == ';') {
                    $queries[] = implode("\n", $query);
                    $query = [];
                }
            }
        }
        
        foreach ($queries as $query) {
            # There may be empty lines added as queries, it is safe to skip them.
            if ($query) {
                $this->connection->executeSql($query);
            }
        }
    }