
    Q
ig                     @    d Z ddlZddlmZmZmZ  G d d          ZdS )z=SQL Query class for executing SQL-like queries against Redis.    N)AnyDictOptionalc                       e Zd ZdZddedeeeef                  fdZdedeeef         defdZ		 	 dd	ee         d
edefdZ
dS )SQLQuerya  A query class that translates SQL-like syntax into Redis queries.

    This class allows users to write SQL SELECT statements that are
    automatically translated into Redis FT.SEARCH or FT.AGGREGATE commands.

    .. code-block:: python

        from redisvl.query import SQLQuery
        from redisvl.index import SearchIndex

        index = SearchIndex.from_existing("products", redis_url="redis://localhost:6379")

        sql_query = SQLQuery('''
            SELECT title, price, category
            FROM products
            WHERE category = 'electronics' AND price < 100
        ''')

        results = index.query(sql_query)

    Note:
        Requires the optional `sql-redis` package. Install with:
        ``pip install redisvl[sql-redis]``
    Nsqlparamsc                 &    || _         |pi | _        dS )a   Initialize a SQLQuery.

        Args:
            sql: The SQL SELECT statement to execute.
            params: Optional dictionary of parameters for parameterized queries.
                   Useful for passing vector data for similarity searches.
        N)r   r	   )selfr   r	   s      C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\redisvl/query/sql.py__init__zSQLQuery.__init__!   s     l    returnc                 L   |s|S t          j        d|          }g }|D ]}|                    d          r|dd         }||v r||         }t          |t          t
          f          r#|                    t          |                     lt          |t                    r0|                    dd          }|                    d| d           |                    |           |                    |           |                    |           d	                    |          S )a  Substitute parameter placeholders in SQL with actual values.

        Uses token-based approach: splits SQL on :param patterns, then rebuilds
        with substituted values. This prevents partial matching (e.g., :id
        won't match inside :product_id) and is faster than regex at scale.

        Args:
            sql: The SQL string with :param placeholders.
            params: Dictionary mapping parameter names to values.

        Returns:
            SQL string with parameters substituted.

        Note:
            - String values are wrapped in single quotes with proper escaping
            - Numeric values are converted to strings
            - Bytes values (e.g., vectors) are NOT substituted here
        z(:[a-zA-Z_][a-zA-Z0-9_]*):   N'z'' )
resplit
startswith
isinstanceintfloatappendstrreplacejoin)	r   r   r	   tokensresulttokenkeyvalueescapeds	            r   _substitute_paramszSQLQuery._substitute_params,   s4   &  	J 6<< 	% 	%E$$ %ABBi&=="3KE!%#u66 -c%jj1111#E3// -"'--T":":n'nnn5555 e,,,, MM%((((e$$$$wwvr   redis://localhost:6379redis_client	redis_urlc                 x   	 ddl m} ddlm} n# t          $ r t	          d          w xY w|ddlm} |                    |          } ||          }|                                  ||          }| 	                    | j
        | j                  }|                    |          }	|	                                S )a?  Translate the SQL query to a Redis command string.

        This method uses the sql-redis translator to convert the SQL statement
        into the equivalent Redis FT.SEARCH or FT.AGGREGATE command.

        Args:
            redis_client: A Redis client connection used to load index schemas.
                If not provided, a connection will be created using redis_url.
            redis_url: The Redis URL to connect to if redis_client is not provided.
                Defaults to "redis://localhost:6379".

        Returns:
            The Redis command string (e.g., 'FT.SEARCH products "@category:{electronics}"').

        Raises:
            ImportError: If sql-redis package is not installed.

        Example:
            .. code-block:: python

                from redisvl.query import SQLQuery

                sql_query = SQLQuery("SELECT * FROM products WHERE category = 'electronics'")

                # Using redis_url
                redis_cmd = sql_query.redis_query_string(redis_url="redis://localhost:6379")

                # Or using an existing client
                from redis import Redis
                client = Redis()
                redis_cmd = sql_query.redis_query_string(redis_client=client)

                print(redis_cmd)
                # Output: FT.SEARCH products "@category:{electronics}"
        r   )SchemaRegistry)
Translatorz\sql-redis is required for SQL query support. Install it with: pip install redisvl[sql-redis]N)Redis)sql_redis.schemar*   sql_redis.translatorr+   ImportErrorredisr,   from_urlload_allr%   r   r	   	translateto_command_string)
r   r'   r(   r*   r+   r,   registry
translatorr   
translateds
             r   redis_query_stringzSQLQuery.redis_query_string]   s   P	7777777777777 	 	 	B  	 ###### >>)44L ">,//  Z))
 %%dh<<))#..
++---s    ))N)Nr&   )__name__
__module____qualname____doc__r   r   r   r   r   r%   r8    r   r   r   r      s         2	# 	#C 	#$sCx.)A 	# 	# 	# 	#/c /4S> /c / / / /f '+1B. B.smB. B. 
	B. B. B. B. B. B.r   r   )r<   r   typingr   r   r   r   r=   r   r   <module>r?      sn    C C 				 & & & & & & & & & &X. X. X. X. X. X. X. X. X. X.r   