core/sqlite: extract immutable connection helper

use in bluemaestro/zotero modules
This commit is contained in:
Dima Gerasimov 2021-04-04 22:21:41 +01:00 committed by karlicoss
parent 349ab78fca
commit f2a339f755
4 changed files with 41 additions and 12 deletions

View file

@ -1,12 +1,14 @@
from pathlib import Path
from .common import assert_subpackage; assert_subpackage(__name__)
from .common import PathIsh
from .sqlite import sqlite_connect_immutable
# TODO wonder if also need to open without WAL.. test this on read-only directory/db file
def connect_readonly(db: Path):
def connect_readonly(db: PathIsh):
import dataset # type: ignore
# see https://github.com/pudo/dataset/issues/136#issuecomment-128693122
# todo not sure if mode=ro has any benefit, but it doesn't work on read-only filesystems
# maybe it should autodetect readonly filesystems and apply this? not sure
import sqlite3
# https://www.sqlite.org/draft/uri.html#uriimmutable
creator = lambda: sqlite3.connect(f'file:{db}?immutable=1', uri=True)
creator = lambda: sqlite_connect_immutable(db)
return dataset.connect('sqlite:///', engine_kwargs={'creator': creator})

25
my/core/sqlite.py Normal file
View file

@ -0,0 +1,25 @@
from .common import assert_subpackage; assert_subpackage(__name__)
import sqlite3
from .common import PathIsh
def sqlite_connect_immutable(db: PathIsh) -> sqlite3.Connection:
# https://www.sqlite.org/draft/uri.html#uriimmutable
return sqlite3.connect(f'file:{db}?immutable=1', uri=True)
from pathlib import Path
def test_sqlite_connect_immutable(tmp_path: Path) -> None:
db = str(tmp_path / 'db.sqlite')
with sqlite3.connect(db) as conn:
conn.execute('CREATE TABLE testtable (col)')
import pytest # type: ignore
with pytest.raises(sqlite3.OperationalError, match='readonly database'):
with sqlite_connect_immutable(db) as conn:
conn.execute('DROP TABLE testtable')
# succeeds without immutable
with sqlite3.connect(db) as conn:
conn.execute('DROP TABLE testtable')