o
    v&iر                     @  st  d 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ZddlZddlZddlZddlZddlmZmZmZ ddlmZmZmZ ddlmZmZmZ ddlmZm Z  ddl!m"Z"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/m0Z0 ddl1m2Z2 e#eZdZ3dZ4dddZ5G dd dZ6G dd dZ7dddZ8dS )zSQLite coverage data.    )annotationsN)
CollectionMappingSequence)AnyCallablecast)NoDebugging	auto_reprfile_summary)CoverageException	DataError)file_be_goneisolate_module)numbits_to_numsnumbits_unionnums_to_numbits)SqliteDb)AnyCallableFilePathTArc	TDebugCtlTLineNoTWarnFn)__version__   a  CREATE TABLE coverage_schema (
    -- One row, to record the version of the schema in this db.
    version integer
);

CREATE TABLE meta (
    -- Key-value pairs, to record metadata about the data
    key text,
    value text,
    unique (key)
    -- Possible keys:
    --  'has_arcs' boolean      -- Is this data recording branches?
    --  'sys_argv' text         -- The coverage command line that recorded the data.
    --  'version' text          -- The version of coverage.py that made the file.
    --  'when' text             -- Datetime when the file was created.
);

CREATE TABLE file (
    -- A row per file measured.
    id integer primary key,
    path text,
    unique (path)
);

CREATE TABLE context (
    -- A row per context measured.
    id integer primary key,
    context text,
    unique (context)
);

CREATE TABLE line_bits (
    -- If recording lines, a row per context per file executed.
    -- All of the line numbers for that file/context are in one numbits.
    file_id integer,            -- foreign key to `file`.
    context_id integer,         -- foreign key to `context`.
    numbits blob,               -- see the numbits functions in coverage.numbits
    foreign key (file_id) references file (id),
    foreign key (context_id) references context (id),
    unique (file_id, context_id)
);

CREATE TABLE arc (
    -- If recording branches, a row per context per from/to line transition executed.
    file_id integer,            -- foreign key to `file`.
    context_id integer,         -- foreign key to `context`.
    fromno integer,             -- line number jumped from.
    tono integer,               -- line number jumped to.
    foreign key (file_id) references file (id),
    foreign key (context_id) references context (id),
    unique (file_id, context_id, fromno, tono)
);

CREATE TABLE tracer (
    -- A row per file indicating the tracer used for that file.
    file_id integer primary key,
    tracer text,
    foreign key (file_id) references file (id)
);
methodr   returnc                   s   t  d
 fdd}|S )z4A decorator for methods that should hold self._lock.selfCoverageDataargsr   kwargsr   c                   s   | j dr| j d| jd j  | j' | j dr,| j d| jd j   | g|R i |W  d    S 1 sAw   Y  d S )NlockzLocking z for zLocked )_debugshouldwrite_lock__name__)r   r    r!   r    V/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/coverage/sqldata.py_wrappedt   s   $z_locked.<locals>._wrappedN)r   r   r    r   r!   r   r   r   )	functoolswraps)r   r+   r)   r(   r*   _lockedq   s   r.   c                   @  s.   e Zd ZdZdddZddd	Zdd
dZdS )NumbitsUnionAggz9SQLite aggregate function for computing union of numbits.r   Nonec                 C  s
   d| _ d S )N    resultr   r)   r)   r*   __init__   s   
zNumbitsUnionAgg.__init__valuebytesc                 C  s   t | j|| _dS )z%Process one value in the aggregation.N)r   r3   )r   r6   r)   r)   r*   step      zNumbitsUnionAgg.stepc                 C     | j S )z#Return the final aggregated result.r2   r4   r)   r)   r*   finalize   s   zNumbitsUnionAgg.finalizeNr   r0   )r6   r7   r   r0   r   r7   )r'   
__module____qualname____doc__r5   r8   r;   r)   r)   r)   r*   r/      s
    

