
    i                       d dl mZ d dlmZ d dlm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 ej"                  dk\  rd dl	mZ  G d	 d
      Znd dlmZmZ d dlmZ d dlmZmZmZ d dlmZ d dlmZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z' ddl(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ d dl0Z0e
r*d dl1Z2ddl3m4Z4 ddl%m5Z6 ddl7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl%m>Z> ddl?m@Z@mAZAmBZB  G d de      ZC G d deC      ZD G d  d!eE      ZFy)"    )annotations)abstractmethod)	timedelta)PathN)TYPE_CHECKINGDictIterableListLiteralOptionalUnion)      )overridec                      e Zd Zy)EnforceOverridesN)__name__
__module____qualname__     F/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/lancedb/db.pyr   r      s    r   r   )r   r   )EmbeddingFunctionRegistry)data_to_readersanitize_urivalidate_schema)LOOP)ListNamespacesResponseCreateNamespaceResponseDropNamespaceResponseDescribeNamespaceResponseListTablesResponse   )__version__)connect)
AsyncTable
LanceTableTablesanitize_create_table)get_uri_schemevalidate_table_name)
LanceModel)
Connection)DATAURI)EmbeddingFunctionConfig)StorageOptionsProvider)Session) _normalize_create_namespace_mode_normalize_drop_namespace_mode"_normalize_drop_namespace_behaviorc                     e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 ddZddZ	 	 	 d	 	 	 	 	 	 	 ddZe		 	 ddd	 	 	 	 	 	 	 dd	       Z
e		 	 	 	 	 	 	 ddddddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       ZddZddddd	 	 	 	 	 	 	 	 	 	 	 d dZd!d"dZ	 	 d	 	 	 	 	 	 	 d#dZd Zd!d$dZed%d       Zy)&DBConnectionz'An active LanceDB connection interface.Nc                $    |g }t        g d      S )a  List immediate child namespace names in the given namespace.

        Parameters
        ----------
        namespace: List[str], default []
            The parent namespace to list namespaces in.
            Empty list represents root namespace.
        page_token: str, optional
            Token for pagination. Use the token from a previous response
            to get the next page of results.
        limit: int, optional
            The maximum number of results to return.

        Returns
        -------
        ListNamespacesResponse
            Response containing namespace names and optional page_token for pagination.
        N)
namespaces
page_token)r   self	namespacer:   limits       r   list_namespaceszDBConnection.list_namespacesD   s    0 I%EEr   c                    t        d      )-  Create a new namespace.

        Parameters
        ----------
        namespace: List[str]
            The namespace identifier to create.
        mode: str, optional
            Creation mode - "create" (fail if exists), "exist_ok" (skip if exists),
            or "overwrite" (replace if exists). Case insensitive.
        properties: Dict[str, str], optional
            Properties to set on the namespace.

        Returns
        -------
        CreateNamespaceResponse
            Response containing the properties of the created namespace.
        ?Namespace operations are not supported for this connection typeNotImplementedErrorr<   r=   mode
