From 63befa27da18e36f2634d9c5e6193e2e3f513fe2 Mon Sep 17 00:00:00 2001 From: Luke Murphy Date: Sat, 29 Feb 2020 23:24:43 +0000 Subject: [PATCH] Enable writing to the DB --- calibrestekje/api.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/calibrestekje/api.py b/calibrestekje/api.py index 3c19e95..c5bb20a 100644 --- a/calibrestekje/api.py +++ b/calibrestekje/api.py @@ -1,11 +1,28 @@ """User facing API.""" +from re import IGNORECASE, compile + from sqlalchemy import create_engine from sqlalchemy.orm import Session from calibrestekje.bindings import * # noqa +def title_sort(title): + """Title sorting SQLAlchemy view function.""" + regex = r"^(A|The|An|Der|Die|Das|Den|Ein|Eine|Einen|Dem|Des|Einem|Eines)\s+" + title_pat = compile(regex, IGNORECASE) + match = title_pat.search(title) + if match: + prep = match.group(1) + title = title.replace(prep, "") + ", " + prep + return title.strip() + + def init_session(url: str): """Initialise a SQLAlchemy session against a Calibre database.""" - return Session(create_engine(url)) + engine = create_engine(url) + session = Session(engine) + connection = session.connection() + connection.connection.create_function("title_sort", 1, title_sort) + return session