r/   c                   @  s  e Zd ZdZ					ddddZeZdddZdddZdddZ	ddddZ
dddZdd d!Zdd$d%Zdd&d'Zdd(d)Zdd+d,Zdd.d/Zddd2d3Zdd5d6Zedd8d9Zdd:d;Zdd<d=Zdd>d?ZeddBdCZeddFdGZdddJdKZeddNdOZdddRdSZdddVdWZddXdYZ	ddd]d^Z ddd`daZ!ddbdcZ"ddddeZ#ddfdgZ$ddhdiZ%ddkdlZ&ddmdnZ'ddodpZ(ddqdrZ)ddudvZ*ddxdyZ+dd{d|Z,dd~dZ-e.dddZ/dS )r   a}  Manages collected coverage data, including file storage.

    This class is the public supported API to the data that coverage.py
    collects during program execution.  It includes information about what code
    was executed. It does not include information from the analysis phase, to
    determine what lines could have been executed, or what lines were not
    executed.

    .. note::

        The data file is currently a SQLite database file, with a
        :ref:`documented schema <dbschema>`. The schema is subject to change
        though, so be careful about querying it directly. Use this API if you
        can to isolate yourself from changes.

    There are a number of kinds of data that can be collected:

    * **lines**: the line numbers of source lines that were executed.
      These are always available.

    * **arcs**: pairs of source and destination line numbers for transitions
      between source lines.  These are only available if branch coverage was
      used.

    * **file tracer names**: the module names of the file tracer plugins that
      handled each file in the data.

    Lines, arcs, and file tracer names are stored for each source file. File
    names in this API are case-sensitive, even on platforms with
    case-insensitive file systems.

    A data file either stores lines, or arcs, but not both.

    A data file is associated with the data when the :class:`CoverageData`
    is created, using the parameters `basename`, `suffix`, and `no_disk`. The
    base name can be queried with :meth:`base_filename`, and the actual file
    name being used is available from :meth:`data_filename`.

    To read an existing coverage.py data file, use :meth:`read`.  You can then
    access the line, arc, or file tracer data with :meth:`lines`, :meth:`arcs`,
    or :meth:`file_tracer`.

    The :meth:`has_arcs` method indicates whether arc data is available.  You
    can get a set of the files in the data with :meth:`measured_files`.  As
    with most Python containers, you can determine if there is any data at all
    by using this object as a boolean value.

    The contexts for each line in a file can be read with
    :meth:`contexts_by_lineno`.

    To limit querying to certain contexts, use :meth:`set_query_context` or
    :meth:`set_query_contexts`. These will narrow the focus of subsequent
    :meth:`lines`, :meth:`arcs`, and :meth:`contexts_by_lineno` calls. The set
    of all measured context names can be retrieved with
    :meth:`measured_contexts`.

    Most data files will be created by coverage.py itself, but you can use
    methods here to create data files if you like.  The :meth:`add_lines`,
    :meth:`add_arcs`, and :meth:`add_file_tracers` methods add data, in ways
    that are convenient for coverage.py.

    To record data for contexts, use :meth:`set_context` to set a context to
    be used for subsequent :meth:`add_lines` and :meth:`add_arcs` calls.

    To add a source file without any measured data, use :meth:`touch_file`,
    or :meth:`touch_files` for a list of such files.

    Write the data to its file with :meth:`write`.

    You can clear the data in memory with :meth:`erase`.  Data for specific
    files can be removed from the database with :meth:`purge_files`.

    Two data collections can be combined by using :meth:`update` on one
    :class:`CoverageData`, passing it the other.

    Data in a :class:`CoverageData` can be serialized and deserialized with
    :meth:`dumps` and :meth:`loads`.

    The methods used during the coverage.py collection phase
    (:meth:`add_lines`, :meth:`add_arcs`, :meth:`set_context`, and
    :meth:`add_file_tracers`) are thread-safe.  Other methods may not be.

    NFbasenameFilePath | Nonesuffixstr | bool | Noneno_diskboolwarnTWarnFn | NonedebugTDebugCtl | Noner   r0   c                 C  s   || _ tj|p	d| _|| _|| _|pt | _| 	  i | _
i | _t | _t | _d| _d| _d| _d| _d| _d| _dS )a  Create a :class:`CoverageData` object to hold coverage-measured data.

        Arguments:
            basename (str): the base name of the data file, defaulting to
                ".coverage". This can be a path to a file in another directory.
            suffix (str or bool): has the same meaning as the `data_suffix`
                argument to :class:`coverage.Coverage`.
            no_disk (bool): if True, keep all data in memory, and don't
                write any disk file.
            warn: a warning callback function, accepting a warning message
                argument.
            debug: a `DebugControl` object (optional)

        z	.coverageFN)_no_diskospathabspath	_basename_suffix_warnr	   r#   _choose_filename	_file_map_dbsgetpid_pid	threadingRLockr&   
_have_used
_has_lines	_has_arcs_current_context_current_context_id_query_context_ids)r   rA   rC   rE   rG   rI   r)   r)   r*   r5      s    


zCoverageData.__init__msgstrfilenamec                 C  s6   | j dr| j | d|dt| d dS dS )z2A helper for debug messages which are all similar.dataio z ()N)r#   r$   r%   r   )r   r_   ra   r)   r)   r*   _debug_dataio  s   &zCoverageData._debug_dataioc                 C  sN   | j rdt  d| _dS | j| _t| j}|r%|  jd| 7  _dS dS )z.Set self._filename based on inited attributes.zfile:coverage-z?mode=memory&cache=shared.N)rK   uuiduuid4	_filenamerO   filename_suffixrP   )r   rC   r)   r)   r*   rR     s   
zCoverageData._choose_filenamec                 C  s$   | j s|   i | _d| _d| _dS )zReset our attributes.FN)rK   closerS   rY   r]   r4   r)   r)   r*   _reset$  s
   
