sql.txt 12 KB

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