-
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathsync.py
1431 lines (1277 loc) · 48.4 KB
/
sync.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
"""Sync module."""
import asyncio
import json
import logging
import os
import pprint
import re
import select
import sys
import time
from collections import defaultdict
from typing import AnyStr, Generator, List, Optional, Set
import click
import sqlalchemy as sa
import sqlparse
from psycopg2 import OperationalError
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from . import __version__, settings
from .base import Base, Payload
from .constants import (
DELETE,
INSERT,
MATERIALIZED_VIEW,
MATERIALIZED_VIEW_COLUMNS,
META,
PRIMARY_KEY_DELIMITER,
TG_OP,
TRUNCATE,
UPDATE,
)
from .exc import (
ForeignKeyError,
InvalidSchemaError,
InvalidTGOPError,
PrimaryKeyNotFoundError,
RDSError,
SchemaError,
)
from .node import Node, Tree
from .plugin import Plugins
from .querybuilder import QueryBuilder
from .redisqueue import RedisQueue
from .search_client import SearchClient
from .singleton import Singleton
from .transform import Transform
from .utils import (
chunks,
compiled_query,
config_loader,
exception,
get_config,
MutuallyExclusiveOption,
show_settings,
threaded,
Timer,
)
logger = logging.getLogger(__name__)
class Sync(Base, metaclass=Singleton):
"""Main application class for Sync."""
def __init__(
self,
document: dict,
verbose: bool = False,
validate: bool = True,
repl_slots: bool = True,
**kwargs,
) -> None:
"""Constructor."""
self.index: str = document.get("index") or document["database"]
self.pipeline: str = document.get("pipeline")
self.plugins: list = document.get("plugins", [])
self.nodes: dict = document.get("nodes", {})
self.setting: dict = document.get("setting")
self.mapping: dict = document.get("mapping")
self.routing: str = document.get("routing")
super().__init__(
document.get("database", self.index), verbose=verbose, **kwargs
)
self.search_client: SearchClient = SearchClient()
self.__name: str = re.sub(
"[^0-9a-zA-Z_]+", "", f"{self.database.lower()}_{self.index}"
)
self._checkpoint: int = None
self._plugins: Plugins = None
self._truncate: bool = False
self._checkpoint_file: str = os.path.join(
settings.CHECKPOINT_PATH, f".{self.__name}"
)
self.redis: RedisQueue = RedisQueue(self.__name)
self.tree: Tree = Tree(self.models)
self.tree.build(self.nodes)
if validate:
self.validate(repl_slots=repl_slots)
self.create_setting()
if self.plugins:
self._plugins: Plugins = Plugins("plugins", self.plugins)
self.query_builder: QueryBuilder = QueryBuilder(verbose=verbose)
self.count: dict = dict(xlog=0, db=0, redis=0)
def validate(self, repl_slots: bool = True) -> None:
"""Perform all validation right away."""
# ensure v2 compatible schema
if not isinstance(self.nodes, dict):
raise SchemaError(
"Incompatible schema. Please run v2 schema migration"
)
self.connect()
max_replication_slots: Optional[str] = self.pg_settings(
"max_replication_slots"
)
try:
if int(max_replication_slots) < 1:
raise TypeError
except TypeError:
raise RuntimeError(
"Ensure there is at least one replication slot defined "
"by setting max_replication_slots = 1"
)
wal_level: Optional[str] = self.pg_settings("wal_level")
if not wal_level or wal_level.lower() != "logical":
raise RuntimeError(
"Enable logical decoding by setting wal_level = logical"
)
self._can_create_replication_slot("_tmp_")
rds_logical_replication: Optional[str] = self.pg_settings(
"rds.logical_replication"
)
if (
rds_logical_replication
and rds_logical_replication.lower() == "off"
):
raise RDSError("rds.logical_replication is not enabled")
if self.index is None:
raise ValueError("Index is missing for document")
# ensure we have run bootstrap and the replication slot exists
if repl_slots and not self.replication_slots(self.__name):
raise RuntimeError(
f'Replication slot "{self.__name}" does not exist.\n'
f'Make sure you have run the "bootstrap" command.'
)
# ensure the checkpoint dirpath is valid
if not os.path.exists(settings.CHECKPOINT_PATH):
raise RuntimeError(
f"Ensure the checkpoint directory exists "
f'"{settings.CHECKPOINT_PATH}" and is readable.'
)
if not os.access(settings.CHECKPOINT_PATH, os.W_OK | os.R_OK):
raise RuntimeError(
f'Ensure the checkpoint directory "{settings.CHECKPOINT_PATH}"'
f" is read/writable"
)
self.tree.display()
for node in self.tree.traverse_breadth_first():
# ensure internal materialized view compatibility
if MATERIALIZED_VIEW in self._materialized_views(node.schema):
if MATERIALIZED_VIEW_COLUMNS != self.columns(
node.schema, MATERIALIZED_VIEW
):
raise RuntimeError(
f"Required materialized view columns not present on "
f"{MATERIALIZED_VIEW}. Please re-run bootstrap."
)
if node.schema not in self.schemas:
raise InvalidSchemaError(
f"Unknown schema name(s): {node.schema}"
)
# ensure all base tables have at least one primary_key
for table in node.base_tables:
model: sa.sql.Alias = self.models(table, node.schema)
if not model.primary_keys:
raise PrimaryKeyNotFoundError(
f"No primary key(s) for base table: {table}"
)
def analyze(self) -> None:
for node in self.tree.traverse_breadth_first():
if node.is_root:
continue
primary_keys: list = [
str(primary_key.name) for primary_key in node.primary_keys
]
foreign_keys: dict
if node.relationship.throughs:
through: Node = node.relationship.throughs[0]
foreign_keys = self.query_builder.get_foreign_keys(
node,
through,
)
else:
foreign_keys = self.query_builder.get_foreign_keys(
node.parent,
node,
)
columns: list
for index in self.indices(node.table, node.schema):
columns = foreign_keys.get(node.name, [])
if set(columns).issubset(index.get("column_names", [])) or set(
columns
).issubset(primary_keys):
sys.stdout.write(
f'Found index "{index.get("name")}" for table '
f'"{node.table}" for columns: {columns}: OK \n'
)
break
else:
columns = foreign_keys.get(node.name, [])
sys.stdout.write(
f'Missing index on table "{node.table}" for columns: '
f"{columns}\n"
)
query: str = sqlparse.format(
f'CREATE INDEX idx_{node.table}_{"_".join(columns)} ON '
f'{node.table} ({", ".join(columns)})',
reindent=True,
keyword_case="upper",
)
sys.stdout.write(f'Create one with: "\033[4m{query}\033[0m"\n')
sys.stdout.write("-" * 80)
sys.stdout.write("\n")
sys.stdout.flush()
def create_setting(self) -> None:
"""Create Elasticsearch/OpenSearch setting and mapping if required."""
self.search_client._create_setting(
self.index,
self.tree,
setting=self.setting,
mapping=self.mapping,
routing=self.routing,
)
def setup(self) -> None:
"""Create the database triggers and replication slot."""
join_queries: bool = settings.JOIN_QUERIES
self.teardown(drop_view=False)
for schema in self.schemas:
self.create_function(schema)
tables: Set = set()
# tables with user defined foreign keys
user_defined_fkey_tables: dict = {}
for node in self.tree.traverse_breadth_first():
if node.schema != schema:
continue
tables |= set(
[through.table for through in node.relationship.throughs]
)
tables |= set([node.table])
# we also need to bootstrap the base tables
tables |= set(node.base_tables)
# we want to get both the parent and the child keys here
# even though only one of them is the foreign_key.
# this is because we define both in the schema but
# do not specify which table is the foreign key.
columns: list = []
if node.relationship.foreign_key.parent:
columns.extend(node.relationship.foreign_key.parent)
if node.relationship.foreign_key.child:
columns.extend(node.relationship.foreign_key.child)
if columns:
user_defined_fkey_tables.setdefault(node.table, set())
user_defined_fkey_tables[node.table] |= set(columns)
if tables:
self.create_view(
self.index, schema, tables, user_defined_fkey_tables
)
self.create_triggers(
schema, tables=tables, join_queries=join_queries
)
self.create_replication_slot(self.__name)
def teardown(self, drop_view: bool = True) -> None:
"""Drop the database triggers and replication slot."""
join_queries: bool = settings.JOIN_QUERIES
try:
os.unlink(self._checkpoint_file)
except (OSError, FileNotFoundError):
logger.warning(
f"Checkpoint file not found: {self._checkpoint_file}"
)
self.redis.delete()
for schema in self.schemas:
tables: Set = set()
for node in self.tree.traverse_breadth_first():
tables |= set(
[through.table for through in node.relationship.throughs]
)
tables |= set([node.table])
# we also need to teardown the base tables
tables |= set(node.base_tables)
self.drop_triggers(
schema=schema, tables=tables, join_queries=join_queries
)
if drop_view:
self.drop_view(schema)
self.drop_function(schema)
self.drop_replication_slot(self.__name)
def get_doc_id(self, primary_keys: List[str], table: str) -> str:
"""
Get the Elasticsearch/OpenSearch document id from the primary keys.
""" # noqa D200
if not primary_keys:
raise PrimaryKeyNotFoundError(
f"No primary key found on table: {table}"
)
return f"{PRIMARY_KEY_DELIMITER}".join(map(str, primary_keys))
def logical_slot_changes(
self,
txmin: Optional[int] = None,
txmax: Optional[int] = None,
upto_nchanges: Optional[int] = None,
) -> None:
"""
Process changes from the db logical replication logs.
Here, we are grouping all rows of the same table and tg_op
and processing them as a group in bulk.
This is more efficient.
e.g [
{'tg_op': INSERT, 'table': A, ...},
{'tg_op': INSERT, 'table': A, ...},
{'tg_op': INSERT, 'table': A, ...},
{'tg_op': DELETE, 'table': A, ...},
{'tg_op': DELETE, 'table': A, ...},
{'tg_op': INSERT, 'table': A, ...},
{'tg_op': INSERT, 'table': A, ...},
]
We will have 3 groups being synced together in one execution
First 3 INSERT, Next 2 DELETE and then the next 2 INSERT.
Perhaps this could be improved but this is the best approach so far.
TODO: We can also process all INSERTS together and rearrange
them as done below
"""
# minimize the tmp file disk usage when calling
# PG_LOGICAL_SLOT_PEEK_CHANGES and PG_LOGICAL_SLOT_GET_CHANGES
# by limiting to a smaller batch size.
offset: int = 0
total: int = 0
limit: int = settings.LOGICAL_SLOT_CHUNK_SIZE
count: int = self.logical_slot_count_changes(
self.__name,
txmin=txmin,
txmax=txmax,
upto_nchanges=upto_nchanges,
)
while True:
changes: int = self.logical_slot_peek_changes(
self.__name,
txmin=txmin,
txmax=txmax,
upto_nchanges=upto_nchanges,
limit=limit,
offset=offset,
)
if not changes or total > count:
break
rows: list = []
for row in changes:
if re.search(r"^BEGIN", row.data) or re.search(
r"^COMMIT", row.data
):
continue
rows.append(row)
payloads: List[Payload] = []
for i, row in enumerate(rows):
logger.debug(f"txid: {row.xid}")
logger.debug(f"data: {row.data}")
# TODO: optimize this so we are not parsing the same row twice
try:
payload: Payload = self.parse_logical_slot(row.data)
except Exception as e:
logger.exception(
f"Error parsing row: {e}\nRow data: {row.data}"
)
raise
payloads.append(payload)
j: int = i + 1
if j < len(rows):
try:
payload2: Payload = self.parse_logical_slot(
rows[j].data
)
except Exception as e:
logger.exception(
f"Error parsing row: {e}\nRow data: {rows[j].data}"
)
raise
if (
payload.tg_op != payload2.tg_op
or payload.table != payload2.table
):
self.search_client.bulk(
self.index, self._payloads(payloads)
)
payloads: list = []
elif j == len(rows):
self.search_client.bulk(
self.index, self._payloads(payloads)
)
payloads: list = []
self.logical_slot_get_changes(
self.__name,
txmin=txmin,
txmax=txmax,
upto_nchanges=upto_nchanges,
limit=limit,
offset=offset,
)
offset += limit
total += len(changes)
self.count["xlog"] += len(rows)
def _root_primary_key_resolver(
self, node: Node, payload: Payload, filters: list
) -> list:
fields: dict = defaultdict(list)
primary_values: list = [
payload.data[key] for key in node.model.primary_keys
]
primary_fields: dict = dict(
zip(node.model.primary_keys, primary_values)
)
for key, value in primary_fields.items():
fields[key].append(value)
for doc_id in self.search_client._search(
self.index, node.table, fields
):
where: dict = {}
params: dict = doc_id.split(PRIMARY_KEY_DELIMITER)
for i, key in enumerate(self.tree.root.model.primary_keys):
where[key] = params[i]
filters.append(where)
return filters
def _root_foreign_key_resolver(
self, node: Node, payload: Payload, foreign_keys: dict, filters: list
) -> list:
"""
Foreign key resolver logic:
This resolver handles n-tiers relationships (n > 3) where we
insert/update a new leaf node.
For the node's parent, get the primary keys values from the
incoming payload.
Lookup this value in the meta section of Elasticsearch/OpenSearch
Then get the root node returned and re-sync that root record.
Essentially, we want to lookup the root node affected by
our insert/update operation and sync the tree branch for that root.
"""
fields: dict = defaultdict(list)
foreign_values: list = [
payload.new.get(key) for key in foreign_keys[node.name]
]
for key in [key.name for key in node.primary_keys]:
for value in foreign_values:
if value:
fields[key].append(value)
# TODO: we should combine this with the filter above
# so we only hit Elasticsearch/OpenSearch once
for doc_id in self.search_client._search(
self.index,
node.parent.table,
fields,
):
where: dict = {}
params: dict = doc_id.split(PRIMARY_KEY_DELIMITER)
for i, key in enumerate(self.tree.root.model.primary_keys):
where[key] = params[i]
filters.append(where)
return filters
def _through_node_resolver(
self, node: Node, payload: Payload, filters: list
) -> list:
"""Handle where node is a through table with a direct references to
root
"""
foreign_key_constraint = payload.foreign_key_constraint(node.model)
if self.tree.root.name in foreign_key_constraint:
filters.append(
{
foreign_key_constraint[self.tree.root.name][
"remote"
]: foreign_key_constraint[self.tree.root.name]["value"]
}
)
return filters
def _insert_op(
self, node: Node, filters: dict, payloads: List[Payload]
) -> dict:
if node.table in self.tree.tables:
if node.is_root:
for payload in payloads:
primary_values = [
payload.data[key]
for key in self.tree.root.model.primary_keys
]
primary_fields = dict(
zip(self.tree.root.model.primary_keys, primary_values)
)
filters[node.table].append(
{key: value for key, value in primary_fields.items()}
)
else:
if not node.parent:
logger.exception(
f"Could not get parent from node: {node.name}"
)
raise
try:
foreign_keys = self.query_builder.get_foreign_keys(
node.parent,
node,
)
except ForeignKeyError:
foreign_keys = self.query_builder._get_foreign_keys(
node.parent,
node,
)
_filters: list = []
for payload in payloads:
for node_key in foreign_keys[node.name]:
for parent_key in foreign_keys[node.parent.name]:
if node_key == parent_key:
filters[node.parent.table].append(
{parent_key: payload.data[node_key]}
)
_filters = self._root_foreign_key_resolver(
node, payload, foreign_keys, _filters
)
# through table with a direct references to root
if not _filters:
_filters = self._through_node_resolver(
node, payload, _filters
)
if _filters:
filters[self.tree.root.table].extend(_filters)
else:
# handle case where we insert into a through table
# set the parent as the new entity that has changed
foreign_keys = self.query_builder.get_foreign_keys(
node.parent,
node,
)
for payload in payloads:
for i, key in enumerate(foreign_keys[node.name]):
filters[node.parent.table].append(
{foreign_keys[node.parent.name][i]: payload.data[key]}
)
return filters
def _update_op(
self,
node: Node,
filters: dict,
payloads: List[dict],
) -> dict:
if node.is_root:
# Here, we are performing two operations:
# 1) Build a filter to sync the updated record(s)
# 2) Delete the old record(s) in Elasticsearch/OpenSearch if the
# primary key has changed
# 2.1) This is crucial otherwise we can have the old and new
# document in Elasticsearch/OpenSearch at the same time
docs: list = []
for payload in payloads:
primary_values: list = [
payload.data[key] for key in node.model.primary_keys
]
primary_fields: dict = dict(
zip(node.model.primary_keys, primary_values)
)
filters[node.table].append(
{key: value for key, value in primary_fields.items()}
)
old_values: list = []
for key in self.tree.root.model.primary_keys:
if key in payload.old.keys():
old_values.append(payload.old[key])
new_values = [
payload.new[key]
for key in self.tree.root.model.primary_keys
]
if (
len(old_values) == len(new_values)
and old_values != new_values
):
doc: dict = {
"_id": self.get_doc_id(
old_values, self.tree.root.table
),
"_index": self.index,
"_op_type": "delete",
}
if self.routing:
doc["_routing"] = old_values[self.routing]
if (
self.search_client.major_version < 7
and not self.search_client.is_opensearch
):
doc["_type"] = "_doc"
docs.append(doc)
if docs:
self.search_client.bulk(self.index, docs)
else:
# update the child tables
for payload in payloads:
_filters: list = []
_filters = self._root_primary_key_resolver(
node, payload, _filters
)
# also handle foreign_keys
if node.parent:
try:
foreign_keys = self.query_builder.get_foreign_keys(
node.parent,
node,
)
except ForeignKeyError:
foreign_keys = self.query_builder._get_foreign_keys(
node.parent,
node,
)
_filters = self._root_foreign_key_resolver(
node, payload, foreign_keys, _filters
)
if _filters:
filters[self.tree.root.table].extend(_filters)
return filters
def _delete_op(
self, node: Node, filters: dict, payloads: List[dict]
) -> dict:
# when deleting a root node, just delete the doc in
# Elasticsearch/OpenSearch
if node.is_root:
docs: list = []
for payload in payloads:
primary_values: list = [
payload.data[key]
for key in self.tree.root.model.primary_keys
]
doc: dict = {
"_id": self.get_doc_id(
primary_values, self.tree.root.table
),
"_index": self.index,
"_op_type": "delete",
}
if self.routing:
doc["_routing"] = payload.data[self.routing]
if (
self.search_client.major_version < 7
and not self.search_client.is_opensearch
):
doc["_type"] = "_doc"
docs.append(doc)
if docs:
raise_on_exception: Optional[bool] = (
False if settings.USE_ASYNC else None
)
raise_on_error: Optional[bool] = (
False if settings.USE_ASYNC else None
)
self.search_client.bulk(
self.index,
docs,
raise_on_exception=raise_on_exception,
raise_on_error=raise_on_error,
)
else:
# when deleting the child node, find the doc _id where
# the child keys match in private, then get the root doc_id and
# re-sync the child tables
for payload in payloads:
_filters: list = []
_filters = self._root_primary_key_resolver(
node, payload, _filters
)
if _filters:
filters[self.tree.root.table].extend(_filters)
return filters
def _truncate_op(self, node: Node, filters: dict) -> dict:
if node.is_root:
docs: list = []
for doc_id in self.search_client._search(self.index, node.table):
doc: dict = {
"_id": doc_id,
"_index": self.index,
"_op_type": "delete",
}
if (
self.search_client.major_version < 7
and not self.search_client.is_opensearch
):
doc["_type"] = "_doc"
docs.append(doc)
if docs:
self.search_client.bulk(self.index, docs)
else:
_filters: list = []
for doc_id in self.search_client._search(self.index, node.table):
where: dict = {}
params = doc_id.split(PRIMARY_KEY_DELIMITER)
for i, key in enumerate(self.tree.root.model.primary_keys):
where[key] = params[i]
_filters.append(where)
if _filters:
filters[self.tree.root.table].extend(_filters)
return filters
def _payloads(self, payloads: List[Payload]) -> None:
"""
The "payloads" is a list of payload operations to process together.
The basic assumption is that all payloads in the list have the
same tg_op and table name.
e.g:
[
Payload(
tg_op='INSERT',
table='book',
old={'id': 1},
new={'id': 4},
),
Payload(
tg_op='INSERT',
table='book',
old={'id': 2},
new={'id': 5},
),
Payload(
tg_op='INSERT',
table='book',
old={'id': 3},
new={'id': 6},
),
...
]
"""
payload: Payload = payloads[0]
if payload.tg_op not in TG_OP:
logger.exception(f"Unknown tg_op {payload.tg_op}")
raise InvalidTGOPError(f"Unknown tg_op {payload.tg_op}")
# we might receive an event triggered for a table
# that is not in the tree node.
# e.g a through table which we need to react to.
# in this case, we find the parent of the through
# table and force a re-sync.
if payload.table not in self.tree.tables:
return
node: Node = self.tree.get_node(payload.table, payload.schema)
for payload in payloads:
# this is only required for the non truncate tg_ops
if payload.data:
if not set(node.model.primary_keys).issubset(
set(payload.data.keys())
):
logger.exception(
f"Primary keys {node.model.primary_keys} not subset "
f"of payload data {payload.data.keys()} for table "
f"{payload.schema}.{payload.table}"
)
raise
logger.debug(f"tg_op: {payload.tg_op} table: {node.name}")
filters: dict = {
node.table: [],
self.tree.root.table: [],
}
if not node.is_root:
filters[node.parent.table] = []
if payload.tg_op == INSERT:
filters = self._insert_op(
node,
filters,
payloads,
)
if payload.tg_op == UPDATE:
filters = self._update_op(
node,
filters,
payloads,
)
if payload.tg_op == DELETE:
filters = self._delete_op(
node,
filters,
payloads,
)
if payload.tg_op == TRUNCATE:
filters = self._truncate_op(node, filters)
# If there are no filters, then don't execute the sync query
# otherwise we would end up performing a full query
# and sync the entire db!
if any(filters.values()):
"""
Filters are applied when an insert, update or delete operation
occurs. For a large table update, this normally results
in a large SQL query with multiple OR clauses.
Filters is a dict of tables where each key is a list of id's
{
'city': [
{'id': '1'},
{'id': '4'},
{'id': '5'},
],
'book': [
{'id': '1'},
{'id': '2'},
{'id': '7'},
...
]
}
"""
for l1 in chunks(
filters.get(self.tree.root.table), settings.FILTER_CHUNK_SIZE
):
if filters.get(node.table):
for l2 in chunks(
filters.get(node.table), settings.FILTER_CHUNK_SIZE
):
if not node.is_root and filters.get(node.parent.table):
for l3 in chunks(
filters.get(node.parent.table),
settings.FILTER_CHUNK_SIZE,
):
yield from self.sync(
filters={
self.tree.root.table: l1,
node.table: l2,
node.parent.table: l3,
},
)
else:
yield from self.sync(
filters={
self.tree.root.table: l1,
node.table: l2,
},
)
else:
yield from self.sync(
filters={self.tree.root.table: l1},
)
def sync(
self,
filters: Optional[dict] = None,
txmin: Optional[int] = None,
txmax: Optional[int] = None,
ctid: Optional[dict] = None,
) -> Generator:
self.query_builder.isouter = True
self.query_builder.from_obj = None
for node in self.tree.traverse_post_order():
node._subquery = None
node._filters = []
node.setup()
try:
self.query_builder.build_queries(
node, filters=filters, txmin=txmin, txmax=txmax, ctid=ctid
)
except Exception as e:
logger.exception(f"Exception {e}")
raise
if self.verbose:
compiled_query(node._subquery, "Query")
count: int = self.fetchcount(node._subquery)
with click.progressbar(
length=count,
show_pos=True,
show_percent=True,
show_eta=True,
fill_char="=",
empty_char="-",
width=50,
) as bar:
for i, (keys, row, primary_keys) in enumerate(
self.fetchmany(node._subquery)
):
bar.update(1)
row: dict = Transform.transform(row, self.nodes)
row[META] = Transform.get_primary_keys(keys)
if self.verbose:
print(f"{(i+1)})")
print(f"pkeys: {primary_keys}")
pprint.pprint(row)
print("-" * 10)
doc: dict = {
"_id": self.get_doc_id(primary_keys, node.table),
"_index": self.index,
"_source": row,
}
if self.routing:
doc["_routing"] = row[self.routing]
if (
self.search_client.major_version < 7
and not self.search_client.is_opensearch
):
doc["_type"] = "_doc"
if self._plugins:
doc = next(self._plugins.transform([doc]))
if not doc:
continue
if self.pipeline:
doc["pipeline"] = self.pipeline
yield doc
@property