sql.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. .. _executing-raw-queries:
  13. Performing raw queries
  14. ======================
  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 takes a raw SQL query, executes it, and returns a
  19. ``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
  20. can be iterated over just like a normal QuerySet to provide object instances.
  21. This is best illustrated with an example. Suppose you have the following model::
  22. class Person(models.Model):
  23. first_name = models.CharField(...)
  24. last_name = models.CharField(...)
  25. birth_date = models.DateField(...)
  26. You could then execute custom SQL like so::
  27. >>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
  28. ... print(p)
  29. John Smith
  30. Jane Jones
  31. Of course, this example isn't very exciting -- it's exactly the same as
  32. running ``Person.objects.all()``. However, ``raw()`` has a bunch of other
  33. options that make it very powerful.
  34. .. admonition:: Model table names
  35. Where'd the name of the ``Person`` table come from in that example?
  36. By default, Django figures out a database table name by joining the
  37. model's "app label" -- the name you used in ``manage.py startapp`` -- to
  38. the model's class name, with an underscore between them. In the example
  39. we've assumed that the ``Person`` model lives in an app named ``myapp``,
  40. so its table would be ``myapp_person``.
  41. For more details check out the documentation for the
  42. :attr:`~Options.db_table` option, which also lets you manually set the
  43. database table name.
  44. .. warning::
  45. No checking is done on the SQL statement that is passed in to ``.raw()``.
  46. Django expects that the statement will return a set of rows from the
  47. database, but does nothing to enforce that. If the query does not
  48. return rows, a (possibly cryptic) error will result.
  49. .. warning::
  50. If you are performing queries on MySQL, note that MySQL's silent type coercion
  51. may cause unexpected results when mixing types. If you query on a string
  52. type column, but with an integer value, MySQL will coerce the types of all values
  53. in the table to an integer before performing the comparison. For example, if your
  54. table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
  55. both rows will match. To prevent this, perform the correct typecasting
  56. before using the value in a query.
  57. Mapping query fields to model fields
  58. ------------------------------------
  59. ``raw()`` automatically maps fields in the query to fields on the model.
  60. The order of fields in your query doesn't matter. In other words, both
  61. of the following queries work identically::
  62. >>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
  63. ...
  64. >>> Person.objects.raw('SELECT last_name, birth_date, first_name, id FROM myapp_person')
  65. ...
  66. Matching is done by name. This means that you can use SQL's ``AS`` clauses to
  67. map fields in the query to model fields. So if you had some other table that
  68. had ``Person`` data in it, you could easily map it into ``Person`` instances::
  69. >>> Person.objects.raw('''SELECT first AS first_name,
  70. ... last AS last_name,
  71. ... bd AS birth_date,
  72. ... pk AS id,
  73. ... FROM some_other_table''')
  74. As long as the names match, the model instances will be created correctly.
  75. Alternatively, you can map fields in the query to model fields using the
  76. ``translations`` argument to ``raw()``. This is a dictionary mapping names of
  77. fields in the query to names of fields on the model. For example, the above
  78. query could also be written::
  79. >>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
  80. >>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
  81. Index lookups
  82. -------------
  83. ``raw()`` supports indexing, so if you need only the first result you can
  84. write::
  85. >>> first_person = Person.objects.raw('SELECT * FROM myapp_person')[0]
  86. However, the indexing and slicing are not performed at the database level. If
  87. you have a large number of ``Person`` objects in your database, it is more
  88. efficient to limit the query at the SQL level::
  89. >>> first_person = Person.objects.raw('SELECT * FROM myapp_person LIMIT 1')[0]
  90. Deferring model fields
  91. ----------------------
  92. Fields may also be left out::
  93. >>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
  94. The ``Person`` objects returned by this query will be deferred model instances
  95. (see :meth:`~django.db.models.query.QuerySet.defer()`). This means that the
  96. fields that are omitted from the query will be loaded on demand. For example::
  97. >>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
  98. ... print(p.first_name, # This will be retrieved by the original query
  99. ... p.last_name) # This will be retrieved on demand
  100. ...
  101. John Smith
  102. Jane Jones
  103. From outward appearances, this looks like the query has retrieved both
  104. the first name and last name. However, this example actually issued 3
  105. queries. Only the first names were retrieved by the raw() query -- the
  106. last names were both retrieved on demand when they were printed.
  107. There is only one field that you can't leave out - the primary key
  108. field. Django uses the primary key to identify model instances, so it
  109. must always be included in a raw query. An ``InvalidQuery`` exception
  110. will be raised if you forget to include the primary key.
  111. Adding annotations
  112. ------------------
  113. You can also execute queries containing fields that aren't defined on the
  114. model. For example, we could use `PostgreSQL's age() function`__ to get a list
  115. of people with their ages calculated by the database::
  116. >>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
  117. >>> for p in people:
  118. ... print("%s is %s." % (p.first_name, p.age))
  119. John is 37.
  120. Jane is 42.
  121. ...
  122. __ http://www.postgresql.org/docs/current/static/functions-datetime.html
  123. Passing parameters into ``raw()``
  124. ---------------------------------
  125. If you need to perform parameterized queries, you can use the ``params``
  126. argument to ``raw()``::
  127. >>> lname = 'Doe'
  128. >>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
  129. ``params`` is a list or dictionary of parameters. You'll use ``%s``
  130. placeholders in the query string for a list, or ``%(key)s``
  131. placeholders for a dictionary (where ``key`` is replaced by a
  132. dictionary key, of course), regardless of your database engine. Such
  133. placeholders will be replaced with parameters from the ``params``
  134. argument.
  135. .. note:: Dictionary params not supported with SQLite
  136. Dictionary params are not supported with the SQLite backend; with
  137. this backend, you must pass parameters as a list.
  138. .. warning::
  139. **Do not use string formatting on raw queries!**
  140. It's tempting to write the above query as::
  141. >>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
  142. >>> Person.objects.raw(query)
  143. **Don't.**
  144. Using the ``params`` argument completely protects you from `SQL injection
  145. attacks`__, a common exploit where attackers inject arbitrary SQL into
  146. your database. If you use string interpolation, sooner or later you'll
  147. fall victim to SQL injection. As long as you remember to always use the
  148. ``params`` argument you'll be protected.
  149. __ http://en.wikipedia.org/wiki/SQL_injection
  150. .. _executing-custom-sql:
  151. Executing custom SQL directly
  152. =============================
  153. Sometimes even :meth:`Manager.raw` isn't quite enough: you might need to
  154. perform queries that don't map cleanly to models, or directly execute
  155. ``UPDATE``, ``INSERT``, or ``DELETE`` queries.
  156. In these cases, you can always access the database directly, routing around
  157. the model layer entirely.
  158. The object ``django.db.connection`` represents the default database
  159. connection. To use the database connection, call ``connection.cursor()`` to
  160. get a cursor object. Then, call ``cursor.execute(sql, [params])`` to execute
  161. the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the
  162. resulting rows.
  163. For example::
  164. from django.db import connection
  165. def my_custom_sql(self):
  166. cursor = connection.cursor()
  167. cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
  168. cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
  169. row = cursor.fetchone()
  170. return row
  171. Note that if you want to include literal percent signs in the query, you have to
  172. double them in the case you are passing parameters::
  173. cursor.execute("SELECT foo FROM bar WHERE baz = '30%'")
  174. cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [self.id])
  175. If you are using :doc:`more than one database </topics/db/multi-db>`, you can
  176. use ``django.db.connections`` to obtain the connection (and cursor) for a
  177. specific database. ``django.db.connections`` is a dictionary-like
  178. object that allows you to retrieve a specific connection using its
  179. alias::
  180. from django.db import connections
  181. cursor = connections['my_db_alias'].cursor()
  182. # Your code here...
  183. By default, the Python DB API will return results without their field
  184. names, which means you end up with a ``list`` of values, rather than a
  185. ``dict``. At a small performance cost, you can return results as a
  186. ``dict`` by using something like this::
  187. def dictfetchall(cursor):
  188. "Returns all rows from a cursor as a dict"
  189. desc = cursor.description
  190. return [
  191. dict(zip([col[0] for col in desc], row))
  192. for row in cursor.fetchall()
  193. ]
  194. Here is an example of the difference between the two::
  195. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
  196. >>> cursor.fetchall()
  197. ((54360982L, None), (54360880L, None))
  198. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
  199. >>> dictfetchall(cursor)
  200. [{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]
  201. Connections and cursors
  202. -----------------------
  203. ``connection`` and ``cursor`` mostly implement the standard Python DB-API
  204. described in :pep:`249` — except when it comes to :doc:`transaction handling
  205. </topics/db/transactions>`.
  206. If you're not familiar with the Python DB-API, note that the SQL statement in
  207. ``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding
  208. parameters directly within the SQL. If you use this technique, the underlying
  209. database library will automatically escape your parameters as necessary.
  210. Also note that Django expects the ``"%s"`` placeholder, *not* the ``"?"``
  211. placeholder, which is used by the SQLite Python bindings. This is for the sake
  212. of consistency and sanity.
  213. .. versionchanged:: 1.7
  214. :pep:`249` does not state whether a cursor should be usable as a context
  215. manager. Prior to Python 2.7, a cursor was usable as a context manager due
  216. an unexpected behavior in magic method lookups (`Python ticket #9220`_).
  217. Django 1.7 explicitly added support to allow using a cursor as context
  218. manager.
  219. .. _`Python ticket #9220`: http://bugs.python.org/issue9220
  220. Using a cursor as a context manager:
  221. .. code-block:: python
  222. with connection.cursor() as c:
  223. c.execute(...)
  224. is equivalent to:
  225. .. code-block:: python
  226. c = connection.cursor()
  227. try:
  228. c.execute(...)
  229. finally:
  230. c.close()