propertiess       r   create_namespacezDBConnection.create_namespace`       . "M
 	
r   c                    t        d      )   Drop a namespace.

        Parameters
        ----------
        namespace: List[str]
            The namespace identifier to drop.
        mode: str, optional
            Whether to skip if not exists ("SKIP") or fail ("FAIL"). Case insensitive.
        behavior: str, optional
            Whether to restrict drop if not empty ("RESTRICT") or cascade ("CASCADE").
            Case insensitive.

        Returns
        -------
        DropNamespaceResponse
            Response containing properties and transaction_id if applicable.
        rB   rC   r<   r=   rF   behaviors       r   drop_namespacezDBConnection.drop_namespace{   rI   r   c                    t        d      )  Describe a namespace.

        Parameters
        ----------
        namespace: List[str]
            The namespace identifier to describe.

        Returns
        -------
        DescribeNamespaceResponse
            Response containing the namespace properties.
        rB   rC   r<   r=   s     r   describe_namespacezDBConnection.describe_namespace   s     "M
 	
r   c                    t        d      )q  List all tables in this database with pagination support.

        Parameters
        ----------
        namespace: List[str], optional
            The namespace to list tables in.
            None or empty list represents root namespace.
        page_token: str, optional
            Token for pagination. Use the token from a previous response
            to get the next page of results.
        limit: int, optional
            The maximum number of results to return.

        Returns
        -------
        ListTablesResponse
            Response containing table names and optional page_token for pagination.
        z5list_tables is not supported for this connection typerC   r;   s       r   list_tableszDBConnection.list_tables   s    0 "C
 	
r   r=   c                    y)a3  List all tables in this database, in sorted order

        Parameters
        ----------
        namespace: List[str], default []
            The namespace to list tables in.
            Empty list represents root namespace.
        page_token: str, optional
            The token to use for pagination. If not present, start from the beginning.
            Typically, this token is last table name from the previous page.
        limit: int, default 10
            The size of the page to return.

        Returns
        -------
        Iterable of str
        Nr   )r<   r:   r>   r=   s       r   table_nameszDBConnection.table_names   s    2 	r   r=   storage_optionsstorage_options_providerdata_storage_versionenable_v2_manifest_pathsc	                   t         )aH  Create a [Table][lancedb.table.Table] in the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], default []
            The namespace to create the table in.
            Empty list represents root namespace.
        data: The data to initialize the table, *optional*
            User must provide at least one of `data` or `schema`.
            Acceptable types are:

            - list-of-dict

            - pandas.DataFrame

            - pyarrow.Table or pyarrow.RecordBatch
        schema: The schema of the table, *optional*
            Acceptable types are:

            - pyarrow.Schema

            - [LanceModel][lancedb.pydantic.LanceModel]
        mode: str; default "create"
            The mode to use when creating the table.
            Can be either "create" or "overwrite".
            By default, if the table already exists, an exception is raised.
            If you want to overwrite the table, use mode="overwrite".
        exist_ok: bool, default False
            If a table by the same name already exists, then raise an exception
            if exist_ok=False. If exist_ok=True, then open the existing table;
            it will not add the provided data but will validate against any
            schema that's specified.
        on_bad_vectors: str, default "error"
            What to do if any of the vectors are not the same size or contains NaNs.
            One of "error", "drop", "fill".
        fill_value: float
            The value to use when filling vectors. Only used if on_bad_vectors="fill".
        storage_options: dict, optional
            Additional options for the storage backend. Options already set on the
            connection will be inherited by the table, but can be overridden here.
            See available options at
            <https://lancedb.com/docs/storage/>

            To enable stable row IDs (row IDs remain stable after compaction,
            update, delete, and merges), set `new_table_enable_stable_row_ids`
            to `"true"` in storage_options when connecting to the database.
        data_storage_version: optional, str, default "stable"
            Deprecated.  Set `storage_options` when connecting to the database and set
            `new_table_data_storage_version` in the options.
        enable_v2_manifest_paths: optional, bool, default False
            Deprecated.  Set `storage_options` when connecting to the database and set
            `new_table_enable_v2_manifest_paths` in the options.
        Returns
        -------
        LanceTable
            A reference to the newly created table.

        !!! note

            The vector index won't be created by default.
            To create the index, call the `create_index` method on the table.

        Examples
        --------

        Can create with list of tuples or dictionaries:

        >>> import lancedb
        >>> db = lancedb.connect("./.lancedb")
        >>> data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
        ...         {"vector": [0.2, 1.8], "lat": 40.1, "long":  -74.1}]
        >>> db.create_table("my_table", data)
        LanceTable(name='my_table', version=1, ...)
        >>> db["my_table"].head()
        pyarrow.Table
        vector: fixed_size_list<item: float>[2]
          child 0, item: float
        lat: double
        long: double
        ----
        vector: [[[1.1,1.2],[0.2,1.8]]]
        lat: [[45.5,40.1]]
        long: [[-122.7,-74.1]]

        You can also pass a pandas DataFrame:

        >>> import pandas as pd
        >>> data = pd.DataFrame({
        ...    "vector": [[1.1, 1.2], [0.2, 1.8]],
        ...    "lat": [45.5, 40.1],
        ...    "long": [-122.7, -74.1]
        ... })
        >>> db.create_table("table2", data)
        LanceTable(name='table2', version=1, ...)
        >>> db["table2"].head()
        pyarrow.Table
        vector: fixed_size_list<item: float>[2]
          child 0, item: float
        lat: double
        long: double
        ----
        vector: [[[1.1,1.2],[0.2,1.8]]]
        lat: [[45.5,40.1]]
        long: [[-122.7,-74.1]]

        Data is converted to Arrow before being written to disk. For maximum
        control over how data is saved, either provide the PyArrow schema to
        convert to or else provide a [PyArrow Table](pyarrow.Table) directly.

        >>> import pyarrow as pa
        >>> custom_schema = pa.schema([
        ...   pa.field("vector", pa.list_(pa.float32(), 2)),
        ...   pa.field("lat", pa.float32()),
        ...   pa.field("long", pa.float32())
        ... ])
        >>> db.create_table("table3", data, schema = custom_schema)
        LanceTable(name='table3', version=1, ...)
        >>> db["table3"].head()
        pyarrow.Table
        vector: fixed_size_list<item: float>[2]
          child 0, item: float
        lat: float
        long: float
        ----
        vector: [[[1.1,1.2],[0.2,1.8]]]
        lat: [[45.5,40.1]]
        long: [[-122.7,-74.1]]


        It is also possible to create an table from `[Iterable[pa.RecordBatch]]`:


        >>> import pyarrow as pa
        >>> def make_batches():
        ...     for i in range(5):
        ...         yield pa.RecordBatch.from_arrays(
        ...             [
        ...                 pa.array([[3.1, 4.1], [5.9, 26.5]],
        ...                     pa.list_(pa.float32(), 2)),
        ...                 pa.array(["foo", "bar"]),
        ...                 pa.array([10.0, 20.0]),
        ...             ],
        ...             ["vector", "item", "price"],
        ...         )
        >>> schema=pa.schema([
        ...     pa.field("vector", pa.list_(pa.float32(), 2)),
        ...     pa.field("item", pa.utf8()),
        ...     pa.field("price", pa.float32()),
        ... ])
        >>> db.create_table("table4", make_batches(), schema=schema)
        LanceTable(name='table4', version=1, ...)

        rC   )r<   namedataschemarF   exist_okon_bad_vectors
fill_valueembedding_functionsr=   rZ   r[   r\   r]   s                 r   create_tablezDBConnection.create_table   s    Z "!r   c                $    | j                  |      S N)
open_tabler<   r_   s     r   __getitem__zDBConnection.__getitem__  s    t$$r   r=   rZ   r[   index_cache_sizec                   t         )aD  Open a Lance Table in the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], optional
            The namespace to open the table from.
            None or empty list represents root namespace.
        index_cache_size: int, default 256
            **Deprecated**: Use session-level cache configuration instead.
            Create a Session with custom cache sizes and pass it to lancedb.connect().

            Set the size of the index cache, specified as a number of entries

            The exact meaning of an "entry" will depend on the type of index:
            * IVF - there is one entry for each IVF partition
            * BTREE - there is one entry for the entire index

            This cache applies to the entire opened table, across all indices.
            Setting this value higher will increase performance on larger datasets
            at the expense of more RAM
        storage_options: dict, optional
            Additional options for the storage backend. Options already set on the
            connection will be inherited by the table, but can be overridden here.
            See available options at
            <https://lancedb.com/docs/storage/>

        Returns
        -------
        A LanceTable object representing the table.
        rC   )r<   r_   r=   rZ   r[   rm   s         r   ri   zDBConnection.open_table  s    R "!r   c                    |g }t         )a  Drop a table from the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], default []
            The namespace to drop the table from.
            Empty list represents root namespace.
        rC   )r<   r_   r=   s      r   
drop_tablezDBConnection.drop_table  s     I!!r   c                    |g }|g }t         )  Rename a table in the database.

        Parameters
        ----------
        cur_name: str
            The current name of the table.
        new_name: str
            The new name of the table.
        cur_namespace: List[str], optional
            The namespace of the current table.
            None or empty list represents root namespace.
        new_namespace: List[str], optional
            The namespace to move the table to.
            If not specified, defaults to the same as cur_namespace.
        rC   r<   cur_namenew_namecur_namespacenew_namespaces        r   rename_tablezDBConnection.rename_table  s     ,  M M!!r   c                    t         )Y
        Drop database
        This is the same thing as dropping all the tables
        rC   r<   s    r   drop_databasezDBConnection.drop_database  s
    
 "!r   c                    |g }t         )z
        Drop all tables from the database

        Parameters
        ----------
        namespace: List[str], optional
            The namespace to drop all tables from.
            None or empty list represents root namespace.
        rC   rQ   s     r   drop_all_tableszDBConnection.drop_all_tables  s     I!!r   c                    | j                   S rh   )_urir{   s    r   urizDBConnection.uri  s    yyr   NNNr=   Optional[List[str]]r:   Optional[str]r>   Optional[int]returnr   NNr=   	List[str]rF   r   rG   Optional[Dict[str, str]]r   r   r=   r   rF   r   rM   r   r   r    r=   r   r   r!   r=   r   r:   r   r>   r   r   r"   N
   r:   r   r>   intr=   r   r   Iterable[str]NNcreateFerror        N)r_   strr`   Optional[DATA]ra   &Optional[Union[pa.Schema, LanceModel]]rF   r   rb   boolrc   r   rd   floatre   'Optional[List[EmbeddingFunctionConfig]]r=   r   rZ   r   r[   "Optional['StorageOptionsProvider']r\   r   r]   Optional[bool]r   r(   )r_   r   r   r'   )r_   r   r=   r   rZ   r   r[   r   rm   r   r   r(   rh   )r_   r   r=   r   rt   r   ru   r   rv   r   rw   r   r=   r   r   r   )r   r   r   __doc__r?   rH   rN   rR   rU   r   rX   rf   rk   ri   rp   rx   r|   r~   propertyr   r   r   r   r7   r7   A   s   1 *.$(#	F&F "F 	F
 
 F> #/3	

 
 -	

 
!
< #"&	

 
  	

 

6
& *.$(#	
&
 "
 	

 

8  %)
 *.! 
 ' 
 4   $9=%GKl" *.48GK.237l"l" l" 7	l"
 l" l" l" l" El" 'l" 2l" #El" ,l" #1l"  
!l" l"\% *.48GK*.)")" '	)"
 2)" #E)" ()" 
)"V"& .2-1"" " +	"
 +"8""  r   r7   c                     e Zd ZdZddddd	 	 	 	 	 	 	 	 	 d$dZed%d       Zed&d       Zed'd       Ze	d(d       Z
