o
    uyi#M                     @  s  U d dl mZ d dlZ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mZ d dlmZmZmZmZmZmZmZmZmZmZ d dl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$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. d dl/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; d dl<m=Z=m>Z>m?Z? d Z@dZAdeBd< G dd de0ZCG dd de0ZDeDd dZEdSd"d#ZFdTd'd(ZGed)ZHG d*d+ d+eeH eZIG d,d- d-eIeJ ZKed.ZLedUd2d3ZMdVd5d6ZNed7d8G d9d: d:ZOed7d8G d;d< d<ZPdWd@dAZQedXdDdEZReRSe8eRSe9dYdHdIZTeRSe3dZdKdIZTeRSe:d[dMdIZTeRSe;d\dPdIZTeRSe6d]dRdIZTdS )^    )annotationsN)ABCabstractmethod)	dataclass)datedatetimetime)cached_propertysingledispatch)
	AnnotatedAnyDictGenericListOptionalSetTupleTypeVarUnion)
quote_plus)BeforeValidatorFieldPlainSerializerWithJsonSchemamodel_validator)Schema)BucketTransformDayTransformHourTransformIdentityTransformMonthTransform	TransformTruncateTransformUnknownTransformVoidTransformYearTransformparse_transform)IcebergBaseModelRecord)	DateTypeIcebergTypeNestedFieldPrimitiveType
StructTypeTimestampTypeTimestamptzTypeTimeTypeUUIDType)date_to_daysdatetime_to_microstime_to_microsi  intPARTITION_FIELD_ID_STARTc                      s   e Zd ZU dZeddZded< eddZded< e Zded	< e Z	d
ed< 				dd fddZ
eddedddZdddZ  ZS )PartitionFielda  PartitionField represents how one partition value is derived from the source column via transformation.

    Attributes:
        source_id(int): The source column id of table's schema.
        field_id(int): The partition field id across all the table partition specs.
        transform(Transform): The transform used to produce partition values from source column.
        name(str): The name of this partition field.
    	source-id)aliasr5   	source_idfield-idfield_idzAnnotated[Transform, BeforeValidator(parse_transform), PlainSerializer(lambda c: str(c), return_type=str), WithJsonSchema({'type': 'string'}, mode='serialization')]	transformstrnameNOptional[int]Optional[Transform[Any, Any]]Optional[str]datar   c                   sV   |d ur||d< |d ur||d< |d ur||d< |d ur ||d< t  jdi | d S )Nr8   r;   r=   r?    )super__init__)selfr:   r<   r=   r?   rC   	__class__rD   Y/home/ubuntu/maya3_transcribe/venv/lib/python3.10/site-packages/pyiceberg/partitioning.pyrF   W   s   zPartitionField.__init__before)modereturnc                 C  s`   t |tr.d|vr.|d  }r.t |tr.t|dkrtdt|dkr(td|d |d< |S )Nr8   z
source-idsr   zEmpty source-ids is not allowed   z/Multi argument transforms are not yet supported)
isinstancedictlistlen
ValueError)clsrC   
source_idsrD   rD   rJ   map_source_ids_onto_source_idj   s   

z,PartitionField.map_source_ids_onto_source_idc                 C  s$   | j  d| j d| j d| j dS )z=Return the string representation of the PartitionField class.z: ())r<   r?   r=   r:   rG   rD   rD   rJ   __str__w   s   $zPartitionField.__str__)NNNN)
r:   r@   r<   r@   r=   rA   r?   rB   rC   r   )rC   r   rM   r   rM   r>   )__name__
__module____qualname____doc__r   r:   __annotations__r<   r=   r?   rF   r   classmethodrV   rZ   __classcell__rD   rD   rH   rJ   r7   C   s    
 	
r7   c                      s   e Zd ZU dZededZded< eedZ	ded< d- fddZ
d.ddZd/ddZd/ddZd0ddZed1ddZed2ddZd3d!d"Zd4d#d$Zd5d(d)Zd6d+d,Z  ZS )7PartitionSpeca  
    PartitionSpec captures the transformation from table data to partition values.

    Attributes:
        spec_id(int): any change to PartitionSpec will produce a new specId.
        fields(Tuple[PartitionField): list of partition fields to produce partition values.
    zspec-id)r9   defaultr5   spec_id)default_factoryzTuple[PartitionField, ...]fieldsr7   rC   r   c                   s&   |rt ||d< t jdi | d S )Nrg   rD   )tuplerE   rF   )rG   rg   rC   rH   rD   rJ   rF      s   zPartitionSpec.__init__otherrM   boolc                 C  s&   t |tsdS | j|jko| j|jkS )z
        Produce a boolean to return True if two objects are considered equal.

        Note:
            Equality of PartitionSpec is determined by spec_id and partition fields only.
        F)rO   rc   re   rg   rG   ri   rD   rD   rJ   __eq__   s   
zPartitionSpec.__eq__r>   c                 C  s8   d}| j r|dddd | j D  d 7 }|d7 }|S )z
        Produce a human-readable string representation of PartitionSpec.

        Note:
            Only include list of partition fields in the PartitionSpec's string representation.
        [z
  c                 S  s   g | ]}t |qS rD   r>   .0fieldrD   rD   rJ   
<listcomp>   s    z)PartitionSpec.__str__.<locals>.<listcomp>
])rg   join)rG   
result_strrD   rD   rJ   rZ      s
   "zPartitionSpec.__str__c                 C  s:   | j rddd | j D  dnd}d| d| j dS )z<Return the string representation of the PartitionSpec class.z, c                 s  s    | ]}t |V  qd S N)repr)rp   columnrD   rD   rJ   	<genexpr>   s    z)PartitionSpec.__repr__.<locals>.<genexpr> zPartitionSpec(zspec_id=rX   )rg   ru   re   )rG   rg   rD   rD   rJ   __repr__   s   &zPartitionSpec.__repr__c                 C  s   | j  S rw   rg   rY   rD   rD   rJ   is_unpartitioned      zPartitionSpec.is_unpartitionedc                 C  s"   | j rtdd | j D S td S )Nc                 s  s    | ]}|j V  qd S rw   )r<   )rp   pfrD   rD   rJ   rz      s    z7PartitionSpec.last_assigned_field_id.<locals>.<genexpr>rN   )rg   maxr6   rY   rD   rD   rJ   last_assigned_field_id   s   z$PartitionSpec.last_assigned_field_idDict[int, List[PartitionField]]c                 C  s6   i }| j D ]}||jg }|| |||j< q|S rw   )rg   getr:   append)rG   source_id_to_fields_mappartition_fieldexistingrD   rD   rJ   r      s   

z%PartitionSpec.source_id_to_fields_mapr<   List[PartitionField]c                 C  s   | j |g S rw   )r   r   )rG   r<   rD   rD   rJ   fields_by_source_id      z!PartitionSpec.fields_by_source_idc                 C  s@   | |krdS t | jt |jkrdS tdd t| j|jD S )zPProduce a boolean to return True if two PartitionSpec are considered compatible.TFc                 s  s8    | ]\}}|j |j ko|j|jko|j|jkV  qd S rw   )r:   r=   r?   )rp   
this_field
that_fieldrD   rD   rJ   rz      s    


z0PartitionSpec.compatible_with.<locals>.<genexpr>)rR   rg   allziprk   rD   rD   rJ   compatible_with   s   zPartitionSpec.compatible_withschemar   r-   c              	   C  sX   g }| j D ]"}||j}|j|}||jj}|t|j	|j
||d qt| S )a  Produce a struct of the PartitionSpec.

        The partition fields should be optional:

        - All partition transforms are required to produce null if the input value is null, so it can
          happen when the source column is optional.
        - Partition fields may be added later, in which case not all files would have the result field,
          and it may be null.

        There is a case where we can guarantee that a partition field in the first and only partition spec
        that uses a required source column will never be null, but it doesn't seem worth tracking this case.

        :param schema: The schema to bind to.
        :return: A StructType that represents the PartitionSpec, with a NestedField for each PartitionField.
        )required)rg   	find_typer:   r=   result_type
find_fieldr   r   r+   r<   r?   r-   )rG   r   nested_fieldsrq   source_typer   r   rD   rD   rJ   partition_type   s   
zPartitionSpec.partition_typer(   c                 C  s   |  |}|j}g }g }tt| jD ]'}| j| }|jj|| j|| d}	|t|	dd |t|j	dd qd
dd t||D }
|
S )N)valuer{   )safe/c                 S  s   g | ]
\}}|d  | qS )=rD   )rp   	field_str	value_strrD   rD   rJ   rr      s    z3PartitionSpec.partition_to_path.<locals>.<listcomp>)r   rg   rangerR   r=   to_human_string
field_typer   r   r?   ru   r   )rG   rC   r   r   field_types
field_strs
value_strsposr   r   pathrD   rD   rJ   partition_to_path   s   

zPartitionSpec.partition_to_path)rg   r7   rC   r   )ri   r   rM   rj   r[   )rM   rj   )rM   r5   )rM   r   )r<   r5   rM   r   )ri   rc   rM   rj   )r   r   rM   r-   )rC   r(   r   r   rM   r>   )r\   r]   r^   r_   r   INITIAL_PARTITION_SPEC_IDre   r`   rh   rg   rF   rl   rZ   r|   r~   propertyr   r	   r   r   r   r   r   rb   rD   rD   rH   rJ   rc   |   s"   
 
	





