import sqlite3
from flask import current_app, g

def get_db():
    """Get database connection"""
    # Use current_app.config to access settings from any module
    conn = sqlite3.connect(current_app.config['DATABASE'])
    conn.row_factory = sqlite3.Row
    return conn

def query_db(query, args=(), one=False):
    """Query database helper"""
    conn = get_db()
    cursor = conn.execute(query, args)
    rv = cursor.fetchall()
    conn.close()
    return (rv[0] if rv else None) if one else rv

def execute_db(query, args=()):
    """Execute database insert/update/delete"""
    conn = get_db()
    cursor = conn.execute(query, args)
    conn.commit()
    last_id = cursor.lastrowid
    conn.close()
    return last_id