zCoverageData._resetforcec                 C  sL   | j dr| j d| d| j  | j D ]}|j|d qi | _dS )z&Really close all the database objects.rb   zClosing dbs, force=: )rm   N)r#   r$   r%   rT   valuesrk   )r   rm   dbr)   r)   r*   rk   ,  s
   
zCoverageData.closec                 C  s6   |  d| j t| j| j| j| jt < |   dS )z0Open an existing db file, and read its metadata.zOpening data fileN)	re   ri   r   r#   rK   rT   rW   	get_ident_read_dbr4   r)   r)   r*   _open_db4  s   zCoverageData._open_dbc                 C  sD  | j t  }z|d}|dusJ W n( ty= } zdt|v r)| | n
td| j	||W Y d}~nd}~ww |d }|t
krPtd| j	|t
|d}|durgtt|d | _| j | _|d}|D ]	\}}|| j|< qoW d   n1 sw   Y  W d   dS W d   dS 1 sw   Y  dS )	zARead the metadata from a database so that we are ready to use it.z#select version from coverage_schemaNzno such table: coverage_schemaz:Data file {!r} doesn't seem to be a coverage data file: {}r   z;Couldn't use data file {!r}: wrong schema: {} instead of {}z-select value from meta where key = 'has_arcs'zselect id, path from file)rT   rW   rq   execute_one	Exceptionr`   _init_dbr   formatri   SCHEMA_VERSIONrF   intr[   rZ   executerS   )r   rp   rowexcschema_versioncurfile_idrM   r)   r)   r*   rr   :  sN   


"zCoverageData._read_dbrp   r   c                 C  sz   |  d| j |t |dtf dtfg}| jdr5|	dt
ttddfdtj d	fg |d
| dS )z+Write the initial contents of the database.zIniting data filez0INSERT INTO coverage_schema (version) VALUES (?)versionprocesssys_argvargvNwhenz%Y-%m-%d %H:%M:%S5INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?))re   ri   executescriptSCHEMAexecute_voidrx   r   r#   r$   extendr`   getattrsysdatetimenowstrftimeexecutemany_void)r   rp   	meta_datar)   r)   r*   rv   ^  s   
zCoverageData._init_dbc                 C  s$   t  | jvr|   | jt   S )zGet the SqliteDb object to use.)rW   rq   rT   rs   r4   r)   r)   r*   _connectr  s   zCoverageData._connectc              	   C  s   t  | jvrtj| jsdS z<|  -}|d}t	t
|W  d    W  d    W S 1 s4w   Y  W d    W d S 1 sEw   Y  W d S  tyV   Y dS w )NFzSELECT * FROM file LIMIT 1)rW   rq   rT   rL   rM   existsri   r   rz   rF   listr   )r   conr~   r)   r)   r*   __bool__x  s   

&zCoverageData.__bool__r7   c                 C  sV   |  d| j |  }| }dt|d W  d   S 1 s$w   Y  dS )a  Serialize the current data to a byte string.

        The format of the serialized data is not documented. It is only
        suitable for use with :meth:`loads` in the same version of
        coverage.py.

        Note that this serialization is not what gets stored in coverage data
        files.  This method is meant to produce bytes that can be transmitted
        elsewhere and then deserialized with :meth:`loads`.

        Returns:
            A byte string of serialized data.

        .. versionadded:: 5.0

        zDumping data from data file   zutf-8N)re   ri   r   dumpzlibcompressencode)r   r   scriptr)   r)   r*   dumps  s
   
$zCoverageData.dumpsdatac                 C  s   |  d| j |dd dkr td|dd dt| dt|dd d	}t| j| j| j	 | j
t < }| || W d   n1 sNw   Y  |   d
| _dS )a  Deserialize data from :meth:`dumps`.

        Use with a newly-created empty :class:`CoverageData` object.  It's
        undefined what happens if the object already has data in it.

        Note that this is not for reading data from a coverage data file.  It
        is only for use on data you produced with :meth:`dumps`.

        Arguments:
            data: A byte string of serialized data produced by :meth:`dumps`.

        .. versionadded:: 5.0

        zLoading data into data fileN   r   zUnrecognized serialization: (   z
 (head of z bytes)r   T)re   ri   r   lenr   
decompressdecoder   r#   rK   rT   rW   rq   r   rr   rY   )r   r   r   rp   r)   r)   r*   loads  s    
zCoverageData.loadsadd
int | Nonec                 C  sV   || j vr%|r%|  }|d|f| j |< W d   n1 s w   Y  | j |S )zGet the file id for `filename`.

        If filename is not in the database yet, add it if `add` is True.
        If `add` is not True, return None.
        z-INSERT OR REPLACE INTO file (path) VALUES (?)N)rS   r   execute_for_rowidget)r   ra   r   r   r)   r)   r*   _file_id  s   

