On 22/02/2012, at 10:32 AM, diafygi wrote:

> There's a previous thread about this[1], but it was closed back in
> 2006 without resolution. So I'd like to check back in and see if there
> is a way to get a complete query string without executing the query.
> 
> At first, I thought I could just use the QuerySet.query.__str__(), but
> that does not put quotes around dates, so MySQL returns a warning when
> trying to execute it. I filed a bug report[2], but apparently
> QuerySet.query.__str__() isn't supposed to return a valid query
> string.
> 
> So is there a way to get the compiled query string without executing
> the query (including when debug=False)?
> 


Technically, yes; practically, no.

The problem is that the SQL argument quoting isn't something that is under 
Django's control. The PyDB interface specifies (with good reason) that you pass 
SQL to the database using parameterized SQL, with a separate tuple of 
arguments. The PyDB backend then handles the process of escaping, quoting, or 
whatever else is required to combine the SQL and arguments to make sure that 
the final SQL is valid.

Unfortunately, what the PyDB interface *doesn't* provide is a way to extract 
the actual SQL that was (or will be) executed.

So - in order for Django to provide a 100% guaranteed correct output for 
Queryset.query.__str()__, we would need to re-implement the quoting and 
escaping feature of the PyDB backend -- and we'd need to do so for every 
backend (because quoting and escaping requirements are slightly different for 
every backend). This would be complex to implement, would be error prone, and 
would lead to even more confusing errors whenever the quoting/escaping failed 
to implement exactly what the PyDB backend implements.

The alternative -- which is what Django has opted to do -- is to provide SQL 
output that is indicative of what was (or would be) executed, and accept that 
sometimes that SQL won't run verbatim. Incorrect quoting is more than 
sufficient for eyeballing whether a query is correct; if you actually need to 
execute the SQL it's not *that* hard to manually correct the quoting.

Yes, it's annoying. Yes, in an ideal world, SQL output would be guaranteed 
valid. However, in this case, pragmatism takes precedence.

Yours,
Russ Magee %-)


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to