2
0

sql.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. ==========================
  2. Performing raw SQL queries
  3. ==========================
  4. .. currentmodule:: django.db.models
  5. Django gives you two ways of performing raw SQL queries: you can use
  6. :meth:`Manager.raw()` to `perform raw queries and return model instances`__, or
  7. you can avoid the model layer entirely and `execute custom SQL directly`__.
  8. __ `performing raw queries`_
  9. __ `executing custom SQL directly`_
  10. .. admonition:: Explore the ORM before using raw SQL!
  11. The Django ORM provides many tools to express queries without writing raw
  12. SQL. For example:
  13. * The :doc:`QuerySet API </ref/models/querysets>` is extensive.
  14. * You can :meth:`annotate <.QuerySet.annotate>` and :doc:`aggregate
  15. </topics/db/aggregation>` using many built-in :doc:`database functions
  16. </ref/models/database-functions>`. Beyond those, you can create
  17. :doc:`custom query expressions </ref/models/expressions/>`.
  18. Before using raw SQL, explore :doc:`the ORM </topics/db/index>`. Ask on
  19. one of :doc:`the support channels </faq/help>` to see if the ORM supports
  20. your use case.
  21. .. warning::
  22. You should be very careful whenever you write raw SQL. Every time you use
  23. it, you should properly escape any parameters that the user can control
  24. by using ``params`` in order to protect against SQL injection attacks.
  25. Please read more about :ref:`SQL injection protection
  26. <sql-injection-protection>`.
  27. .. _executing-raw-queries:
  28. Performing raw queries
  29. ======================
  30. The ``raw()`` manager method can be used to perform raw SQL queries that
  31. return model instances:
  32. .. method:: Manager.raw(raw_query, params=(), translations=None)
  33. This method takes a raw SQL query, executes it, and returns a
  34. ``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
  35. can be iterated over like a normal :class:`~django.db.models.query.QuerySet` to
  36. provide object instances.
  37. This is best illustrated with an example. Suppose you have the following model::
  38. class Person(models.Model):
  39. first_name = models.CharField(...)
  40. last_name = models.CharField(...)
  41. birth_date = models.DateField(...)
  42. You could then execute custom SQL like so:
  43. .. code-block:: pycon
  44. >>> for p in Person.objects.raw("SELECT * FROM myapp_person"):
  45. ... print(p)
  46. ...
  47. John Smith
  48. Jane Jones
  49. This example isn't very exciting -- it's exactly the same as running
  50. ``Person.objects.all()``. However, ``raw()`` has a bunch of other options that
  51. make it very powerful.
  52. .. admonition:: Model table names
  53. Where did the name of the ``Person`` table come from in that example?
  54. By default, Django figures out a database table name by joining the
  55. model's "app label" -- the name you used in ``manage.py startapp`` -- to
  56. the model's class name, with an underscore between them. In the example
  57. we've assumed that the ``Person`` model lives in an app named ``myapp``,
  58. so its table would be ``myapp_person``.
  59. For more details check out the documentation for the
  60. :attr:`~Options.db_table` option, which also lets you manually set the
  61. database table name.
  62. .. warning::
  63. No checking is done on the SQL statement that is passed in to ``.raw()``.
  64. Django expects that the statement will return a set of rows from the
  65. database, but does nothing to enforce that. If the query does not
  66. return rows, a (possibly cryptic) error will result.
  67. .. warning::
  68. If you are performing queries on MySQL, note that MySQL's silent type coercion
  69. may cause unexpected results when mixing types. If you query on a string
  70. type column, but with an integer value, MySQL will coerce the types of all values
  71. in the table to an integer before performing the comparison. For example, if your
  72. table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
  73. both rows will match. To prevent this, perform the correct typecasting
  74. before using the value in a query.
  75. Mapping query fields to model fields
  76. ------------------------------------
  77. ``raw()`` automatically maps fields in the query to fields on the model.
  78. The order of fields in your query doesn't matter. In other words, both
  79. of the following queries work identically:
  80. .. code-block:: pycon
  81. >>> Person.objects.raw("SELECT id, first_name, last_name, birth_date FROM myapp_person")
  82. >>> Person.objects.raw("SELECT last_name, birth_date, first_name, id FROM myapp_person")
  83. Matching is done by name. This means that you can use SQL's ``AS`` clauses to
  84. map fields in the query to model fields. So if you had some other table that
  85. had ``Person`` data in it, you could easily map it into ``Person`` instances:
  86. .. code-block:: pycon
  87. >>> Person.objects.raw(
  88. ... """
  89. ... SELECT first AS first_name,
  90. ... last AS last_name,
  91. ... bd AS birth_date,
  92. ... pk AS id,
  93. ... FROM some_other_table
  94. ... """
  95. ... )
  96. As long as the names match, the model instances will be created correctly.
  97. Alternatively, you can map fields in the query to model fields using the
  98. ``translations`` argument to ``raw()``. This is a dictionary mapping names of
  99. fields in the query to names of fields on the model. For example, the above
  100. query could also be written:
  101. .. code-block:: pycon
  102. >>> name_map = {"first": "first_name", "last": "last_name", "bd": "birth_date", "pk": "id"}
  103. >>> Person.objects.raw("SELECT * FROM some_other_table", translations=name_map)
  104. Index lookups
  105. -------------
  106. ``raw()`` supports indexing, so if you need only the first result you can
  107. write:
  108. .. code-block:: pycon
  109. >>> first_person = Person.objects.raw("SELECT * FROM myapp_person")[0]
  110. However, the indexing and slicing are not performed at the database level. If
  111. you have a large number of ``Person`` objects in your database, it is more
  112. efficient to limit the query at the SQL level:
  113. .. code-block:: pycon
  114. >>> first_person = Person.objects.raw("SELECT * FROM myapp_person LIMIT 1")[0]
  115. Deferring model fields
  116. ----------------------
  117. Fields may also be left out:
  118. .. code-block:: pycon
  119. >>> people = Person.objects.raw("SELECT id, first_name FROM myapp_person")
  120. The ``Person`` objects returned by this query will be deferred model instances
  121. (see :meth:`~django.db.models.query.QuerySet.defer()`). This means that the
  122. fields that are omitted from the query will be loaded on demand. For example:
  123. .. code-block:: pycon
  124. >>> for p in Person.objects.raw("SELECT id, first_name FROM myapp_person"):
  125. ... print(
  126. ... p.first_name, # This will be retrieved by the original query
  127. ... p.last_name, # This will be retrieved on demand
  128. ... )
  129. ...
  130. John Smith
  131. Jane Jones
  132. From outward appearances, this looks like the query has retrieved both
  133. the first name and last name. However, this example actually issued 3
  134. queries. Only the first names were retrieved by the ``raw()`` query -- the
  135. last names were both retrieved on demand when they were printed.
  136. There is only one field that you can't leave out - the primary key
  137. field. Django uses the primary key to identify model instances, so it
  138. must always be included in a raw query. A
  139. :class:`~django.core.exceptions.FieldDoesNotExist` exception will be raised if
  140. you forget to include the primary key.
  141. Adding annotations
  142. ------------------
  143. You can also execute queries containing fields that aren't defined on the
  144. model. For example, we could use `PostgreSQL's age() function`__ to get a list
  145. of people with their ages calculated by the database:
  146. .. code-block:: pycon
  147. >>> people = Person.objects.raw("SELECT *, age(birth_date) AS age FROM myapp_person")
  148. >>> for p in people:
  149. ... print("%s is %s." % (p.first_name, p.age))
  150. ...
  151. John is 37.
  152. Jane is 42.
  153. ...
  154. You can often avoid using raw SQL to compute annotations by instead using a
  155. :ref:`Func() expression <func-expressions>`.
  156. __ https://www.postgresql.org/docs/current/functions-datetime.html
  157. Passing parameters into ``raw()``
  158. ---------------------------------
  159. If you need to perform parameterized queries, you can use the ``params``
  160. argument to ``raw()``:
  161. .. code-block:: pycon
  162. >>> lname = "Doe"
  163. >>> Person.objects.raw("SELECT * FROM myapp_person WHERE last_name = %s", [lname])
  164. ``params`` is a list or dictionary of parameters. You'll use ``%s``
  165. placeholders in the query string for a list, or ``%(key)s``
  166. placeholders for a dictionary (where ``key`` is replaced by a
  167. dictionary key), regardless of your database engine. Such placeholders will be
  168. replaced with parameters from the ``params`` argument.
  169. .. note::
  170. Dictionary params are not supported with the SQLite backend; with
  171. this backend, you must pass parameters as a list.
  172. .. warning::
  173. **Do not use string formatting on raw queries or quote placeholders in your
  174. SQL strings!**
  175. It's tempting to write the above query as:
  176. .. code-block:: pycon
  177. >>> query = "SELECT * FROM myapp_person WHERE last_name = %s" % lname
  178. >>> Person.objects.raw(query)
  179. You might also think you should write your query like this (with quotes
  180. around ``%s``):
  181. .. code-block:: pycon
  182. >>> query = "SELECT * FROM myapp_person WHERE last_name = '%s'"
  183. **Don't make either of these mistakes.**
  184. As discussed in :ref:`sql-injection-protection`, using the ``params``
  185. argument and leaving the placeholders unquoted protects you from `SQL
  186. injection attacks`__, a common exploit where attackers inject arbitrary
  187. SQL into your database. If you use string interpolation or quote the
  188. placeholder, you're at risk for SQL injection.
  189. __ https://en.wikipedia.org/wiki/SQL_injection
  190. .. _executing-custom-sql:
  191. Executing custom SQL directly
  192. =============================
  193. Sometimes even :meth:`Manager.raw` isn't quite enough: you might need to
  194. perform queries that don't map cleanly to models, or directly execute
  195. ``UPDATE``, ``INSERT``, or ``DELETE`` queries.
  196. In these cases, you can always access the database directly, routing around
  197. the model layer entirely.
  198. The object ``django.db.connection`` represents the default database
  199. connection. To use the database connection, call ``connection.cursor()`` to
  200. get a cursor object. Then, call ``cursor.execute(sql, [params])`` to execute
  201. the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the
  202. resulting rows.
  203. For example::
  204. from django.db import connection
  205. def my_custom_sql(self):
  206. with connection.cursor() as cursor:
  207. cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
  208. cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
  209. row = cursor.fetchone()
  210. return row
  211. To protect against SQL injection, you must not include quotes around the ``%s``
  212. placeholders in the SQL string.
  213. Note that if you want to include literal percent signs in the query, you have to
  214. double them in the case you are passing parameters::
  215. cursor.execute("SELECT foo FROM bar WHERE baz = '30%'")
  216. cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [self.id])
  217. If you are using :doc:`more than one database </topics/db/multi-db>`, you can
  218. use ``django.db.connections`` to obtain the connection (and cursor) for a
  219. specific database. ``django.db.connections`` is a dictionary-like
  220. object that allows you to retrieve a specific connection using its
  221. alias::
  222. from django.db import connections
  223. with connections["my_db_alias"].cursor() as cursor:
  224. # Your code here
  225. ...
  226. By default, the Python DB API will return results without their field names,
  227. which means you end up with a ``list`` of values, rather than a ``dict``. At a
  228. small performance and memory cost, you can return results as a ``dict`` by
  229. using something like this::
  230. def dictfetchall(cursor):
  231. """
  232. Return all rows from a cursor as a dict.
  233. Assume the column names are unique.
  234. """
  235. columns = [col[0] for col in cursor.description]
  236. return [dict(zip(columns, row)) for row in cursor.fetchall()]
  237. Another option is to use :func:`collections.namedtuple` from the Python
  238. standard library. A ``namedtuple`` is a tuple-like object that has fields
  239. accessible by attribute lookup; it's also indexable and iterable. Results are
  240. immutable and accessible by field names or indices, which might be useful::
  241. from collections import namedtuple
  242. def namedtuplefetchall(cursor):
  243. """
  244. Return all rows from a cursor as a namedtuple.
  245. Assume the column names are unique.
  246. """
  247. desc = cursor.description
  248. nt_result = namedtuple("Result", [col[0] for col in desc])
  249. return [nt_result(*row) for row in cursor.fetchall()]
  250. The ``dictfetchall()`` and ``namedtuplefetchall()`` examples assume unique
  251. column names, since a cursor cannot distinguish columns from different tables.
  252. Here is an example of the difference between the three:
  253. .. code-block:: pycon
  254. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2")
  255. >>> cursor.fetchall()
  256. ((54360982, None), (54360880, None))
  257. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2")
  258. >>> dictfetchall(cursor)
  259. [{'parent_id': None, 'id': 54360982}, {'parent_id': None, 'id': 54360880}]
  260. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2")
  261. >>> results = namedtuplefetchall(cursor)
  262. >>> results
  263. [Result(id=54360982, parent_id=None), Result(id=54360880, parent_id=None)]
  264. >>> results[0].id
  265. 54360982
  266. >>> results[0][0]
  267. 54360982
  268. Connections and cursors
  269. -----------------------
  270. ``connection`` and ``cursor`` mostly implement the standard Python DB-API
  271. described in :pep:`249` — except when it comes to :doc:`transaction handling
  272. </topics/db/transactions>`.
  273. If you're not familiar with the Python DB-API, note that the SQL statement in
  274. ``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding
  275. parameters directly within the SQL. If you use this technique, the underlying
  276. database library will automatically escape your parameters as necessary.
  277. Also note that Django expects the ``"%s"`` placeholder, *not* the ``"?"``
  278. placeholder, which is used by the SQLite Python bindings. This is for the sake
  279. of consistency and sanity.
  280. Using a cursor as a context manager::
  281. with connection.cursor() as c:
  282. c.execute(...)
  283. is equivalent to::
  284. c = connection.cursor()
  285. try:
  286. c.execute(...)
  287. finally:
  288. c.close()
  289. Calling stored procedures
  290. ~~~~~~~~~~~~~~~~~~~~~~~~~
  291. .. method:: CursorWrapper.callproc(procname, params=None, kparams=None)
  292. Calls a database stored procedure with the given name. A sequence
  293. (``params``) or dictionary (``kparams``) of input parameters may be
  294. provided. Most databases don't support ``kparams``. Of Django's built-in
  295. backends, only Oracle supports it.
  296. For example, given this stored procedure in an Oracle database:
  297. .. code-block:: sql
  298. CREATE PROCEDURE "TEST_PROCEDURE"(v_i INTEGER, v_text NVARCHAR2(10)) AS
  299. p_i INTEGER;
  300. p_text NVARCHAR2(10);
  301. BEGIN
  302. p_i := v_i;
  303. p_text := v_text;
  304. ...
  305. END;
  306. This will call it::
  307. with connection.cursor() as cursor:
  308. cursor.callproc("test_procedure", [1, "test"])