d'd	Zd)d
Zed*d       Ze	 	 	 d+	 	 	 	 	 	 	 d,d       Ze	 	 d-	 	 	 	 	 	 	 d.d       Ze	 	 d-	 	 	 	 	 	 	 d/d       Zed0d       Ze	 	 	 d+	 	 	 	 	 	 	 d1d       Ze	 	 d2dd	 	 	 	 	 	 	 d3d       Zd4dZd5dZe	 	 	 	 	 	 	 d6dddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d7d       Zeddddd	 	 	 	 	 	 	 	 	 	 	 d8d       Zddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d9dZe	 	 d:	 	 	 	 	 d;d       Zed<d=d       Ze	 	 d-	 	 	 	 	 	 	 d>d       Z ej<                  dd ed!"      ed#               Z y)?LanceDBConnectiona  
    A connection to a LanceDB database.

    Parameters
    ----------
    uri: str or Path
        The root uri of the database.
    read_consistency_interval: timedelta, default None
        The interval at which to check for updates to the table from other
        processes. If None, then consistency is not checked. For performance
        reasons, this is the default. For strong consistency, set this to
        zero seconds. Then every read will check for updates from other
        processes. As a compromise, you can set this to a non-zero timedelta
        for eventual consistency. If more than that interval has passed since
        the last check, then the table will be checked for updates. Note: this
        consistency only applies to read operations. Write operations are
        always consistent.

    Examples
    --------
    >>> import lancedb
    >>> db = lancedb.connect("./.lancedb")
    >>> db.create_table("my_table", data=[{"vector": [1.1, 1.2], "b": 2},
    ...                                   {"vector": [0.5, 1.3], "b": 4}])
    LanceTable(name='my_table', version=1, ...)
    >>> db.create_table("another_table", data=[{"vector": [0.4, 0.4], "b": 6}])
    LanceTable(name='another_table', version=1, ...)
    >>> sorted(db.table_names())
    ['another_table', 'my_table']
    >>> len(db)
    2
    >>> db["my_table"]
    LanceTable(name='my_table', version=1, ...)
    >>> "my_table" in db
    True
    >>> db.drop_table("my_table")
    >>> db.drop_table("another_table")
    N)read_consistency_intervalrZ   session_innerc                 	 ||| _         y t        t              st              }t        t              xs dk(  }|rt        t              rnj                  d      rdd  nj                  d      rdd  t        j                  dk(  r#t              dk\  rd   d	k(  rd
   dk(  rdd  t              j                         j                         t              j                  dd       ||j                         	nd 		fd}| _        t        t        j                    |                   | _         y )Nfilezfile://   zfile:/   win32r   r   /   :r#   T)parentsrb   c            
     V   K   t        t              d d d  d        d {   S 7 wrh   )lancedb_connectr   )read_consistency_interval_secsr   rZ   r   s   r   
