#!/usr/bin/env python3 import argparse import pathlib import sqlite3 BASE_DB_SCHEMA = """ CREATE TABLE IF NOT EXISTS recipes( name TEXT NOT NULL, category TEXT NOT NULL, book TEXT NOT NULL, page INTEGER NULL, magazine TEXT NULL, is_actually_in_book BOOLEAN NOT NULL DEFAULT 1 CHECK (is_actually_in_book IN (0, 1)), UNIQUE(name, book, magazine, page) ); CREATE TABLE IF NOT EXISTS books( name TEXT NOT NULL, path TEXT NOT NULL, page_offset INTEGER DEFAULT 0, UNIQUE(name) ); """ USER_DB_SCHEMA = """ CREATE TABLE IF NOT EXISTS favorites( recipe_id INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS tested( recipe_id INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS excluded( recipe_id INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """ def base(arguments: argparse.Namespace) -> None: # Create the base tables db = sqlite3.connect(arguments.database) db.executescript(BASE_DB_SCHEMA) db.commit() # Populate the books table for book_name in db.execute("SELECT book FROM recipes GROUP BY book"): if globbed := list(arguments.books.glob(f"*{book_name[0].lower()}*.pdf", case_sensitive=False)): db.execute("INSERT OR IGNORE INTO books(name, path) VALUES (?, ?)", (book_name[0], str(globbed[0]))) else: print(f"Not found: {book_name[0]}") db.commit() db.close() def user(arguments: argparse.Namespace) -> None: # Create the base tables db = sqlite3.connect(arguments.database) db.executescript(USER_DB_SCHEMA) db.commit() db.close() def main() -> None: parser = argparse.ArgumentParser( prog="supermix", description="Create and manage books + user-specific databases") commands = parser.add_subparsers(title="command", dest="command") parser.add_argument("database", type=pathlib.Path, help="sqlite3 database file to manage") commands.add_parser("user", help="create or update a user database") command_base = commands.add_parser("base", help="generate the base database") command_base.add_argument("--books", type=pathlib.Path, help="a folder containing PDF books", default="books/") arguments = parser.parse_args() match arguments.command: case "user": user(arguments) case "base": base(arguments) if __name__ == "__main__": main()