
    ¿#jB                        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mZmZmZmZmZmZmZ d dlZ	 d dlZd dlmZ ej0                  ZdZ ej8                         Zd Zdee   fd	Z d
 Z!d Z"d Z#d Z$ G d d      Z%ejL                  d3d       Z' G d dejP                        Z) G d de*      Z+ G d de+      Z, G d de*      Z-	 	 d4dee.   dee/   dee   dee.   fdZ0	 	 	 	 	 d5dedee)   deeejb                        d ee   dee/   dee   deee.   e)f   fd!Z2 G d" d#      Z3 G d$ d%      Z4 G d& d'      Z5ejL                  d(        Z6d6d)Z7d*ed+e8dee   fd,Z9d7d-ed.eee      fd/Z:d0 Z;d1e.de.fd2Z<y# e$ r= 	 d dlZd dlmZ ej0                  Zn!# e$ r d dlZd dlmZ ej0                  ZY nw xY wY rw xY w)8    N   )recipes)DictcastBinaryIOIterableOptionalTupleType)dbapi2)z+/usr/lib/x86_64-linux-gnu/mod_spatialite.soz,/usr/lib/aarch64-linux-gnu/mod_spatialite.soz#/usr/local/lib/mod_spatialite.dylibz /usr/local/lib/mod_spatialite.soz&/opt/homebrew/lib/mod_spatialite.dylibc                      t         j                  } 	 	 t        j                  |        y# t        $ r t        | dz        } Y nw xY w5)zD
    Increase the CSV field size limit to the maximum possible.
    
   N)sysmaxsizecsvfield_size_limitOverflowErrorint)r   s    h/home/mi/.openclaw/workspace/fridge-app/backend/.venv/lib/python3.12/site-packages/sqlite_utils/utils.pymaximize_csv_field_size_limitr   .   sM    
 {{
	:  !12 	:"#3b#89	:	 s   ) AAreturnc                  `    t         D ]%  } t        j                  j                  |       s#| c S  y)a  
    The ``find_spatialite()`` function searches for the `SpatiaLite <https://www.gaia-gis.it/fossil/libspatialite/index>`__
    SQLite extension in some common places. It returns a string path to the location, or ``None`` if SpatiaLite was not found.

    You can use it in code like this:

    .. code-block:: python

        from sqlite_utils import Database
        from sqlite_utils.utils import find_spatialite

        db = Database("mydb.db")
        spatialite = find_spatialite()
        if spatialite:
            db.conn.enable_load_extension(True)
            db.conn.load_extension(spatialite)

        # or use with db.init_spatialite like this
        db.init_spatialite(find_spatialite())

    N)SPATIALITE_PATHSospathexists)r   s    r   find_spatialiter   =   s-    , ! 77>>$K     c                     i }| D ]L  }|j                         D ]7  \  }}|j                  |t                     j                  t	        |             9 N t        |      S N)items
setdefaultsetaddtypetypes_for_column_types)recordsall_column_typesrecordkeyvalues        r   suggest_column_typesr,   Y   sc     E ,,. 	EJC''SU377UD	EE ""233r   c                 6   i }| j                         D ]  \  }}t        |      dkD  r|j                  d j                         d j                  h|k(  rt        }nt        |      dk(  r8t        |      d   }t
        t        t        fD ]  }t        ||      st        } nqt        t        hj                  |      rt        }nOt        t        t        hj                  |      rt        }n(t        t        hj                  |      rt        }nt        }|||<    |S )Nr   r   )r!   lendiscard	__class__strlisttupledict
issubclassr   bool
issupersetfloatbytes)r(   column_typesr*   typest
superclasss         r   r&   r&   a   s    L&,,. 
Uu:>MM$..)NNu$AZ1_UAA  $UD1 
a,A 4[##E*A5$**51AS\$$U+AAS+, r   c                     t        | t              sJ | j                         j                         } | dk(  rt        S d| v rt        S d| v sd| v sd| v rt        S d| v rt
        S d| v sd| v sd	| v rt        S t        S )