do_connectz.LanceDBConnection.__init__.<locals>.do_connectO  s;     (S!.	 	 	 	s   )'))_conn
isinstancer   r*   r   
startswithsysplatformlen
expanduserabsolutemkdirtotal_secondsrZ   AsyncConnectionr   run)
r<   r   r   rZ   r   r   schemeis_localr   r   s
    ` ``    @r   __init__zLanceDBConnection.__init__(  s%    DJ#t$#C(Fc4(<Ff,<#s# >>),ab'C^^H-ab'C<<7*3x1}Q33q6S=!!"g3i.."++-CIOOD4O8$0-F-T-T-V*-1*
	"  /$TXXjl%;<
r   c                \    t        j                  | j                  j                               S rh   )r   r   r   get_read_consistency_intervalr{   s    r   r   z+LanceDBConnection.read_consistency_intervalc  s    xx

@@BCCr   c                .    | j                   j                  S rh   )r   r   r{   s    r   r   zLanceDBConnection.sessiong  s    zz!!!r   c                .    | j                   j                  S rh   )r   r   r{   s    r   r   zLanceDBConnection.urik  s    zz~~r   c                     | d |      S )Nr   r   )clsinners     r   
from_innerzLanceDBConnection.from_innero  s    4&&r   c                    | j                   j                   d| j                  j                  }| j                  |dt        | j                         z  }|dz  }|S )Nz(uri=z, read_consistency_interval=))	__class__r   r   r   r   repr)r<   vals     r   __repr__zLanceDBConnection.__repr__s  s^    (()tzz~~.@A))51$t7U7U2V1WXXCs

r   c                   K   t        t        | j                         d {         }|j                  ||       d {   S 7 #7 w)N)start_afterr>   )r   r   r   rX   )r<   r   r>   conns       r   _async_get_table_namesz(LanceDBConnection._async_get_table_namesz  s>     _TXX%>>?%%+U%KKK  ?Ks    AAAA AAc                .    | j                   j                  S rh   )r   r   r{   s    r   r   zLanceDBConnection._inner~  s    zz   r   c                l    |g }t        j                  | j                  j                  |||            S )a  List immediate child namespace names in the given namespace.

        Parameters
        ----------
        namespace: List[str], optional
            The parent namespace to list namespaces in.
            None or empty list represents root namespace.
        page_token: str, optional
            Token for pagination. Use the token from a previous response
            to get the next page of results.
        limit: int, optional
            The maximum number of results to return.

        Returns
        -------
        ListNamespacesResponse
            Response containing namespace names and optional page_token for pagination.
        r=   r:   r>   )r   r   r   r?   r;   s       r   r?   z!LanceDBConnection.list_namespaces  s>    2 IxxJJ&&#
% ' 
 	
r   c                d    t        j                  | j                  j                  |||            S )rA   )r=   rF   rG   )r   r   r   rH   rE   s       r   rH   z"LanceDBConnection.create_namespace  s3    0 xxJJ''#$: ( 
 	
r   c                d    t        j                  | j                  j                  |||            S )rK   )r=   rF   rM   )r   r   r   rN   rL   s       r   rN   z LanceDBConnection.drop_namespace  s.    0 xxJJ%%	x%X
 	
r   c                `    t        j                  | j                  j                  |            S )rP   rV   )r   r   r   rR   rQ   s     r   rR   z$LanceDBConnection.describe_namespace  s%     xx

55	5JKKr   c                l    |g }t        j                  | j                  j                  |||            S )rT   r   )r   r   r   rU   r;   s       r   rU   zLanceDBConnection.list_tables  s>    2 IxxJJ""#
% # 
 	
r   rV   c                   ddl }|j                  dt        d       |g }t        j                  | j
                  j                  |||            S )a5  Get the names of all tables in the database. The names are sorted.

        .. deprecated::
            Use :meth:`list_tables` instead, which provides proper pagination support.

        Parameters
        ----------
        namespace: List[str], optional
            The namespace to list tables in.
        page_token: str, optional
            The token to use for pagination.
        limit: int, default 10
            The maximum number of tables to return.

        Returns
        -------
        Iterator of str.
            A list of table names.
        r   N6table_names() is deprecated, use list_tables() insteadr   
stacklevelr=   r   r>   )warningswarnDeprecationWarningr   r   r   rX   )r<   r:   r>   r=   r   s        r   rX   zLanceDBConnection.table_names  s]    6 	D 	 	

 IxxJJ""#5 # 
 	
r   c                4    t        | j                               S rh   )r   rX   r{   s    r   __len__zLanceDBConnection.__len__8  s    4##%&&r   c                &    || j                         v S rh   )rX   rj   s     r   __contains__zLanceDBConnection.__contains__;  s    t'')))r   rY   c	                   |	g }	|j                         dvrt        d      t        |       t        j                  | |||||||||	|
|      }|S )zCreate a table in the database.

        Parameters
        ----------
        namespace: List[str], optional
            The namespace to create the table in.

        See
        ---
        DBConnection.create_table
        )r   	overwritez+mode must be either 'create' or 'overwrite')rF   rb   rc   rd   re   r=   rZ   r[   )lower
ValueErrorr+   r'   r   )r<   r_   r`   ra   rF   rb   rc   rd   re   r=   rZ   r[   r\   r]   tbls                  r   rf   zLanceDBConnection.create_table>  sm    : I::<66JKKD!)! 3+%=
 
