Created
August 18, 2017 22:51
-
-
Save morozov/bafa508cac064997de8e62547fb0c3cc to your computer and use it in GitHub Desktop.
Prepared Statements Debugging Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function format_sugar_query(SugarQuery $query) | |
{ | |
return format_builder( | |
$query->compile() | |
); | |
} | |
function format_builder(\Doctrine\DBAL\Query\QueryBuilder $builder) | |
{ | |
return format_stmt( | |
$builder->getSQL(), | |
$builder->getParameters() | |
); | |
} | |
function format_stmt($sql, array $params) | |
{ | |
$chunks = array(); | |
$currentQuote = false; | |
for ($start = $i = 0, $length = strlen($sql); $i < $length; $i++) { | |
if (!$currentQuote && ($sql[$i] == "'" || $sql[$i] == '"')) { | |
$currentQuote = $sql[$i]; | |
} elseif ($currentQuote && $sql[$i] == $currentQuote && $sql[$i - 1] != '\\') { | |
$currentQuote = false; | |
} elseif (!$currentQuote && $sql[$i] == '?') { | |
$chunks[] = substr($sql, $start, $i - $start); | |
$start = ++$i; | |
} | |
} | |
if ($currentQuote) { | |
return 'The statement contains non-terminated string literal'; | |
} | |
$count = count($chunks); | |
if (count($params) != $count) { | |
return sprintf( | |
'The statement expects %d parameters, %d given', | |
$count, | |
count($params) | |
); | |
} | |
$chunks[] = substr($sql, $start); | |
foreach (array_values($params) as $i => $param) { | |
if (is_string($param)) { | |
$sql = sprintf("'%s'", addslashes($param)); | |
} elseif (is_bool($param)) { | |
$sql = (int) $param; | |
} elseif ($param === null) { | |
$sql = 'NULL'; | |
} else { | |
$sql = $param; | |
} | |
array_splice($chunks, $i * 2 + 1, 0, $sql); | |
} | |
return implode('', $chunks); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment