U aݾ@sdZddlZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z dd l m Z dd l mZdd l mZdd lmZdd lmZddlmZddlmZddlmZddlmZddl mZddl mZddl mZddl mZddl mZddl mZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl"m#Z#ddl"m$Z$dd l"m%Z%dd!l"m&Z&Gd"d#d#e'Z(Gd$d%d%e'Z)Gd&d'd'e'Z*Gd(d)d)e)eZ+Gd*d+d+e+Z,Gd,d-d-e+Z-Gd.d/d/e,Z.Gd0d1d1e(eZ/Gd2d3d3e/Z0Gd4d5d5e/Z1Gd6d7d7e(eZ2Gd8d9d9e2Z3Gd:d;d;e(eZ4Gdd?d?e(eZ6Gd@dAdAeZ7GdBdCdCe7Z8GdDdEdEeZ9GdFdGdGee+e9Z:GdHdIdIeZ;GdJdKdKeee9ZGdPdQdQe*eZ?GdRdSdSee*e)eZ@GdTdUdUeZAGdVdWdWe3ZBGdXdYdYe3ZCGdZd[d[e2ZDGd\d]d]e2ZEGd^d_d_e/ZFeFZGGd`dadae0ZHGdbdcdce1ZIGdddedee4ZJGdfdgdge4ZKGdhdidie5ZLGdjdkdke6ZMGdldmdme,ZNGdndodoe,ZOGdpdqdqe+ZPGdrdsdse-ZQGdtdudue+ZRGdvdwdwe-ZSGdxdydye8ZTGdzd{d{e7ZUGd|d}d}e7ZVGd~dde<ZWGdddeZXGdddeeZYGddde<ZZeXZ[e<Z\e+Z]e/Z^eZZ_eYZ`eae/ebe3ece\ejde2ejee5eje4ejfe6ejge>e"jhe[i Zie"jjrLe8eiek<e-eiel<ne-eiem<e+eiel<eijnZoddZpe\e _\e]e _]e^e _^e[e _[e_e __e*e _qe`e _`epe _pe\ejr_\dS)zSQL specific types. N) coercions)elements) operators)roles)type_api)_bind_or_error)NO_ARG)SchemaEventTarget) _NONE_NAME) quoted_name)Slice) TypeCoerce) HasCacheKey)InternalTraversal)Emulated)NativeForEmulated) to_instance) TypeDecorator) TypeEngine)Variant)event)exc) inspection) processors)util)compat) langhelpers) OrderedDict)picklec@s2eZdZdZeddZGdddejZeZdS)_LookupExpressionAdapterzMixin expression adaptations based on lookup tables. These rules are currently used by the numeric, integer and date types which have detailed cross-expression coercion rules. cCs tdSNNotImplementedErrorselfr'XC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\sql\sqltypes.py_expression_adaptations9sz0_LookupExpressionAdapter._expression_adaptationsc@seZdZeZddZdS)z#_LookupExpressionAdapter.ComparatorcCs\|jj}|jj||j||j}||kr6||jfS||jjkrL||jfS|t|fSdSr")type_type_affinityr)get _blank_dictr)r&opother_comparatorZ othertypelookupr'r'r(_adapt_expression@s   z5_LookupExpressionAdapter.Comparator._adapt_expressionN)__name__ __module__ __qualname__rZ immutabledictr-r1r'r'r'r( Comparator=sr5N) r2r3r4__doc__propertyr)rr5comparator_factoryr'r'r'r(r!0s  r!c@s&eZdZdZGdddejZeZdS) ConcatenablezOA mixin that marks a type as supporting 'concatenation', typically strings.cseZdZfddZZS)zConcatenable.ComparatorcsB|tjkr*t|tjtjfr*tj|jjfSt tj| ||SdSr") radd isinstancer9r5NullType concat_opexprr*superr1r&r.r/ __class__r'r(r1Us   z)Concatenable.Comparator._adapt_expressionr2r3r4r1 __classcell__r'r'rAr(r5Tsr5Nr2r3r4r6rr5r8r'r'r'r(r9Os r9c@s&eZdZdZGdddejZeZdS) IndexablezA mixin that marks a type as supporting indexing operations, such as array or JSON structures. .. versionadded:: 1.1.0 c@seZdZddZddZdS)zIndexable.ComparatorcCs tdSr"r#)r&indexr'r'r(_setup_getitemnsz#Indexable.Comparator._setup_getitemcCs ||\}}}|j|||dS)N) result_type)rHZoperate)r&rGZ adjusted_opZadjusted_right_exprrIr'r'r( __getitem__qsz Indexable.Comparator.__getitem__N)r2r3r4rHrJr'r'r'r(r5msr5NrEr'r'r'r(rFcs rFc@seZdZdZdZeddZeddZeddZ ed d Z ej d d d dddZ ddZ ddZddZeddZddZeddZdS)StringaThe base for all string and character types. In SQL, corresponds to VARCHAR. Can also take Python unicode objects and encode to the database's encoding in bind params (and the reverse for result sets.) The `length` field is usually required when the `String` type is used within a CREATE TABLE statement, as VARCHAR requires a length on most databases. stringRETURNS_UNICODEaIndicates that the DBAPI returns Python Unicode for VARCHAR, NVARCHAR, and other character-based datatypes in all cases. This is the default value for :attr:`.DefaultDialect.returns_unicode_strings` under Python 3. .. versionadded:: 1.4 RETURNS_BYTESaRIndicates that the DBAPI returns byte objects under Python 3 or non-Unicode string objects under Python 2 for VARCHAR, NVARCHAR, and other character-based datatypes in all cases. This may be applied to the :attr:`.DefaultDialect.returns_unicode_strings` attribute. .. versionadded:: 1.4 RETURNS_CONDITIONALaIndicates that the DBAPI may return Unicode or bytestrings for VARCHAR, NVARCHAR, and other character-based datatypes, and that SQLAlchemy's default String datatype will need to test on a per-row basis for Unicode or bytes. This may be applied to the :attr:`.DefaultDialect.returns_unicode_strings` attribute. .. versionadded:: 1.4 RETURNS_UNKNOWNaIndicates that the dialect should test on first connect what the string-returning behavior of character-based datatypes is. This is the default value for DefaultDialect.unicode_returns under Python 2. This may be applied to the :attr:`.DefaultDialect.returns_unicode_strings` attribute under Python 2 only. The value is disallowed under Python 3. .. versionadded:: 1.4 .. deprecated:: 1.4 This value will be removed in SQLAlchemy 2.0. )1.3zThe :paramref:`.String.convert_unicode` parameter is deprecated and will be removed in a future release. All modern DBAPIs now support Python Unicode directly and this parameter is unnecessary.)rQzThe :paramref:`.String.unicode_errors` parameter is deprecated and will be removed in a future release. This parameter is unnecessary for modern Python DBAPIs and degrades performance significantly.)convert_unicode unicode_errorNFcCs@|dk r|dkrtd||_||_|p,||_||_||_dS)aL Create a string-holding type. :param length: optional, a length for the column for use in DDL and CAST expressions. May be safely omitted if no ``CREATE TABLE`` will be issued. Certain databases may require a ``length`` for use in DDL, and will raise an exception when the ``CREATE TABLE`` DDL is issued if a ``VARCHAR`` with no length is included. Whether the value is interpreted as bytes or characters is database specific. :param collation: Optional, a column-level collation for use in DDL and CAST expressions. Renders using the COLLATE keyword supported by SQLite, MySQL, and PostgreSQL. E.g.:: >>> from sqlalchemy import cast, select, String >>> print(select(cast('some string', String(collation='utf8')))) SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1 :param convert_unicode: When set to ``True``, the :class:`.String` type will assume that input is to be passed as Python Unicode objects under Python 2, and results returned as Python Unicode objects. In the rare circumstance that the DBAPI does not support Python unicode under Python 2, SQLAlchemy will use its own encoder/decoder functionality on strings, referring to the value of the :paramref:`_sa.create_engine.encoding` parameter parameter passed to :func:`_sa.create_engine` as the encoding. For the extremely rare case that Python Unicode is to be encoded/decoded by SQLAlchemy on a backend that *does* natively support Python Unicode, the string value ``"force"`` can be passed here which will cause SQLAlchemy's encode/decode services to be used unconditionally. .. note:: SQLAlchemy's unicode-conversion flags and features only apply to Python 2; in Python 3, all string objects are Unicode objects. For this reason, as well as the fact that virtually all modern DBAPIs now support Unicode natively even under Python 2, the :paramref:`.String.convert_unicode` flag is inherently a legacy feature. .. note:: In the vast majority of cases, the :class:`.Unicode` or :class:`.UnicodeText` datatypes should be used for a :class:`_schema.Column` that expects to store non-ascii data. These datatypes will ensure that the correct types are used on the database side as well as set up the correct Unicode behaviors under Python 2. .. seealso:: :paramref:`_sa.create_engine.convert_unicode` - :class:`_engine.Engine`-wide parameter :param unicode_error: Optional, a method to use to handle Unicode conversion errors. Behaves like the ``errors`` keyword argument to the standard library's ``string.decode()`` functions, requires that :paramref:`.String.convert_unicode` is set to ``"force"`` Nforcez:convert_unicode must be 'force' when unicode_error is set.)r ArgumentErrorlength collation_expect_unicode_expect_unicode_error_warn_on_bytestring)r&rVrWrRrSrZrXr'r'r(__init__s] zString.__init__csfdd}|S)Ncs(|dd}jjr |dd}d|S)N'''%z%%'%s')replaceZidentifier_preparerZ_double_percentsvaluedialectr'r(process5s  z)String.literal_processor..processr'r&rdrer'rcr(literal_processor4s zString.literal_processorcsbjs |jrZ|jr4jdkr4jr.dd}|SdSn"t|jjfdd}|SdSdS)NrTcSs$t|tjr tdt|f|S)N6Unicode type received non-unicode bind param value %r.)r;r binary_type warn_limitedellipses_stringrar'r'r(reGs   z&String.bind_processor..processcs@t|tjr|jdSr<|dk reZdZdZdZddZeddZddZe j d d Z d S) IntegerzA type for ``int`` integers.integercCs|jSr"NUMBERryr'r'r(r{szInteger.get_dbapi_typecCstSr")intr%r'r'r(rwszInteger.python_typecCs dd}|S)NcSs tt|Sr")rvrrar'r'r(resz*Integer.literal_processor..processr'rfr'r'r(rgszInteger.literal_processorc Cs\tjttt|jttitjttt|jttitjt|jttitj t|jttitj t|jttiiSr") rr:DaterrBNumericmulIntervaldivtruedivsubr%r'r'r(r)s.   zInteger._expression_adaptationsN) r2r3r4r6rr{r7rwrgrmemoized_propertyr)r'r'r'r(r s rc@seZdZdZdZdS) SmallIntegerzA type for smaller ``int`` integers. Typically generates a ``SMALLINT`` in DDL, and otherwise acts like a normal :class:`.Integer` on the Python side. Z small_integerNrr'r'r'r(r4src@seZdZdZdZdS) BigIntegerzA type for bigger ``int`` integers. Typically generates a ``BIGINT`` in DDL, and otherwise acts like a normal :class:`.Integer` on the Python side. Z big_integerNrr'r'r'r(r@src@sheZdZdZdZdZdddZedd Zd d Z d d Z eddZ ddZ ddZ ejddZdS)raA type for fixed precision numbers, such as ``NUMERIC`` or ``DECIMAL``. This type returns Python ``decimal.Decimal`` objects by default, unless the :paramref:`.Numeric.asdecimal` flag is set to False, in which case they are coerced to Python ``float`` objects. .. note:: The :class:`.Numeric` type is designed to receive data from a database type that is explicitly known to be a decimal type (e.g. ``DECIMAL``, ``NUMERIC``, others) and not a floating point type (e.g. ``FLOAT``, ``REAL``, others). If the database column on the server is in fact a floating-point type, such as ``FLOAT`` or ``REAL``, use the :class:`.Float` type or a subclass, otherwise numeric coercion between ``float``/``Decimal`` may or may not function as expected. .. note:: The Python ``decimal.Decimal`` class is generally slow performing; cPython 3.3 has now switched to use the `cdecimal `_ library natively. For older Python versions, the ``cdecimal`` library can be patched into any application where it will replace the ``decimal`` library fully, however this needs to be applied globally and before any other modules have been imported, as follows:: import sys import cdecimal sys.modules["decimal"] = cdecimal Note that the ``cdecimal`` and ``decimal`` libraries are **not compatible with each other**, so patching ``cdecimal`` at the global level is the only way it can be used effectively with various DBAPIs that hardcode to import the ``decimal`` library. numeric NTcCs||_||_||_||_dS)a Construct a Numeric. :param precision: the numeric precision for use in DDL ``CREATE TABLE``. :param scale: the numeric scale for use in DDL ``CREATE TABLE``. :param asdecimal: default True. Return whether or not values should be sent as Python Decimal objects, or as floats. Different DBAPIs send one or the other based on datatypes - the Numeric type will ensure that return values are one or the other across DBAPIs consistently. :param decimal_return_scale: Default scale to use when converting from floats to Python decimals. Floating point values will typically be much longer due to decimal inaccuracy, and most floating point database types don't have a notion of "scale", so by default the float type looks for the first ten decimal places when converting. Specifying this value will override that length. Types which do include an explicit ".scale" value, such as the base :class:`.Numeric` as well as the MySQL float types, will use the value of ".scale" as the default for decimal_return_scale, if not otherwise specified. .. versionadded:: 0.9.0 When using the ``Numeric`` type, care should be taken to ensure that the asdecimal setting is appropriate for the DBAPI in use - when Numeric applies a conversion from Decimal->float or float-> Decimal, this conversion incurs an additional performance overhead for all result columns received. DBAPIs that return Decimal natively (e.g. psycopg2) will have better accuracy and higher performance with a setting of ``True``, as the native translation to Decimal reduces the amount of floating- point issues at play, and the Numeric type itself doesn't need to apply any further conversions. However, another DBAPI which returns floats natively *will* incur an additional conversion overhead, and is still subject to floating point data loss - in which case ``asdecimal=False`` will at least remove the extra conversion overhead. N) precisionscaledecimal_return_scale asdecimal)r&rrrrr'r'r(r[xs3zNumeric.__init__cCs0|jdk r|jSt|dddk r&|jS|jSdS)Nr)rgetattrr_default_decimal_return_scaler%r'r'r(_effective_decimal_return_scales  z'Numeric._effective_decimal_return_scalecCs|jSr"rryr'r'r(r{szNumeric.get_dbapi_typecCs dd}|S)NcSst|Sr")rvrar'r'r(resz*Numeric.literal_processor..processr'rfr'r'r(rgszNumeric.literal_processorcCs|jr tjStSdSr")rdecimalDecimalfloatr%r'r'r(rwszNumeric.python_typecCs|jr dStjSdSr")supports_native_decimalrto_floatr&rdr'r'r(rrszNumeric.bind_processorcCs\|jrH|jrdStd|j|jfttj |j dk r>|j n|j Sn|jrTtj SdSdS)NzDialect %s+%s does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.) rrrwarnnameZdriverrto_decimal_processor_factoryrrrrrr&rdrtr'r'r(rus"  zNumeric.result_processorc Csbtjttt|jt|jitjt|jt|jitjt|jt|jitjt|jt|jitj t|jt|jiiSr") rrrrrBrrrr:rr%r'r'r(r)s*zNumeric._expression_adaptations)NNNT)r2r3r4r6rrr[r7rr{rgrwrrrurrr)r'r'r'r(rLs$& 8  rc@s*eZdZdZdZdZd ddZddZdS) Floata.Type representing floating point types, such as ``FLOAT`` or ``REAL``. This type returns Python ``float`` objects by default, unless the :paramref:`.Float.asdecimal` flag is set to True, in which case they are coerced to ``decimal.Decimal`` objects. .. note:: The :class:`.Float` type is designed to receive data from a database type that is explicitly known to be a floating point type (e.g. ``FLOAT``, ``REAL``, others) and not a decimal type (e.g. ``DECIMAL``, ``NUMERIC``, others). If the database column on the server is in fact a Numeric type, such as ``DECIMAL`` or ``NUMERIC``, use the :class:`.Numeric` type or a subclass, otherwise numeric coercion between ``float``/``Decimal`` may or may not function as expected. rNFcCs||_||_||_dS)a Construct a Float. :param precision: the numeric precision for use in DDL ``CREATE TABLE``. :param asdecimal: the same flag as that of :class:`.Numeric`, but defaults to ``False``. Note that setting this flag to ``True`` results in floating point conversion. :param decimal_return_scale: Default scale to use when converting from floats to Python decimals. Floating point values will typically be much longer due to decimal inaccuracy, and most floating point database types don't have a notion of "scale", so by default the float type looks for the first ten decimal places when converting. Specifying this value will override that length. Note that the MySQL float types, which do include "scale", will use "scale" as the default for decimal_return_scale, if not otherwise specified. .. versionadded:: 0.9.0 N)rrr)r&rrrr'r'r(r[szFloat.__init__cCs*|jrttj|jS|jr"tjSdSdSr")rrrrrrrrrr'r'r(ru4szFloat.result_processor)NFN)r2r3r4r6rrr[rur'r'r'r(rs rc@s@eZdZdZdZd ddZddZedd Ze j d d Z d S)DateTimeaA type for ``datetime.datetime()`` objects. Date and time types return objects from the Python ``datetime`` module. Most DBAPIs have built in support for the datetime module, with the noted exception of SQLite. In the case of SQLite, date and time types are stored as strings which are then converted back to datetime objects when rows are returned. For the time representation within the datetime type, some backends include additional options, such as timezone support and fractional seconds support. For fractional seconds, use the dialect-specific datatype, such as :class:`.mysql.TIME`. For timezone support, use at least the :class:`_types.TIMESTAMP` datatype, if not the dialect-specific datatype object. datetimeFcCs ||_dS)aConstruct a new :class:`.DateTime`. :param timezone: boolean. Indicates that the datetime type should enable timezone support, if available on the **base date/time-holding type only**. It is recommended to make use of the :class:`_types.TIMESTAMP` datatype directly when using this flag, as some databases include separate generic date/time-holding types distinct from the timezone-capable TIMESTAMP datatype, such as Oracle. Ntimezoner&rr'r'r(r[Ts zDateTime.__init__cCs|jSr"DATETIMEryr'r'r(r{cszDateTime.get_dbapi_typecCstjSr")dtrr%r'r'r(rwfszDateTime.python_typecCs tjt|jitjt|jttiiSr")rr:rrBrrr%r'r'r(r)js  z DateTime._expression_adaptationsN)F r2r3r4r6rr[r{r7rwrrr)r'r'r'r(r?s  rc@s6eZdZdZdZddZeddZej ddZ d S) rz'A type for ``datetime.date()`` objects.datecCs|jSr"rryr'r'r(r{|szDate.get_dbapi_typecCstjSr")rrr%r'r'r(rwszDate.python_typec Cs0tjt|jttttitjt|jttttttiiSr") rr:rrBrrTimerrr%r'r'r(r)s&zDate._expression_adaptationsN) r2r3r4r6rr{r7rwrrr)r'r'r'r(rvs rc@s@eZdZdZdZd ddZddZedd Ze j d d Z d S)rz'A type for ``datetime.time()`` objects.timeFcCs ||_dSr"rrr'r'r(r[sz Time.__init__cCs|jSr"rryr'r'r(r{szTime.get_dbapi_typecCstjSr")rrr%r'r'r(rwszTime.python_typecCs$tjttt|jitjttt|jiiSr")rr:rrrrBrrr%r'r'r(r)s   zTime._expression_adaptationsN)Frr'r'r'r(rs  rcsfeZdZdZdddZddZeddZd d Ze j rBd d Z nd d Z fddZ ddZ ZS)_Binaryz&Define base behavior for binary types.NcCs ||_dSr"rVr&rVr'r'r(r[sz_Binary.__init__csfdd}|S)Ncs|jdd}d|S)Nr\r]r_)decoderqr`rarcr'r(resz*_Binary.literal_processor..processr'rfr'rcr(rgs z_Binary.literal_processorcCstjSr")rrir%r'r'r(rwsz_Binary.python_typecs&|jdkrdS|jjfdd}|S)Ncs|dk r|SdSdSr"r'raZ DBAPIBinaryr'r(resz'_Binary.bind_processor..process)rzBinaryrfr'rr(rrs   z_Binary.bind_processorcCstjSr")rZto_strrr'r'r(rusz_Binary.result_processorcCs dd}|S)NcSs|dk rt|}|Sr")bytesrar'r'r(resz)_Binary.result_processor..processr'r&rdrtrer'r'r(ruscs&t|tjr|Stt|||SdS)@See :meth:`.TypeEngine.coerce_compared_value` for a description.N)r;r string_typesr?rcoerce_compared_valuer&r.rbrAr'r(rs z_Binary.coerce_compared_valuecCs|jSr")BINARYryr'r'r(r{sz_Binary.get_dbapi_type)N)r2r3r4r6r[rgr7rwrrrZpy2krurr{rDr'r'rAr(rs    rc@seZdZdZdZdddZdS) LargeBinarya A type for large binary byte data. The :class:`.LargeBinary` type corresponds to a large and/or unlengthed binary type for the target platform, such as BLOB on MySQL and BYTEA for PostgreSQL. It also handles the necessary conversions for the DBAPI. Z large_binaryNcCstj||ddS)z Construct a LargeBinary type. :param length: optional, a length for the column for use in DDL statements, for those binary types that accept a length, such as the MySQL BLOB type. rN)rr[rr'r'r(r[s zLargeBinary.__init__)N)r2r3r4r6rr[r'r'r'r(rsrc@seZdZdZdZd!ddZddZd d Zd d Zd dZ ddZ e ddZ d"ddZ d#ddZddZddZddZddZdd ZdS)$ SchemaTypeabMark a type as possibly requiring schema-level DDL for usage. Supports types that must be explicitly created/dropped (i.e. PG ENUM type) as well as types that are complimented by table or schema level constraints, triggers, and other rules. :class:`.SchemaType` classes can also be targets for the :meth:`.DDLEvents.before_parent_attach` and :meth:`.DDLEvents.after_parent_attach` events, where the events fire off surrounding the association of the type object with a parent :class:`_schema.Column`. .. seealso:: :class:`.Enum` :class:`.Boolean` TNFcCsr|dk rt|||_nd|_||_||_||_||_|rn|jrnt|jdt |j t|jdt |j dS)N before_create after_drop) r rschemametadatainherit_schema_create_eventsrlistenrportable_instancemethod_on_metadata_create_on_metadata_drop)r&rrrrquoterr'r'r(r[(s$    zSchemaType.__init__cKs|t|jdSr")Z_on_table_attachrr _set_table)r&columnkwr'r'r( _set_parentFszSchemaType._set_parentcCs.t|jtr&|jj}|jj|d<nd}|S)N_default)r;r*rmappingcopyimpl)r&rvariant_mappingr'r'r(_variant_mapping_for_set_tableIs   z)SchemaType._variant_mapping_for_set_tablec Cs|jr|j|_n"|jr2|jdkr2|jjr2|jj|_|js._we_are_the_implr)rr)r&rdrrrr'r%r(rs    zSchemaType._is_impl_for_variant)NNNFNT)NF)NF)r2r3r4r6Z_use_schema_mapr[rrrrrr7rrrrrrrrr'r'r'r(rs. -   rcseZdZdZdZejddddZeddZ fd d Z d d Z d dZ eddZ eddZddZGdddejZeZddZddZd1ddZddZfd d!Zd"d#Zed$d%d&Zfd'd(Zfd)d*Zfd+d,Zd-d.Zefd/d0ZZ S)2Enuma Generic Enum Type. The :class:`.Enum` type provides a set of possible string values which the column is constrained towards. The :class:`.Enum` type will make use of the backend's native "ENUM" type if one is available; otherwise, it uses a VARCHAR datatype. An option also exists to automatically produce a CHECK constraint when the VARCHAR (so called "non-native") variant is produced; see the :paramref:`.Enum.create_constraint` flag. The :class:`.Enum` type also provides in-Python validation of string values during both read and write operations. When reading a value from the database in a result set, the string value is always checked against the list of possible values and a ``LookupError`` is raised if no match is found. When passing a value to the database as a plain string within a SQL statement, if the :paramref:`.Enum.validate_strings` parameter is set to True, a ``LookupError`` is raised for any string value that's not located in the given list of possible values; note that this impacts usage of LIKE expressions with enumerated values (an unusual use case). .. versionchanged:: 1.1 the :class:`.Enum` type now provides in-Python validation of input values as well as on data being returned by the database. The source of enumerated values may be a list of string values, or alternatively a PEP-435-compliant enumerated class. For the purposes of the :class:`.Enum` datatype, this class need only provide a ``__members__`` method. When using an enumerated class, the enumerated objects are used both for input and output, rather than strings as is the case with a plain-string enumerated type:: import enum class MyEnum(enum.Enum): one = 1 two = 2 three = 3 t = Table( 'data', MetaData(), Column('value', Enum(MyEnum)) ) connection.execute(t.insert(), {"value": MyEnum.two}) assert connection.scalar(t.select()) is MyEnum.two Above, the string names of each element, e.g. "one", "two", "three", are persisted to the database; the values of the Python Enum, here indicated as integers, are **not** used; the value of each enum can therefore be any kind of Python object whether or not it is persistable. In order to persist the values and not the names, the :paramref:`.Enum.values_callable` parameter may be used. The value of this parameter is a user-supplied callable, which is intended to be used with a PEP-435-compliant enumerated class and returns a list of string values to be persisted. For a simple enumeration that uses string values, a callable such as ``lambda x: [e.value for e in x]`` is sufficient. .. versionadded:: 1.1 - support for PEP-435-style enumerated classes. .. seealso:: :class:`_postgresql.ENUM` - PostgreSQL-specific type, which has additional functionality. :class:`.mysql.ENUM` - MySQL-specific type enum)rQzThe :paramref:`.Enum.convert_unicode` parameter is deprecated and will be removed in a future release. All modern DBAPIs now support Python Unicode directly and this parameter is unnecessary.)rRcOs|||dS)aConstruct an enum. Keyword arguments which don't apply to a specific backend are ignored by that backend. :param \*enums: either exactly one PEP-435 compliant enumerated type or one or more string labels. .. versionadded:: 1.1 a PEP-435 style enumerated class may be passed. :param convert_unicode: Enable unicode-aware bind parameter and result-set processing for this Enum's data under Python 2 only. Under Python 2, this is set automatically based on the presence of unicode label strings. This flag will be removed in SQLAlchemy 2.0. :param create_constraint: defaults to False. When creating a non-native enumerated type, also build a CHECK constraint on the database against the valid values. .. note:: it is strongly recommended that the CHECK constraint have an explicit name in order to support schema-management concerns. This can be established either by setting the :paramref:`.Enum.name` parameter or by setting up an appropriate naming convention; see :ref:`constraint_naming_conventions` for background. .. versionchanged:: 1.4 - this flag now defaults to False, meaning no CHECK constraint is generated for a non-native enumerated type. :param metadata: Associate this type directly with a ``MetaData`` object. For types that exist on the target database as an independent schema construct (PostgreSQL), this type will be created and dropped within ``create_all()`` and ``drop_all()`` operations. If the type is not associated with any ``MetaData`` object, it will associate itself with each ``Table`` in which it is used, and will be created when any of those individual tables are created, after a check is performed for its existence. The type is only dropped when ``drop_all()`` is called for that ``Table`` object's metadata, however. The value of the :paramref:`_schema.MetaData.schema` parameter of the :class:`_schema.MetaData` object, if set, will be used as the default value of the :paramref:`_types.Enum.schema` on this object if an explicit value is not otherwise supplied. .. versionchanged:: 1.4.12 :class:`_types.Enum` inherits the :paramref:`_schema.MetaData.schema` parameter of the :class:`_schema.MetaData` object if present, when passed using the :paramref:`_types.Enum.metadata` parameter. :param name: The name of this type. This is required for PostgreSQL and any future supported database which requires an explicitly named type, or an explicitly named constraint in order to generate the type and/or a table that uses it. If a PEP-435 enumerated class was used, its name (converted to lower case) is used by default. :param native_enum: Use the database's native ENUM type when available. Defaults to True. When False, uses VARCHAR + check constraint for all backends. The VARCHAR length can be controlled with :paramref:`.Enum.length` :param length: Allows specifying a custom length for the VARCHAR when :paramref:`.Enum.native_enum` is False. By default it uses the length of the longest value. .. versionadded:: 1.3.16 :param schema: Schema name of this type. For types that exist on the target database as an independent schema construct (PostgreSQL), this parameter specifies the named schema in which the type is present. If not present, the schema name will be taken from the :class:`_schema.MetaData` collection if passed as :paramref:`_types.Enum.metadata`, for a :class:`_schema.MetaData` that includes the :paramref:`_schema.MetaData.schema` parameter. .. versionchanged:: 1.4.12 :class:`_types.Enum` inherits the :paramref:`_schema.MetaData.schema` parameter of the :class:`_schema.MetaData` object if present, when passed using the :paramref:`_types.Enum.metadata` parameter. Otherwise, if the :paramref:`_types.Enum.inherit_schema` flag is set to ``True``, the schema will be inherited from the associated :class:`_schema.Table` object if any; when :paramref:`_types.Enum.inherit_schema` is at its default of ``False``, the owning table's schema is **not** used. :param quote: Set explicit quoting preferences for the type's name. :param inherit_schema: When ``True``, the "schema" from the owning :class:`_schema.Table` will be copied to the "schema" attribute of this :class:`.Enum`, replacing whatever value was passed for the ``schema`` attribute. This also takes effect when using the :meth:`_schema.Table.to_metadata` operation. :param validate_strings: when True, string values that are being passed to the database in a SQL statement will be checked for validity against the list of enumerated values. Unrecognized values will result in a ``LookupError`` being raised. .. versionadded:: 1.1.0b2 :param values_callable: A callable which will be passed the PEP-435 compliant enumerated type, which should then return a list of string values to be persisted. This allows for alternate usages such as using the string value of an enum to be persisted to the database instead of its name. .. versionadded:: 1.2.3 :param sort_key_function: a Python callable which may be used as the "key" argument in the Python ``sorted()`` built-in. The SQLAlchemy ORM requires that primary key columns which are mapped must be sortable in some way. When using an unsortable enumeration object such as a Python 3 ``Enum`` object, this parameter may be used to set a default sort key function for the objects. By default, the database value of the enumeration is used as the sorting function. .. versionadded:: 1.3.8 :param omit_aliases: A boolean that when true will remove aliases from pep 435 enums. For backward compatibility it defaults to ``False``. A deprecation warning is raised if the enum has aliases and this flag was not set. .. versionadded:: 1.4.5 .. deprecated:: 1.4 The default will be changed to ``True`` in SQLAlchemy 2.0. N) _enum_init)r&enumsrr'r'r(r[&sz Enum.__init__cCs|jdk r|jgS|jSdSr") enum_classrr%r'r'r(_enums_arguments zEnum._enums_argumentc s|dd|_|dd|_|dd|_|dt|_|dt}|d t|_|||\}}|||||d d}|d d|_ |dkr|j D]}t |t j rd}qqd}n|}|j rtd d |j D} nd} |js |tk r || krtd|| f|} d|jd<|jd<tt|j| |d|jrP|d|jjtj||dd|dd|dd|dd|dd|ddddS)zinternal init for :class:`.Enum` and subclasses. friendly init helper used by subclasses to remove all the Enum-specific keyword arguments from kw. Allows all other arguments in kw to pass through. native_enumTcreate_constraintFvalues_callableNsort_key_functionrV omit_aliasesrRvalidate_stringscss|]}t|VqdSr")len).0xr'r'r( sz"Enum._enum_init..rz`When provided, length must be larger or equal than the length of the longest enum value. %s < %s)rVrXrrrrrr)rrrrrr)rrrrr _sort_key_function _omit_aliases_parse_into_values_setup_for_valuesrrr;rrlmax ValueError _valid_lookup_object_lookupr?rr[rrr2lowerr) r&rrZ length_argvaluesobjectsrRerXrVrAr'r(rsX            zEnum._enum_initcs|sd|kr|d}t|dkrt|ddr|d|_|jj}dd|D}|jtkrx|rxt d|jj |f|jdkrt d d |Dn||j r| |j}nt }fd dD}||fSd|_||fSdS) N_enumsrr __members__cSsg|]\}}|j|kr|qSr'rrnvr'r'r( s z+Enum._parse_into_values..zThe provided enum %s contains the aliases %s. The ``omit_aliases`` will default to ``True`` in SQLAlchemy 2.0. Specify a value to silence this warning.Tcss$|]\}}|j|kr||fVqdSr"rrr'r'r(rs z*Enum._parse_into_values..csg|] }|qSr'r')rkmembersr'r(rs)rrhasattrrritemsrr rZwarn_deprecated_20r2rrlist)r&rrZ_membersaliasesrrr'rr(rs0      zEnum._parse_into_valuescsPt|_ttt|t|_tt||_jfdd|DdS)Ncs g|]}|jj|fqSr')r r )rrbr%r'r(r-sz*Enum._setup_for_values..)rrdictzipreversedr r update)r&rrrr'r%r(r%s  zEnum._setup_for_valuescCs|jtkr|jS|jSdSr")rr _db_value_for_elemr%r'r'r(r3s zEnum.sort_key_functioncCs|jSr")rr%r'r'r(native:sz Enum.nativec Csxz |j|WStk rr}zH|jss&     zEnum._db_value_for_elemcseZdZfddZZS)zEnum.Comparatorcs>ttj|||\}}|tjkr6t|jj|jj d}||fS)NrX) r?rr5r1rr=rKr*rVrX)r&r.r/rrAr'r(r1]s  z!Enum.Comparator._adapt_expressionrCr'r'rAr(r5\sr5c CsZz |j|WStk rT}z*tjtd||jt|jf|dW5d}~XYnXdSr%) r r&rr'r(rrr)rr*r'r'r(_object_value_for_elemis   zEnum._object_value_for_elemcCstj|dgttgdS)N)rT)Z additional_kwZ to_inspect)rZ generic_reprrrr%r'r'r(__repr__zs z Enum.__repr__FcCs.t|dr|j}ntdtj||jf|S)NrzpTypeEngine.as_generic() heuristic is undefined for types that inherit Enum but do not have an `enums` attribute.)rrr$rZconstructor_copyZ_generic_type_affinity)r&Zallow_nulltypeargsr'r'r( as_generics  zEnum.as_genericcKs|d|j|d|j|d|j|d|j|d|j|d|j|dd|d |j|d |j|d |j |d |j |d |j d|kst |f|S)NrXrrrrrrFrrrrVrr) rrXrrrrrrrrrVrAssertionErrorr&rrr'r'r(adapt_to_emulateds  zEnum.adapt_to_emulatedc s|j|d<tt|j|f|S)Nr)rr?rrr3rAr'r(rs z Enum.adaptcKs$||j|sdS|j p"|jj SNF)rrdrZsupports_native_enumr&compilerrr'r'r(_should_create_constraintszEnum._should_create_constraintsqlalchemy.sql.schemacCsztjj}t||||js dS||}|jt|| |j |j dkrLt n|j t |jd|idd}|j|ksvtdS)NrTrZ _create_ruleZ _type_bound)r preloaded sql_schemarrrrCheckConstraint type_coercein_rrr rr8rr2r&rrrrrr'r'r(rs  zEnum._set_tablecs"tt|fdd}|S)Ncs|}r|}|Sr"r#raZparent_processorr&r'r(res z'Enum.literal_processor..process)r?rrgrfrArBr(rgszEnum.literal_processorcs"fdd}tt||S)Ncs|}r|}|Sr"rArarBr'r(res z$Enum.bind_processor..process)r?rrrrfrArBr(rrszEnum.bind_processorcs$tt||fdd}|S)Ncsr |}|}|Sr")r.rarBr'r(res z&Enum.result_processor..process)r?rrurrArBr(ruszEnum.result_processorcKstj|f|Sr")rrrr'r'r(rsz Enum.copycs|jr |jStt|jSdSr")rr?rrwr%rAr'r(rwszEnum.python_type)F)!r2r3r4r6rrrr[r7rrrrrr$r#rKr5r8r.r/r1r4rr8preload_modulerrgrrrurrwrDr'r'rAr(rsBK   @"       rcsTeZdZdZeZdZejdddffdd Z ddZ dd Z d d Z d d Z ZS) PickleTypeaHolds Python objects, which are serialized using pickle. PickleType builds upon the Binary type to apply Python's ``pickle.dumps()`` to incoming objects, and ``pickle.loads()`` on the way out, allowing any pickleable Python object to be stored as a serialized binary field. To allow ORM change events to propagate for elements associated with :class:`.PickleType`, see :ref:`mutable_toplevel`. TNcs6||_|p t|_||_tt||r2t||_dS)a Construct a PickleType. :param protocol: defaults to ``pickle.HIGHEST_PROTOCOL``. :param pickler: defaults to cPickle.pickle or pickle.pickle if cPickle is not available. May be any object with pickle-compatible ``dumps`` and ``loads`` methods. :param comparator: a 2-arg callable predicate used to compare values of this type. If left as ``None``, the Python "equals" operator is used to compare values. :param impl: A binary-storing :class:`_types.TypeEngine` class or instance to use in place of the default :class:`_types.LargeBinary`. For example the :class: `_mysql.LONGBLOB` class may be more effective when using MySQL. .. versionadded:: 1.4.20 N) protocolr pickler comparatorr?rDr[rr)r&rErFrGrrAr'r(r[s  zPickleType.__init__cCst|jd|jffSr")rDrErGr%r'r'r( __reduce__szPickleType.__reduce__csB|j||jj|jr0fdd}nfdd}|S)Ncs|dk r|}|Sr"r'radumpsimpl_processorrEr'r(re&s z*PickleType.bind_processor..processcs|dk r|}|Sr"r'ra)rJrEr'r(re-s )rrrrFrJrErfr'rIr(rr s zPickleType.bind_processorcs:|j|||jjr*fdd}n fdd}|S)Ncs|}|dkrdS|Sr"r'rarKloadsr'r(re9sz,PickleType.result_processor..processcs|dkr dS|Sr"r'ra)rMr'r(reAs)rrurFrMrr'rLr(ru4s  zPickleType.result_processorcCs|jr|||S||kSdSr")rGr&ryr'r'r(compare_valuesHs zPickleType.compare_values)r2r3r4r6rrcache_okr HIGHEST_PROTOCOLr[rHrrrurPrDr'r'rAr(rDs $rDc@sveZdZdZdZdZdddZdd Ze d d d Z e d dZ e dddgZddZddZddZddZdS)BooleanaA bool datatype. :class:`.Boolean` typically uses BOOLEAN or SMALLINT on the DDL side, and on the Python side deals in ``True`` or ``False``. The :class:`.Boolean` datatype currently has two levels of assertion that the values persisted are simple true/false values. For all backends, only the Python values ``None``, ``True``, ``False``, ``1`` or ``0`` are accepted as parameter values. For those backends that don't support a "native boolean" datatype, an option exists to also create a CHECK constraint on the target column .. versionchanged:: 1.2 the :class:`.Boolean` datatype now asserts that incoming Python values are already in pure boolean form. booleanTFNcCs||_||_||_dS)aConstruct a Boolean. :param create_constraint: defaults to False. If the boolean is generated as an int/smallint, also create a CHECK constraint on the table that ensures 1 or 0 as a value. .. note:: it is strongly recommended that the CHECK constraint have an explicit name in order to support schema-management concerns. This can be established either by setting the :paramref:`.Boolean.name` parameter or by setting up an appropriate naming convention; see :ref:`constraint_naming_conventions` for background. .. versionchanged:: 1.4 - this flag now defaults to False, meaning no CHECK constraint is generated for a non-native enumerated type. :param name: if a CHECK constraint is generated, specify the name of the constraint. N)rrr)r&rrrr'r'r(r[fszBoolean.__init__cKs$||j|sdS|jj o"|jjSr5)rrdsupports_native_booleanZ#non_native_boolean_check_constraintr6r'r'r(r8s  z!Boolean._should_create_constraintr9cCsntjj}|jsdS||}|jt||ddg|jdkr@t n|jt |j d|idd}|j |ksjt dS)NrrrTr:)rr;r<rrr=r>r?rr rr8rr2r@r'r'r(rs  zBoolean._set_tablecCstSr")boolr%r'r'r(rwszBoolean.python_typecCs2||jkr.t|ts"td|n td||S)NzNot a boolean value: %rz$Value %r is not None, True, or False) _strict_boolsr;r TypeErrorr r&rbr'r'r(_strict_as_bools  zBoolean._strict_as_boolcs4||d}|d|dfdd}|S)Ncs|rSSr")rZrafalser&truer'r(resz*Boolean.literal_processor..process)Zstatement_compilerZ visit_trueZ visit_false)r&rdr7rer'r[r(rgs    zBoolean.literal_processorcs(|j|jrtntfdd}|S)Ncs|}|dk r|}|Sr"r'raZ_coercerZr'r(resz'Boolean.bind_processor..process)rZrUrVrrfr'r^r(rrs zBoolean.bind_processorcCs|jr dStjSdSr")rUrZint_to_booleanrr'r'r(ruszBoolean.result_processor)FNT)r2r3r4r6rr$r[r8rrCrr7rw frozensetrWrZrgrrrur'r'r'r(rSOs"     rSc@s.eZdZejddZeddZddZdS)_AbstractIntervalc CsLtjttt|jttttitjt|jitjt |jitj t |jitj t |jiiSr") rr:rrrrBrrrrrrr%r'r'r(r)s&z)_AbstractInterval._expression_adaptationscCstSr")rr%r'r'r(r+sz _AbstractInterval._type_affinitycCs|j||S)r)rrrr'r'r(rsz'_AbstractInterval.coerce_compared_valueN) r2r3r4rrr)r7r+rr'r'r'r(r`s   r`csZeZdZdZeZejdZ dZ dfdd Z e ddZ d d Zd d Zd dZZS)raA type for ``datetime.timedelta()`` objects. The Interval type deals with ``datetime.timedelta`` objects. In PostgreSQL, the native ``INTERVAL`` type is used; for others, the value is stored as a date which is relative to the "epoch" (Jan. 1, 1970). Note that the ``Interval`` type does not currently provide date arithmetic operations on platforms which do not support interval types natively. Such operations usually require transformation of both sides of the expression (such as, conversion of both sides into integer epoch values first) which currently is a manual procedure (such as via :attr:`~sqlalchemy.sql.expression.func`). rTNcs$tt|||_||_||_dS)a;Construct an Interval object. :param native: when True, use the actual INTERVAL type provided by the database, if supported (currently PostgreSQL, Oracle). Otherwise, represent the interval data as an epoch value regardless. :param second_precision: For native interval types which support a "fractional seconds precision" parameter, i.e. Oracle and PostgreSQL :param day_precision: for native interval types which support a "day precision" parameter, i.e. Oracle. N)r?rr[r$second_precision day_precision)r&r$rarbrAr'r(r[szInterval.__init__cCstjSr")r timedeltar%r'r'r(rwszInterval.python_typecKstj||f|Sr")r`rr3r'r'r(r4szInterval.adapt_to_emulatedcs6|j||jr&fdd}n fdd}|S)Ncs|dk r|}|Sr"r'raepochrKr'r(re!sz(Interval.bind_processor..processcs|dk r|}|Sr"r'rarer'r(re(s)rrrrerfr'rdr(rrs   zInterval.bind_processorcs8|j|||jr(fdd}n fdd}|S)Ncs|}|dkrdS|Sr"r'rardr'r(re4sz*Interval.result_processor..processcs|dkr dS|Sr"r'rarfr'r(re<s)rrurerr'rdr(ru/s  zInterval.result_processor)TNN)r2r3r4r6rrrrutcfromtimestamprerQr[r7rwr4rrrurDr'r'rAr(rs  rc@seZdZdZdZdZedZdddZ Gddde Z Gdd d e Z Gd d d e Z Gd d d e ZGddde ZGdddejejZeZeddZeddZejddZejddZddZddZdS)JSONaRepresent a SQL JSON type. .. note:: :class:`_types.JSON` is provided as a facade for vendor-specific JSON types. Since it supports JSON SQL operations, it only works on backends that have an actual JSON type, currently: * PostgreSQL - see :class:`sqlalchemy.dialects.postgresql.JSON` and :class:`sqlalchemy.dialects.postgresql.JSONB` for backend-specific notes * MySQL - see :class:`sqlalchemy.dialects.mysql.JSON` for backend-specific notes * SQLite as of version 3.9 - see :class:`sqlalchemy.dialects.sqlite.JSON` for backend-specific notes * Microsoft SQL Server 2016 and later - see :class:`sqlalchemy.dialects.mssql.JSON` for backend-specific notes :class:`_types.JSON` is part of the Core in support of the growing popularity of native JSON datatypes. The :class:`_types.JSON` type stores arbitrary JSON format data, e.g.:: data_table = Table('data_table', metadata, Column('id', Integer, primary_key=True), Column('data', JSON) ) with engine.connect() as conn: conn.execute( data_table.insert(), data = {"key1": "value1", "key2": "value2"} ) **JSON-Specific Expression Operators** The :class:`_types.JSON` datatype provides these additional SQL operations: * Keyed index operations:: data_table.c.data['some key'] * Integer index operations:: data_table.c.data[3] * Path index operations:: data_table.c.data[('key_1', 'key_2', 5, ..., 'key_n')] * Data casters for specific JSON element types, subsequent to an index or path operation being invoked:: data_table.c.data["some key"].as_integer() .. versionadded:: 1.3.11 Additional operations may be available from the dialect-specific versions of :class:`_types.JSON`, such as :class:`sqlalchemy.dialects.postgresql.JSON` and :class:`sqlalchemy.dialects.postgresql.JSONB` which both offer additional PostgreSQL-specific operations. **Casting JSON Elements to Other Types** Index operations, i.e. those invoked by calling upon the expression using the Python bracket operator as in ``some_column['some key']``, return an expression object whose type defaults to :class:`_types.JSON` by default, so that further JSON-oriented instructions may be called upon the result type. However, it is likely more common that an index operation is expected to return a specific scalar element, such as a string or integer. In order to provide access to these elements in a backend-agnostic way, a series of data casters are provided: * :meth:`.JSON.Comparator.as_string` - return the element as a string * :meth:`.JSON.Comparator.as_boolean` - return the element as a boolean * :meth:`.JSON.Comparator.as_float` - return the element as a float * :meth:`.JSON.Comparator.as_integer` - return the element as an integer These data casters are implemented by supporting dialects in order to assure that comparisons to the above types will work as expected, such as:: # integer comparison data_table.c.data["some_integer_key"].as_integer() == 5 # boolean comparison data_table.c.data["some_boolean"].as_boolean() == True .. versionadded:: 1.3.11 Added type-specific casters for the basic JSON data element types. .. note:: The data caster functions are new in version 1.3.11, and supersede the previous documented approaches of using CAST; for reference, this looked like:: from sqlalchemy import cast, type_coerce from sqlalchemy import String, JSON cast( data_table.c.data['some_key'], String ) == type_coerce(55, JSON) The above case now works directly as:: data_table.c.data['some_key'].as_integer() == 5 For details on the previous comparison approach within the 1.3.x series, see the documentation for SQLAlchemy 1.2 or the included HTML files in the doc/ directory of the version's distribution. **Detecting Changes in JSON columns when using the ORM** The :class:`_types.JSON` type, when used with the SQLAlchemy ORM, does not detect in-place mutations to the structure. In order to detect these, the :mod:`sqlalchemy.ext.mutable` extension must be used. This extension will allow "in-place" changes to the datastructure to produce events which will be detected by the unit of work. See the example at :class:`.HSTORE` for a simple example involving a dictionary. **Support for JSON null vs. SQL NULL** When working with NULL values, the :class:`_types.JSON` type recommends the use of two specific constants in order to differentiate between a column that evaluates to SQL NULL, e.g. no value, vs. the JSON-encoded string of ``"null"``. To insert or select against a value that is SQL NULL, use the constant :func:`.null`:: from sqlalchemy import null conn.execute(table.insert(), json_value=null()) To insert or select against a value that is JSON ``"null"``, use the constant :attr:`_types.JSON.NULL`:: conn.execute(table.insert(), json_value=JSON.NULL) The :class:`_types.JSON` type supports a flag :paramref:`_types.JSON.none_as_null` which when set to True will result in the Python constant ``None`` evaluating to the value of SQL NULL, and when set to False results in the Python constant ``None`` evaluating to the value of JSON ``"null"``. The Python value ``None`` may be used in conjunction with either :attr:`_types.JSON.NULL` and :func:`.null` in order to indicate NULL values, but care must be taken as to the value of the :paramref:`_types.JSON.none_as_null` in these cases. **Customizing the JSON Serializer** The JSON serializer and deserializer used by :class:`_types.JSON` defaults to Python's ``json.dumps`` and ``json.loads`` functions; in the case of the psycopg2 dialect, psycopg2 may be using its own custom loader function. In order to affect the serializer / deserializer, they are currently configurable at the :func:`_sa.create_engine` level via the :paramref:`_sa.create_engine.json_serializer` and :paramref:`_sa.create_engine.json_deserializer` parameters. For example, to turn off ``ensure_ascii``:: engine = create_engine( "sqlite://", json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False)) .. versionchanged:: 1.3.7 SQLite dialect's ``json_serializer`` and ``json_deserializer`` parameters renamed from ``_json_serializer`` and ``_json_deserializer``. .. seealso:: :class:`sqlalchemy.dialects.postgresql.JSON` :class:`sqlalchemy.dialects.postgresql.JSONB` :class:`sqlalchemy.dialects.mysql.JSON` :class:`sqlalchemy.dialects.sqlite.JSON` .. versionadded:: 1.1 FZ JSON_NULLcCs ||_dS)aConstruct a :class:`_types.JSON` type. :param none_as_null=False: if True, persist the value ``None`` as a SQL NULL value, not the JSON encoding of ``null``. Note that when this flag is False, the :func:`.null` construct can still be used to persist a NULL value:: from sqlalchemy import null conn.execute(table.insert(), data=null()) .. note:: :paramref:`_types.JSON.none_as_null` does **not** apply to the values passed to :paramref:`_schema.Column.default` and :paramref:`_schema.Column.server_default`; a value of ``None`` passed for these parameters means "no default present". Additionally, when used in SQL comparison expressions, the Python value ``None`` continues to refer to SQL null, and not JSON NULL. The :paramref:`_types.JSON.none_as_null` flag refers explicitly to the **persistence** of the value within an INSERT or UPDATE statement. The :attr:`_types.JSON.NULL` value should be used for SQL expressions that wish to compare to JSON null. .. seealso:: :attr:`.types.JSON.NULL` N none_as_null)r&rjr'r'r(r[4 sz JSON.__init__c@s<eZdZdZeZeZddZddZ ddZ dd Z d S) zJSON.JSONElementTypez?Common function for index / path elements in a JSON expression.cCs |j|Sr")_string_cached_bind_processorrr'r'r(string_bind_processor[ sz*JSON.JSONElementType.string_bind_processorcCs |j|Sr")rk_cached_literal_processorrr'r'r(string_literal_processor^ sz-JSON.JSONElementType.string_literal_processorcs(|j|||fdd}|S)Ncs4rt|tr|}nr0t|tjr0|}|Sr"r;rrrraZ int_processorZstring_processorr'r(ree s  z4JSON.JSONElementType.bind_processor..process)_integerrlrmrfr'rqr(rra s  z#JSON.JSONElementType.bind_processorcs(|j|||fdd}|S)Ncs4rt|tr|}nr0t|tjr0|}|Sr"rprarqr'r(rer s  z7JSON.JSONElementType.literal_processor..process)rrrnrorfr'rqr(rgn s  z&JSON.JSONElementType.literal_processorN) r2r3r4r6rrrrKrkrmrorrrgr'r'r'r(JSONElementTypeU s rsc@seZdZdZdS)zJSON.JSONIndexTypePlaceholder for the datatype of a JSON index value. This allows execution-time processing of JSON index values for special syntaxes. Nr2r3r4r6r'r'r'r( JSONIndexType{ srvc@seZdZdZdS)zJSON.JSONIntIndexTypertNrur'r'r'r(JSONIntIndexType srwc@seZdZdZdS)zJSON.JSONStrIndexTypertNrur'r'r'r(JSONStrIndexType srxc@seZdZdZdS)zJSON.JSONPathTypezPlaceholder type for JSON path operations. This allows execution-time processing of a path-based index value into a specific SQL syntax. Nrur'r'r'r( JSONPathType sryc@sReZdZdZddZddZddZdd Zd d Zdd dZ ddZ ddZ dS)zJSON.Comparatorz6Define comparison operations for :class:`_types.JSON`.cCs|t|tjs>t|tjjr>tjtj ||j t j t jd}t j }n2tjtj ||j t jt|tr`t jnt jd}t j}|||jfS)N)r>operatorZbindparam_type)r;rrrcollections_abcSequencerexpectrZBinaryElementRoler>rjson_path_getitem_oprhryjson_getitem_oprrwrxr*)r&rGrzr'r'r(rH s. zJSON.Comparator._setup_getitemcCs|tdS)aDCast an indexed value as boolean. e.g.:: stmt = select( mytable.c.json_column['some_data'].as_boolean() ).where( mytable.c.json_column['some_data'].as_boolean() == True ) .. versionadded:: 1.3.11 as_boolean)_binary_w_typerSr%r'r'r(r szJSON.Comparator.as_booleancCs|tdS)a^Cast an indexed value as string. e.g.:: stmt = select( mytable.c.json_column['some_data'].as_string() ).where( mytable.c.json_column['some_data'].as_string() == 'some string' ) .. versionadded:: 1.3.11 as_string)rrKr%r'r'r(r szJSON.Comparator.as_stringcCs|tdS)aACast an indexed value as integer. e.g.:: stmt = select( mytable.c.json_column['some_data'].as_integer() ).where( mytable.c.json_column['some_data'].as_integer() == 5 ) .. versionadded:: 1.3.11 as_integer)rrr%r'r'r(r szJSON.Comparator.as_integercCs|tdS)a?Cast an indexed value as float. e.g.:: stmt = select( mytable.c.json_column['some_data'].as_float() ).where( mytable.c.json_column['some_data'].as_float() == 29.75 ) .. versionadded:: 1.3.11 as_float)rrr%r'r'r(r szJSON.Comparator.as_floatTcCs|t|||ddS)amCast an indexed value as numeric/decimal. e.g.:: stmt = select( mytable.c.json_column['some_data'].as_numeric(10, 6) ).where( mytable.c. json_column['some_data'].as_numeric(10, 6) == 29.75 ) .. versionadded:: 1.4.0b2 )r as_numeric)rr)r&rrrr'r'r(r s zJSON.Comparator.as_numericcCs|jS)aCast an indexed value as JSON. e.g.:: stmt = select(mytable.c.json_column['some_data'].as_json()) This is typically the default behavior of indexed elements in any case. Note that comparison of full JSON structures may not be supported by all backends. .. versionadded:: 1.3.11 )r>r%r'r'r(as_json szJSON.Comparator.as_jsoncCsHt|jtjr"|jjtjtjfkr4t d||f|j }||_ |S)Nz[The JSON cast operator JSON.%s() only works with a JSON index expression e.g. col['q'].%s()) r;r>rBinaryExpressionrzrrr~rZInvalidRequestErrorZ_cloner*)r&r method_namer>r'r'r(r s" zJSON.Comparator._binary_w_typeN)T) r2r3r4r6rHrrrrrrrr'r'r'r(r5 s r5cCstSr")rr%r'r'r(rw1 szJSON.python_typecCs|j S)z)Alias of :attr:`_types.JSON.none_as_null`rir%r'r'r(should_evaluate_none5 szJSON.should_evaluate_nonecCs | |_dSr"rirYr'r'r(r: scCs tddS)NTr-)rKr%r'r'r( _str_impl> szJSON._str_implcs,j||jptjfdd}|S)NcsF|jkrd}nt|tjs*|dkr.jr.dS|}rB|}|Sr")NULLr;rZNullrj)rbZ serializedZjson_serializerr&string_processr'r(reG s  z$JSON.bind_processor..process)rrrZ_json_serializerjsonrJrfr'rr(rrB s   zJSON.bind_processorcs,|j|||jptjfdd}|S)Ncs |dkr dSr|}|Sr"r'raZjson_deserializerrr'r(reZ s z&JSON.result_processor..process)rruZ_json_deserializerrrMrr'rr(ruV s zJSON.result_processorN)F)r2r3r4r6rhashablerrrr[rrsrvrwrxryrFr5r9r8r7rwrsetterrrrrrur'r'r'r(rhDs0A , !&    rhcszeZdZdZdZdZdZGdddeje jZeZ dddZ e d d Z e d d Zd dZdddZfddZZS)ra Represent a SQL Array type. .. note:: This type serves as the basis for all ARRAY operations. However, currently **only the PostgreSQL backend has support for SQL arrays in SQLAlchemy**. It is recommended to use the PostgreSQL-specific :class:`sqlalchemy.dialects.postgresql.ARRAY` type directly when using ARRAY types with PostgreSQL, as it provides additional operators specific to that backend. :class:`_types.ARRAY` is part of the Core in support of various SQL standard functions such as :class:`_functions.array_agg` which explicitly involve arrays; however, with the exception of the PostgreSQL backend and possibly some third-party dialects, no other SQLAlchemy built-in dialect has support for this type. An :class:`_types.ARRAY` type is constructed given the "type" of element:: mytable = Table("mytable", metadata, Column("data", ARRAY(Integer)) ) The above type represents an N-dimensional array, meaning a supporting backend such as PostgreSQL will interpret values with any number of dimensions automatically. To produce an INSERT construct that passes in a 1-dimensional array of integers:: connection.execute( mytable.insert(), data=[1,2,3] ) The :class:`_types.ARRAY` type can be constructed given a fixed number of dimensions:: mytable = Table("mytable", metadata, Column("data", ARRAY(Integer, dimensions=2)) ) Sending a number of dimensions is optional, but recommended if the datatype is to represent arrays of more than one dimension. This number is used: * When emitting the type declaration itself to the database, e.g. ``INTEGER[][]`` * When translating Python values to database values, and vice versa, e.g. an ARRAY of :class:`.Unicode` objects uses this number to efficiently access the string values inside of array structures without resorting to per-row type inspection * When used with the Python ``getitem`` accessor, the number of dimensions serves to define the kind of type that the ``[]`` operator should return, e.g. for an ARRAY of INTEGER with two dimensions:: >>> expr = table.c.column[5] # returns ARRAY(Integer, dimensions=1) >>> expr = expr[6] # returns Integer For 1-dimensional arrays, an :class:`_types.ARRAY` instance with no dimension parameter will generally assume single-dimensional behaviors. SQL expressions of type :class:`_types.ARRAY` have support for "index" and "slice" behavior. The Python ``[]`` operator works normally here, given integer indexes or slices. Arrays default to 1-based indexing. The operator produces binary expression constructs which will produce the appropriate SQL, both for SELECT statements:: select(mytable.c.data[5], mytable.c.data[2:7]) as well as UPDATE statements when the :meth:`_expression.Update.values` method is used:: mytable.update().values({ mytable.c.data[5]: 7, mytable.c.data[2:7]: [1, 2, 3] }) The :class:`_types.ARRAY` type also provides for the operators :meth:`.types.ARRAY.Comparator.any` and :meth:`.types.ARRAY.Comparator.all`. The PostgreSQL-specific version of :class:`_types.ARRAY` also provides additional operators. .. versionadded:: 1.1.0 .. seealso:: :class:`sqlalchemy.dialects.postgresql.ARRAY` TFc@sHeZdZdZddZddZedd dd Zedd d d Z dS)zARRAY.ComparatorzDefine comparison operations for :class:`_types.ARRAY`. More operators are available on the dialect-specific form of this type. See :class:`.postgresql.ARRAY.Comparator`. cCst|trX|j}|jjr2t|jd|jd|j}t|j|j|j|jj d}t j ||fS|jjrh|d7}|jj dks|jj dkr|jj }n$d|jj di}|jj|jjf|}t j ||fSdS)Nr)_name dimensions)r;slicer* zero_indexesstartstopstepr r>keyrgetitemrrrrB)r&rG return_typeZslice_Zadapt_kwr'r'r(rH s,   zARRAY.Comparator._setup_getitemcOs tddS)NzdARRAY.contains() not implemented for the base ARRAY type; please use the dialect-specific ARRAY typer#)r&argrr'r'r(contains szARRAY.Comparator.containszsqlalchemy.sql.elementsNcCs8tjj}|r|ntj}|ttj ||j |j |S)aReturn ``other operator ANY (array)`` clause. Argument places are switched, because ANY requires array expression to be on the right hand-side. E.g.:: from sqlalchemy.sql import operators conn.execute( select(table.c.data).where( table.c.data.any(7, operator=operators.lt) ) ) :param other: expression to be compared :param operator: an operator object from the :mod:`sqlalchemy.sql.operators` package, defaults to :func:`.operators.eq`. .. seealso:: :func:`_expression.any_` :meth:`.types.ARRAY.Comparator.all` ) rr; sql_elementsreqrrr}rExpressionElementRoleCollectionAggregateZ _create_anyr>r&otherrzrr'r'r(any s  zARRAY.Comparator.anycCs8tjj}|r|ntj}|ttj ||j |j |S)aReturn ``other operator ALL (array)`` clause. Argument places are switched, because ALL requires array expression to be on the right hand-side. E.g.:: from sqlalchemy.sql import operators conn.execute( select(table.c.data).where( table.c.data.all(7, operator=operators.lt) ) ) :param other: expression to be compared :param operator: an operator object from the :mod:`sqlalchemy.sql.operators` package, defaults to :func:`.operators.eq`. .. seealso:: :func:`_expression.all_` :meth:`.types.ARRAY.Comparator.any` ) rr;rrrrrr}rrrZ _create_allr>rr'r'r(all s  zARRAY.Comparator.all)N)N) r2r3r4r6rHrrrCrrr'r'r'r(r5 s 'r5NcCs>t|trtdt|tr"|}||_||_||_||_dS)aConstruct an :class:`_types.ARRAY`. E.g.:: Column('myarray', ARRAY(Integer)) Arguments are: :param item_type: The data type of items of this array. Note that dimensionality is irrelevant here, so multi-dimensional arrays like ``INTEGER[][]``, are constructed as ``ARRAY(Integer)``, not as ``ARRAY(ARRAY(Integer))`` or such. :param as_tuple=False: Specify whether return results should be converted to tuples from lists. This parameter is not generally needed as a Python list corresponds well to a SQL array. :param dimensions: if non-None, the ARRAY will assume a fixed number of dimensions. This impacts how the array is declared on the database, how it goes about interpreting Python and result values, as well as how expression behavior in conjunction with the "getitem" operator works. See the description at :class:`_types.ARRAY` for additional detail. :param zero_indexes=False: when True, index values will be converted between Python zero-based and SQL one-based indexes, e.g. a value of one will be added to all index values before passing to the database. zUDo not nest ARRAY types; ARRAY(basetype) handles multi-dimensional arrays of basetypeN)r;rr r*ras_tuplerr)r&rrrrr'r'r(r[A s"  zARRAY.__init__cCs|jSr")rr%r'r'r(ro szARRAY.hashablecCstSr")rr%r'r'r(rws szARRAY.python_typecCs||kSr"r'rNr'r'r(rPw szARRAY.compare_valuescKs$|s t|jtr |jj|f|dS)Support SchemaEventTargetN)r;rr r)r&routerrr'r'r(rz szARRAY._set_parentcs0tt|j|ddt|jtr,|j|dS)rT)rN)r?r_set_parent_with_dispatchr;rr )r&parentrAr'r(r s zARRAY._set_parent_with_dispatch)FNF)F)r2r3r4r6rZ _is_arrayrrFr5r9r8r[r7rrwrPrrrDr'r'rAr(rd s"]u .   rc@s,eZdZdZdZddZddZddZd S) TupleTypez(represent the composite type of a Tuple.TcGst|k|_||_dSr")NULLTYPE _fully_typedtypes)r&rr'r'r(r[ s zTupleType.__init__cCs(|jr |Stddt|j|DSdS)NcSs$g|]\}}|tkrt|n|qSr')r_resolve_value_to_type)rrr+r'r'r(r sz6TupleType._resolve_values_to_types..)rrr rrYr'r'r(_resolve_values_to_types s z"TupleType._resolve_values_to_typescCs tddS)NzJThe tuple type does not support being fetched as a column in a result row.r#rr'r'r(ru szTupleType.result_processorN)r2r3r4r6Z_is_tuple_typer[rrur'r'r'r(r s  rc@seZdZdZdZdS)REALzThe SQL REAL type.Nrr'r'r'r(r src@seZdZdZdZdS)FLOATzThe SQL FLOAT type.Nrr'r'r'r(r src@seZdZdZdZdS)NUMERICzThe SQL NUMERIC type.Nrr'r'r'r(r src@seZdZdZdZdS)DECIMALzThe SQL DECIMAL type.Nrr'r'r'r(r src@seZdZdZdZdS)INTEGERzThe SQL INT or INTEGER type.Nrr'r'r'r(r src@seZdZdZdZdS)SMALLINTzThe SQL SMALLINT type.Nrr'r'r'r(r src@seZdZdZdZdS)BIGINTzThe SQL BIGINT type.Nrr'r'r'r(r srcs.eZdZdZdZdfdd ZddZZS) TIMESTAMPaThe SQL TIMESTAMP type. :class:`_types.TIMESTAMP` datatypes have support for timezone storage on some backends, such as PostgreSQL and Oracle. Use the :paramref:`~types.TIMESTAMP.timezone` argument in order to enable "TIMESTAMP WITH TIMEZONE" for these backends. Fcstt|j|ddS)amConstruct a new :class:`_types.TIMESTAMP`. :param timezone: boolean. Indicates that the TIMESTAMP type should enable timezone support, if available on the target database. On a per-dialect basis is similar to "TIMESTAMP WITH TIMEZONE". If the target database does not support timezones, this flag is ignored. rN)r?rr[rrAr'r(r[ s zTIMESTAMP.__init__cCs|jSr")rryr'r'r(r{ szTIMESTAMP.get_dbapi_type)F)r2r3r4r6rr[r{rDr'r'rAr(r s  rc@seZdZdZdZdS)rzThe SQL DATETIME type.Nrr'r'r'r(r src@seZdZdZdZdS)DATEzThe SQL DATE type.Nrr'r'r'r(r src@seZdZdZdZdS)TIMEzThe SQL TIME type.Nrr'r'r'r(r src@seZdZdZdZdS)TEXTzThe SQL TEXT type.Nrr'r'r'r(r src@seZdZdZdZdS)CLOBzCThe CLOB type. This type is found in Oracle and Informix. Nrr'r'r'r(r src@seZdZdZdZdS)VARCHARzThe SQL VARCHAR type.Nrr'r'r'r(r src@seZdZdZdZdS)NVARCHARzThe SQL NVARCHAR type.Nrr'r'r'r(r# src@seZdZdZdZdS)CHARzThe SQL CHAR type.Nrr'r'r'r(r* src@seZdZdZdZdS)NCHARzThe SQL NCHAR type.Nrr'r'r'r(r1 src@seZdZdZdZdS)BLOBzThe SQL BLOB type.Nrr'r'r'r(r8 src@seZdZdZdZdS)rzThe SQL BINARY type.Nrr'r'r'r(r? src@seZdZdZdZdS) VARBINARYzThe SQL VARBINARY type.Nrr'r'r'r(rF src@seZdZdZdZdS)BOOLEANzThe SQL BOOLEAN type.Nrr'r'r'r(rM src@s6eZdZdZdZdZddZGdddejZeZ dS) r<aAn unknown type. :class:`.NullType` is used as a default type for those cases where a type cannot be determined, including: * During table reflection, when the type of a column is not recognized by the :class:`.Dialect` * When constructing SQL expressions using plain Python objects of unknown types (e.g. ``somecolumn == my_special_object``) * When a new :class:`_schema.Column` is created, and the given type is passed as ``None`` or is not passed at all. The :class:`.NullType` can be used within SQL expression invocation without issue, it just has no behavior either at the expression construction level or at the bind-parameter/result processing level. :class:`.NullType` will result in a :exc:`.CompileError` if the compiler is asked to render the type itself, such as if it is used in a :func:`.cast` operation or within a schema creation operation such as that invoked by :meth:`_schema.MetaData.create_all` or the :class:`.CreateTable` construct. nullTcCs dd}|S)NcSstd|dS)Nz.Don't know how to render literal SQL value: %r)r CompileErrorrar'r'r(ret sz+NullType.literal_processor..processr'rfr'r'r(rgs szNullType.literal_processorc@seZdZddZdS)zNullType.ComparatorcCs2t|tjst|s"||jjfS|||SdSr")r;r<r5rZis_commutativer>r*r1r@r'r'r(r1| s z%NullType.Comparator._adapt_expressionN)r2r3r4r1r'r'r'r(r5{ sr5N) r2r3r4r6rZ_isnullrgrr5r8r'r'r'r(r<T s  r<c@s(eZdZdZdZdejfgZddZdS)TableValueTypezRefers to a table value type.T _elementscGsdd|D|_dS)NcSsg|]}ttj|qSr')rr}rZStrAsPlainColumnRole)rr+r'r'r(r sz+TableValueType.__init__..)r)r&rr'r'r(r[ szTableValueType.__init__N) r2r3r4r6Z_is_table_valuerZdp_clauseelement_listZ_traverse_internalsr[r'r'r'r(r s rc@seZdZdZdS) MatchTypeaDRefers to the return type of the MATCH operator. As the :meth:`.ColumnOperators.match` is probably the most open-ended operator in generic SQLAlchemy Core, we can't assume the return type at SQL evaluation time, as MySQL returns a floating point, not a boolean, and other backends might do something different. So this type acts as a placeholder, currently subclassing :class:`.Boolean`. The type allows dialects to inject result-processing functionality if needed, and on MySQL will return floating-point values. .. versionadded:: 1.0.0 Nrur'r'r'r(r srcCsPtt|d}|dkrHt|d}|dk rD|jtjkrDtd|tS|SdS)NFz-Object %r is not legal as a SQL literal value) _type_map_getr*rinspectrBZ _registrarsrrUr)rbZ _result_typeZinspr'r'r(r s  r)sr6rorrrrrrrrrbaserr r r r r rr>Z traversalsrrrrrrrrrrrrrrrrr objectr!r9rFrKrrrrrrrrrrrrrrrrDrSr`rrhrrrrrrrINTrrrrrrrrrrrrrrrrr<rrrZ BOOLEANTYPEZ STRINGTYPEZ INTEGERTYPEZ MATCHTYPEZ TABLEVALUErrrVrrrrcZNoneTypeZ _type_mapZpy3krrvrr,rrZ INDEXABLEr5r'r'r'r(s                             F (  3A7&@Jf~[$' 3