
    ¿#j-D                    Z   d dl mZmZmZmZmZmZmZmZm	Z	 ddl
Z
ddlmZ ddlmZ ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlZddlmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'Z'ddl(m)Z) 	 dd	l*m+Z+ d
Z- ej\                  d      Z/ ej\                  dej`                  ejb                  z        Z2	 ddl3Z4	 ddl5Z6 edd      Z7de7_8         edd      Z9de9_8         edd      Z: edd      Z; edd      Z< edd      Z= edd      Z> G d de?      Z@e#eAe:e&eAeAf   e&eAeAeAf   e&eAeAeAeAf   f   ZBe#e"eB   e%eB   f   ZC G d d       ZD eD       ZEi eFd!eGd"eHd"eAd#eId#eJd#eKd#eLj                  d$eLd$eNd$ej                   d#ej                  d#ej                  d#ej                  d#ej                  d!dj                  d#e'j                  d#d#d"d!d$d#d#d"d"d!d$d$d%ZTe6r	 eTj                  e6j                  d"e6j                  d"e6j                  d"e6j                  d"e6j                  d"e6j                  d"e6j                  d"e6j                  d"e6j                  d!e6j                  d!e6j                  d!i       e4reTj                  e4j                  d#i        G d& d'e?      Zc G d( d)e?      Zd G d* d+e?      Ze G d, d-e?      Zf G d. d/e?      Zg G d0 d1e?      Zh G d2 d3e?      Zi G d4 d5eA      Zj G d6 d7e?      Zkd8j                         Zm G d9 d:      Zn G d; d<      Zo G d= d>eo      Zp G d? d@eo      ZqdA ZrdBe$e#e eAeAf   e%eA   e&eA   f      dCeIfdDZsdE ZtdFe"e eAef      fdGZudH Zvy# e,$ r dZ+Y w xY w# e,$ r dZ4Y w xY w# e,$ r dZ6Y w xY w# ea$ r Y "w xY w)I   )	chunkshash_recordsqlite3OperationalErrorsuggest_column_typestypes_for_column_typescolumn_affinityprogressbarfind_spatialite    N)
namedtuple)Mapping)	rank_bm25)
castAnyCallableDict	GeneratorIterableUnionOptionalListTuple)pm)iterdump  z\s+|(".*?")a  
^ # Start of string
\s*CREATE\s+VIRTUAL\s+TABLE\s+ # CREATE VIRTUAL TABLE
(
    '(?P<squoted_table>[^']*(?:''[^']*)*)' | # single quoted name
    "(?P<dquoted_table>[^"]*(?:""[^"]*)*)" | # double quoted name
    `(?P<backtick_table>[^`]+)`            | # `backtick` quoted name
    \[(?P<squarequoted_table>[^\]]+)\]     | # [...] quoted name
    (?P<identifier>                          # SQLite non-quoted identifier
        [A-Za-z_\u0080-\uffff]  # \u0080-\uffff = "any character larger than u007f"
        [A-Za-z_\u0080-\uffff0-9\$]* # zero-or-more alphanemuric or $
    )
)
\s+(IF\s+NOT\s+EXISTS\s+)?      # IF NOT EXISTS (optional)
USING\s+(?P<using>\w+)          # for example USING FTS5
Column)cidnametypenotnulldefault_valueis_pkaF  
Describes a SQLite column returned by the  :attr:`.Table.columns` property.

``cid``
    Column index

``name``
    Column name

``type``
    Column type

``notnull``
    Does the column have a ``not null`` constraint

``default_value``
    Default value for this column

``is_pk``
    Is this column part of the primary key
ColumnDetails)tablecolumn
total_rowsnum_null	num_blanknum_distinctmost_commonleast_commonaH  
Summary information about a column, see :ref:`python_api_analyze_column`.

``table``
    The name of the table

``column``
    The name of the column

``total_rows``
    The total number of rows in the table

``num_null``
    The number of rows for which this column is null

``num_blank``
    The number of rows for which this column is blank (the empty string)

``num_distinct``
    The number of distinct values in this column

``most_common``
    The ``N`` most common values as a list of ``(value, count)`` tuples, or ``None`` if the table consists entirely of distinct values

``least_common``
    The ``N`` least common values as a list of ``(value, count)`` tuples, or ``None`` if the table is entirely distinct
    or if the number of distinct values is less than N (since they will already have been returned in ``most_common``)

ForeignKeyr%   r&   other_tableother_columnIndex)seqr   uniqueoriginpartialcolumnsXIndex)r   r6   XIndexColumn)seqnor   r   desccollkeyTrigger)r   r%   sqlc                       e Zd Zy)TransformErrorN__name__
__module____qualname__     e/home/mi/.openclaw/workspace/fridge-app/backend/.venv/lib/python3.12/site-packages/sqlite_utils/db.pyr@   r@          rF   r@   c                       e Zd Zy)DefaultNrA   rE   rF   rG   rJ   rJ      rH   rF   rJ   FLOATINTEGERTEXTBLOB)rM   rL   rK   rN   textstrintegerintfloatblobbytesc                       e Zd ZdZy)
AlterErrorzError altering tableNrB   rC   rD   __doc__rE   rF   rG   rW   rW      s    rF   rW   c                       e Zd ZdZy)NoObviousTablez3Could not tell which table this operation refers toNrX   rE   rF   rG   r[   r[      s    9rF   r[   c                       e Zd ZdZy)NoTablezSpecified table does not existNrX   rE   rF   rG   r]   r]          $rF   r]   c                       e Zd ZdZy)BadPrimaryKeyz0Table does not have a single obvious primary keyNrX   rE   rF   rG   r`   r`      s    6rF   r`   c                       e Zd ZdZy)NotFoundErrorzRecord not foundNrX   rE   rF   rG   rb   rb     s    rF   rb   c                       e Zd ZdZy)PrimaryKeyRequiredz!Primary key needs to be specifiedNrX   rE   rF   rG   rd   rd     s    'rF   rd   c                       e Zd ZdZy)InvalidColumnszSpecified columns do not existNrX   rE   rF   rG   rf   rf     r^   rF   rf   c                       e Zd Zy)	DescIndexNrA   rE   rF   rG   rh   rh     rH   rF   rh   c                       e Zd ZdZd Zy)BadMultiValuesz4With multi=True code must return a Python dictionaryc                     || _         y N)values)selfrm   s     rG   __init__zBadMultiValues.__init__  s	    rF   N)rB   rC   rD   rY   ro   rE   rF   rG   rj   rj     s
    :rF   rj   z]
CREATE TABLE IF NOT EXISTS [{}](
   [table] TEXT PRIMARY KEY,
   count INTEGER DEFAULT 0
);
c            !       ,   e Zd ZdZdZdZ	 	 	 	 	 	 	 	 	 d_deeee	j                  ej                  f      dedee   ded	ed
ee   dededefdZd`dZej$                  d        Zej$                  dad
ee   fd       Zdeded   fdZdefdZ	 	 	 	 dbdee   dededee   fdZd Zdedeee	j                  f   fdZ	 dad ed!eeeef      deeddf   fd"Z	 dad ed#eeeef      dej<                  fd$Zd edej<                  fd%Z deded   fd&Z!d'edefd(Z"d)edefd*Z#d'edefd+Z$dcd,ed-ede%e   fd.Z&de%e   fd/Z'e(de%d0   fd1       Z)e(de%d2   fd3       Z*e(de%e+   fd4       Z,e(de-eef   fd5       Z.e(defd6       Z/e(defd7       Z0e(de1e2d8f   fd9       Z3e(defd:       Z4d; Z5d< Z6d= Z7d> Z8dad?eee      de-ee2f   fd@Z9dA Z:	 dad ed!eeeef      de%e   fdBZ;dedCe<de%e=   fdDZ>	 	 	 	 	 	 	 	 	 	 dddedEe-ee?f   dFee?   dCee<   dGee%e      dHeee      dIee-ee?f      dJee   dKeee      dLeee-eef   e%e   f      dMededefdNZ@	 	 	 	 	 	 	 	 	 	 	 	 	 dededEe-ee?f   dFee?   dCee<   dGee%e      dHeee      dIee-ee?f      dJee   dKeee      dLeee-eef   e%e   f      dMededOedPededd0f dQZAdedRefdSZB	 dcded edOedefdTZCdUedVede%e   fdWZDdCee1eeeef      fdXZEdY ZFdZ ZGdad[ZHdeeddf   fd\ZIdad]ee   defd^ZJy)fDatabasea  
    Wrapper for a SQLite database connection that adds a variety of useful utility methods.

    To create an instance::

        # create data.db file, or open existing:
        db = Database("data.db")
        # Create an in-memory database:
        dB = Database(memory=True)

    :param filename_or_conn: String path to a file, or a ``pathlib.Path`` object, or a
      ``sqlite3`` connection
    :param memory: set to ``True`` to create an in-memory database
    :param memory_name: creates a named in-memory database that can be shared across multiple connections
    :param recreate: set to ``True`` to delete and recreate a file database (**dangerous**)
    :param recursive_triggers: defaults to ``True``, which sets ``PRAGMA recursive_triggers=on;`` -
      set to ``False`` to avoid setting this pragma
    :param tracer: set a tracer function (``print`` works for this) which will be called with
      ``sql, parameters`` every time a SQL query is executed
    :param use_counts_table: set to ``True`` to use a cached counts table, if available. See
      :ref:`python_api_cached_table_counts`
    :param strict: Apply STRICT mode to all created tables (unless overridden)
    _countsFNfilename_or_connmemorymemory_namerecreaterecursive_triggerstraceruse_counts_tableexecute_pluginsstrictc
                 B   d | _         d| _        ||s|r||s	|sJ d       |r=dj                  |      }
t        j                  |
dd      | _        d| _        || _         n|s|dk(  r"t        j                  d      | _        d| _        nt        |t        t        j                  f      r[|r5t        j                  j                  |      r	 t        j                  |       t        j                  t        |            | _        n|rJ d       || _        || _        |r| j!                  d       t#               | _        || _        |r*t(        j*                  j-                  | j
                  	       |	| _        y # t        $ r t        j                  d      | _         w xY w)
NFz5Either specify a filename_or_conn or pass memory=Truez file:{}?mode=memory&cache=sharedT)uricheck_same_threadz:memory:z4recreate cannot be used with connections, only pathszPRAGMA recursive_triggers=on;)conn)ru   rt   formatr   connectr   
isinstancerP   pathlibPathospathexistsremoveOSError_tracerexecuteset_registered_functionsry   r   hookprepare_connectionr{   )rn   rs   rt   ru   rv   rw   rx   ry   rz   r{   r}   s              rG   ro   zDatabase.__init__G  st      ,f[$&K	CB	C 
 4;;KHC"'DI
 DK*D':5
3DIDK(3*=>BGGNN+;<II./  ,<(=>DIW!WW<(DILL89*-%" 0GG&&DII&6!   !(
 ;DI	s   E9 9%Freturnc                 8    | j                   j                          y)z=Close the SQLite connection, and the underlying database fileN)r   closern   s    rG   r   zDatabase.closez  s    		rF   c              #      K   | j                   j                  }	 d| j                   _        d || j                   _        y# || j                   _        w xY ww)a  
        Ensure autocommit is off for this database connection.

        Example usage::

            with db.ensure_autocommit_off():
                # do stuff here

        This will reset to the previous autocommit state at the end of the block.
        N)r   isolation_level)rn   old_isolation_levels     rG   ensure_autocommit_offzDatabase.ensure_autocommit_off~  sE      #ii77	<(,DII%(;DII%(;DII%s   AA AAAc              #   r   K   | j                   }|xs t        | _         	 |  || _         y# || _         w xY ww)a  
        Context manager to temporarily set a tracer function - all executed SQL queries will
        be passed to this.

        The tracer function should accept two arguments: ``sql`` and ``parameters``

        Example usage::

            with db.tracer(print):
                db["creatures"].insert({"name": "Cleo"})

        See :ref:`python_api_tracing`.

        :param tracer: Callable accepting ``sql`` and ``parameters`` arguments
        N)r   print)rn   rx   prev_tracers      rG   rx   zDatabase.tracer  s4     " ll	'J&DL;DLs   7+ 7	47
table_name)TableViewc                 $    | j                  |      S )a  
        ``db[table_name]`` returns a :class:`.Table` object for the table with the specified name.
        If the table does not exist yet it will be created the first time data is inserted into it.

        :param table_name: The name of the table
        r%   rn   r   s     rG   __getitem__zDatabase.__getitem__  s     zz*%%rF   c                 8    dj                  | j                        S )Nz<Database {}>)r   r   r   s    rG   __repr__zDatabase.__repr__  s    %%dii00rF   fndeterministicreplacer   c                 4      fd}||S  ||       y)af  
        ``fn`` will be made available as a function within SQL, with the same name and number
        of arguments. Can be used as a decorator::

            @db.register_function
            def upper(value):
                return str(value).upper()

        The decorator can take arguments::

            @db.register_function(deterministic=True, replace=True)
            def upper(value):
                return str(value).upper()

        See :ref:`python_api_register_function`.

        :param fn: Function to register
        :param deterministic: set ``True`` for functions that always returns the same output for a given input
        :param replace: set ``True`` to replace an existing function with the same name - otherwise throw an error
        :param name: name of the SQLite function - if not specified, the Python function name will be used
        c                    xs | j                   }t        t        j                  |       j                        }s||fj
                  v r| S i }d}r-	  j                  j                  ||| fi t        |d       d}|s j                  j                  ||| fi | j
                  j                  ||f       | S # t        j                  $ r Y Uw xY w)NFT)r   )rB   leninspect	signature
parametersr   r   create_functiondictr   NotSupportedErroradd)	r   fn_namearitykwargs
registeredr   r   r   rn   s	        rG   registerz,Database.register_function.<locals>.register  s    )bkkG))"-889E/43M3MM	FJ-DII--.26.N "&J )		))'5"GG&&**GU+;<I 00 s   ,C CCNrE   )rn   r   r   r   r   r   s   ` ``` rG   register_functionzDatabase.register_function  s    :	* :ORLrF   c                 4    | j                  t        dd       y)z`Register the ``rank_bm25(match_info)`` function used for calculating relevance with SQLite FTS4.T)r   r   N)r   r   r   s    rG   register_fts4_bm25zDatabase.register_fts4_bm25  s    ydKrF   aliasfilepathc                     dj                  t        t        j                  |      j	                               |      j                         }| j                  |       y)a  
        Attach another SQLite database file to this connection with the specified alias, equivalent to::

            ATTACH DATABASE 'filepath.db' AS alias

        :param alias: Alias name to use
        :param filepath: Path to SQLite database file on disk
        z3
            ATTACH DATABASE '{}' AS [{}];
        N)r   rP   r   r   resolvestripr   )rn   r   r   
attach_sqls       rG   attachzDatabase.attach  sG    FX&..015

%'	 	
 	Z rF   r>   paramsc              #      K   | j                  ||xs
 t                     }|j                  D cg c]  }|d   	 }}|D ]  }t        t	        ||              yc c}w w)a   
        Execute ``sql`` and return an iterable of dictionaries representing each row.

        :param sql: SQL query to execute
        :param params: Parameters to use in that query - an iterable for ``where id = ?``
          parameters, or a dictionary for ``where id = :id``
        r   N)r   tupledescriptionr   zip)rn   r>   r   cursordkeysrows          rG   queryzDatabase.query   sa      c6#4UW5$001!11 	'Cs4~&&	' 2s   -A!A&A!r   c                     | j                   r| j                  ||       || j                  j                  ||      S | j                  j                  |      S )a	  
        Execute SQL query and return a ``sqlite3.Cursor``.

        :param sql: SQL query to execute
        :param parameters: Parameters to use in that query - an iterable for ``where id = ?``
          parameters, or a dictionary for ``where id = :id``
        )r   r   r   )rn   r>   r   s      rG   r   zDatabase.execute  sK     <<LLj)!99$$S*5599$$S))rF   c                 t    | j                   r| j                  |d       | j                  j                  |      S )z
        Execute multiple SQL statements separated by ; and return the ``sqlite3.Cursor``.

        :param sql: SQL to execute
        N)r   r   executescriptrn   r>   s     rG   r   zDatabase.executescript   s.     <<LLd#yy&&s++rF   c                     || j                         v rt        | |fi |S |j                  d| j                         t	        | |fi |S )z
        Return a table object, optionally configured with default options.

        See :ref:`reference_db_table` for option details.

        :param table_name: Name of the table
        r{   )
