U a@sdZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z d Z d Z d Zd Zd Zd Zd Zd ZGd d d eZGd dde je ZGddde eeZGdddeZGdddeZGdddeeZGdddeZddZddZddZ d S)zBase types API. ) operators)SchemaEventTarget)NO_CACHE) Traversible)TraversibleType)exc)utilNc@seZdZdZdZdZdZdZdZdZ Gddde j Z dZ e ZdZdZddZd d Zd d Zd dZddZddZddZddZejddZddZejddZeddZdd Z d!d"Z!e"d#d$Z#d%d&Z$ejd'd(Z%ejd)d*Z&dNd+d,Z'd-d.Z(d/d0Z)d1d2Z*d3d4Z+d5d6Z,d7d8Z-d9d:Z.d;d<Z/ejd=d>Z0d?d@Z1dAdBZ2dCdDZ3dOdEdFZ4e5dGdHdIZ6dJdKZ7dLdMZ8dS)P TypeEnginea1The ultimate base class for all SQL datatypes. Common subclasses of :class:`.TypeEngine` include :class:`.String`, :class:`.Integer`, and :class:`.Boolean`. For an overview of the SQLAlchemy typing system, see :ref:`types_toplevel`. .. seealso:: :ref:`types_toplevel` TFc@s\eZdZdZdZdZddZddZe dd d Z e dd d Z d dZ ddZ dS)zTypeEngine.ComparatorzBase class for custom comparison operations defined at the type level. See :attr:`.TypeEngine.comparator_factory`. exprtypeNcCs|jSN)r selfrXC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\sql\type_api.py__clause_element__Asz(TypeEngine.Comparator.__clause_element__cCs||_|j|_dSrr )rr rrr__init__DszTypeEngine.Comparator.__init__z!sqlalchemy.sql.default_comparatorcOs8tjj}|j|j}|d|j|f||dd|S)Nrr preloadedZsql_default_comparatorZoperator_lookup__name__r ropotherkwargsdefault_comparatororrroperateHs zTypeEngine.Comparator.operatecKs>tjj}|j|j}|d|j||f|ddddi|S)NrrreverseTrrrrrreverse_operateNs z%TypeEngine.Comparator.reverse_operatecCs ||jfS)aOevaluate the return type of , and apply any adaptations to the given operator. This method determines the type of a resulting binary expression given two source types and an operator. For example, two :class:`_schema.Column` objects, both of the type :class:`.Integer`, will produce a :class:`.BinaryExpression` that also has the type :class:`.Integer` when compared via the addition (``+``) operator. However, using the addition operator with an :class:`.Integer` and a :class:`.Date` object will produce a :class:`.Date`, assuming "days delta" behavior by the database (in reality, most databases other than PostgreSQL don't accept this particular operation). The method returns a tuple of the form , . The resulting operator and type will be those applied to the resulting :class:`.BinaryExpression` as the final operator and the right-hand side of the expression. Note that only a subset of operators make usage of :meth:`._adapt_expression`, including math operators and user-defined operators, but not boolean comparison or special SQL keywords like MATCH or BETWEEN. )r )rrZother_comparatorrrr_adapt_expressionTsz'TypeEngine.Comparator._adapt_expressioncCs t|jffSr)_reconstitute_comparatorr rrrr __reduce__qsz TypeEngine.Comparator.__reduce__)r __module__ __qualname____doc__ __slots__rrrr preload_modulerr!r"r$rrrr Comparator6s  r*NcCs|}d|_|S)aReturn a copy of this type which has the :attr:`.should_evaluate_none` flag set to True. E.g.:: Table( 'some_table', metadata, Column( String(50).evaluates_none(), nullable=True, server_default='no value') ) The ORM uses this flag to indicate that a positive value of ``None`` is passed to the column in an INSERT statement, rather than omitting the column from the INSERT statement which has the effect of firing off column-level defaults. It also allows for types which have special behavior associated with the Python None value to indicate that the value doesn't necessarily translate into SQL NULL; a prime example of this is a JSON type which may wish to persist the JSON value ``'null'``. In all cases, the actual NULL SQL value can be always be persisted in any column by using the :obj:`_expression.null` SQL construct in an INSERT statement or associated with an ORM-mapped attribute. .. note:: The "evaluates none" flag does **not** apply to a value of ``None`` passed to :paramref:`_schema.Column.default` or :paramref:`_schema.Column.server_default`; in these cases, ``None`` still means "no default". .. versionadded:: 1.1 .. seealso:: :ref:`session_forcing_null` - in the ORM documentation :paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON interaction with this flag. :attr:`.TypeEngine.should_evaluate_none` - class-level flag T)copyshould_evaluate_none)rtyprrrevaluates_nones0zTypeEngine.evaluates_nonecKs ||jSr)adapt __class__)rkwrrrr+szTypeEngine.copycCsdS)aCompare this type against the given backend type. This function is currently not implemented for SQLAlchemy types, and for all built in types will return ``None``. However, it can be implemented by a user-defined type where it can be consumed by schema comparison tools such as Alembic autogenerate. A future release of SQLAlchemy will potentially implement this method for builtin types as well. The function should return True if this type is equivalent to the given type; the type is typically reflected from the database so should be database specific. The dialect in use is also passed. It can also return False to assert that the type is not equivalent. :param dialect: a :class:`.Dialect` that is involved in the comparison. :param conn_type: the type object reflected from the backend. .. versionadded:: 1.0.3 Nr)rdialectZ conn_typerrrcompare_against_backendsz"TypeEngine.compare_against_backendcCs|Srr)rvaluerrr copy_valueszTypeEngine.copy_valuecCsdS)azReturn a conversion function for processing literal values that are to be rendered directly without using binds. This function is used when the compiler makes use of the "literal_binds" flag, typically used in DDL generation as well as in certain scenarios where backends don't accept bound parameters. .. versionadded:: 0.9.0 Nrrr2rrrliteral_processor s zTypeEngine.literal_processorcCsdS)aeReturn a conversion function for processing bind values. Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API. If processing is not necessary, the method should return ``None``. :param dialect: Dialect instance in use. Nrr6rrrbind_processors zTypeEngine.bind_processorcCsdS)aReturn a conversion function for processing result row values. Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user. If processing is not necessary, the method should return ``None``. :param dialect: Dialect instance in use. :param coltype: DBAPI coltype argument received in cursor.description. Nr)rr2coltyperrrresult_processor$szTypeEngine.result_processorcCsdS)aGiven a SELECT column expression, return a wrapping SQL expression. This is typically a SQL function that wraps a column expression as rendered in the columns clause of a SELECT statement. It is used for special data types that require columns to be wrapped in some special database function in order to coerce the value before being sent back to the application. It is the SQL analogue of the :meth:`.TypeEngine.result_processor` method. The method is evaluated at statement compile time, as opposed to statement construction time. .. seealso:: :ref:`types_sql_value_processing` Nr)rZcolexprrrrcolumn_expression4szTypeEngine.column_expressioncCs|jjjtjjk Szmemoized boolean, check if column_expression is implemented. Allows the method to be skipped for the vast majority of expression types that don't use this feature. )r0r;__code__r rrrr_has_column_expressionJs z!TypeEngine._has_column_expressioncCsdS)aGiven a bind value (i.e. a :class:`.BindParameter` instance), return a SQL expression in its place. This is typically a SQL function that wraps the existing bound parameter within the statement. It is used for special data types that require literals being wrapped in some special database function in order to coerce an application-level value into a database-specific format. It is the SQL analogue of the :meth:`.TypeEngine.bind_processor` method. The method is evaluated at statement compile time, as opposed to statement construction time. Note that this method, when implemented, should always return the exact same structure, without any conditional logic, as it may be used in an executemany() call against an arbitrary number of bound parameter sets. .. seealso:: :ref:`types_sql_value_processing` Nr)rZ bindvaluerrrbind_expressionXszTypeEngine.bind_expressioncCst|tjS)zmemoized boolean, check if bind_expression is implemented. Allows the method to be skipped for the vast majority of expression types that don't use this feature. )r method_is_overriddenr r?rrrr_has_bind_expressionrs zTypeEngine._has_bind_expressioncCst|Sr) to_instance) cls_or_selfrrr _to_instance}szTypeEngine._to_instancecCs||kS)z Compare two values for equality.rrxyrrrcompare_valuesszTypeEngine.compare_valuescCsdS)zReturn the corresponding type object from the underlying DB-API, if any. This can be useful for calling ``setinputsizes()``, for example. NrrZdbapirrrget_dbapi_typeszTypeEngine.get_dbapi_typecCs tdS)aReturn the Python type object expected to be returned by instances of this type, if known. Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like ``int`` for example), will return that type. If a return type is not defined, raises ``NotImplementedError``. Note that any type also accommodates NULL in SQL which means you can also get back ``None`` from any type in practice. NNotImplementedErrorrrrr python_typeszTypeEngine.python_typecCst||t|iS)aProduce a new type object that will utilize the given type when applied to the dialect of the given name. e.g.:: from sqlalchemy.types import String from sqlalchemy.dialects import mysql s = String() s = s.with_variant(mysql.VARCHAR(collation='foo'), 'mysql') The construction of :meth:`.TypeEngine.with_variant` is always from the "fallback" type to that which is dialect specific. The returned type is an instance of :class:`.Variant`, which itself provides a :meth:`.Variant.with_variant` that can be called repeatedly. :param type\_: a :class:`.TypeEngine` that will be selected as a variant from the originating type, when a dialect of the given name is in use. :param dialect_name: base name of the dialect which uses this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.) )VariantrB)rtype_ dialect_namerrr with_variantszTypeEngine.with_variantcCs>d}|jjD]*}|ttfkr$|St|ttfr |}q |jS)zRReturn a rudimental 'affinity' value expressing the general class of type.N)r0__mro__r UserDefinedType issubclass)rr-trrr_type_affinitys  zTypeEngine._type_affinitycCsd}d}t|ttfs|jS|jjD]T}|jdkr$t|tr$|tk r$|jddkr$|jrf|sf|}q$|js$|s$|}q$|p|pt jS)N)zsqlalchemy.sql.sqltypeszsqlalchemy.sql.type_apir_) isinstancer rSr0rRr%rTrisupperNULLTYPE)rZbest_camelcaseZbest_uppercaserUrrr_generic_type_affinitys(   z!TypeEngine._generic_type_affinitycCs<|s.|jtjkr.td|jjd|jjt||jS)a Return an instance of the generic type corresponding to this type using heuristic rule. The method may be overridden if this heuristic rule is not sufficient. >>> from sqlalchemy.dialects.mysql import INTEGER >>> INTEGER(display_width=4).as_generic() Integer() >>> from sqlalchemy.dialects.mysql import NVARCHAR >>> NVARCHAR(length=100).as_generic() Unicode(length=100) .. versionadded:: 1.4.0b2 .. seealso:: :ref:`metadata_reflection_dbagnostic_types` - describes the use of :meth:`_types.TypeEngine.as_generic` in conjunction with the :meth:`_sql.DDLEvents.column_reflect` event, which is its intended use. zDefault TypeEngine.as_generic() heuristic method was unsuccessful for {}. A custom as_generic() method must be implemented for this type class..) r[rZr0rLformatr%rr constructor_copy)rZallow_nulltyperrr as_generics  zTypeEngine.as_genericcCs8z|j|dWStk r2||dYSXdS)zYReturn a dialect-specific implementation for this :class:`.TypeEngine`. implN _type_memosKeyError _dialect_infor6rrr dialect_implszTypeEngine.dialect_implcCs ||S)aReturn the 'unwrapped' dialect impl for this type. For a type that applies wrapping logic (e.g. TypeDecorator), give us the real, actual dialect-level type that is used. This is used by TypeDecorator itself as well at least one case where dialects need to check that a particular specific dialect-level type is in use, within the :meth:`.DefaultDialect.set_input_sizes` method. )rer6rrr_unwrapped_dialect_impls z"TypeEngine._unwrapped_dialect_implcCsJz|j|dWStk r$YnX||}|d||d<}|S)z:Return a dialect-specific literal processor for this type.literalr`)rbrcrdr7)rr2dlprrr_cached_literal_processor&s z$TypeEngine._cached_literal_processorcCsJz|j|dWStk r$YnX||}|d||d<}|S)z7Return a dialect-specific bind processor for this type.bindr`)rbrcrdr8)rr2rhZbprrr_cached_bind_processor2s z!TypeEngine._cached_bind_processorcCsLz|j||WStk r$YnX||}|d||||<}|S)z9Return a dialect-specific result processor for this type.r`)rbrcrdr:)rr2r9rhrprrr_cached_result_processor?s z#TypeEngine._cached_result_processorcCsLz|j||WStk r$YnX||}|d}||||<}|S)Nr`ra)rr2keyfnrhr`resultrrr_cached_custom_processorOs z#TypeEngine._cached_custom_processorcCsZ||jkr|j|S||}||kr4|t|}||k s@td|i|j|<}|SdS)zReturn a dialect-specific registry which caches a dialect-specific implementation, bind processing function, and one or more result processing functions.r`N)rb_gen_dialect_implr/r AssertionError)rr2r`rhrrrrd[s    zTypeEngine._dialect_infocCs ||Sr)type_descriptorr6rrrrskszTypeEngine._gen_dialect_implcs*tj}jftfdd|DS)Nc3sL|]D}|jkr|ds|tj|tr8j|jnj|fVqdS)rWN)__dict__ startswithrXr _static_cache_key).0krrr qs z/TypeEngine._static_cache_key..)r Zget_cls_kwargsr0tuple)rnamesrrrrxns zTypeEngine._static_cache_keycKstj||f|S)zProduce an "adapted" form of this type, given an "impl" class to work with. This method is used internally to associate generic types with "implementation" types that are specific to a particular dialect. )r r^)rclsr1rrrr/|szTypeEngine.adaptcCs(t|}|tks|j|jkr |S|SdS)aoSuggest a type for a 'coerced' Python value in an expression. Given an operator and value, gives the type a chance to return a type which the value should be coerced into. The default behavior here is conservative; if the right-hand side is already coerced into a SQL type based on its Python type, it is usually left alone. End-user functionality extension here should generally be via :class:`.TypeDecorator`, which provides more liberal behavior in that it defaults to coercing the other side of the expression into this type, thus applying special Python conversions above and beyond those needed by the DBAPI to both ides. It also provides the public method :meth:`.TypeDecorator.coerce_compared_value` which is intended for end-user customization of this behavior. N)_resolve_value_to_typerZrV)rrr4Z _coerced_typerrrcoerce_compared_values z TypeEngine.coerce_compared_valuecCs |j|jkSr)rV)rrrrr_compare_type_affinitysz!TypeEngine._compare_type_affinitycCs|s |}|j|S)zProduce a string-compiled form of this :class:`.TypeEngine`. When called with no arguments, uses a "default" dialect to produce a string result. :param dialect: a :class:`.Dialect` instance. )_default_dialectZ type_compilerprocessr6rrrcompiles zTypeEngine.compilezsqlalchemy.engine.defaultcCstjj}|Sr)r rZengine_defaultZStrCompileDialect)rdefaultrrrrszTypeEngine._default_dialectcCs*tjrt|ddSt|SdS)Nasciibackslashreplace)r Zpy2kunicoderencodestrrrrr__str__s  zTypeEngine.__str__cCs t|Sr)r generic_reprrrrr__repr__szTypeEngine.__repr__)F)N)9rr%r&r'Z _sqla_typeZ_isnullZ_is_tuple_typeZ_is_table_valueZ _is_array_is_type_decoratorrZColumnOperatorsr*Zhashablecomparator_factorysort_key_functionr,r.r+r3r5r7r8r:r;r memoized_propertyr>r?rA staticmethodrDrHrJpropertyrMrQrVr[r_rerfrjrlrnrrrdrsrxr/rrrr)rrrrrrrr sn> 4         (        r c@s eZdZdS)VisitableCheckKWArgN)rr%r&rrrrrsrc@s eZdZdZdZdZddZdS)rSaBase for user defined types. This should be the base of new types. Note that for most cases, :class:`.TypeDecorator` is probably more appropriate:: import sqlalchemy.types as types class MyType(types.UserDefinedType): def __init__(self, precision = 8): self.precision = precision def get_col_spec(self, **kw): return "MYTYPE(%s)" % self.precision def bind_processor(self, dialect): def process(value): return value return process def result_processor(self, dialect, coltype): def process(value): return value return process Once the type is made, it's immediately usable:: table = Table('foo', meta, Column('id', Integer, primary_key=True), Column('data', MyType(16)) ) The ``get_col_spec()`` method will in most cases receive a keyword argument ``type_expression`` which refers to the owning expression of the type as being compiled, such as a :class:`_schema.Column` or :func:`.cast` construct. This keyword is only sent if the method accepts keyword arguments (e.g. ``**kw``) in its argument signature; introspection is used to check for this in order to support legacy forms of this function. .. versionadded:: 1.0.0 the owning expression is passed to the ``get_col_spec()`` method via the keyword argument ``type_expression``, if it receives ``**kw`` in its signature. Z user_definedZ get_col_speccCs|S)aSuggest a type for a 'coerced' Python value in an expression. Default behavior for :class:`.UserDefinedType` is the same as that of :class:`.TypeDecorator`; by default it returns ``self``, assuming the compared value should be coerced into the same type as this one. See :meth:`.TypeDecorator.coerce_compared_value` for more detail. rrrr4rrrrs z%UserDefinedType.coerce_compared_valueN)rr%r&r'__visit_name__Z ensure_kwargrrrrrrSs.rScs,eZdZdZfddZfddZZS)EmulatedaMixin for base types that emulate the behavior of a DB-native type. An :class:`.Emulated` type will use an available database type in conjunction with Python-side routines and/or database constraints in order to approximate the behavior of a database type that is provided natively by some backends. When a native-providing backend is in use, the native version of the type is used. This native version should include the :class:`.NativeForEmulated` mixin to allow it to be distinguished from :class:`.Emulated`. Current examples of :class:`.Emulated` are: :class:`.Interval`, :class:`.Enum`, :class:`.Boolean`. .. versionadded:: 1.2.0b3 c stt|j|f|S)aGiven an impl class, adapt this type to the impl assuming "emulated". The impl should also be an "emulated" version of this type, most likely the same class as this type itself. e.g.: sqltypes.Enum adapts to the Enum class. )superrr/rimpltyper1r0rradapt_to_emulateds zEmulated.adapt_to_emulatedc s`t|dr.|jr|j|f|S|j|f|Sn.t||jrH|j|f|Stt|j |f|SdS)Nadapt_emulated_to_native) hasattrZnativeradapt_native_to_emulatedrTr0rrrr/rrrrr/)s  zEmulated.adapt)rr%r&r'rr/ __classcell__rrrrr s rc@s(eZdZdZeddZeddZdS)NativeForEmulatedzgIndicates DB-native types supported by an :class:`.Emulated` type. .. versionadded:: 1.2.0b3 cKs|j}|j|f|S)zZGiven an impl, adapt this type's class to the impl assuming "emulated". )r0r/)r~r`r1rrrrrBsz*NativeForEmulated.adapt_native_to_emulatedcKs |f|S)zGiven an impl, adapt this type's class to the impl assuming "native". The impl will be an :class:`.Emulated` class but not a :class:`.NativeForEmulated`. e.g.: postgresql.ENUM produces a type given an Enum instance. r)r~r`r1rrrrLs z*NativeForEmulated.adapt_emulated_to_nativeN)rr%r&r' classmethodrrrrrrr;s  rcsfeZdZdZdZdZddZejfZ dZ Gddde j Z e d d Ze fd d Zd dZe ddZdDfdd ZfddZddZddZddZddZddZd d!Zd"d#Zejd$d%Zejd&d'Zd(d)Zd*d+Zejd,d-Z d.d/Z!ejd0d1Z"d2d3Z#ejd4d5Z$d6d7Z%d8d9Z&d:d;Z'dd?Z)e d@dAZ*dBdCZ+Z,S)E TypeDecoratoraAllows the creation of types which add additional functionality to an existing type. This method is preferred to direct subclassing of SQLAlchemy's built-in types as it ensures that all required functionality of the underlying type is kept in place. Typical usage:: import sqlalchemy.types as types class MyType(types.TypeDecorator): '''Prefixes Unicode values with "PREFIX:" on the way in and strips it off on the way out. ''' impl = types.Unicode cache_ok = True def process_bind_param(self, value, dialect): return "PREFIX:" + value def process_result_value(self, value, dialect): return value[7:] def copy(self, **kw): return MyType(self.impl.length) The class-level ``impl`` attribute is required, and can reference any :class:`.TypeEngine` class. Alternatively, the :meth:`load_dialect_impl` method can be used to provide different type classes based on the dialect given; in this case, the ``impl`` variable can reference ``TypeEngine`` as a placeholder. The :attr:`.TypeDecorator.cache_ok` class-level flag indicates if this custom :class:`.TypeDecorator` is safe to be used as part of a cache key. This flag defaults to ``None`` which will initially generate a warning when the SQL compiler attempts to generate a cache key for a statement that uses this type. If the :class:`.TypeDecorator` is not guaranteed to produce the same bind/result behavior and SQL generation every time, this flag should be set to ``False``; otherwise if the class produces the same behavior each time, it may be set to ``True``. See :attr:`.TypeDecorator.cache_ok` for further notes on how this works. Types that receive a Python type that isn't similar to the ultimate type used may want to define the :meth:`TypeDecorator.coerce_compared_value` method. This is used to give the expression system a hint when coercing Python objects into bind parameters within expressions. Consider this expression:: mytable.c.somecol + datetime.date(2009, 5, 15) Above, if "somecol" is an ``Integer`` variant, it makes sense that we're doing date arithmetic, where above is usually interpreted by databases as adding a number of days to the given date. The expression system does the right thing by not attempting to coerce the "date()" value into an integer-oriented bind parameter. However, in the case of ``TypeDecorator``, we are usually changing an incoming Python type to something new - ``TypeDecorator`` by default will "coerce" the non-typed side to be the same type as itself. Such as below, we define an "epoch" type that stores a date value as an integer:: class MyEpochType(types.TypeDecorator): impl = types.Integer epoch = datetime.date(1970, 1, 1) def process_bind_param(self, value, dialect): return (value - self.epoch).days def process_result_value(self, value, dialect): return self.epoch + timedelta(days=value) Our expression of ``somecol + date`` with the above type will coerce the "date" on the right side to also be treated as ``MyEpochType``. This behavior can be overridden via the :meth:`~TypeDecorator.coerce_compared_value` method, which returns a type that should be used for the value of the expression. Below we set it such that an integer value will be treated as an ``Integer``, and any other value is assumed to be a date and will be treated as a ``MyEpochType``:: def coerce_compared_value(self, op, value): if isinstance(value, int): return Integer() else: return self .. warning:: Note that the **behavior of coerce_compared_value is not inherited by default from that of the base type**. If the :class:`.TypeDecorator` is augmenting a type that requires special logic for certain types of operators, this method **must** be overridden. A key example is when decorating the :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types; the default rules of :meth:`.TypeEngine.coerce_compared_value` should be used in order to deal with operators like index operations:: class MyJsonType(TypeDecorator): impl = postgresql.JSON cache_ok = True def coerce_compared_value(self, op, value): return self.impl.coerce_compared_value(op, value) Without the above step, index operations such as ``mycol['foo']`` will cause the index value ``'foo'`` to be JSON encoded. Ztype_decoratorTcOs.t|jdstdt|jjf|||_dS)aConstruct a :class:`.TypeDecorator`. Arguments sent here are passed to the constructor of the class assigned to the ``impl`` class level attribute, assuming the ``impl`` is a callable, and the resulting object is assigned to the ``self.impl`` instance attribute (thus overriding the class attribute of the same name). If the class level ``impl`` is not a callable (the unusual case), it will be assigned to the same instance attribute 'as-is', ignoring those arguments passed to the constructor. Subclasses can override this to customize the generation of ``self.impl`` entirely. r`zuTypeDecorator implementations require a class-level variable 'impl' which refers to the class of type being decoratedN)rr0rtrBr`)rargsrrrrrs  zTypeDecorator.__init__Ncs0eZdZdZdZfddZfddZZS)zTypeDecorator.ComparatorzA :class:`.TypeEngine.Comparator` that is specific to :class:`.TypeDecorator`. User-defined :class:`.TypeDecorator` classes should not typically need to modify this. rcs(|jjj|d<ttj|j|f||SNZ_python_is_types)r r coerce_to_is_typesrrr*rrrrrrrrr1s z TypeDecorator.Comparator.operatec s&|jjj|d<ttj|j||f|Sr)r r rrrr*r!rrrrr!7s z(TypeDecorator.Comparator.reverse_operate)rr%r&r'r(rr!rrrrrr*%s  r*cCs2tj|jjjkr|jjStdtj|jjfiSdS)NZ TDComparator)rr*r`rrRr rrrrr=s z TypeDecorator.comparator_factorycs4|jdkrtd|n|jdkr0tt|jStS)NzTypeDecorator %r will not produce a cache key because the ``cache_ok`` flag is not set to True. Set this flag to True if this type object's state is safe to use in a cache key, or False to disable this warning.T)cache_okr warnrrrxrrrrrrxHs   zTypeDecorator._static_cache_keycCsV||}||k r|S|||}|}t||jsLtd||jf||_|S) #todo zaType object %s does not properly implement the copy() method, it must return an object of type %s)ruload_dialect_implrer+rXr0rtr`)rr2adaptedZtypedescttrrrrsWs  zTypeDecorator._gen_dialect_implcCs|jjS)r)r`rVrrrrrVmszTypeDecorator._type_affinityFc s<tt|||s8t|jtr8|jj|fddi|dS)Support SchemaEventTargetouterFN)rr _set_parentrXr`r)rcolumnrr1rrrrtszTypeDecorator._set_parentcs0tt|j|ddt|jtr,|j|dS)rT)rN)rr_set_parent_with_dispatchrXr`r)rparentrrrr|s   z'TypeDecorator._set_parent_with_dispatchcCs*||}t|t|s|S||SdS)asReturn a dialect-specific :class:`.TypeEngine` instance for this :class:`.TypeDecorator`. In most cases this returns a dialect-adapted form of the :class:`.TypeEngine` type represented by ``self.impl``. Makes usage of :meth:`dialect_impl`. Behavior can be customized here by overriding :meth:`load_dialect_impl`. N)rurXr r)rr2rrrr type_engines zTypeDecorator.type_enginecCs|jS)aReturn a :class:`.TypeEngine` object corresponding to a dialect. This is an end-user override hook that can be used to provide differing types depending on the given dialect. It is used by the :class:`.TypeDecorator` implementation of :meth:`type_engine` to help determine what type should ultimately be returned for a given :class:`.TypeDecorator`. By default returns ``self.impl``. )r`r6rrrrs zTypeDecorator.load_dialect_implcCs.||}t||jr&|||S|SdS)zReturn the 'unwrapped' dialect impl for this type. This is used by the :meth:`.DefaultDialect.set_input_sizes` method. N)rerXr0r)rr2r-rrrrfs  z%TypeDecorator._unwrapped_dialect_implcCs t|j|S)zMProxy all other undefined accessors to the underlying implementation.)getattrr`)rrorrr __getattr__szTypeDecorator.__getattr__cCs tdS)aReceive a literal parameter value to be rendered inline within a statement. This method is used when the compiler renders a literal value without using binds, typically within DDL such as in the "server default" of a column or an expression within a CHECK constraint. The returned string will be rendered into the output string. .. versionadded:: 0.9.0 NrKrr4r2rrrprocess_literal_paramsz#TypeDecorator.process_literal_paramcCs tdS)aReceive a bound parameter value to be converted. Subclasses override this method to return the value that should be passed along to the underlying :class:`.TypeEngine` object, and from there to the DBAPI ``execute()`` method. The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic. This operation should be designed with the reverse operation in mind, which would be the process_result_value method of this class. :param value: Data to operate upon, of any type expected by this method in the subclass. Can be ``None``. :param dialect: the :class:`.Dialect` in use. NrKrrrrprocess_bind_paramsz TypeDecorator.process_bind_paramcCs tdS)aReceive a result-row column value to be converted. Subclasses should implement this method to operate on data fetched from the database. Subclasses override this method to return the value that should be passed back to the application, given a value that is already processed by the underlying :class:`.TypeEngine` object, originally from the DBAPI cursor method ``fetchone()`` or similar. The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic. :param value: Data to operate upon, of any type expected by this method in the subclass. Can be ``None``. :param dialect: the :class:`.Dialect` in use. This operation should be designed to be reversible by the "process_bind_param" method of this class. NrKrrrrprocess_result_valuesz"TypeDecorator.process_result_valuecCst|tjS)zmemoized boolean, check if process_bind_param is implemented. Allows the base process_bind_param to raise NotImplementedError without needing to test an expensive exception throw. )r r@rrrrrr_has_bind_processors z!TypeDecorator._has_bind_processorcCst|tjS)z@memoized boolean, check if process_literal_param is implemented.)r r@rrrrrr_has_literal_processor sz$TypeDecorator._has_literal_processorcsh|jr|jn|jr|jndrX|jrFfdd}nfdd}|S|jSdS)alProvide a literal processing function for the given :class:`.Dialect`. Subclasses here will typically override :meth:`.TypeDecorator.process_literal_param` instead of this method directly. By default, this method makes use of :meth:`.TypeDecorator.process_bind_param` if that method is implemented, where :meth:`.TypeDecorator.process_literal_param` is not. The rationale here is that :class:`.TypeDecorator` typically deals with Python conversions of data that are above the layer of database presentation. With the value converted by :meth:`.TypeDecorator.process_bind_param`, the underlying type will then handle whether it needs to be presented to the DBAPI as a bound parameter or to the database as an inline SQL value. .. versionadded:: 0.9.0 Ncs|Srrr4r2impl_processor process_paramrrr9sz0TypeDecorator.literal_processor..processcs |Srrrr2rrrr>s)rrrrr`r7rr2rrrrr7s zTypeDecorator.literal_processorcsP|jr@|j|jr.fdd}nfdd}|S|jSdS)aProvide a bound value processing function for the given :class:`.Dialect`. This is the method that fulfills the :class:`.TypeEngine` contract for bound value conversion. :class:`.TypeDecorator` will wrap a user-defined implementation of :meth:`process_bind_param` here. User-defined code can override this method directly, though its likely best to use :meth:`process_bind_param` so that the processing provided by ``self.impl`` is maintained. :param dialect: Dialect instance in use. This method is the reverse counterpart to the :meth:`result_processor` method of this class. cs|Srrrrrrr]sz-TypeDecorator.bind_processor..processcs |SrrrrrrrbsN)rrr`r8rrrrr8Es zTypeDecorator.bind_processorcCst|tjS)zmemoized boolean, check if process_result_value is implemented. Allows the base process_result_value to raise NotImplementedError without needing to test an expensive exception throw. )r r@rrrrrr_has_result_processoris z#TypeDecorator._has_result_processorcsT|jrB|j|j|r0fdd}nfdd}|S|j|SdS)aProvide a result value processing function for the given :class:`.Dialect`. This is the method that fulfills the :class:`.TypeEngine` contract for result value conversion. :class:`.TypeDecorator` will wrap a user-defined implementation of :meth:`process_result_value` here. User-defined code can override this method directly, though its likely best to use :meth:`process_result_value` so that the processing provided by ``self.impl`` is maintained. :param dialect: Dialect instance in use. :param coltype: A SQLAlchemy data type This method is the reverse counterpart to the :meth:`bind_processor` method of this class. cs|Srrrr2r process_valuerrrsz/TypeDecorator.result_processor..processcs |Srrr)r2rrrrsN)rrr`r:)rr2r9rrrrr:wszTypeDecorator.result_processorcCst|tjp|jjSr)r r@rr?r`rArrrrrAsz"TypeDecorator._has_bind_expressioncCs |j|Sr)r`r?)rZ bindparamrrrr?szTypeDecorator.bind_expressioncCst|tjp|jjSr<)r r@rr;r`r>rrrrr>s z$TypeDecorator._has_column_expressioncCs |j|Sr)r`r;)rrrrrr;szTypeDecorator.column_expressioncCs|S)a}Suggest a type for a 'coerced' Python value in an expression. By default, returns self. This method is called by the expression system when an object using this type is on the left or right side of an expression against a plain Python object which does not yet have a SQLAlchemy type assigned:: expr = table.c.somecolumn + 35 Where above, if ``somecolumn`` uses this type, this method will be called with the value ``operator.add`` and ``35``. The return value is whatever SQLAlchemy type should be used for ``35`` for this particular operation. rrrrrrsz#TypeDecorator.coerce_compared_valuecKs |j|j}|j|j|S)aGProduce a copy of this :class:`.TypeDecorator` instance. This is a shallow copy and is provided to fulfill part of the :class:`.TypeEngine` contract. It usually does not need to be overridden unless the user-defined :class:`.TypeDecorator` has local state that should be deep-copied. )r0__new__rvupdate)rr1instancerrrr+s zTypeDecorator.copycCs |j|S)zReturn the DBAPI type object represented by this :class:`.TypeDecorator`. By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the underlying "impl". )r`rJrIrrrrJszTypeDecorator.get_dbapi_typecCs|j||S)aGiven two values, compare them for equality. By default this calls upon :meth:`.TypeEngine.compare_values` of the underlying "impl", which in turn usually uses the Python equals operator ``==``. This function is used by the ORM to compare an original-loaded value with an intercepted "changed" value, to determine if a net change has occurred. )r`rHrErrrrHs zTypeDecorator.compare_valuescCs|jjSr)r`rrrrrrszTypeDecorator.sort_key_functioncCstj||jdS)N)Z to_inspect)r rr`rrrrrszTypeDecorator.__repr__)F)-rr%r&r'rrrr ZNoneTyperrr r*rrrxrsrVrrrrrfrrrrrrrr7r8rr:rAr?r>r;rr+rJrHrrrrrrrrYsZr)     0$ %    rc@s`eZdZdZdZddZejddZddZ d d Z dd d Z ddZ ddZ eddZdS)rNaA wrapping type that selects among a variety of implementations based on dialect in use. The :class:`.Variant` type is typically constructed using the :meth:`.TypeEngine.with_variant` method. .. seealso:: :meth:`.TypeEngine.with_variant` for an example of use. TcCs||_||_dS)zConstruct a new :class:`.Variant`. :param base: the base 'fallback' type :param mapping: dictionary of string dialect names to :class:`.TypeEngine` instances. N)r`mapping)rbaserrrrrszVariant.__init__cs,jfjjtfddtjDfS)Nc3s|]}|j|jfVqdSr)rrx)ryrorrrr{sz,Variant._static_cache_key..)r0r`rxr|sortedrrrrrrxs  zVariant._static_cache_keycCs$|j||}||jkr|S|SdSr)r`r)roperatorr4rqrrrrs zVariant.coerce_compared_valuecCs"|j|jkr|j|jS|jSdSr)namerr`r6rrrr"s  zVariant.load_dialect_implFcKsHt|jtr|jj|f||jD]}t|tr&|j|f|q&dSrN)rXr`rrrvalues)rrrr1r`rrrr(s   zVariant._set_parentcCs@t|jtr|j||jD]}t|tr"||q"dSr)rXr`rrrr)rrr`rrrr1s    z!Variant._set_parent_with_dispatchcCs6||jkrtd||j}|||<t|j|S)aReturn a new :class:`.Variant` which adds the given type + dialect name to the mapping, in addition to the mapping present in this :class:`.Variant`. :param type\_: a :class:`.TypeEngine` that will be selected as a variant from the originating type, when a dialect of the given name is in use. :param dialect_name: base name of the dialect which uses this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.) z?Dialect '%s' is already present in the mapping for this Variant)rr ArgumentErrorr+rNr`)rrOrPrrrrrQ:s  zVariant.with_variantcCs|jjS)z5express comparison behavior in terms of the base type)r`rrrrrrPszVariant.comparator_factoryN)F)rr%r&r'rrr rrxrrrrrQrrrrrrrNs     rNcCs|jSr)Z comparator)Z expressionrrrr#Vsr#cOs&|dkr tSt|r|||S|SdSr)rZcallable)typeobjargr1rrrrBZs  rBc Cslt|tr|}|jjddD],}z||}WqRWq tk rJYq Xq |St|j|rb|S||S)Nr)rXr r0rRrcrTr/)rZcolspecsrUrrrr adapt_typeds   r)!r'rrrZ traversalsrZvisitorsrrrr Z BOOLEANTYPEZ INTEGERTYPErZZ STRINGTYPEZ MATCHTYPEZ INDEXABLEZ TABLEVALUErr ZEnsureKWArgTyperwith_metaclassrSobjectrrrrNr#rBrrrrrsF       ,A/$^