Basing on question's comments (thanks @Scuzzy for inspiration) I wrote some simple piece of code to convert SelectQuery
object:
class ExportableSelectQuery {
public static function toSql(SelectQuery $obj) {
$_string = $obj->__toString();
$_conditions = $obj->conditions();
$_tables = $obj->getTables();
$_fields = $obj->getFields();
foreach($_tables as $k => $t) {
if(!empty($t['alias'])) {
$_string = str_replace('{' . $t['table'] . '}', $t['table'] . ' as', $_string);
}
else {
$_string = str_replace('{' . $t['table'] . '}', $t['table'], $_string);
}
}
foreach($_conditions as $k => $c) {
if(is_int($c['value'])) {
$_string = str_replace(':db_condition_placeholder_' . $k, $c['value'], $_string);
}
else {
$_string = str_replace(':db_condition_placeholder_' . $k, "'" . $c['value'] . "'", $_string);
}
}
return $_string;
}
}
Usage of this code is now simple (if you only have SelectQuery
object somewhere):
die(ExportableSelectQuery::toSql($query));
I was thinking about extending original SelectQuery
object, and provide method to get SQL code, but Drupal's db_select
function returns SelectQuery
, so I will have to either change db_select
function or cast returned object to ExportableSelectQuery
.
Also this is not probably best solution I could write, but assuming limit of time and purpose it solved my problem just fine.