view_namesr   
setdefaultr{   r   )rn   r   r   s      rG   r%   zDatabase.table*  sK     **j3F33h4z4V44rF   valuec                 L    | j                  dd|i      j                         d   S )z
        Apply SQLite string quoting to a value, including wrapping it in single quotes.

        :param value: String to quote
        zSELECT quote(:value)r   r   r   fetchonern   r   s     rG   quotezDatabase.quote8  s0     ||"e
 (*Q	 	rF   r   c                     |j                  d      dz  r|dz  }t        j                  |      }|D cg c]  }|s|dk7  s| }}dj                  d |D              S c c}w )a  
        Escape special characters in a SQLite full-text search query.

        This works by surrounding each token within the query with double
        quotes, in order to avoid words like ``NOT`` and ``OR`` having
        special meaning as defined by the FTS query syntax here:

        https://www.sqlite.org/fts5.html#full_text_query_syntax

        If the query has unbalanced ``"`` characters, adds one at end.

        :param query: String to escape
        "   z"" c              3   d   K   | ](  }|j                  d       sdj                  |      n| * yw)r   "{}"N)
startswithr   ).0bits     rG   	<genexpr>z%Database.quote_fts.<locals>.<genexpr>Y  s.      
GJcnnS&9FMM#sB
s   .0)count_quote_fts_resplitjoin)rn   r   bitsbs       rG   	quote_ftszDatabase.quote_ftsG  sl     ;;saSLE""5)3a1d33xx 
NR
 
 	
 4s   AAAc                    t        t        |      j                  d      xr t        |      j                  d      t        |      j                  d      xr t        |      j                  d      g      r|S t        |      j	                         dv r|S t        |      j                  d      rdj                  |      S | j                  |      S )N'r   )CURRENT_TIMECURRENT_DATECURRENT_TIMESTAMP)z({}))anyrP   r   endswithupperr   r   r   s     rG   quote_default_valuezDatabase.quote_default_value]  s    E
%%c*Gs5z/B/B3/GE
%%c*Gs5z/B/B3/G
 Lu:!VVLu:s#==''zz%  rF   fts4fts5c                     dg}|r|j                  d       |r|j                  d       dj                  dj                  |            }| j                  |      j	                         D cg c]  }|d   	 c}S c c}w )z
        List of string table names in this database.

        :param fts4: Only return tables that are part of FTS4 indexes
        :param fts5: Only return tables that are part of FTS5 indexes
        ztype = 'table'zsql like '%USING FTS4%'zsql like '%USING FTS5%'z'select name from sqlite_master where {} AND r   )appendr   r   r   fetchall)rn   r   r   wherer>   rs         rG   table_nameszDatabase.table_nameso  so     ""LL23LL237>>w||E?RS"ll3/88:;!;;;s   +A:c                 l    | j                  d      j                         D cg c]  }|d   	 c}S c c}w )z+List of string view names in this database.z2select name from sqlite_master where type = 'view'r   )r   r   rn   r   s     rG   r   zDatabase.view_names~  s;     \\Dhj	
 aD
 	
 
s   1r   c                 p    t        t        d   | j                         D cg c]  }| |   	 c}      S c c}w )z'List of Table objects in this database.r   )r   r   r   rn   r   s     rG   tableszDatabase.tables  s0     DM4;K;K;M#N4DJ#NOO#N   3
r   c                 p    t        t        d   | j                         D cg c]  }| |   	 c}      S c c}w )z&List of View objects in this database.r   )r   r   r   r   s     rG   viewszDatabase.views  s.     DL$//:K"L$4:"LMM"Lr   c                 r    | j                  d      j                         D cg c]
  }t        |  c}S c c}w )zRList of ``(name, table_name, sql)`` tuples representing triggers in this database.zDselect name, tbl_name, sql from sqlite_master where type = 'trigger')r   r   r=   r   s     rG   triggerszDatabase.triggers  s;    
 \\Vhj	
 QK
 	
 
s   4c                 j    | j                   D ci c]  }|j                  |j                   c}S c c}w )zBA ``{trigger_name: sql}`` dictionary of triggers in this database.r  r   r>   rn   triggers     rG   triggers_dictzDatabase.triggers_dict  )     :>Gggkk)GGG   0c                     g }| j                  d      j                         D ]<  }|d   }|j                         j                  d      s|dz  }|j	                  |       > dj                  |      S )zSQL schema for this database.z3select sql from sqlite_master where sql is not nullr   ;
)r   r   r   r   r   r   )rn   sqlsr   r>   s       rG   schemazDatabase.schema  so     <<A

(*	C a&C99;'',s
KK	 yyrF   c                 V   	 dj                  t        j                  d            }| j                  5  | j                  j	                  dj                  |             | j                  j	                  dj                  |             ddd       y# 1 sw Y   yxY w# t
        $ r Y yw xY w)z'Does this database support STRICT mode?zt{}   z"create table {} (name text) strictzdrop table {}NTF)r   secrets	token_hexr   r   	Exceptionr   s     rG   supports_strictzDatabase.supports_strict  s    		g&7&7&;<J F		!!8??
K 		!!/"8"8"DE	F
 F
  		s/   0B ABB BB B 	B('B(.c                     | j                  d      j                         d   }t        t        t        |d   j                  d                  S )zEVersion of SQLite, as a tuple of integers for example ``(3, 36, 0)``.zselect sqlite_version()r   .)r   r   r   maprR   r   )rn   r   s     rG   sqlite_versionzDatabase.sqlite_version  s@     ll45>>@CSc!fll3/011rF   c                 F    | j                  d      j                         d   S )z|
        Current ``journal_mode`` of this database.

        https://www.sqlite.org/pragma.html#pragma_journal_mode
        zPRAGMA journal_mode;r   r   r   s    rG   journal_modezDatabase.journal_mode  s"     ||23<<>qAArF   c                     | j                   dk7  r+| j                         5  | j                  d       ddd       yy# 1 sw Y   yxY w)zT
        Sets ``journal_mode`` to ``'wal'`` to enable Write-Ahead Log mode.
        walzPRAGMA journal_mode=wal;Nr  r   r   r   s    rG   
enable_walzDatabase.enable_wal  sJ     %++- 9789 9 &9 9	   <Ac                     | j                   dk7  r+| j                         5  | j                  d       ddd       yy# 1 sw Y   yxY w)zKSets ``journal_mode`` back to ``'delete'`` to disable Write-Ahead Log mode.deletezPRAGMA journal_mode=delete;Nr  r   s    rG   disable_walzDatabase.disable_wal  sH    (++- <:;< < )< <r!  c                     | j                   5  | j                  t        j                  | j                               d d d        y # 1 sw Y   y xY wrl   )r   r   _COUNTS_TABLE_CREATE_SQLr   _counts_table_namer   s    rG   _ensure_counts_tablezDatabase._ensure_counts_table  s@    YY 	SLL1889P9PQR	S 	S 	Ss   /AAc                     | j                          | j                  D ]9  }|j                  |j                  | j                  k7  s*|j                          ; d| _        y)z
        Enable trigger-based count caching for every table in the database, see
        :ref:`python_api_cached_table_counts`.
        NT)r(  r   virtual_table_usingr   r'  enable_countsry   )rn   r%   s     rG   r+  zDatabase.enable_counts  sW    
 	!!#[[ 	&E))1JJ$"9"99##%	& !%rF   r   c                 (   dj                  | j                        }|r*|dj                  dj                  d |D                    z  }	 | j                  ||      j	                         D ci c]  }|d   |d    c}S c c}w # t
        $ r i cY S w xY w)z
        Return ``{table_name: count}`` dictionary of cached counts for specified tables, or
        all tables if ``tables`` not provided.

        :param tables: Subset list of tables to return counts for.
        zselect [table], count from {}z where [table] in ({}), c              3       K   | ]  }d   yw)?NrE   r   r%   s     rG   r   z)Database.cached_counts.<locals>.<genexpr>  s     <UUS<Us   r   r   )r   r'  r   r   r   r   )rn   r   r>   r   s       rG   cached_countszDatabase.cached_counts  s     .44T5L5LM+22499<Uf<U3UVVC	(,S&(A(J(J(LM1AaD!A$JMMM 	I	s$   	"B +A>;B >B BBc                 *   | j                   D cg c]  }|j                  s| }}| j                  5  | j                          | | j                     }|j                          |j                  d |D               ddd       yc c}w # 1 sw Y   yxY w)z&Re-calculate cached counts for tables.c              3   V   K   | ]!  }|j                   |j                         d  # yw))r%   r   N)r   execute_countr0  s     rG   r   z(Database.reset_counts.<locals>.<genexpr>   s*      $  **u/B/B/DE$s   ')N)r   has_counts_triggersr   r(  r'  delete_where
insert_all)rn   r%   r   counts_tables       rG   reset_countszDatabase.reset_counts  s    %)[[NEE4M4M%NNYY 	%%' 7 78L%%'## $#$ 		 	 O	 	s   BBAB		Bc                 8    t        | j                  ||            S rl   )listr   )rn   r>   r   s      rG   execute_returning_dictsz Database.execute_returning_dicts  s     DJJsF+,,rF   foreign_keysc                    t        t        | |         }t        d |D              rt        t        t           |      S t        d |D              rZg }|D ]Q  }t        t
        |      }|j                  |      }|j                  |      }|j                  t	        ||||             S |S t        d |D              sJ d       g }|D ]  }t        |      dk(  r|d   |k(  sJ dj                  ||             t        |      dv sJ d	       t        |      d
v r}t        |      dk(  r&t        t        t
        t
        t
        f   |dd       }n"t        t        t
        t
        t
        f   |      }|j                  t	        ||d   |d   |d                |j                  t	        ||d   |d   |j                  |d                       |S )a  
        Given a list of differing foreign_keys definitions, return a list of
        fully resolved ForeignKey() named tuples.

        :param name: Name of table that foreign keys are being defined for
        :param foreign_keys: List of foreign keys, each of which can be a
            string, a ForeignKey() named tuple, a tuple of (column, other_table),
            or a tuple of (column, other_table, other_column), or a tuple of
            (table, column, other_table, other_column)
        c              3   <   K   | ]  }t        |t                y wrl   )r   r-   r   fks     rG   r   z0Database.resolve_foreign_keys.<locals>.<genexpr>  s     Abz"j)A   c              3   <   K   | ]  }t        |t                y wrl   )r   rP   r@  s     rG   r   z0Database.resolve_foreign_keys.<locals>.<genexpr>  s     :rz"c":rB  c              3   H   K   | ]  }t        |t        t        f        y wrl   )r   r   r;  r@  s     rG   r   z0Database.resolve_foreign_keys.<locals>.<genexpr>#  s       
.0JrE4=)
s    "z(foreign_keys= should be a list of tuples   r   z$First item in {} should have been {})r      rE  z8foreign_keys= should be a list of tuple pairs or triples)rF  rE  r   Nr   )r   r   allr   r-   rP   guess_foreign_tableguess_foreign_columnr   r   r   r   )	rn   r   r=  r%   fksr&   r/   r0   tuple_or_lists	            rG   resolve_foreign_keyszDatabase.resolve_foreign_keys
  s    UDJ'ALAAZ(,77:\::C& Pc6*#77?$99+F

:dFKNO	P
 J 
4@
 
 	65	6 
 ) 	M=!Q&!!$,V9@@PTUV,}% *  J J	J 
 =!V+}%*$(sC})=}QR?P$QM$(sC})=}$MM

mA.a0@-PQBR 

%a(%a(22=3CD	-	< 
rF   r6   pkcolumn_ordernot_nulldefaultshash_idhash_id_columnsextractsif_not_existsc                 @	   |	r|d}| j                  ||xs g       }|D ci c]  }|j                  | }}t        |
      }
|
j                         D ]c  \  }}t	        |t
              rJ | |   j                         s| j                  |t        t        dd       t        |<   t        |||d      ||<   e |xs
 t               }|xs i }sJ d       t        fd|D              s@J dj                  t        |      t        t        j                                                  t        fd|D              sIJ d	j                  t        t        |            t        t        j                                                  t!        j                                t#        j                               }fd
}|j%                  |       |r|j'                  d|t        f       |}|D ]  j(                  |k(  rj+                  j,                        r.j,                  dk7  s>t/        fd| j(                     j0                  D              rjt3        dj                  j(                  j,                               g }d}t	        |t"              r&t5        |      dk(  rt	        |d   t              r|d   }t	        |t              r/|}||D cg c]  }|d   	 c}vr|j'                  d|t        f       |D ]  \  }}g }||k(  r|j7                  d       ||v r|j7                  d       ||v r7||   2|j7                  dj                  | j9                  ||                      ||v r<|j7                  dj                  ||   j(                  ||   j,                               t:        |   }|r|dk(  rd}|j7                  dj                  |||rddj=                  |      z   nd              d}|N|rLt5        |      dkD  r>dj                  dj=                  |D cg c]  }dj                  |       c}            }d j=                  |      }d!j                  |rd"nd||||r| j>                  rd#nd$      }|S c c}w c c}w c c}w )%ai  
        Returns the SQL ``CREATE TABLE`` statement for creating the specified table.

        :param name: Name of table
        :param columns: Dictionary mapping column names to their types, for example ``{"name": str, "age": int}``
        :param pk: String name of column to use as a primary key, or a tuple of strings for a compound primary key covering multiple columns
        :param foreign_keys: List of foreign key definitions for this table
        :param column_order: List specifying which columns should come first
        :param not_null: List of columns that should be created as ``NOT NULL``
        :param defaults: Dictionary specifying default values for columns
        :param hash_id: Name of column to be used as a primary key containing a hash of the other columns
        :param hash_id_columns: List of columns to be used when calculating the hash ID for a row
        :param extracts: List or dictionary of columns to be extracted during inserts, see :ref:`python_api_extracts`
        :param if_not_exists: Use ``CREATE TABLE IF NOT EXISTS``
        :param strict: Apply STRICT mode to table
        Nid)rV  r   rM  z$Tables must have at least one columnc              3   &   K   | ]  }|v  
 y wrl   rE   r   nr6   s     rG   r   z,Database.create_table_sql.<locals>.<genexpr>z        
AL
   z0not_null set {} includes items not in columns {}c              3   &   K   | ]  }|v  
 y wrl   rE   rY  s     rG   r   z,Database.create_table_sql.<locals>.<genexpr>  r[  r\  z0defaults set {} includes items not in columns {}c                 >    | d   v rj                  | d         S dS )Nr   r   )index)prN  s    rG   sort_keyz+Database.create_table_sql.<locals>.sort_key  s(    34Q4<3G|))!A$/PSPrF   r<   r   rowidc              3   V   K   | ]   }|j                   j                  k(  s| " y wrl   )r   r0   )r   crA  s     rG   r   z,Database.create_table_sql.<locals>.<genexpr>  s%      6166R__;T6s   ))No such column: {}.{}r   zPRIMARY KEYzNOT NULLz
DEFAULT {}z,REFERENCES [{other_table}]([{other_column}]))r/   r0   rK   REALz/   [{column_name}] {column_type}{column_extras}r    )column_namecolumn_typecolumn_extrasz,
   PRIMARY KEY ({pks})r-  [{}])pksz,