rc   )re   
field_namer>   partition_transformTransform[Any, Any]r:   r   r   partition_namesSet[str]rM   Nonec                 C  s   z| | }W n
 ty   Y dS w t|ttfr&|j|kr%td|  ntd|  | s3td| |v r>td|  dS )zNValidate that a partition field name doesn't conflict with schema field names.NzICannot create identity partition sourced from different field in schema: z;Cannot create partition with a name that exists in schema: zUndefined namez!Partition name has to be unique: )r   rS   rO   r   r$   r<   )r   r   r:   r   r   schema_fieldrD   rD   rJ   validate_partition_name   s   
r   spec
old_schemafresh_schemac              	   C  s   g }t | jD ]A\}}||j}|d u rtd| ||}|d u r,td| t|j|j|j	|t
  |t|j|j	t| |jd qt|dtiS )NzCould not find in old schema: z&Could not find field in fresh schema: )r?   r:   r<   r=   re   )	enumeraterg   find_column_namer:   rS   r   r   r?   r=   r<   setr   r7   r6   rc   r   )r   r   r   partition_fieldsr   rq   original_column_namefresh_fieldrD   rD   rJ   assign_fresh_partition_spec_ids  s$   
r   Tc                   @  s   e Zd Zeddd	ZedddZed ddZedddZedddZedddZ	edddZ
edddZed!ddZdS )"PartitionSpecVisitorr<   r5   source_namer>   r:   rM   r   c                 C     dS )zVisit identity partition field.NrD   rG   r<   r   r:   rD   rD   rJ   identity0      zPartitionSpecVisitor.identitynum_bucketsc                 C  r   )zVisit bucket partition field.NrD   rG   r<   r   r:   r   rD   rD   rJ   bucket4  r   zPartitionSpecVisitor.bucketwidthc                 C  r   )zVisit truncate partition field.NrD   rG   r<   r   r:   r   rD   rD   rJ   truncate8  r   zPartitionSpecVisitor.truncatec                 C  r   )zVisit year partition field.NrD   r   rD   rD   rJ   year<  r   zPartitionSpecVisitor.yearc                 C  r   )zVisit month partition field.NrD   r   rD   rD   rJ   month@  r   zPartitionSpecVisitor.monthc                 C  r   )zVisit day partition field.NrD   r   rD   rD   rJ   dayD  r   zPartitionSpecVisitor.dayc                 C  r   )zVisit hour partition field.NrD   r   rD   rD   rJ   hourH  r   zPartitionSpecVisitor.hourc                 C  r   )zVisit void partition field.NrD   r   rD   rD   rJ   always_nullL  r   z PartitionSpecVisitor.always_nullr=   c                 C  s   t d| )zVisit unknown partition field.z$Unknown transform is not supported: )rS   rG   r<   r   r:   r=   rD   rD   rJ   unknownP  s   zPartitionSpecVisitor.unknownN)r<   r5   r   r>   r:   r5   rM   r   )
r<   r5   r   r>   r:   r5   r   r5   rM   r   )
r<   r5   r   r>   r:   r5   r   r5   rM   r   )
r<   r5   r   r>   r:   r5   r=   r>   rM   r   )r\   r]   r^   r   r   r   r   r   r   r   r   r   r   rD   rD   rD   rJ   r   /  s&    r   c                      sn   e Zd ZdddZdd
dZdddZdddZdddZdddZdddZ	dddZ
d fddZ  ZS ) _PartitionNameGeneratorr<   r5   r   r>   r:   rM   c                 C  s   |S rw   rD   r   rD   rD   rJ   r   W  s   z _PartitionNameGenerator.identityr   c                 C  s   | d| S )N_bucket_rD   r   rD   rD   rJ   r   Z  r   z_PartitionNameGenerator.bucketr   c                 C  s   |d t | S )N_trunc_rn   r   rD   rD   rJ   r   ]  s   z _PartitionNameGenerator.truncatec                 C     |d S )N_yearrD   r   rD   rD   rJ   r   `  r   z_PartitionNameGenerator.yearc                 C  r   )N_monthrD   r   rD   rD   rJ   r   c  r   z_PartitionNameGenerator.monthc                 C  r   )N_dayrD   r   rD   rD   rJ   r   f  r   z_PartitionNameGenerator.dayc                 C  r   )N_hourrD   r   rD   rD   rJ   r   i  r   z_PartitionNameGenerator.hourc                 C  r   )N_nullrD   r   rD   rD   rJ   r   l  r   z#_PartitionNameGenerator.always_nullr=   c                   s   t  ||||S rw   )rE   r   r   rH   rD   rJ   r   o     z_PartitionNameGenerator.unknown)r<   r5   r   r>   r:   r5   rM   r>   )
r<   r5   r   r>   r:   r5   r   r5   rM   r>   )
r<   r5   r   r>   r:   r5   r   r5   rM   r>   )
r<   r5   r   r>   r:   r5   r=   r>   rM   r>   )r\   r]   r^   r   r   r   r   r   r   r   r   r   rb   rD   rD   rH   rJ   r   V  s    







r   RvisitorPartitionSpecVisitor[R]List[R]c                   s    fdd| j D S )Nc                   s   g | ]}t  |qS rD   )_visit_partition_fieldro   r   r   rD   rJ   rr   x  s    z_visit.<locals>.<listcomp>r}   )r   r   r   rD   r   rJ   _visitv  s   r   rq   c                 C  s>  |  |j}|std|j |j}t|tr!||j||jS t|tr1|	|j||j|j
S t|trA||j||j|jS t|trO||j||jS t|tr]||j||jS t|trk||j||jS t|try||j||jS t|tr||j||jS t|tr||j||jt|S td| )NzCould not find field with id zUnknown transform )r   r:   rS   r=   rO   r   r   r<   r   r   r   r"   r   r   r   r   r   r   r    r   r%   r   r$   r   r#   r   rx   )r   rq   r   r   r=   rD   rD   rJ   r   {  s.   








r   T)frozenc                   @  s   e Zd ZU ded< ded< dS )PartitionFieldValuer7   rq   r   r   N)r\   r]   r^   r`   rD   rD   rD   rJ   r     s   
 r   c                   @  s>   e Zd ZU ded< ded< ded< edd	d
ZdddZdS )PartitionKeyzList[PartitionFieldValue]field_valuesrc   partition_specr   r   rM   r(   c                 C  sb   g }| j D ]'}| jj|jj }t|dkrtd| |d }|t||j	| j
d qt| S )NrN   z"Cannot have redundant partitions: r   )r   r   r   )r   r   r   rq   r:   rR   rS   r   partition_record_valuer   r   r(   )rG   iceberg_typed_key_valuesraw_partition_field_valuer   r   rD   rD   rJ   	partition  s   
zPartitionKey.partitionr>   c                 C  s   | j | j| jS rw   )r   r   r   r   rY   rD   rD   rJ   to_path  r   zPartitionKey.to_pathN)rM   r(   r[   )r\   r]   r^   r`   r	   r   r   rD   rD   rD   rJ   r     s   
 r   r   r   r   c                 C  s   |j | jdj}t||S )aP  
    Return the Partition Record representation of the value.

    The value is first converted to internal partition representation.
    For example, UUID is converted to bytes[16], DateType to days since epoch, etc.

    Then the corresponding PartitionField's transform is applied to return
    the final partition record value.
    )
name_or_id)r   r:   r   _to_partition_representation)r   r   r   iceberg_typerD   rD   rJ   r     s   

r   typer*   c                 C  s   t d|  S )ao  Strip the logical type into the physical type.

    It can be that the value is already transformed into its physical type,
    in this case it will return the original value. Keep in mind that the
    bucket transform always will return an int, but an identity transform
    can return date that still needs to be transformed into an int (days
    since epoch).
    z"Unsupported partition field type: )	TypeErrorr   r   rD   rD   rJ   r     s   
r   Optional[Union[int, datetime]]r@   c                 C  :   |d u rd S t |tr|S t |trt|S td| NzType not recognized: )rO   r5   r   r3   rS   r   rD   rD   rJ   _  s   

r   Optional[Union[int, date]]c                 C  r   r   )rO   r5   r   r2   rS   r   rD   rD   rJ   r     s   

Optional[time]c                 C  s   |d urt |S d S rw   )r4   r   rD   rD   rJ   r     s   &Optional[Union[uuid.UUID, int, bytes]]Optional[Union[bytes, int]]c                 C  sH   |d u rd S t |tr|S t |tjr|jS t |tr|S td| r   )rO   bytesuuidUUIDr5   rS   r   rD   rD   rJ   r     s   

Optional[Any]c                 C  s   |S rw   rD   r   rD   rD   rJ   r     s   )r   r>   r   r   r:   r5   r   r   r   r   rM   r   )r   rc   r   r   r   r   rM   rc   )r   rc   r   r   r   r   rM   r   )r   r   rq   r7   r   r   rM   r   )r   r7   r   r   r   r   rM   r   )r   r*   r   r   rM   r   )r   r*   r   r   rM   r@   )r   r*   r   r   rM   r@   )r   r*   r   r   rM   r@   )r   r*   r   r   rM   r   )r   r*   r   r   rM   r   )U
__future__r   r   abcr   r   dataclassesr   r   r   r   	functoolsr	   r
   typingr   r   r   r   r   r   r   r   r   r   urllib.parser   pydanticr   r   r   r   r   pyiceberg.schemar   pyiceberg.transformsr   r   r   r   r    r!   r"   r#   r$   r%   r&   pyiceberg.typedefr'   r(   pyiceberg.typesr)   r*   r+   r,   r-   r.   r/   r0   r1   pyiceberg.utils.datetimer2   r3   r4   r   r6   r`   r7   rc   UNPARTITIONED_PARTITION_SPECr   r   r   r   r>   r   r   r   r   r   r   r   r   registerr   rD   rD   rD   rJ   <module>   s\   04,9
}

'

