forked from City-of-Helsinki/aura
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.py
66 lines (54 loc) · 1.92 KB
/
migrate.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
#!/usr/bin/env python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlmodels import *
import settings
engine = create_engine(settings.DATABASE_URL)
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()
from models import Plow as MongoPlow
import mongoengine
mongoengine.connect(settings.MONGO_DB)
count = MongoPlow.objects.count()
print("%d plows" % count)
def migrate_plow(mp, event_types):
plow = session.query(Plow).filter_by(id=mp.id).first()
if not plow:
plow = Plow(id=mp.id)
session.add(plow)
points = plow.points
p_count = len(points)
if p_count > 0 and p_count != len(mp.points):
print("Plow %d, points mismatch: %d vs. %d" % (plow.id, p_count, len(mp_points)))
del plow.points
if p_count != len(mp.points):
last_timestamp = None
for idx, mpoint in enumerate(mp.points):
pnt = Point(plow=plow, index=idx, timestamp=mpoint.timestamp)
pnt.lon = mpoint.coords[0]
pnt.lat = mpoint.coords[1]
last_timestamp = mpoint.timestamp
session.add(pnt)
for ev_type in mpoint.events:
if ev_type not in event_types:
print("Adding new event type %s" % ev_type)
ev = EventType(id=ev_type)
session.add(ev)
event_types[ev_type] = ev
else:
ev = event_types[ev_type]
pnt.events.append(ev)
plow.last_timestamp = last_timestamp
session.commit()
event_types = {}
for ev in session.query(EventType):
event_types[ev.id] = ev
PER_PAGE = 20
mongo_count = MongoPlow.objects.count()
plow_idx = 0
while plow_idx < mongo_count:
plow_list = MongoPlow.objects.limit(PER_PAGE).skip(plow_idx)
for plow in plow_list:
migrate_plow(plow, event_types)
plow_idx += plow_list.count()
print(plow_idx)