zSCREATE TABLE {if_not_exists}[{table}] (
{columns_sql}{extra_pk}
){strict};
        IF NOT EXISTS z STRICT)rT  r%   columns_sqlextra_pkr{   ) rL  r&   resolve_extractsitemsr   r   r   create_tablerR   rP   r-   r   rG  r   reprr   validate_column_namesr;  sortinsertr/   getr0   r   r6   rW   r   r   r   COLUMN_TYPE_MAPPINGr   r  )rn   r   r6   rM  r=  rN  rO  rP  rQ  rR  rS  rT  r{   rA  foreign_keys_by_columnextract_columnextract_tablecolumn_itemsra  column_defs	single_pkre  ri  rj  rk  column_type_strrp  r`  ro  r>   s     `  `       `                rG   create_table_sqlzDatabase.create_table_sqlG  s   > G00|7IrJ:F!GB"))R-!G!G#H--5^^-= 		)NM.%0u&--/!!-c1Jt!T&)GN#5?nmT6">2		 $su>r>>>w 
"*
 
 	
=DDNDW\\^!45
	
 

  
"*
 
 	
=DDXc',,.&9!:
	
 

 	glln-GMMO,#Q (+GS>2B 	B~~%'++boo*F')# 6/776 3 !+222>>2??S 	 	b$CGqLZ1s5KABb#I51!A$55##ACy1(4 	$KMi'$$]3h&$$Z0h&8K+@+L$$ ''(@(@+AV(WX 44$$BII$:;$G$S$S%;K%H%U%U J  2+>O /W4"(AHH + /;Hsxx66b	 I -	> B!299II<Av}}Q/<= : H jj- F.;*# &4+?+?9R  
 	 
S "Hp 6H =s   RR0Rignore	transformc                 .   | |   j                         r*|rt        t        | |         S |r| |   j                          |rt| |   j                         r`t        t        | |         }d}|j                  t        fd|j                         D              }D cg c]	  }||vs| }}|r*|j                         D ]  \  }}|j                  ||        |s|s|k7  rd}|rt              dt        |       |k7  rd}|j                  }d}t        |t              r|g}n|rt        |      }|r||k7  rd}|j                  D ch c]  }|j                  s|j                   }}|rt!        |      n	t!               }||k7  rd}|r||j"                  k7  rd}|r|j%                  ||||||       |S | j'                  |||||||||	|
||      }| j)                  |       | j+                  ||||||||	      }t        t        |      S c c}w c c}w )a  
        Create a table with the specified name and the specified ``{column_name: type}`` columns.

        See :ref:`python_api_explicit_create`.

        :param name: Name of table
        :param columns: Dictionary mapping column names to their types, for example ``{"name": str, "age": int}``
        :param pk: String name of column to use as a primary key, or a tuple of strings for a compound primary key covering multiple columns
        :param foreign_keys: List of foreign key definitions for this table
        :param column_order: List specifying which columns should come first
        :param not_null: List of columns that should be created as ``NOT NULL``
        :param defaults: Dictionary specifying default values for columns
        :param hash_id: Name of column to be used as a primary key containing a hash of the other columns
        :param hash_id_columns: List of columns to be used when calculating the hash ID for a row
        :param extracts: List or dictionary of columns to be extracted during inserts, see :ref:`python_api_extracts`
        :param if_not_exists: Use ``CREATE TABLE IF NOT EXISTS``
        :param replace: Drop and replace table if it already exists
        :param ignore: Silently do nothing if table already exists
        :param transform: If table already exists transform it to fit the specified schema
        :param strict: Apply STRICT mode to table
        Fc              3   4   K   | ]  \  }}|vr||f  y wrl   rE   )r   col_namecol_typeexisting_columnss      rG   r   z(Database.create_table.<locals>.<genexpr>  s+      #&Hh#33 8$#s   TN)typesdroprN  rO  rP  rM  )r   r6   rM  r=  rN  rO  rP  rQ  rR  rS  rT  r{   )rM  r=  rN  rO  rP  rQ  rR  )r   r   r   r  columns_dictr   rr  
add_columnr;  r   rm  r   rP   r6   r!   r   r   default_valuesr  r  r   r%   )rn   r   r6   rM  r=  rN  rO  rP  rQ  rR  rS  rT  r   r  r  r{   r%   should_transformmissing_columnsr&   columns_to_dropr  r  current_pks
desired_pkre  current_not_nulldesired_not_nullr>   created_tabler  s                                 @rG   rs  zDatabase.create_table  sf   P :E4:..T
!d**,T
+E$$11" #*1--/# O &6!w9NO  *9*?*?*A 9&Hh$$Xx89/W@P5P#'  )*+>S->?<O#' ))KJ"c" T
!"X
kZ7#' 05K1KK08s8}ce#33#' H(<(<<#' !(!-%%    L##%%+' $ 
 	S

%%+ # 	
 E=))G0  Ls   	H'HHHnew_namec                 H    | j                  dj                  ||             y)zx
        Rename a table.

        :param name: Current table name
        :param new_name: Name to rename it to
        z+ALTER TABLE [{name}] RENAME TO [{new_name}])r   r  N)r   r   )rn   r   r  s      rG   rename_tablezDatabase.rename_tableP  s)     	9@@H A 	
rF   c                     |r	|rJ d       dj                  ||      }|s|r?|| j                         v r-|r| S |r'|| |   j                  k(  r| S | |   j                          | j	                  |       | S )a  
        Create a new SQL view with the specified name - ``sql`` should start with ``SELECT ...``.

        :param name: Name of the view
        :param sql: SQL ``SELECT`` query to use for this view.
        :param ignore: Set to ``True`` to do nothing if a view with this name already exists
        :param replace: Set to ``True`` to replace the view if one with this name already exists
        z0Use one or the other of ignore/replace, not bothzCREATE VIEW {name} AS {sql})r   r>   )r   r   r  r  r   )rn   r   r>   r  r   
create_sqls         rG   create_viewzDatabase.create_view]  s     w	>=	> 
 399t9M
Wt((K!T$Z%6%66#JOO%Z rF   r%   r/   c                     g }||h}| j                   D ]R  }|j                  D ch c]  }|j                   }}|j                  |      s8|j	                  |j
                         T |S c c}w )a&  
        Given two table names returns the name of tables that could define a
        many-to-many relationship between those two tables, based on having
        foreign keys to both of the provided tables.

        :param table: Table name
        :param other_table: Other table name
        )r   r=  r/   
issupersetr   r   )rn   r%   r/   
candidatesr   	table_objrA  
has_fks_tos           rG   m2m_table_candidateszDatabase.m2m_table_candidatesy  sq     
% 	2I3<3I3IJR"..JJJ$$V,!!)..1		2
  Ks   A*c                   	
 t        d |D              sJ d       g }|D ]2  \  }
	| |   j                         st        dj                  |            | |   }t	        |t
              st        dj                  |            t        t
        |      }|j                  vrt        dj                  |            | 
   j                         st        dj                  
            	dk7  r,	| 
   j                  vrt        dj                  	
            t        	
fd	|j                  D              r|j                  |
	f       5 i }|D ]&  }|j                  |d
   g       j                  |       ( |j                         D ](  \  }}t        t
        | |         j                  |       * | j                          y)z
        See :ref:`python_api_add_foreign_keys`.

        :param foreign_keys: A list of  ``(table, column, other_table, other_column)``
          tuples
        c              3   h   K   | ]*  }t        |      d k(  xr t        |t        t        f       , yw)rE  N)r   r   r;  r   r@  s     rG   r   z,Database.add_foreign_keys.<locals>.<genexpr>  s0      
?ACGqL:ZT5M::
s   02zSforeign_keys must be a list of 4-tuples, (table, column, other_table, other_column)zNo such table: {}zMust be a table, not a view: {}zNo such column: {} in {}zNo such other_table: {}rc  zNo such other_column: {} in {}c              3   |   K   | ]3  }|j                   k(  r"|j                  k(  r|j                  k(  r| 5 y wrl   r&   r/   r0   r   rA  r&   r0   r/   s     rG   r   z,Database.add_foreign_keys.<locals>.<genexpr>  s=      99&NNk1OO|3	    9<r   )add_foreign_keysN)rG  r   rW   r   r   r   r   r  r   r=  r   r   rr  r  vacuum)rn   r=  foreign_keys_to_creater%   r  by_tablerA  rJ  r&   r0   r/   s           @@@rG   r  zDatabase.add_foreign_keys  s     
EQ
 
 	a`	a 
 "$ 9E 	4E6;;%%' !4!;!;E!BCCUIi/ !B!I!I%!PQQUI.IY333 !;!B!B65!QRR$++- !:!A!A+!NOO' [(9(F(FF 4;;L+V   #00  '--FK>5	> %'( 	6B1r*11"5	6 #..* 	EJE3U$...D	E 	rF   c                 <   | j                         D ]  }| |   }|j                  D ch c]*  }t        |j                        dk(  s|j                  d   , }}|j                  D ]/  }|j
                  |vs|j                  |j
                  gd       1  yc c}w )zKCreate indexes for every foreign key column on every table in the database.r   r   T)find_unique_nameN)r   indexesr   r6   r=  r&   create_index)rn   r   r%   iexisting_indexesrA  s         rG   index_foreign_keyszDatabase.index_foreign_keys  s    **, 	KJ$E&+mm !"s199~7J		!    (( K99$44&&		{T&JK	K s   BBc                 &    | j                  d       y)z-Run a SQLite ``VACUUM`` against the database.zVACUUM;N)r   r   s    rG   r  zDatabase.vacuum  s    YrF   c                 V    d}||dj                  |      z  }| j                  |       y)z
        Run ``ANALYZE`` against the entire database or a named table or index.

        :param name: Run ``ANALYZE`` against this specific named table or index
        ANALYZENz [{}])r   r   )rn   r   r>   s      rG   analyzezDatabase.analyze  s.     7>>$''CSrF   c              #      K   t         rt        | j                        E d{    y	 | j                  j                         E d{    y7 )7 # t        $ r t        d      w xY ww)z=A sequence of strings representing a SQL dump of the databaseNz7conn.iterdump() not found - try pip install sqlite-dump)r   r   AttributeErrorr   s    rG   r   zDatabase.iterdump  s_     		***99--/// + 0! $M s8   A'AA'A AA 
A'A A$$A'r   c                    |
t               }| j                  j                  d       | j                  j                  |       d| j	                         v ry| j                  d      }|j                         }|xr t        |d         S )a  
        The ``init_spatialite`` method will load and initialize the SpatiaLite extension.
        The ``path`` argument should be an absolute path to the compiled extension, which
        can be found using ``find_spatialite``.

        Returns ``True`` if SpatiaLite was successfully initialized.

        .. code-block:: python

            from sqlite_utils.db import Database
            from sqlite_utils.utils import find_spatialite

            db = Database("mydb.db")
            db.init_spatialite(find_spatialite())

        If you've installed SpatiaLite somewhere unexpected (for testing an alternate version, for example)
        you can pass in an absolute path:

        .. code-block:: python

            from sqlite_utils.db import Database
            from sqlite_utils.utils import find_spatialite

            db = Database("mydb.db")
            db.init_spatialite("./local/mod_spatialite.dylib")

        :param path: Path to SpatiaLite module on disk
        Tspatial_ref_sysFzselect InitSpatialMetadata(1)r   )r   r   enable_load_extensionload_extensionr   r   r   bool)rn   r   r   results       rG   init_spatialitezDatabase.init_spatialite  sw    : <"$D		''-		  & 0 0 22=>")$vay/)rF   )	NFNFTNFTF)r   Nrl   )NFFN)FF)
NNNNNNNNFFNNNNNNNNFFFFF)KrB   rC   rD   rY   r'  ry   r   r   rP   r   r   r   
Connectionr  r   ro   r   
contextlibcontextmanagerr   rx   r   r   r   r   r   r   r   r   r   Cursorr   r   r%   r   r   r   r   r   r   propertyr   r  r=   r  r   r	  r  r  r   rR   r  r  r   r$  r(  r+  r1  r9  r<  ForeignKeysTyper-   rL  r   r  rs  r  r  r  r  r  r  r  r   r  rE   rF   rG   rq   rq   +  s(   0 # TX%)#'%)!& $1"5gllG<N<N)N#OP1 1 c]	1
 1 !1 "1 1 1 1f < <$ 'Xh/ ' '.&c &eO.D &1# 1
 "&#"5X5 5 	5
 sm5nL!C !5gll1B+C !" CG'' (x~)> ?'	4t#	$'  GK**$,U8T>-B$C*	*", , ,5 5%2H 53 3 
s 
s 
,! ! !$< <D <T#Y <
DI 
 PW P P NtF| N N 
$w- 
 
 HtCH~ H H 
 
 
    2c3h 2 2
 Bc B B9<S%HXc]$; tCQTH~ 
 CG-- (x~)> ?-	d-
;;'6;	j	;B !26,0,0-1!%37?C#KK c3hK SM	K
 /K tCy)K 8C=)K 4S>*K #K "(3-0K 5c3hc!:;<K K K 
Kb !26,0,0-1!%37?C#!z*z* c3hz* SM	z*
 /z* tCy)z* 8C=)z* 4S>*z* #z* "(3-0z* 5c3hc!:;<z* z* z* z* z*  !z*" 
#z*x
 
 
 JO!+/BF8# C DI $5XeCc3<N6O-P 5n	K 	
)CtO4 
'*HSM '*T '*rF   rq   c                      e Zd ZdefdZd Z	 	 ddee   deee	e
f      defdZd Zedefd	       Zedee
ddf   fd
       Z	 	 	 	 	 	 ddee   deee	e
f      dee   dedee   dee   dee
ddf   fdZ	 	 	 	 	 ddee   deee	e
f      dee   dee   dee   deeeef   ddf   fdZeded   fd       Zedeeef   fd       Zedefd       Zy)	Queryabler   c                      y)z"Does this table or view exist yet?FrE   r   s    rG   r   zQueryable.exists  s    rF   c                      || _         || _        y rl   )dbr   )rn   r  r   s      rG   ro   zQueryable.__init__  s    	rF   Nr   
where_argsc                     dj                  | j                        }||d|z   z  }| j                  j                  ||xs g       j	                         d   S )a5  
        Executes ``SELECT count(*) FROM table WHERE ...`` and returns a count.

        :param where: SQL where fragment to use, for example ``id > ?``
        :param where_args: Parameters to use with that fragment - an iterable for ``id > ?``
          parameters, or a dictionary for ``id > :id``
        zselect count(*) from [{}] where r   )r   r   r  r   r   )rn   r   r  r>   s       rG   count_wherezQueryable.count_where  sU     *00;9u$$CwwsJ$4"5>>@CCrF   c                 "    | j                         S rl   r  r   s    rG   r4  zQueryable.execute_count,  s    !!rF   c                 "    | j                         S )z*A count of the rows in this table or view.r  r   s    rG   r   zQueryable.count0  s     !!rF   c                 "    | j                         S )zCIterate over every dictionaries for each row in this table or view.)
rows_wherer   s    rG   rowszQueryable.rows5  s       rF   order_byselectlimitoffsetc              #     K   | j                         sydj                  || j                        }||d|z   z  }||d|z   z  }||dj                  |      z  }||dj                  |      z  }| j                  j	                  ||xs g       }|j
                  D 	cg c]  }	|	d   	 }
}	|D ]  }t        t        |
|              yc c}	w w)a  
        Iterate over every row in this table or view that matches the specified where clause.

        Returns each row as a dictionary. See :ref:`python_api_rows` for more details.

        :param where: SQL where fragment to use, for example ``id > ?``
        :param where_args: Parameters to use with that fragment - an iterable for ``id > ?``
          parameters, or a dictionary for ``id > :id``
        :param order_by: Column or fragment of SQL to order by
        :param select: Comma-separated list of columns to select - defaults to ``*``
        :param limit: Integer number of rows to limit to
        :param offset: Integer for SQL offset
        Nzselect {} from [{}]r  z
 order by 	 limit {}
 offset {}r   )r   r   r   r  r   r   r   r   )rn   r   r  r  r  r  r  r>   r   re  r6   r   s               rG   r  zQueryable.rows_where:  s     , {{}#**6499=9u$$C<(**C;%%e,,C<&&v..Cj&6B7!'!3!34A1Q444 	*Cs7C())	* 5s   BCC*&Cc              #     K   | j                   D cg c]  }|j                   }}| j                   D cg c]  }|j                  s|j                   }}|s|j                  dd       dg}dj	                  d |D              }	| j                  |	|||||      D ]/  t        fd|D              }
t        |
      dk(  r|
d   }
|
f 1 yc c}w c c}w w)	aI  
        Like ``.rows_where()`` but returns ``(pk, row)`` pairs - ``pk`` can be a single value or tuple.

        :param where: SQL where fragment to use, for example ``id > ?``
        :param where_args: Parameters to use with that fragment - an iterable for ``id > ?``
          parameters, or a dictionary for ``id > :id``
        :param order_by: Column or fragment of SQL to order by
        :param select: Comma-separated list of columns to select - defaults to ``*``
        :param limit: Integer number of rows to limit to
        :param offset: Integer for SQL offset
        r   rc  ,c              3   >   K   | ]  }d j                  |        ywrl  Nr   r   ri  s     rG   r   z/Queryable.pks_and_rows_where.<locals>.<genexpr>x  s     U&--4U   )r  r   r  r  r  r  c              3   (   K   | ]	  }|     y wrl   rE   r   rM  r   s     rG   r   z/Queryable.pks_and_rows_where.<locals>.<genexpr>  s     1r3r71   r   N)r6   r   r#   rw  r   r  r   r   )rn   r   r  r  r  r  r&   column_namesrm  r  row_pkr   s              @rG   pks_and_rows_wherezQueryable.pks_and_rows_where`  s     & 37,,???)-Fvv{{FF7+)CUUU??! # 
 	C 1S11F6{a#+	 @Fs!   CCCCCBCr   c                     | j                         sg S | j                  j                  dj                  | j                              j                         }|D cg c]
  }t        |  c}S c c}w )zbList of :ref:`Columns <reference_db_other_column>` representing the columns in this table or view.zPRAGMA table_info([{}]))r   r  r   r   r   r   r   )rn   r  r   s      rG   r6   zQueryable.columns  sU     {{}Iww8??		JKTTV(,----s   A+c                 |    | j                   D ci c]"  }|j                  t        |j                        $ c}S c c}w )zU``{column_name: python-type}`` dictionary representing columns in this table or view.)r6   r   r	   r    rn   r&   s     rG   r  zQueryable.columns_dict  s0     IMUf_V[[99UUUs   '9c                 r    | j                   j                  d| j                  f      j                         d   S )z"SQL schema for this table or view.z,select sql from sqlite_master where name = ?r   )r  r   r   r   r   s    rG   r  zQueryable.schema  s2     ww:TYYL

