-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathfunctions.py
More file actions
2939 lines (2141 loc) · 89 KB
/
functions.py
File metadata and controls
2939 lines (2141 loc) · 89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""User functions for operating on :py:class:`~datafusion.expr.Expr`."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import pyarrow as pa
from datafusion._internal import functions as f
from datafusion.common import NullTreatment
from datafusion.expr import (
CaseBuilder,
Expr,
SortExpr,
SortKey,
WindowFrame,
expr_list_to_raw_expr_list,
sort_list_to_raw_sort_list,
sort_or_default,
)
try:
from warnings import deprecated # Python 3.13+
except ImportError:
from typing_extensions import deprecated # Python 3.12
if TYPE_CHECKING:
from datafusion.context import SessionContext
__all__ = [
"abs",
"acos",
"acosh",
"alias",
"approx_distinct",
"approx_median",
"approx_percentile_cont",
"approx_percentile_cont_with_weight",
"array",
"array_agg",
"array_append",
"array_cat",
"array_concat",
"array_dims",
"array_distinct",
"array_element",
"array_empty",
"array_except",
"array_extract",
"array_has",
"array_has_all",
"array_has_any",
"array_indexof",
"array_intersect",
"array_join",
"array_length",
"array_ndims",
"array_pop_back",
"array_pop_front",
"array_position",
"array_positions",
"array_prepend",
"array_push_back",
"array_push_front",
"array_remove",
"array_remove_all",
"array_remove_n",
"array_repeat",
"array_replace",
"array_replace_all",
"array_replace_n",
"array_resize",
"array_slice",
"array_sort",
"array_to_string",
"array_union",
"arrow_cast",
"arrow_typeof",
"ascii",
"asin",
"asinh",
"atan",
"atan2",
"atanh",
"avg",
"bit_and",
"bit_length",
"bit_or",
"bit_xor",
"bool_and",
"bool_or",
"btrim",
"cardinality",
"case",
"cbrt",
"ceil",
"char_length",
"character_length",
"chr",
"coalesce",
"col",
"concat",
"concat_ws",
"corr",
"cos",
"cosh",
"cot",
"count",
"count_star",
"covar",
"covar_pop",
"covar_samp",
"cume_dist",
"current_date",
"current_time",
"date_bin",
"date_part",
"date_trunc",
"datepart",
"datetrunc",
"decode",
"degrees",
"dense_rank",
"digest",
"empty",
"encode",
"ends_with",
"exp",
"extract",
"factorial",
"find_in_set",
"first_value",
"flatten",
"floor",
"from_unixtime",
"gcd",
"in_list",
"initcap",
"isnan",
"iszero",
"lag",
"last_value",
"lcm",
"lead",
"left",
"length",
"levenshtein",
"list_append",
"list_cat",
"list_concat",
"list_dims",
"list_distinct",
"list_element",
"list_except",
"list_extract",
"list_indexof",
"list_intersect",
"list_join",
"list_length",
"list_ndims",
"list_position",
"list_positions",
"list_prepend",
"list_push_back",
"list_push_front",
"list_remove",
"list_remove_all",
"list_remove_n",
"list_repeat",
"list_replace",
"list_replace_all",
"list_replace_n",
"list_resize",
"list_slice",
"list_sort",
"list_to_string",
"list_union",
"ln",
"log",
"log2",
"log10",
"lower",
"lpad",
"ltrim",
"make_array",
"make_date",
"make_list",
"max",
"md5",
"mean",
"median",
"min",
"named_struct",
"nanvl",
"now",
"nth_value",
"ntile",
"nullif",
"nvl",
"octet_length",
"order_by",
"overlay",
"percent_rank",
"pi",
"pow",
"power",
"radians",
"random",
"range",
"rank",
"regexp_count",
"regexp_instr",
"regexp_like",
"regexp_match",
"regexp_replace",
"regr_avgx",
"regr_avgy",
"regr_count",
"regr_intercept",
"regr_r2",
"regr_slope",
"regr_sxx",
"regr_sxy",
"regr_syy",
"repeat",
"replace",
"reverse",
"right",
"round",
"row_number",
"rpad",
"rtrim",
"sha224",
"sha256",
"sha384",
"sha512",
"signum",
"sin",
"sinh",
"split_part",
"sqrt",
"starts_with",
"stddev",
"stddev_pop",
"stddev_samp",
"string_agg",
"strpos",
"struct",
"substr",
"substr_index",
"substring",
"sum",
"tan",
"tanh",
"to_char",
"to_date",
"to_hex",
"to_local_time",
"to_time",
"to_timestamp",
"to_timestamp_micros",
"to_timestamp_millis",
"to_timestamp_nanos",
"to_timestamp_seconds",
"to_unixtime",
"today",
"translate",
"trim",
"trunc",
"upper",
"uuid",
"var",
"var_pop",
"var_samp",
"var_sample",
"when",
# Window Functions
"window",
]
def isnan(expr: Expr) -> Expr:
"""Returns true if a given number is +NaN or -NaN otherwise returns false."""
return Expr(f.isnan(expr.expr))
def nullif(expr1: Expr, expr2: Expr) -> Expr:
"""Returns NULL if expr1 equals expr2; otherwise it returns expr1.
This can be used to perform the inverse operation of the COALESCE expression.
"""
return Expr(f.nullif(expr1.expr, expr2.expr))
def encode(expr: Expr, encoding: Expr) -> Expr:
"""Encode the ``input``, using the ``encoding``. encoding can be base64 or hex."""
return Expr(f.encode(expr.expr, encoding.expr))
def decode(expr: Expr, encoding: Expr) -> Expr:
"""Decode the ``input``, using the ``encoding``. encoding can be base64 or hex."""
return Expr(f.decode(expr.expr, encoding.expr))
def array_to_string(expr: Expr, delimiter: Expr) -> Expr:
"""Converts each element to its text representation."""
return Expr(f.array_to_string(expr.expr, delimiter.expr.cast(pa.string())))
def array_join(expr: Expr, delimiter: Expr) -> Expr:
"""Converts each element to its text representation.
This is an alias for :py:func:`array_to_string`.
"""
return array_to_string(expr, delimiter)
def list_to_string(expr: Expr, delimiter: Expr) -> Expr:
"""Converts each element to its text representation.
This is an alias for :py:func:`array_to_string`.
"""
return array_to_string(expr, delimiter)
def list_join(expr: Expr, delimiter: Expr) -> Expr:
"""Converts each element to its text representation.
This is an alias for :py:func:`array_to_string`.
"""
return array_to_string(expr, delimiter)
def in_list(arg: Expr, values: list[Expr], negated: bool = False) -> Expr:
"""Returns whether the argument is contained within the list ``values``."""
values = [v.expr for v in values]
return Expr(f.in_list(arg.expr, values, negated))
def digest(value: Expr, method: Expr) -> Expr:
"""Computes the binary hash of an expression using the specified algorithm.
Standard algorithms are md5, sha224, sha256, sha384, sha512, blake2s,
blake2b, and blake3.
"""
return Expr(f.digest(value.expr, method.expr))
def concat(*args: Expr) -> Expr:
"""Concatenates the text representations of all the arguments.
NULL arguments are ignored.
"""
args = [arg.expr for arg in args]
return Expr(f.concat(args))
def concat_ws(separator: str, *args: Expr) -> Expr:
"""Concatenates the list ``args`` with the separator.
``NULL`` arguments are ignored. ``separator`` should not be ``NULL``.
"""
args = [arg.expr for arg in args]
return Expr(f.concat_ws(separator, args))
def order_by(expr: Expr, ascending: bool = True, nulls_first: bool = True) -> SortExpr:
"""Creates a new sort expression."""
return SortExpr(expr, ascending=ascending, nulls_first=nulls_first)
def alias(expr: Expr, name: str, metadata: dict[str, str] | None = None) -> Expr:
"""Creates an alias expression with an optional metadata dictionary.
Args:
expr: The expression to alias
name: The alias name
metadata: Optional metadata to attach to the column
Returns:
An expression with the given alias
"""
return Expr(f.alias(expr.expr, name, metadata))
def col(name: str) -> Expr:
"""Creates a column reference expression."""
return Expr(f.col(name))
def count_star(filter: Expr | None = None) -> Expr:
"""Create a COUNT(1) aggregate expression.
This aggregate function will count all of the rows in the partition.
If using the builder functions described in ref:`_aggregation` this function ignores
the options ``order_by``, ``distinct``, and ``null_treatment``.
Args:
filter: If provided, only count rows for which the filter is True
"""
return count(Expr.literal(1), filter=filter)
def case(expr: Expr) -> CaseBuilder:
"""Create a case expression.
Create a :py:class:`~datafusion.expr.CaseBuilder` to match cases for the
expression ``expr``. See :py:class:`~datafusion.expr.CaseBuilder` for
detailed usage.
"""
return CaseBuilder(f.case(expr.expr))
def when(when: Expr, then: Expr) -> CaseBuilder:
"""Create a case expression that has no base expression.
Create a :py:class:`~datafusion.expr.CaseBuilder` to match cases for the
expression ``expr``. See :py:class:`~datafusion.expr.CaseBuilder` for
detailed usage.
"""
return CaseBuilder(f.when(when.expr, then.expr))
@deprecated("Prefer to call Expr.over() instead")
def window(
name: str,
args: list[Expr],
partition_by: list[Expr] | Expr | None = None,
order_by: list[SortKey] | SortKey | None = None,
window_frame: WindowFrame | None = None,
filter: Expr | None = None,
distinct: bool = False,
ctx: SessionContext | None = None,
) -> Expr:
"""Creates a new Window function expression.
This interface will soon be deprecated. Instead of using this interface,
users should call the window functions directly. For example, to perform a
lag use::
df.select(functions.lag(col("a")).partition_by(col("b")).build())
The ``order_by`` parameter accepts column names or expressions, e.g.::
window("lag", [col("a")], order_by="ts")
"""
args = [a.expr for a in args]
partition_by_raw = expr_list_to_raw_expr_list(partition_by)
order_by_raw = sort_list_to_raw_sort_list(order_by)
window_frame = window_frame.window_frame if window_frame is not None else None
ctx = ctx.ctx if ctx is not None else None
filter_raw = filter.expr if filter is not None else None
return Expr(
f.window(
name,
args,
partition_by=partition_by_raw,
order_by=order_by_raw,
window_frame=window_frame,
ctx=ctx,
filter=filter_raw,
distinct=distinct,
)
)
# scalar functions
def abs(arg: Expr) -> Expr:
"""Return the absolute value of a given number.
Returns:
--------
Expr
A new expression representing the absolute value of the input expression.
"""
return Expr(f.abs(arg.expr))
def acos(arg: Expr) -> Expr:
"""Returns the arc cosine or inverse cosine of a number.
Returns:
--------
Expr
A new expression representing the arc cosine of the input expression.
"""
return Expr(f.acos(arg.expr))
def acosh(arg: Expr) -> Expr:
"""Returns inverse hyperbolic cosine."""
return Expr(f.acosh(arg.expr))
def ascii(arg: Expr) -> Expr:
"""Returns the numeric code of the first character of the argument."""
return Expr(f.ascii(arg.expr))
def asin(arg: Expr) -> Expr:
"""Returns the arc sine or inverse sine of a number."""
return Expr(f.asin(arg.expr))
def asinh(arg: Expr) -> Expr:
"""Returns inverse hyperbolic sine."""
return Expr(f.asinh(arg.expr))
def atan(arg: Expr) -> Expr:
"""Returns inverse tangent of a number."""
return Expr(f.atan(arg.expr))
def atanh(arg: Expr) -> Expr:
"""Returns inverse hyperbolic tangent."""
return Expr(f.atanh(arg.expr))
def atan2(y: Expr, x: Expr) -> Expr:
"""Returns inverse tangent of a division given in the argument."""
return Expr(f.atan2(y.expr, x.expr))
def bit_length(arg: Expr) -> Expr:
"""Returns the number of bits in the string argument."""
return Expr(f.bit_length(arg.expr))
def btrim(arg: Expr) -> Expr:
"""Removes all characters, spaces by default, from both sides of a string."""
return Expr(f.btrim(arg.expr))
def cbrt(arg: Expr) -> Expr:
"""Returns the cube root of a number."""
return Expr(f.cbrt(arg.expr))
def ceil(arg: Expr) -> Expr:
"""Returns the nearest integer greater than or equal to argument."""
return Expr(f.ceil(arg.expr))
def character_length(arg: Expr) -> Expr:
"""Returns the number of characters in the argument."""
return Expr(f.character_length(arg.expr))
def length(string: Expr) -> Expr:
"""The number of characters in the ``string``."""
return Expr(f.length(string.expr))
def char_length(string: Expr) -> Expr:
"""The number of characters in the ``string``."""
return Expr(f.char_length(string.expr))
def chr(arg: Expr) -> Expr:
"""Converts the Unicode code point to a UTF8 character."""
return Expr(f.chr(arg.expr))
def coalesce(*args: Expr) -> Expr:
"""Returns the value of the first expr in ``args`` which is not NULL."""
args = [arg.expr for arg in args]
return Expr(f.coalesce(*args))
def cos(arg: Expr) -> Expr:
"""Returns the cosine of the argument."""
return Expr(f.cos(arg.expr))
def cosh(arg: Expr) -> Expr:
"""Returns the hyperbolic cosine of the argument."""
return Expr(f.cosh(arg.expr))
def cot(arg: Expr) -> Expr:
"""Returns the cotangent of the argument."""
return Expr(f.cot(arg.expr))
def degrees(arg: Expr) -> Expr:
"""Converts the argument from radians to degrees."""
return Expr(f.degrees(arg.expr))
def ends_with(arg: Expr, suffix: Expr) -> Expr:
"""Returns true if the ``string`` ends with the ``suffix``, false otherwise."""
return Expr(f.ends_with(arg.expr, suffix.expr))
def exp(arg: Expr) -> Expr:
"""Returns the exponential of the argument."""
return Expr(f.exp(arg.expr))
def factorial(arg: Expr) -> Expr:
"""Returns the factorial of the argument."""
return Expr(f.factorial(arg.expr))
def find_in_set(string: Expr, string_list: Expr) -> Expr:
"""Find a string in a list of strings.
Returns a value in the range of 1 to N if the string is in the string list
``string_list`` consisting of N substrings.
The string list is a string composed of substrings separated by ``,`` characters.
"""
return Expr(f.find_in_set(string.expr, string_list.expr))
def floor(arg: Expr) -> Expr:
"""Returns the nearest integer less than or equal to the argument."""
return Expr(f.floor(arg.expr))
def gcd(x: Expr, y: Expr) -> Expr:
"""Returns the greatest common divisor."""
return Expr(f.gcd(x.expr, y.expr))
def initcap(string: Expr) -> Expr:
"""Set the initial letter of each word to capital.
Converts the first letter of each word in ``string`` to uppercase and the remaining
characters to lowercase.
"""
return Expr(f.initcap(string.expr))
def instr(string: Expr, substring: Expr) -> Expr:
"""Finds the position from where the ``substring`` matches the ``string``.
This is an alias for :py:func:`strpos`.
"""
return strpos(string, substring)
def iszero(arg: Expr) -> Expr:
"""Returns true if a given number is +0.0 or -0.0 otherwise returns false."""
return Expr(f.iszero(arg.expr))
def lcm(x: Expr, y: Expr) -> Expr:
"""Returns the least common multiple."""
return Expr(f.lcm(x.expr, y.expr))
def left(string: Expr, n: Expr) -> Expr:
"""Returns the first ``n`` characters in the ``string``."""
return Expr(f.left(string.expr, n.expr))
def levenshtein(string1: Expr, string2: Expr) -> Expr:
"""Returns the Levenshtein distance between the two given strings."""
return Expr(f.levenshtein(string1.expr, string2.expr))
def ln(arg: Expr) -> Expr:
"""Returns the natural logarithm (base e) of the argument."""
return Expr(f.ln(arg.expr))
def log(base: Expr, num: Expr) -> Expr:
"""Returns the logarithm of a number for a particular ``base``."""
return Expr(f.log(base.expr, num.expr))
def log10(arg: Expr) -> Expr:
"""Base 10 logarithm of the argument."""
return Expr(f.log10(arg.expr))
def log2(arg: Expr) -> Expr:
"""Base 2 logarithm of the argument."""
return Expr(f.log2(arg.expr))
def lower(arg: Expr) -> Expr:
"""Converts a string to lowercase."""
return Expr(f.lower(arg.expr))
def lpad(string: Expr, count: Expr, characters: Expr | None = None) -> Expr:
"""Add left padding to a string.
Extends the string to length length by prepending the characters fill (a
space by default). If the string is already longer than length then it is
truncated (on the right).
"""
characters = characters if characters is not None else Expr.literal(" ")
return Expr(f.lpad(string.expr, count.expr, characters.expr))
def ltrim(arg: Expr) -> Expr:
"""Removes all characters, spaces by default, from the beginning of a string."""
return Expr(f.ltrim(arg.expr))
def md5(arg: Expr) -> Expr:
"""Computes an MD5 128-bit checksum for a string expression."""
return Expr(f.md5(arg.expr))
def nanvl(x: Expr, y: Expr) -> Expr:
"""Returns ``x`` if ``x`` is not ``NaN``. Otherwise returns ``y``."""
return Expr(f.nanvl(x.expr, y.expr))
def nvl(x: Expr, y: Expr) -> Expr:
"""Returns ``x`` if ``x`` is not ``NULL``. Otherwise returns ``y``."""
return Expr(f.nvl(x.expr, y.expr))
def octet_length(arg: Expr) -> Expr:
"""Returns the number of bytes of a string."""
return Expr(f.octet_length(arg.expr))
def overlay(
string: Expr, substring: Expr, start: Expr, length: Expr | None = None
) -> Expr:
"""Replace a substring with a new substring.
Replace the substring of string that starts at the ``start``'th character and
extends for ``length`` characters with new substring.
"""
if length is None:
return Expr(f.overlay(string.expr, substring.expr, start.expr))
return Expr(f.overlay(string.expr, substring.expr, start.expr, length.expr))
def pi() -> Expr:
"""Returns an approximate value of π."""
return Expr(f.pi())
def position(string: Expr, substring: Expr) -> Expr:
"""Finds the position from where the ``substring`` matches the ``string``.
This is an alias for :py:func:`strpos`.
"""
return strpos(string, substring)
def power(base: Expr, exponent: Expr) -> Expr:
"""Returns ``base`` raised to the power of ``exponent``."""
return Expr(f.power(base.expr, exponent.expr))
def pow(base: Expr, exponent: Expr) -> Expr:
"""Returns ``base`` raised to the power of ``exponent``.
This is an alias of :py:func:`power`.
"""
return power(base, exponent)
def radians(arg: Expr) -> Expr:
"""Converts the argument from degrees to radians."""
return Expr(f.radians(arg.expr))
def regexp_like(string: Expr, regex: Expr, flags: Expr | None = None) -> Expr:
"""Find if any regular expression (regex) matches exist.
Tests a string using a regular expression returning true if at least one match,
false otherwise.
"""
if flags is not None:
flags = flags.expr
return Expr(f.regexp_like(string.expr, regex.expr, flags))
def regexp_match(string: Expr, regex: Expr, flags: Expr | None = None) -> Expr:
"""Perform regular expression (regex) matching.
Returns an array with each element containing the leftmost-first match of the
corresponding index in ``regex`` to string in ``string``.
"""
if flags is not None:
flags = flags.expr
return Expr(f.regexp_match(string.expr, regex.expr, flags))
def regexp_replace(
string: Expr, pattern: Expr, replacement: Expr, flags: Expr | None = None
) -> Expr:
"""Replaces substring(s) matching a PCRE-like regular expression.
The full list of supported features and syntax can be found at
<https://docs.rs/regex/latest/regex/#syntax>
Supported flags with the addition of 'g' can be found at
<https://docs.rs/regex/latest/regex/#grouping-and-flags>
"""
if flags is not None:
flags = flags.expr
return Expr(f.regexp_replace(string.expr, pattern.expr, replacement.expr, flags))
def regexp_count(
string: Expr, pattern: Expr, start: Expr | None = None, flags: Expr | None = None
) -> Expr:
"""Returns the number of matches in a string.
Optional start position (the first position is 1) to search for the regular
expression.
"""
if flags is not None:
flags = flags.expr
start = start.expr if start is not None else start
return Expr(f.regexp_count(string.expr, pattern.expr, start, flags))
def regexp_instr(
values: Expr,
regex: Expr,
start: Expr | None = None,
n: Expr | None = None,
flags: Expr | None = None,
sub_expr: Expr | None = None,
) -> Expr:
"""Returns the position of a regular expression match in a string.
Searches ``values`` for the ``n``-th occurrence of ``regex``, starting at position
``start`` (the first position is 1). Returns the starting or ending position based
on ``end_position``. Use ``flags`` to control regex behavior and ``sub_expr`` to
return the position of a specific capture group instead of the entire match.
"""
start = start.expr if start is not None else None
n = n.expr if n is not None else None
flags = flags.expr if flags is not None else None
sub_expr = sub_expr.expr if sub_expr is not None else None
return Expr(
f.regexp_instr(
values.expr,
regex.expr,
start,
n,
flags,
sub_expr,
)
)
def repeat(string: Expr, n: Expr) -> Expr:
"""Repeats the ``string`` to ``n`` times."""
return Expr(f.repeat(string.expr, n.expr))
def replace(string: Expr, from_val: Expr, to_val: Expr) -> Expr:
"""Replaces all occurrences of ``from_val`` with ``to_val`` in the ``string``."""
return Expr(f.replace(string.expr, from_val.expr, to_val.expr))
def reverse(arg: Expr) -> Expr:
"""Reverse the string argument."""
return Expr(f.reverse(arg.expr))
def right(string: Expr, n: Expr) -> Expr:
"""Returns the last ``n`` characters in the ``string``."""
return Expr(f.right(string.expr, n.expr))
def round(value: Expr, decimal_places: Expr | None = None) -> Expr:
"""Round the argument to the nearest integer.
If the optional ``decimal_places`` is specified, round to the nearest number of
decimal places. You can specify a negative number of decimal places. For example
``round(lit(125.2345), lit(-2))`` would yield a value of ``100.0``.
"""
if decimal_places is None:
decimal_places = Expr.literal(0)
return Expr(f.round(value.expr, decimal_places.expr))
def rpad(string: Expr, count: Expr, characters: Expr | None = None) -> Expr:
"""Add right padding to a string.
Extends the string to length length by appending the characters fill (a space
by default). If the string is already longer than length then it is truncated.
"""
characters = characters if characters is not None else Expr.literal(" ")
return Expr(f.rpad(string.expr, count.expr, characters.expr))
def rtrim(arg: Expr) -> Expr:
"""Removes all characters, spaces by default, from the end of a string."""
return Expr(f.rtrim(arg.expr))
def sha224(arg: Expr) -> Expr:
"""Computes the SHA-224 hash of a binary string."""
return Expr(f.sha224(arg.expr))
def sha256(arg: Expr) -> Expr:
"""Computes the SHA-256 hash of a binary string."""
return Expr(f.sha256(arg.expr))
def sha384(arg: Expr) -> Expr:
"""Computes the SHA-384 hash of a binary string."""
return Expr(f.sha384(arg.expr))
def sha512(arg: Expr) -> Expr:
"""Computes the SHA-512 hash of a binary string."""
return Expr(f.sha512(arg.expr))
def signum(arg: Expr) -> Expr:
"""Returns the sign of the argument (-1, 0, +1)."""
return Expr(f.signum(arg.expr))
def sin(arg: Expr) -> Expr:
"""Returns the sine of the argument."""
return Expr(f.sin(arg.expr))
def sinh(arg: Expr) -> Expr:
"""Returns the hyperbolic sine of the argument."""
return Expr(f.sinh(arg.expr))
def split_part(string: Expr, delimiter: Expr, index: Expr) -> Expr:
"""Split a string and return one part.
Splits a string based on a delimiter and picks out the desired field based
on the index.
"""
return Expr(f.split_part(string.expr, delimiter.expr, index.expr))
def sqrt(arg: Expr) -> Expr:
"""Returns the square root of the argument."""
return Expr(f.sqrt(arg.expr))
def starts_with(string: Expr, prefix: Expr) -> Expr:
"""Returns true if string starts with prefix."""
return Expr(f.starts_with(string.expr, prefix.expr))
def strpos(string: Expr, substring: Expr) -> Expr:
"""Finds the position from where the ``substring`` matches the ``string``."""
return Expr(f.strpos(string.expr, substring.expr))
def substr(string: Expr, position: Expr) -> Expr:
"""Substring from the ``position`` to the end."""
return Expr(f.substr(string.expr, position.expr))
def substr_index(string: Expr, delimiter: Expr, count: Expr) -> Expr:
"""Returns an indexed substring.
The return will be the ``string`` from before ``count`` occurrences of
``delimiter``.
"""
return Expr(f.substr_index(string.expr, delimiter.expr, count.expr))
def substring(string: Expr, position: Expr, length: Expr) -> Expr:
"""Substring from the ``position`` with ``length`` characters."""
return Expr(f.substring(string.expr, position.expr, length.expr))
def tan(arg: Expr) -> Expr:
"""Returns the tangent of the argument."""
return Expr(f.tan(arg.expr))
def tanh(arg: Expr) -> Expr:
"""Returns the hyperbolic tangent of the argument."""