forked from googleapis/python-bigquery-dataframes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes.py
More file actions
1508 lines (1216 loc) · 47 KB
/
Copy pathnodes.py
File metadata and controls
1508 lines (1216 loc) · 47 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
# Copyright 2023 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.
from __future__ import annotations
import abc
import dataclasses
import datetime
import functools
import itertools
import typing
from typing import Callable, cast, Iterable, Mapping, Optional, Sequence, Tuple
import google.cloud.bigquery as bq
import bigframes.core.expression as ex
import bigframes.core.guid
import bigframes.core.identifiers
import bigframes.core.identifiers as bfet_ids
from bigframes.core.ordering import OrderingExpression
import bigframes.core.schema as schemata
import bigframes.core.slices as slices
import bigframes.core.window_spec as window
import bigframes.dtypes
import bigframes.operations.aggregations as agg_ops
if typing.TYPE_CHECKING:
import bigframes.core.ordering as orderings
import bigframes.session
# A fixed number of variable to assume for overhead on some operations
OVERHEAD_VARIABLES = 5
COLUMN_SET = frozenset[bfet_ids.ColumnId]
@dataclasses.dataclass(frozen=True)
class Field:
id: bfet_ids.ColumnId
dtype: bigframes.dtypes.Dtype
@dataclasses.dataclass(eq=False, frozen=True)
class BigFrameNode(abc.ABC):
"""
Immutable node for representing 2D typed array as a tree of operators.
All subclasses must be hashable so as to be usable as caching key.
"""
@property
def deterministic(self) -> bool:
"""Whether this node will evaluates deterministically."""
return True
@property
def row_preserving(self) -> bool:
"""Whether this node preserves input rows."""
return True
@property
def non_local(self) -> bool:
"""
Whether this node combines information across multiple rows instead of processing rows independently.
Used as an approximation for whether the expression may require shuffling to execute (and therefore be expensive).
"""
return False
@property
def child_nodes(self) -> typing.Sequence[BigFrameNode]:
"""Direct children of this node"""
return tuple([])
@property
def projection_base(self) -> BigFrameNode:
return self
@property
@abc.abstractmethod
def row_count(self) -> typing.Optional[int]:
return None
@abc.abstractmethod
def remap_refs(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
"""Remap variable references"""
...
@property
@abc.abstractmethod
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
"""The variables defined in this node (as opposed to by child nodes)."""
...
@functools.cached_property
def session(self):
sessions = []
for child in self.child_nodes:
if child.session is not None:
sessions.append(child.session)
unique_sessions = len(set(sessions))
if unique_sessions > 1:
raise ValueError("Cannot use combine sources from multiple sessions.")
elif unique_sessions == 1:
return sessions[0]
return None
def _validate(self):
"""Validate the local data in the node."""
return
@functools.cache
def validate_tree(self) -> bool:
for child in self.child_nodes:
child.validate_tree()
self._validate()
field_list = list(self.fields)
if len(set(field_list)) != len(field_list):
raise ValueError(f"Non unique field ids {list(self.fields)}")
return True
def _as_tuple(self) -> Tuple:
"""Get all fields as tuple."""
return tuple(getattr(self, field.name) for field in dataclasses.fields(self))
def __hash__(self) -> int:
# Custom hash that uses cache to avoid costly recomputation
return self._cached_hash
def __eq__(self, other) -> bool:
# Custom eq that tries to short-circuit full structural comparison
if not isinstance(other, self.__class__):
return False
if self is other:
return True
if hash(self) != hash(other):
return False
return self._as_tuple() == other._as_tuple()
# BigFrameNode trees can be very deep so its important avoid recalculating the hash from scratch
# Each subclass of BigFrameNode should use this property to implement __hash__
# The default dataclass-generated __hash__ method is not cached
@functools.cached_property
def _cached_hash(self):
return hash(self._as_tuple())
@property
def roots(self) -> typing.Set[BigFrameNode]:
roots = itertools.chain.from_iterable(
map(lambda child: child.roots, self.child_nodes)
)
return set(roots)
# TODO: Store some local data lazily for select, aggregate nodes.
@property
@abc.abstractmethod
def fields(self) -> Iterable[Field]:
...
@property
def ids(self) -> Iterable[bfet_ids.ColumnId]:
"""All output ids from the node."""
return (field.id for field in self.fields)
@property
@abc.abstractmethod
def variables_introduced(self) -> int:
"""
Defines number of values created by the current node. Helps represent the "width" of a query
"""
...
@property
def relation_ops_created(self) -> int:
"""
Defines the number of relational ops generated by the current node. Used to estimate query planning complexity.
"""
return 1
@property
def joins(self) -> bool:
"""
Defines whether the node joins data.
"""
return False
@property
@abc.abstractmethod
def order_ambiguous(self) -> bool:
"""
Whether row ordering is potentially ambiguous. For example, ReadTable (without a primary key) could be ordered in different ways.
"""
...
@property
@abc.abstractmethod
def explicitly_ordered(self) -> bool:
"""
Whether row ordering is potentially ambiguous. For example, ReadTable (without a primary key) could be ordered in different ways.
"""
...
@functools.cached_property
def total_variables(self) -> int:
return self.variables_introduced + sum(
map(lambda x: x.total_variables, self.child_nodes)
)
@functools.cached_property
def total_relational_ops(self) -> int:
return self.relation_ops_created + sum(
map(lambda x: x.total_relational_ops, self.child_nodes)
)
@functools.cached_property
def total_joins(self) -> int:
return int(self.joins) + sum(map(lambda x: x.total_joins, self.child_nodes))
@functools.cached_property
def schema(self) -> schemata.ArraySchema:
# TODO: Make schema just a view on fields
return schemata.ArraySchema(
tuple(schemata.SchemaItem(i.id.name, i.dtype) for i in self.fields)
)
@property
def planning_complexity(self) -> int:
"""
Empirical heuristic measure of planning complexity.
Used to determine when to decompose overly complex computations. May require tuning.
"""
return self.total_variables * self.total_relational_ops * (1 + self.total_joins)
@abc.abstractmethod
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> BigFrameNode:
"""Apply a function to each child node."""
...
@abc.abstractmethod
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
"""Remap defined (in this node only) variables."""
...
@property
def defines_namespace(self) -> bool:
"""
If true, this node establishes a new column id namespace.
If false, this node consumes and produces ids in the namespace
"""
return False
@functools.cached_property
def defined_variables(self) -> set[str]:
"""Full set of variables defined in the namespace, even if not selected."""
self_defined_variables = set(self.schema.names)
if self.defines_namespace:
return self_defined_variables
return self_defined_variables.union(
*(child.defined_variables for child in self.child_nodes)
)
def get_type(self, id: bfet_ids.ColumnId) -> bigframes.dtypes.Dtype:
return self._dtype_lookup[id]
@functools.cached_property
def _dtype_lookup(self):
return {field.id: field.dtype for field in self.fields}
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
return self.transform_children(lambda x: x.prune(used_cols))
@dataclasses.dataclass(frozen=True, eq=False)
class UnaryNode(BigFrameNode):
child: BigFrameNode
@property
def child_nodes(self) -> typing.Sequence[BigFrameNode]:
return (self.child,)
@property
def fields(self) -> Iterable[Field]:
return self.child.fields
@property
def explicitly_ordered(self) -> bool:
return self.child.explicitly_ordered
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> BigFrameNode:
transformed = dataclasses.replace(self, child=t(self.child))
if self == transformed:
# reusing existing object speeds up eq, and saves a small amount of memory
return self
return transformed
def replace_child(self, new_child: BigFrameNode) -> UnaryNode:
new_self = dataclasses.replace(self, child=new_child) # type: ignore
return new_self
@property
def order_ambiguous(self) -> bool:
return self.child.order_ambiguous
@dataclasses.dataclass(frozen=True, eq=False)
class SliceNode(UnaryNode):
"""Logical slice node conditionally becomes limit or filter over row numbers."""
start: Optional[int]
stop: Optional[int]
step: int = 1
@property
def row_preserving(self) -> bool:
"""Whether this node preserves input rows."""
return False
@property
def non_local(self) -> bool:
"""
Whether this node combines information across multiple rows instead of processing rows independently.
Used as an approximation for whether the expression may require shuffling to execute (and therefore be expensive).
"""
return True
# these are overestimates, more accurate numbers available by converting to concrete limit or analytic+filter ops
@property
def variables_introduced(self) -> int:
return 2
@property
def relation_ops_created(self) -> int:
return 2
@property
def is_limit(self) -> bool:
"""Returns whether this is equivalent to a ORDER BY ... LIMIT N."""
# TODO: Handle tail case.
return (
(not self.start)
and (self.step == 1)
and (self.stop is not None)
and (self.stop > 0)
)
@property
def row_count(self) -> typing.Optional[int]:
child_length = self.child.row_count
if child_length is None:
return None
return slices.slice_output_rows(
(self.start, self.stop, self.step), child_length
)
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return ()
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
return self
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
return self
@dataclasses.dataclass(frozen=True, eq=False)
class JoinNode(BigFrameNode):
left_child: BigFrameNode
right_child: BigFrameNode
conditions: typing.Tuple[typing.Tuple[ex.DerefOp, ex.DerefOp], ...]
type: typing.Literal["inner", "outer", "left", "right", "cross"]
def _validate(self):
assert not (
set(self.left_child.ids) & set(self.right_child.ids)
), "Join ids collide"
@property
def row_preserving(self) -> bool:
return False
@property
def non_local(self) -> bool:
return True
@property
def child_nodes(self) -> typing.Sequence[BigFrameNode]:
return (self.left_child, self.right_child)
@property
def order_ambiguous(self) -> bool:
return True
@property
def explicitly_ordered(self) -> bool:
# Do not consider user pre-join ordering intent - they need to re-order post-join in unordered mode.
return False
@property
def fields(self) -> Iterable[Field]:
return itertools.chain(self.left_child.fields, self.right_child.fields)
@functools.cached_property
def variables_introduced(self) -> int:
"""Defines the number of variables generated by the current node. Used to estimate query planning complexity."""
return OVERHEAD_VARIABLES
@property
def joins(self) -> bool:
return True
@property
def row_count(self) -> Optional[int]:
if self.type == "cross":
if self.left_child.row_count is None or self.right_child.row_count is None:
return None
return self.left_child.row_count * self.right_child.row_count
return None
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return ()
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> BigFrameNode:
transformed = dataclasses.replace(
self, left_child=t(self.left_child), right_child=t(self.right_child)
)
if self == transformed:
# reusing existing object speeds up eq, and saves a small amount of memory
return self
return transformed
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
# If this is a cross join, make sure to select at least one column from each side
condition_cols = used_cols.union(
map(lambda x: x.id, itertools.chain.from_iterable(self.conditions))
)
return self.transform_children(
lambda x: x.prune(frozenset([*condition_cols, *used_cols]))
)
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
return self
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
new_conds = tuple(
(
l_cond.remap_column_refs(mappings, allow_partial_bindings=True),
r_cond.remap_column_refs(mappings, allow_partial_bindings=True),
)
for l_cond, r_cond in self.conditions
)
return dataclasses.replace(self, conditions=new_conds) # type: ignore
@dataclasses.dataclass(frozen=True, eq=False)
class ConcatNode(BigFrameNode):
# TODO: Explcitly map column ids from each child
children: Tuple[BigFrameNode, ...]
output_ids: Tuple[bfet_ids.ColumnId, ...]
def _validate(self):
if len(self.children) == 0:
raise ValueError("Concat requires at least one input table. Zero provided.")
child_schemas = [child.schema.dtypes for child in self.children]
if not len(set(child_schemas)) == 1:
raise ValueError("All inputs must have identical dtypes. {child_schemas}")
@property
def child_nodes(self) -> typing.Sequence[BigFrameNode]:
return self.children
@property
def order_ambiguous(self) -> bool:
return any(child.order_ambiguous for child in self.children)
@property
def explicitly_ordered(self) -> bool:
# Consider concat as an ordered operations (even though input frames may not be ordered)
return True
@property
def fields(self) -> Iterable[Field]:
# TODO: Output names should probably be aligned beforehand or be part of concat definition
return (
Field(id, field.dtype)
for id, field in zip(self.output_ids, self.children[0].fields)
)
@functools.cached_property
def variables_introduced(self) -> int:
"""Defines the number of variables generated by the current node. Used to estimate query planning complexity."""
return len(self.schema.items) + OVERHEAD_VARIABLES
@property
def row_count(self) -> Optional[int]:
sub_counts = [node.row_count for node in self.child_nodes]
total = 0
for count in sub_counts:
if count is None:
return None
total += count
return total
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return self.output_ids
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> BigFrameNode:
transformed = dataclasses.replace(
self, children=tuple(t(child) for child in self.children)
)
if self == transformed:
# reusing existing object speeds up eq, and saves a small amount of memory
return self
return transformed
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
# TODO: Make concat prunable, probably by redefining
return self
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
new_ids = tuple(mappings.get(id, id) for id in self.output_ids)
return dataclasses.replace(self, output_ids=new_ids)
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
return self
@dataclasses.dataclass(frozen=True, eq=False)
class FromRangeNode(BigFrameNode):
# TODO: Enforce single-row, single column constraint
start: BigFrameNode
end: BigFrameNode
step: int
output_id: bfet_ids.ColumnId = bfet_ids.ColumnId("labels")
@property
def roots(self) -> typing.Set[BigFrameNode]:
return {self}
@property
def child_nodes(self) -> typing.Sequence[BigFrameNode]:
return (self.start, self.end)
@property
def order_ambiguous(self) -> bool:
return False
@property
def explicitly_ordered(self) -> bool:
return True
@functools.cached_property
def fields(self) -> Iterable[Field]:
return (Field(self.output_id, next(iter(self.start.fields)).dtype),)
@functools.cached_property
def variables_introduced(self) -> int:
"""Defines the number of variables generated by the current node. Used to estimate query planning complexity."""
return len(self.schema.items) + OVERHEAD_VARIABLES
@property
def row_count(self) -> Optional[int]:
return None
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return (self.output_id,)
@property
def defines_namespace(self) -> bool:
return True
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> BigFrameNode:
transformed = dataclasses.replace(self, start=t(self.start), end=t(self.end))
if self == transformed:
# reusing existing object speeds up eq, and saves a small amount of memory
return self
return transformed
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
# TODO: Make FromRangeNode prunable (or convert to other node types)
return self
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
return dataclasses.replace(
self, output_id=mappings.get(self.output_id, self.output_id)
)
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
return self
# Input Nodex
# TODO: Most leaf nodes produce fixed column names based on the datasource
# They should support renaming
@dataclasses.dataclass(frozen=True, eq=False)
class LeafNode(BigFrameNode):
@property
def roots(self) -> typing.Set[BigFrameNode]:
return {self}
@property
def fast_offsets(self) -> bool:
return False
@property
def fast_ordered_limit(self) -> bool:
return False
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> BigFrameNode:
return self
class ScanItem(typing.NamedTuple):
id: bfet_ids.ColumnId
dtype: bigframes.dtypes.Dtype # Might be multiple logical types for a given physical source type
source_id: str # Flexible enough for both local data and bq data
@dataclasses.dataclass(frozen=True)
class ScanList:
items: typing.Tuple[ScanItem, ...]
@dataclasses.dataclass(frozen=True, eq=False)
class ReadLocalNode(LeafNode):
feather_bytes: bytes
data_schema: schemata.ArraySchema
n_rows: int
# Mapping of local ids to bfet id.
scan_list: ScanList
session: typing.Optional[bigframes.session.Session] = None
@property
def fields(self) -> Iterable[Field]:
return (Field(col_id, dtype) for col_id, dtype, _ in self.scan_list.items)
@property
def variables_introduced(self) -> int:
"""Defines the number of variables generated by the current node. Used to estimate query planning complexity."""
return len(self.scan_list.items) + 1
@property
def fast_offsets(self) -> bool:
return True
@property
def fast_ordered_limit(self) -> bool:
return True
@property
def order_ambiguous(self) -> bool:
return False
@property
def explicitly_ordered(self) -> bool:
return True
@property
def row_count(self) -> typing.Optional[int]:
return self.n_rows
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return tuple(item.id for item in self.scan_list.items)
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
# Don't preoduce empty scan list no matter what, will result in broken sql syntax
# TODO: Handle more elegantly
new_scan_list = ScanList(
tuple(item for item in self.scan_list.items if item.id in used_cols)
or (self.scan_list.items[0],)
)
return ReadLocalNode(
self.feather_bytes,
self.data_schema,
self.n_rows,
new_scan_list,
self.session,
)
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
new_scan_list = ScanList(
tuple(
ScanItem(mappings.get(item.id, item.id), item.dtype, item.source_id)
for item in self.scan_list.items
)
)
return dataclasses.replace(self, scan_list=new_scan_list)
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
return self
@dataclasses.dataclass(frozen=True)
class GbqTable:
project_id: str = dataclasses.field()
dataset_id: str = dataclasses.field()
table_id: str = dataclasses.field()
physical_schema: Tuple[bq.SchemaField, ...] = dataclasses.field()
n_rows: int = dataclasses.field()
is_physically_stored: bool = dataclasses.field()
cluster_cols: typing.Optional[Tuple[str, ...]]
@staticmethod
def from_table(table: bq.Table, columns: Sequence[str] = ()) -> GbqTable:
# Subsetting fields with columns can reduce cost of row-hash default ordering
if columns:
schema = tuple(item for item in table.schema if item.name in columns)
else:
schema = tuple(table.schema)
return GbqTable(
project_id=table.project,
dataset_id=table.dataset_id,
table_id=table.table_id,
physical_schema=schema,
n_rows=table.num_rows,
is_physically_stored=(table.table_type in ["TABLE", "MATERIALIZED_VIEW"]),
cluster_cols=None
if table.clustering_fields is None
else tuple(table.clustering_fields),
)
@dataclasses.dataclass(frozen=True)
class BigqueryDataSource:
"""
Google BigQuery Data source.
This should not be modified once defined, as all attributes contribute to the default ordering.
"""
table: GbqTable
at_time: typing.Optional[datetime.datetime] = None
# Added for backwards compatibility, not validated
sql_predicate: typing.Optional[str] = None
ordering: typing.Optional[orderings.RowOrdering] = None
## Put ordering in here or just add order_by node above?
@dataclasses.dataclass(frozen=True, eq=False)
class ReadTableNode(LeafNode):
source: BigqueryDataSource
# Subset of physical schema column
# Mapping of table schema ids to bfet id.
scan_list: ScanList
table_session: bigframes.session.Session = dataclasses.field()
def _validate(self):
# enforce invariants
physical_names = set(map(lambda i: i.name, self.source.table.physical_schema))
if not set(scan.source_id for scan in self.scan_list.items).issubset(
physical_names
):
raise ValueError(
f"Requested schema {self.scan_list} cannot be derived from table schemal {self.source.table.physical_schema}"
)
@property
def session(self):
return self.table_session
@property
def fields(self) -> Iterable[Field]:
return (Field(col_id, dtype) for col_id, dtype, _ in self.scan_list.items)
@property
def relation_ops_created(self) -> int:
# Assume worst case, where readgbq actually has baked in analytic operation to generate index
return 3
@property
def fast_offsets(self) -> bool:
# Fast head is only supported when row offsets are available or data is clustered over ordering key.
return (self.source.ordering is not None) and self.source.ordering.is_sequential
@property
def fast_ordered_limit(self) -> bool:
if self.source.ordering is None:
return False
order_cols = self.source.ordering.all_ordering_columns
# monotonicity would probably be fine
if not all(col.scalar_expression.is_identity for col in order_cols):
return False
order_col_ids = tuple(
cast(ex.DerefOp, col.scalar_expression).id.name for col in order_cols
)
cluster_col_ids = self.source.table.cluster_cols
if cluster_col_ids is None:
return False
return order_col_ids == cluster_col_ids[: len(order_col_ids)]
@property
def order_ambiguous(self) -> bool:
return (
self.source.ordering is None
) or not self.source.ordering.is_total_ordering
@property
def explicitly_ordered(self) -> bool:
return self.source.ordering is not None
@functools.cached_property
def variables_introduced(self) -> int:
return len(self.scan_list.items) + 1
@property
def row_count(self) -> typing.Optional[int]:
if self.source.sql_predicate is None and self.source.table.is_physically_stored:
return self.source.table.n_rows
return None
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return tuple(item.id for item in self.scan_list.items)
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
new_scan_list = ScanList(
tuple(item for item in self.scan_list.items if item.id in used_cols)
or (self.scan_list.items[0],)
)
return dataclasses.replace(self, scan_list=new_scan_list)
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
new_scan_list = ScanList(
tuple(
ScanItem(mappings.get(item.id, item.id), item.dtype, item.source_id)
for item in self.scan_list.items
)
)
return dataclasses.replace(self, scan_list=new_scan_list)
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
return self
@dataclasses.dataclass(frozen=True, eq=False)
class CachedTableNode(ReadTableNode):
# The original BFET subtree that was cached
# note: this isn't a "child" node.
original_node: BigFrameNode = dataclasses.field()
# Unary nodes
@dataclasses.dataclass(frozen=True, eq=False)
class PromoteOffsetsNode(UnaryNode):
col_id: bigframes.core.identifiers.ColumnId
@property
def non_local(self) -> bool:
return True
@property
def fields(self) -> Iterable[Field]:
return itertools.chain(
self.child.fields, [Field(self.col_id, bigframes.dtypes.INT_DTYPE)]
)
@property
def relation_ops_created(self) -> int:
return 2
@functools.cached_property
def variables_introduced(self) -> int:
return 1
@property
def row_count(self) -> Optional[int]:
return self.child.row_count
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return (self.col_id,)
@property
def projection_base(self) -> BigFrameNode:
return self.child.projection_base
@property
def added_fields(self) -> Tuple[Field, ...]:
return (Field(self.col_id, bigframes.dtypes.INT_DTYPE),)
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
if self.col_id not in used_cols:
return self.child.prune(used_cols)
else:
new_used = used_cols.difference([self.col_id])
return self.transform_children(lambda x: x.prune(new_used))
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
return dataclasses.replace(self, col_id=mappings.get(self.col_id, self.col_id))
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
return self
@dataclasses.dataclass(frozen=True, eq=False)
class FilterNode(UnaryNode):
predicate: ex.Expression
@property
def row_preserving(self) -> bool:
return False
@property
def variables_introduced(self) -> int:
return 1
@property
def row_count(self) -> Optional[int]:
return None
@property
def node_defined_ids(self) -> Tuple[bfet_ids.ColumnId, ...]:
return ()
def prune(self, used_cols: COLUMN_SET) -> BigFrameNode:
consumed_ids = used_cols.union(self.predicate.column_references)
pruned_child = self.child.prune(consumed_ids)
return FilterNode(pruned_child, self.predicate)
def remap_vars(
self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]
) -> BigFrameNode:
return self
def remap_refs(self, mappings: Mapping[bfet_ids.ColumnId, bfet_ids.ColumnId]):
return dataclasses.replace(
self,
predicate=self.predicate.remap_column_refs(
mappings, allow_partial_bindings=True
),
)
@dataclasses.dataclass(frozen=True, eq=False)
class OrderByNode(UnaryNode):
by: Tuple[OrderingExpression, ...]
@property
def variables_introduced(self) -> int:
return 0
@property
def relation_ops_created(self) -> int:
# Doesnt directly create any relational operations
return 0
@property
def explicitly_ordered(self) -> bool:
return True