(*Q 	rF   NN)NNN*NN)NNNNN)rB   rC   rD   r  r   ro   r   rP   r   r   r   rR   r  r4  r  r   r   r  r  r   r   r   r  r   r6   r  r  rE   rF   rG   r  r    s      $6:D}D U8T>23D 
	D"" "s " " !idD 01 ! !  $6:"&# $$*}$* U8T>23$* 3-	$*
 $* }$* $* 
4t#	$$*P  $6:"&# $$}$ U8T>23$ 3-	$
 }$ $ 
5d#T4/	0$L .h . . Vd38n V V   rF   r  c            $       V    e Zd ZU dZdZee   ed<   dZee	   ed<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dde
dedee	   d	ee   d
eee      deee      deeee	f      dedee   deee      dedededeeeeef   ee   f      dee   deeee	f      def" fdZdefdZedefd       ZdefdZedee   fd       Zedefd       Zdeeeeef   defdZeded    fd!       Zedee   fd"       Zedee   fd#       Z edee!   fd$       Z"edee#   fd%       Z$edeeef   fd&       Z%edeee	f   fd'       Z&edefd(       Z'	 	 	 	 	 	 	 	 	 	 	 	 	 ddeee	f   dee	   d	ee   d
eee      deee      deeee	f      dee   deee      deeeeef   ee   f      d)ededed*ededd fd+Z(d,edd fd-Z)ddde*dddddddd.d/ee   d0ee   d1ee   dee	   deee      deeee	f      d2eee      d3ee   d	ee   d
eee      d4ee   dd fd5Z+ddde*ddddddddd6d/ee   d0ee   d1ee   dee	   deee      deeee	f      d2ee   d3ee   d	ee   d
eee      d7ee   d4ee   dee   fd8Z,	 	 	 ddeeee   f   d9ee   d:ee   d0eeeef      dd f
d;Z-	 	 	 	 	 ddeeee.f      d<ee   d=ed)ed>ed?efd@Z/	 	 	 	 ddAedBee	   dCee   dDee   dEee	   f
dFZ0ddefdGZ1dHedefdIZ2dJefdKZ3	 	 	 ddHedJee   dLee   defdMZ4dN Z5edefdO       Z6	 	 	 	 ddee   dPedQedRee   def
dSZ7dee   dd fdTZ8ddUZ9dV Z:dee   fdWZ;ddXZ<	 	 	 	 	 	 ddeee      dYee   dZee   d[ee   d\ee   d]edefd^Z=	 	 	 	 	 	 	 	 dd_edYee   deee      dZee   d[ee   d\ee   d`eeeef      d]edaede>eddf   fdbZ?dc Z@deeeeeeAf   dd fddZB	 	 	 dd\ee   d`eeeef      d?edd fdeZC	 	 	 ddeeeeeeAf   dfee   dedee   dd f
dgZD	 	 	 	 	 	 	 	 ddeeee   f   dheEdiee   djee	   d1edked\ee   d`eeeef      dledmefdnZF	 ddoZGdp ZHdq ZIe*e*e*e*e*e*e*e*e*e*e*e*e*e*fdreee	f   d
eeee   eJf      deeee   eJf      deeeee	f   eJf      deeeeJf      deeee   eJf      deeeeJf      deeeeJf      deeeeJf      deeeeef   ee   eJf      deeeeef   eJf      deeeee	f   eJf      deeeeJf      dd fdsZKe*e*e*e*e*e*e*e*e*e*e*de*e*e*dde*f	 ddtZLe*e*e*e*e*e*e*e*e*e*e*e*f	 dduZMe*e*e*e*e*e*e*e*e*e*e*e*de*f	 ddvZNdweeee	f      dd fdxZO	 	 	 	 	 	 	 	 	 	 ddyeee	f   dzeeee	f      dee   d	ee   d
eee      deee      deeee	f      deeeeef   ee   f      deeeef      deeee	f      dee   fd{ZPde*dddfdJeed f   d|eeeeee	f      eee	f   f      deee	eJf      d}eeee	f      d~ee   defdZQd ZR	 	 	 	 	 ddHededededdf
dZS	 	 	 ddedededededefdZTdefdZU xZVS )r   ak  
    Tables should usually be initialized using the ``db.table(table_name)`` or
    ``db[table_name]`` methods.

    The following optional parameters can be passed to ``db.table(table_name, ...)``:

    :param db: Provided by ``db.table(table_name)``
    :param name: Provided by ``db.table(table_name)``
    :param pk: Name of the primary key column, or tuple of columns
    :param foreign_keys: List of foreign key definitions
    :param column_order: List of column names in the order they should be in the table
    :param not_null: List of columns that cannot be null
    :param defaults: Dictionary of column names and default values
    :param batch_size: Integer number of rows to insert at a time
    :param hash_id: If True, use a hash of the row values as the primary key
    :param hash_id_columns: List of columns to use for the hash_id
    :param alter: If True, automatically alter the table if it doesn't match the schema
    :param ignore: If True, ignore rows that already exist when inserting
    :param replace: If True, replace rows that already exist when inserting
    :param extracts: Dictionary or list of column names to extract into a separate table on inserts
    :param conversions: Dictionary of column names and conversion functions
    :param columns: Dictionary of column names to column types
    :param strict: If True, apply STRICT mode to table
    N
last_rowidlast_pkFr  r   rM  r=  rN  rO  rP  
batch_sizerQ  rR  alterr  r   rS  conversionsr6   r{   c                 l    t         |   ||       t        |||||||	|
|||||xs i ||      | _        y )N)rM  r=  rN  rO  rP  r  rQ  rR  r  r  r   rS  r  r6   r{   )superro   r   	_defaults)rn   r  r   rM  r=  rN  rO  rP  r  rQ  rR  r  r  r   rS  r  r6   r{   	__class__s                     rG   ro   zTable.__init__  sR    ( 	T"%%!+#)r
rF   r   c           	          dj                  | j                  | j                         sd      S dj                  dj                  d | j                  D                          S )Nz<Table {}{}>z (does not exist yet)z ({})r-  c              3   4   K   | ]  }|j                     y wrl   r   r   re  s     rG   r   z!Table.__repr__.<locals>.<genexpr>  s     -Kaff-K   )r   r   r   r   r6   r   s    rG   r   zTable.__repr__  sW    $$II {{} (
 	

 ^^DII-Kdll-K$KL
 	
rF   c                     | j                   j                  rJ| j                   j                  | j                  g      }|r"t	        t        |j                                     S | j                         S )zWCount of the rows in this table - optionally from the table count cache, if configured.)r  ry   r1  r   nextiterrm   r  )rn   countss     rG   r   zTable.count  sS     77##WW**DII;7FD122!!rF   c                 N    | j                   | j                  j                         v S rl   )r   r  r   r   s    rG   r   zTable.exists  s    yyDGG//111rF   c                 z    | j                   D cg c]  }|j                  s|j                   }}|sdg}|S c c}w )z#Primary key columns for this table.rc  )r6   r#   r   )rn   r&   namess      rG   rm  z	Table.pks  s:     ,0<<H6<<HHIE Is   88c                 <    t        d | j                  D               S )zXDoes this table use ``rowid`` for its primary key (no other primary keys are specified)?c              3   :   K   | ]  }|j                   s|  y wrl   )r#   )r   r&   s     rG   r   z"Table.use_rowid.<locals>.<genexpr>  s     I&FLLvIs   )r   r6   r   s    rG   	use_rowidzTable.use_rowid  s     IDLLIIIIrF   	pk_valuesc                    t        |t        t        f      s|g}| j                  }t	        |      dk(  r|d   n|}t	        |      t	        |      k7  r<t        dj                  t	        |      t	        |      dk(  r
d            d            |D cg c]  }dj                  |       }}| j                  dj                  |      |      }	 t        |      d   }|| _	        |S c c}w # t        $ r t
        w xY w)a  
        Return row (as dictionary) for the specified primary key.

        Raises ``sqlite_utils.db.NotFoundError`` if a matching row cannot be found.

        :param pk_values: A single value, or a tuple of values for tables that have a compound primary key
        r   r   zNeed {} primary key value{}rh  s[{}] = ? and )r   r;  r   rm  r   rb   r   r  r   r  
IndexError)rn   r	  rm  r  pk_namewheresr  r   s           rG   rx  z	Table.get  s     )dE]3"Ihh"%c(a-)A,Ys8s9~%-44HCHMb 7:  =@@*##G,@@w||F3Y?	 t*Q-C"DLJ A  	 	 s   C%C* *C:r-   c           	         g }| j                   j                  dj                  | j                              j	                         D ]8  }||\  }}}}}}}	}
|j                  t        | j                  |||             : |S )z+List of foreign keys defined on this table.zPRAGMA foreign_key_list([{}])r.   )r  r   r   r   r   r   r-   )rn   rJ  r   rV  r2   r   from_to_	on_update	on_deletematchs              rG   r=  zTable.foreign_keys   s     77??+22499=

(*	C ORLCUCIu

"ii$$.%(		 
rF   c                     t         j                  | j                        }|y|j                         d   j	                         S )zBType of virtual table, or ``None`` if this is not a virtual table.Nusing)_virtual_table_using_rer  r  	groupdictr   )rn   r  s     rG   r*  zTable.virtual_table_using3  s;     (--dkk:= )//11rF   c                    dj                  | j                        }g }| j                  j                  |      D ]  }|d   }|j	                  d      sdj                  |      n|}dj                  |      }g }| j                  j                  |      j                         D ]  \  }}	}
|j                  |
        ||d<   ddd	j                         D ]  \  }}||vs|||<    |j                  t        d
i |        |S )z&List of indexes defined on this table.PRAGMA index_list("{}")r   r   r   zPRAGMA index_info({})r6   re  r   )r4   r5   rE   )
r   r   r  r<  r   r   r   r   rr  r1   )rn   r>   r  r   
index_nameindex_name_quoted
column_sqlr6   r9   r   r   r<   defaults                rG   r  zTable.indexes;  s    (..tyy9772237 	)CVJ ",,S1 j) 
 1778IJJG$(GGOOJ$?$H$H$J % sDt$%$C	N+.1 = C C E 'Wc>&CH' NN5<3<(!	)" rF   c                    dj                  | j                        }g }| j                  j                  |      D ]  }|d   }|j	                  d      sdj                  |      n|}dj                  |      }g }| j                  j                  |      j                         D ]  }|j                  t        |         |j                  t        ||              |S )zPList of indexes defined on this table using the more detailed ``XIndex`` format.r  r   r   r   zPRAGMA index_xinfo({}))
r   r   r  r<  r   r   r   r   r8   r7   )	rn   r>   r  r   r  r  r  index_columnsinfos	            rG   xindexeszTable.xindexesS  s     (..tyy9772237 	>CVJ ",,S1 j) 
 2889JKJM
3<<> :$$\4%89:NN6*m<=	> rF   c                     | j                   j                  d| j                  f      j                         D cg c]
  }t	        |  c}S c c}w )z'List of triggers defined on this table.zUselect name, tbl_name, sql from sqlite_master where type = 'trigger' and tbl_name = ?)r  r   r   r   r=   r   s     rG   r  zTable.triggersf  sL    
 WW__$ hj
 QK
 	
 
s   A
c                 j    | j                   D ci c]  }|j                  |j                   c}S c c}w )zE``{trigger_name: sql}`` dictionary of triggers defined on this table.r  r  s     rG   r	  zTable.triggers_dictr  r
  r  c                     | j                   D ci c].  }|j                   |j                  t        |j                        0 c}S c c}w )zX``{column_name: default_value}`` dictionary of default values for columns in this table.)r6   r"   r   _decode_default_valuer  s     rG   r  zTable.default_valuesw  sI    
 ,,
##/ KK.v/C/CDD
 	
 
s   3Ac                     | j                   j                  d      d   j                         j                         }|j                  d      D cg c]  }|j                          }}d|v S c c}w )zIs this a STRICT table?r   r  STRICT)r  r   r   r   )rn   table_suffixr   table_optionss       rG   r{   zTable.strict  sd     {{((-b1779??A0<0B0B30GHHH=(( Is   A+rT  r  c                    |j                         D ci c]  \  }}||
 }}}| j                  j                  5  | j                  j                  | j                  |||||||||	|
||||       ddd       | S c c}}w # 1 sw Y   | S xY w)aG  
        Create a table with the specified columns.

        See :ref:`python_api_explicit_create` for full details.

        :param columns: Dictionary mapping column names to their types, for example ``{"name": str, "age": int}``
        :param pk: String name of column to use as a primary key, or a tuple of strings for a compound primary key covering multiple columns
        :param foreign_keys: List of foreign key definitions for this table
        :param column_order: List specifying which columns should come first
        :param not_null: List of columns that should be created as ``NOT NULL``
        :param defaults: Dictionary specifying default values for columns
        :param hash_id: Name of column to be used as a primary key containing a hash of the other columns
        :param hash_id_columns: List of columns to be used when calculating the hash ID for a row
        :param extracts: List or dictionary of columns to be extracted during inserts, see :ref:`python_api_extracts`
        :param if_not_exists: Use ``CREATE TABLE IF NOT EXISTS``
        :param replace: Drop and replace table if it already exists
        :param ignore: Silently do nothing if table already exists
        :param transform: If table already exists transform it to fit the specified schema
        :param strict: Apply STRICT mode to table
        )rM  r=  rN  rO  rP  rQ  rR  rS  rT  r   r  r  r{   N)rr  r  r   rs  r   )rn   r6   rM  r=  rN  rO  rP  rQ  rR  rS  rT  r   r  r  r{   r   r   s                    rG   createzTable.create  s    J 5<MMOD=D%4;DDWW\\ 	GG  		))!! /!+# ! 	$ ' E	$ s   A95A??B	r  c                 8   | j                         st        d| j                   d      | j                  j                  5  dj                  || j                        }| j                  j                  |       ddd       | j                  |   S # 1 sw Y   xY w)z
        Create a duplicate of this table, copying across the schema and all row data.

        :param new_name: Name of the new table
        zTable z does not existz6CREATE TABLE [{new_table}] AS SELECT * FROM [{table}];)	new_tabler%   N)r   r]   r   r  r   r   r   )rn   r  r>   s      rG   	duplicatezTable.duplicate  s     {{}F499+_=>>WW\\ 	!JQQ"ii R C GGOOC 	! wwx  	! 	!s    9BBr  renamer  rM  rO  rP  drop_foreign_keysr  r=  rN  
keep_tabler  r4  r  r5  r  r6  c                T   | j                         sJ d       | j                  |||||||||	|
|      }| j                  j                  d      j	                         d   }	 |r| j                  j                  d       | j                  j
                  5  |D ]  }| j                  j                  |        |r| j                  j                  d       ddd       |r| j                  j                  d       | S # 1 sw Y   (xY w# |r| j                  j                  d       w w xY w)	aR  
        Apply an advanced alter table, including operations that are not supported by
        ``ALTER TABLE`` in SQLite itself.

        See :ref:`python_api_transform` for full details.

        :param types: Columns that should have their type changed, for example ``{"weight": float}``
        :param rename: Columns to rename, for example ``{"headline": "title"}``
        :param drop: Columns to drop
        :param pk: New primary key for the table
        :param not_null: Columns to set as ``NOT NULL``
        :param defaults: Default values for columns
        :param drop_foreign_keys: Names of columns that should have their foreign key constraints removed
        :param add_foreign_keys: List of foreign keys to add to the table
        :param foreign_keys: List of foreign keys to set for the table, replacing any existing foreign keys
        :param column_order: List of strings specifying a full or partial column order
          to use when creating the table
        :param keep_table: If specified, the existing table will be renamed to this and will not be
          dropped
        z/Cannot transform a table that doesn't exist yetr3  zPRAGMA foreign_keysr   zPRAGMA foreign_keys=0;zPRAGMA foreign_key_check;NzPRAGMA foreign_keys=1;)r   transform_sqlr  r   r   r   )rn   r  r4  r  rM  rO  rP  r5  r  r=  rN  r6  r  pragma_foreign_keys_was_onr>   s                  rG   r  zTable.transform  s   F {{}OOO}!!/-%%! " 
 &*WW__5J%K%T%T%V&
"	:) 89 A )CGGOOC() .GGOO$?@A * 89A A * 89 *s%   !3D A C;D ;D D  D')r  r4  r  rM  rO  rP  r5  r  r=  rN  
tmp_suffixr6  r:  c                   |xs i }xs i |xs
 t               }g }|	,|t        d      |t        d      |j                  |	       ng }| j                  D ]>  \  }}}}|||vs|j	                  t        |j                  |      xs |||             @ || j                  j                  | j                  |      D ]d  }|j	                  t        | j                  j                  |j                        xs |j                  |j                  |j                               f dj                  | j                  |xs# t        j                  d      j!                               }t#        | j$                  j'                               }g }|D ci c]  \  }}||
 }}}|D ]O  \  }}|j                  |      xs |}||v r||= #j                  |      xs |}|j	                  ||f       |||<   Q |t(        u r4t+        fd| j,                  D              }t/        |      dk(  r|d   }n|}| j,                  D ch c]E  }|j0                  r7|j                  |vr)j                  |j                        xs |j                  G }}t3        |t4              rY|j'                         D ]E  \  }}j                  |      xs |}|du r||v r|j7                  |       5|j9                  |       G nMt3        |t               r|j;                  fd	|D               n"|snJ d
j                  t=        |                   | j,                  D ci c]P  }|j>                  B|j                  |vr4j                  |j                        xs |j                  |j>                  R } }|F| j;                  |j'                         D !ci c]  \  }}!j                  |      xs ||! c}!}       |
"|
D "cg c]  }"j                  |"      xs |" }
}"g }#|#j	                  | j                  jA                  |t5        |      ||| ||
| jB                        jE                                g }$g }%|j'                         D ]'  \  }&}'|%j	                  |&       |$j	                  |'       ) d|$vr$|$jG                  dd       |%jG                  dd       dj                  || j                  djI                  d |%D              djI                  d |$D                    }(|#j	                  |(       |r,|#j	                  dj                  | j                  |             n*|#j	                  dj                  | j                               |#j	                  dj                  || j                               | jJ                  D ]  })|)jL                  dk7  s| j                  jO                  dd|)j                  i      jQ                         d   d   }*|*&tS        d|)j                   d| j                   d      |r|#j	                  d|)j                   d       |)j,                  D ]D  }"|"jU                         v s|"|v stS        d|)j                   d|" d| j                   d|* d	       |#j	                  |*        |#S c c}}w c c}w c c}w c c}!}w c c}"w ) aD  
        Return a list of SQL statements that should be executed in order to apply this transformation.

        :param types: Columns that should have their type changed, for example ``{"weight": float}``
        :param rename: Columns to rename, for example ``{"headline": "title"}``
        :param drop: Columns to drop
        :param pk: New primary key for the table
        :param not_null: Columns to set as ``NOT NULL``
        :param defaults: Default values for columns
        :param drop_foreign_keys: Names of columns that should have their foreign key constraints removed
        :param add_foreign_keys: List of foreign keys to add to the table
        :param foreign_keys: List of foreign keys to set for the table, replacing any existing foreign keys
        :param column_order: List of strings specifying a full or partial column order
          to use when creating the table
        :param tmp_suffix: Suffix to use for the temporary table name
        :param keep_table: If specified, the existing table will be renamed to this and will not be
          dropped
        z5Cannot specify both foreign_keys and add_foreign_keysz6Cannot specify both foreign_keys and drop_foreign_keysz	{}_new_{}   c              3      K   | ]:  }|j                   sj                  |j                        xs |j                   < y wrl   )r#   rx  r   )r   r`  r4  s     rG   r   z&Table.transform_sql.<locals>.<genexpr>o  s5       12agg

166",aff, s
   A.Ar   r   Fc              3   H   K   | ]  }j                  |      xs |  y wrl   )rx  )r   kr4  s     rG   r   z&Table.transform_sql.<locals>.<genexpr>  s!     (P!&**Q-*<1*<(Ps   "z3not_null must be a dict or a set or None, it was {})rM  rO  rP  r=  rN  r{   rc  zOINSERT INTO [{new_table}] ({new_cols})
   SELECT {old_cols} FROM [{old_table}];r-  c              3   >   K   | ]  }d j                  |        ywr  r  r   cols     rG   r   z&Table.transform_sql.<locals>.<genexpr>       Fcv}}S1Fr  c              3   >   K   | ]  }d j                  |        ywr  r  rA  s     rG   r   z&Table.transform_sql.<locals>.<genexpr>  rC  r  )r1  	old_tableold_colsnew_colsz ALTER TABLE [{}] RENAME TO [{}];zDROP TABLE [{}];rM  zJSELECT sql FROM sqlite_master WHERE type = 'index' AND name = :index_name;r  zIndex 'z' on table 'z' does not have a CREATE INDEX statement. You must manually drop this index prior to running this transformation and manually recreate the new index after running this transformation.zDROP INDEX IF EXISTS [z];z
