L i7ddlmZddlmZddlmZddlmZddlmZddlmZddlmZdd l m Z dd l m Z dd l m Z dd l mZdd l mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddlmZddlmZddlmZerddlmZddl m!Z!ddl"m#Z#ddl"m$Z$ddl"m%Z%dZ&Gdd ejNjPZ(Gd!d"e(Z)Gd#d$ejNZ'Gd%d&e'Z*y')() annotations)Any)Callable)List)Optional) TYPE_CHECKING)Union)ARRAY)array)ASTEXT) CONTAINED_BY)CONTAINS) DELETE_PATH)HAS_ALL)HAS_ANY)HAS_KEY)JSONPATH_ASTEXT) PATH_EXISTS) PATH_MATCH)types)cast)_T)Dialect) ColumnElement)_BindProcessorType)_LiteralProcessorType) TypeEngine)JSONJSONBc8eZdZ ddZddZ ddZy) JSONPathTypecdfd }|S)Nct|tr|S|r#ddjtt|z}nd}r|}|S)Nz{%s}z, z{}) isinstancestrjoinmap)value super_procs i/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/json.pyprocessz(JSONPathType._processor..process/sI%% $))CUO"<="5)L)r*rreturnr)selfdialectr+r-s ` r, _processorzJSONPathType._processor,s r.cD|j||j|SN)r3string_bind_processorr1r2s r,bind_processorzJSONPathType.bind_processor@sw(B(B7(KLLr.cD|j||j|Sr5)r3string_literal_processorr7s r,literal_processorzJSONPathType.literal_processorCs w(E(Eg(NOOr.N)r2rr+zOptional[Callable[[Any], Any]]r/zCallable[[Any], Any])r2rr/z_BindProcessorType[Any])r2rr/z_LiteralProcessorType[Any])__name__ __module__ __qualname__r3r8r;r0r.r,r#r#+s=,J (MPP #Pr.r#ceZdZdZdZy)JSONPATHadJSON Path Type. This is usually required to cast literal values to json path when using json search like function, such as ``jsonb_path_query_array`` or ``jsonb_path_exists``:: stmt = sa.select( sa.func.jsonb_path_query_array( table.c.jsonb_col, cast("$.address.id", JSONPATH) ) ) N)r<r=r>__doc____visit_name__r0r.r,r@r@Is  Nr.r@ceZdZUdZdZej Zded< d d fd Z Gddejje Z e Z xZS) r a Represent the PostgreSQL JSON type. :class:`_postgresql.JSON` is used automatically whenever the base :class:`_types.JSON` datatype is used against a PostgreSQL backend, however base :class:`_types.JSON` datatype does not provide Python accessors for PostgreSQL-specific comparison methods such as :meth:`_postgresql.JSON.Comparator.astext`; additionally, to use PostgreSQL ``JSONB``, the :class:`_postgresql.JSONB` datatype should be used explicitly. .. seealso:: :class:`_types.JSON` - main documentation for the generic cross-platform JSON datatype. The operators provided by the PostgreSQL version of :class:`_types.JSON` include: * Index operations (the ``->`` operator):: data_table.c.data["some key"] data_table.c.data[5] * Index operations returning text (the ``->>`` operator):: data_table.c.data["some key"].astext == "some value" Note that equivalent functionality is available via the :attr:`.JSON.Comparator.as_string` accessor. * Index operations with CAST (equivalent to ``CAST(col ->> ['some key'] AS )``):: data_table.c.data["some key"].astext.cast(Integer) == 5 Note that equivalent functionality is available via the :attr:`.JSON.Comparator.as_integer` and similar accessors. * Path index operations (the ``#>`` operator):: data_table.c.data[("key_1", "key_2", 5, ..., "key_n")] * Path index operations returning text (the ``#>>`` operator):: data_table.c.data[ ("key_1", "key_2", 5, ..., "key_n") ].astext == "some value" Index operations 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. Custom serializers and deserializers are specified at the dialect level, that is using :func:`_sa.create_engine`. The reason for this is that when using psycopg2, the DBAPI only allows serializers at the per-cursor or per-connection level. E.g.:: engine = create_engine( "postgresql+psycopg2://scott:tiger@localhost/test", json_serializer=my_serialize_fn, json_deserializer=my_deserialize_fn, ) When using the psycopg2 dialect, the json_deserializer is registered against the database using ``psycopg2.extras.register_default_json``. .. seealso:: :class:`_types.JSON` - Core level JSON type :class:`_postgresql.JSONB` TzTypeEngine[str] astext_typec:t|||||_yy)aConstruct a :class:`_types.JSON` type. :param none_as_null: 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()}) .. seealso:: :attr:`_types.JSON.NULL` :param astext_type: the type to use for the :attr:`.JSON.Comparator.astext` accessor on indexed attributes. Defaults to :class:`_types.Text`. ) none_as_nullN)super__init__rD)r1rFrD __class__s r,rHz JSON.__init__s(2 l3  "*D  #r.c.eZdZUdZded<eddZy)JSON.Comparator6Define comparison operations for :class:`_types.JSON`.r typect|jjjtj j rT|jjjt|jj|jjS|jjjt|jj|jjS)aOn an indexed expression, use the "astext" (e.g. "->>") conversion when rendered in SQL. E.g.:: select(data_table.c.data["some key"].astext) .. seealso:: :meth:`_expression.ColumnElement.cast`  result_type) r&exprrightrMsqltypesr r#leftoperaterrDr )r1s r,astextzJSON.Comparator.astexts$))//.. 0J0JKyy~~--#IIOO $ 5 5. yy~~--DIIOO9N9N.r.N)r/zColumnElement[str])r<r=r>rA__annotations__propertyrVr0r.r, ComparatorrKsD    r.rY)FN)rFboolrDzOptional[TypeEngine[str]])r<r=r>rArender_bind_castrSTextrDrWrHr rYrcomparator_factory __classcell__)rIs@r,r r [sfKZ#08==?K2#15++/+:X]]--b1<$r.r cHeZdZdZdZGddej eZeZy)r!a Represent the PostgreSQL JSONB type. The :class:`_postgresql.JSONB` type stores arbitrary JSONB format data, e.g.:: data_table = Table( "data_table", metadata, Column("id", Integer, primary_key=True), Column("data", JSONB), ) with engine.connect() as conn: conn.execute( data_table.insert(), data={"key1": "value1", "key2": "value2"} ) The :class:`_postgresql.JSONB` type includes all operations provided by :class:`_types.JSON`, including the same behaviors for indexing operations. It also adds additional operators specific to JSONB, including :meth:`.JSONB.Comparator.has_key`, :meth:`.JSONB.Comparator.has_all`, :meth:`.JSONB.Comparator.has_any`, :meth:`.JSONB.Comparator.contains`, :meth:`.JSONB.Comparator.contained_by`, :meth:`.JSONB.Comparator.delete_path`, :meth:`.JSONB.Comparator.path_exists` and :meth:`.JSONB.Comparator.path_match`. Like the :class:`_types.JSON` type, the :class:`_postgresql.JSONB` type does not detect in-place changes when used with the ORM, unless the :mod:`sqlalchemy.ext.mutable` extension is used. Custom serializers and deserializers are shared with the :class:`_types.JSON` class, using the ``json_serializer`` and ``json_deserializer`` keyword arguments. These must be specified at the dialect level using :func:`_sa.create_engine`. When using psycopg2, the serializers are associated with the jsonb type using ``psycopg2.extras.register_default_jsonb`` on a per-connection basis, in the same way that ``psycopg2.extras.register_default_json`` is used to register these handlers with the json type. .. seealso:: :class:`_types.JSON` .. warning:: **For applications that have indexes against JSONB subscript expressions** SQLAlchemy 2.0.42 made a change in how the subscript operation for :class:`.JSONB` is rendered, from ``-> 'element'`` to ``['element']``, for PostgreSQL versions greater than 14. This change caused an unintended side effect for indexes that were created against expressions that use subscript notation, e.g. ``Index("ix_entity_json_ab_text", data["a"]["b"].astext)``. If these indexes were generated with the older syntax e.g. ``((entity.data -> 'a') ->> 'b')``, they will not be used by the PostgreSQL query planner when a query is made using SQLAlchemy 2.0.42 or higher on PostgreSQL versions 14 or higher. This occurs because the new text will resemble ``(entity.data['a'] ->> 'b')`` which will fail to produce the exact textual syntax match required by the PostgreSQL query planner. Therefore, for users upgrading to SQLAlchemy 2.0.42 or higher, existing indexes that were created against :class:`.JSONB` expressions that use subscripting would need to be dropped and re-created in order for them to work with the new query syntax, e.g. an expression like ``((entity.data -> 'a') ->> 'b')`` would become ``(entity.data['a'] ->> 'b')``. .. seealso:: :ticket:`12868` - discussion of this issue cdeZdZUdZded<d dZd dZd dZddZd dZ dd Z d d Z d d Z y )JSONB.ComparatorrLr!rMcN|jt|tjS)zBoolean expression. Test for presence of a key (equivalent of the ``?`` operator). Note that the key may be a SQLA expression. rO)rUrrSBooleanr1others r,has_keyzJSONB.Comparator.has_key?<<H`` operator). kwargs may be ignored by this operator but are required for API conformance. rO)rUrrSrc)r1rekwargss r,containszJSONB.Comparator.containsQs<<%X=M=M<N Nr.cN|jt|tjS)zBoolean expression. Test if keys are a proper subset of the keys of the argument jsonb expression (equivalent of the ``<@`` operator). rO)rUrrSrcrds r, contained_byzJSONB.Comparator.contained_by[s' <<e1A1A  r.ct|ts t|}t|ttj }|j t|tS)a=JSONB expression. Deletes field or array element specified in the argument array (equivalent of the ``#-`` operator). The input may be a list of strings that will be coerced to an ``ARRAY`` or an instance of :meth:`_postgres.array`. .. versionadded:: 2.0 rO) r& _pg_arrayrr rSTEXTrUrr!)r1r right_sides r, delete_pathzJSONB.Comparator.delete_pathdsBeY/!%(eU8==%9:J<< ZU<K Kr.cN|jt|tjS)zBoolean expression. Test for presence of item given by the argument JSONPath expression (equivalent of the ``@?`` operator). .. versionadded:: 2.0 rO)rUrrSrcrds r, path_existszJSONB.Comparator.path_existsts' <<U0@0@  r.cN|jt|tjS)aBoolean expression. Test if JSONPath predicate given by the argument JSONPath expression matches (equivalent of the ``@@`` operator). Only the first item of the result is taken into account. .. versionadded:: 2.0 rO)rUrrSrcrds r, path_matchzJSONB.Comparator.path_match~s'<<Ex/?/?  r.N)rerr/ColumnElement[bool])rerrmrr/rz)r z Union[List[str], _pg_array[str]]r/zColumnElement[JSONB]) r<r=r>rArWrfrirkrnrprurwryr0r.r,rYra:sID  N  N  N  O  L9 L ! L   r.rYN) r<r=r>rArBr rYrr]r0r.r,r!r!s0KZNOT__R(Ob$r.r!N)+ __future__rtypingrrrrrr r r rr operatorsr rrrrrrrrrrrSsqlr sql._typingrengine.interfacesr sql.elementsr sql.type_apirrr__all__r r#r@r!r0r.r,rs# %#"&"!!,-25* P8==--P< | $L$8==L$^a$Da$r.