dml.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. from ... import exc
  2. from ... import util
  3. from ...sql.base import _exclusive_against
  4. from ...sql.base import _generative
  5. from ...sql.base import ColumnCollection
  6. from ...sql.dml import Insert as StandardInsert
  7. from ...sql.elements import ClauseElement
  8. from ...sql.expression import alias
  9. from ...util.langhelpers import public_factory
  10. __all__ = ("Insert", "insert")
  11. class Insert(StandardInsert):
  12. """MySQL-specific implementation of INSERT.
  13. Adds methods for MySQL-specific syntaxes such as ON DUPLICATE KEY UPDATE.
  14. The :class:`~.mysql.Insert` object is created using the
  15. :func:`sqlalchemy.dialects.mysql.insert` function.
  16. .. versionadded:: 1.2
  17. """
  18. stringify_dialect = "mysql"
  19. inherit_cache = False
  20. @property
  21. def inserted(self):
  22. """Provide the "inserted" namespace for an ON DUPLICATE KEY UPDATE statement
  23. MySQL's ON DUPLICATE KEY UPDATE clause allows reference to the row
  24. that would be inserted, via a special function called ``VALUES()``.
  25. This attribute provides all columns in this row to be referenceable
  26. such that they will render within a ``VALUES()`` function inside the
  27. ON DUPLICATE KEY UPDATE clause. The attribute is named ``.inserted``
  28. so as not to conflict with the existing
  29. :meth:`_expression.Insert.values` method.
  30. .. tip:: The :attr:`_mysql.Insert.inserted` attribute is an instance
  31. of :class:`_expression.ColumnCollection`, which provides an
  32. interface the same as that of the :attr:`_schema.Table.c`
  33. collection described at :ref:`metadata_tables_and_columns`.
  34. With this collection, ordinary names are accessible like attributes
  35. (e.g. ``stmt.inserted.some_column``), but special names and
  36. dictionary method names should be accessed using indexed access,
  37. such as ``stmt.inserted["column name"]`` or
  38. ``stmt.inserted["values"]``. See the docstring for
  39. :class:`_expression.ColumnCollection` for further examples.
  40. .. seealso::
  41. :ref:`mysql_insert_on_duplicate_key_update` - example of how
  42. to use :attr:`_expression.Insert.inserted`
  43. """
  44. return self.inserted_alias.columns
  45. @util.memoized_property
  46. def inserted_alias(self):
  47. return alias(self.table, name="inserted")
  48. @_generative
  49. @_exclusive_against(
  50. "_post_values_clause",
  51. msgs={
  52. "_post_values_clause": "This Insert construct already "
  53. "has an ON DUPLICATE KEY clause present"
  54. },
  55. )
  56. def on_duplicate_key_update(self, *args, **kw):
  57. r"""
  58. Specifies the ON DUPLICATE KEY UPDATE clause.
  59. :param \**kw: Column keys linked to UPDATE values. The
  60. values may be any SQL expression or supported literal Python
  61. values.
  62. .. warning:: This dictionary does **not** take into account
  63. Python-specified default UPDATE values or generation functions,
  64. e.g. those specified using :paramref:`_schema.Column.onupdate`.
  65. These values will not be exercised for an ON DUPLICATE KEY UPDATE
  66. style of UPDATE, unless values are manually specified here.
  67. :param \*args: As an alternative to passing key/value parameters,
  68. a dictionary or list of 2-tuples can be passed as a single positional
  69. argument.
  70. Passing a single dictionary is equivalent to the keyword argument
  71. form::
  72. insert().on_duplicate_key_update({"name": "some name"})
  73. Passing a list of 2-tuples indicates that the parameter assignments
  74. in the UPDATE clause should be ordered as sent, in a manner similar
  75. to that described for the :class:`_expression.Update`
  76. construct overall
  77. in :ref:`updates_order_parameters`::
  78. insert().on_duplicate_key_update(
  79. [("name", "some name"), ("value", "some value")])
  80. .. versionchanged:: 1.3 parameters can be specified as a dictionary
  81. or list of 2-tuples; the latter form provides for parameter
  82. ordering.
  83. .. versionadded:: 1.2
  84. .. seealso::
  85. :ref:`mysql_insert_on_duplicate_key_update`
  86. """
  87. if args and kw:
  88. raise exc.ArgumentError(
  89. "Can't pass kwargs and positional arguments simultaneously"
  90. )
  91. if args:
  92. if len(args) > 1:
  93. raise exc.ArgumentError(
  94. "Only a single dictionary or list of tuples "
  95. "is accepted positionally."
  96. )
  97. values = args[0]
  98. else:
  99. values = kw
  100. inserted_alias = getattr(self, "inserted_alias", None)
  101. self._post_values_clause = OnDuplicateClause(inserted_alias, values)
  102. insert = public_factory(
  103. Insert, ".dialects.mysql.insert", ".dialects.mysql.Insert"
  104. )
  105. class OnDuplicateClause(ClauseElement):
  106. __visit_name__ = "on_duplicate_key_update"
  107. _parameter_ordering = None
  108. stringify_dialect = "mysql"
  109. def __init__(self, inserted_alias, update):
  110. self.inserted_alias = inserted_alias
  111. # auto-detect that parameters should be ordered. This is copied from
  112. # Update._proces_colparams(), however we don't look for a special flag
  113. # in this case since we are not disambiguating from other use cases as
  114. # we are in Update.values().
  115. if isinstance(update, list) and (
  116. update and isinstance(update[0], tuple)
  117. ):
  118. self._parameter_ordering = [key for key, value in update]
  119. update = dict(update)
  120. if isinstance(update, dict):
  121. if not update:
  122. raise ValueError(
  123. "update parameter dictionary must not be empty"
  124. )
  125. elif isinstance(update, ColumnCollection):
  126. update = dict(update)
  127. else:
  128. raise ValueError(
  129. "update parameter must be a non-empty dictionary "
  130. "or a ColumnCollection such as the `.c.` collection "
  131. "of a Table object"
  132. )
  133. self.update = update