sql.txt 10 KB

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