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 pathnodes.py
More file actions
1766 lines (1438 loc) · 54.8 KB
/
nodes.py
File metadata and controls
1766 lines (1438 loc) · 54.8 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 (
AbstractSet,
Callable,
cast,
Iterable,
Mapping,
Optional,
Sequence,
Tuple,
)
import google.cloud.bigquery as bq
from bigframes.core import agg_expressions, identifiers, local_data, sequences
from bigframes.core.bigframe_node import BigFrameNode, COLUMN_SET
import bigframes.core.expression as ex
from bigframes.core.field import Field
from bigframes.core.ordering import OrderingExpression, RowOrdering
import bigframes.core.slices as slices
import bigframes.core.window_spec as window
import bigframes.dtypes
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
class AdditiveNode:
"""Definition of additive - if you drop added_fields, you end up with the descendent.
.. code-block:: text
AdditiveNode (fields: a, b, c; added_fields: c)
|
| additive_base
V
BigFrameNode (fields: a, b)
"""
@property
@abc.abstractmethod
def added_fields(self) -> Tuple[Field, ...]:
...
@property
@abc.abstractmethod
def additive_base(self) -> BigFrameNode:
...
@abc.abstractmethod
def replace_additive_base(self, BigFrameNode) -> BigFrameNode:
...
@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) -> Sequence[Field]:
return self.child.fields
@property
def explicitly_ordered(self) -> bool:
return self.child.explicitly_ordered
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> UnaryNode:
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 is_noop(self) -> bool:
"""Returns whether this node doesn't actually change the results."""
# TODO: Handle tail case.
return (
((not self.start) or (self.start == 0))
and (self.step == 1)
and ((self.stop is None) or (self.stop == self.child.row_count))
)
@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[identifiers.ColumnId, ...]:
return ()
@property
def referenced_ids(self) -> COLUMN_SET:
return frozenset()
def remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> SliceNode:
return self
def remap_refs(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> SliceNode:
return self
@dataclasses.dataclass(frozen=True, eq=False)
class InNode(BigFrameNode, AdditiveNode):
"""
Special Join Type that only returns rows from the left side, as well as adding a bool column indicating whether a match exists on the right side.
Modelled separately from join node, as this operation preserves row identity.
"""
left_child: BigFrameNode
right_child: BigFrameNode
left_col: ex.DerefOp
right_col: ex.DerefOp
indicator_col: identifiers.ColumnId
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 False
@property
def explicitly_ordered(self) -> bool:
# Preserves left ordering always
return True
@property
def added_fields(self) -> Tuple[Field, ...]:
return (Field(self.indicator_col, bigframes.dtypes.BOOL_DTYPE, nullable=False),)
@property
def fields(self) -> Sequence[Field]:
return sequences.ChainedSequence(
self.left_child.fields,
self.added_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 1
@property
def joins(self) -> bool:
return True
@property
def row_count(self) -> Optional[int]:
return self.left_child.row_count
@property
def node_defined_ids(self) -> Tuple[identifiers.ColumnId, ...]:
return (self.indicator_col,)
@property
def referenced_ids(self) -> COLUMN_SET:
return frozenset({self.left_col.id, self.right_col.id})
@property
def additive_base(self) -> BigFrameNode:
return self.left_child
@property
def joins_nulls(self) -> bool:
left_nullable = self.left_child.field_by_id[self.left_col.id].nullable
right_nullable = self.right_child.field_by_id[self.right_col.id].nullable
return left_nullable or right_nullable
@property
def _node_expressions(self):
return (self.left_col, self.right_col)
def replace_additive_base(self, node: BigFrameNode):
return dataclasses.replace(self, left_child=node)
def transform_children(self, t: Callable[[BigFrameNode], BigFrameNode]) -> InNode:
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 remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> InNode:
return dataclasses.replace(
self, indicator_col=mappings.get(self.indicator_col, self.indicator_col)
)
def remap_refs(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> InNode:
return dataclasses.replace(
self,
left_col=self.left_col.remap_column_refs(
mappings, allow_partial_bindings=True
),
right_col=self.right_col.remap_column_refs(
mappings, allow_partial_bindings=True
),
) # type: ignore
@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"]
propogate_order: bool
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:
return self.propogate_order
@functools.cached_property
def fields(self) -> Sequence[Field]:
left_fields: Iterable[Field] = self.left_child.fields
if self.type in ("right", "outer"):
left_fields = map(lambda x: x.with_nullable(), left_fields)
right_fields: Iterable[Field] = self.right_child.fields
if self.type in ("left", "outer"):
right_fields = map(lambda x: x.with_nullable(), right_fields)
return (*left_fields, *right_fields)
@property
def joins_nulls(self) -> bool:
for left_ref, right_ref in self.conditions:
if (
self.left_child.field_by_id[left_ref.id].nullable
and self.right_child.field_by_id[right_ref.id].nullable
):
return True
return False
@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[identifiers.ColumnId, ...]:
return ()
@property
def referenced_ids(self) -> COLUMN_SET:
return frozenset(
itertools.chain.from_iterable(
(*l_cond.column_references, *r_cond.column_references)
for l_cond, r_cond in self.conditions
)
)
@property
def consumed_ids(self) -> COLUMN_SET:
return frozenset(*self.ids, *self.referenced_ids)
@property
def _node_expressions(self):
return tuple(itertools.chain.from_iterable(self.conditions))
def transform_children(self, t: Callable[[BigFrameNode], BigFrameNode]) -> JoinNode:
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 remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> JoinNode:
return self
def remap_refs(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> JoinNode:
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[identifiers.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) -> Sequence[Field]:
# TODO: Output names should probably be aligned beforehand or be part of concat definition
# TODO: Handle nullability
return tuple(
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[identifiers.ColumnId, ...]:
return self.output_ids
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> ConcatNode:
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 remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> ConcatNode:
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[identifiers.ColumnId, identifiers.ColumnId]
) -> ConcatNode:
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: identifiers.ColumnId = identifiers.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) -> Sequence[Field]:
return (
Field(self.output_id, next(iter(self.start.fields)).dtype, nullable=False),
)
@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[identifiers.ColumnId, ...]:
return (self.output_id,)
@property
def defines_namespace(self) -> bool:
return True
def transform_children(
self, t: Callable[[BigFrameNode], BigFrameNode]
) -> FromRangeNode:
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 remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> FromRangeNode:
return dataclasses.replace(
self, output_id=mappings.get(self.output_id, self.output_id)
)
def remap_refs(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> FromRangeNode:
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]) -> LeafNode:
return self
class ScanItem(typing.NamedTuple):
id: identifiers.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
def with_id(self, id: identifiers.ColumnId) -> ScanItem:
return ScanItem(id, self.dtype, self.source_id)
def with_source_id(self, source_id: str) -> ScanItem:
return ScanItem(self.id, self.dtype, source_id)
@dataclasses.dataclass(frozen=True)
class ScanList:
"""
Defines the set of columns to scan from a source, along with the variable to bind the columns to.
"""
items: typing.Tuple[ScanItem, ...]
@classmethod
def from_items(cls, items: Iterable[ScanItem]) -> ScanList:
return cls(tuple(items))
def filter_cols(
self,
ids: AbstractSet[identifiers.ColumnId],
) -> ScanList:
"""Drop columns from the scan that except those in the 'ids' arg."""
result = ScanList(tuple(item for item in self.items if item.id in ids))
if len(result.items) == 0:
# We need to select something, or sql syntax breaks
result = ScanList(self.items[:1])
return result
def project(
self,
selections: Mapping[identifiers.ColumnId, identifiers.ColumnId],
) -> ScanList:
"""Project given ids from the scanlist, dropping previous bindings."""
by_id = {item.id: item for item in self.items}
result = ScanList(
tuple(
by_id[old_id].with_id(new_id) for old_id, new_id in selections.items()
)
)
if len(result.items) == 0:
# We need to select something, or sql syntax breaks
result = ScanList((self.items[:1]))
return result
def remap_source_ids(
self,
mapping: Mapping[str, str],
) -> ScanList:
items = tuple(
item.with_source_id(mapping.get(item.source_id, item.source_id))
for item in self.items
)
return ScanList(items)
def append(
self, source_id: str, dtype: bigframes.dtypes.Dtype, id: identifiers.ColumnId
) -> ScanList:
return ScanList((*self.items, ScanItem(id, dtype, source_id)))
@dataclasses.dataclass(frozen=True, eq=False)
class ReadLocalNode(LeafNode):
# TODO: Track nullability for local data
local_data_source: local_data.ManagedArrowTable
# Mapping of local ids to bfet id.
scan_list: ScanList
session: bigframes.session.Session
# Offsets are generated only if this is non-null
offsets_col: Optional[identifiers.ColumnId] = None
@property
def fields(self) -> Sequence[Field]:
fields = tuple(
Field(col_id, dtype) for col_id, dtype, _ in self.scan_list.items
)
if self.offsets_col is not None:
return tuple(
itertools.chain(
fields,
(
Field(
self.offsets_col, bigframes.dtypes.INT_DTYPE, nullable=False
),
),
)
)
return fields
@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.local_data_source.metadata.row_count
@property
def node_defined_ids(self) -> Tuple[identifiers.ColumnId, ...]:
return tuple(item.id for item in self.fields)
def remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> ReadLocalNode:
new_scan_list = ScanList(
tuple(
ScanItem(mappings.get(item.id, item.id), item.dtype, item.source_id)
for item in self.scan_list.items
)
)
new_offsets_col = (
mappings.get(self.offsets_col, self.offsets_col)
if (self.offsets_col is not None)
else None
)
return dataclasses.replace(
self, scan_list=new_scan_list, offsets_col=new_offsets_col
)
def remap_refs(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> ReadLocalNode:
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()
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,
is_physically_stored=(table.table_type in ["TABLE", "MATERIALIZED_VIEW"]),
cluster_cols=None
if table.clustering_fields is None
else tuple(table.clustering_fields),
)
def get_table_ref(self) -> bq.TableReference:
return bq.TableReference(
bq.DatasetReference(self.project_id, self.dataset_id), self.table_id
)
@property
@functools.cache
def schema_by_id(self):
return {col.name: col for col in self.physical_schema}
@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
n_rows: Optional[int] = 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) -> Sequence[Field]:
return tuple(
Field(col_id, dtype, self.source.table.schema_by_id[source_id].is_nullable)
for col_id, dtype, source_id 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.n_rows
return None
@property
def node_defined_ids(self) -> Tuple[identifiers.ColumnId, ...]:
return tuple(item.id for item in self.scan_list.items)
def remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> ReadTableNode:
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[identifiers.ColumnId, identifiers.ColumnId]
) -> ReadTableNode:
return self
def with_order_cols(self):
# Maybe the ordering should be required to always be in the scan list, and then we won't need this?
if self.source.ordering is None:
return self, orderings.RowOrdering()
order_cols = {col.sql for col in self.source.ordering.referenced_columns}
scan_cols = {col.source_id for col in self.scan_list.items}
new_scan_cols = [
ScanItem(
identifiers.ColumnId.unique(),
dtype=bigframes.dtypes.convert_schema_field(field)[1],
source_id=field.name,
)
for field in self.source.table.physical_schema
if (field.name in order_cols) and (field.name not in scan_cols)
]
new_scan_list = ScanList(items=(*self.scan_list.items, *new_scan_cols))
new_order = self.source.ordering.remap_column_refs(
{identifiers.ColumnId(item.source_id): item.id for item in new_scan_cols},
allow_partial_bindings=True,
)
return dataclasses.replace(self, scan_list=new_scan_list), new_order
@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, AdditiveNode):
col_id: identifiers.ColumnId
@property
def non_local(self) -> bool:
return True
@property
def fields(self) -> Sequence[Field]:
return sequences.ChainedSequence(self.child.fields, self.added_fields)
@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[identifiers.ColumnId, ...]:
return (self.col_id,)
@property
def referenced_ids(self) -> COLUMN_SET:
return frozenset()
@property
def added_fields(self) -> Tuple[Field, ...]:
return (Field(self.col_id, bigframes.dtypes.INT_DTYPE, nullable=False),)
@property
def additive_base(self) -> BigFrameNode:
return self.child
def replace_additive_base(self, node: BigFrameNode) -> PromoteOffsetsNode:
return dataclasses.replace(self, child=node)
def remap_vars(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> PromoteOffsetsNode:
return dataclasses.replace(self, col_id=mappings.get(self.col_id, self.col_id))
def remap_refs(
self, mappings: Mapping[identifiers.ColumnId, identifiers.ColumnId]
) -> PromoteOffsetsNode:
return self
@dataclasses.dataclass(frozen=True, eq=False)
class FilterNode(UnaryNode):
# TODO: Infer null constraints from predicate
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]: