-
-
Notifications
You must be signed in to change notification settings - Fork 494
/
filtering.py
1994 lines (1729 loc) · 72.1 KB
/
filtering.py
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
import logging
from abc import ABC, abstractmethod
from collections.abc import Collection, Sequence
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Any, Generic, Literal, NamedTuple, TypeVar
from rotkehlchen.accounting.types import SchemaEventType
from rotkehlchen.api.v1.types import IncludeExcludeFilterData
from rotkehlchen.assets.asset import Asset
from rotkehlchen.assets.types import AssetType
from rotkehlchen.assets.utils import IgnoredAssetsHandling
from rotkehlchen.chain.ethereum.modules.nft.structures import NftLpHandling
from rotkehlchen.chain.evm.types import EvmAccount
from rotkehlchen.db.constants import (
ETH_STAKING_EVENT_FIELDS,
EVM_EVENT_FIELDS,
HISTORY_BASE_ENTRY_FIELDS,
HISTORY_MAPPING_KEY_STATE,
HISTORY_MAPPING_STATE_CUSTOMIZED,
)
from rotkehlchen.errors.serialization import DeserializationError
from rotkehlchen.fval import FVal
from rotkehlchen.globaldb.cache import compute_cache_key
from rotkehlchen.history.events.structures.base import HistoryBaseEntryType
from rotkehlchen.history.events.structures.evm_event import EvmProduct
from rotkehlchen.history.events.structures.types import HistoryEventSubType, HistoryEventType
from rotkehlchen.logging import RotkehlchenLogsAdapter
from rotkehlchen.types import (
SUPPORTED_CHAIN_IDS,
AssetMovementCategory,
CacheType,
ChainID,
ChecksumEvmAddress,
EVMTxHash,
Location,
OptionalBlockchainAddress,
OptionalChainAddress,
SupportedBlockchain,
Timestamp,
TradeType,
)
from rotkehlchen.utils.misc import ts_now
class InvalidFilter(Exception):
"""Raised if an invalid filter combination has been given"""
logger = logging.getLogger(__name__)
log = RotkehlchenLogsAdapter(logger)
ALL_EVENTS_DATA_JOIN = """FROM history_events
LEFT JOIN evm_events_info ON history_events.identifier=evm_events_info.identifier
LEFT JOIN eth_staking_events_info ON history_events.identifier=eth_staking_events_info.identifier """ # noqa: E501
EVM_EVENT_JOIN = 'FROM history_events INNER JOIN evm_events_info ON history_events.identifier=evm_events_info.identifier ' # noqa: E501
ETH_STAKING_EVENT_JOIN = 'FROM history_events INNER JOIN eth_staking_events_info ON history_events.identifier=eth_staking_events_info.identifier ' # noqa: E501
ETH_DEPOSIT_EVENT_JOIN = ALL_EVENTS_DATA_JOIN
T = TypeVar('T')
V = TypeVar('V')
T_FilterQ = TypeVar('T_FilterQ', bound='DBFilterQuery')
T_HistoryBaseEntryFilterQ = TypeVar('T_HistoryBaseEntryFilterQ', bound='HistoryBaseEntryFilterQuery') # noqa: E501
T_EthSTakingFilterQ = TypeVar('T_EthSTakingFilterQ', bound='EthStakingEventFilterQuery')
class DBFilterOrder(NamedTuple):
rules: list[tuple[str, bool]]
case_sensitive: bool
def prepare(self) -> str:
querystr = 'ORDER BY '
for idx, (attribute, ascending) in enumerate(self.rules):
if idx != 0:
querystr += ','
if attribute in {'amount', 'fee', 'rate', 'last_price', 'last_price_asset', 'manual_price'}: # noqa: E501
order_by = f'CAST({attribute} AS REAL)'
else:
order_by = attribute
if self.case_sensitive is False:
querystr += f'{order_by} COLLATE NOCASE {"ASC" if ascending else "DESC"}'
else:
querystr += f'{order_by} {"ASC" if ascending else "DESC"}'
return querystr
class DBFilterPagination(NamedTuple):
limit: int
offset: int
def prepare(self) -> str:
return f'LIMIT {self.limit} OFFSET {self.offset}'
class DBFilterGroupBy(NamedTuple):
field_name: str
def prepare(self) -> str:
return f'GROUP BY {self.field_name}'
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBFilter:
and_op: bool
def prepare(self) -> tuple[list[str], Collection[Any]]:
raise NotImplementedError('prepare should be implemented by subclasses')
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBNestedFilter(DBFilter):
"""Filter that allows combination of multiple subfilters with different operands."""
filters: list[DBFilter]
def prepare(self) -> tuple[list[str], list[Any]]:
filterstrings = []
bindings: list[Any] = []
for single_filter in self.filters:
filters, single_bindings = single_filter.prepare()
if len(filters) == 0:
continue
operator = ' AND ' if single_filter.and_op else ' OR '
filterstrings.append(f'({operator.join(filters)})')
bindings.extend(single_bindings)
return filterstrings, bindings
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBTimestampFilter(DBFilter):
from_ts: Timestamp | None = None
to_ts: Timestamp | None = None
scaling_factor: FVal | None = None
timestamp_field: str | None = None
def prepare(self) -> tuple[list[str], list[Any]]:
filters = []
bindings = []
timestamp_field = 'timestamp'
if self.timestamp_field is not None:
timestamp_field = self.timestamp_field
if self.from_ts is not None:
filters.append(f'{timestamp_field} >= ?')
from_ts = self.from_ts
if self.scaling_factor is not None:
from_ts = Timestamp((from_ts * self.scaling_factor).to_int(exact=False))
bindings.append(from_ts)
if self.to_ts is not None:
filters.append(f'{timestamp_field} <= ?')
to_ts = self.to_ts
if self.scaling_factor is not None:
to_ts = Timestamp((to_ts * self.scaling_factor).to_int(exact=False))
bindings.append(to_ts)
return filters, bindings
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBEvmTransactionJoinsFilter(DBFilter):
"""This join finds transactions involving any of the address/chain combos.
Including internal ones. This uses the mappings we create in the DB at transaction
addition to signify relevant addresses for a transaction.
"""
accounts: list[EvmAccount]
def prepare(self) -> tuple[list[str], list[Any]]:
query_filters: list[str] = []
bindings: list[ChecksumEvmAddress | int] = []
query_filter_str = (
'INNER JOIN evmtx_address_mappings WHERE '
'evm_transactions.identifier=evmtx_address_mappings.tx_id AND ('
)
individual_queries = []
for address, _ in self.accounts: # chain not used here but accessed earlier up the chain
individual_query = '(evmtx_address_mappings.address = ?'
bindings.append(address)
individual_query += ')'
individual_queries.append(individual_query)
query_filter_str += ' OR '.join(individual_queries)
query_filters.append(query_filter_str + ')')
query = f' {" ".join(query_filters)} '
return [query], bindings
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBTransactionsPendingDecodingFilter(DBFilter):
"""
This filter is used to find the ethereum transactions that have not been decoded yet
using the query in `TRANSACTIONS_MISSING_DECODING_QUERY`. It allows filtering by chain.
"""
chain_id: ChainID | None
def prepare(self) -> tuple[list[str], list[Any]]:
query_filters = ['B.tx_id is NULL']
bindings: list[int] = []
if self.chain_id is not None:
bindings.append(self.chain_id.serialize_for_db())
query_filters.append('C.chain_id=?')
query = ' AND '.join(query_filters)
return [query], bindings
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBEvmTransactionHashFilter(DBFilter):
tx_hash: EVMTxHash | None = None
def prepare(self) -> tuple[list[str], list[Any]]:
if self.tx_hash is None:
return [], []
return ['evm_transactions.tx_hash=?'], [self.tx_hash]
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBEvmChainIDFilter(DBFilter):
chain_id: SUPPORTED_CHAIN_IDS | None = None
table_name: str | None = None
def prepare(self) -> tuple[list[str], list[Any]]:
if self.chain_id is None:
return [], []
prefix = f'{self.table_name}.' if self.table_name else ''
return [f'{prefix}chain_id=?'], [self.chain_id.serialize_for_db()]
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBReportDataReportIDFilter(DBFilter):
report_id: str | int | None = None
def prepare(self) -> tuple[list[str], list[Any]]:
if self.report_id is None:
return [], []
if isinstance(self.report_id, str):
try:
value = int(self.report_id)
except DeserializationError as e:
log.error(f'Failed to filter a DB transaction query by report_id: {e!s}')
return [], []
else:
value = self.report_id
return ['report_id=?'], [value]
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBReportDataEventTypeFilter(DBFilter):
event_type: str | SchemaEventType | None = None
def prepare(self) -> tuple[list[str], list[Any]]:
if self.event_type is None:
return [], []
if isinstance(self.event_type, str):
try:
value = SchemaEventType.deserialize_from_db(self.event_type)
except DeserializationError as e:
log.error(f'Failed to filter a DB transaction query by event_type: {e!s}')
return [], []
else:
value = self.event_type
return ['event_type=?'], [str(value)]
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBLocationFilter(DBFilter):
location: Location
def prepare(self) -> tuple[list[str], list[Any]]:
return ['location=?'], [self.location.serialize_for_db()]
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBNullableLocationFilter(DBFilter):
location: Location | None
def prepare(self) -> tuple[list[str], list[Any]]:
return (['location IS ?'], [None if self.location is None else self.location.serialize_for_db()]) # noqa: E501
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBSubStringFilter(DBFilter):
field: str
search_string: str
def prepare(self) -> tuple[list[str], list[Any]]:
return [f'{self.field} LIKE ?'], [f'%{self.search_string}%']
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBFilterQuery(ABC):
and_op: bool
filters: list[DBFilter]
join_clause: DBFilter | None = None
group_by: DBFilterGroupBy | None = None
order_by: DBFilterOrder | None = None
pagination: DBFilterPagination | None = None
def prepare(
self,
with_pagination: bool = True,
with_order: bool = True,
with_group_by: bool = False,
special_free_query: bool = False,
) -> tuple[str, list[Any]]:
"""Prepares a filter by converting the filters to a query string
Can be configured to:
- with_pagination: Use or not the pagination filters
- with_order: Use or not the order by filters
- with_group_by: Use or not the group by filters
- special_free_query: This is only for history events query and since we have quite
a complicated query in the backend to count the limited grouped history events, there is
no need to rerun the ignored assets filter as it's already part of the inner
query in order to not count ignored/spam assets in the limit of free events.
TODO: Quite hacky. Improve this.
"""
query_parts = []
bindings: list[Any] = []
filterstrings = []
if self.join_clause is not None:
join_querystr, single_bindings = self.join_clause.prepare()
query_parts.append(join_querystr[0])
bindings.extend(single_bindings)
for fil in self.filters:
if special_free_query and isinstance(fil, DBIgnoredAssetsFilter):
continue # skip subtable select filter as it's already applied
filters, single_bindings = fil.prepare()
if len(filters) == 0:
continue
operator = ' AND ' if fil.and_op else ' OR '
filterstrings.append(f'({operator.join(filters)})')
bindings.extend(single_bindings)
if len(filterstrings) != 0:
operator = ' AND ' if self.and_op else ' OR '
filter_query = f'{"WHERE " if self.join_clause is None else "AND ("}{operator.join(filterstrings)}{"" if self.join_clause is None else ")"}' # noqa: E501
query_parts.append(filter_query)
if with_group_by and self.group_by is not None:
groupby_query = self.group_by.prepare()
query_parts.append(groupby_query)
if with_order and self.order_by is not None:
orderby_query = self.order_by.prepare()
query_parts.append(orderby_query)
if with_pagination and self.pagination is not None:
pagination_query = self.pagination.prepare()
query_parts.append(pagination_query)
return ' '.join(query_parts), bindings
@classmethod
def create(
cls: type[T_FilterQ],
and_op: bool,
limit: int | None,
offset: int | None,
order_by_case_sensitive: bool = True,
order_by_rules: list[tuple[str, bool]] | None = None,
group_by_field: str | None = None,
) -> T_FilterQ:
if limit is None or offset is None:
pagination = None
else:
pagination = DBFilterPagination(limit=limit, offset=offset)
group_by = None
if group_by_field is not None:
group_by = DBFilterGroupBy(field_name=group_by_field)
order_by = None
if order_by_rules is not None:
order_by = DBFilterOrder(rules=order_by_rules, case_sensitive=order_by_case_sensitive)
return cls(
and_op=and_op,
filters=[],
group_by=group_by,
order_by=order_by,
pagination=pagination,
)
class FilterWithTimestamp:
timestamp_filter: DBTimestampFilter
@property
def from_ts(self) -> Timestamp:
if self.timestamp_filter.from_ts is None:
return Timestamp(0)
return self.timestamp_filter.from_ts
@from_ts.setter
def from_ts(self, from_ts: Timestamp | None) -> None:
self.timestamp_filter.from_ts = from_ts
@property
def to_ts(self) -> Timestamp:
if self.timestamp_filter.to_ts is None:
return ts_now()
return self.timestamp_filter.to_ts
@to_ts.setter
def to_ts(self, to_ts: Timestamp | None) -> None:
self.timestamp_filter.to_ts = to_ts
class FilterWithLocation:
location_filter: DBLocationFilter | None = None
@property
def location(self) -> Location | None:
if self.location_filter is None:
return None
return self.location_filter.location
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class EvmTransactionsFilterQuery(DBFilterQuery, FilterWithTimestamp):
@property
def accounts(self) -> list[EvmAccount] | None:
if not isinstance(self.join_clause, DBEvmTransactionJoinsFilter):
return None
return self.join_clause.accounts
@property
def chain_id(self) -> SUPPORTED_CHAIN_IDS | None:
if isinstance(self.filters[-1], DBEvmChainIDFilter):
return self.filters[-1].chain_id
return None
@classmethod
def make(
cls: type['EvmTransactionsFilterQuery'],
and_op: bool = True,
order_by_rules: list[tuple[str, bool]] | None = None,
limit: int | None = None,
offset: int | None = None,
accounts: list[EvmAccount] | None = None,
from_ts: Timestamp | None = None,
to_ts: Timestamp | None = None,
tx_hash: EVMTxHash | None = None,
chain_id: SUPPORTED_CHAIN_IDS | None = None,
) -> 'EvmTransactionsFilterQuery':
"""May raise:
- InvalidFilter for invalid combination of filters
"""
if order_by_rules is None:
order_by_rules = [('timestamp', True)]
filter_query = cls.create(
and_op=and_op,
limit=limit,
offset=offset,
order_by_rules=order_by_rules,
)
# Create the timestamp filter so that from/to ts works. But add it only if needed
filter_query.timestamp_filter = DBTimestampFilter(
and_op=True,
from_ts=from_ts,
to_ts=to_ts,
)
filters: list[DBFilter] = []
if tx_hash is not None: # tx_hash means single result so make it as single filter
filters.append(DBEvmTransactionHashFilter(and_op=True, tx_hash=tx_hash))
if chain_id is not None: # keep it as last (see chain_id property of this filter)
filters.append(DBEvmChainIDFilter(and_op=True, chain_id=chain_id, table_name='evm_transactions')) # noqa: E501
else:
if accounts is not None:
if filter_query.join_clause is not None: # atm "should not happen"
raise InvalidFilter('Unable to filter by account due to conflicting filter')
filter_query.join_clause = DBEvmTransactionJoinsFilter(
and_op=False,
accounts=accounts,
)
filters.append(filter_query.timestamp_filter)
if chain_id is not None: # keep it as last (see chain_id property of this filter)
filters.append(DBEvmChainIDFilter(
and_op=True,
table_name='evm_transactions',
chain_id=chain_id,
))
filter_query.filters = filters
return filter_query
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBAssetFilter(DBFilter):
asset: Asset
asset_key: str
def prepare(self) -> tuple[list[str], list[Any]]:
return [f'{self.asset_key}=?'], [self.asset.identifier]
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBIgnoreValuesFilter(DBFilter):
column: str
values: Collection[Any]
def prepare(self) -> tuple[list[str], Collection[Any]]:
if len(self.values) == 0:
return [], []
return [f'{self.column} NOT IN ({", ".join(["?"] * len(self.values))})'], self.values
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBEth2ValidatorIndicesFilter(DBFilter):
"""A filter for Eth2 validator indices"""
validators: set[int] | None
def prepare(self) -> tuple[list[str], list[Any]]:
if self.validators is None:
return [], []
questionmarks = '?' * len(self.validators)
return [f'validator_index IN ({",".join(questionmarks)})'], list(self.validators)
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBTypeFilter(DBFilter):
"""A filter for type/category/HistoryBaseEntry enums"""
filter_types: list[TradeType] | list[AssetMovementCategory]
type_key: Literal['type', 'subtype', 'category']
def prepare(self) -> tuple[list[str], list[Any]]:
if len(self.filter_types) == 1:
return [f'{self.type_key}=?'], [self.filter_types[0].serialize_for_db()]
return (
[f'{self.type_key} IN ({", ".join(["?"] * len(self.filter_types))})'],
[entry.serialize_for_db() for entry in self.filter_types],
)
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBEqualsFilter(DBFilter):
"""Filter a column by comparing its column to its value for equality."""
column: str
value: str | (bytes | (int | bool))
alias: str | None = None
def prepare(self) -> tuple[list[str], list[Any]]:
key_name = self.column
if self.alias is not None:
key_name = f'{self.alias}.{key_name}'
return [f'{key_name}=?'], [self.value]
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBMultiValueFilter(Generic[T], DBFilter):
"""Filter a column having a value out of a selection of values"""
column: str
values: Sequence[T]
operator: Literal['IN', 'NOT IN'] = 'IN'
def prepare(self) -> tuple[list[str], Sequence[T]]:
suffix = '' # for NOT IN comparison remember NULL is a special case
if self.operator == 'NOT IN':
suffix = f' OR {self.column} IS NULL'
return (
[f'{self.column} {self.operator} ({", ".join(["?"] * len(self.values))}){suffix}'],
self.values,
)
class DBMultiStringFilter(DBMultiValueFilter[str]):
"""Filter a column having a string value out of a selection of values"""
class DBMultiBytesFilter(DBMultiValueFilter[bytes]):
"""Filter a column having a bytes value out of a selection of values"""
class DBMultiIntegerFilter(DBMultiValueFilter[int]):
"""Filter a column having an integer value out of a selection of values"""
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBOptionalChainAddressesFilter(DBFilter):
"""Filter the address column by a selection of optional chain addresses"""
optional_chain_addresses: (
list[OptionalChainAddress] |
list[OptionalBlockchainAddress] |
None
)
def prepare(self) -> tuple[list[str], list[str]]:
query_filters = []
bindings: list[str | ChecksumEvmAddress] = []
if self.optional_chain_addresses is not None:
for optional_chain_address in self.optional_chain_addresses:
query_part = 'address = ?'
bindings.append(optional_chain_address.address)
if optional_chain_address.blockchain is not None:
query_part += ' AND blockchain = ?'
bindings.append(optional_chain_address.blockchain.value)
query_filters.append(query_part)
return query_filters, bindings
class TradesFilterQuery(DBFilterQuery, FilterWithTimestamp, FilterWithLocation):
@classmethod
def make(
cls: type['TradesFilterQuery'],
and_op: bool = True,
order_by_rules: list[tuple[str, bool]] | None = None,
limit: int | None = None,
offset: int | None = None,
from_ts: Timestamp | None = None,
to_ts: Timestamp | None = None,
base_assets: tuple[Asset, ...] | None = None,
quote_assets: tuple[Asset, ...] | None = None,
trade_type: list[TradeType] | None = None,
location: Location | None = None,
trades_idx_to_ignore: set[str] | None = None,
exclude_ignored_assets: bool = False,
) -> 'TradesFilterQuery':
if order_by_rules is None:
order_by_rules = [('timestamp', True)]
filter_query = cls.create(
and_op=and_op,
limit=limit,
offset=offset,
order_by_rules=order_by_rules,
)
filters: list[DBFilter] = []
if base_assets is not None:
if len(base_assets) == 1:
filters.append(
DBAssetFilter(and_op=True, asset=base_assets[0], asset_key='base_asset'),
)
else:
filters.append(
DBMultiStringFilter(
and_op=True,
column='base_asset',
values=[asset.identifier for asset in base_assets],
),
)
if quote_assets is not None:
if len(quote_assets) == 1:
filters.append(
DBAssetFilter(and_op=True, asset=quote_assets[0], asset_key='quote_asset'),
)
else:
filters.append(
DBMultiStringFilter(
and_op=True,
column='quote_asset',
values=[asset.identifier for asset in quote_assets],
),
)
if trade_type is not None:
filters.append(DBTypeFilter(and_op=True, filter_types=trade_type, type_key='type'))
if location is not None:
filter_query.location_filter = DBLocationFilter(and_op=True, location=location)
filters.append(filter_query.location_filter)
if trades_idx_to_ignore is not None:
filters.append(DBIgnoreValuesFilter(
and_op=True,
column='id',
values=trades_idx_to_ignore,
))
if exclude_ignored_assets is True:
filters.extend((
DBIgnoredAssetsFilter(
and_op=True,
asset_key='base_asset',
operator='NOT IN',
), DBIgnoredAssetsFilter(
and_op=True,
asset_key='quote_asset',
operator='NOT IN',
)))
filter_query.timestamp_filter = DBTimestampFilter(
and_op=True,
from_ts=from_ts,
to_ts=to_ts,
)
filters.append(filter_query.timestamp_filter)
filter_query.filters = filters
return filter_query
class AssetMovementsFilterQuery(DBFilterQuery, FilterWithTimestamp, FilterWithLocation):
@classmethod
def make(
cls: type['AssetMovementsFilterQuery'],
and_op: bool = True,
order_by_rules: list[tuple[str, bool]] | None = None,
limit: int | None = None,
offset: int | None = None,
from_ts: Timestamp | None = None,
to_ts: Timestamp | None = None,
assets: tuple[Asset, ...] | None = None,
action: list[AssetMovementCategory] | None = None,
location: Location | None = None,
exclude_ignored_assets: bool = False,
) -> 'AssetMovementsFilterQuery':
if order_by_rules is None:
order_by_rules = [('timestamp', True)]
filter_query = cls.create(
and_op=and_op,
limit=limit,
offset=offset,
order_by_rules=order_by_rules,
)
filters: list[DBFilter] = []
if assets is not None:
if len(assets) == 1:
filters.append(DBAssetFilter(and_op=True, asset=assets[0], asset_key='asset'))
else:
filters.append(
DBMultiStringFilter(
and_op=True,
column='asset',
values=[asset.identifier for asset in assets],
),
)
if action is not None:
filters.append(DBTypeFilter(and_op=True, filter_types=action, type_key='category'))
if location is not None:
filter_query.location_filter = DBLocationFilter(and_op=True, location=location)
filters.append(filter_query.location_filter)
if exclude_ignored_assets is True:
filters.append(DBIgnoredAssetsFilter(
and_op=True,
asset_key='asset',
operator='NOT IN',
))
filter_query.timestamp_filter = DBTimestampFilter(
and_op=True,
from_ts=from_ts,
to_ts=to_ts,
)
filters.append(filter_query.timestamp_filter)
filter_query.filters = filters
return filter_query
class Eth2DailyStatsFilterQuery(DBFilterQuery, FilterWithTimestamp):
@classmethod
def make(
cls: type['Eth2DailyStatsFilterQuery'],
and_op: bool = True,
order_by_rules: list[tuple[str, bool]] | None = None,
limit: int | None = None,
offset: int | None = None,
from_ts: Timestamp | None = None,
to_ts: Timestamp | None = None,
validator_indices: set[int] | None = None,
) -> 'Eth2DailyStatsFilterQuery':
if order_by_rules is None:
order_by_rules = [('timestamp', True)]
filter_query = cls.create(
and_op=and_op,
limit=limit,
offset=offset,
order_by_rules=order_by_rules,
)
filters: list[DBFilter] = []
filter_query.timestamp_filter = DBTimestampFilter(
and_op=True,
from_ts=from_ts,
to_ts=to_ts,
)
filters.extend((
filter_query.timestamp_filter,
DBEth2ValidatorIndicesFilter(and_op=True, validators=validator_indices)))
filter_query.filters = filters
return filter_query
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class ReportDataFilterQuery(DBFilterQuery, FilterWithTimestamp):
@property
def report_id_filter(self) -> DBReportDataReportIDFilter | None:
if len(self.filters) >= 1 and isinstance(self.filters[0], DBReportDataReportIDFilter):
return self.filters[0]
return None
@property
def event_type_filter(self) -> DBReportDataEventTypeFilter | None:
if len(self.filters) >= 2 and isinstance(self.filters[1], DBReportDataEventTypeFilter):
return self.filters[1]
return None
@property
def report_id(self) -> str | int | None:
report_id_filter = self.report_id_filter
if report_id_filter is None:
return None
return report_id_filter.report_id
@property
def event_type(self) -> str | SchemaEventType | None:
event_type_filter = self.event_type_filter
if event_type_filter is None:
return None
return event_type_filter.event_type
@classmethod
def make(
cls: type['ReportDataFilterQuery'],
and_op: bool = True,
order_by_rules: list[tuple[str, bool]] | None = None,
limit: int | None = None,
offset: int | None = None,
report_id: int | None = None,
event_type: str | None = None,
from_ts: Timestamp | None = None,
to_ts: Timestamp | None = None,
) -> 'ReportDataFilterQuery':
if order_by_rules is None:
order_by_rules = [('timestamp', True)]
filter_query = cls.create(
and_op=and_op,
limit=limit,
offset=offset,
order_by_rules=order_by_rules,
)
filters: list[DBFilter] = []
if report_id is not None:
filters.append(DBReportDataReportIDFilter(and_op=True, report_id=report_id))
if event_type is not None:
filters.append(DBReportDataEventTypeFilter(and_op=True, event_type=event_type))
filter_query.timestamp_filter = DBTimestampFilter(
and_op=True,
from_ts=from_ts,
to_ts=to_ts,
)
filters.append(filter_query.timestamp_filter)
filter_query.filters = filters
return filter_query
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class DBNullFilter(DBFilter):
columns: list[str]
verb: Literal['IS', 'IS NOT'] = 'IS'
def prepare(self) -> tuple[list[str], list[Any]]:
return [f'{column} {self.verb} NULL' for column in self.columns], []
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class HistoryEventCustomizedOnlyJoinsFilter(DBFilter):
"""This join finds customized history events (exclusively)."""
def prepare(self) -> tuple[list[str], list[Any]]:
query = (
'INNER JOIN history_events_mappings '
'ON history_events_mappings.parent_identifier = history_events_identifier '
'WHERE history_events_mappings.name = ? AND history_events_mappings.value = ?'
)
bindings: list[str | int] = [HISTORY_MAPPING_KEY_STATE, HISTORY_MAPPING_STATE_CUSTOMIZED]
return [query], bindings
class HistoryBaseEntryFilterQuery(DBFilterQuery, FilterWithTimestamp, FilterWithLocation, ABC):
@classmethod
def make(
cls: type[T_HistoryBaseEntryFilterQ],
and_op: bool = True,
order_by_rules: list[tuple[str, bool]] | None = None,
limit: int | None = None,
offset: int | None = None,
from_ts: Timestamp | None = None,
to_ts: Timestamp | None = None,
assets: tuple[Asset, ...] | None = None,
event_types: list[HistoryEventType] | None = None,
event_subtypes: list[HistoryEventSubType] | None = None,
exclude_subtypes: list[HistoryEventSubType] | None = None,
location: Location | None = None,
location_labels: list[str] | None = None,
excluded_locations: list[Location] | None = None,
ignored_ids: list[str] | None = None,
null_columns: list[str] | None = None,
event_identifiers: list[str] | None = None,
entry_types: IncludeExcludeFilterData | None = None,
exclude_ignored_assets: bool = False,
customized_events_only: bool = False,
) -> T_HistoryBaseEntryFilterQ:
"""May raise:
- InvalidFilter for invalid combination of filters
"""
if order_by_rules is None:
order_by_rules = [('timestamp', True), ('sequence_index', True)]
filter_query = cls.create(
and_op=and_op,
limit=limit,
offset=offset,
order_by_rules=order_by_rules,
group_by_field='event_identifier',
)
if customized_events_only is True:
if filter_query.join_clause is not None: # atm "should not happen"
raise InvalidFilter('Unable to filter by customized events due to conflicting filter') # noqa: E501
filter_query.join_clause = HistoryEventCustomizedOnlyJoinsFilter(and_op=True)
filters: list[DBFilter] = []
if assets is not None:
if len(assets) == 1:
filters.append(DBAssetFilter(and_op=True, asset=assets[0], asset_key='asset'))
else:
filters.append(
DBMultiStringFilter(
and_op=True,
column='asset',
values=[asset.identifier for asset in assets],
),
)
if entry_types is not None:
filters.append(DBMultiIntegerFilter(
and_op=True,
column='entry_type',
values=[x.value for x in entry_types.values],
operator=entry_types.operator,
))
if event_types is not None:
filters.append(DBMultiStringFilter(
and_op=True,
column='type',
values=[x.serialize() for x in event_types],
operator='IN',
))
if event_subtypes is not None:
filters.append(DBMultiStringFilter(
and_op=True,
column='subtype',
values=[x.serialize() for x in event_subtypes],
operator='IN',
))
if exclude_subtypes is not None:
filters.append(DBMultiStringFilter(
and_op=True,
column='subtype',
values=[x.serialize() for x in exclude_subtypes],
operator='NOT IN',
))
if location is not None:
filter_query.location_filter = DBLocationFilter(and_op=True, location=location)
filters.append(filter_query.location_filter)
if excluded_locations is not None:
filters.append(DBMultiStringFilter(
and_op=True,
column='location',
values=[x.serialize_for_db() for x in excluded_locations],
operator='NOT IN',
))
if location_labels is not None:
filters.append(DBMultiStringFilter(
and_op=True,
column='location_label',
values=location_labels,
operator='IN',
))