sql.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. .. _topics-db-sql:
  2. ==========================
  3. Performing raw SQL queries
  4. ==========================
  5. .. currentmodule:: django.db.models
  6. When the :ref:`model query APIs <topics-db-queries>` don't go far enough, you
  7. can fall back to writing raw SQL. Django gives you two ways of performing raw
  8. SQL queries: you can use :meth:`Manager.raw()` to `perform raw queries and
  9. return model instances`__, or you can avoid the model layer entirely and
  10. `execute custom SQL directly`__.
  11. __ `performing raw queries`_
  12. __ `executing custom SQL directly`_
  13. Performing raw queries
  14. ======================
  15. .. versionadded:: 1.2
  16. The ``raw()`` manager method can be used to perform raw SQL queries that
  17. return model instances:
  18. .. method:: Manager.raw(raw_query, params=None, translations=None)
  19. This method method takes a raw SQL query, executes it, and returns a
  20. :class:`~django.db.models.query.RawQuerySet` instance. This
  21. :class:`~django.db.models.query.RawQuerySet` instance can be iterated
  22. over just like an normal QuerySet to provide object instances.
  23. This is best illustrated with an example. Suppose you've got the following model::
  24. class Person(models.Model):
  25. first_name = models.CharField(...)
  26. last_name = models.CharField(...)
  27. birth_date = models.DateField(...)
  28. You could then execute custom SQL like so::
  29. >>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
  30. ... print p
  31. John Smith
  32. Jane Jones
  33. .. admonition:: Model table names
  34. Where'd the name of the ``Person`` table come from in that example?
  35. By default, Django figures out a database table name by joining the
  36. model's "app label" -- the name you used in ``manage.py startapp`` -- to
  37. the model's class name, with an underscore between them. In the example
  38. we've assumed that the ``Person`` model lives in an app named ``myapp``,
  39. so its table would be ``myapp_person``.
  40. For more details check out the documentation for the
  41. :attr:`~Options.db_table` option, which also lets you manually set the
  42. database table name.
  43. Of course, this example isn't very exciting -- it's exactly the same as
  44. running ``Person.objects.all()``. However, ``raw()`` has a bunch of other
  45. options that make it very powerful.
  46. Mapping query fields to model fields
  47. ------------------------------------
  48. ``raw()`` automatically maps fields in the query to fields on the model.
  49. The order of fields in your query doesn't matter. In other words, both
  50. of the following queries work identically::
  51. >>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
  52. ...
  53. >>> Person.objects.raw('SELECT last_name, birth_date, first_name, id FROM myapp_person')
  54. ...
  55. Matching is done by name. This means that you can use SQL's ``AS`` clauses to
  56. map fields in the query to model fields. So if you had some other table that
  57. had ``Person`` data in it, you could easily map it into ``Person`` instances::
  58. >>> Person.objects.raw('''SELECT first AS first_name,
  59. ... last AS last_name,
  60. ... bd AS birth_date,
  61. ... pk as id,
  62. ... FROM some_other_table)
  63. As long as the names match, the model instances will be created correctly.
  64. Alternatively, you can map fields in the query to model fields using the
  65. ``translations`` argument to ``raw()``. This is a dictionary mapping names of
  66. fields in the query to names of fields on the model. For example, the above
  67. query could also be written::
  68. >>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
  69. >>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
  70. Index lookups
  71. -------------
  72. ``raw()`` supports indexing, so if you need only the first result you can
  73. write::
  74. >>> first_person = Person.objects.raw('SELECT * from myapp_person')[0]
  75. However, the indexing and slicing are not performed at the database level. If
  76. you have a big amount of ``Person`` objects in your database, it is more
  77. efficient to limit the query at the SQL level::
  78. >>> first_person = Person.objects.raw('SELECT * from myapp_person LIMIT 1')[0]
  79. Deferring model fields
  80. ----------------------
  81. Fields may also be left out::
  82. >>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
  83. The ``Person`` objects returned by this query will be deferred model instances
  84. (see :meth:`~django.db.models.QuerySet.defer()`). This means that the fields
  85. that are omitted from the query will be loaded on demand. For example::
  86. >>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
  87. ... print p.first_name, # This will be retrieved by the original query
  88. ... print p.last_name # This will be retrieved on demand
  89. ...
  90. John Smith
  91. Jane Jones
  92. From outward appearances, this looks like the query has retrieved both
  93. the first name and last name. However, this example actually issued 3
  94. queries. Only the first names were retrieved by the raw() query -- the
  95. last names were both retrieved on demand when they were printed.
  96. There is only one field that you can't leave out - the primary key
  97. field. Django uses the primary key to identify model instances, so it
  98. must always be included in a raw query. An ``InvalidQuery`` exception
  99. will be raised if you forget to include the primary key.
  100. Adding annotations
  101. ------------------
  102. You can also execute queries containing fields that aren't defined on the
  103. model. For example, we could use `PostgreSQL's age() function`__ to get a list
  104. of people with their ages calculated by the database::
  105. >>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
  106. >>> for p in people:
  107. ... print "%s is %s." % (p.first_name, p.age)
  108. John is 37.
  109. Jane is 42.
  110. ...
  111. __ http://www.postgresql.org/docs/8.4/static/functions-datetime.html
  112. Passing parameters into ``raw()``
  113. ---------------------------------
  114. If you need to perform parameterized queries, you can use the ``params``
  115. argument to ``raw()``::
  116. >>> lname = 'Doe'
  117. >>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
  118. ``params`` is a list of parameters. You'll use ``%s`` placeholders in the
  119. query string (regardless of your database engine); they'll be replaced with
  120. parameters from the ``params`` list.
  121. .. warning::
  122. **Do not use string formatting on raw queries!**
  123. It's tempting to write the above query as::
  124. >>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
  125. >>> Person.objects.raw(query)
  126. **Don't.**
  127. Using the ``params`` list completely protects you from `SQL injection
  128. attacks`__, a common exploit where attackers inject arbitrary SQL into
  129. your database. If you use string interpolation, sooner or later you'll
  130. fall victim to SQL injection. As long as you remember to always use the
  131. ``params`` list you'll be protected.
  132. __ http://en.wikipedia.org/wiki/SQL_injection
  133. Executing custom SQL directly
  134. =============================
  135. Sometimes even :meth:`Manager.raw` isn't quite enough: you might need to
  136. perform queries that don't map cleanly to models, or directly execute
  137. ``UPDATE``, ``INSERT``, or ``DELETE`` queries.
  138. In these cases, you can always access the database directly, routing around
  139. the model layer entirely.
  140. The object ``django.db.connection`` represents the
  141. default database connection, and ``django.db.transaction`` represents the
  142. default database transaction. To use the database connection, call
  143. ``connection.cursor()`` to get a cursor object. Then, call
  144. ``cursor.execute(sql, [params])`` to execute the SQL and ``cursor.fetchone()``
  145. or ``cursor.fetchall()`` to return the resulting rows. After performing a data
  146. changing operation, you should then call
  147. ``transaction.commit_unless_managed()`` to ensure your changes are committed
  148. to the database. If your query is purely a data retrieval operation, no commit
  149. is required. For example::
  150. def my_custom_sql():
  151. from django.db import connection, transaction
  152. cursor = connection.cursor()
  153. # Data modifying operation - commit required
  154. cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
  155. transaction.commit_unless_managed()
  156. # Data retrieval operation - no commit required
  157. cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
  158. row = cursor.fetchone()
  159. return row
  160. If you are using more than one database you can use
  161. ``django.db.connections`` to obtain the connection (and cursor) for a
  162. specific database. ``django.db.connections`` is a dictionary-like
  163. object that allows you to retrieve a specific connection using it's
  164. alias::
  165. from django.db import connections
  166. cursor = connections['my_db_alias'].cursor()
  167. .. _transactions-and-raw-sql:
  168. Transactions and raw SQL
  169. ------------------------
  170. If you are using transaction decorators (such as ``commit_on_success``) to
  171. wrap your views and provide transaction control, you don't have to make a
  172. manual call to ``transaction.commit_unless_managed()`` -- you can manually
  173. commit if you want to, but you aren't required to, since the decorator will
  174. commit for you. However, if you don't manually commit your changes, you will
  175. need to manually mark the transaction as dirty, using
  176. ``transaction.set_dirty()``::
  177. @commit_on_success
  178. def my_custom_sql_view(request, value):
  179. from django.db import connection, transaction
  180. cursor = connection.cursor()
  181. # Data modifying operation
  182. cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])
  183. # Since we modified data, mark the transaction as dirty
  184. transaction.set_dirty()
  185. # Data retrieval operation. This doesn't dirty the transaction,
  186. # so no call to set_dirty() is required.
  187. cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value])
  188. row = cursor.fetchone()
  189. return render_to_response('template.html', {'row': row})
  190. The call to ``set_dirty()`` is made automatically when you use the Django ORM
  191. to make data modifying database calls. However, when you use raw SQL, Django
  192. has no way of knowing if your SQL modifies data or not. The manual call to
  193. ``set_dirty()`` ensures that Django knows that there are modifications that
  194. must be committed.
  195. Connections and cursors
  196. -----------------------
  197. ``connection`` and ``cursor`` mostly implement the standard `Python DB-API`_
  198. (except when it comes to :ref:`transaction handling <topics-db-transactions>`).
  199. If you're not familiar with the Python DB-API, note that the SQL statement in
  200. ``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters
  201. directly within the SQL. If you use this technique, the underlying database
  202. library will automatically add quotes and escaping to your parameter(s) as
  203. necessary. (Also note that Django expects the ``"%s"`` placeholder, *not* the
  204. ``"?"`` placeholder, which is used by the SQLite Python bindings. This is for
  205. the sake of consistency and sanity.)
  206. .. _Python DB-API: http://www.python.org/dev/peps/pep-0249/