o
    QDiL2                     @  s   d dl mZ d dlmZmZmZmZmZmZ d dl	Z	d dl
m
Z
 ddlmZmZmZ ddlmZ ddlmZ dd	lmZ d
dlmZ d
dlmZ d
dlmZ e	jdddG dd deedZdS )    )annotations)AnyClassVarDictListOptionalUnionN)tabulate   )errorssettingstypes)FrictionlessException)Metadata)platform   )FactoryField)INotesTF)kw_onlyreprc                      s  e Zd ZU dZejdddZded< 	 dZded< 	 dZ	d	ed
< 	 dZ
ded< 	 dZded< 	 ejedZded< 	 ejejjdZded< 	 ejedZded< 	 ejedZded< 	  fddZdd ZedjddZedjddZdddkd$d%Zdld(d)Zdmd*d+Zdnd-d.Zdod/d0Zdpd2d3Zdmd4d5Zdqd6d7Z d8d9 Z!e"drdsd>d?Z#dtdBdCZ$dDdE Z%g dFdudHdIZ&dJdK Z'dd
gfdvdMdNZ(e)dwdQdRZ*dxdTdUZ+dydVdWZ,dXZ-e.j/Z0dYdgdZej1d[dZej2d[d
dZid
dZid
d\id\d
dZid]d\d
dZid]d\dYd\d
dZid]dYd^dgd
dZid\d
dZid]d_d`dadbd]dcd`Z3e)dzdddeZ4e)d{ fdfdgZ5e)d{ fdhdiZ6  Z7S )|Schemaa  Schema representation

    This class is one of the cornerstones of of Frictionless framework.
    It allow to work with Table Schema and its fields.

    ```python
    schema = Schema('schema.json')
    schema.add_fied(Field(name='name', type='string'))
    ```
    NF)defaultr   z'Optional[Union[types.IDescriptor, str]]
descriptorzOptional[str]namezClassVar[Union[str, None]]typetitledescription)factoryzList[Field]fields	List[str]missing_valuesprimary_keyzList[Dict[str, Any]]foreign_keysc                   s    | j D ]}| |_qt   d S N)r    schemasuper__attrs_post_init__)selffield	__class__ S/var/www/Datamplify/venv/lib/python3.10/site-packages/frictionless/schema/schema.pyr(   Q   s   
zSchema.__attrs_post_init__c                 C  s   t | jp
t |  S r%   )boolr    to_descriptorr)   r-   r-   r.   __bool__V   s   zSchema.__bool__returnc                 C     dd | j D S )zList of field namesc                 S  s   g | ]
}|j d ur|j qS r%   )r   .0r*   r-   r-   r.   
<listcomp>_   s    z&Schema.field_names.<locals>.<listcomp>r    r1   r-   r-   r.   field_names[   s   zSchema.field_namesc                 C  r4   )zList of field typesc                 S  s   g | ]}|j qS r-   )r   r5   r-   r-   r.   r7   d   s    z&Schema.field_types.<locals>.<listcomp>r8   r1   r-   r-   r.   field_typesa   s   zSchema.field_types)positionr*   r   r;   Optional[int]Nonec                C  s4   | |_ |du r| j| dS | j|d | dS )zAdd new field to the schemaNr   )r&   r    appendinsert)r)   r*   r;   r-   r-   r.   	add_fieldf   s   zSchema.add_fieldstrr/   c                 C  s    | j D ]
}|j|kr dS qdS )zCheck if a field is presentTF)r    r   r)   r   r*   r-   r-   r.   	has_fieldn   s
   

zSchema.has_fieldc                 C  s:   | j D ]}|j|kr|  S qtjd| dd}t|)zGet field by namezfield "z" does not existnote)r    r   r   SchemaErrorr   )r)   r   r*   errorr-   r-   r.   	get_fieldu   s   

zSchema.get_fieldOptional[Field]c                 C  sP   |j sJ | |j r!| |j }| j|}|| j|< | |_|S | | dS )zSet field by nameN)r   rC   rH   r    indexr&   r@   )r)   r*   
prev_fieldrJ   r-   r-   r.   	set_field}   s   

zSchema.set_fieldc                 C  s   |  |d|iS )zSet field typer   )update_field)r)   r   r   r-   r-   r.   set_field_type   s   zSchema.set_field_typetypes.IDescriptorc                 C  sF   |  |}| j|}| }|| t|}| |_|| j|< |S )zUpdate field)rH   r    rJ   r0   updater   from_descriptorr&   )r)   r   r   rK   field_indexfield_descriptor	new_fieldr-   r-   r.   rM      s   



zSchema.update_fieldc                 C  s   |  |}| j| |S )zRemove field by name)rH   r    removerB   r-   r-   r.   remove_field   s   
zSchema.remove_fieldc                 C  s
   g | _ dS )zRemove all the fieldsNr8   r1   r-   r-   r.   clear_fields   s   
zSchema.clear_fieldsc                 C  sl   t | jt t| jkr2g }t| jD ] \}}||d }|dkr,d||f | j| _|| qd S d S )Nr   z%s%s)lenr9   set	enumeratecountr    r   r>   )r)   
seen_namesrJ   r   r[   r-   r-   r.   deduplicate_fields   s   zSchema.deduplicate_fieldssourceOptional[Any]optionsr   c                 K  s0   t jj}|j| fddi|}t|tsJ |S )zDescribe the given source as a schema

        Parameters:
            source (any): data source
            **options (dict): describe resource options

        Returns:
            Schema: table schema
        r   r&   )r   frictionlessResourcedescribe
