o
    Gý¤h^  ã                   @   s@   d Z ddlZddlZddlmZ ddlmZ dd„ Zdd	„ ZdS )
a¬  
db.py

Purpose:
  Encapsulate SQLite connection lifecycle, providing `get_db()` for obtaining a
  request-scoped connection and `register_teardown(app)` to close it after the
  request. This mirrors Flask's application context pattern and keeps DB logic
  out of `app.py`.

Exports:
  - get_db(): returns a sqlite3.Row-based connection stored on flask.g
  - register_teardown(app): registers a teardown handler to close the DB
é    N)Úgé   )ÚROOT_DIRc                  C   s~   t tdd ƒ} | d u r=t d¡ptj td¡}t |¡} tj	| _
z|  d¡ |  d¡ |  d¡ W n	 ty9   Y nw | t_| S )NÚ	_databaseÚDATABASE_PATHztheialogin.dbzPRAGMA journal_mode=WALzPRAGMA synchronous=NORMALzPRAGMA foreign_keys=ON)Úgetattrr   ÚosÚgetenvÚpathÚjoinr   Úsqlite3ÚconnectÚRowÚrow_factoryÚexecuteÚ	Exceptionr   )ÚdbÚdb_path© r   ú/var/www/html/app_modules/db.pyÚget_db   s   


ÿr   c                 C   s   | j dd„ ƒ}d S )Nc                 S   s$   t tdd ƒ}|d ur| ¡  d S d S )Nr   )r   r   Úclose)Ú	exceptionr   r   r   r   Úclose_connection(   s   ÿz+register_teardown.<locals>.close_connection)Úteardown_appcontext)Úappr   r   r   r   Úregister_teardown'   s   r   )	Ú__doc__r   r   Úflaskr   Úpathsr   r   r   r   r   r   r   Ú<module>   s    