N INTCHARCLOBTEXTBLOBREALFLOADOUB)
isinstancer1   upperstripr   r9   r8   )column_types    r   column_affinityrL   |   s     k3'''##%++-Kb

+ 5;9N
+ 5;9NLr   c                    | D cg c]4  }t        | |   t              r| |   j                  d      du r	d| |   v r|6 }}|s| S t        | fi |D ci c]  }|t        j                  | |   d           c}S c c}w c c}w )Nz$base64Tencoded)rH   r4   getbase64	b64decode)dockto_fixs      r   decode_base64_valuesrU      s     c!fd#FJJy!T)Q	 	
F  
PO16++CF9,=>>OPP Ps   9A8#A=c                        e Zd Zd Zd ZddZy)UpdateWrapperc                      || _         || _        y r    )_wrapped_update)selfwrappedupdates      r   __init__zUpdateWrapper.__init__   s    r   c              #   j   K   | j                   D ]   }| j                  t        |             | " y wr    )rY   rZ   r.   )r[   lines     r   __iter__zUpdateWrapper.__iter__   s.     MM 	DLLT#J	s   13c                 p    | j                   j                  |      }| j                  t        |             |S r    )rY   readrZ   r.   )r[   sizedatas      r   rc   zUpdateWrapper.read   s+    }}!!$'SYr   N))__name__
__module____qualname__r^   ra   rc    r   r   rW   rW      s    
r   rW   c              +   d  K   |r|  y 	 | j                         }|dk(  r|  y t        j                  j                  | j                        }t        j                  dd|i|5 }t        | |j                         d d d        y # t        j                  $ r |  Y y w xY w# 1 sw Y   y xY ww)Nr   lengthrj   )filenoioUnsupportedOperationr   r   getsizenameclickprogressbarrW   r]   )filesilentkwargsrm   file_lengthbars         r   file_progressry      s     
 {
ggoodii0<k<V< 	2cjj11	2 	2 "" 
	2 	2s@   B0B A
B0%B$>	B0B!B0 B!!B0$B-)B0c                       e Zd ZdZdZdZdZy)Formatr            N)rg   rh   ri   CSVTSVJSONNLrj   r   r   r{   r{      s    
C
CD	
Br   r{   c                       e Zd Zy)RowsFromFileErrorNrg   rh   ri   rj   r   r   r   r          r   r   c                       e Zd Zy)RowsFromFileBadJSONNr   rj   r   r   r   r      r   r   r   c                       e Zd Zy)RowErrorNr   rj   r   r   r   r      r   r   r   readerignore_extras
extras_keyc              #      K   | D ]i  }d |vr| |r|j                  d        | $|s,|j                  d       }t        dj                  ||            |j                  d       ||<   | k y w)Nz'Row {} contained these extra values: {})popr   format)r   r   r   rowextrass        r   _extra_key_strategyr      s}       s?I GGDMIWWT]F9@@fM  "ggdmC
OI!s   A0A2fpr   dialectencodingc                    |r|rt        d      |t        j                  k(  rUt        j                  |       }t        |t              r|g}t        |t              st        d      |t        j                  fS |t        j                  k(  rd | D        t        j                  fS |t        j                  k(  ri|xs d}t        j                  | |      }|t        j                  ||      }	nt        j                  |      }	t        |	||      t        j                  fS |t        j                   k(  rKt#        | t        j                  t        j$                  |      d   }
t        |
||      t        j                   fS |!t        j&                  t)        t        j*                  |       d	
      }	 |j-                  d      j/                         }|j5                  d      s|j5                  d      rt#        |t        j                        S t        j6                         j9                  |j;                  |xs dd            }t#        |t        j                  ||      \  }
}|j<                  dk(  rt        j                   nt        j                  }t        |
||      |fS t?        d      # t0        $ r t3        d      w xY w)ap  
    Load a sequence of dictionaries from a file-like object containing one of four different formats.

    .. code-block:: python

        from sqlite_utils.utils import rows_from_file
        import io

        rows, format = rows_from_file(io.StringIO("id,name\n1,Cleo")))
        print(list(rows), format)
        # Outputs [{'id': '1', 'name': 'Cleo'}] Format.CSV

    This defaults to attempting to automatically detect the format of the data, or you can pass in an
    explicit format using the format= option.

    Returns a tuple of ``(rows_generator, format_used)`` where ``rows_generator`` can be iterated over
    to return dictionaries, while ``format_used`` is a value from the ``sqlite_utils.utils.Format`` enum:

    .. code-block:: python

        class Format(enum.Enum):
            CSV = 1
            TSV = 2
            JSON = 3
            NL = 4

    If a CSV or TSV file includes rows with more fields than are declared in the header a
    ``sqlite_utils.utils.RowError`` exception will be raised when you loop over the generator.

    You can instead ignore the extra data by passing ``ignore_extras=True``.

    Or pass ``extras_key="rest"`` to put those additional values in a list in a key called ``rest``.

    :param fp: a file-like object containing binary data
    :param format: the format to use - omit this to detect the format
    :param dialect: the CSV dialect to use - omit this to detect the dialect
    :param encoding: the character encoding to use when reading CSV/TSV data
    :param ignore_extras: ignore any extra fields on rows
    :param extras_key: put any extra fields in a list with this key
    z2Cannot use ignore_extras= and extras_key= togetherz#JSON must be a list or a dictionaryc              3   h   K   | ]*  }|j                         st        j                  |       , y wr    )rJ   jsonloads).0r`   s     r   	<genexpr>z!rows_from_file.<locals>.<genexpr>&  s!     @T4::<

4 @s   22z	utf-8-sig)r   )r   )r   r   r   r   i   )buffer_sizei   zUrows_from_file() requires a file-like object that supports peek(), such as io.BytesIO   [   {)r   ignore	z
Bad format) 
ValueErrorr{   r   r   loadrH   r4   r2   r   r   r   rn   TextIOWrapperr   
DictReaderr   r   rows_from_file	excel_tabBufferedReaderr   	RawIOBasepeekrJ   AttributeError	TypeError
startswithSniffersniffdecode	delimiterr   )r   r   r   r   r   r   decodeduse_encoding
decoded_fpr   rowsbufferedfirst_bytes_s                 r   r   r      sD   ` MNN))B-gt$iG'4(%&KLL##	699	@R@&))KK	6::	$3%%b<@
^^J@F^^J/F"6=*EvzzQQ	6::	vzz3==8

 #4
CVZZOO	$$T",,%;N	"---335K !!$';+A+A$+G!(6;;??kkm))""8#:{HEG %WxGD! $+#4#4#<VZZ&**F&t]JGOO--'  	g 	s   1J- -Kc                   R    e Zd ZdZd Zdee   dee   fdZede	e
e
f   fd       Zy)TypeTrackerac  
    Wrap an iterator of dictionaries and keep track of which SQLite column
    types are the most likely fit for each of their keys.

    Example usage:

    .. code-block:: python

        from sqlite_utils.utils import TypeTracker
        import sqlite_utils

        db = sqlite_utils.Database(memory=True)
        tracker = TypeTracker()
        rows = [{"id": "1", "name": "Cleo", "id": "2", "name": "Cardi"}]
        db["creatures"].insert_all(tracker.wrap(rows))
        print(tracker.types)
        # Outputs {'id': 'integer', 'name': 'text'}
        db["creatures"].transform(types=tracker.types)
    c                     i | _         y r    )trackersr[   s    r   r^   zTypeTracker.__init__d  s	    r   iteratorr   c              #      K   |D ]S  }|j                         D ]:  \  }}| j                  j                  |t                     }|j	                  |       < | U yw)z
        Use this to loop through an existing iterator, tracking the column types
        as part of the iteration.

        :param iterator: The iterator to wrap
        N)r!   r   r"   ValueTrackerevaluate)r[   r   r   r*   r+   trackers         r   wrapzTypeTracker.wrapg  s]       	C!iik (
U--223G  '( I		s   AAc                 ~    | j                   j                         D ci c]  \  }}||j                   c}}S c c}}w )z
        A dictionary mapping column names to their detected types. This can be passed
        to the ``db[table_name].transform(types=tracker.types)`` method.
        )r   r!   guessed_type)r[   r*   r   s      r   r;   zTypeTracker.typest  s5     ?Cmm>Q>Q>STlc7W)))TTTs   9N)rg   rh   ri   __doc__r^   r   r4   r   propertyr   r1   r;   rj   r   r   r   r   O  sM    (Xd^   UtCH~ U Ur   r   c                   P    e Zd Zd Zed        Zd Zd ZdefdZ	e
d        Zd Zy	)
r   c           	      p    | j                         D ci c]  }|t        | d|z          c}| _        y c c}w )Ntest_)	get_testsgetattrcouldbe)r[   r*   s     r   r^   zValueTracker.__init__~  s.    EI^^EUVcWT7S=99VVs   3c                     | j                   j                         D cg c]'  }|j                  d      r|j                  d      d   ) c}S c c}w )Nr   rf   )__dict__keysr   split)clsr*   s     r   r   zValueTracker.get_tests  sK     ||((*
~~g& IIgr"
 	
 
s   ,Ac                 F    	 t        |       y# t        t        f$ r Y yw xY wNTF)r   r   r   r[   r+   s     r   test_integerzValueTracker.test_integer  s(    	JI& 		      c                 F    	 t        |       y# t        t        f$ r Y yw xY wr   )r8   r   r   r   s     r   
test_floatzValueTracker.test_float  s(    	%LI& 		r   r   c                 L    | j                   dz   t        | j                        z   S )Nz: possibilities = )r   reprr   r   s    r   __repr__zValueTracker.__repr__  s"      #77$t||:LLLr   c                     t        | j                  j                               }| j                         D ]
  }||v s|c S  y)Ntext)r#   r   r   r   )r[   optionsr*   s      r   r   zValueTracker.guessed_type  s@    dll'')*>># 	Cg~
	 r   c                     |r| j                   sy g }| j                   j                         D ]  \  }} ||      r|j                  |       ! |D ]  }| j                   |=  y r    )r   r!   append)r[   r+   	not_theserq   testr*   s         r   r   zValueTracker.evaluate  se    DLL	,,,,. 	'JD$;  &	'  	"CS!	"r   N)rg   rh   ri   r^   classmethodr   r   r   r1   r   r   r   r   rj   r   r   r   r   }  sM    W 
 
M# M  "r   r   c                       e Zd Zd Zd Zd Zy)NullProgressBarc                     || _         y r    args)r[   r   s     r   r^   zNullProgressBar.__init__  s	    	r   c              #   >   K   | j                   d   E d {    y 7 w)Nr   r   r   s    r   ra   zNullProgressBar.__iter__  s     99Q<s   c                      y r    rj   r   s     r   r]   zNullProgressBar.update  s    r   N)rg   rh   ri   r^   ra   r]   rj   r   r   r   r     s     r   r   c               /      K   |j                  d      }|rt        |   y t        j                  | i |5 }| d d d        y # 1 sw Y   y xY ww)Nru   )r   r   rr   rs   )r   rv   ru   rx   s       r   rs   rs     sP     ZZ!Ft$$// 	3I	 	 	s   4AA	AA	Ac                    t         t         d}	 t        | |       |d   S # t        t        t        t
        t        f$ r Y nw xY w| g}d| vr@| j                         j                  d      s!|j                  ddj                  |              d }|D ]w  }dj                  |      g}|j                  d      D ]"  }|j                  dj                  |             $ 	 t        dj                  |      d	d
      } n# t        $ r Y uw xY w |t        d      |D ]"  }	t        |	      ||	j                  d      d   <   $ t        ||       |d   S )N)rr   convert
zreturn r   z	return {}zdef fn({}):z    {}z<string>execzCould not compile code.fn)r   r   r   SyntaxError	NameErrorKeyErrorr   rJ   r   insertr   r   r   compilejoin
__import__)
codeimportsvariableglobalsbody_variantscode_ovariantnew_coder`   import_s
             r   _compile_coder    sZ   0GT7y!!KHiH  FM4

 7 7	 BQ 2 24 89F  	!((23MM$' 	3DOOHOOD12	3	TYYx0*fEF 			 ~233 =)3G)<c"1%&=4=s!     A AC99	DDsequencerd   c           	   #      K   t        |       }|D ]2  }t        j                  |gt        j                  ||dz
               4 yw)z
    Iterate over chunks of the sequence of the given size.

    :param sequence: Any Python iterator
    :param size: The size of each chunk
    r   N)iter	itertoolschainislice)r  rd   r   items       r   chunksr    sF      H~H Lootfi&6&6x&JKKLs   AAr)   r   c                     | }||D ci c]  }|| |   
 }}t        j                  t        j                  |ddt              j                  d            j                         S c c}w )ac  
    ``record`` should be a Python dictionary. Returns a sha1 hash of the
    keys and values in that record.

    If ``keys=`` is provided, uses just those keys to generate the hash.

    Example usage::

        from sqlite_utils.utils import hash_record

        hashed = hash_record({"name": "Cleo", "twitter": "CleoPaws"})
        # Or with the keys= option:
        hashed = hash_record(
            {"name": "Cleo", "twitter": "CleoPaws", "age": 7},
            keys=("name", "twitter")
        )

    :param record: Record to generate a hash for
    :param keys: Subset of keys to use for that hash
    ),:T)
separators	sort_keysdefaultutf8)hashlibsha1r   dumpsr   encode	hexdigest)r)   r   to_hashr*   s       r   hash_recordr    sj    * G/343s#44<<

7zT4PWW	
 ik	 5s   A%c              #      K   | j                         D ];  \  }}t        |t              r t        |      D ]  \  }}|dz   |z   |f  6||f = y w)Nr   )r!   rH   r4   _flatten)dr*   r+   key2value2s        r   r  r    s`     ggi 
UeT" ( /fCi$&../ u*s   AAr   c                 *    t        t        |             S )z
    Turn a nested dict e.g. ``{"a": {"b": 1}}`` into a flat dict: ``{"a_b": 1}``

    :param row: A Python dictionary, optionally with nested dictionaries
    )r4   r  )r   s    r   flattenr!    s     r   )F)FN)NNNFN)r+   r    )=rP   
contextlibr   enumr  rn   r  r   r   r   r?   r   typingr   r   r   r   r	   r
   r   rr   	pysqlite3sqlite3r   OperationalErrorImportErrorsqleanr   r   ORIGINAL_CSV_FIELD_SIZE_LIMITr   r1   r   r,   r&   rL   rU   rW   contextmanagerry   Enumr{   	Exceptionr   r   r   r4   r6   r   Dialectr   r   r   r   rs   r  r   r  r  r  r!  rj   r   r   <module>r/     s     
   	   	 
  H H H 3 ..  !5 4 4 6 :# 846&Q   2 2$TYY 		 		+ 		y 	 %* $TND>  d^	6  $+/"$) $`.`.V`. d3;;'(`. sm	`.
 D>`. `. 8D>6!"`.F+U +U\." ."b   !H	LX 	LS 	LXh-? 	L HXc]$; > $ M  
3	3 !!22 3"!22	3
3s6   F GF*)G*GGGGG