Skip to content

Commit

Permalink
Migrate old media DB if present
Browse files Browse the repository at this point in the history
  • Loading branch information
tsudoko committed Jan 4, 2020
1 parent e8f274e commit e8850f2
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
13 changes: 12 additions & 1 deletion ankisyncd/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
# Original source: https://raw.githubusercontent.com/dae/anki/62481ddc1aa78430cb8114cbf00a7739824318a8/anki/media.py

import logging
import re
import os
import os.path

import anki.db

logger = logging.getLogger("ankisyncd.media")


class ServerMediaManager:
def __init__(self, col):
Expand All @@ -16,7 +19,6 @@ def __init__(self, col):

def connect(self):
path = self.dir() + ".server.db"
# TODO: migrate old db
create = not os.path.exists(path)
self.db = anki.db.DB(path)
if create:
Expand All @@ -28,6 +30,15 @@ def connect(self):
);
CREATE INDEX idx_media_usn ON media (usn);"""
)
oldpath = self.dir() + ".db2"
if os.path.exists(oldpath):
logger.info("Found client media database, migrating contents")
self.db.execute("ATTACH ? AS old", oldpath)
self.db.execute(
"INSERT INTO media SELECT fname, lastUsn, csum FROM old.media, old.meta"
)
self.db.commit()
self.db.execute("DETACH old")

def close(self):
self.db.close()
Expand Down
44 changes: 44 additions & 0 deletions tests/test_media.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import os.path
import unittest

import ankisyncd.media
import helpers.collection_utils


class ServerMediaManagerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.colutils = helpers.collection_utils.CollectionUtils()

@classmethod
def tearDownClass(cls):
cls.colutils.clean_up()
cls.colutils = None

def test_upgrade(self):
col = self.colutils.create_empty_col()
cm = col.media

fpath = os.path.join(cm.dir(), "file")
with open(fpath + "A", "w") as f:
f.write("some contents")
with open(fpath + "B", "w") as f:
f.write("other contents")
cm._logChanges()

self.assertEqual(
set(cm.db.execute("SELECT fname, csum FROM media")),
{
("fileA", "53059abba1a72c7aff34a3eaf7fef10ed65541ce"),
("fileB", "a5ae546046d09559399c80fa7076fb10f1ce4bcd"),
},
)
cm.setLastUsn(161)

sm = ankisyncd.media.ServerMediaManager(col)
self.assertEqual(
list(sm.db.execute("SELECT fname, csum FROM media")),
list(cm.db.execute("SELECT fname, csum FROM media")),
)
self.assertEqual(cm.lastUsn(), sm.lastUsn())
self.assertEqual(list(sm.db.execute("SELECT usn FROM media")), [(161,), (161,)])

0 comments on commit e8850f2

Please sign in to comment.