zCoverageData._file_idcontextc                 C  sv   |dusJ |    |  #}|d|f}|dur(tt|d W  d   S 	 W d   dS 1 s4w   Y  dS )zGet the id for a context.N(SELECT id FROM context WHERE context = ?r   )_start_usingr   rt   r   ry   )r   r   r   r{   r)   r)   r*   _context_id  s   
$zCoverageData._context_id
str | Nonec                 C  s.   | j dr| j d| || _d| _dS )zSet the current context for future :meth:`add_lines` etc.

        `context` is a str, the name of the context to use for the next data
        additions.  The context persists until the next :meth:`set_context`.

        .. versionadded:: 5.0

        dataopzSetting coverage context: N)r#   r$   r%   r\   r]   )r   r   r)   r)   r*   set_context  s   

zCoverageData.set_contextc                 C  sd   | j pd}| |}|dur|| _dS |  }|d|f| _W d   dS 1 s+w   Y  dS )z4Use the _current_context to set _current_context_id. Nz(INSERT INTO context (context) VALUES (?))r\   r   r]   r   r   )r   r   
context_idr   r)   r)   r*   _set_context_id  s   



"zCoverageData._set_context_idc                 C  r:   )zLThe base filename for storing data.

        .. versionadded:: 5.0

        )rO   r4   r)   r)   r*   base_filename     zCoverageData.base_filenamec                 C  r:   )zBWhere is the data stored?

        .. versionadded:: 5.0

        )ri   r4   r)   r)   r*   data_filename  r   zCoverageData.data_filename	line_data!Mapping[str, Collection[TLineNo]]c           
   
   C  sR  | j dr8| j dt|tdd | D f  | j dr8t| D ]\}}| j d| d|  q'|   | j	dd	 |sFd
S | 
 U}|   | D ]C\}}t|}| j|dd}d}|||| jf}t|}	W d
   n1 s|w   Y  |	rt||	d d }|d|| j|f qSW d
   d
S 1 sw   Y  d
S )zAdd measured line data.

        `line_data` is a dictionary mapping file names to iterables of ints::

            { filename: { line1, line2, ... }, ...}

        r   z&Adding lines: %d files, %d lines totalc                 s      | ]}t |V  qd S Nr   ).0linesr)   r)   r*   	<genexpr>      z)CoverageData.add_lines.<locals>.<genexpr>dataop2  rn   Tr   Nr   zBSELECT numbits FROM line_bits WHERE file_id = ? AND context_id = ?r   z
                    INSERT OR REPLACE INTO line_bits
                    (file_id, context_id, numbits) VALUES (?, ?, ?)
                    )r#   r$   r%   r   sumro   sorteditemsr   _choose_lines_or_arcsr   r   r   r   rz   r]   r   r   r   )
r   r   ra   linenosr   	line_bitsr   queryr~   existingr)   r)   r*   	add_lines  s@   	


"zCoverageData.add_linesarc_dataMapping[str, Collection[TArc]]c                   s  j dr8j dt|tdd | D f  j dr8t| D ]\}}j d| d|  q'  j	dd	 |sFd
S 
 0}  | D ]\}}|sZqSj|dd  fdd|D }|d| qSW d
   d
S 1 s}w   Y  d
S )zAdd measured arc data.

        `arc_data` is a dictionary mapping file names to iterables of pairs of
        ints::

            { filename: { (l1,l2), (l1,l2), ... }, ...}

        r   z$Adding arcs: %d files, %d arcs totalc                 s  r   r   r   )r   arcsr)   r)   r*   r   3  r   z(CoverageData.add_arcs.<locals>.<genexpr>r   r   rn   Tr   Nr   c                   s   g | ]\}} j ||fqS r)   )r]   )r   fromnotonor   r   r)   r*   
<listcomp>C  s    z)CoverageData.add_arcs.<locals>.<listcomp>z
                    INSERT OR IGNORE INTO arc
                    (file_id, context_id, fromno, tono) VALUES (?, ?, ?, ?)
                    )r#   r$   r%   r   r   ro   r   r   r   r   r   r   r   r   )r   r   ra   r   r   r   r)   r   r*   add_arcs$  s8   

"zCoverageData.add_arcsr   r   c                 C  s   |s|sJ |r|rJ |r!| j r!| jdr| jd td|r6| jr6| jdr2| jd td| j se| jsg|| _|| _ |  }|ddtt	|f W d   dS 1 s^w   Y  dS dS dS )	z5Force the data file to choose between lines and arcs.r   z:Error: Can't add line measurements to existing branch dataz3Can't add line measurements to existing branch dataz:Error: Can't add branch measurements to existing line dataz3Can't add branch measurements to existing line datar   has_arcsN)
r[   r#   r$   r%   r   rZ   r   r   r`   ry   )r   r   r   r   r)   r)   r*   r   L  s(   


"z"CoverageData._choose_lines_or_arcsfile_tracersMapping[str, str]c                 C  s   | j dr| j dt| d |sdS |   |  8}| D ]*\}}| j|dd}| |}|rC||krBt	d
|||q#|rM|d||f q#W d   dS 1 sYw   Y  dS )	zdAdd per-file plugin information.

        `file_tracers` is { filename: plugin_name, ... }

        r   zAdding file tracers: z filesNTr   3Conflicting file tracer name for '{}': {!r} vs {!r}z2INSERT INTO TRACER (file_id, tracer) VALUES (?, ?))r#   r$   r%   r   r   r   r   r   file_tracerr   rw   r   )r   r   r   ra   plugin_namer   existing_pluginr)   r)   r*   add_file_tracersa  s6   

"zCoverageData.add_file_tracersr   r   c                 C  s   |  |g| dS )zEnsure that `filename` appears in the data, empty if needed.

        `plugin_name` is the name of the plugin responsible for this file.
        It is used to associate the right filereporter, etc.
        N)touch_files)r   ra   r   r)   r)   r*   
touch_file  s   zCoverageData.touch_file	filenamesCollection[str]c                 C  s   | j dr| j d| |   |  ( | js"| js"td|D ]}| j|dd |r6| 	||i q$W d   dS 1 sBw   Y  dS )zEnsure that `filenames` appear in the data, empty if needed.

        `plugin_name` is the name of the plugin responsible for these files.
        It is used to associate the right filereporter, etc.
        r   z	Touching z*Can't touch files in an empty CoverageDataTr   N)
r#   r$   r%   r   r   r[   rZ   r   r   r   )r   r   r   ra   r)   r)   r*   r     s   
"zCoverageData.touch_filesc                 C  s   | j dr| j d| |   |  1}| jrd}n
| jr$d}ntd|D ]}| j|dd}|du r8q*|	||f q*W d   dS 1 sKw   Y  dS )	zdPurge any existing coverage data for the given `filenames`.

        .. versionadded:: 7.2

        r   zPurging data for z%DELETE FROM line_bits WHERE file_id=?zDELETE FROM arc WHERE file_id=?z*Can't purge files in an empty CoverageDataFr   N)
r#   r$   r%   r   r   rZ   r[   r   r   r   )r   r   r   sqlra   r   r)   r)   r*   purge_files  s    
"zCoverageData.purge_files
other_datamap_pathCallable[[str], str] | Nonec              	   C  sr  | j dr| j dt|dd | jr|jrtddd| jr+|jr+tddd|p0d	d
 }|   |	  |
  W d   n1 sHw   Y  | 
 }|jdusYJ d|j_|jddt |jdd| |jddt |d| f |d |d}t|}|r|d \}}}td|||W d   n1 sw   Y  |d |d |d}| jdd |D  W d   n1 sw   Y  |d}| \}	}
W d   n1 sw   Y  |	r| jdd |d |d  |
r| jdd! |d" |d# W d   n	1 s$w   Y  | js7|   | 	  dS dS )$a  Update this data with data from another :class:`CoverageData`.

        If `map_path` is provided, it's a function that re-map paths to match
        the local machine's.  Note: `map_path` is None only when called
        directly from the test suite.

        r   zUpdating with data from {!r}ri   z???z6Can't combine branch coverage data with statement datazcant-combine)slugz6Can't combine statement coverage data with branch datac                 S  s   | S r   r)   )pr)   r)   r*   <lambda>  s    z%CoverageData.update.<locals>.<lambda>N	IMMEDIATEr      r   r   numbits_union_aggzATTACH DATABASE ? AS other_dbz
                CREATE TEMP TABLE other_file_mapped AS
                SELECT
                    other_file.id as other_file_id,
                    map_path(other_file.path) as mapped_path
                FROM other_db.file AS other_file
            aH  
                SELECT other_file_mapped.mapped_path,
                       COALESCE(main.tracer.tracer, ''),
                       COALESCE(other_db.tracer.tracer, '')
                FROM main.file
                LEFT JOIN main.tracer ON main.file.id = main.tracer.file_id
                INNER JOIN other_file_mapped ON main.file.path = other_file_mapped.mapped_path
                LEFT JOIN other_db.tracer ON other_file_mapped.other_file_id = other_db.tracer.file_id
                WHERE COALESCE(main.tracer.tracer, '') != COALESCE(other_db.tracer.tracer, '')
            r   r   z
                INSERT OR IGNORE INTO main.file (path)
                SELECT DISTINCT mapped_path FROM other_file_mapped
            z
                INSERT OR IGNORE INTO main.context (context)
                SELECT context FROM other_db.context
            zSELECT id, path FROM filec                 S  s   i | ]\}}||qS r)   r)   )r   idrM   r)   r)   r*   
<dictcomp>  s    z'CoverageData.update.<locals>.<dictcomp>z
                SELECT
                    EXISTS(SELECT 1 FROM other_db.arc),
                    EXISTS(SELECT 1 FROM other_db.line_bits)
            Tr   au  
                    CREATE TEMP TABLE context_mapping AS
                    SELECT
                        other_context.id as other_id,
                        main_context.id as main_id
                    FROM other_db.context AS other_context
                    INNER JOIN main.context AS main_context ON other_context.context = main_context.context
                a  
                    INSERT OR IGNORE INTO main.arc (file_id, context_id, fromno, tono)
                    SELECT
                        main_file.id,
                        context_mapping.main_id,
                        other_arc.fromno,
                        other_arc.tono
                    FROM other_db.arc AS other_arc
                    INNER JOIN other_file_mapped ON other_arc.file_id = other_file_mapped.other_file_id
                    INNER JOIN context_mapping ON other_arc.context_id = context_mapping.other_id
                    INNER JOIN main.file AS main_file ON other_file_mapped.mapped_path = main_file.path
                r   a  
                    INSERT OR REPLACE INTO main.line_bits (file_id, context_id, numbits)
                    SELECT
                        main_file.id,
                        main_context.id,
                        numbits_union(
                            COALESCE((
                                SELECT numbits FROM main.line_bits
                                WHERE file_id = main_file.id AND context_id = main_context.id
                            ), X''),
                            aggregated.combined_numbits
                        )
                    FROM (
                        SELECT
                            other_file_mapped.mapped_path,
                            other_context.context,
                            numbits_union_agg(other_line_bits.numbits) as combined_numbits
                        FROM other_db.line_bits AS other_line_bits
                        INNER JOIN other_file_mapped ON other_line_bits.file_id = other_file_mapped.other_file_id
                        INNER JOIN other_db.context AS other_context ON other_line_bits.context_id = other_context.id
                        GROUP BY other_file_mapped.mapped_path, other_context.context
                    ) AS aggregated
                    INNER JOIN main.file AS main_file ON aggregated.mapped_path = main_file.path
                    INNER JOIN main.context AS main_context ON aggregated.context = main_context.context
                a  
                INSERT OR IGNORE INTO main.tracer (file_id, tracer)
                SELECT
                    main_file.id,
                    other_tracer.tracer
                FROM other_db.tracer AS other_tracer
                INNER JOIN other_file_mapped ON other_tracer.file_id = other_file_mapped.other_file_id
                INNER JOIN main.file AS main_file ON other_file_mapped.mapped_path = main_file.path
            )r#   r$   r%   rw   r   rZ   r[   r   r   readr   r   isolation_levelcreate_functionr   create_aggregater/   r   r   rz   r   rS   updatefetchoner   rK   rl   )r   r   r   r   r~   	conflictsrM   this_tracerother_tracerr   	has_linesr)   r)   r*   r     s   




		




	
  zCoverageData.updateparallelc                 C  s   |    | jr	dS | d| j t| j |rDtj| j\}}tjtj	||}t
|d }t

|D ]}| d| t| q7dS dS )zErase the data in this object.

        If `parallel` is true, then also deletes data files created from the
        basename by parallel-mode.

        NzErasing data filez.*zErasing parallel data file)rl   rK   re   ri   r   rL   rM   splitjoinrN   globescape)r   r   data_dirlocallocal_abs_pathpatternra   r)   r)   r*   eraseh  s   

zCoverageData.erasec                 C  sF   t j| jr!|   d| _W d   dS 1 sw   Y  dS dS )z"Start using an existing data file.TN)rL   rM   r   ri   r   rY   r4   r)   r)   r*   r   |  s
   
"zCoverageData.readc                 C  s   |  d| j dS )z,Ensure the data is written to the data file.zWriting (no-op) data fileN)re   ri   r4   r)   r)   r*   r%     r9   zCoverageData.writec                 C  s@   | j t kr|   |   t | _ | js|   d| _dS )z+Call this before using the database at all.TN)rV   rL   rU   rl   rR   rY   r  r4   r)   r)   r*   r     s   

zCoverageData._start_usingc                 C  
   t | jS )z4Does the database have arcs (True) or lines (False).)rF   r[   r4   r)   r)   r*   r     s   
zCoverageData.has_arcsset[str]c                 C  r  )zA set of all files that have been measured.

        Note that a file may be mentioned as measured even though no lines or
        arcs for that file are present in the data.

        )setrS   r4   r)   r)   r*   measured_files  s   
zCoverageData.measured_filesc              	   C  s~   |    |  -}|d}dd |D }W d   n1 s w   Y  W d   |S W d   |S 1 s8w   Y  |S )zWA set of all contexts that have been measured.

        .. versionadded:: 5.0

        z%SELECT DISTINCT(context) FROM contextc                 S  s   h | ]}|d  qS r   r)   r   r{   r)   r)   r*   	<setcomp>      z1CoverageData.measured_contexts.<locals>.<setcomp>N)r   r   rz   )r   r   r~   contextsr)   r)   r*   measured_contexts  s   


zCoverageData.measured_contextsc                 C  s   |    |  4}| |}|du r	 W d   dS |d|f}|dur3|d p+dW  d   S 	 W d   dS 1 s?w   Y  dS )a  Get the plugin name of the file tracer for a file.

        Returns the name of the plugin that handles this file.  If the file was
        measured, but didn't use a plugin, then "" is returned.  If the file
        was not measured, then None is returned.

        Nz+SELECT tracer FROM tracer WHERE file_id = ?r   r   )r   r   r   rt   )r   ra   r   r   r{   r)   r)   r*   r     s   


$zCoverageData.file_tracerc              	   C  s   |    |  2}|d|f}dd | D | _W d   n1 s%w   Y  W d   dS W d   dS 1 s=w   Y  dS )ad  Set a context for subsequent querying.

        The next :meth:`lines`, :meth:`arcs`, or :meth:`contexts_by_lineno`
        calls will be limited to only one context.  `context` is a string which
        must match a context exactly.  If it does not, no exception is raised,
        but queries will return no data.

        .. versionadded:: 5.0

        r   c                 S     g | ]}|d  qS r  r)   r  r)   r)   r*   r     r
  z2CoverageData.set_query_context.<locals>.<listcomp>N)r   r   rz   fetchallr^   )r   r   r   r~   r)   r)   r*   set_query_context  s   
"zCoverageData.set_query_contextr  Sequence[str] | Nonec              	   C  s   |    |rQ|  =}ddgt| }|d| |}dd | D | _W d   n1 s2w   Y  W d   dS W d   dS 1 sJw   Y  dS d| _dS )a  Set a number of contexts for subsequent querying.

        The next :meth:`lines`, :meth:`arcs`, or :meth:`contexts_by_lineno`
        calls will be limited to the specified contexts.  `contexts` is a list
        of Python regular expressions.  Contexts will be matched using
        :func:`re.search <python:re.search>`.  Data will be included in query
        results if they are part of any of the contexts matched.

        .. versionadded:: 5.0

        z or zcontext REGEXP ?zSELECT id FROM context WHERE c                 S  r  r  r)   r  r)   r)   r*   r     r
  z3CoverageData.set_query_contexts.<locals>.<listcomp>N)r   r   r   r   rz   r  r^   )r   r  r   context_clauser~   r)   r)   r*   set_query_contexts  s   
"
zCoverageData.set_query_contextslist[TLineNo] | Nonec              	   C  s0  |    |  r | |}|dur tj|}tdd |D S |  j}| |}|du r7	 W d   dS d}|g}| j	durXd
dt| j	 }|d| d 7 }|| j	7 }|||}	t|	}
W d   n1 smw   Y  t }|
D ]}|t|d	  qwt|W  d   S 1 sw   Y  dS )
aj  Get the list of lines executed for a source file.

        If the file was not measured, returns None.  A file might be measured,
        and have no lines executed, in which case an empty list is returned.

        If the file was executed, returns a list of integers, the line numbers
        executed in the file. The list is in no particular order.

        Nc                 S  s   h | ]}|d kr|qS r  r)   )r   lr)   r)   r*   r	    s    z%CoverageData.lines.<locals>.<setcomp>z/SELECT numbits FROM line_bits WHERE file_id = ?, ? AND context_id IN (rd   r   )r   r   r   	itertoolschainfrom_iterabler   r   r   r^   r   r   rz   r  r   r   )r   ra   r   	all_linesr   r   r   r   	ids_arrayr~   bitmapsnumsr{   r)   r)   r*   r     s2   






$zCoverageData.lineslist[TArc] | Nonec              	   C  s   |    |  ]}| |}|du r	 W d   dS d}|g}| jdur<ddt| j }|d| d 7 }|| j7 }|||}t|W  d   W  d   S 1 sXw   Y  W d   dS 1 shw   Y  dS )a  Get the list of arcs executed for a file.

        If the file was not measured, returns None.  A file might be measured,
        and have no arcs executed, in which case an empty list is returned.

        If the file was executed, returns a list of 2-tuples of integers. Each
        pair is a starting line number and an ending line number for a
        transition from one line to another. The list is in no particular
        order.

        Negative numbers have special meaning.  If the starting line number is
        -N, it represents an entry to the code object that starts at line N.
        If the ending ling number is -N, it's an exit from the code object that
        starts at line N.

        Nz7SELECT DISTINCT fromno, tono FROM arc WHERE file_id = ?r  r  r  rd   )r   r   r   r^   r   r   rz   r   )r   ra   r   r   r   r   r  r~   r)   r)   r*   r     s$   