' column 'z' is not in updated table 'z'. You must manually drop this index prior to running this transformation and manually recreate the new index after running this transformation. The original index sql statement is: `z.`. No changes have been applied to this table.)+r   
ValueErrorextendr=  r   r-   rx  r  rL  r   r&   r/   r0   r   r   urandomhexr;  r  rr  DEFAULTr   r6   r   r!   r   r   r   r   updatert  r"   r  r{   r   rw  r   r  r4   r   r   r@   r   )+rn   r  r4  r  rM  rO  rP  r5  r  r=  rN  r:  r6  create_table_foreign_keysr%   r&   r/   r0   rA  new_table_namecurrent_column_pairsnew_column_pairs_copy_from_tor   type_r  pks_renamedre  create_table_not_nullr<   r   create_table_defaultsvrB  r  rG  rF  r  r  copy_sqlr_  	index_sqls+     `                                        rG   r8  zTable.transform_sql  s   D 2}su?A!#+ K  !, L  &,,\: )+%<@<M<M 
8v{L%-6AR3R-44"!"JJv.8&'(	
  +''66tyyBRS B-44" II"JJryy1>RYYNNOO	 %++IIz8RZZ]%6%6%8
  $D$5$5$;$;$=>8LM961MM/ 	*KD%IIdO,uEt|!$'zz$'/4H##Xu$56!)L	* =  6:ll  K ;1$ ^ 
 \\!
yyvvT! JJqvv(!&&(!
 !
 h%&nn. 3
Ujjo,E>c-B&B)005)--c23 #&!(((Px(PPOVVX 5 \\!
*qvvT/A ZZ)166AOO;!
 !

 !((3;>>3CD41aA#!Q&D #>JKsFJJsO2s2KLKGG$$%&..6){{ % 	 eg	
 &,,. 	!JE3OOE"OOC 	! ("OOAw'OOAw'ell$iiYYFXFFYYFXFF	 m 
 	HKK299$))ZP KK*11$))<=.55ndiiP	
 \\ 	'E||t# GGOOd!5::. (*Q  !"#	 $(!%**\$)) Ep p 
 KK"8B GH == Cfkkm+sd{,%ejj\C5@[\`\e\e[f gE FOKO}  I&-	'. w N(!
0!
 E Ls    Z<A
[A[
 [
8[r%   	fk_columnc                     xs i t        |t              r|g}t        |      j                   j                  j                               s<t        dj                  |t         j                  j                                           xs dj                  |       j                     }|xs dj                        }dj                  |t        j                  d      j                               } j                  j                         D ci c]  \  }}||v rj                  |      xs ||! }	}}|j!                         r[t        |	j                               j                  |j                  j                               s8t        dj                  |	            |j#                  i dt$        i|	d       |D cg c]  }j                  |      xs | }
}|j'                  |
d	d	
        j                  j)                  dj                  dj                  d |
D              dj                  d |D               j*                                j-                  |t$                j                  j)                  dj                   j*                  |dj                   fd|D                           g } j.                  D ]Q  }|j*                  |v r||vr|j1                  |       '|j*                  |k(  r7|j1                  |j*                         S  j3                  t        |      ||i|        j5                  |d        S c c}}w c c}w )a  
        Extract specified columns into a separate table.

        See :ref:`python_api_extract` for details.

        :param columns: Single column or list of columns that should be extracted
        :param table: Name of table in which the new records should be created
        :param fk_column: Name of the foreign key column to populate in the original table
        :param rename: Dictionary of columns that should be renamed when populating the new table
        z,Invalid columns {} for table with columns {}rR  {}_id{}_{}r<  z;Lookup table {} already exists but does not have columns {}rV  rW  T)r3   rT  zeINSERT OR IGNORE INTO [{lookup_table}] ({lookup_columns}) SELECT DISTINCT {table_cols} FROM [{table}]r-  c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z Table.extract.<locals>.<genexpr>  s     (Raq)9(Rr  c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z Table.extract.<locals>.<genexpr>  s     $G!V]]1%5$Gr  )lookup_tablelookup_columns
table_colsr%   z^UPDATE [{table}] SET [{magic_lookup_column}] = (SELECT id FROM [{lookup_table}] WHERE {where})r   c           	   3      K   | ]6  }d j                  j                  |j                  |      xs |       8 yw)z:[{table}].[{column}] IS [{lookup_table}].[{lookup_column}])r%   ra  r&   lookup_columnN)r   r   rx  )r   r&   r4  rn   r%   s     rG   r   z Table.extract.<locals>.<genexpr>-  sK      #  QWW"ii%*%&,jj&8&BF	 X #s   <?)r%   magic_lookup_columnra  r   )r  r4  rN  )r   rP   r   issubsetr  r   rf   r   r;  r   r  r   rJ  rK  rr  rx  r   r/  rR   r  r   r   r  r6   r   r  add_foreign_key)rn   r6   r%   r[  r4  ra  rf  rB  typlookup_columns_definitionrb  rN  re  s   ` ` `        rG   extractzTable.extract  sD   " 2gs#iG7|$$T%6%6%;%;%=> >EET$"3"3"8"8":; 
 *'*wwu~6!6	%nnY

18I8I8KL
 !--335%
Sg~ ZZ_#c)%
! %

  06689BB))//1 %QXX8  c 0	     ?FFs6::c?1c1FF!!.T!Rszz"#yy(R>(RR99$Gw$GGii	 { 	
 	+S1 	lssii$7"ll # #*# 	 t 	
"  	,Avv %8%L##$78..##AFF+	, 	W'3% 	 	
 	Yt4U%
0 Gs   $MM!r  r3   r  r  c                     |;dj                  | j                  j                  dd      dj                  |            }g }|D ]7  }t	        |t
              rd}	nd}	|j                  |	j                  |             9 d}
d}	 |
rdj                  ||
      n|}t        j                  d      j                         j                  || j                  d	j                  |      |rd
nd|rdnd      }	 | j                  j                  |       	 |r| j                  j!                  |       | S # t        $ rI}|j                  d   }|r1|j                  d      r |j                  d      r|
d}
n|
dz  }
Y d}~|d}~ww xY w)aT  
        Create an index on this table.

        :param columns: A single columns or list of columns to index. These can be strings or,
          to create an index using the column in descending order, ``db.DescIndex(column_name)`` objects.
        :param index_name: The name to use for the new index. Defaults to the column names joined on ``_``.
        :param unique: Should the index be marked as unique, forcing unique values?
        :param if_not_exists: Only create the index if one with that name does not already exist.
        :param find_unique_name: If ``index_name`` is not provided and the automatically derived name
          already exists, keep incrementing a suffix number to find an available name.
        :param analyze: Run ``ANALYZE`` against this index after creating it.

        See :ref:`python_api_create_index`.
        Nz	idx_{}_{}r   rR  z	[{}] descrl  r^  z
                CREATE {unique}INDEX {if_not_exists}[{index_name}]
                    ON [{table_name}] ({columns});
            r-  zUNIQUE rh  rn  )r  r   r6   r3   rT  r   zindex z already existsr   r   )r   r   r   r   r   rh   r   textwrapdedentr   r  r   r   argsr   r   r  )rn   r6   r  r3   rT  r  r  ro  r&   fmtsuffixcreated_index_namer>   eargs                  rG   r  zTable.create_indexM  s   . $++		!!#s+SXXg->J  	3F&),!szz&12	3 !6<z62*   1#yy IIk2(.9B6C"2    $  GGOO./# $ ffQi$x0%67~!"!Gs   0D+ +	E=4=E86E88E=r  r  rA  fk_colnot_null_defaultc                    d}||| j                   j                         vrt        dj                  |            |6|| j                   |   j                  vrst        dj                  ||            | j                   |   j
                  D cg c]  }|j                  s| }}|r|d   j                  }|d   j                  }nd}d}|t        }d}	|*dj                  | j                   j                  |            }	dj                  | j                  ||xs	 t        |   |	rd	|	z   nd
      }
| j                   j                  |
       || j                  |||       | S c c}w )a  
        Add a column to this table. See :ref:`python_api_add_column`.

        :param col_name: Name of the new column
        :param col_type: Column type - a Python type such as ``str`` or a SQLite type string such as ``"BLOB"``
        :param fk: Name of a table that this column should be a foreign key reference to
        :param fk_col: Column in the foreign key table that this should reference
        :param not_null_default: Set this column to ``not null`` and give it this default value
        Nztable '{}' does not existztable '{}' has no column {}r   rc  rL   zNOT NULL DEFAULT {}zKALTER TABLE [{table}] ADD COLUMN [{col_name}] {col_type}{not_null_default};r   rh  )r%   r  r  rv  )r  r   rW   r   r  r6   r#   r   r    rP   r   ry  r   rh  )rn   r  r  rA  ru  rv  fk_col_typere  rm  not_null_sqlr>   s              rG   r  zTable.add_column  si   " >,,.. !<!C!CB!GHH!!9!99$%B%I%I"f%UVV #'''"+"5"5AQqAA V[[F"%a&++K$F"+KH'077++,<=L \bb)) A$7$A5AcL0r	 c 
 	>  2v6/ Bs   E$ E$c                     	 | j                   j                  dj                  | j                               y# t        j
                  $ r |s Y yw xY w)zz
        Drop this table.

        :param ignore: Set to ``True`` to ignore the error if the table does not exist
        zDROP TABLE [{}]Nr  r   r   r   r   r   rn   r  s     rG   r  z
