40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
import sqlite3
|
|
import os
|
|
from pathlib import Path
|
|
from flask import current_app, g
|
|
import click
|
|
|
|
|
|
def get_db():
|
|
"""Stellt eine Datenbankverbindung für den aktuellen Request bereit"""
|
|
if 'db' not in g:
|
|
db_path = current_app.config['DATABASE_PATH']
|
|
# Stelle sicher, dass das instance Verzeichnis existiert
|
|
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
|
g.db = sqlite3.connect(db_path)
|
|
g.db.row_factory = sqlite3.Row
|
|
return g.db
|
|
|
|
|
|
def close_db(e=None):
|
|
"""Schließt die Datenbankverbindung am Ende des Requests"""
|
|
db = g.pop('db', None)
|
|
if db is not None:
|
|
db.close()
|
|
|
|
|
|
def init_db():
|
|
"""Initialisiert die Datenbank mit dem Schema"""
|
|
db = get_db()
|
|
schema_path = Path(current_app.root_path).parent / 'migrations' / 'schema.sql'
|
|
with open(schema_path, 'r', encoding='utf-8') as f:
|
|
db.executescript(f.read())
|
|
db.commit()
|
|
|
|
|
|
@click.command('init-db')
|
|
def init_db_command():
|
|
"""CLI-Befehl zum Initialisieren der Datenbank"""
|
|
init_db()
|
|
click.echo('Datenbank wurde initialisiert.')
|