You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1656 lines
56KB

  1. # sql/types_api.py
  2. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Base types API.
  8. """
  9. from . import operators
  10. from .base import SchemaEventTarget
  11. from .traversals import NO_CACHE
  12. from .visitors import Traversible
  13. from .visitors import TraversibleType
  14. from .. import exc
  15. from .. import util
  16. # these are back-assigned by sqltypes.
  17. BOOLEANTYPE = None
  18. INTEGERTYPE = None
  19. NULLTYPE = None
  20. STRINGTYPE = None
  21. MATCHTYPE = None
  22. INDEXABLE = None
  23. TABLEVALUE = None
  24. _resolve_value_to_type = None
  25. class TypeEngine(Traversible):
  26. """The ultimate base class for all SQL datatypes.
  27. Common subclasses of :class:`.TypeEngine` include
  28. :class:`.String`, :class:`.Integer`, and :class:`.Boolean`.
  29. For an overview of the SQLAlchemy typing system, see
  30. :ref:`types_toplevel`.
  31. .. seealso::
  32. :ref:`types_toplevel`
  33. """
  34. _sqla_type = True
  35. _isnull = False
  36. _is_tuple_type = False
  37. _is_table_value = False
  38. _is_array = False
  39. _is_type_decorator = False
  40. class Comparator(operators.ColumnOperators):
  41. """Base class for custom comparison operations defined at the
  42. type level. See :attr:`.TypeEngine.comparator_factory`.
  43. """
  44. __slots__ = "expr", "type"
  45. default_comparator = None
  46. def __clause_element__(self):
  47. return self.expr
  48. def __init__(self, expr):
  49. self.expr = expr
  50. self.type = expr.type
  51. @util.preload_module("sqlalchemy.sql.default_comparator")
  52. def operate(self, op, *other, **kwargs):
  53. default_comparator = util.preloaded.sql_default_comparator
  54. o = default_comparator.operator_lookup[op.__name__]
  55. return o[0](self.expr, op, *(other + o[1:]), **kwargs)
  56. @util.preload_module("sqlalchemy.sql.default_comparator")
  57. def reverse_operate(self, op, other, **kwargs):
  58. default_comparator = util.preloaded.sql_default_comparator
  59. o = default_comparator.operator_lookup[op.__name__]
  60. return o[0](self.expr, op, other, reverse=True, *o[1:], **kwargs)
  61. def _adapt_expression(self, op, other_comparator):
  62. """evaluate the return type of <self> <op> <othertype>,
  63. and apply any adaptations to the given operator.
  64. This method determines the type of a resulting binary expression
  65. given two source types and an operator. For example, two
  66. :class:`_schema.Column` objects, both of the type
  67. :class:`.Integer`, will
  68. produce a :class:`.BinaryExpression` that also has the type
  69. :class:`.Integer` when compared via the addition (``+``) operator.
  70. However, using the addition operator with an :class:`.Integer`
  71. and a :class:`.Date` object will produce a :class:`.Date`, assuming
  72. "days delta" behavior by the database (in reality, most databases
  73. other than PostgreSQL don't accept this particular operation).
  74. The method returns a tuple of the form <operator>, <type>.
  75. The resulting operator and type will be those applied to the
  76. resulting :class:`.BinaryExpression` as the final operator and the
  77. right-hand side of the expression.
  78. Note that only a subset of operators make usage of
  79. :meth:`._adapt_expression`,
  80. including math operators and user-defined operators, but not
  81. boolean comparison or special SQL keywords like MATCH or BETWEEN.
  82. """
  83. return op, self.type
  84. def __reduce__(self):
  85. return _reconstitute_comparator, (self.expr,)
  86. hashable = True
  87. """Flag, if False, means values from this type aren't hashable.
  88. Used by the ORM when uniquing result lists.
  89. """
  90. comparator_factory = Comparator
  91. """A :class:`.TypeEngine.Comparator` class which will apply
  92. to operations performed by owning :class:`_expression.ColumnElement`
  93. objects.
  94. The :attr:`.comparator_factory` attribute is a hook consulted by
  95. the core expression system when column and SQL expression operations
  96. are performed. When a :class:`.TypeEngine.Comparator` class is
  97. associated with this attribute, it allows custom re-definition of
  98. all existing operators, as well as definition of new operators.
  99. Existing operators include those provided by Python operator overloading
  100. such as :meth:`.operators.ColumnOperators.__add__` and
  101. :meth:`.operators.ColumnOperators.__eq__`,
  102. those provided as standard
  103. attributes of :class:`.operators.ColumnOperators` such as
  104. :meth:`.operators.ColumnOperators.like`
  105. and :meth:`.operators.ColumnOperators.in_`.
  106. Rudimentary usage of this hook is allowed through simple subclassing
  107. of existing types, or alternatively by using :class:`.TypeDecorator`.
  108. See the documentation section :ref:`types_operators` for examples.
  109. """
  110. sort_key_function = None
  111. """A sorting function that can be passed as the key to sorted.
  112. The default value of ``None`` indicates that the values stored by
  113. this type are self-sorting.
  114. .. versionadded:: 1.3.8
  115. """
  116. should_evaluate_none = False
  117. """If True, the Python constant ``None`` is considered to be handled
  118. explicitly by this type.
  119. The ORM uses this flag to indicate that a positive value of ``None``
  120. is passed to the column in an INSERT statement, rather than omitting
  121. the column from the INSERT statement which has the effect of firing
  122. off column-level defaults. It also allows types which have special
  123. behavior for Python None, such as a JSON type, to indicate that
  124. they'd like to handle the None value explicitly.
  125. To set this flag on an existing type, use the
  126. :meth:`.TypeEngine.evaluates_none` method.
  127. .. seealso::
  128. :meth:`.TypeEngine.evaluates_none`
  129. .. versionadded:: 1.1
  130. """
  131. def evaluates_none(self):
  132. """Return a copy of this type which has the :attr:`.should_evaluate_none`
  133. flag set to True.
  134. E.g.::
  135. Table(
  136. 'some_table', metadata,
  137. Column(
  138. String(50).evaluates_none(),
  139. nullable=True,
  140. server_default='no value')
  141. )
  142. The ORM uses this flag to indicate that a positive value of ``None``
  143. is passed to the column in an INSERT statement, rather than omitting
  144. the column from the INSERT statement which has the effect of firing
  145. off column-level defaults. It also allows for types which have
  146. special behavior associated with the Python None value to indicate
  147. that the value doesn't necessarily translate into SQL NULL; a
  148. prime example of this is a JSON type which may wish to persist the
  149. JSON value ``'null'``.
  150. In all cases, the actual NULL SQL value can be always be
  151. persisted in any column by using
  152. the :obj:`_expression.null` SQL construct in an INSERT statement
  153. or associated with an ORM-mapped attribute.
  154. .. note::
  155. The "evaluates none" flag does **not** apply to a value
  156. of ``None`` passed to :paramref:`_schema.Column.default` or
  157. :paramref:`_schema.Column.server_default`; in these cases,
  158. ``None``
  159. still means "no default".
  160. .. versionadded:: 1.1
  161. .. seealso::
  162. :ref:`session_forcing_null` - in the ORM documentation
  163. :paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON
  164. interaction with this flag.
  165. :attr:`.TypeEngine.should_evaluate_none` - class-level flag
  166. """
  167. typ = self.copy()
  168. typ.should_evaluate_none = True
  169. return typ
  170. def copy(self, **kw):
  171. return self.adapt(self.__class__)
  172. def compare_against_backend(self, dialect, conn_type):
  173. """Compare this type against the given backend type.
  174. This function is currently not implemented for SQLAlchemy
  175. types, and for all built in types will return ``None``. However,
  176. it can be implemented by a user-defined type
  177. where it can be consumed by schema comparison tools such as
  178. Alembic autogenerate.
  179. A future release of SQLAlchemy will potentially implement this method
  180. for builtin types as well.
  181. The function should return True if this type is equivalent to the
  182. given type; the type is typically reflected from the database
  183. so should be database specific. The dialect in use is also
  184. passed. It can also return False to assert that the type is
  185. not equivalent.
  186. :param dialect: a :class:`.Dialect` that is involved in the comparison.
  187. :param conn_type: the type object reflected from the backend.
  188. .. versionadded:: 1.0.3
  189. """
  190. return None
  191. def copy_value(self, value):
  192. return value
  193. def literal_processor(self, dialect):
  194. """Return a conversion function for processing literal values that are
  195. to be rendered directly without using binds.
  196. This function is used when the compiler makes use of the
  197. "literal_binds" flag, typically used in DDL generation as well
  198. as in certain scenarios where backends don't accept bound parameters.
  199. .. versionadded:: 0.9.0
  200. """
  201. return None
  202. def bind_processor(self, dialect):
  203. """Return a conversion function for processing bind values.
  204. Returns a callable which will receive a bind parameter value
  205. as the sole positional argument and will return a value to
  206. send to the DB-API.
  207. If processing is not necessary, the method should return ``None``.
  208. :param dialect: Dialect instance in use.
  209. """
  210. return None
  211. def result_processor(self, dialect, coltype):
  212. """Return a conversion function for processing result row values.
  213. Returns a callable which will receive a result row column
  214. value as the sole positional argument and will return a value
  215. to return to the user.
  216. If processing is not necessary, the method should return ``None``.
  217. :param dialect: Dialect instance in use.
  218. :param coltype: DBAPI coltype argument received in cursor.description.
  219. """
  220. return None
  221. def column_expression(self, colexpr):
  222. """Given a SELECT column expression, return a wrapping SQL expression.
  223. This is typically a SQL function that wraps a column expression
  224. as rendered in the columns clause of a SELECT statement.
  225. It is used for special data types that require
  226. columns to be wrapped in some special database function in order
  227. to coerce the value before being sent back to the application.
  228. It is the SQL analogue of the :meth:`.TypeEngine.result_processor`
  229. method.
  230. The method is evaluated at statement compile time, as opposed
  231. to statement construction time.
  232. .. seealso::
  233. :ref:`types_sql_value_processing`
  234. """
  235. return None
  236. @util.memoized_property
  237. def _has_column_expression(self):
  238. """memoized boolean, check if column_expression is implemented.
  239. Allows the method to be skipped for the vast majority of expression
  240. types that don't use this feature.
  241. """
  242. return (
  243. self.__class__.column_expression.__code__
  244. is not TypeEngine.column_expression.__code__
  245. )
  246. def bind_expression(self, bindvalue):
  247. """Given a bind value (i.e. a :class:`.BindParameter` instance),
  248. return a SQL expression in its place.
  249. This is typically a SQL function that wraps the existing bound
  250. parameter within the statement. It is used for special data types
  251. that require literals being wrapped in some special database function
  252. in order to coerce an application-level value into a database-specific
  253. format. It is the SQL analogue of the
  254. :meth:`.TypeEngine.bind_processor` method.
  255. The method is evaluated at statement compile time, as opposed
  256. to statement construction time.
  257. Note that this method, when implemented, should always return
  258. the exact same structure, without any conditional logic, as it
  259. may be used in an executemany() call against an arbitrary number
  260. of bound parameter sets.
  261. .. seealso::
  262. :ref:`types_sql_value_processing`
  263. """
  264. return None
  265. @util.memoized_property
  266. def _has_bind_expression(self):
  267. """memoized boolean, check if bind_expression is implemented.
  268. Allows the method to be skipped for the vast majority of expression
  269. types that don't use this feature.
  270. """
  271. return util.method_is_overridden(self, TypeEngine.bind_expression)
  272. @staticmethod
  273. def _to_instance(cls_or_self):
  274. return to_instance(cls_or_self)
  275. def compare_values(self, x, y):
  276. """Compare two values for equality."""
  277. return x == y
  278. def get_dbapi_type(self, dbapi):
  279. """Return the corresponding type object from the underlying DB-API, if
  280. any.
  281. This can be useful for calling ``setinputsizes()``, for example.
  282. """
  283. return None
  284. @property
  285. def python_type(self):
  286. """Return the Python type object expected to be returned
  287. by instances of this type, if known.
  288. Basically, for those types which enforce a return type,
  289. or are known across the board to do such for all common
  290. DBAPIs (like ``int`` for example), will return that type.
  291. If a return type is not defined, raises
  292. ``NotImplementedError``.
  293. Note that any type also accommodates NULL in SQL which
  294. means you can also get back ``None`` from any type
  295. in practice.
  296. """
  297. raise NotImplementedError()
  298. def with_variant(self, type_, dialect_name):
  299. r"""Produce a new type object that will utilize the given
  300. type when applied to the dialect of the given name.
  301. e.g.::
  302. from sqlalchemy.types import String
  303. from sqlalchemy.dialects import mysql
  304. s = String()
  305. s = s.with_variant(mysql.VARCHAR(collation='foo'), 'mysql')
  306. The construction of :meth:`.TypeEngine.with_variant` is always
  307. from the "fallback" type to that which is dialect specific.
  308. The returned type is an instance of :class:`.Variant`, which
  309. itself provides a :meth:`.Variant.with_variant`
  310. that can be called repeatedly.
  311. :param type\_: a :class:`.TypeEngine` that will be selected
  312. as a variant from the originating type, when a dialect
  313. of the given name is in use.
  314. :param dialect_name: base name of the dialect which uses
  315. this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
  316. """
  317. return Variant(self, {dialect_name: to_instance(type_)})
  318. @util.memoized_property
  319. def _type_affinity(self):
  320. """Return a rudimental 'affinity' value expressing the general class
  321. of type."""
  322. typ = None
  323. for t in self.__class__.__mro__:
  324. if t in (TypeEngine, UserDefinedType):
  325. return typ
  326. elif issubclass(t, (TypeEngine, UserDefinedType)):
  327. typ = t
  328. else:
  329. return self.__class__
  330. @util.memoized_property
  331. def _generic_type_affinity(self):
  332. best_camelcase = None
  333. best_uppercase = None
  334. if not isinstance(self, (TypeEngine, UserDefinedType)):
  335. return self.__class__
  336. for t in self.__class__.__mro__:
  337. if (
  338. t.__module__
  339. in (
  340. "sqlalchemy.sql.sqltypes",
  341. "sqlalchemy.sql.type_api",
  342. )
  343. and issubclass(t, TypeEngine)
  344. and t is not TypeEngine
  345. and t.__name__[0] != "_"
  346. ):
  347. if t.__name__.isupper() and not best_uppercase:
  348. best_uppercase = t
  349. elif not t.__name__.isupper() and not best_camelcase:
  350. best_camelcase = t
  351. return best_camelcase or best_uppercase or NULLTYPE.__class__
  352. def as_generic(self, allow_nulltype=False):
  353. """
  354. Return an instance of the generic type corresponding to this type
  355. using heuristic rule. The method may be overridden if this
  356. heuristic rule is not sufficient.
  357. >>> from sqlalchemy.dialects.mysql import INTEGER
  358. >>> INTEGER(display_width=4).as_generic()
  359. Integer()
  360. >>> from sqlalchemy.dialects.mysql import NVARCHAR
  361. >>> NVARCHAR(length=100).as_generic()
  362. Unicode(length=100)
  363. .. versionadded:: 1.4.0b2
  364. .. seealso::
  365. :ref:`metadata_reflection_dbagnostic_types` - describes the
  366. use of :meth:`_types.TypeEngine.as_generic` in conjunction with
  367. the :meth:`_sql.DDLEvents.column_reflect` event, which is its
  368. intended use.
  369. """
  370. if (
  371. not allow_nulltype
  372. and self._generic_type_affinity == NULLTYPE.__class__
  373. ):
  374. raise NotImplementedError(
  375. "Default TypeEngine.as_generic() "
  376. "heuristic method was unsuccessful for {}. A custom "
  377. "as_generic() method must be implemented for this "
  378. "type class.".format(
  379. self.__class__.__module__ + "." + self.__class__.__name__
  380. )
  381. )
  382. return util.constructor_copy(self, self._generic_type_affinity)
  383. def dialect_impl(self, dialect):
  384. """Return a dialect-specific implementation for this
  385. :class:`.TypeEngine`.
  386. """
  387. try:
  388. return dialect._type_memos[self]["impl"]
  389. except KeyError:
  390. return self._dialect_info(dialect)["impl"]
  391. def _unwrapped_dialect_impl(self, dialect):
  392. """Return the 'unwrapped' dialect impl for this type.
  393. For a type that applies wrapping logic (e.g. TypeDecorator), give
  394. us the real, actual dialect-level type that is used.
  395. This is used by TypeDecorator itself as well at least one case where
  396. dialects need to check that a particular specific dialect-level
  397. type is in use, within the :meth:`.DefaultDialect.set_input_sizes`
  398. method.
  399. """
  400. return self.dialect_impl(dialect)
  401. def _cached_literal_processor(self, dialect):
  402. """Return a dialect-specific literal processor for this type."""
  403. try:
  404. return dialect._type_memos[self]["literal"]
  405. except KeyError:
  406. pass
  407. # avoid KeyError context coming into literal_processor() function
  408. # raises
  409. d = self._dialect_info(dialect)
  410. d["literal"] = lp = d["impl"].literal_processor(dialect)
  411. return lp
  412. def _cached_bind_processor(self, dialect):
  413. """Return a dialect-specific bind processor for this type."""
  414. try:
  415. return dialect._type_memos[self]["bind"]
  416. except KeyError:
  417. pass
  418. # avoid KeyError context coming into bind_processor() function
  419. # raises
  420. d = self._dialect_info(dialect)
  421. d["bind"] = bp = d["impl"].bind_processor(dialect)
  422. return bp
  423. def _cached_result_processor(self, dialect, coltype):
  424. """Return a dialect-specific result processor for this type."""
  425. try:
  426. return dialect._type_memos[self][coltype]
  427. except KeyError:
  428. pass
  429. # avoid KeyError context coming into result_processor() function
  430. # raises
  431. d = self._dialect_info(dialect)
  432. # key assumption: DBAPI type codes are
  433. # constants. Else this dictionary would
  434. # grow unbounded.
  435. d[coltype] = rp = d["impl"].result_processor(dialect, coltype)
  436. return rp
  437. def _cached_custom_processor(self, dialect, key, fn):
  438. try:
  439. return dialect._type_memos[self][key]
  440. except KeyError:
  441. pass
  442. # avoid KeyError context coming into fn() function
  443. # raises
  444. d = self._dialect_info(dialect)
  445. impl = d["impl"]
  446. d[key] = result = fn(impl)
  447. return result
  448. def _dialect_info(self, dialect):
  449. """Return a dialect-specific registry which
  450. caches a dialect-specific implementation, bind processing
  451. function, and one or more result processing functions."""
  452. if self in dialect._type_memos:
  453. return dialect._type_memos[self]
  454. else:
  455. impl = self._gen_dialect_impl(dialect)
  456. if impl is self:
  457. impl = self.adapt(type(self))
  458. # this can't be self, else we create a cycle
  459. assert impl is not self
  460. dialect._type_memos[self] = d = {"impl": impl}
  461. return d
  462. def _gen_dialect_impl(self, dialect):
  463. return dialect.type_descriptor(self)
  464. @util.memoized_property
  465. def _static_cache_key(self):
  466. names = util.get_cls_kwargs(self.__class__)
  467. return (self.__class__,) + tuple(
  468. (
  469. k,
  470. self.__dict__[k]._static_cache_key
  471. if isinstance(self.__dict__[k], TypeEngine)
  472. else self.__dict__[k],
  473. )
  474. for k in names
  475. if k in self.__dict__ and not k.startswith("_")
  476. )
  477. def adapt(self, cls, **kw):
  478. """Produce an "adapted" form of this type, given an "impl" class
  479. to work with.
  480. This method is used internally to associate generic
  481. types with "implementation" types that are specific to a particular
  482. dialect.
  483. """
  484. return util.constructor_copy(self, cls, **kw)
  485. def coerce_compared_value(self, op, value):
  486. """Suggest a type for a 'coerced' Python value in an expression.
  487. Given an operator and value, gives the type a chance
  488. to return a type which the value should be coerced into.
  489. The default behavior here is conservative; if the right-hand
  490. side is already coerced into a SQL type based on its
  491. Python type, it is usually left alone.
  492. End-user functionality extension here should generally be via
  493. :class:`.TypeDecorator`, which provides more liberal behavior in that
  494. it defaults to coercing the other side of the expression into this
  495. type, thus applying special Python conversions above and beyond those
  496. needed by the DBAPI to both ides. It also provides the public method
  497. :meth:`.TypeDecorator.coerce_compared_value` which is intended for
  498. end-user customization of this behavior.
  499. """
  500. _coerced_type = _resolve_value_to_type(value)
  501. if (
  502. _coerced_type is NULLTYPE
  503. or _coerced_type._type_affinity is self._type_affinity
  504. ):
  505. return self
  506. else:
  507. return _coerced_type
  508. def _compare_type_affinity(self, other):
  509. return self._type_affinity is other._type_affinity
  510. def compile(self, dialect=None):
  511. """Produce a string-compiled form of this :class:`.TypeEngine`.
  512. When called with no arguments, uses a "default" dialect
  513. to produce a string result.
  514. :param dialect: a :class:`.Dialect` instance.
  515. """
  516. # arg, return value is inconsistent with
  517. # ClauseElement.compile()....this is a mistake.
  518. if not dialect:
  519. dialect = self._default_dialect()
  520. return dialect.type_compiler.process(self)
  521. @util.preload_module("sqlalchemy.engine.default")
  522. def _default_dialect(self):
  523. default = util.preloaded.engine_default
  524. return default.StrCompileDialect()
  525. def __str__(self):
  526. if util.py2k:
  527. return unicode(self.compile()).encode( # noqa
  528. "ascii", "backslashreplace"
  529. ) # noqa
  530. else:
  531. return str(self.compile())
  532. def __repr__(self):
  533. return util.generic_repr(self)
  534. class VisitableCheckKWArg(util.EnsureKWArgType, TraversibleType):
  535. pass
  536. class UserDefinedType(util.with_metaclass(VisitableCheckKWArg, TypeEngine)):
  537. """Base for user defined types.
  538. This should be the base of new types. Note that
  539. for most cases, :class:`.TypeDecorator` is probably
  540. more appropriate::
  541. import sqlalchemy.types as types
  542. class MyType(types.UserDefinedType):
  543. def __init__(self, precision = 8):
  544. self.precision = precision
  545. def get_col_spec(self, **kw):
  546. return "MYTYPE(%s)" % self.precision
  547. def bind_processor(self, dialect):
  548. def process(value):
  549. return value
  550. return process
  551. def result_processor(self, dialect, coltype):
  552. def process(value):
  553. return value
  554. return process
  555. Once the type is made, it's immediately usable::
  556. table = Table('foo', meta,
  557. Column('id', Integer, primary_key=True),
  558. Column('data', MyType(16))
  559. )
  560. The ``get_col_spec()`` method will in most cases receive a keyword
  561. argument ``type_expression`` which refers to the owning expression
  562. of the type as being compiled, such as a :class:`_schema.Column` or
  563. :func:`.cast` construct. This keyword is only sent if the method
  564. accepts keyword arguments (e.g. ``**kw``) in its argument signature;
  565. introspection is used to check for this in order to support legacy
  566. forms of this function.
  567. .. versionadded:: 1.0.0 the owning expression is passed to
  568. the ``get_col_spec()`` method via the keyword argument
  569. ``type_expression``, if it receives ``**kw`` in its signature.
  570. """
  571. __visit_name__ = "user_defined"
  572. ensure_kwarg = "get_col_spec"
  573. def coerce_compared_value(self, op, value):
  574. """Suggest a type for a 'coerced' Python value in an expression.
  575. Default behavior for :class:`.UserDefinedType` is the
  576. same as that of :class:`.TypeDecorator`; by default it returns
  577. ``self``, assuming the compared value should be coerced into
  578. the same type as this one. See
  579. :meth:`.TypeDecorator.coerce_compared_value` for more detail.
  580. """
  581. return self
  582. class Emulated(object):
  583. """Mixin for base types that emulate the behavior of a DB-native type.
  584. An :class:`.Emulated` type will use an available database type
  585. in conjunction with Python-side routines and/or database constraints
  586. in order to approximate the behavior of a database type that is provided
  587. natively by some backends. When a native-providing backend is in
  588. use, the native version of the type is used. This native version
  589. should include the :class:`.NativeForEmulated` mixin to allow it to be
  590. distinguished from :class:`.Emulated`.
  591. Current examples of :class:`.Emulated` are: :class:`.Interval`,
  592. :class:`.Enum`, :class:`.Boolean`.
  593. .. versionadded:: 1.2.0b3
  594. """
  595. def adapt_to_emulated(self, impltype, **kw):
  596. """Given an impl class, adapt this type to the impl assuming "emulated".
  597. The impl should also be an "emulated" version of this type,
  598. most likely the same class as this type itself.
  599. e.g.: sqltypes.Enum adapts to the Enum class.
  600. """
  601. return super(Emulated, self).adapt(impltype, **kw)
  602. def adapt(self, impltype, **kw):
  603. if hasattr(impltype, "adapt_emulated_to_native"):
  604. if self.native:
  605. # native support requested, dialect gave us a native
  606. # implementor, pass control over to it
  607. return impltype.adapt_emulated_to_native(self, **kw)
  608. else:
  609. # non-native support, let the native implementor
  610. # decide also, at the moment this is just to help debugging
  611. # as only the default logic is implemented.
  612. return impltype.adapt_native_to_emulated(self, **kw)
  613. else:
  614. if issubclass(impltype, self.__class__):
  615. return self.adapt_to_emulated(impltype, **kw)
  616. else:
  617. return super(Emulated, self).adapt(impltype, **kw)
  618. class NativeForEmulated(object):
  619. """Indicates DB-native types supported by an :class:`.Emulated` type.
  620. .. versionadded:: 1.2.0b3
  621. """
  622. @classmethod
  623. def adapt_native_to_emulated(cls, impl, **kw):
  624. """Given an impl, adapt this type's class to the impl assuming
  625. "emulated".
  626. """
  627. impltype = impl.__class__
  628. return impl.adapt(impltype, **kw)
  629. @classmethod
  630. def adapt_emulated_to_native(cls, impl, **kw):
  631. """Given an impl, adapt this type's class to the impl assuming "native".
  632. The impl will be an :class:`.Emulated` class but not a
  633. :class:`.NativeForEmulated`.
  634. e.g.: postgresql.ENUM produces a type given an Enum instance.
  635. """
  636. return cls(**kw)
  637. class TypeDecorator(SchemaEventTarget, TypeEngine):
  638. """Allows the creation of types which add additional functionality
  639. to an existing type.
  640. This method is preferred to direct subclassing of SQLAlchemy's
  641. built-in types as it ensures that all required functionality of
  642. the underlying type is kept in place.
  643. Typical usage::
  644. import sqlalchemy.types as types
  645. class MyType(types.TypeDecorator):
  646. '''Prefixes Unicode values with "PREFIX:" on the way in and
  647. strips it off on the way out.
  648. '''
  649. impl = types.Unicode
  650. cache_ok = True
  651. def process_bind_param(self, value, dialect):
  652. return "PREFIX:" + value
  653. def process_result_value(self, value, dialect):
  654. return value[7:]
  655. def copy(self, **kw):
  656. return MyType(self.impl.length)
  657. The class-level ``impl`` attribute is required, and can reference any
  658. :class:`.TypeEngine` class. Alternatively, the :meth:`load_dialect_impl`
  659. method can be used to provide different type classes based on the dialect
  660. given; in this case, the ``impl`` variable can reference
  661. ``TypeEngine`` as a placeholder.
  662. The :attr:`.TypeDecorator.cache_ok` class-level flag indicates if this
  663. custom :class:`.TypeDecorator` is safe to be used as part of a cache key.
  664. This flag defaults to ``None`` which will initially generate a warning
  665. when the SQL compiler attempts to generate a cache key for a statement
  666. that uses this type. If the :class:`.TypeDecorator` is not guaranteed
  667. to produce the same bind/result behavior and SQL generation
  668. every time, this flag should be set to ``False``; otherwise if the
  669. class produces the same behavior each time, it may be set to ``True``.
  670. See :attr:`.TypeDecorator.cache_ok` for further notes on how this works.
  671. Types that receive a Python type that isn't similar to the ultimate type
  672. used may want to define the :meth:`TypeDecorator.coerce_compared_value`
  673. method. This is used to give the expression system a hint when coercing
  674. Python objects into bind parameters within expressions. Consider this
  675. expression::
  676. mytable.c.somecol + datetime.date(2009, 5, 15)
  677. Above, if "somecol" is an ``Integer`` variant, it makes sense that
  678. we're doing date arithmetic, where above is usually interpreted
  679. by databases as adding a number of days to the given date.
  680. The expression system does the right thing by not attempting to
  681. coerce the "date()" value into an integer-oriented bind parameter.
  682. However, in the case of ``TypeDecorator``, we are usually changing an
  683. incoming Python type to something new - ``TypeDecorator`` by default will
  684. "coerce" the non-typed side to be the same type as itself. Such as below,
  685. we define an "epoch" type that stores a date value as an integer::
  686. class MyEpochType(types.TypeDecorator):
  687. impl = types.Integer
  688. epoch = datetime.date(1970, 1, 1)
  689. def process_bind_param(self, value, dialect):
  690. return (value - self.epoch).days
  691. def process_result_value(self, value, dialect):
  692. return self.epoch + timedelta(days=value)
  693. Our expression of ``somecol + date`` with the above type will coerce the
  694. "date" on the right side to also be treated as ``MyEpochType``.
  695. This behavior can be overridden via the
  696. :meth:`~TypeDecorator.coerce_compared_value` method, which returns a type
  697. that should be used for the value of the expression. Below we set it such
  698. that an integer value will be treated as an ``Integer``, and any other
  699. value is assumed to be a date and will be treated as a ``MyEpochType``::
  700. def coerce_compared_value(self, op, value):
  701. if isinstance(value, int):
  702. return Integer()
  703. else:
  704. return self
  705. .. warning::
  706. Note that the **behavior of coerce_compared_value is not inherited
  707. by default from that of the base type**.
  708. If the :class:`.TypeDecorator` is augmenting a
  709. type that requires special logic for certain types of operators,
  710. this method **must** be overridden. A key example is when decorating
  711. the :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types;
  712. the default rules of :meth:`.TypeEngine.coerce_compared_value` should
  713. be used in order to deal with operators like index operations::
  714. class MyJsonType(TypeDecorator):
  715. impl = postgresql.JSON
  716. cache_ok = True
  717. def coerce_compared_value(self, op, value):
  718. return self.impl.coerce_compared_value(op, value)
  719. Without the above step, index operations such as ``mycol['foo']``
  720. will cause the index value ``'foo'`` to be JSON encoded.
  721. """
  722. __visit_name__ = "type_decorator"
  723. _is_type_decorator = True
  724. def __init__(self, *args, **kwargs):
  725. """Construct a :class:`.TypeDecorator`.
  726. Arguments sent here are passed to the constructor
  727. of the class assigned to the ``impl`` class level attribute,
  728. assuming the ``impl`` is a callable, and the resulting
  729. object is assigned to the ``self.impl`` instance attribute
  730. (thus overriding the class attribute of the same name).
  731. If the class level ``impl`` is not a callable (the unusual case),
  732. it will be assigned to the same instance attribute 'as-is',
  733. ignoring those arguments passed to the constructor.
  734. Subclasses can override this to customize the generation
  735. of ``self.impl`` entirely.
  736. """
  737. if not hasattr(self.__class__, "impl"):
  738. raise AssertionError(
  739. "TypeDecorator implementations "
  740. "require a class-level variable "
  741. "'impl' which refers to the class of "
  742. "type being decorated"
  743. )
  744. self.impl = to_instance(self.__class__.impl, *args, **kwargs)
  745. coerce_to_is_types = (util.NoneType,)
  746. """Specify those Python types which should be coerced at the expression
  747. level to "IS <constant>" when compared using ``==`` (and same for
  748. ``IS NOT`` in conjunction with ``!=``).
  749. For most SQLAlchemy types, this includes ``NoneType``, as well as
  750. ``bool``.
  751. :class:`.TypeDecorator` modifies this list to only include ``NoneType``,
  752. as typedecorator implementations that deal with boolean types are common.
  753. Custom :class:`.TypeDecorator` classes can override this attribute to
  754. return an empty tuple, in which case no values will be coerced to
  755. constants.
  756. """
  757. cache_ok = None
  758. """Indicate if statements using this :class:`.TypeDecorator` are "safe to
  759. cache".
  760. The default value ``None`` will emit a warning and then not allow caching
  761. of a statement which includes this type. Set to ``False`` to disable
  762. statements using this type from being cached at all without a warning.
  763. When set to ``True``, the object's class and selected elements from its
  764. state will be used as part of the cache key, e.g.::
  765. class MyType(TypeDecorator):
  766. impl = String
  767. cache_ok = True
  768. def __init__(self, choices):
  769. self.choices = tuple(choices)
  770. self.internal_only = True
  771. The cache key for the above type would be equivalent to::
  772. (<class '__main__.MyType'>, ('choices', ('a', 'b', 'c')))
  773. The caching scheme will extract attributes from the type that correspond
  774. to the names of parameters in the ``__init__()`` method. Above, the
  775. "choices" attribute becomes part of the cache key but "internal_only"
  776. does not, because there is no parameter named "internal_only".
  777. The requirements for cacheable elements is that they are hashable
  778. and also that they indicate the same SQL rendered for expressions using
  779. this type every time for a given cache value.
  780. .. versionadded:: 1.4.14 - added the ``cache_ok`` flag to allow
  781. some configurability of caching for :class:`.TypeDecorator` classes.
  782. .. seealso::
  783. :ref:`sql_caching`
  784. """
  785. class Comparator(TypeEngine.Comparator):
  786. """A :class:`.TypeEngine.Comparator` that is specific to
  787. :class:`.TypeDecorator`.
  788. User-defined :class:`.TypeDecorator` classes should not typically
  789. need to modify this.
  790. """
  791. __slots__ = ()
  792. def operate(self, op, *other, **kwargs):
  793. kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
  794. return super(TypeDecorator.Comparator, self).operate(
  795. op, *other, **kwargs
  796. )
  797. def reverse_operate(self, op, other, **kwargs):
  798. kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
  799. return super(TypeDecorator.Comparator, self).reverse_operate(
  800. op, other, **kwargs
  801. )
  802. @property
  803. def comparator_factory(self):
  804. if TypeDecorator.Comparator in self.impl.comparator_factory.__mro__:
  805. return self.impl.comparator_factory
  806. else:
  807. return type(
  808. "TDComparator",
  809. (TypeDecorator.Comparator, self.impl.comparator_factory),
  810. {},
  811. )
  812. @property
  813. def _static_cache_key(self):
  814. if self.cache_ok is None:
  815. util.warn(
  816. "TypeDecorator %r will not produce a cache key because "
  817. "the ``cache_ok`` flag is not set to True. "
  818. "Set this flag to True if this type object's "
  819. "state is safe to use in a cache key, or False to "
  820. "disable this warning." % self
  821. )
  822. elif self.cache_ok is True:
  823. return super(TypeDecorator, self)._static_cache_key
  824. return NO_CACHE
  825. def _gen_dialect_impl(self, dialect):
  826. """
  827. #todo
  828. """
  829. adapted = dialect.type_descriptor(self)
  830. if adapted is not self:
  831. return adapted
  832. # otherwise adapt the impl type, link
  833. # to a copy of this TypeDecorator and return
  834. # that.
  835. typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect)
  836. tt = self.copy()
  837. if not isinstance(tt, self.__class__):
  838. raise AssertionError(
  839. "Type object %s does not properly "
  840. "implement the copy() method, it must "
  841. "return an object of type %s" % (self, self.__class__)
  842. )
  843. tt.impl = typedesc
  844. return tt
  845. @property
  846. def _type_affinity(self):
  847. """
  848. #todo
  849. """
  850. return self.impl._type_affinity
  851. def _set_parent(self, column, outer=False, **kw):
  852. """Support SchemaEventTarget"""
  853. super(TypeDecorator, self)._set_parent(column)
  854. if not outer and isinstance(self.impl, SchemaEventTarget):
  855. self.impl._set_parent(column, outer=False, **kw)
  856. def _set_parent_with_dispatch(self, parent):
  857. """Support SchemaEventTarget"""
  858. super(TypeDecorator, self)._set_parent_with_dispatch(
  859. parent, outer=True
  860. )
  861. if isinstance(self.impl, SchemaEventTarget):
  862. self.impl._set_parent_with_dispatch(parent)
  863. def type_engine(self, dialect):
  864. """Return a dialect-specific :class:`.TypeEngine` instance
  865. for this :class:`.TypeDecorator`.
  866. In most cases this returns a dialect-adapted form of
  867. the :class:`.TypeEngine` type represented by ``self.impl``.
  868. Makes usage of :meth:`dialect_impl`.
  869. Behavior can be customized here by overriding
  870. :meth:`load_dialect_impl`.
  871. """
  872. adapted = dialect.type_descriptor(self)
  873. if not isinstance(adapted, type(self)):
  874. return adapted
  875. else:
  876. return self.load_dialect_impl(dialect)
  877. def load_dialect_impl(self, dialect):
  878. """Return a :class:`.TypeEngine` object corresponding to a dialect.
  879. This is an end-user override hook that can be used to provide
  880. differing types depending on the given dialect. It is used
  881. by the :class:`.TypeDecorator` implementation of :meth:`type_engine`
  882. to help determine what type should ultimately be returned
  883. for a given :class:`.TypeDecorator`.
  884. By default returns ``self.impl``.
  885. """
  886. return self.impl
  887. def _unwrapped_dialect_impl(self, dialect):
  888. """Return the 'unwrapped' dialect impl for this type.
  889. This is used by the :meth:`.DefaultDialect.set_input_sizes`
  890. method.
  891. """
  892. # some dialects have a lookup for a TypeDecorator subclass directly.
  893. # postgresql.INTERVAL being the main example
  894. typ = self.dialect_impl(dialect)
  895. # if we are still a type decorator, load the per-dialect switch
  896. # (such as what Variant uses), then get the dialect impl for that.
  897. if isinstance(typ, self.__class__):
  898. return typ.load_dialect_impl(dialect).dialect_impl(dialect)
  899. else:
  900. return typ
  901. def __getattr__(self, key):
  902. """Proxy all other undefined accessors to the underlying
  903. implementation."""
  904. return getattr(self.impl, key)
  905. def process_literal_param(self, value, dialect):
  906. """Receive a literal parameter value to be rendered inline within
  907. a statement.
  908. This method is used when the compiler renders a
  909. literal value without using binds, typically within DDL
  910. such as in the "server default" of a column or an expression
  911. within a CHECK constraint.
  912. The returned string will be rendered into the output string.
  913. .. versionadded:: 0.9.0
  914. """
  915. raise NotImplementedError()
  916. def process_bind_param(self, value, dialect):
  917. """Receive a bound parameter value to be converted.
  918. Subclasses override this method to return the
  919. value that should be passed along to the underlying
  920. :class:`.TypeEngine` object, and from there to the
  921. DBAPI ``execute()`` method.
  922. The operation could be anything desired to perform custom
  923. behavior, such as transforming or serializing data.
  924. This could also be used as a hook for validating logic.
  925. This operation should be designed with the reverse operation
  926. in mind, which would be the process_result_value method of
  927. this class.
  928. :param value: Data to operate upon, of any type expected by
  929. this method in the subclass. Can be ``None``.
  930. :param dialect: the :class:`.Dialect` in use.
  931. """
  932. raise NotImplementedError()
  933. def process_result_value(self, value, dialect):
  934. """Receive a result-row column value to be converted.
  935. Subclasses should implement this method to operate on data
  936. fetched from the database.
  937. Subclasses override this method to return the
  938. value that should be passed back to the application,
  939. given a value that is already processed by
  940. the underlying :class:`.TypeEngine` object, originally
  941. from the DBAPI cursor method ``fetchone()`` or similar.
  942. The operation could be anything desired to perform custom
  943. behavior, such as transforming or serializing data.
  944. This could also be used as a hook for validating logic.
  945. :param value: Data to operate upon, of any type expected by
  946. this method in the subclass. Can be ``None``.
  947. :param dialect: the :class:`.Dialect` in use.
  948. This operation should be designed to be reversible by
  949. the "process_bind_param" method of this class.
  950. """
  951. raise NotImplementedError()
  952. @util.memoized_property
  953. def _has_bind_processor(self):
  954. """memoized boolean, check if process_bind_param is implemented.
  955. Allows the base process_bind_param to raise
  956. NotImplementedError without needing to test an expensive
  957. exception throw.
  958. """
  959. return util.method_is_overridden(
  960. self, TypeDecorator.process_bind_param
  961. )
  962. @util.memoized_property
  963. def _has_literal_processor(self):
  964. """memoized boolean, check if process_literal_param is implemented."""
  965. return util.method_is_overridden(
  966. self, TypeDecorator.process_literal_param
  967. )
  968. def literal_processor(self, dialect):
  969. """Provide a literal processing function for the given
  970. :class:`.Dialect`.
  971. Subclasses here will typically override
  972. :meth:`.TypeDecorator.process_literal_param` instead of this method
  973. directly.
  974. By default, this method makes use of
  975. :meth:`.TypeDecorator.process_bind_param` if that method is
  976. implemented, where :meth:`.TypeDecorator.process_literal_param` is
  977. not. The rationale here is that :class:`.TypeDecorator` typically
  978. deals with Python conversions of data that are above the layer of
  979. database presentation. With the value converted by
  980. :meth:`.TypeDecorator.process_bind_param`, the underlying type will
  981. then handle whether it needs to be presented to the DBAPI as a bound
  982. parameter or to the database as an inline SQL value.
  983. .. versionadded:: 0.9.0
  984. """
  985. if self._has_literal_processor:
  986. process_param = self.process_literal_param
  987. elif self._has_bind_processor:
  988. # the bind processor should normally be OK
  989. # for TypeDecorator since it isn't doing DB-level
  990. # handling, the handling here won't be different for bound vs.
  991. # literals.
  992. process_param = self.process_bind_param
  993. else:
  994. process_param = None
  995. if process_param:
  996. impl_processor = self.impl.literal_processor(dialect)
  997. if impl_processor:
  998. def process(value):
  999. return impl_processor(process_param(value, dialect))
  1000. else:
  1001. def process(value):
  1002. return process_param(value, dialect)
  1003. return process
  1004. else:
  1005. return self.impl.literal_processor(dialect)
  1006. def bind_processor(self, dialect):
  1007. """Provide a bound value processing function for the
  1008. given :class:`.Dialect`.
  1009. This is the method that fulfills the :class:`.TypeEngine`
  1010. contract for bound value conversion. :class:`.TypeDecorator`
  1011. will wrap a user-defined implementation of
  1012. :meth:`process_bind_param` here.
  1013. User-defined code can override this method directly,
  1014. though its likely best to use :meth:`process_bind_param` so that
  1015. the processing provided by ``self.impl`` is maintained.
  1016. :param dialect: Dialect instance in use.
  1017. This method is the reverse counterpart to the
  1018. :meth:`result_processor` method of this class.
  1019. """
  1020. if self._has_bind_processor:
  1021. process_param = self.process_bind_param
  1022. impl_processor = self.impl.bind_processor(dialect)
  1023. if impl_processor:
  1024. def process(value):
  1025. return impl_processor(process_param(value, dialect))
  1026. else:
  1027. def process(value):
  1028. return process_param(value, dialect)
  1029. return process
  1030. else:
  1031. return self.impl.bind_processor(dialect)
  1032. @util.memoized_property
  1033. def _has_result_processor(self):
  1034. """memoized boolean, check if process_result_value is implemented.
  1035. Allows the base process_result_value to raise
  1036. NotImplementedError without needing to test an expensive
  1037. exception throw.
  1038. """
  1039. return util.method_is_overridden(
  1040. self, TypeDecorator.process_result_value
  1041. )
  1042. def result_processor(self, dialect, coltype):
  1043. """Provide a result value processing function for the given
  1044. :class:`.Dialect`.
  1045. This is the method that fulfills the :class:`.TypeEngine`
  1046. contract for result value conversion. :class:`.TypeDecorator`
  1047. will wrap a user-defined implementation of
  1048. :meth:`process_result_value` here.
  1049. User-defined code can override this method directly,
  1050. though its likely best to use :meth:`process_result_value` so that
  1051. the processing provided by ``self.impl`` is maintained.
  1052. :param dialect: Dialect instance in use.
  1053. :param coltype: A SQLAlchemy data type
  1054. This method is the reverse counterpart to the
  1055. :meth:`bind_processor` method of this class.
  1056. """
  1057. if self._has_result_processor:
  1058. process_value = self.process_result_value
  1059. impl_processor = self.impl.result_processor(dialect, coltype)
  1060. if impl_processor:
  1061. def process(value):
  1062. return process_value(impl_processor(value), dialect)
  1063. else:
  1064. def process(value):
  1065. return process_value(value, dialect)
  1066. return process
  1067. else:
  1068. return self.impl.result_processor(dialect, coltype)
  1069. @util.memoized_property
  1070. def _has_bind_expression(self):
  1071. return (
  1072. util.method_is_overridden(self, TypeDecorator.bind_expression)
  1073. or self.impl._has_bind_expression
  1074. )
  1075. def bind_expression(self, bindparam):
  1076. return self.impl.bind_expression(bindparam)
  1077. @util.memoized_property
  1078. def _has_column_expression(self):
  1079. """memoized boolean, check if column_expression is implemented.
  1080. Allows the method to be skipped for the vast majority of expression
  1081. types that don't use this feature.
  1082. """
  1083. return (
  1084. util.method_is_overridden(self, TypeDecorator.column_expression)
  1085. or self.impl._has_column_expression
  1086. )
  1087. def column_expression(self, column):
  1088. return self.impl.column_expression(column)
  1089. def coerce_compared_value(self, op, value):
  1090. """Suggest a type for a 'coerced' Python value in an expression.
  1091. By default, returns self. This method is called by
  1092. the expression system when an object using this type is
  1093. on the left or right side of an expression against a plain Python
  1094. object which does not yet have a SQLAlchemy type assigned::
  1095. expr = table.c.somecolumn + 35
  1096. Where above, if ``somecolumn`` uses this type, this method will
  1097. be called with the value ``operator.add``
  1098. and ``35``. The return value is whatever SQLAlchemy type should
  1099. be used for ``35`` for this particular operation.
  1100. """
  1101. return self
  1102. def copy(self, **kw):
  1103. """Produce a copy of this :class:`.TypeDecorator` instance.
  1104. This is a shallow copy and is provided to fulfill part of
  1105. the :class:`.TypeEngine` contract. It usually does not
  1106. need to be overridden unless the user-defined :class:`.TypeDecorator`
  1107. has local state that should be deep-copied.
  1108. """
  1109. instance = self.__class__.__new__(self.__class__)
  1110. instance.__dict__.update(self.__dict__)
  1111. return instance
  1112. def get_dbapi_type(self, dbapi):
  1113. """Return the DBAPI type object represented by this
  1114. :class:`.TypeDecorator`.
  1115. By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the
  1116. underlying "impl".
  1117. """
  1118. return self.impl.get_dbapi_type(dbapi)
  1119. def compare_values(self, x, y):
  1120. """Given two values, compare them for equality.
  1121. By default this calls upon :meth:`.TypeEngine.compare_values`
  1122. of the underlying "impl", which in turn usually
  1123. uses the Python equals operator ``==``.
  1124. This function is used by the ORM to compare
  1125. an original-loaded value with an intercepted
  1126. "changed" value, to determine if a net change
  1127. has occurred.
  1128. """
  1129. return self.impl.compare_values(x, y)
  1130. @property
  1131. def sort_key_function(self):
  1132. return self.impl.sort_key_function
  1133. def __repr__(self):
  1134. return util.generic_repr(self, to_inspect=self.impl)
  1135. class Variant(TypeDecorator):
  1136. """A wrapping type that selects among a variety of
  1137. implementations based on dialect in use.
  1138. The :class:`.Variant` type is typically constructed
  1139. using the :meth:`.TypeEngine.with_variant` method.
  1140. .. seealso:: :meth:`.TypeEngine.with_variant` for an example of use.
  1141. """
  1142. cache_ok = True
  1143. def __init__(self, base, mapping):
  1144. """Construct a new :class:`.Variant`.
  1145. :param base: the base 'fallback' type
  1146. :param mapping: dictionary of string dialect names to
  1147. :class:`.TypeEngine` instances.
  1148. """
  1149. self.impl = base
  1150. self.mapping = mapping
  1151. @util.memoized_property
  1152. def _static_cache_key(self):
  1153. # TODO: needs tests in test/sql/test_compare.py
  1154. return (self.__class__,) + (
  1155. self.impl._static_cache_key,
  1156. tuple(
  1157. (key, self.mapping[key]._static_cache_key)
  1158. for key in sorted(self.mapping)
  1159. ),
  1160. )
  1161. def coerce_compared_value(self, operator, value):
  1162. result = self.impl.coerce_compared_value(operator, value)
  1163. if result is self.impl:
  1164. return self
  1165. else:
  1166. return result
  1167. def load_dialect_impl(self, dialect):
  1168. if dialect.name in self.mapping:
  1169. return self.mapping[dialect.name]
  1170. else:
  1171. return self.impl
  1172. def _set_parent(self, column, outer=False, **kw):
  1173. """Support SchemaEventTarget"""
  1174. if isinstance(self.impl, SchemaEventTarget):
  1175. self.impl._set_parent(column, **kw)
  1176. for impl in self.mapping.values():
  1177. if isinstance(impl, SchemaEventTarget):
  1178. impl._set_parent(column, **kw)
  1179. def _set_parent_with_dispatch(self, parent):
  1180. """Support SchemaEventTarget"""
  1181. if isinstance(self.impl, SchemaEventTarget):
  1182. self.impl._set_parent_with_dispatch(parent)
  1183. for impl in self.mapping.values():
  1184. if isinstance(impl, SchemaEventTarget):
  1185. impl._set_parent_with_dispatch(parent)
  1186. def with_variant(self, type_, dialect_name):
  1187. r"""Return a new :class:`.Variant` which adds the given
  1188. type + dialect name to the mapping, in addition to the
  1189. mapping present in this :class:`.Variant`.
  1190. :param type\_: a :class:`.TypeEngine` that will be selected
  1191. as a variant from the originating type, when a dialect
  1192. of the given name is in use.
  1193. :param dialect_name: base name of the dialect which uses
  1194. this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
  1195. """
  1196. if dialect_name in self.mapping:
  1197. raise exc.ArgumentError(
  1198. "Dialect '%s' is already present in "
  1199. "the mapping for this Variant" % dialect_name
  1200. )
  1201. mapping = self.mapping.copy()
  1202. mapping[dialect_name] = type_
  1203. return Variant(self.impl, mapping)
  1204. @property
  1205. def comparator_factory(self):
  1206. """express comparison behavior in terms of the base type"""
  1207. return self.impl.comparator_factory
  1208. def _reconstitute_comparator(expression):
  1209. return expression.comparator
  1210. def to_instance(typeobj, *arg, **kw):
  1211. if typeobj is None:
  1212. return NULLTYPE
  1213. if callable(typeobj):
  1214. return typeobj(*arg, **kw)
  1215. else:
  1216. return typeobj
  1217. def adapt_type(typeobj, colspecs):
  1218. if isinstance(typeobj, type):
  1219. typeobj = typeobj()
  1220. for t in typeobj.__class__.__mro__[0:-1]:
  1221. try:
  1222. impltype = colspecs[t]
  1223. break
  1224. except KeyError:
  1225. pass
  1226. else:
  1227. # couldn't adapt - so just return the type itself
  1228. # (it may be a user-defined type)
  1229. return typeobj
  1230. # if we adapted the given generic type to a database-specific type,
  1231. # but it turns out the originally given "generic" type
  1232. # is actually a subclass of our resulting type, then we were already
  1233. # given a more specific type than that required; so use that.
  1234. if issubclass(typeobj.__class__, impltype):
  1235. return typeobj
  1236. return typeobj.adapt(impltype)