74 lines
1.9 KiB
Python
74 lines
1.9 KiB
Python
from __future__ import annotations
|
|
from sqlalchemy import inspect
|
|
from .extensions import db
|
|
from .models import AppSetting, CompanySettings, User
|
|
|
|
|
|
DEFAULT_SETTINGS = {
|
|
"theme": "bootstrap",
|
|
"invoice_split_enabled": "1",
|
|
}
|
|
|
|
|
|
def create_schema() -> None:
|
|
"""Tworzy wszystkie tabele, ograniczenia i indeksy zdefiniowane w modelach."""
|
|
db.metadata.create_all(bind=db.engine)
|
|
|
|
|
|
def seed_initial_data() -> None:
|
|
"""Dodaje minimalne dane startowe do świeżej bazy."""
|
|
if not CompanySettings.query.first():
|
|
db.session.add(CompanySettings())
|
|
|
|
for key, value in DEFAULT_SETTINGS.items():
|
|
if db.session.get(AppSetting, key) is None:
|
|
db.session.add(AppSetting(key=key, value=value))
|
|
|
|
if not User.query.first():
|
|
admin = User(
|
|
email="admin@example.com",
|
|
name="Administrator",
|
|
role="admin",
|
|
)
|
|
admin.set_password("admin123!")
|
|
db.session.add(admin)
|
|
|
|
db.session.commit()
|
|
|
|
|
|
def initialize_database() -> None:
|
|
"""Zakłada świeżą bazę: schemat, indeksy, constraints i dane startowe."""
|
|
create_schema()
|
|
seed_initial_data()
|
|
|
|
|
|
def schema_summary() -> dict[str, list[str]]:
|
|
"""Zwraca utworzone tabele i indeksy; przydatne do logów i testów."""
|
|
inspector = inspect(db.engine)
|
|
tables = sorted(inspector.get_table_names())
|
|
indexes = sorted(
|
|
f"{table}.{index['name']}"
|
|
for table in tables
|
|
for index in inspector.get_indexes(table)
|
|
if index.get("name")
|
|
)
|
|
return {"tables": tables, "indexes": indexes}
|
|
|
|
|
|
def main() -> None:
|
|
from . import create_app
|
|
|
|
app = create_app()
|
|
with app.app_context():
|
|
initialize_database()
|
|
summary = schema_summary()
|
|
|
|
print(
|
|
"Baza danych została zainicjalizowana "
|
|
f"({len(summary['tables'])} tabel, {len(summary['indexes'])} indeksów)."
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|