r   rl   c               |    |g }|ddl }|j                  dt        d       t        j                  | |||||      S )a0  Open a table in the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], optional
            The namespace to open the table from.

        Returns
        -------
        A LanceTable object representing the table.
        Nr   zindex_cache_size is deprecated. Use session-level cache configuration instead. Create a Session with custom cache sizes and pass it to lancedb.connect().r   r   rl   )r   r   r   r'   open)r<   r_   r=   rZ   r[   rm   r   s          r   ri   zLanceDBConnection.open_tableq  s[    . I'MM4 #   +%=-
 	
r   Ttarget_namespacesource_version
source_tag
is_shallowc          
         |g }t        j                  | j                  j                  ||||||             t	        j
                  | ||      S )ar  Clone a table from a source table.

        A shallow clone creates a new table that shares the underlying data files
        with the source table but has its own independent manifest. This allows
        both the source and cloned tables to evolve independently while initially
        sharing the same data, deletion, and index files.

        Parameters
        ----------
        target_table_name: str
            The name of the target table to create.
        source_uri: str
            The URI of the source table to clone from.
        target_namespace: List[str], optional
            The namespace for the target table.
            None or empty list represents root namespace.
        source_version: int, optional
            The version of the source table to clone.
        source_tag: str, optional
            The tag of the source table to clone.
        is_shallow: bool, default True
            Whether to perform a shallow clone (True) or deep clone (False).
            Currently only shallow clone is supported.

        Returns
        -------
        A LanceTable object representing the cloned table.
        r   rV   )r   r   r   clone_tabler'   r   )r<   target_table_name
source_urir   r   r   r   s          r   r   zLanceDBConnection.clone_table  sb    L #!JJ""!!1-%% # 		
 &
 	
r   c                n    |g }t        j                  | j                  j                  |||             y)aB  Drop a table from the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], optional
            The namespace to drop the table from.
        ignore_missing: bool, default False
            If True, ignore if the table does not exist.
        Nr=   ignore_missing)r   r   r   rp   )r<   r_   r=   r   s       r   rp   zLanceDBConnection.drop_table  s9    $ IJJ!!	. " 	
r   c                j    |g }t        j                  | j                  j                  |             y )NrV   r   r   r   r~   rQ   s     r   r~   z!LanceDBConnection.drop_all_tables  s+    I++i+@Ar   c                x    |g }|g }t        j                  | j                  j                  ||||             y)a  Rename a table in the database.

        Parameters
        ----------
        cur_name: str
            The current name of the table.
        new_name: str
            The new name of the table.
        cur_namespace: List[str], optional
            The namespace of the current table.
        new_namespace: List[str], optional
            The namespace to move the table to.
        Nrv   rw   )r   r   r   rx   rs   s        r   rx   zLanceDBConnection.rename_table  sI    *  M MJJ##++	 $ 	
