-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathdbsync.py
1543 lines (1364 loc) · 46.6 KB
/
dbsync.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
"""
Mergin Maps DB Sync - a tool for two-way synchronization between Mergin Maps and a PostGIS database
Copyright (C) 2020 Lutra Consulting
License: MIT
"""
import getpass
import json
import os
import shutil
import string
import subprocess
import tempfile
import random
import uuid
import re
import pathlib
import logging
import psycopg2
import psycopg2.extensions
from psycopg2 import (
sql,
)
from itertools import (
chain,
)
from mergin import (
MerginClient,
MerginProject,
LoginError,
ClientError,
InvalidProject,
)
from version import (
__version__,
)
from config import (
config,
validate_config,
get_ignored_tables,
ConfigError,
)
# set high logging level for geodiff (used by geodiff executable)
# so we get as much information as possible
os.environ["GEODIFF_LOGGER_LEVEL"] = "4" # 0 = nothing, 1 = errors, 2 = warning, 3 = info, 4 = debug
FORCE_INIT_MESSAGE = "Running `dbsync_deamon.py` with `--force-init` should fix the issue."
class DbSyncError(Exception):
default_print_password = "password='*****'"
def __init__(
self,
message,
):
# escaped password
message = re.sub(
r"password=[\"\'].+[\"\'](?=\s)",
self.default_print_password,
message,
)
# not escaped password
message = re.sub(
r"password=\S+",
self.default_print_password,
message,
)
super().__init__(message)
def _add_quotes_to_schema_name(
schema: str,
) -> str:
matches = re.findall(
r"[^a-z0-9_]",
schema,
)
if len(matches) != 0:
schema = schema.replace(
'"',
'""',
)
schema = f'"{schema}"'
return schema
def _tables_list_to_string(
tables,
):
return ";".join(tables)
def _check_has_working_dir(
work_path,
):
if not os.path.exists(work_path):
raise DbSyncError("The project working directory does not exist: " + work_path)
if not os.path.exists(
os.path.join(
work_path,
".mergin",
)
):
raise DbSyncError("The project working directory does not seem to contain Mergin Maps project: " + work_path)
def _check_has_sync_file(
file_path,
):
"""Checks whether the dbsync environment is initialized already (so that we can pull/push).
Emits an exception if not initialized yet."""
if not os.path.exists(file_path):
raise DbSyncError("The output GPKG file does not exist: " + file_path)
def _drop_schema(
conn,
schema_name: str,
) -> None:
cur = conn.cursor()
cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_name)))
conn.commit()
def _check_schema_exists(
conn,
schema_name,
):
cur = conn.cursor()
cur.execute(
"SELECT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = %s)",
(schema_name,),
)
return cur.fetchone()[0]
def _check_postgis_available(
conn: psycopg2.extensions.connection,
) -> bool:
cur = conn.cursor()
cur.execute("SELECT extname FROM pg_extension;")
try:
result = cur.fetchall()
for row in result:
if row[0].lower() == "postgis":
return True
return False
except psycopg2.ProgrammingError:
return False
def _try_install_postgis(
conn: psycopg2.extensions.connection,
) -> bool:
cur = conn.cursor()
try:
cur.execute("CREATE EXTENSION postgis;")
return True
except psycopg2.ProgrammingError:
return False
def _check_has_password():
"""Checks whether we have password for Mergin Maps user - if not, we will ask for it"""
if config.mergin.password is None:
config.mergin.password = getpass.getpass(
prompt="Mergin Maps password for '{}': ".format(config.mergin.username)
)
def _run_geodiff(
cmd,
):
"""will run a command (with geodiff) and report what got to stderr and raise exception
if the command returns non-zero exit code"""
res = subprocess.run(
cmd,
stderr=subprocess.PIPE,
)
geodiff_stderr = res.stderr.decode()
if geodiff_stderr:
logging.error("GEODIFF: " + geodiff_stderr)
if res.returncode != 0:
raise DbSyncError("geodiff failed!\n" + str(cmd))
def _geodiff_create_changeset(
driver,
conn_info,
base,
modified,
changeset,
ignored_tables,
):
if ignored_tables:
_run_geodiff(
[
config.geodiff_exe,
"diff",
"--driver",
driver,
conn_info,
"--skip-tables",
_tables_list_to_string(ignored_tables),
base,
modified,
changeset,
]
)
else:
_run_geodiff(
[
config.geodiff_exe,
"diff",
"--driver",
driver,
conn_info,
base,
modified,
changeset,
]
)
def _geodiff_apply_changeset(
driver,
conn_info,
base,
changeset,
ignored_tables,
):
if ignored_tables:
_run_geodiff(
[
config.geodiff_exe,
"apply",
"--driver",
driver,
conn_info,
"--skip-tables",
_tables_list_to_string(ignored_tables),
base,
changeset,
]
)
else:
_run_geodiff(
[
config.geodiff_exe,
"apply",
"--driver",
driver,
conn_info,
base,
changeset,
]
)
def _geodiff_rebase(
driver,
conn_info,
base,
our,
base2their,
conflicts,
ignored_tables,
):
if ignored_tables:
_run_geodiff(
[
config.geodiff_exe,
"rebase-db",
"--driver",
driver,
conn_info,
"--skip-tables",
_tables_list_to_string(ignored_tables),
base,
our,
base2their,
conflicts,
]
)
else:
_run_geodiff(
[
config.geodiff_exe,
"rebase-db",
"--driver",
driver,
conn_info,
base,
our,
base2their,
conflicts,
]
)
def _geodiff_list_changes_details(
changeset,
):
"""Returns a list with changeset details:
[ { 'table': 'foo', 'type': 'update', 'changes': [ ... old/new column values ... ] }, ... ]
"""
tmp_dir = tempfile.gettempdir()
tmp_output = os.path.join(
tmp_dir,
"dbsync-changeset-details",
)
if os.path.exists(tmp_output):
os.remove(tmp_output)
_run_geodiff(
[
config.geodiff_exe,
"as-json",
changeset,
tmp_output,
]
)
with open(tmp_output) as f:
out = json.load(f)
os.remove(tmp_output)
return out["geodiff"]
def _geodiff_list_changes_summary(
changeset,
):
"""Returns a list with changeset summary:
[ { 'table': 'foo', 'insert': 1, 'update': 2, 'delete': 3 }, ... ]
"""
tmp_dir = tempfile.gettempdir()
tmp_output = os.path.join(
tmp_dir,
"dbsync-changeset-summary",
)
if os.path.exists(tmp_output):
os.remove(tmp_output)
_run_geodiff(
[
config.geodiff_exe,
"as-summary",
changeset,
tmp_output,
]
)
with open(tmp_output) as f:
out = json.load(f)
os.remove(tmp_output)
return out["geodiff_summary"]
def _geodiff_make_copy(
src_driver,
src_conn_info,
src,
dst_driver,
dst_conn_info,
dst,
ignored_tables,
):
if ignored_tables:
_run_geodiff(
[
config.geodiff_exe,
"copy",
"--driver-1",
src_driver,
src_conn_info,
"--driver-2",
dst_driver,
dst_conn_info,
"--skip-tables",
_tables_list_to_string(ignored_tables),
src,
dst,
]
)
else:
_run_geodiff(
[
config.geodiff_exe,
"copy",
"--driver-1",
src_driver,
src_conn_info,
"--driver-2",
dst_driver,
dst_conn_info,
src,
dst,
]
)
def _geodiff_create_changeset_dr(
src_driver,
src_conn_info,
src,
dst_driver,
dst_conn_info,
dst,
changeset,
ignored_tables,
):
if ignored_tables:
_run_geodiff(
[
config.geodiff_exe,
"diff",
"--driver-1",
src_driver,
src_conn_info,
"--driver-2",
dst_driver,
dst_conn_info,
"--skip-tables",
_tables_list_to_string(ignored_tables),
src,
dst,
changeset,
]
)
else:
_run_geodiff(
[
config.geodiff_exe,
"diff",
"--driver-1",
src_driver,
src_conn_info,
"--driver-2",
dst_driver,
dst_conn_info,
src,
dst,
changeset,
]
)
def _compare_datasets(
src_driver,
src_conn_info,
src,
dst_driver,
dst_conn_info,
dst,
ignored_tables,
summary_only=True,
):
"""Compare content of two datasets (from various drivers) and return geodiff JSON summary of changes"""
tmp_dir = tempfile.gettempdir()
tmp_changeset = os.path.join(
tmp_dir,
"".join(
random.choices(
string.ascii_letters,
k=8,
)
),
)
_geodiff_create_changeset_dr(
src_driver,
src_conn_info,
src,
dst_driver,
dst_conn_info,
dst,
tmp_changeset,
ignored_tables,
)
if summary_only:
return _geodiff_list_changes_summary(tmp_changeset)
else:
return _geodiff_list_changes_details(tmp_changeset)
def _print_changes_summary(
summary,
label=None,
):
"""Takes a geodiff JSON summary of changes and prints them"""
print("Changes:" if label is None else label)
for item in summary:
print(
"{:20} {:4} {:4} {:4}".format(
item["table"],
item["insert"],
item["update"],
item["delete"],
)
)
def _print_mergin_changes(
diff_dict,
):
"""Takes a dictionary with format { 'added': [...], 'removed': [...], 'updated': [...] }
where each item is another dictionary with file details, e.g.:
{ 'path': 'myfile.gpkg', size: 123456, ... }
and prints it in a way that's easy to parse for a human :-)
"""
for item in diff_dict["added"]:
logging.debug(" added: " + item["path"])
for item in diff_dict["updated"]:
logging.debug(" updated: " + item["path"])
for item in diff_dict["removed"]:
logging.debug(" removed: " + item["path"])
# Dictionary used by _get_mergin_project() function below.
# key = path to a local dir with Mergin project, value = cached MerginProject object
cached_mergin_project_objects = {}
def _get_mergin_project(work_path) -> MerginProject:
"""
Returns a cached MerginProject object or creates one if it does not exist yet.
This is to avoid creating many of these objects (e.g. every pull/push) because it does
initialization of geodiff as well, so things should be 1. a bit faster, and 2. safer.
(Safer because we are having a cycle of refs between GeoDiff and MerginProject objects
related to logging - and untangling those would need some extra calls when we are done
with MerginProject. But since we use the object all the time, it's better to cache it anyway.)
"""
if work_path not in cached_mergin_project_objects:
cached_mergin_project_objects[work_path] = MerginProject(work_path)
cached_mergin_project_objects[work_path]._read_metadata()
return cached_mergin_project_objects[work_path]
def _get_project_version(work_path) -> str:
"""Returns the current version of the project"""
mp = _get_mergin_project(work_path)
return mp.version()
def _get_project_id(mp: MerginProject):
"""Returns the project ID"""
try:
project_id = uuid.UUID(mp.project_id())
except (
KeyError,
ValueError,
):
project_id = None
return project_id
def _set_db_project_comment(
conn,
schema,
project_name,
version,
project_id=None,
error=None,
):
"""Set postgres COMMENT on SCHEMA with Mergin Maps project name and version
or eventually error message if initialisation failed
"""
comment = {
"name": project_name,
"version": version,
}
if project_id:
comment["project_id"] = project_id
if error:
comment["error"] = error
cur = conn.cursor()
query = sql.SQL("COMMENT ON SCHEMA {} IS %s").format(sql.Identifier(schema))
cur.execute(
query.as_string(conn),
(json.dumps(comment),),
)
conn.commit()
def _get_db_project_comment(conn, schema):
"""Get Mergin Maps project name and its current version in db schema"""
cur = conn.cursor()
schema = _add_quotes_to_schema_name(schema)
cur.execute(
"SELECT obj_description(%s::regnamespace, 'pg_namespace')",
(schema,),
)
res = cur.fetchone()[0]
try:
comment = json.loads(res) if res else None
except (
TypeError,
json.decoder.JSONDecodeError,
):
return
return comment
def _redownload_project(conn_cfg, mc, work_dir, db_proj_info):
logging.debug(f"Removing local working directory {work_dir}")
shutil.rmtree(work_dir)
logging.debug(
f"Downloading version {db_proj_info['version']} of Mergin Maps project {conn_cfg.mergin_project} "
f"to {work_dir}"
)
try:
mc.download_project(
conn_cfg.mergin_project,
work_dir,
db_proj_info["version"],
)
except ClientError as e:
raise DbSyncError("Mergin Maps client error: " + str(e))
def _validate_local_project_id(
mp,
mc,
server_info=None,
):
"""Compare local project ID with remote version on the server."""
local_project_id = _get_project_id(mp)
if local_project_id is None:
return
if server_info is None:
try:
server_info = mc.project_info(mp.project_full_name())
except ClientError as e:
raise DbSyncError("Mergin Maps client error: " + str(e))
remote_project_id = uuid.UUID(server_info["id"])
if local_project_id != remote_project_id:
raise DbSyncError(
f"The local project ID ({local_project_id}) does not match the server project ID ({remote_project_id})"
)
def create_mergin_client():
"""Create instance of MerginClient"""
_check_has_password()
try:
return MerginClient(
config.mergin.url,
login=config.mergin.username,
password=config.mergin.password,
plugin_version=f"DB-sync/{__version__}",
)
except LoginError as e:
# this could be auth failure, but could be also server problem (e.g. worker crash)
raise DbSyncError(
f"Unable to log in to Mergin Maps: {str(e)} \n\n"
+ "Have you specified correct credentials in configuration file?"
)
except ClientError as e:
# this could be e.g. DNS error
raise DbSyncError("Mergin Maps client error: " + str(e))
def revert_local_changes(
mc,
mp,
local_changes=None,
):
"""Revert local changes from the existing project."""
if local_changes is None:
local_changes = mp.get_push_changes()
if not any(local_changes.values()):
return local_changes
logging.debug("Reverting local changes: " + str(local_changes))
for add_change in local_changes["added"]:
added_file = add_change["path"]
added_filepath = os.path.join(
mp.dir,
added_file,
)
os.remove(added_filepath)
for update_delete_change in chain(
local_changes["updated"],
local_changes["removed"],
):
update_delete_file = update_delete_change["path"]
update_delete_filepath = os.path.join(
mp.dir,
update_delete_file,
)
delete_file = os.path.isfile(update_delete_filepath)
if update_delete_file.lower().endswith(".gpkg"):
update_delete_filepath_base = os.path.join(
mp.meta_dir,
update_delete_file,
)
if delete_file:
os.remove(update_delete_filepath)
shutil.copy(
update_delete_filepath_base,
update_delete_filepath,
)
else:
if delete_file:
os.remove(update_delete_filepath)
try:
mc.download_file(
mp.dir,
update_delete_file,
update_delete_filepath,
mp.version(),
)
except ClientError as e:
raise DbSyncError("Mergin Maps client error: " + str(e))
leftovers = mp.get_push_changes()
logging.debug("LEFTOVERS: " + str(leftovers))
return leftovers
def pull(conn_cfg, mc):
"""Downloads any changes from Mergin Maps and applies them to the database"""
logging.debug(f"Processing Mergin Maps project '{conn_cfg.mergin_project}'")
ignored_tables = get_ignored_tables(conn_cfg)
project_name = conn_cfg.mergin_project.split("/")[1]
work_dir = os.path.join(
config.working_dir,
project_name,
)
gpkg_full_path = os.path.join(
work_dir,
conn_cfg.sync_file,
)
_check_has_working_dir(work_dir)
_check_has_sync_file(gpkg_full_path)
mp = _get_mergin_project(work_dir)
mp.set_tables_to_skip(ignored_tables)
if mp.geodiff is None:
raise DbSyncError("Mergin Maps client installation problem: geodiff not available")
# Make sure that local project ID (if available) is the same as on the server
_validate_local_project_id(mp, mc)
local_version = mp.version()
try:
projects = mc.get_projects_by_names([mp.project_full_name()])
server_version = projects[mp.project_full_name()]["version"]
except ClientError as e:
# this could be e.g. DNS error
raise DbSyncError("Mergin Maps client error: " + str(e))
local_changes = mp.get_push_changes()
if any(local_changes.values()):
local_changes = revert_local_changes(
mc,
mp,
local_changes,
)
if any(local_changes.values()):
raise DbSyncError(
"There are pending changes in the local directory - that should never happen! " + str(local_changes)
)
if server_version == local_version:
logging.debug("No changes on Mergin Maps.")
return
gpkg_basefile = os.path.join(
work_dir,
".mergin",
conn_cfg.sync_file,
)
gpkg_basefile_old = gpkg_basefile + "-old"
# make a copy of the basefile in the current version (base) - because after pull it will be set to "their"
shutil.copy(
gpkg_basefile,
gpkg_basefile_old,
)
tmp_dir = tempfile.gettempdir()
tmp_base2our = os.path.join(
tmp_dir,
f"{project_name}-dbsync-pull-base2our",
)
tmp_base2their = os.path.join(
tmp_dir,
f"{project_name}-dbsync-pull-base2their",
)
# find out our local changes in the database (base2our)
_geodiff_create_changeset(
conn_cfg.driver,
conn_cfg.conn_info,
conn_cfg.base,
conn_cfg.modified,
tmp_base2our,
ignored_tables,
)
needs_rebase = False
if os.path.getsize(tmp_base2our) != 0:
needs_rebase = True
summary = _geodiff_list_changes_summary(tmp_base2our)
_print_changes_summary(
summary,
"DB Changes:",
)
try:
mc.pull_project(work_dir) # will do rebase as needed
except ClientError as e:
# TODO: do we need some cleanup here?
raise DbSyncError("Mergin Maps client error on pull: " + str(e))
logging.debug("Pulled new version from Mergin Maps: " + _get_project_version(work_dir))
# simple case when there are no pending local changes - just apply whatever changes are coming
_geodiff_create_changeset(
"sqlite",
"",
gpkg_basefile_old,
gpkg_basefile,
tmp_base2their,
ignored_tables,
)
# summarize changes
summary = _geodiff_list_changes_summary(tmp_base2their)
_print_changes_summary(
summary,
"Mergin Maps Changes:",
)
if not needs_rebase:
logging.debug("Applying new version [no rebase]")
_geodiff_apply_changeset(conn_cfg.driver, conn_cfg.conn_info, conn_cfg.base, tmp_base2their, ignored_tables)
_geodiff_apply_changeset(conn_cfg.driver, conn_cfg.conn_info, conn_cfg.modified, tmp_base2their, ignored_tables)
else:
logging.debug("Applying new version [WITH rebase]")
tmp_conflicts = os.path.join(tmp_dir, f"{project_name}-dbsync-pull-conflicts")
_geodiff_rebase(
conn_cfg.driver,
conn_cfg.conn_info,
conn_cfg.base,
conn_cfg.modified,
tmp_base2their,
tmp_conflicts,
ignored_tables,
)
_geodiff_apply_changeset(conn_cfg.driver, conn_cfg.conn_info, conn_cfg.base, tmp_base2their, ignored_tables)
os.remove(gpkg_basefile_old)
conn = psycopg2.connect(conn_cfg.conn_info)
version = _get_project_version(work_dir)
_set_db_project_comment(
conn,
conn_cfg.base,
conn_cfg.mergin_project,
version,
)
def status(conn_cfg, mc):
"""Figure out if there are any pending changes in the database or in Mergin Maps"""
logging.debug(f"Processing Mergin Maps project '{conn_cfg.mergin_project}'")
ignored_tables = get_ignored_tables(conn_cfg)
project_name = conn_cfg.mergin_project.split("/")[1]
work_dir = os.path.join(
config.working_dir,
project_name,
)
gpkg_full_path = os.path.join(
work_dir,
conn_cfg.sync_file,
)
_check_has_working_dir(work_dir)
_check_has_sync_file(gpkg_full_path)
# get basic information
mp = _get_mergin_project(work_dir)
mp.set_tables_to_skip(ignored_tables)
if mp.geodiff is None:
raise DbSyncError("Mergin Maps client installation problem: geodiff not available")
project_path = mp.project_full_name()
local_version = mp.version()
logging.debug("Checking status...")
try:
server_info = mc.project_info(
project_path,
since=local_version,
)
except ClientError as e:
raise DbSyncError("Mergin Maps client error: " + str(e))
# Make sure that local project ID (if available) is the same as on the server
_validate_local_project_id(
mp,
mc,
server_info,
)
status_push = mp.get_push_changes()
if status_push["added"] or status_push["updated"] or status_push["removed"]:
raise DbSyncError("Pending changes in the local directory - that should never happen! " + str(status_push))
logging.debug("Working directory " + work_dir)
logging.debug("Mergin Maps project " + project_path + " at local version " + local_version)
logging.debug("")
logging.debug("Server is at version " + server_info["version"])
status_pull = mp.get_pull_changes(server_info["files"])
if status_pull["added"] or status_pull["updated"] or status_pull["removed"]:
logging.debug("There are pending changes on server:")
_print_mergin_changes(status_pull)
else:
logging.debug("No pending changes on server.")
logging.debug("")
conn = psycopg2.connect(conn_cfg.conn_info)
if not _check_schema_exists(
conn,
conn_cfg.base,
):
raise DbSyncError("The base schema does not exist: " + conn_cfg.base)
if not _check_schema_exists(
conn,
conn_cfg.modified,
):
raise DbSyncError("The 'modified' schema does not exist: " + conn_cfg.modified)
# get changes in the DB
tmp_dir = tempfile.gettempdir()
tmp_changeset_file = os.path.join(
tmp_dir,
f"{project_name}-dbsync-status-base2our",
)
if os.path.exists(tmp_changeset_file):
os.remove(tmp_changeset_file)
_geodiff_create_changeset(
conn_cfg.driver,
conn_cfg.conn_info,
conn_cfg.base,
conn_cfg.modified,
tmp_changeset_file,
ignored_tables,
)
if os.path.getsize(tmp_changeset_file) == 0:
logging.debug("No changes in the database.")
else:
logging.debug("There are changes in DB")
# summarize changes
summary = _geodiff_list_changes_summary(tmp_changeset_file)
_print_changes_summary(summary)
def push(conn_cfg, mc):
"""Take changes in the 'modified' schema in the database and push them to Mergin Maps"""
logging.debug(f"Processing Mergin Maps project '{conn_cfg.mergin_project}'")
ignored_tables = get_ignored_tables(conn_cfg)
project_name = conn_cfg.mergin_project.split("/")[1]
tmp_dir = tempfile.gettempdir()
tmp_changeset_file = os.path.join(
tmp_dir,
f"{project_name}-dbsync-push-base2our",
)
if os.path.exists(tmp_changeset_file):
os.remove(tmp_changeset_file)
work_dir = os.path.join(
config.working_dir,
project_name,
)
gpkg_full_path = os.path.join(
work_dir,
conn_cfg.sync_file,
)
_check_has_working_dir(work_dir)
_check_has_sync_file(gpkg_full_path)
mp = _get_mergin_project(work_dir)
mp.set_tables_to_skip(ignored_tables)
if mp.geodiff is None:
raise DbSyncError("Mergin Maps client installation problem: geodiff not available")