Read-only mode

This commit is contained in:
Geoffrey Frogeye 2019-12-13 12:35:05 +01:00
parent e19f666331
commit 9050a84670
Signed by: geoffrey
GPG key ID: D8A7ECA00A8CD3DD
3 changed files with 14 additions and 8 deletions

View file

@ -12,7 +12,6 @@ import logging
import argparse
import coloredlogs
import ipaddress
import ctypes
coloredlogs.install(
level='DEBUG',
@ -27,7 +26,9 @@ class Database():
PATH = "blocking.db"
def open(self) -> None:
self.conn = sqlite3.connect(self.PATH)
mode = 'rwc' if self.write else 'ro'
uri = f'file:{self.PATH}?mode={mode}'
self.conn = sqlite3.connect(uri, uri=True)
self.cursor = self.conn.cursor()
self.execute("PRAGMA foreign_keys = ON")
# self.conn.create_function("prepare_ip4address", 1,
@ -40,6 +41,8 @@ class Database():
def execute(self, cmd: str, args: typing.Union[
typing.Tuple[DbValue, ...],
typing.Dict[str, DbValue]] = None) -> None:
# self.log.debug(cmd)
# self.log.debug(args)
self.cursor.execute(cmd, args or tuple())
def get_meta(self, key: str) -> typing.Optional[int]:
@ -65,8 +68,11 @@ class Database():
self.profile()
def initialize(self) -> None:
self.enter_step('initialize')
self.close()
self.enter_step('initialize')
if not self.write:
self.log.error("Cannot initialize in read-only mode.")
raise
os.unlink(self.PATH)
self.open()
self.log.info("Creating database version %d.", self.VERSION)
@ -75,13 +81,13 @@ class Database():
self.set_meta('version', self.VERSION)
self.conn.commit()
def __init__(self) -> None:
def __init__(self, write: bool = False) -> None:
self.log = logging.getLogger('db')
self.time_last = time.perf_counter()
self.time_step = 'init'
self.time_dict: typing.Dict[str, float] = dict()
self.step_dict: typing.Dict[str, int] = dict()
self.accel_ip4_buf = ctypes.create_unicode_buffer('Z'*32, 32)
self.write = write
self.open()
version = self.get_meta('version')
@ -440,7 +446,7 @@ if __name__ == '__main__':
help="Update the reference count")
args = parser.parse_args()
DB = Database()
DB = Database(write=True)
if args.initialize:
DB.initialize()

View file

@ -17,7 +17,7 @@ if __name__ == '__main__':
help="TODO")
args = parser.parse_args()
DB = database.Database()
DB = database.Database(write=True)
try:
DB.enter_step('iowait')

View file

@ -27,7 +27,7 @@ if __name__ == '__main__':
help="The input only comes from verified first-party sources")
args = parser.parse_args()
DB = database.Database()
DB = database.Database(write=True)
fun = FUNCTION_MAP[args.type]