r   0.15.10.17Use drop_all_tables() insteaddeprecated_in
removed_incurrent_versiondetailsc                ^    t        j                  | j                  j                                y rh   r   r{   s    r   r|   zLanceDBConnection.drop_database  s     	++-.r   )
r   r/   r   Optional[timedelta]rZ   r   r   Optional[Session]r   zOptional[LanceDbConnection]r   r  )r   r  r   )r   LanceDbConnection)r   r   r>   r   )r   r  r   r   r   r   r   r   r   r   r   )r   r   )r_   r   r   r   r   )r_   r   r`   r   ra   r   rF   r   rb   r   rc   r   rd   r   re   r   r=   r   rZ   r   r[   r   r\   r   r]   r   r   r'   )r_   r   r=   r   rZ   r   r[   r   rm   r   r   r'   )r   r   r   r   r   r   r   r   r   r   r   r   r   r'   )NFr_   r   r=   r   r   r   rh   r   r   )!r   r   r   r   r   r   r   r   r   classmethodr   r   r   r   r   r?   rH   rN   rR   rU   rX   r   r   rf   ri   r   rp   r~   rx   deprecation
deprecatedr$   r|   r   r   r   r   r      s   %V :>48%).29=9= $7	9=
 29= #9= ,9=v D D " "   ' 'L ! !  *.$(#	
&
 "
 	

 
 
 
@  #/3	

 
 -	

 
!
 
:  #"&	

 
  	

 

 
6 L L  *.$(#	
&
 "
 	

 

 
@  %)'

 *.'
!'
 '

 ''
 
'
 '
R'*   $9=%GK0 *.48GK.23700 0 7	0
 0 0 0 0 E0 '0 20 #E0 ,0 #10  
!0 0d 
 *.48GK*.*
*
 '	*

 2*
 #E*
 (*
 
*
 *
b 15(,$(6
6
 6

 .6
 &6
 "6
 6
 
6
p  *.$	

 '
 	
 
2 B B
 
 .2-1

 
 +	

 +
 
B [#/	 / /r   r   c                      e Zd ZdZd#dZd Zd Zd Zd Zd Z	e
d$d       Zd%d	Z	 	 	 d&	 	 	 	 	 	 	 d'dZ	 	 d(	 	 	 	 	 	 	 d)dZ	 	 d(	 	 	 	 	 	 	 d*dZ	 	 	 	 d+dZ	 	 	 d&	 	 	 	 	 	 	 d,dZd
d
d
d	 	 	 	 	 	 	 d-dZ	 	 	 	 	 	 	 	 d.d
d
d
d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d/dZd
d
d
d
d
d	 	 	 	 	 	 	 	 	 	 	 	 	 d0dZd
d
d
dd	 	 	 	 	 	 	 	 	 	 	 	 	 d1dZ	 	 d(	 	 	 	 	 	 	 d2dZd
dd	 	 	 	 	 d3dZd4d5dZ ej4                  dded !      d"        Zy
)6r   a1  An active LanceDB connection

    To obtain a connection you can use the [connect_async][lancedb.connect_async]
    function.

    This could be a native connection (using lance) or a remote connection (e.g. for
    connecting to LanceDb Cloud)

    Local connections do not currently hold any open resources but they may do so in the
    future (for example, for shared cache or connections to catalog services) Remote
    connections represent an open connection to the remote server.  The
    [close][lancedb.db.AsyncConnection.close] method can be used to release any
    underlying resources eagerly.  The connection can also be used as a context manager.

    Connections can be shared on multiple threads and are expected to be long lived.
    Connections can also be used as a context manager, however, in many cases a single
    connection can be used for the lifetime of the application and so this is often
    not needed.  Closing a connection is optional.  If it is not closed then it will
    be automatically closed when the connection object is deleted.

    Examples
    --------

    >>> import lancedb
    >>> async def doctest_example():
    ...   with await lancedb.connect_async("/tmp/my_dataset") as conn:
    ...     # do something with the connection
    ...     pass
    ...   # conn is closed here
    c                    || _         y rh   r   )r<   
connections     r   r   zAsyncConnection.__init__C  s	     r   c                6    | j                   j                         S rh   )r   r   r{   s    r   r   zAsyncConnection.__repr__F  s    {{##%%r   c                    | S rh   r   r{   s    r   	__enter__zAsyncConnection.__enter__I  s    r   c                $    | j                          y rh   )close)r<   _s     r   __exit__zAsyncConnection.__exit__L  s    

r   c                6    | j                   j                         S )z&Return True if the connection is open.)r   is_openr{   s    r   r  zAsyncConnection.is_openO  s    {{""$$r   c                8    | j                   j                          y)zClose the connection, releasing any underlying resources.

        It is safe to call this method multiple times.

        Any attempt to use the connection after it is closed will result in an error.N)r   r  r{   s    r   r  zAsyncConnection.closeS  s     	r   c                .    | j                   j                  S rh   )r   r   r{   s    r   r   zAsyncConnection.uri[  s    {{r   c                p   K   | j                   j                          d {   }|t        |      S y 7 w)N)seconds)r   r   r   )r<   interval_secss     r   r   z-AsyncConnection.get_read_consistency_interval_  s5     "kkGGII$]33	 Js   646Nc                x   K   |g }| j                   j                  |||       d{   }t        di |S 7 w)a^  List immediate child namespace names in the given namespace.

        Parameters
        ----------
        namespace: List[str], optional
            The parent namespace to list namespaces in.
            None or empty list represents root namespace.
        page_token: str, optional
            The token to use for pagination. If not present, start from the beginning.
        limit: int, optional
            The maximum number of results to return.

        Returns
        -------
        ListNamespacesResponse
            Response containing namespace names and optional pagination token
        Nr   r   )r   r?   r   r<   r=   r:   r>   results        r   r?   zAsyncConnection.list_namespacesf  sM     . I{{22Je 3 
 
 &///
   &:8:c                   K   | j                   j                  |t        |      |       d{   }t        di |S 7 w)a  Create a new namespace.

        Parameters
        ----------
        namespace: List[str]
            The namespace identifier to create.
        mode: str, optional
            Creation mode - "create", "exist_ok", or "overwrite". Case insensitive.
        properties: Dict[str, str], optional
            Properties to associate with the namespace

        Returns
        -------
        CreateNamespaceResponse
            Response containing namespace properties
        )rF   rG   Nr   )r   rH   r3   r   )r<   r=   rF   rG   r'  s        r   rH   z AsyncConnection.create_namespace  sI     , {{331$7! 4 
 

 '000
s   +?=?c                   K   | j                   j                  |t        |      t        |             d{   }t	        di |S 7 w)rK   )rF   rM   Nr   )r   rN   r4   r5   r    )r<   r=   rF   rM   r'  s        r   rN   zAsyncConnection.drop_namespace  sN     . {{11/57A 2 
 

 %.v..
s   4AAAc                j   K   | j                   j                  |       d{   }t        di |S 7 w)rP   Nr   )r   rR   r!   )r<   r=   r'  s      r   rR   z"AsyncConnection.describe_namespace  s3      {{55i@@(2622 As   313c                x   K   |g }| j                   j                  |||       d{   }t        di |S 7 w)rT   Nr   r   )r   rU   r"   r&  s        r   rU   zAsyncConnection.list_tables  sM     0 I{{..Je / 
 
 "+F++
r(  r   c                  K   ddl }|j                  dt        d       |g }| j                  j	                  |||       d{   S 7 w)a  List all tables in this database, in sorted order

        .. deprecated::
            Use :meth:`list_tables` instead, which provides proper pagination support.

        Parameters
        ----------
        namespace: List[str], optional
            The namespace to list tables in.
            None or empty list represents root namespace.
        start_after: str, optional
            If present, only return names that come lexicographically after the supplied
            value.

            This can be combined with limit to implement pagination by setting this to
            the last table name from the previous page.
        limit: int, default 10
            The number of results to return.

        Returns
        -------
        Iterable of str
        r   Nr   r   r   r   )r   r   r   r   rX   )r<   r=   r   r>   r   s        r   rX   zAsyncConnection.table_names  s_     < 	D 	 	

 I[[,,[ - 
 
 	
 
s   AAA	A)r=   re   locationc
          	       K   |
g }
d}|%t        j                         }|j                  |      }|d}|d}t        |||||      \  }}t	        |       |d}|d}|dk(  r|rd}|5| j
                  j                  ||||
||	|       d{   }t        |      S t        ||      }| j
                  j                  ||||
||	|       d{   }t        |      S 7 P7 w)a  Create an [AsyncTable][lancedb.table.AsyncTable] in the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], default []
            The namespace to create the table in.
            Empty list represents root namespace.
        data: The data to initialize the table, *optional*
            User must provide at least one of `data` or `schema`.
            Acceptable types are:

            - list-of-dict

            - pandas.DataFrame

            - pyarrow.Table or pyarrow.RecordBatch
        schema: The schema of the table, *optional*
            Acceptable types are:

            - pyarrow.Schema

            - [LanceModel][lancedb.pydantic.LanceModel]
        mode: Literal["create", "overwrite"]; default "create"
            The mode to use when creating the table.
            Can be either "create" or "overwrite".
            By default, if the table already exists, an exception is raised.
            If you want to overwrite the table, use mode="overwrite".
        exist_ok: bool, default False
            If a table by the same name already exists, then raise an exception
            if exist_ok=False. If exist_ok=True, then open the existing table;
            it will not add the provided data but will validate against any
            schema that's specified.
        on_bad_vectors: str, default "error"
            What to do if any of the vectors are not the same size or contains NaNs.
            One of "error", "drop", "fill".
        fill_value: float
            The value to use when filling vectors. Only used if on_bad_vectors="fill".
        storage_options: dict, optional
            Additional options for the storage backend. Options already set on the
            connection will be inherited by the table, but can be overridden here.
            See available options at
            <https://lancedb.com/docs/storage/>

            To enable stable row IDs (row IDs remain stable after compaction,
            update, delete, and merges), set `new_table_enable_stable_row_ids`
            to `"true"` in storage_options when connecting to the database.

        Returns
        -------
        AsyncTable
            A reference to the newly created table.

        !!! note

            The vector index won't be created by default.
            To create the index, call the `create_index` method on the table.

        Examples
        --------

        Can create with list of tuples or dictionaries:

        >>> import lancedb
        >>> async def doctest_example():
        ...     db = await lancedb.connect_async("./.lancedb")
        ...     data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
        ...             {"vector": [0.2, 1.8], "lat": 40.1, "long":  -74.1}]
        ...     my_table = await db.create_table("my_table", data)
        ...     print(await my_table.query().limit(5).to_arrow())
        >>> import asyncio
        >>> asyncio.run(doctest_example())
        pyarrow.Table
        vector: fixed_size_list<item: float>[2]
          child 0, item: float
        lat: double
        long: double
        ----
        vector: [[[1.1,1.2],[0.2,1.8]]]
        lat: [[45.5,40.1]]
        long: [[-122.7,-74.1]]

        You can also pass a pandas DataFrame:

        >>> import pandas as pd
        >>> data = pd.DataFrame({
        ...    "vector": [[1.1, 1.2], [0.2, 1.8]],
        ...    "lat": [45.5, 40.1],
        ...    "long": [-122.7, -74.1]
        ... })
        >>> async def pandas_example():
        ...     db = await lancedb.connect_async("./.lancedb")
        ...     my_table = await db.create_table("table2", data)
        ...     print(await my_table.query().limit(5).to_arrow())
        >>> asyncio.run(pandas_example())
        pyarrow.Table
        vector: fixed_size_list<item: float>[2]
          child 0, item: float
        lat: double
        long: double
        ----
        vector: [[[1.1,1.2],[0.2,1.8]]]
        lat: [[45.5,40.1]]
        long: [[-122.7,-74.1]]

        Data is converted to Arrow before being written to disk. For maximum
        control over how data is saved, either provide the PyArrow schema to
        convert to or else provide a [PyArrow Table](pyarrow.Table) directly.

        >>> import pyarrow as pa
        >>> custom_schema = pa.schema([
        ...   pa.field("vector", pa.list_(pa.float32(), 2)),
        ...   pa.field("lat", pa.float32()),
        ...   pa.field("long", pa.float32())
        ... ])
        >>> async def with_schema():
        ...     db = await lancedb.connect_async("./.lancedb")
        ...     my_table = await db.create_table("table3", data, schema = custom_schema)
        ...     print(await my_table.query().limit(5).to_arrow())
        >>> asyncio.run(with_schema())
        pyarrow.Table
        vector: fixed_size_list<item: float>[2]
          child 0, item: float
        lat: float
        long: float
        ----
        vector: [[[1.1,1.2],[0.2,1.8]]]
        lat: [[45.5,40.1]]
        long: [[-122.7,-74.1]]


        It is also possible to create an table from `[Iterable[pa.RecordBatch]]`:


        >>> import pyarrow as pa
        >>> def make_batches():
        ...     for i in range(5):
        ...         yield pa.RecordBatch.from_arrays(
        ...             [
        ...                 pa.array([[3.1, 4.1], [5.9, 26.5]],
        ...                     pa.list_(pa.float32(), 2)),
        ...                 pa.array(["foo", "bar"]),
        ...                 pa.array([10.0, 20.0]),
        ...             ],
        ...             ["vector", "item", "price"],
        ...         )
        >>> schema=pa.schema([
        ...     pa.field("vector", pa.list_(pa.float32(), 2)),
        ...     pa.field("item", pa.utf8()),
        ...     pa.field("price", pa.float32()),
        ... ])
        >>> async def iterable_example():
        ...     db = await lancedb.connect_async("./.lancedb")
        ...     await db.create_table("table4", make_batches(), schema=schema)
        >>> asyncio.run(iterable_example())
        Nr   r   Fr   rb   )r=   rZ   r[   r.  )
r   get_instanceget_table_metadatar)   r   r   create_empty_tabler   rf   r&   )r<   r_   r`   ra   rF   rb   rc   rd   rZ   r[   r=   re   r.  metadataregistry	new_tables                   r   rf   zAsyncConnection.create_table  s=    Z I* 1==?H223FGH !$NJ,&(NJ
f 	H<D8D<"kk<<# /)A! =  I* )$$ "$/D"kk66# /)A! 7  I )$$+s%   BC"CA C"C C" C"r=   rZ   r[   rm   r.  c               ~   K   |g }| j                   j                  ||||||       d{   }t        |      S 7 w)a(  Open a Lance Table in the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], optional
            The namespace to open the table from.
            None or empty list represents root namespace.
        storage_options: dict, optional
            Additional options for the storage backend. Options already set on the
            connection will be inherited by the table, but can be overridden here.
            See available options at
            <https://lancedb.com/docs/storage/>
        index_cache_size: int, default 256
            **Deprecated**: Use session-level cache configuration instead.
            Create a Session with custom cache sizes and pass it to lancedb.connect().

            Set the size of the index cache, specified as a number of entries

            The exact meaning of an "entry" will depend on the type of index:
            * IVF - there is one entry for each IVF partition
            * BTREE - there is one entry for the entire index

            This cache applies to the entire opened table, across all indices.
            Setting this value higher will increase performance on larger datasets
            at the expense of more RAM
        location: str, optional
            The explicit location (URI) of the table. If provided, the table will be
            opened from this location instead of deriving it from the database URI
            and table name.

        Returns
        -------
        A LanceTable object representing the table.
        Nr6  )r   ri   r&   )r<   r_   r=   rZ   r[   rm   r.  tables           r   ri   zAsyncConnection.open_table  sV     \ Ikk,,+%=- - 
 
 %  
   )=;=Tr   c               ~   K   |g }| j                   j                  ||||||       d{   }t        |      S 7 w)as  Clone a table from a source table.

        A shallow clone creates a new table that shares the underlying data files
        with the source table but has its own independent manifest. This allows
        both the source and cloned tables to evolve independently while initially
        sharing the same data, deletion, and index files.

        Parameters
        ----------
        target_table_name: str
            The name of the target table to create.
        source_uri: str
            The URI of the source table to clone from.
        target_namespace: List[str], optional
            The namespace for the target table.
            None or empty list represents root namespace.
        source_version: int, optional
            The version of the source table to clone.
        source_tag: str, optional
            The tag of the source table to clone.
        is_shallow: bool, default True
            Whether to perform a shallow clone (True) or deep clone (False).
            Currently only shallow clone is supported.

        Returns
        -------
        An AsyncTable object representing the cloned table.
        Nr   )r   r   r&   )r<   r   r   r   r   r   r   r8  s           r   r   zAsyncConnection.clone_table9  sW     L #!kk---)!! . 
 
 %  
