FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
mage/python/migrate.py at main · memgraph/mage · GitHub
This repository was archived by the owner on Jan 23, 2026. It is now read-only.
memgraph
/
mage
Public archive
Notifications
You must be signed in to change notification settings
Fork
35
Star
331
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
mage
/
python
/
migrate.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1323 lines (993 loc) · 41 KB
Breadcrumbs
mage
/
python
/
migrate.py
Copy path
File metadata and controls
1323 lines (993 loc) · 41 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
base64
import
csv
import
datetime
import
hashlib
import
io
import
json
import
os
import
re
from
decimal
import
Decimal
from
typing
import
Any
,
Dict
,
List
import
boto3
import
duckdb
as
duckDB
import
mgp
import
mysql
.
connector
as
mysql_connector
import
oracledb
import
psycopg2
import
pyarrow
.
flight
as
flight
import
pyodbc
import
requests
from
gqlalchemy
import
Memgraph
from
neo4j
import
GraphDatabase
from
neo4j
.
time
import
DateTime
as
Neo4jDateTime
from
neo4j
.
time
import
Date
as
Neo4jDate
class
Constants
:
BATCH_SIZE
=
1000
COLUMN_NAMES
=
"column_names"
CONNECTION
=
"connection"
CURSOR
=
"cursor"
DATABASE
=
"database"
DRIVER
=
"driver"
HOST
=
"host"
I_COLUMN_NAME
=
0
PASSWORD
=
"password"
PORT
=
"port"
RESULT
=
"result"
SESSION
=
"session"
URI_SCHEME
=
"uri_scheme"
USERNAME
=
"username"
def
_get_query_hash
(
query
:
str
,
config
:
mgp
.
Map
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
)
->
str
:
"""
Create a hash from query, config, and params to use as a cache key.
:param query: The query string (or table name, endpoint, file path, etc.)
:param config: Configuration map
:param params: Optional query parameters
"""
config_dict
=
dict
(
config
)
config_str
=
json
.
dumps
(
config_dict
,
sort_keys
=
True
,
default
=
str
)
params_str
=
""
if
params
is
not
None
:
if
isinstance
(
params
,
dict
):
params_str
=
json
.
dumps
(
params
,
sort_keys
=
True
,
default
=
str
)
elif
isinstance
(
params
, (
list
,
tuple
)):
params_str
=
json
.
dumps
(
list
(
params
),
sort_keys
=
False
,
default
=
str
)
else
:
params_str
=
str
(
params
)
hash_input
=
f"
{
query
}
|
{
config_str
}
|
{
params_str
}
"
return
hashlib
.
sha256
(
hash_input
.
encode
(
"utf-8"
)).
hexdigest
()
# MYSQL
mysql_dict
=
{}
def
init_migrate_mysql
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
):
global
mysql_dict
if
params
:
_check_params_type
(
params
)
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
;"
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
# check if query is already running
if
query_hash
in
mysql_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
mysql_dict
[
query_hash
]
=
{}
connection
=
mysql_connector
.
connect
(
**
config
)
cursor
=
connection
.
cursor
()
cursor
.
execute
(
table_or_sql
,
params
=
params
)
mysql_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
connection
mysql_dict
[
query_hash
][
Constants
.
CURSOR
]
=
cursor
mysql_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
[
column
[
Constants
.
I_COLUMN_NAME
]
for
column
in
cursor
.
description
]
def
mysql
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
With migrate.mysql you can access MySQL and execute queries.
The result table is converted into a stream, and returned rows can be
used to create graph structures. Config must be at least empty map.
If config_path is passed, every key,value pair from JSON file will
overwrite any values in config file.
:param table_or_sql: Table name or an SQL query
:param config: Connection configuration parameters
(as in mysql.connector.connect)
:param config_path: Path to the JSON file containing configuration
parameters (as in mysql.connector.connect)
:param params: Optionally, queries may be parameterized. In that case,
`params` provides parameter values
:return: The result table as a stream of rows
"""
global
mysql_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
;"
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
cursor
=
mysql_dict
[
query_hash
][
Constants
.
CURSOR
]
column_names
=
mysql_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
rows
=
cursor
.
fetchmany
(
Constants
.
BATCH_SIZE
)
result
=
[
mgp
.
Record
(
row
=
_name_row_cells_mysql
(
row
,
column_names
))
for
row
in
rows
]
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
result
:
_cleanup_mysql_by_hash
(
query_hash
)
return
result
def
_cleanup_mysql_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
mysql_dict
if
query_hash
in
mysql_dict
:
mysql_dict
[
query_hash
][
Constants
.
CURSOR
]
=
None
mysql_dict
[
query_hash
][
Constants
.
CONNECTION
].
commit
()
mysql_dict
[
query_hash
][
Constants
.
CONNECTION
].
close
()
mysql_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
None
mysql_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
None
mysql_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_mysql
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
mysql
,
init_migrate_mysql
,
cleanup_migrate_mysql
)
# SQL SERVER
sql_server_dict
=
{}
def
init_migrate_sql_server
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
):
global
sql_server_dict
if
params
:
_check_params_type
(
params
, (
list
,
tuple
))
else
:
params
=
[]
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
;"
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
# check if query is already running
if
query_hash
in
sql_server_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
sql_server_dict
[
query_hash
]
=
{}
connection
=
pyodbc
.
connect
(
**
config
)
cursor
=
connection
.
cursor
()
cursor
.
execute
(
table_or_sql
,
*
params
)
sql_server_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
connection
sql_server_dict
[
query_hash
][
Constants
.
CURSOR
]
=
cursor
sql_server_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
[
column
[
Constants
.
I_COLUMN_NAME
]
for
column
in
cursor
.
description
]
def
sql_server
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
With migrate.sql_server you can access SQL Server and execute queries.
The result table is converted into a stream, and returned rows can be
used to create graph structures. Config must be at least empty map.
If config_path is passed, every key,value pair from JSON file will
overwrite any values in config file.
:param table_or_sql: Table name or an SQL query
:param config: Connection configuration parameters (as in pyodbc.connect)
:param config_path: Path to the JSON file containing configuration
parameters (as in pyodbc.connect)
:param params: Optionally, queries may be parameterized. In that case,
`params` provides parameter values
:return: The result table as a stream of rows
"""
global
sql_server_dict
if
not
params
:
params
=
[]
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
;"
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
cursor
=
sql_server_dict
[
query_hash
][
Constants
.
CURSOR
]
column_names
=
sql_server_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
rows
=
cursor
.
fetchmany
(
Constants
.
BATCH_SIZE
)
result
=
[
mgp
.
Record
(
row
=
_name_row_cells
(
row
,
column_names
))
for
row
in
rows
]
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
result
:
_cleanup_sql_server_by_hash
(
query_hash
)
return
result
def
_cleanup_sql_server_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
sql_server_dict
if
query_hash
in
sql_server_dict
:
sql_server_dict
[
query_hash
][
Constants
.
CURSOR
]
=
None
sql_server_dict
[
query_hash
][
Constants
.
CONNECTION
].
commit
()
sql_server_dict
[
query_hash
][
Constants
.
CONNECTION
].
close
()
sql_server_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
None
sql_server_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
None
sql_server_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_sql_server
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
sql_server
,
init_migrate_sql_server
,
cleanup_migrate_sql_server
)
# Oracle DB
oracle_db_dict
=
{}
def
init_migrate_oracle_db
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
):
global
oracle_db_dict
if
params
:
_check_params_type
(
params
)
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
"
if
not
config
:
config
=
{}
# To prevent query execution from hanging
config
[
"disable_oob"
]
=
True
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
# check if query is already running
if
query_hash
in
oracle_db_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
oracle_db_dict
[
query_hash
]
=
{}
connection
=
oracledb
.
connect
(
**
config
)
cursor
=
connection
.
cursor
()
if
not
params
:
cursor
.
execute
(
table_or_sql
)
elif
isinstance
(
params
, (
list
,
tuple
)):
cursor
.
execute
(
table_or_sql
,
params
)
else
:
cursor
.
execute
(
table_or_sql
,
**
params
)
oracle_db_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
connection
oracle_db_dict
[
query_hash
][
Constants
.
CURSOR
]
=
cursor
oracle_db_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
[
column
[
Constants
.
I_COLUMN_NAME
]
for
column
in
cursor
.
description
]
def
oracle_db
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
With migrate.oracle_db you can access Oracle DB and execute queries.
The result table is converted into a stream, and returned rows can be
used to create graph structures. Config must be at least empty map.
If config_path is passed, every key,value pair from JSON file will
overwrite any values in config file.
:param table_or_sql: Table name or an SQL query
:param config: Connection configuration parameters (as in oracledb.connect)
:param config_path: Path to the JSON file containing configuration
parameters (as in oracledb.connect)
:param params: Optionally, queries may be parameterized. In that case,
`params` provides parameter values
:return: The result table as a stream of rows
"""
global
oracle_db_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
"
if
not
config
:
config
=
{}
config
[
"disable_oob"
]
=
True
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
cursor
=
oracle_db_dict
[
query_hash
][
Constants
.
CURSOR
]
column_names
=
oracle_db_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
rows
=
cursor
.
fetchmany
(
Constants
.
BATCH_SIZE
)
result
=
[
mgp
.
Record
(
row
=
_name_row_cells
(
row
,
column_names
))
for
row
in
rows
]
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
result
:
_cleanup_oracle_db_by_hash
(
query_hash
)
return
result
def
_cleanup_oracle_db_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
oracle_db_dict
if
query_hash
in
oracle_db_dict
:
oracle_db_dict
[
query_hash
][
Constants
.
CURSOR
]
=
None
oracle_db_dict
[
query_hash
][
Constants
.
CONNECTION
].
commit
()
oracle_db_dict
[
query_hash
][
Constants
.
CONNECTION
].
close
()
oracle_db_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
None
oracle_db_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
None
oracle_db_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_oracle_db
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
oracle_db
,
init_migrate_oracle_db
,
cleanup_migrate_oracle_db
)
# PostgreSQL dictionary to store connections and cursors by thread
postgres_dict
=
{}
def
init_migrate_postgresql
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
):
global
postgres_dict
if
params
:
_check_params_type
(
params
, (
list
,
tuple
))
else
:
params
=
[]
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
;"
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
# check if query is already running
if
query_hash
in
postgres_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
postgres_dict
[
query_hash
]
=
{}
connection
=
psycopg2
.
connect
(
**
config
)
cursor
=
connection
.
cursor
()
cursor
.
execute
(
table_or_sql
,
params
)
postgres_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
connection
postgres_dict
[
query_hash
][
Constants
.
CURSOR
]
=
cursor
postgres_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
[
column
.
name
for
column
in
cursor
.
description
]
def
postgresql
(
table_or_sql
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
With migrate.postgresql you can access PostgreSQL and execute queries.
The result table is converted into a stream, and returned rows can be
used to create graph structures. Config must be at least empty map.
If config_path is passed, every key,value pair from JSON file will
overwrite any values in config file.
:param table_or_sql: Table name or an SQL query
:param config: Connection configuration parameters (as in psycopg2.connect)
:param config_path: Path to the JSON file containing configuration
parameters (as in psycopg2.connect)
:param params: Optionally, queries may be parameterized. In that case,
`params` provides parameter values
:return: The result table as a stream of rows
"""
global
postgres_dict
if
not
params
:
params
=
[]
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
if
_query_is_table
(
table_or_sql
):
table_or_sql
=
f"SELECT * FROM
{
table_or_sql
}
;"
query_hash
=
_get_query_hash
(
table_or_sql
,
config
,
params
)
cursor
=
postgres_dict
[
query_hash
][
Constants
.
CURSOR
]
column_names
=
postgres_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
rows
=
cursor
.
fetchmany
(
Constants
.
BATCH_SIZE
)
result
=
[
mgp
.
Record
(
row
=
_name_row_cells
(
row
,
column_names
))
for
row
in
rows
]
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
result
:
_cleanup_postgresql_by_hash
(
query_hash
)
return
result
def
_cleanup_postgresql_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
postgres_dict
if
query_hash
in
postgres_dict
:
postgres_dict
[
query_hash
][
Constants
.
CURSOR
]
=
None
postgres_dict
[
query_hash
][
Constants
.
CONNECTION
].
commit
()
postgres_dict
[
query_hash
][
Constants
.
CONNECTION
].
close
()
postgres_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
None
postgres_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
None
postgres_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_postgresql
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
postgresql
,
init_migrate_postgresql
,
cleanup_migrate_postgresql
)
# S3
s3_dict
=
{}
def
init_migrate_s3
(
file_path
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
):
"""
Initialize an S3 connection and prepare to stream a CSV file.
:param file_path: S3 file path in the format
's3://bucket-name/path/to/file.csv'
:param config: Configuration map containing AWS credentials
(access_key, secret_key, region, etc.)
:param config_path: Path to a JSON file containing configuration parameters
"""
global
s3_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
# Extract S3 bucket and key
if
not
file_path
.
startswith
(
"s3://"
):
raise
ValueError
(
"Invalid S3 path format. "
"Expected 's3://bucket-name/path'."
)
file_path_no_protocol
=
file_path
[
5
:]
bucket_name
,
*
key_parts
=
file_path_no_protocol
.
split
(
"/"
)
s3_key
=
"/"
.
join
(
key_parts
)
query_hash
=
_get_query_hash
(
file_path
,
config
)
# check if query is already running
if
query_hash
in
s3_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
# Initialize S3 client
s3_client
=
boto3
.
client
(
"s3"
,
aws_access_key_id
=
config
.
get
(
"aws_access_key_id"
,
os
.
getenv
(
"AWS_ACCESS_KEY_ID"
,
None
)
),
aws_secret_access_key
=
config
.
get
(
"aws_secret_access_key"
,
os
.
getenv
(
"AWS_SECRET_ACCESS_KEY"
,
None
)
),
aws_session_token
=
config
.
get
(
"aws_session_token"
,
os
.
getenv
(
"AWS_SESSION_TOKEN"
,
None
)
),
region_name
=
config
.
get
(
"region_name"
,
os
.
getenv
(
"AWS_REGION"
,
None
)),
)
# Fetch and read file as a streaming object
response
=
s3_client
.
get_object
(
Bucket
=
bucket_name
,
Key
=
s3_key
)
# Convert binary stream to text stream
text_stream
=
io
.
TextIOWrapper
(
response
[
"Body"
],
encoding
=
"utf-8"
)
# Read CSV headers
csv_reader
=
csv
.
reader
(
text_stream
)
column_names
=
next
(
csv_reader
)
# First row contains column names
s3_dict
[
query_hash
]
=
{}
s3_dict
[
query_hash
][
Constants
.
CURSOR
]
=
csv_reader
s3_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
column_names
def
s3
(
file_path
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
Fetch rows from an S3 CSV file in batches.
:param file_path: S3 file path in the format
's3://bucket-name/path/to/file.csv'
:param config: AWS S3 connection parameters (AWS credentials, region, etc.)
:param config_path: Optional path to a JSON file containing AWS credentials
:return: The result table as a stream of rows
"""
global
s3_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
query_hash
=
_get_query_hash
(
file_path
,
config
)
csv_reader
=
s3_dict
[
query_hash
][
Constants
.
CURSOR
]
column_names
=
s3_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
batch_rows
=
[]
for
_
in
range
(
Constants
.
BATCH_SIZE
):
try
:
row
=
next
(
csv_reader
)
batch_rows
.
append
(
mgp
.
Record
(
row
=
_name_row_cells
(
row
,
column_names
)))
except
StopIteration
:
break
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
batch_rows
:
_cleanup_s3_by_hash
(
query_hash
)
return
batch_rows
def
_cleanup_s3_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
s3_dict
if
query_hash
in
s3_dict
:
s3_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_s3
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
s3
,
init_migrate_s3
,
cleanup_migrate_s3
)
neo4j_dict
=
{}
def
init_migrate_neo4j
(
label_or_rel_or_query
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
):
global
neo4j_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
query
=
_formulate_cypher_query
(
label_or_rel_or_query
)
query_hash
=
_get_query_hash
(
query
,
config
,
params
)
# check if query is already running
if
query_hash
in
neo4j_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
uri
=
_build_neo4j_uri
(
config
)
username
=
config
.
get
(
Constants
.
USERNAME
,
"neo4j"
)
password
=
config
.
get
(
Constants
.
PASSWORD
,
"password"
)
database
=
config
.
get
(
Constants
.
DATABASE
,
None
)
# None means default database
driver
=
GraphDatabase
.
driver
(
uri
,
auth
=
(
username
,
password
))
# Create session with optional database parameter
if
database
:
session
=
driver
.
session
(
database
=
database
)
else
:
session
=
driver
.
session
()
# Neo4j expects params to be a dict or None
cypher_params
=
params
if
params
is
not
None
else
{}
result
=
session
.
run
(
query
,
parameters
=
cypher_params
)
neo4j_dict
[
query_hash
]
=
{}
neo4j_dict
[
query_hash
][
Constants
.
DRIVER
]
=
driver
neo4j_dict
[
query_hash
][
Constants
.
SESSION
]
=
session
neo4j_dict
[
query_hash
][
Constants
.
RESULT
]
=
result
def
neo4j
(
label_or_rel_or_query
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
Migrate data from Neo4j to Memgraph. Can migrate a specific node label, relationship type, or execute a custom Cypher query.
:param label_or_rel_or_query: Node label, relationship type, or a Cypher query
:param config: Connection configuration for Neo4j
:param config_path: Path to a JSON file containing connection parameters
:param params: Optional query parameters
:return: Stream of rows from Neo4j
"""
global
neo4j_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
query
=
_formulate_cypher_query
(
label_or_rel_or_query
)
query_hash
=
_get_query_hash
(
query
,
config
,
params
)
result
=
neo4j_dict
[
query_hash
][
Constants
.
RESULT
]
# Fetch up to BATCH_SIZE records
batch
=
[]
for
record
in
result
:
# Convert neo4j.Record to dict with proper type conversion
batch
.
append
(
mgp
.
Record
(
row
=
_convert_neo4j_record
(
record
)))
# Check if we've reached the batch size limit
if
len
(
batch
)
>=
Constants
.
BATCH_SIZE
:
break
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
batch
:
_cleanup_neo4j_by_hash
(
query_hash
)
return
batch
def
_cleanup_neo4j_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
neo4j_dict
if
query_hash
in
neo4j_dict
:
session
=
neo4j_dict
[
query_hash
].
get
(
Constants
.
SESSION
)
driver
=
neo4j_dict
[
query_hash
].
get
(
Constants
.
DRIVER
)
if
session
:
session
.
close
()
if
driver
:
driver
.
close
()
neo4j_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_neo4j
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
neo4j
,
init_migrate_neo4j
,
cleanup_migrate_neo4j
)
# Dictionary to store Flight connections per thread
flight_dict
=
{}
def
init_migrate_arrow_flight
(
query
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
):
global
flight_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
query_hash
=
_get_query_hash
(
query
,
config
)
# check if query is already running
if
query_hash
in
flight_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
host
=
config
.
get
(
Constants
.
HOST
,
None
)
port
=
config
.
get
(
Constants
.
PORT
,
None
)
username
=
config
.
get
(
Constants
.
USERNAME
,
""
)
password
=
config
.
get
(
Constants
.
PASSWORD
,
""
)
# Encode credentials
auth_string
=
f"
{
username
}
:
{
password
}
"
.
encode
(
"utf-8"
)
encoded_auth
=
base64
.
b64encode
(
auth_string
).
decode
(
"utf-8"
)
# Establish Flight connection
client
=
flight
.
connect
(
f"grpc://
{
host
}
:
{
port
}
"
)
# Authenticate
options
=
flight
.
FlightCallOptions
(
headers
=
[(
b"authorization"
,
f"Basic
{
encoded_auth
}
"
.
encode
(
"utf-8"
))]
)
flight_info
=
client
.
get_flight_info
(
flight
.
FlightDescriptor
.
for_command
(
query
),
options
)
flight_dict
[
query_hash
]
=
{}
flight_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
client
flight_dict
[
query_hash
][
Constants
.
CURSOR
]
=
iter
(
_fetch_flight_data
(
client
,
flight_info
,
options
)
)
def
_fetch_flight_data
(
client
,
flight_info
,
options
):
"""
Efficiently fetches data in batches from Arrow Flight using RecordBatchReader.
This prevents high memory usage by avoiding full table loading.
"""
for
endpoint
in
flight_info
.
endpoints
:
reader
=
client
.
do_get
(
endpoint
.
ticket
,
options
)
# Stream the data
for
chunk
in
reader
:
# Iterate over RecordBatches
batch
=
chunk
.
data
# Convert each batch to an Arrow Table
yield
from
batch
.
to_pylist
()
# Convert to row dictionaries on demand
def
arrow_flight
(
query
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
Execute a SQL query on Arrow Flight and stream results into Memgraph.
:param query: SQL query to execute
:param config: Arrow Flight connection configuration
:param config_path: Path to a JSON config file
:return: Stream of rows from Arrow Flight
"""
global
flight_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
query_hash
=
_get_query_hash
(
query
,
config
)
cursor
=
flight_dict
[
query_hash
][
Constants
.
CURSOR
]
batch
=
[]
for
_
in
range
(
Constants
.
BATCH_SIZE
):
try
:
row
=
_convert_row_types
(
next
(
cursor
))
batch
.
append
(
mgp
.
Record
(
row
=
row
))
except
StopIteration
:
break
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
batch
:
_cleanup_arrow_flight_by_hash
(
query_hash
)
return
batch
def
_cleanup_arrow_flight_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
flight_dict
if
query_hash
in
flight_dict
:
flight_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_arrow_flight
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
arrow_flight
,
init_migrate_arrow_flight
,
cleanup_migrate_arrow_flight
)
# Dictionary to store DuckDB connections and cursors per thread
duckdb_dict
=
{}
def
init_migrate_duckdb
(
query
:
str
,
setup_queries
:
mgp
.
Nullable
[
List
[
str
]]
=
None
):
"""
Initialize an in-memory DuckDB connection and execute the query.
:param query: SQL query to execute
:param setup_queries: Optional list of setup queries to execute before the main query
"""
global
duckdb_dict
# Create hash from query and setup_queries
setup_queries_str
=
(
json
.
dumps
(
setup_queries
,
sort_keys
=
False
)
if
setup_queries
else
""
)
query_hash
=
hashlib
.
sha256
(
f"
{
query
}
|
{
setup_queries_str
}
"
.
encode
(
"utf-8"
)
).
hexdigest
()
# check if query is already running
if
query_hash
in
duckdb_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
# Ensure a fresh in-memory DuckDB instance for each query
connection
=
duckDB
.
connect
()
cursor
=
connection
.
cursor
()
if
setup_queries
is
not
None
:
for
setup_query
in
setup_queries
:
cursor
.
execute
(
setup_query
)
cursor
.
execute
(
query
)
duckdb_dict
[
query_hash
]
=
{}
duckdb_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
connection
duckdb_dict
[
query_hash
][
Constants
.
CURSOR
]
=
cursor
duckdb_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
=
[
desc
[
0
]
for
desc
in
cursor
.
description
]
def
duckdb
(
query
:
str
,
setup_queries
:
mgp
.
Nullable
[
List
[
str
]]
=
None
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
Fetch rows from DuckDB in batches.
:param query: SQL query to execute
:param setup_queries: Optional list of setup queries to execute before the main query
:return: The result table as a stream of rows
"""
global
duckdb_dict
setup_queries_str
=
(
json
.
dumps
(
setup_queries
,
sort_keys
=
False
)
if
setup_queries
else
""
)
query_hash
=
hashlib
.
sha256
(
f"
{
query
}
|
{
setup_queries_str
}
"
.
encode
(
"utf-8"
)
).
hexdigest
()
cursor
=
duckdb_dict
[
query_hash
][
Constants
.
CURSOR
]
column_names
=
duckdb_dict
[
query_hash
][
Constants
.
COLUMN_NAMES
]
rows
=
cursor
.
fetchmany
(
Constants
.
BATCH_SIZE
)
result
=
[
mgp
.
Record
(
row
=
_name_row_cells
(
row
,
column_names
))
for
row
in
rows
]
# if results are empty, cleanup the query since cleanup doesn't accept any parameters
if
not
result
:
_cleanup_duckdb_by_hash
(
query_hash
)
return
result
def
_cleanup_duckdb_by_hash
(
query_hash
:
str
):
"""Internal cleanup function that takes a query hash."""
global
duckdb_dict
if
query_hash
in
duckdb_dict
:
if
Constants
.
CONNECTION
in
duckdb_dict
[
query_hash
]:
duckdb_dict
[
query_hash
][
Constants
.
CONNECTION
].
close
()
duckdb_dict
.
pop
(
query_hash
,
None
)
def
cleanup_migrate_duckdb
():
"""Cleanup function called by mgp framework (no parameters)."""
pass
mgp
.
add_batch_read_proc
(
duckdb
,
init_migrate_duckdb
,
cleanup_migrate_duckdb
)
memgraph_dict
=
{}
def
init_migrate_memgraph
(
label_or_rel_or_query
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
):
global
memgraph_dict
if
len
(
config_path
)
>
0
:
config
=
_combine_config
(
config
=
config
,
config_path
=
config_path
)
query
=
_formulate_cypher_query
(
label_or_rel_or_query
)
query_hash
=
_get_query_hash
(
query
,
config
,
params
)
# check if query is already running
if
query_hash
in
memgraph_dict
:
raise
RuntimeError
(
f"Migrate module with these parameters is already running. Please wait for it to finish before starting a new one."
)
memgraph_db
=
Memgraph
(
**
config
)
cursor
=
memgraph_db
.
execute_and_fetch
(
query
,
params
)
memgraph_dict
[
query_hash
]
=
{}
memgraph_dict
[
query_hash
][
Constants
.
CONNECTION
]
=
memgraph_db
memgraph_dict
[
query_hash
][
Constants
.
CURSOR
]
=
cursor
def
memgraph
(
label_or_rel_or_query
:
str
,
config
:
mgp
.
Map
,
config_path
:
str
=
""
,
params
:
mgp
.
Nullable
[
mgp
.
Any
]
=
None
,
)
->
mgp
.
Record
(
row
=
mgp
.
Map
):
"""
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL