This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathgeneric_ops.py
More file actions
462 lines (407 loc) · 11.6 KB
/
generic_ops.py
File metadata and controls
462 lines (407 loc) · 11.6 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
# Copyright 2025 Google LLC
#
# Licensed 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.
import dataclasses
import functools
import typing
from bigframes import dtypes
from bigframes.operations import base_ops
import bigframes.operations.type as op_typing
InvertOp = base_ops.create_unary_op(
name="invert",
type_signature=op_typing.TypePreserving(
dtypes.is_binary_like,
description="binary-like",
),
)
invert_op = InvertOp()
IsNullOp = base_ops.create_unary_op(
name="isnull",
type_signature=op_typing.FixedOutputType(
lambda x: True, dtypes.BOOL_DTYPE, description="nullable"
),
)
isnull_op = IsNullOp()
NotNullOp = base_ops.create_unary_op(
name="notnull",
type_signature=op_typing.FixedOutputType(
lambda x: True, dtypes.BOOL_DTYPE, description="nullable"
),
)
notnull_op = NotNullOp()
HashOp = base_ops.create_unary_op(
name="hash",
type_signature=op_typing.FixedOutputType(
dtypes.is_string_like, dtypes.INT_DTYPE, description="string-like"
),
)
hash_op = HashOp()
# source, dest type
_VALID_CASTS = set(
(
# INT casts
(
dtypes.BOOL_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.FLOAT_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.NUMERIC_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.BIGNUMERIC_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.TIME_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.DATETIME_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.TIMESTAMP_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.TIMEDELTA_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.STRING_DTYPE,
dtypes.INT_DTYPE,
),
(
dtypes.JSON_DTYPE,
dtypes.INT_DTYPE,
),
# Float casts
(
dtypes.BOOL_DTYPE,
dtypes.FLOAT_DTYPE,
),
(
dtypes.NUMERIC_DTYPE,
dtypes.FLOAT_DTYPE,
),
(
dtypes.BIGNUMERIC_DTYPE,
dtypes.FLOAT_DTYPE,
),
(
dtypes.INT_DTYPE,
dtypes.FLOAT_DTYPE,
),
(
dtypes.STRING_DTYPE,
dtypes.FLOAT_DTYPE,
),
(
dtypes.JSON_DTYPE,
dtypes.FLOAT_DTYPE,
),
# Bool casts
(
dtypes.INT_DTYPE,
dtypes.BOOL_DTYPE,
),
(
dtypes.FLOAT_DTYPE,
dtypes.BOOL_DTYPE,
),
(
dtypes.JSON_DTYPE,
dtypes.BOOL_DTYPE,
),
# String casts
(
dtypes.BYTES_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.BOOL_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.FLOAT_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.TIME_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.INT_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.DATETIME_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.TIMESTAMP_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.DATE_DTYPE,
dtypes.STRING_DTYPE,
),
(
dtypes.JSON_DTYPE,
dtypes.STRING_DTYPE,
),
# bytes casts
(
dtypes.STRING_DTYPE,
dtypes.BYTES_DTYPE,
),
# decimal casts
(
dtypes.STRING_DTYPE,
dtypes.NUMERIC_DTYPE,
),
(
dtypes.INT_DTYPE,
dtypes.NUMERIC_DTYPE,
),
(
dtypes.FLOAT_DTYPE,
dtypes.NUMERIC_DTYPE,
),
(
dtypes.BIGNUMERIC_DTYPE,
dtypes.NUMERIC_DTYPE,
),
# big decimal casts
(
dtypes.STRING_DTYPE,
dtypes.BIGNUMERIC_DTYPE,
),
(
dtypes.INT_DTYPE,
dtypes.BIGNUMERIC_DTYPE,
),
(
dtypes.FLOAT_DTYPE,
dtypes.BIGNUMERIC_DTYPE,
),
(
dtypes.NUMERIC_DTYPE,
dtypes.BIGNUMERIC_DTYPE,
),
# time casts
(
dtypes.INT_DTYPE,
dtypes.TIME_DTYPE,
),
(
dtypes.DATETIME_DTYPE,
dtypes.TIME_DTYPE,
),
(
dtypes.TIMESTAMP_DTYPE,
dtypes.TIME_DTYPE,
),
# date casts
(
dtypes.STRING_DTYPE,
dtypes.DATE_DTYPE,
),
(
dtypes.DATETIME_DTYPE,
dtypes.DATE_DTYPE,
),
(
dtypes.TIMESTAMP_DTYPE,
dtypes.DATE_DTYPE,
),
# datetime casts
(
dtypes.DATE_DTYPE,
dtypes.DATETIME_DTYPE,
),
(
dtypes.STRING_DTYPE,
dtypes.DATETIME_DTYPE,
),
(
dtypes.TIMESTAMP_DTYPE,
dtypes.DATETIME_DTYPE,
),
(
dtypes.INT_DTYPE,
dtypes.DATETIME_DTYPE,
),
# timestamp casts
(
dtypes.DATE_DTYPE,
dtypes.TIMESTAMP_DTYPE,
),
(
dtypes.STRING_DTYPE,
dtypes.TIMESTAMP_DTYPE,
),
(
dtypes.DATETIME_DTYPE,
dtypes.TIMESTAMP_DTYPE,
),
(
dtypes.INT_DTYPE,
dtypes.TIMESTAMP_DTYPE,
),
# timedelta casts
(
dtypes.INT_DTYPE,
dtypes.TIMEDELTA_DTYPE,
),
# json casts
(
dtypes.BOOL_DTYPE,
dtypes.JSON_DTYPE,
),
(
dtypes.FLOAT_DTYPE,
dtypes.JSON_DTYPE,
),
(
dtypes.STRING_DTYPE,
dtypes.JSON_DTYPE,
),
(
dtypes.INT_DTYPE,
dtypes.JSON_DTYPE,
),
)
)
def _valid_scalar_cast(src: dtypes.Dtype, dst: dtypes.Dtype):
if src == dst:
return True
elif (src, dst) in _VALID_CASTS:
return True
return False
def _valid_cast(src: dtypes.Dtype, dst: dtypes.Dtype):
if src == dst:
return True
# TODO: Might need to be more strict within list/array context
if dtypes.is_array_like(src) and dtypes.is_array_like(dst):
src_inner = dtypes.get_array_inner_type(src)
dst_inner = dtypes.get_array_inner_type(dst)
return _valid_cast(src_inner, dst_inner)
if dtypes.is_struct_like(src) and dtypes.is_struct_like(dst):
src_fields = dtypes.get_struct_fields(src)
dst_fields = dtypes.get_struct_fields(dst)
if len(src_fields) != len(dst_fields):
return False
for (_, src_dtype), (_, dst_dtype) in zip(
src_fields.items(), dst_fields.items()
):
if not _valid_cast(src_dtype, dst_dtype):
return False
return True
if dtypes.is_struct_like(src) and dst == dtypes.JSON_DTYPE:
return True
return _valid_scalar_cast(src, dst)
@dataclasses.dataclass(frozen=True)
class AsTypeOp(base_ops.UnaryOp):
name: typing.ClassVar[str] = "astype"
# TODO: Convert strings to dtype earlier
to_type: dtypes.Dtype
safe: bool = False
def output_type(self, *input_types):
if not _valid_cast(input_types[0], self.to_type):
raise TypeError(f"Cannot cast {input_types[0]} to {self.to_type}")
return self.to_type
@dataclasses.dataclass(frozen=True)
class IsInOp(base_ops.UnaryOp):
name: typing.ClassVar[str] = "is_in"
values: typing.Tuple
match_nulls: bool = True
def output_type(self, *input_types):
return dtypes.BOOL_DTYPE
@dataclasses.dataclass(frozen=True)
class MapOp(base_ops.UnaryOp):
name = "map_values"
mappings: typing.Tuple[typing.Tuple[typing.Hashable, typing.Hashable], ...]
def output_type(self, *input_types):
return input_types[0]
FillNaOp = base_ops.create_binary_op(name="fillna", type_signature=op_typing.COERCE)
fillna_op = FillNaOp()
MaximumOp = base_ops.create_binary_op(name="maximum", type_signature=op_typing.COERCE)
maximum_op = MaximumOp()
MinimumOp = base_ops.create_binary_op(name="minimum", type_signature=op_typing.COERCE)
minimum_op = MinimumOp()
CoalesceOp = base_ops.create_binary_op(name="coalesce", type_signature=op_typing.COERCE)
coalesce_op = CoalesceOp()
@dataclasses.dataclass(frozen=True)
class WhereOp(base_ops.TernaryOp):
name: typing.ClassVar[str] = "where"
def output_type(self, *input_types: dtypes.ExpressionType) -> dtypes.ExpressionType:
if input_types[1] != dtypes.BOOL_DTYPE:
raise TypeError("where condition must be a boolean")
return dtypes.coerce_to_common(input_types[0], input_types[2])
where_op = WhereOp()
@dataclasses.dataclass(frozen=True)
class ClipOp(base_ops.TernaryOp):
name: typing.ClassVar[str] = "clip"
def output_type(self, *input_types: dtypes.ExpressionType) -> dtypes.ExpressionType:
return dtypes.coerce_to_common(
input_types[0], dtypes.coerce_to_common(input_types[1], input_types[2])
)
clip_op = ClipOp()
class CaseWhenOp(base_ops.NaryOp):
name: typing.ClassVar[str] = "switch"
def output_type(self, *input_types: dtypes.ExpressionType) -> dtypes.ExpressionType:
assert len(input_types) % 2 == 0
# predicate1, output1, predicate2, output2...
if not all(map(lambda x: x == dtypes.BOOL_DTYPE, input_types[::2])):
raise TypeError(f"Case inputs {input_types[::2]} must be boolean-valued")
output_expr_types = input_types[1::2]
return functools.reduce(
lambda t1, t2: dtypes.coerce_to_common(t1, t2),
output_expr_types,
)
case_when_op = CaseWhenOp()
# Really doesn't need to be its own op, but allows us to try to get the most compact representation
@dataclasses.dataclass(frozen=True)
class RowKey(base_ops.NaryOp):
name: typing.ClassVar[str] = "rowkey"
def output_type(self, *input_types: dtypes.ExpressionType) -> dtypes.ExpressionType:
return dtypes.STRING_DTYPE
@property
def is_bijective(self) -> bool:
"""Whether the operation has a 1:1 mapping between inputs and outputs"""
return True
@property
def deterministic(self) -> bool:
return False
@dataclasses.dataclass(frozen=True)
class SqlScalarOp(base_ops.NaryOp):
"""An escape to SQL, representing a single column."""
name: typing.ClassVar[str] = "sql_scalar"
_output_type: dtypes.ExpressionType
sql_template: str
def output_type(self, *input_types: dtypes.ExpressionType) -> dtypes.ExpressionType:
return self._output_type
@dataclasses.dataclass(frozen=True)
class PyUdfOp(base_ops.NaryOp):
"""Represents a local UDF."""
name: typing.ClassVar[str] = "py_udf"
fn: typing.Callable
_output_type: dtypes.ExpressionType
def output_type(self, *input_types: dtypes.ExpressionType) -> dtypes.ExpressionType:
return self._output_type