"zCoverageData.arcsdict[TLineNo, list[str]]c              	   C  s  |    |  }| |}|du ri W  d   S tt}|  rzd}|g}| jdurEddt	| j }|d| d 7 }|| j7 }|
||&}|D ]\}	}
}|	dkr^||	 | |
dkri||
 | qNW d   n1 stw   Y  nLd}|g}| jdurddt	| j }|d	| d 7 }|| j7 }|
||}|D ]\}}t|D ]	}|| | qqW d   n1 sw   Y  W d   n1 sw   Y  d
d | D S )zGet the contexts for each line in a file.

        Returns:
            A dict mapping line numbers to a list of context names.

        .. versionadded:: 5.0

        Nz
                    SELECT arc.fromno, arc.tono, context.context
                    FROM arc, context
                    WHERE arc.file_id = ? AND arc.context_id = context.id
                r  r  z AND arc.context_id IN (rd   r   z
                    SELECT l.numbits, c.context FROM line_bits l, context c
                    WHERE l.context_id = c.id
                    AND file_id = ?
                z AND l.context_id IN (c                 S  s   i | ]	\}}|t |qS r)   )r   )r   linenor  r)   r)   r*   r   U  s    z3CoverageData.contexts_by_lineno.<locals>.<dictcomp>)r   r   r   collectionsdefaultdictr  r   r^   r   r   rz   r   r   r   )r   ra   r   r   lineno_contexts_mapr   r   r  r~   r   r   r   numbitsr!  r)   r)   r*   contexts_by_lineno$  sP   	






'zCoverageData.contexts_by_linenolist[tuple[str, Any]]c              	   C  s   t dt dJ}|d}dd |D }W d   n1 sw   Y  |d}dd |D }W d   n1 s;w   Y  tjd	|d
d}W d   n1 sTw   Y  dtjfd|fd|fgS )zaOur information for `Coverage.sys_info`.

        Returns a list of (key, value) pairs.

        z:memory:)rI   zPRAGMA temp_storec                 S  r  r  r)   r  r)   r)   r*   r   `  r
  z)CoverageData.sys_info.<locals>.<listcomp>NzPRAGMA compile_optionsc                 S  r  r  r)   r  r)   r)   r*   r   b  r
  r  K   )widthsqlite3_sqlite_versionsqlite3_temp_storesqlite3_compile_options)r   r	   rz   textwrapwrapr   sqlite3sqlite_version)clsrp   r~   
temp_storecoptsr)   r)   r*   sys_infoW  s   zCoverageData.sys_info)NNFNN)rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   r   r0   )r_   r`   ra   r`   r   r0   r<   )F)rm   rF   r   r0   )rp   r   r   r0   )r   r   )r   rF   r=   )r   r7   r   r0   )ra   r`   r   rF   r   r   )r   r`   r   r   )r   r   r   r0   )r   r`   )r   r   r   r0   )r   r   r   r0   )FF)r   rF   r   rF   r   r0   )r   r   r   r0   )r   )ra   r`   r   r`   r   r0   r   )r   r   r   r   r   r0   )r   r   r   r0   )r   r   r   r   r   r0   )r   rF   r   r0   )r   r  )ra   r`   r   r   )r   r`   r   r0   )r  r  r   r0   )ra   r`   r   r  )ra   r`   r   r  )ra   r`   r   r   )r   r'  )0r'   r>   r?   r@   r5   r
   __repr__re   rR   rl   rk   rs   rr   rv   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  r   r  r  r   r   r&  classmethodr4  r)   r)   r)   r*   r      sn    V/






$








*'
 7





	




#
 3r   rC   rD   r   c                   st   | du r2t td tjtj d fddtdD }t	
  dt  d| d	} | S | d
u r8d} | S )zCompute a filename suffix for a data file.

    If `suffix` is a string or None, simply return it. If `suffix` is True,
    then build a suffix incorporating the hostname, process id, and a random
    number.

    Returns a string or None.

    T   r   c                 3  s    | ]}  V  qd S r   )choice)r   _dielettersr)   r*   r   }  s    z"filename_suffix.<locals>.<genexpr>   rf   z.XxFN)randomRandomrL   urandomstringascii_uppercaseascii_lowercaser   rangesocketgethostnamerU   )rC   rollsr)   r:  r*   rj   l  s   
rj   )r   r   r   r   )rC   rD   r   r   )9r@   
__future__r   r"  r   r,   r   r  rL   r?  rF  r/  rB  r   r-  rW   rg   r   collections.abcr   r   r   typingr   r   r   coverage.debugr	   r
   r   coverage.exceptionsr   r   coverage.miscr   r   coverage.numbitsr   r   r   coverage.sqlitedbr   coverage.typesr   r   r   r   r   r   coverage.versionr   rx   r   r.   r/   r   rj   r)   r)   r)   r*   <module>   sP    
?       d