add database migration

Clear voters bloomfilter and initialize with an (almost) empty one.
This commit is contained in:
Martin Zimmermann 2013-11-13 20:00:06 +01:00
parent 58645ca945
commit 6178e93348

View File

@ -1,6 +1,9 @@
# -*- encoding: utf-8 -*- # -*- encoding: utf-8 -*-
import sqlite3 import sqlite3
import logging
logger = logging.getLogger("isso")
class IssoDBException(Exception): class IssoDBException(Exception):
pass pass
@ -11,12 +14,24 @@ from isso.db.threads import Threads
class SQLite3: class SQLite3:
MAX_VERSION = 1
def __init__(self, path, conf): def __init__(self, path, conf):
self.path = path self.path = path
self.conf = conf self.conf = conf
self.mode = 1 self.mode = 1
rv = self.execute([
"SELECT name FROM sqlite_master"
" WHERE type='table' AND name IN ('threads', 'comments')"]
).fetchall()
if rv:
self.migrate(to=SQLite3.MAX_VERSION)
else:
self.execute("PRAGMA user_version = %i" % SQLite3.MAX_VERSION)
self.threads = Threads(self) self.threads = Threads(self)
self.comments = Comments(self) self.comments = Comments(self)
@ -34,3 +49,24 @@ class SQLite3:
with sqlite3.connect(self.path) as con: with sqlite3.connect(self.path) as con:
return con.execute(sql, args) return con.execute(sql, args)
@property
def version(self):
return self.execute("PRAGMA user_version").fetchone()[0]
def migrate(self, to):
if self.version >= to:
return
logger.info("migrate database from version %i to %i", self.version, to)
if self.version == 0:
from isso.utils import Bloomfilter
bf = buffer(Bloomfilter(iterable=["127.0.0.0"]).array)
with sqlite3.connect(self.path) as con:
con.execute('UPDATE comments SET voters=?', (bf, ))
con.execute('PRAGMA user_version = 1')
logger.info("%i rows changed", con.total_changes)