r9  c                n   K   |g }|g }| j                   j                  ||||       d{    y7 w)rr   Nr  )r   rx   rs   s        r   rx   zAsyncConnection.rename_tablek  sH     ,  M Mkk&&hm= ' 
 	
 	
s   +535Fr   c                  K   |g }	 | j                   j                  ||       d{    y7 # t        $ r!}|s|d| dt        |      vr|Y d}~yd}~ww xY ww)av  Drop a table from the database.

        Parameters
        ----------
        name: str
            The name of the table.
        namespace: List[str], default []
            The namespace to drop the table from.
            Empty list represents root namespace.
        ignore_missing: bool, default False
            If True, ignore if the table does not exist.
        NrV   zTable 'z' was not found)r   rp   r   r   )r<   r_   r=   r   es        r   rp   zAsyncConnection.drop_table  sk     & I	++(((CCC 	!o.c!f< =	s6   A 0 .0 A0 	AAAAAc                `   K   |g }| j                   j                  |       d{    y7 w)zDrop all tables from the database.

        Parameters
        ----------
        namespace: List[str], optional
            The namespace to drop all tables from.
            None or empty list represents root namespace.
        NrV   r   r~   rQ   s     r   r~   zAsyncConnection.drop_all_tables  s.      Ikk))I)>>>s   $.,.r  r  r  r  c                T   K   | j                   j                          d{    y7 w)rz   Nr?  r{   s    r   r|   zAsyncConnection.drop_database  s      kk))+++s   (&()r  r  r   r  r   r   r   r   r   r   r   )r=   r   r   r   r>   r   r   r   )NNNNNNNN)r_   r   r`   r   ra   r   rF   z(Optional[Literal['create', 'overwrite']]rb   r   rc   r   rd   zOptional[float]rZ   r   r[   r   r=   r   re   r   r.  r   r   r&   )r_   r   r=   r   rZ   r   r[   r   rm   r   r.  r   r   r&   )r   r   r   r   r   r   r   r   r   r   r   r   r   r&   r   r  rh   r   )r   r   r   r   r   r   r  r  r  r  r   r   r   r?   rH   rN   rR   rU   rX   rf   ri   r   rx   rp   r~   r  r  r$   r|   r   r   r   r   r   #  se   >!&%   *.$(#	0&0 "0 	0
 
 0B #/3	11 1 -	1
 
!1@ #"&	// /  	/
 
/<3"3	"3( *.$(#	,&, ", 	,
 
,D *.%)#)
 ')
 #	)

 )
 
)
\  $9=9=#'(,&*48GKb% *.GK"&b%b% b% 7	b%
 7b% !b% &b% $b% 2b% #Eb% 'b% Eb%  b% 
b%P *.48GK*."&8!8! '	8!
 28! #E8! (8!  8! 
8!~ 15(,$(0!0! 0!
 .0! &0! "0! 0! 
0!l .2-1

 
 +	

 +
D *.$ '	
 :? [#/	,,r   r   )G
__future__r   abcr   datetimer   pathlibr   r   typingr   r   r	   r
   r   r   r   version_infor   r   	overrideslancedb.embeddings.registryr   lancedb.commonr   r   r   lancedb.background_loopr   lance_namespacer   r   r    r!   r"    r$   _lancedbr%   r   r8  r&   r'   r(   r)   utilr*   r+   r  pyarrowpapydanticr,   r-   r  commonr.   r/   
embeddingsr0   ior1   r2   namespace_utilsr3   r4   r5   r7   r   objectr   r   r   r   <module>rW     s   
 #    
 P P Pw  5 A H H (   0 
 $9!3*! |# |~`/ `/F[
,f [
,r   