Table.drop  sG    	GGOO-44TYY?@'' 	 	   47 AAr&   c                    |j                         }|g}|j                  d      r<|dd }|j                  |       |j                  d      s:|j                  |dz          n%|j                  d      s|j                  |dz          | j                  j	                         D ci c]  }|j                         | }}|D ]  }||v s||   c S  t        dj                  |t        |                  c c}w )a  
        For a given column, suggest another table that might be referenced by this
        column should it be used as a foreign key.

        For example, a column called ``tag_id`` or ``tag`` or ``tags`` might suggest
        a ``tag`` table, if one exists.

        If no candidates can be found, raises a ``NoObviousTable`` exception.

        :param column: Name of column
        _idNr  z7No obvious foreign key table for column '{}' - tried {})lowerr   r   r  r   r[   r   rt  )rn   r&   possibilitiescolumn_without_idtexisting_tablesr%   s          rG   rH  zTable.guess_foreign_table  s     ??5! &s  !23$--c2$$%6%<=%  #.151D1D1FGA1779a<GG" 	.E'&u--	. ELL]+
 	
 Hs   "C2r/   c                     | j                   |   j                  D cg c]  }|j                  s| }}t        |      dk7  rt	        dj                  |            |d   j                  S c c}w )Nr   z2Could not detect single primary key for table '{}'r   )r  r6   r#   r   r`   r   r   )rn   r/   re  rm  s       rG   rI  zTable.guess_foreign_column  sf    ''+.66BQ!''qBBs8q=DKKKX  q6;; Cs
   A+A+r0   c                 4   | j                   vrt        dj                              | j                        | j	                        | j
                     j                  D cg c]  }|j                  k(  s| c}s dk7  rt        dj                              t        fd| j                  D              r |r| S t        dj                              | j
                  j                  | j                  fg       | S c c}w )a  
        Alter the schema to mark the specified column as a foreign key to another table.

        :param column: The column to mark as a foreign key.
        :param other_table: The table it refers to - if omitted, will be guessed based on the column name.
        :param other_column: The column on the other table it - if omitted, will be guessed.
        :param ignore: Set this to ``True`` to ignore an existing foreign key - otherwise a ``AlterError`` will be raised.
        zNo such column: {}rc  rf  c              3   |   K   | ]3  }|j                   k(  r"|j                  k(  r|j                  k(  r| 5 y wrl   r  r  s     rG   r   z(Table.add_foreign_key.<locals>.<genexpr>&	  s=      
yyF"+-</	 
r  z*Foreign key already exists for {} => {}.{})r  rW   r   rH  rI  r  r6   r   r   r=  r  )rn   r&   r/   r0   r  re  s    ```  rG   rh  zTable.add_foreign_key	  s     ***188@AA226:K44[AL !GGK088SqAFFl<RS'4;;KVWW 
''
 
  @GG\ 
 	  499fk<"P!QR+ Ts   -DDc                    t        j                  d      j                         j                  t        j                  | j
                  j                        | j
                  j                  | j                  | j
                  j                  | j                              }| j
                  j                  5  | j
                  j                  j                  |       ddd       d| j
                  _        y# 1 sw Y   xY w)z
        Set up triggers to update a cache of the count of rows in this table.

        See :ref:`python_api_cached_table_counts` for details.
        a  
        {create_counts_table}
        CREATE TRIGGER IF NOT EXISTS [{table}{counts_table}_insert] AFTER INSERT ON [{table}]
        BEGIN
            INSERT OR REPLACE INTO [{counts_table}]
            VALUES (
                {table_quoted},
                COALESCE(
                    (SELECT count FROM [{counts_table}] WHERE [table] = {table_quoted}),
                0
                ) + 1
            );
        END;
        CREATE TRIGGER IF NOT EXISTS [{table}{counts_table}_delete] AFTER DELETE ON [{table}]
        BEGIN
            INSERT OR REPLACE INTO [{counts_table}]
            VALUES (
                {table_quoted},
                COALESCE(
                    (SELECT count FROM [{counts_table}] WHERE [table] = {table_quoted}),
                0
                ) - 1
            );
        END;
        INSERT OR REPLACE INTO _counts VALUES ({table_quoted}, (select count(*) from [{table}]));
        )create_counts_tabler8  r%   table_quotedNT)rm  rn  r   r   r&  r  r'  r   r   r   r   ry   r   s     rG   r+  zTable.enable_counts8	  s     OO8 UWV$<$C$CGG..% "WW77ii!WW]]4995  = 	N WW\\ 	,GGLL&&s+	,#' 	, 	,s   5&C55C>c                     dD ch c]4  }dj                  | j                  j                  | j                  |      6 }}|j	                  | j
                  j                               S c c}w )z<Does this table have triggers setup to update cached counts?)rw  r#  z{table}{counts_table}_{suffix})r8  r%   rq  )r   r  r'  r   rg  r	  r   )rn   rq  trigger_namess      rG   r5  zTable.has_counts_triggersi	  sp     /	
  -33!WW77tyyQW 4 
 
 %%d&8&8&=&=&?@@
s   9A)fts_versioncreate_triggerstokenizec                 J   t        j                  d      j                         j                  | j                  dj                  d |D              ||rdj                  |      nd      }d}|r| j                  dj                  | j                           j                         r| j                  dj                  | j                           j                  }||k7  rd	}d
D 	ch c]  }	| j                  |	z    }
}	| j                  D ch c]  }|j                   }}|j                  |
      }||k7  rd	}|s| S |r| j                          | j                  j                  |       | j                  |       |rdj                  d |D              }dj                  d |D              }t        j                  d      j                         j                  | j                  dj                  d |D              ||      }| j                  j                  |       | S c c}	w c c}w )a  
        Enable SQLite full-text search against the specified columns.

        See :ref:`python_api_fts` for more details.

        :param columns: List of column names to include in the search index.
        :param fts_version: FTS version to use - defaults to ``FTS5`` but you may want ``FTS4`` for older SQLite versions.
        :param create_triggers: Should triggers be created to keep the search index up-to-date? Defaults to ``False``.
        :param tokenize: Custom SQLite tokenizer to use, for example ``"porter"`` to enable Porter stemming.
        :param replace: Should any existing FTS index for this table be replaced by the new one?
        z
            CREATE VIRTUAL TABLE [{table}_fts] USING {fts_version} (
                {columns},{tokenize}
                content=[{table}]
            )
        r-  c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z#Table.enable_fts.<locals>.<genexpr>	  s     !Dq&--"2!Dr  z
    tokenize='{}',rh  )r%   r6   r  r  Fz{}_ftsT)_ai_ad_auc              3   >   K   | ]  }d j                  |        yw)zold.[{}]Nr  r  s     rG   r   z#Table.enable_fts.<locals>.<genexpr>	        G!!2!21!5 Gr  c              3   >   K   | ]  }d j                  |        yw)znew.[{}]Nr  r  s     rG   r   z#Table.enable_fts.<locals>.<genexpr>	  r  r  a  
                CREATE TRIGGER [{table}_ai] AFTER INSERT ON [{table}] BEGIN
                  INSERT INTO [{table}_fts] (rowid, {columns}) VALUES (new.rowid, {new_cols});
                END;
                CREATE TRIGGER [{table}_ad] AFTER DELETE ON [{table}] BEGIN
                  INSERT INTO [{table}_fts] ([{table}_fts], rowid, {columns}) VALUES('delete', old.rowid, {old_cols});
                END;
                CREATE TRIGGER [{table}_au] AFTER UPDATE ON [{table}] BEGIN
                  INSERT INTO [{table}_fts] ([{table}_fts], rowid, {columns}) VALUES('delete', old.rowid, {old_cols});
                  INSERT INTO [{table}_fts] (rowid, {columns}) VALUES (new.rowid, {new_cols});
                END;
            c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z#Table.enable_fts.<locals>.<genexpr>	  s     %H1fmmA&6%Hr  )r%   r6   rF  rG  )rm  rn  r   r   r   r   r  r   r  r  r  disable_ftsr   populate_fts)rn   r6   r  r  r  r   create_fts_sqlshould_recreate
fts_schemarq  expected_triggersr  existing_triggershas_triggersrF  rG  r  s                    rG   
enable_ftszTable.enable_ftst	  s   ( OO UWVii		!DG!DD'DL/66x@RT	   	"  twwxtyy9:AAC!;<CCJ^+"&BW XV!3 X X15 ?A ? ?,778IJL."&"n-'"yy Gw GGHyy Gw GGH )) II%H%HH%%	  ! . GG!!(+U !Y ?s   !HH c                     t        j                  d      j                         j                  | j                  dj                  d |D                    }| j                  j                  |       | S )z
        Update the associated SQLite full-text search index with the latest data from the
        table for the specified columns.

        :param columns: Columns to populate the data for
        zz
            INSERT INTO [{table}_fts] (rowid, {columns})
                SELECT rowid, {columns} FROM [{table}];
        r-  c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z%Table.populate_fts.<locals>.<genexpr>	  s     2U6==3C2Ur  )r%   r6   )rm  rn  r   r   r   r   r  r   )rn   r6   r>   s      rG   r  zTable.populate_fts	  sc     OO UWVii2UW2U)U   	 	c"rF   c                    | j                         }|r| j                  |   j                          t        j                  d      j                         j                  |      }g }| j                  j                  |      j                         D ]  }|j                  |d           | j                  j                  5  |D ],  }| j                  j                  dj                  |             . 	 ddd       | S # 1 sw Y   | S xY w)zQRemove any full-text search index and related triggers configured for this table.z
            SELECT name FROM sqlite_master
                WHERE type = 'trigger'
                AND sql LIKE '% INSERT INTO [{}]%'
        r   zDROP TRIGGER IF EXISTS [{}]N)
detect_ftsr  r  rm  rn  r   r   r   r   r   r   )rn   	fts_tabler>   r  r   trigger_names         rG   r  zTable.disable_fts	  s    OO%	GGI##% OO UWVI 	 77??3'002 	)C  Q(	)WW\\ 	T - T = D D\ RST	T 	T s   <2C99Dc                     | j                         }|| j                  }| j                  j                  dj	                  |             | S )zRRun the ``rebuild`` operation against the associated full-text search index table.z3INSERT INTO [{table}]([{table}]) VALUES('rebuild');r   )r  r   r  r   r   rn   r  s     rG   rebuild_ftszTable.rebuild_fts	  sK    OO%			IAHH I 	

 rF   c                 N   t        j                  d      j                         }dj                  | j                        dj                  | j                        | j                  d}| j
                  j                  ||      j                         }t        |      dk(  ry|d   d   S )zCDetect if table has a corresponding FTS virtual table and return itac  
            SELECT name FROM sqlite_master
                WHERE rootpage = 0
                AND (
                    sql LIKE :like
                    OR sql LIKE :like2
                    OR (
                        tbl_name = :table
                        AND sql LIKE '%VIRTUAL TABLE%USING FTS%'
                    )
                )
        z&%VIRTUAL TABLE%USING FTS%content=[{}]%z&%VIRTUAL TABLE%USING FTS%content="{}"%)likelike2r%   r   N)	rm  rn  r   r   r   r  r   r   r   )rn   r>   ro  r  s       rG   r  zTable.detect_fts
  s    oo
 %' 	 =CCDIIN=DDTYYOYY

 wwsD)224t9>71:rF   c                     | j                         }|9| j                  j                  dj                         j	                  |             | S )zSRun the ``optimize`` operation against the associated full-text search index table.zT
                INSERT INTO [{table}] ([{table}]) VALUES ("optimize");
            r   )r  r  r   r   r   r  s     rG   optimizezTable.optimize!
  sH    OO%	 GGOO#   rF   r  r  r  r   include_rankc                 :   | j                   dk(  rdndd}dj                        }|r2dj                  d |D              }dj                  fd|D              }| j                         }	|	s J d	j                  | j                                | j                  |	   j
                  }
t        j                  d
      j                         }|
dk(  rdj                  |	      }n+| j                  j                          dj                  |	      }|r|d|z   dz   z  }d}||dj                  |      z  }||dj                  |      z  }|j                  | j                   |rdj                  |      nd|||	|xs ||j                               j                         S )a   "
        Return SQL string that can be used to execute searches against this table.

        :param columns: Columns to search against
        :param order_by: Column or SQL expression to sort by
        :param limit: SQL limit
        :param offset: SQL offset
        :param where: Extra SQL fragment for the WHERE clause
        :param include_rank: Select the search rank column in the final query
        original	original_r  z[{}].*z
,
        c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z#Table.search_sql.<locals>.<genexpr>F
  s     ,O!V]]1-=,Or  z,
    c              3   B   K   | ]  }d j                  |        yw)z	[{}].[{}]Nr  )r   re  r  s     rG   r   z#Table.search_sql.<locals>.<genexpr>G
  s#      545""8Q/5s   z1Full-text search is not configured for table '{}'a  
        with {original} as (
            select
                rowid,
                {columns}
            from [{dbtable}]{where_clause}
        )
        select
            {columns_with_prefix}
        from
            [{original}]
            join [{fts_table}] on [{original}].rowid = [{fts_table}].rowid
        where
            [{fts_table}] match :query
        order by
            {order_by}
        {limit_offset}
        FTS5z	[{}].rankz$rank_bm25(matchinfo([{}], 'pcnalx'))z rankrh  r  r  z
    where {})dbtablewhere_clauser  r6   columns_with_prefixr  r  limit_offset)
r   r   r   r  r  r*  rm  rn  r   r   )rn   r6   r  r  r  r   r  ro  columns_with_prefix_sqlr  r*  r>   rank_implementationr  r  s                 @rG   
search_sqlzTable.search_sql.
  s   ( #'))z"9;z"*//(";',,,Ow,OOK&/nn 59@5 '# OO%	 	
MTTII
 	
y #ggi0DDoo
& %'' 	( &("-"4"4Y"?GG&&("H"O"O# #y3F'F'PP#K..u55LL//77LzzII;@)007b 74!4%++-  	
 %'		rF   qr  r   c
           
   #   v  K   d|	r| j                   j                  |      n|i}
|rd|v rt        d      |r|
j                  |       | j                   j	                  | j                  ||||||      |
      }|j                  D cg c]  }|d   	 }}|D ]  }t        t        ||              yc c}w w)a3  
        Execute a search against this table using SQLite full-text search, returning a sequence of
        dictionaries for each row.

        :param q: Terms to search for
        :param order_by: Defaults to order by rank, or specify a column here.
        :param columns: List of columns to return, defaults to all columns.
        :param limit: Optional integer limit for returned rows.
        :param offset: Optional integer SQL offset.
        :param where: Extra SQL fragment for the WHERE clause
        :param where_args: Arguments to use for :param placeholders in the extra WHERE clause
        :param include_rank: Select the search rank column in the final query
        :param quote: Apply quoting to disable any special characters in the search query

        See :ref:`python_api_fts_search`.
        r   zJ'query' is a reserved key and cannot be passed to where_args for .search())r  r6   r  r  r   r  r   N)	r  r   rH  rM  r   r  r   r   r   )rn   r  r  r6   r  r  r   r  r  r   ro  r   re  r   s                 rG   searchzTable.search|
  s     8 **1-A>'Z/\  KK
#OO!)   

 "(!3!34A1Q444 	*Cs7C())	* 5s   BB9B4&B9c                 4    |t         u r| j                  |   S |S rl   )rL  r  )rn   r<   r   s      rG   value_or_defaultzTable.value_or_default
  s    &+w&6t~~c"AEArF   c                    t        |t        t        f      s|g}| j                  |       | j                  D cg c]  }dj                  |       }}dj                  | j                  dj                  |            }| j                  j                  5  | j                  j                  ||       ddd       | S c c}w # 1 sw Y   | S xY w)z
        Delete row matching the specified primary key.

        :param pk_values: A single value, or a tuple of values for tables that have a compound primary key
        r  z$delete from [{table}] where {wheres}r  )r%   r  N)r   r;  r   rx  rm  r   r   r   r  r   r   )rn   r	  r  r  r>   s        rG   r#  zTable.delete
  s     )dE]3"I<@HHE*##G,EE4;;))GLL$8 < 
 WW\\ 	,GGOOC+	, F	,s   B<CCc                     | j                         s| S dj                  | j                        }||d|z   z  }| j                  j	                  ||xs g        |r| j                          | S )a  
        Delete rows matching the specified where clause, or delete all rows in the table.

        See :ref:`python_api_delete_where`.

        :param where: SQL where fragment to use, for example ``id > ?``
        :param where_args: Parameters to use with that fragment - an iterable for ``id > ?``
          parameters, or a dictionary for ``id > :id``
        :param analyze: Set to ``True`` to run ``ANALYZE`` after the rows have been deleted.
        zdelete from [{}]r  )r   r   r   r  r   r  )rn   r   r  r  r>   s        rG   r6  zTable.delete_where
  sc      {{}K ''		29u$$CZ-2.LLNrF   updatesc           
      2   |xs i }|xs i }t        |t        t        f      s|g}| j                  |       |s| S g }g }g }| j                  }t        |j                                |j                         D ]P  \  }	}
|j                  dj                  |	|j                  |	d                   |j                  t        |
             R |D cg c]  }dj                  |       }}|j                  |       dj                  | j                  dj                  |      dj                  |            }| j                  j                  5  	 | j                  j!                  ||      j"                  }|dk(  sJ 	 d
d
d
       t+        |      dk(  r|d	   | _        | S || _        | S c c}w # t$        $ rW}|rJd|j&                  d	   v r9| j)                  |g       | j                  j!                  ||      j"                  }n Y d
}~d
}~ww xY w# 1 sw Y   xY w)a  
        Execute a SQL ``UPDATE`` against the specified row.

        See :ref:`python_api_update`.

        :param pk_values: The primary key of an individual record - can be a tuple if the
          table has a compound primary key.
        :param updates: A dictionary mapping columns to their updated values.
        :param alter: Set to ``True`` to add any missing columns.
        :param conversions: Optional dictionary of SQL functions to apply during the update, for example
          ``{"mycolumn": "upper(?)"}``.
        	[{}] = {}r/  r  z*update [{table}] set {sets} where {wheres}r-  r  )r%   setsr   columnr   Nr   )r   r;  r   rx  rm  ru  r   rr  r   r   jsonify_if_neededrI  r   r   r  r   r   rowcountr   ro  add_missing_columnsr   r  )rn   r	  r  r  r  ro  r  r  rm  r<   r   r  r>   r  rs  s                  rG   rM  zTable.update
  s   & -R!'R)dE]3"IKhhglln-!--/ 	2JCKK**3S0IJKKK)%01	2 =@@*##G,@@I:AA))$))D/',,v:N B 
 WW\\ 	!77??35>> q= =	! (+3x1}y| ;D' A $ i166!94,,gY7#wwsD9BBH 		! 	!s=   F%
H&F*2H*	H
3AH HH

HHr   outputoutput_typemultishow_progress
skip_falsec                   
 t        |t              r|g}|r| j                  |d   ||||	      S |9t        |      dk(  sJ d       || j                  vr| j                  ||xs d       | j                  ||      t        |      z  }t        ||	       5 
fd}j                  }|d	k(  rd
t        t                     }| j                  j                  ||       dj                  | j                  dj                  |D cg c]  }dj                  |xs |||       c}      |dj                  |      nd      }| j                  j                   5  | j                  j#                  ||xs g        |r| j%                  |       ddd       ddd       | S c c}w # 1 sw Y   xY w# 1 sw Y   | S xY w)a  
        Apply conversion function ``fn`` to every value in the specified columns.

        :param columns: A single column or list of string column names to convert.
        :param fn: A callable that takes a single argument, ``value``, and returns it converted.
        :param output: Optional string column name to write the results to (defaults to the input column).
        :param output_type: If the output column needs to be created, this is the type that will be used
          for the new column.
        :param drop: Should the original column be dropped once the conversion is complete?
        :param multi: If ``True`` the return value of ``fn(value)`` will be expected to be a
          dictionary, and new columns will be created for each key of that dictionary.
        :param where: SQL fragment to use as a ``WHERE`` clause to limit the rows to which the conversion
          is applied, for example ``age > ?`` or ``age > :age``.
        :param where_args: List of arguments (if using ``?``) or a dictionary (if using ``:age``).
        :param show_progress: Should a progress bar be displayed?

        See :ref:`python_api_convert`.
        r   )r  r   r  r  Nr   z-output= can only be used with a single columnrO   )lengthsilentc                 T    j                  d       r| s| S t         |             S )Nr   )rM  r  )rX  barr   r  s    rG   convert_valuez$Table.convert.<locals>.convert_valueI  s'    

1aH(A//rF   z<lambda>lambda_r  z#update [{table}] set {sets}{where};r-  z)[{output_column}] = {fn_name}([{column}]))output_columnr&   r   z	 where {}rh  )r%   r  r   r  )r   rP   _convert_multir   r  r  r  r
   rB   abshashr  r   r   r   r   r   r   r  )rn   r6   r   r  r  r  r  r   r  r  r  
todo_countr  r   r&   r>   r  s     `       `     @rG   convertzTable.convert  s   > gs#iG&&
%+ '   w<1$U&UU$T...(=v>%%eZ83w<G

}3DE 	10 kkG*$#CRM?3GG%%m'%B7>>iiYY '. # DJJ*0*:F#)$+ K 	 493Dk((/" ? C  1Z%526NNN015	1< 1 15	1< s7   A2F9F(+6F9!5F-F9(F9-F6	2F99Gc                    i }i }| j                   D cg c]  }|j                  s|j                   }	}|	sdg}	t        | j                  | d      5 }
| j                  dj                  d |	gz   D              ||      D ]  t        fd|	D              }t        |      dk(  r|d	   } ||         }|t        |t              st        |      |rO|j                         D ]7  \  }}|j                  |t                     j                  t!        |             9 |||<   |
j#                  d        	 d d d        t%        |      }|j                         D ]&  \  }}|| j&                  vs| j)                  ||       ( t        | j                  | d
      5 }
| j*                  j,                  5  |j                         D ](  \  }}| j#                  ||       |
j#                  d       * |r| j/                  f       d d d        d d d        y c c}w # 1 sw Y   xY w# 1 sw Y   #xY w# 1 sw Y   y xY w)Nrc  z1: Evaluating)r  r  labelr-  c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z'Table._convert_multi.<locals>.<genexpr>u  s      !3>FMM+.!r  )r  r   r  c              3   (   K   | ]	  }|     y wrl   rE   r  s     rG   r   z'Table._convert_multi.<locals>.<genexpr>{  s     52s2w5r  r   r   z2: Updatingr  )r6   r#   r   r
   r   r  r   r   r   r   r   rj   rr  r   r   r   r    rM  r   r  r  r  r   r  )rn   r&   r   r  r  r   r  pk_to_valuesnew_column_typesrm  r  r  rm   r<   r   columns_to_createri  rj  rM  r  r   s                       @rG   r  zTable._convert_multig  s=    )-Fvv{{FF)C::-&7
 	yy !CF&>!  % '   555v;!##AYFCK%j.F(00&,lln Q
U(33C?CCDKPQ+1L(

1#	. 33CD(9(?(?(A 	:$K$"3"33[9	:
 ::-&7}
 	3 3#/#5#5#7 "KBKKG,JJqM" NN	N23	3 	3C G	 	@3 3	3 	3s<   HHC%HH56AH)H5H&)H2	.H55H>c                 d  	 g }|r|d}t        |      }|D ]  g }D ]h  }t        j                  |||k7  rd nt        |                  }||v r%||   }| j                  |   j                  d|i      }|j                  |       j |j                  |        g }|rt        |t              r|g}n|}d | _	        |D ]  }t        t        |            t        |      }|r|j                  |       dj                  | j                  dj!                  |D cg c]  }dj                  |       c}      dj!                  |D cg c]  }d c}            }|j                  ||D cg c]  }|   	 c}|xs g D cg c]  }d c}z   f       D cg c]	  }||vs| }}|rd	j                  | j                  dj!                  	fd
|D              dj!                  d |D                    }|j                  ||D cg c]  }|   	 c}|D cg c]  }|   	 c}z   f       |
dk(  sxt#        fd|D              | _	        t%        | j                        dk(  s| j                  d   | _	         |S d}|rd}n|rd}dj'                         j                  || j                  dj!                  d D              dj!                  	fd|D                    }t        t)        j*                  |       }||fg}|S c c}w c c}w c c}w c c}w c c}w c c}w c c}w )NrV  r   z?INSERT OR IGNORE INTO [{table}]({cols}) VALUES({placeholders});r-  rl  r/  )r%   colsplaceholdersrh  z+UPDATE [{table}] SET {pairs} WHERE {wheres}c              3   b   K   | ]&  }d j                  |j                  |d             ( yw)r  r/  N)r   rx  )r   rB  r  s     rG   r   z8Table.build_insert_queries_and_params.<locals>.<genexpr>  s1      ( # (..sKOOC4MN(s   ,/r   c              3   >   K   | ]  }d j                  |        yw)r  Nr  )r   rM  s     rG   r   z8Table.build_insert_queries_and_params.<locals>.<genexpr>  s     +PbJ,=,=b,A+Pr  )r%   pairsr  r   c              3   (   K   | ]	  }|     y wrl   rE   )r   rM  records     rG   r   z8Table.build_insert_queries_and_params.<locals>.<genexpr>  s     (B(Br  r   zOR REPLACE z
OR IGNORE zW
                INSERT {or_what}INTO [{table}] ({columns}) VALUES {rows};
            c              3   >   K   | ]  }d j                  |        ywr  r  r  s     rG   r   z8Table.build_insert_queries_and_params.<locals>.<genexpr>  s     !Hq&--"2!Hr  c              3      K   | ]C  }d j                  dj                  D cg c]  }j                  |d       c}             E yc c}w w)z({placeholders})r-  r/  )r  N)r   r   rx  )r   r  rB  all_columnsr  s      rG   r   z8Table.build_insert_queries_and_params.<locals>.<genexpr>  sV        '--%)YYBMN3[__S#6N& .  Os   AAA)or_whatr%   r6   r  )rq  r  rx  r   r  lookupr   r   rP   r  r   r   r;  rI  r   r   r   r   r   r   	itertoolschain)rn   rS  chunkr  rQ  rR  upsertrM  rO  r  num_records_processedr   r  rm   record_valuesr<   r   r|  queries_and_paramsrm  r  r`  r>   rB  rR  set_colssql2r  flat_valuesr  s      `     `                   @rG   build_insert_queries_and_paramsz%Table.build_insert_queries_and_params  sY   $ wG#H- 	)FM" ,)JJ  #g~ !!,V_!E	 (?$,SMM GGM2997E:JKE$$U+, MM-(#	)&  "c"dDL!' %7c+}=>#Cy  ''1W^^))l#KFMM!$4#KL!%+FAC+F!G _ 
 #))#636#;6x~SU9W"9WWX ,7IC#S.CIIHOO"ii"ii ('/(   '||+PC+PP P D '-- 4<=SVC[=478bvbz89 )A-#((Bc(B#BDL4<<(A-'+||AK%7~ "!/ G'&ii		!HK!HHYY  #( 	    y78K#&"4!5!!m $L+F 79W J >8s0   L	L0L	L	L#'L#L(L-c                    | j                  ||||||||	|
