[8.x] Add toRawSql() method on the query builder#38027
[8.x] Add toRawSql() method on the query builder#38027therobfonz wants to merge 4 commits intolaravel:8.xfrom
toRawSql() method on the query builder#38027Conversation
| public function toRawSql() | ||
| { | ||
| return array_reduce($this->getBindings(), function ($sql, $binding) { | ||
| return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'", $sql, 1); |
There was a problem hiding this comment.
Also there are $this->grammar->quoteString() or $this->connection->quote() for quoting value.
There was a problem hiding this comment.
I'd suggest to add null check and return a 'null' sql string. It may be important in insert/update query.
Since insert/update statement return a boolean, it's actually not possible to run toSql() or toRawSql() on those statements. Was there a particular way you were writing the statement where you had this scenario that might not work? Ran a few tests and any where('field', null) was already converted by toSql() to "field" is null.
|
Your code is missing edge cases because of PostgreSQL. In PostgreSQL there are multiple operators consisting of a questionmark (e.g. the jsonb operators). These parameters can be used in queries but the question mark needs to be escaped by another question mark. So the operator |
|
Thanks for your pull request to Laravel! Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include. If possible, please consider releasing your code as a package so that the community can still take advantage of your contributions! If you feel absolutely certain that this code corrects a bug in the framework, please "@" mention me in a follow-up comment with further explanation so that GitHub will send me a notification of your response. |
|
@taylorotwell Thanks! I have been using this as a macro and you have given us the ability to do that so no problem with closing this. Appreciate the feedback! |

This feature came from the desire to debug queries by combining
toSql()andgetBindings()into a complete raw query string. This adds another helpful debugging method to the query builder and enables a user to easily copy a raw query directly into a database GUI without having to manually replace parameter bindings in thetoSql()output.Usage
The method takes into consideration if a parameter is a string or integer and will wrap a string in single quotes accordingly.