isinstancer   )r^   r`   rb   metadatar-   r-   r.   rc      s   zSchema.describecells	List[Any]c           	      C  sf   g }g }|   }t| D ] \}}t||kr|| nd}||\}}|| || q||fS )zRead a list of cells (normalize/cast)

        Parameters:
            cells (any[]): list of cells

        Returns:
            any[]: list of processed cells
        N)create_cell_readersrZ   valuesrX   r>   )	r)   rf   	res_cells	res_notesreadersrJ   readercellnotesr-   r-   r.   
read_cells      	
zSchema.read_cellsc                 C  r4   )Nc                 S     i | ]}|j | qS r-   r   create_cell_readerr5   r-   r-   r.   
<dictcomp>       z.Schema.create_cell_readers.<locals>.<dictcomp>r8   r1   r-   r-   r.   rh         zSchema.create_cell_readers)r   r   c          
      C  sf   g }g }|   }t| D ] \}}t||kr|| nd}||\}}	|| ||	 q||fS )zWrite a list of cells (normalize/uncast)

        Parameters:
            cells (any[]): list of cells

        Returns:
            any[]: list of processed cells
        N)create_cell_writersrZ   ri   rX   r>   )
r)   rf   r   rj   rk   writersrJ   writerrn   ro   r-   r-   r.   write_cells   rq   zSchema.write_cellsc                 C  r4   )Nc                 S  rr   r-   rs   r5   r-   r-   r.   ru      rv   z.Schema.create_cell_writers.<locals>.<dictcomp>r8   r1   r-   r-   r.   rx      rw   zSchema.create_cell_writersspecc                   s>   g }| j D ]}i   |  | fdd|D  q|S )zFlatten the schema

        Parameters
            spec (str[]): flatten specification

        Returns:
            any[]: flatten schema
        c                   s   g | ]}  |qS r-   )get)r6   propcontextr-   r.   r7      s    z"Schema.flatten.<locals>.<listcomp>)r    rP   r0   r>   )r)   r|   resultr*   r-   r   r.   flatten   s   	
zSchema.flattenprofileUnion[types.IDescriptor, str]c                 C  s    |  |}tjj }||S )zCreate a Schema from JSONSchema profile

        Parameters:
            profile: path or dict with JSONSchema profile
        )metadata_retriever   frictionless_formats
jsonschemaJsonschemaMapperread_schema)clsr   mapperr-   r-   r.   from_jsonschema  s   

zSchema.from_jsonschemapathc                 C  s   t jj }|j| |dS )zExport schema as an excel template

        Parameters:
            path: path of excel file to create with ".xlsx" extension
        )r   )r   r   excelExcelMapperwrite_schema)r)   r   r   r-   r-   r.   to_excel_template  s   zSchema.to_excel_templatec                 C  s"   dd | j D }t|g dddS )z%Summary of the schema in table formatc                 S  s$   g | ]}|j |j|jrd ndgqS )T r   r   required)r6   fr-   r-   r.   r7     s   $ z%Schema.to_summary.<locals>.<listcomp>r   grid)headerstablefmt)r    r	   )r)   contentr-   r-   r.   
to_summary  s   zSchema.to_summaryr&   objectstring)r   patternarray)r   itemsresource)r   r    )r   r   
properties)r    	reference)r   r   )r   r   r   r   r    missingValues
primaryKeyforeignKeysc                 C  s   |dkrt S d S )Nr    r   )r   r   r-   r-   r.   metadata_select_property_classC  s   z%Schema.metadata_select_property_classc                   s   t  | |d}|rt|ts|g|d< |d}|rg|D ]H}t|ts(q |dg  |di  |d dd |d dg  t|d tsR|d g|d< t|d d tsf|d d g|d d< q d S d S )Nr   r   r    r   r   r   )r'   metadata_transformr}   rd   listdict
setdefault)r   r   r#   r$   fkr+   r-   r.   r   I  s(   



zSchema.metadata_transformc           
      #  sB   t t |}|r|E d H  d S g }|d D ]}d|v r%||d  qt|tt|kr9d}tj|dV  |dg }|D ]}||vrVd}|||f }tj|dV  qA|dg }|D ]?}	|	d D ]}||vrzd}||	|f }tj|dV  qet|	d t|	d	 d krd
}||	d |	d	 d f }tj|dV  q_d S )Nr    r   z"names of the fields are not uniquerD   r   z/primary key "%s" does not match the fields "%s"r   z/foreign key "%s" does not match the fields "%s"r   z@foreign key fields "%s" does not match the reference fields "%s")	r   r'   metadata_validater>   rX   rY   r   rF   r}   )
r   r   metadata_errorsr9   r*   rE   pkr   fksr   r+   r-   r.   r   a  sD   
zSchema.metadata_validate)r3   r!   )r*   r   r;   r<   r3   r=   )r   rA   r3   r/   )r   rA   r3   r   )r*   r   r3   rI   )r   rA   r   rA   r3   r   )r   rA   r   rO   r3   r   )r3   r=   r%   )r^   r_   r`   r   r3   r   )rf   rg   )rf   rg   r   r!   )r|   r!   )r   r   r3   r   )r   rA   r3   r=   )r3   rA   )r   rA   )r   rO   )8__name__
__module____qualname____doc__attrsr*   r   __annotations__r   r   r   r   r   r    r   DEFAULT_MISSING_VALUEScopyr"   r#   r$   r(   r2   propertyr9   r:   r@   rC   rH   rL   rN   rM   rV   rW   r]   staticmethodrc   rp   rh   r{   rx   r   classmethodr   r   r   metadata_typer   rF   metadata_ErrorNAME_PATTERNTYPE_PATTERNmetadata_profiler   r   r   __classcell__r-   r-   r+   r.   r      s   
 










	

%r   )	metaclass)
__future__r   typingr   r   r   r   r   r   r   r	   r   r   r   r   	exceptionr   re   r   r   r   r   r*   r   r   definer   r-   r-   r-   r.   <module>   s     