|||      }| j                  j                  5  d }|D ]"  \  }}	 | j                  j                  ||      }$ |dk(  r|s|j                  | _
        | j                  | _        |s|rv| j                  rjt        | j                  d| j                  g            d   |r|   | _        n4t        |t              r|   | _        nt!        fd|D              | _        d d d        y # t        $ r}|r?d|j
                  d   v r.| j                  |       | j                  j                  ||      }np|j
                  d   dk(  r]|d t        |      dz   }|t        |      dz  d  }| j                  |||||||||	|
|||       | j                  |||||||||	|
|||       n Y d }~d }~ww xY w# 1 sw Y   y xY w)Nr  r   ztoo many SQL variablesr   r   z	rowid = ?c              3   (   K   | ]	  }|     y wrl   rE   )r   r`  r   s     rG   r   z%Table.insert_chunk.<locals>.<genexpr>c  s     ,@SV,@r  )r  r  r   r   r   ro  r  r   insert_chunk	lastrowidr  r  r;  r  r   rP   r   )rn   r  rS  r  r  rQ  rR  r  rM  rO  r  r  r   r  r  r  r   r   rs  
first_halfsecond_halfr   s                        @rG   r  zTable.insert_chunk	  s     "AA!
 WW\\ ;	AF!3 -v,!WW__UF;F-\ %)&"("2"2#rtt{T__<MNOPQRC'*7|#B,'*2w',,@R,@'@w;	Az 	q ( *)qvvay"8007!%!?&>>%*+<SZ1_%=
&+CJ!O,=&>))!$&'#+"$'1#"  ))!$''#+"$'1#"" U*;	Az 	s7   G D
B%G
	GB1G
G
GGGr  c                 D    | j                  |g||||||||	|
|||||      S )a  
        Insert a single record into the table. The table will be created with a schema that matches
        the inserted record if it does not already exist, see :ref:`python_api_creating_tables`.

        - ``record`` - required: a dictionary representing the record to be inserted.

        The other parameters are optional, and mostly influence how the new table will be created if
        that table does not exist yet.

        Each of them defaults to ``DEFAULT``, which indicates that the default setting for the current
        ``Table`` object (specified in the table constructor) should be used.

        :param record: Dictionary record to be inserted
        :param pk: If creating the table, which column should be the primary key.
        :param foreign_keys: See :ref:`python_api_foreign_keys`.
        :param column_order: List of strings specifying a full or partial column order
          to use when creating the table.
        :param not_null: Set of strings specifying columns that should be ``NOT NULL``.
        :param defaults: Dictionary specifying default values for specific columns.
        :param hash_id: Name of a column to create and use as a primary key, where the
          value of that primary key will be derived as a SHA1 hash of the other column values
          in the record. ``hash_id="id"`` is a common column name used for this.
        :param alter: Boolean, should any missing columns be added automatically?
        :param ignore: Boolean, if a record already exists with this primary key, ignore this insert.
        :param replace: Boolean, if a record already exists with this primary key, replace it with this new record.
        :param extracts: A list of columns to extract to other tables, or a dictionary that maps
          ``{column_name: other_table_name}``. See :ref:`python_api_extracts`.
        :param conversions: Dictionary specifying SQL conversion functions to be applied to the data while it
          is being inserted, for example ``{"name": "upper(?)"}``. See :ref:`python_api_conversions`.
        :param columns: Dictionary over-riding the detected types used for the columns, for example
          ``{"age": int, "weight": float}``.
        :param strict: Boolean, apply STRICT mode if creating the table.
        )rM  r=  rN  rO  rP  rQ  rR  r  r  r   rS  r  r6   r{   r7  )rn   r  rM  r=  rN  rO  rP  rQ  rR  r  r  r   rS  r  r6   r{   s                   rG   rw  zTable.insertg  sJ    f H%%+#  
 	
rF   c                    | j                  d|      }| j                  d|      }| j                  d|      }| j                  d|      }| j                  d|      }| j                  d|      }| j                  d|      }| j                  d|	      }	| j                  d	|
      }
| j                  d
|      }| j                  d|      }| j                  d|      }| j                  d|      xs i }| j                  d|      }| j                  d|      }|	r|d}|r|s|st        d      |r	|rJ d       |	r|d}|r|}|r	|rJ d       g }d}d}t        |      }t        |      }	 t	        |      }t        |j                               }|t        k  sJ dj                  t                     t        dt        |t        |z              }d| _        d| _        |rD| j                         r4| j                  j!                  dj                  | j"                               t%        t'        j(                  |g|      |      D ]   }t+        |      }|t        |      z  }|r| j                         s;t-        |      }|j/                  |xs i        | j1                  ||||||||	||
       t3               }|D ]!  }|j/                  |j                                # t+        t5        |            }|r2|j7                  d|       n|D ]  }||D cg c]	  }||vs| c}z  } d}| j9                  |
|||||	|||||||        |r| j;                          | S # t
        $ r | cY S w xY wc c}w )a   
        Like ``.insert()`` but takes a list of records and ensures that the table
        that it creates (if table does not exist) has columns for ALL of that data.

        Use ``analyze=True`` to run ``ANALYZE`` after the insert has completed.
        rM  r=  rN  rO  rP  r  rQ  rR  r  r  r   rS  r  r6   r{   NrV  zupsert() requires a pkzUse either pk= or hash_id=z0Use either ignore=True or replace=True, not bothTr   z%Rows can have a maximum of {} columnsr   zDELETE FROM [{}];)rN  rO  rP  rQ  rR  rS  r{   F)r  rd   fix_square_bracesr  r   StopIterationr   r   SQLITE_MAX_VARSr   maxminr  r  r   r  r   r   r   r  r  r;  r   rM  r/  r   sortedrw  r  r  )rn   recordsrM  r=  rN  rO  rP  r  rQ  rR  r  r  r   truncaterS  r  r6   r  r  r{   r  firstr  first_recordnum_columnsr  column_typesall_columns_setr  r&   s                                 rG   r7  zTable.insert_all  s   8 ""4,,,^\J,,^\J((X>((X>**<D
''	7;//0A?S%%gu5&&x8''	7;((X>++M;GM2''	7;&&x8wG2g$%=>>A%AA#GB w	>=	> 
  !#G, w-	=L ,++-.?*	K299/J	K*C
O{,JKL
GGOO/66tyyABIOO\NGDjQ 0	EKE!SZ/!{{}#7#>L ''26KK$$%1!)!) '(7!)%    #&%# :F#**6;;=9:"6/#:;&&q'2# F-3$#)v[7P$ K
 E%E0	d LLNA  	K	N$s   'M 	M)
M)
M&%M&c                 @    | j                  |g||||||||	|
|||      S )z
        Like ``.insert()`` but performs an ``UPSERT``, where records are inserted if they do
        not exist and updated if they DO exist, based on matching against their primary key.

        See :ref:`python_api_upsert`.
        )rM  r=  rN  rO  rP  rQ  rR  r  rS  r  r6   r{   )
upsert_all)rn   r  rM  r=  rN  rO  rP  rQ  rR  r  rS  r  r6   r{   s                 rG   r  zTable.upsert3  sC    , H%%+#  
 	
rF   c                 D    | j                  |||||||||	|
|||d||      S )zM
        Like ``.upsert()`` but can be applied to a list of records.
        T)rM  r=  rN  rO  rP  r  rQ  rR  r  rS  r  r6   r  r  r{   r  )rn   r  rM  r=  rN  rO  rP  r  rQ  rR  r  rS  r  r6   r  r{   s                   rG   r  zTable.upsert_allY  sJ    * %%!+#!  
 	
rF   r  c                     t        |      }| j                  D ch c]  }|j                          }}|j                         D ]*  \  }}|j                         |vs| j	                  ||       , | S c c}w rl   )r   r  r  rr  r  )rn   r  needed_columnsre  current_columnsr  r  s          rG   r  zTable.add_missing_columns  sr    -g6.2.?.?@1779@@"0"6"6"8 	4Hh~~6(3	4 	 As   A2lookup_valuesextra_valuesc                    t        |t              sJ |t        |t              sJ t        |      }||j                  |       | j                         r| j	                  |g       | j
                  D cg c]  }t        |j                         }}t        |j                               |vr!| j                  |j                         d       |D cg c]  }dj                  |       }}t        | j                  dj                  |      |j                         D cg c]  \  }}|	 c}}            }	 |d   |   S | j!                  ||||||||	|
|
      j"                  }| j                  |j                         d       |S c c}w c c}w c c}}w # t        $ r( | j!                  ||||||||	|
|
      j"                  cY S w xY w)a  
        Create or populate a lookup table with the specified values.

        ``db["Species"].lookup({"name": "Palm"})`` will create a table called ``Species``
        (if one does not already exist) with two columns: ``id`` and ``name``. It will
        set up a unique constraint on the ``name`` column to guarantee it will not
        contain duplicate rows.

        It will then insert a new row with the ``name`` set to ``Palm`` and return the
        new integer primary key value.

        An optional second argument can be provided with more ``name: value`` pairs to
        be included only if the record is being created for the first time. These will
        be ignored on subsequent lookup calls for records that already exist.

        All other keyword arguments are passed through to ``.insert()``.

        See :ref:`python_api_lookup_tables` for more details.

        :param lookup_values: Dictionary specifying column names and values to use for the lookup
        :param extra_values: Additional column values to be used only if creating a new record
        :param strict: Boolean, apply STRICT mode if creating the table.
        T)r3   r  r  r   )	rM  r=  rN  rO  rP  rS  r  r6   r{   )r   r   rM  r   r  r  r   r6   r   r  r   r;  r  r   rr  r  rw  r  )rn   r  r  rM  r=  rN  rO  rP  rS  r  r6   r{   combined_valuesr  unique_column_setsr&   r  rR  r   r  s                       rG   r  zTable.lookup  s   J -...#lD111}-#""<0;;=$$o%67:>,,!GQ#aii.!G!G=%%'(0BB!!-"4"4"6t!D>KLFj''/LFLLL(ATATAV*WXQ5*WD
Awr{" ))!!!'   g  m0024@IM "H M +X
  {{#!-!-%%% +#! #  's$   5F	F F9F .G
	G
record_or_iterabler  	m2m_tablec                    t        |t              r+t        t        | j                  j                  ||            }| j                  }|	|J d       |J d       t        t        | j                  |j                  g            }|D 	cg c]  }	dj                  |	       }
}	||}n| j                  j                  | j                  |j                        }t        |      dk(  r|d   }nPt        |      dkD  r/t        dj                  | j                  |j                              |xs  dj                  | }| j                  j                  ||
|
      }|t        |t              r|g}nt        t        |      }|D ]x  }|j!                  t        t"        |      |d	|
      j                  }|j!                  dj                  |j                        |dj                  | j                        |id	       z | S |j%                  |      }|j!                  dj                  |j                        |dj                  | j                        |id	       | S c c}	w )a9  
        After inserting a record in a table, create one or more records in some other
        table and then create many-to-many records linking the original record and the
        newly created records together.

        For example::

            db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id").m2m(
                "humans", {"id": 1, "name": "Natalie"}, pk="id"
            )

        See :ref:`python_api_m2m` for details.

        :param other_table: The name of the table to insert the new records into.
        :param record_or_iterable: A single dictionary record to insert, or a list of records.
        :param pk: The primary key to use if creating ``other_table``.
        :param lookup: Same dictionary as for ``.lookup()``, to create a many-to-many lookup table.
        :param m2m_table: The string name to use for the many-to-many table, defaults to creating
          this automatically based on the names of the two tables.
        :param alter: Set to ``True`` to add any missing columns on ``other_table`` if that table
          already exists.
        rW  z#Provide lookup= or record, not bothr]  r   r   zANo single obvious m2m table for {}, {} - use m2m_table= parameterr^  )rM  r=  T)rM  r   r  )r   )r   rP   r   r   r  r%   r  r;  r  r   r   r  r   r[   r   r   rw  r   r  )rn   r/   r!  rM  r  r"  r  our_idr   r  r6   m2m_table_namer  m2m_table_objr  r  rV  s                    rG   m2mz	Table.m2m  sO   B k3'udggmmKBm&GHK%-T/TT-%1X3XX1fdii)9)9:;<.457>>!$55 &N 55diiAQAQRJ:!#!+AZ1$$W^^		;#3#3  "+!Engnnf.EnwW>,g6-.t%78! 
 ''v&2t5 ( '  $${'7'78"tyy16 ! % 	
(  ##F+B  NN;#3#34bNN499-v  !  [ 6s   
Ic                 N    | j                   j                  | j                         y)zRun ANALYZE against this tableN)r  r  r   r   s    rG   r  zTable.analyze6  s    		"rF   common_limitr+   r,   r$   c           
          | j                   }| j                  }|||   j                  }fd}	|j                  dj	                  ||            j                         d   }
|j                  dj	                  ||            j                         d   }|j                  dj	                  ||            j                         d   }d}d}|dk(  r>|j                  dj	                  ||            j                         d   } |	|      |fg}n||k7  r|rl|
|k(  rd|fg}na|j                  d	j	                  |||||            j                         D cg c]  } |	|d         |d   f }}|j                  d
 d       |rh||k  rd}n`|j                  dj	                  |||||            j                         D cg c]  } |	|d         |d   f }}|j                  d        t        | j                  |||
||||      S c c}w c c}w )aA  
        Return statistics about the specified column.

        See :ref:`python_api_analyze_column`.

        :param column: Column to analyze
        :param common_limit: Show this many column values
        :param value_truncate: Truncate display of common values to this many characters
        :param total_rows: Optimization - pass the total number of rows in the table to save running a fresh ``count(*)`` query
        :param most_common: If ``True``, calculate the most common values
        :param least_common: If ``True``, calculate the least common values
        Nc                 ~    t        | t        t        f      r| S t        |       } t	        |       kD  r| d  dz   } | S )Nz...)r   rS   rR   rP   r   )r   value_truncates    rG   r  z&Table.analyze_column.<locals>.truncateT  sF    %EE3<)HJE5zN*o~.6LrF   z,select count(*) from [{}] where [{}] is nullr   z)select count(*) from [{}] where [{}] = ''z%select count(distinct [{}]) from [{}]r   zselect [{}] from [{}] limit 1zSselect [{}], count(*) from [{}] group by [{}] order by count(*) desc, [{}] limit {}c                     | d   | d   fS Nr   r   rE   r`  s    rG   <lambda>z&Table.analyze_column.<locals>.<lambda>z  s    AaD!A$< rF   T)r<   reversezSselect [{}], count(*) from [{}] group by [{}] order by count(*), [{}] desc limit {}c                     | d   | d   fS r.  rE   r/  s    rG   r0  z&Table.analyze_column.<locals>.<lambda>  s    QqT1Q4L rF   rb  )	r  r   r   r   r   r   r   rv  r$   )rn   r&   r)  r,  r'   r+   r,   r  r%   r  r(   r)   r*   most_common_resultsleast_common_resultsr   r   s      `             rG   analyze_columnzTable.analyze_column:  sW   * WW		EJ	 :::AA%P

(*Q JJ7>>ufM

(*Q	 zz3::65I

(*Q ##1JJ/66vuEhjE %-UOZ#@"AZ'z),0*+=*>' "$qxx &vv|" #(*+ "!A$1.+' + (,,1GQU,V</+/( "$qxx &vv|" #(*, "!A$1.,( , )--2H-III 	
 		
/+,s   H>Hri  geometry_typesridcoord_dimensionc                     | j                   j                  d| j                  ||||t        |      g      }|j	                         }|xr t        |d         S )a  
        In SpatiaLite, a geometry column can only be added to an existing table.
        To do so, use ``table.add_geometry_column``, passing in a geometry type.

        By default, this will add a nullable column using
        `SRID 4326 <https://spatialreference.org/ref/epsg/wgs-84/>`__. This can
        be customized using the ``column_name``, ``srid`` and ``not_null`` arguments.

        Returns ``True`` if the column was successfully added, ``False`` if not.

        .. code-block:: python

            from sqlite_utils.db import Database
            from sqlite_utils.utils import find_spatialite

            db = Database("mydb.db")
            db.init_spatialite(find_spatialite())

            # the table must exist before adding a geometry column
            table = db["locations"].create({"name": str})
            table.add_geometry_column("geometry", "POINT")

        :param column_name: Name of column to add
        :param geometry_type: Type of geometry column, for example ``"GEOMETRY"`` or ``"POINT" or ``"POLYGON"``
        :param srid: Integer SRID, defaults to 4326 for WGS84
        :param coord_dimension: Dimensions to use, defaults to ``"XY"`` - set to ``"XYZ"`` to work in three dimensions
        :param not_null: Should the column be ``NOT NULL``
        z+SELECT AddGeometryColumn(?, ?, ?, ?, ?, ?);r   )r  r   r   rR   r   r  )rn   ri  r6  r7  r8  rO  r   r  s           rG   add_geometry_columnzTable.add_geometry_column  sZ    H 9		H

 ")$vay/)rF   c                     d| j                    d| | j                  j                         v ry| j                  j                  d| j                   |g      }|j	                         }|xr t        |d         S )a  
        A spatial index allows for significantly faster bounding box queries.
        To create one, use ``create_spatial_index`` with the name of an existing geometry column.

        Returns ``True`` if the index was successfully created, ``False`` if not. Calling this
        function if an index already exists is a no-op.

        .. code-block:: python

            # assuming SpatiaLite is loaded, create the table, add the column
            table = db["locations"].create({"name": str})
            table.add_geometry_column("geometry", "POINT")

            # now we can index it
            table.create_spatial_index("geometry")

            # the spatial index is a virtual table, which we can inspect
            print(db["idx_locations_geometry"].schema)
            # outputs:
            # CREATE VIRTUAL TABLE "idx_locations_geometry" USING rtree(pkid, xmin, xmax, ymin, ymax)

        :param column_name: Geometry column to create the spatial index against
        idx_rR  Fzselect CreateSpatialIndex(?, ?)r   )r   r  r   r   r   r  )rn   ri  r   r  s       rG   create_spatial_indexzTable.create_spatial_index  sn    0 $))Ak]+tww/B/B/DD-		;/G
 ")$vay/)rF   )NNNNNd   NNFFFNNNFr  )NNN)NFFFF)NNNNF)NNF)r  FNF)r   r   )NNNNNF)NNNNNNFF)NFN)NNFFNNFTr  )
NrV  NNNNNNNF)
   NNTT)i  XYF)WrB   rC   rD   rY   r  r   rR   __annotations__r  r   rq   rP   r  r   r   r   r  r   r   ro   r   r  r   r   rm  r  r;  r   rx  r=  r*  r1   r  r7   r$  r=   r  r	  r  r{   r/  r2  rL  r  r8  rk  rh   r  r  r  rH  rI  rh  r+  r5  r  r  r  r  r  r  r  r   r  r  rS   r#  r6  rM  r   r  r  r  r  rJ   rw  r7  r  r  r  r  r'  r  r5  r:  r=  __classcell__)r  s   @rG   r   r     s   4 !%J$!GXc]! !26,0,0-1!%37?C&*,0%%
%
 %
 SM	%

 /%
 tCy)%
 8C=)%
 4S>*%
 %
 #%
 "(3-0%
 %
 %
 %
 5c3hc!:;<%
  d^!%
" $sCx.)#%
$ %%
N
# 
 "s " "2 2 T#Y   J4 J J U4S#89  d  8 d<0  $ 2Xc] 2 2 e  . $v,  $ 	
$w- 	
 	
 HtCH~ H H 
S#X 
 
 ) ) ) !26,0,0-1!%37?C#8c3h8 SM8 /	8
 tCy)8 8C=)8 4S>*8 #8 "(3-08 5c3hc!:;<8 8 8 8 8 8  
!8t!# !' !& !%!%#'#,0-1596:26,0$(@ ~@ 	@
 x @ SM@ 8C=)@ 4S>*@ $HSM2@ #?3@ /@ tCy)@ SM@ 
@J !%!%#'#,0-1046:26,0$($(L ~L 	L
 x L SML 8C=)L 4S>*L $H-L #?3L /L tCy)L SML SML 
cLb  $#'+/jsHSM)*j }j C=	j
 c3h(j 
j^ %)#!&M%Y/0M SMM 	M
 M M Md #'  $*.33 3-3 SM	3
 3 #3-3j
4 

# 
# 
@  &*&*00 c]0 sm	0
 0d/(b AT A A " %"&T#T T 	T
 3-T TlHSM g ,2HSM 6 ,0"&# $#"L(3-(L 3-L }	L
 L }L L 
Lb #'+/# $#6:"1*1* 3-1* (3-(	1*
 }1* 1* }1* U8T>231* 1* 1* 
4t#	$1*fBdE3U&B C  &  $6:	} U8T>23 	
 
: #'&*6uc3566 $6 	6
 d^6 
6x !%%)#6:#PsDI~&P P 	P
 c]P P P }P U8T>23P P Pf GK/3bo"b\B <C<C=D18CJ071829HO@G<C18!C
S#XC

 uT#Y%789C
 5#!789C
 5c3h!89:C
 %W-.C
 "%w(>"?@C
 dGm,-C
 tW}-.C
 %g./C
 5c3hcG!CDEC
 eDcNG$;<=C
 %S#X 789C
  tW}-.!C
" 
#C
P )E* 
+ET $
 
$
R !&
" 
#&
P8DcN+C   26 26,0,0-1?C04,0!&SCH~S tCH~.S SM	S
 /S tCy)S 8C=)S 4S>*S 5c3hc!:;<S d38n-S $sCx.)S St ,3+/#'V3<(V %(4S>*DcN:;
V U3<()V c3h(V C=V Vp#  !X
X
 X
 X
 X
 
X
| #1*1* 1* 	1*
 1* 1* 
1*f*4 *rF   r   c                   ,    e Zd Zd ZdefdZddZd Zy)r   c                      y)NTrE   r   s    rG   r   zView.exists  s    rF   r   c                 z    dj                  | j                  dj                  d | j                  D                    S )Nz<View {} ({})>r-  c              3   4   K   | ]  }|j                     y wrl   r  r  s     rG   r   z View.__repr__.<locals>.<genexpr>  s      >A >r  )r   r   r   r6   r   s    rG   r   zView.__repr__  s1    &&IItyy > >>
 	
rF   c                     	 | j                   j                  dj                  | j                               y# t        j
                  $ r |s Y yw xY w)zx
        Drop this view.

        :param ignore: Set to ``True`` to ignore the error if the view does not exist
        zDROP VIEW [{}]Nr{  r|  s     rG   r  z	View.drop  sG    	GGOO,33DII>?'' 	 	r}  c                     t        d      )z9``enable_fts()`` is supported on tables but not on views.z4enable_fts() is supported on tables but not on views)NotImplementedError)rn   ro  r   s      rG   r  zView.enable_fts  s    !B
 	
rF   Nr?  )rB   rC   rD   r   rP   r   r  r  rE   rF   rG   r   r     s    
# 


rF   r   c                    t        | t        j                        rt        |       S t        | t        t
        t        f      rt        j                  | t        d      S t        | t        j                  t        j                  t        j                  f      r| j                         S t        | t        j                        rt        |       S t        | t         j"                        rt        |       S | S )NF)r   ensure_ascii)r   decimalDecimalrS   r   r;  r   jsondumpsrt  datetimetimedate	isoformat	timedeltarP   uuidUUID)r   s    rG   r  r    s    %)U|%$e,-zz%EBB	EHMM8==(:K:KL	M  	E8--	.5z	E499	%5zrF   rS  r   c                 d    | i } t        | t        t        f      r| D ci c]  }|| } }| S c c}w rl   )r   r;  r   )rS  items     rG   rq  rq    s>     (T5M*+344D$J44O 5s   
-c                 0    | D ]  }d|vrd|vrJ d        y )N[]z*'[' and ']' cannot be used in column namesrE   )r6   r&   s     rG   ru  ru    s0     8v#V"3	87	838rF   r  c           	   #      K   | D ]m  }t        d |j                         D              rG|j                         D ci c](  \  }}|j                  dd      j                  dd      |* c}} j| o y c c}}w w)Nc              3   0   K   | ]  }d |v xs d|v   yw)r[  r\  NrE   )r   r<   s     rG   r   z$fix_square_braces.<locals>.<genexpr>)  s      ACscz'SCZ'As   r[  rR  r\  )r   r   rr  r   )r  r  r<   r   s       rG   r	  r	  '  sy      A6;;=AA #),,.C C%--c37> 
 Ls   9A<-A6(A<c                 6   | j                  d      r| j                  d      r| dd S | j                         rt        |       S | j                  d      r+| j                  d      r| dd }t	        j
                  |      S 	 t        |       S # t        $ r Y | S w xY w)Nr   r   r*  zX'r   )r   r   isdigitrR   binascii	unhexlifyrS   rH  )r   	to_decodes     rG   r(  r(  2  s    !4Qr{}}5z%.."5!BK	!!),,U| Ls    
B 	BB)wutilsr   r   r   r   r   r   r	   r
   r   ra  collectionsr   collections.abcr   r  rQ  rM  r   r  rO  r   r   rer  sqlite_fts4r   rm  typingr   r   r   r   r   r   r   r   r   r   rV  sqlite_utils.pluginsr   sqlite_dumpr   ImportErrorr  compiler   VERBOSE
IGNORECASEr  pandaspdnumpynpr   rY   r$   r-   r1   r7   r8   r=   r  r@   rP   ForeignKeyIndicatorr  rJ   rL  rS   rR   r  r   r   r;  rU   r  
memoryviewrS  rR  rU  rN  rW  ry  rM  int8int16int32int64uint8uint16uint32uint64float16float32float64r  	TimestamprW   r[   r]   r`   rb   rd   rf   rh   rj   r   r&  rq   r  r   r   r  rq  ru  r	  r(  rE   rF   rG   <module>r     s  
 
 
  " #       	  	  !     #$
 

>*$"**  JJ# ( 
J
, 	 8 D
 	7UV	H1	2C Y 8
9	Y 	 	#s(O	#sC-	#sC
	  !45t<O7PPQ	 	 )	7 	) 	
 	& 
6 	& 
OOV 
6  v MM6 MM6  OOW  	NNF!" 	IIv#& ; @ ""))))		9		9		9

G

G

G	
( f56	 		Y 		i 		I 		I 		 		Y 		 	Y 
 
EG d* d*NF FRK%*I K%*\J
9 
:uT#s(^T#Yc
BCD	8xS#X7 Mx  H<  	B
  	Bl  sI   <M7 N N 2BN! 7NNNNNN!N*)N*