Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
265 lines
9.6 KiB
Python
265 lines
9.6 KiB
Python
"""SQLite access layer."""
|
|
|
|
import os
|
|
import sqlite3
|
|
import threading
|
|
from contextlib import contextmanager
|
|
|
|
from errors import NotFoundError
|
|
from models import RESOURCES, STAGES, now_iso, record_label
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS companies (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL,
|
|
website TEXT NOT NULL DEFAULT '',
|
|
industry TEXT NOT NULL DEFAULT ''
|
|
);
|
|
CREATE TABLE IF NOT EXISTS contacts (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL,
|
|
email TEXT NOT NULL DEFAULT '',
|
|
phone TEXT NOT NULL DEFAULT '',
|
|
company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS deals (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
title TEXT NOT NULL,
|
|
amount REAL NOT NULL DEFAULT 0,
|
|
stage TEXT NOT NULL DEFAULT 'lead',
|
|
company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL,
|
|
contact_id INTEGER REFERENCES contacts(id) ON DELETE SET NULL,
|
|
created_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS notes (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
deal_id INTEGER NOT NULL REFERENCES deals(id) ON DELETE CASCADE,
|
|
body TEXT NOT NULL,
|
|
created_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS activity (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
created_at TEXT NOT NULL,
|
|
action TEXT NOT NULL,
|
|
entity TEXT NOT NULL,
|
|
entity_id INTEGER NOT NULL,
|
|
deal_id INTEGER,
|
|
summary TEXT NOT NULL
|
|
);
|
|
"""
|
|
|
|
|
|
def _paging(sql, params, limit, offset):
|
|
"""Append a SQLite page clause; OFFSET alone needs ``LIMIT -1``."""
|
|
page_params = list(params)
|
|
if limit is not None:
|
|
sql += " LIMIT ? OFFSET ?"
|
|
page_params.extend([limit, offset])
|
|
elif offset:
|
|
sql += " LIMIT -1 OFFSET ?"
|
|
page_params.append(offset)
|
|
return sql, page_params
|
|
|
|
|
|
def activity_params(action, entity, record):
|
|
"""Build the activity row for a mutation, linked to its deal when known."""
|
|
if entity == "notes":
|
|
deal_id = record.get("deal_id")
|
|
elif entity == "deals":
|
|
deal_id = record["id"]
|
|
else:
|
|
deal_id = None
|
|
return (now_iso(), action, entity, record["id"], deal_id, record_label(entity, record))
|
|
|
|
|
|
class Store:
|
|
"""One SQLite connection guarded by a lock (the server is threaded)."""
|
|
|
|
def __init__(self, path):
|
|
self.path = path
|
|
self.lock = threading.RLock()
|
|
directory = os.path.dirname(os.path.abspath(path))
|
|
if directory and not os.path.isdir(directory):
|
|
os.makedirs(directory, exist_ok=True)
|
|
self.conn = sqlite3.connect(path, check_same_thread=False)
|
|
self.conn.row_factory = sqlite3.Row
|
|
with self.lock:
|
|
self.conn.execute("PRAGMA foreign_keys = ON")
|
|
self.conn.executescript(SCHEMA)
|
|
self.conn.commit()
|
|
|
|
def close(self):
|
|
with self.lock:
|
|
self.conn.close()
|
|
|
|
@contextmanager
|
|
def transaction(self):
|
|
"""Hold the lock and commit on success, roll back on any failure."""
|
|
with self.lock:
|
|
try:
|
|
yield
|
|
self.conn.commit()
|
|
except BaseException:
|
|
self.conn.rollback()
|
|
raise
|
|
|
|
def exists(self, table, record_id):
|
|
with self.lock:
|
|
row = self.conn.execute(
|
|
"SELECT 1 FROM %s WHERE id = ?" % table, (record_id,)
|
|
).fetchone()
|
|
return row is not None
|
|
|
|
def _filters(self, resource, q=None, stage=None):
|
|
cfg = RESOURCES[resource]
|
|
where, params = [], []
|
|
if q:
|
|
clauses = ["LOWER(%s) LIKE LOWER(?)" % field for field in cfg["search"]]
|
|
where.append("(%s)" % " OR ".join(clauses))
|
|
params.extend(["%%%s%%" % q] * len(clauses))
|
|
if stage and resource == "deals":
|
|
where.append("stage = ?")
|
|
params.append(stage)
|
|
return where, params
|
|
|
|
def list(self, resource, q=None, stage=None, limit=None, offset=0):
|
|
cfg = RESOURCES[resource]
|
|
where, params = self._filters(resource, q, stage)
|
|
sql = "SELECT * FROM %s" % cfg["table"]
|
|
if where:
|
|
sql += " WHERE " + " AND ".join(where)
|
|
sql += " ORDER BY id"
|
|
sql, page_params = _paging(sql, params, limit, offset)
|
|
with self.lock:
|
|
rows = self.conn.execute(sql, page_params).fetchall()
|
|
total = self.conn.execute(
|
|
"SELECT COUNT(*) FROM %s%s"
|
|
% (cfg["table"], (" WHERE " + " AND ".join(where)) if where else ""),
|
|
params,
|
|
).fetchone()[0]
|
|
return [dict(row) for row in rows], int(total)
|
|
|
|
def get(self, resource, record_id):
|
|
cfg = RESOURCES[resource]
|
|
with self.lock:
|
|
row = self.conn.execute(
|
|
"SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,)
|
|
).fetchone()
|
|
if row is None:
|
|
raise NotFoundError("%s %s not found" % (resource, record_id))
|
|
return dict(row)
|
|
|
|
def create(self, resource, values, log_action=None):
|
|
cfg = RESOURCES[resource]
|
|
columns = list(values.keys())
|
|
sql = "INSERT INTO %s (%s) VALUES (%s)" % (
|
|
cfg["table"],
|
|
", ".join(columns),
|
|
", ".join("?" for _ in columns),
|
|
)
|
|
with self.transaction():
|
|
cursor = self.conn.execute(sql, [values[c] for c in columns])
|
|
record_id = cursor.lastrowid
|
|
if log_action:
|
|
created = self.conn.execute(
|
|
"SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,)
|
|
).fetchone()
|
|
self._append_activity(activity_params(log_action, resource, dict(created)))
|
|
return self.get(resource, record_id)
|
|
|
|
def update(self, resource, record_id, values, log_action=None):
|
|
cfg = RESOURCES[resource]
|
|
columns = list(values.keys())
|
|
sql = "UPDATE %s SET %s WHERE id = ?" % (
|
|
cfg["table"],
|
|
", ".join("%s = ?" % column for column in columns),
|
|
)
|
|
with self.transaction():
|
|
self.get(resource, record_id)
|
|
self.conn.execute(sql, [values[c] for c in columns] + [record_id])
|
|
updated = self.conn.execute(
|
|
"SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,)
|
|
).fetchone()
|
|
if updated is None:
|
|
raise NotFoundError("%s %s not found" % (resource, record_id))
|
|
if log_action:
|
|
self._append_activity(activity_params(log_action, resource, dict(updated)))
|
|
return self.get(resource, record_id)
|
|
|
|
def delete(self, resource, record_id, log_action=None):
|
|
cfg = RESOURCES[resource]
|
|
with self.transaction():
|
|
record = self.get(resource, record_id)
|
|
self.conn.execute("DELETE FROM %s WHERE id = ?" % cfg["table"], (record_id,))
|
|
if log_action:
|
|
self._append_activity(activity_params(log_action, resource, record))
|
|
return record
|
|
|
|
def _append_activity(self, params):
|
|
"""Insert one activity row inside the caller's transaction."""
|
|
self.conn.execute(
|
|
"INSERT INTO activity (created_at, action, entity, entity_id, deal_id, summary)"
|
|
" VALUES (?, ?, ?, ?, ?, ?)",
|
|
params,
|
|
)
|
|
|
|
def list_activity(self, limit=None, offset=0, deal_id=None, entity=None):
|
|
where, params = [], []
|
|
if deal_id is not None:
|
|
where.append("deal_id = ?")
|
|
params.append(deal_id)
|
|
if entity:
|
|
where.append("entity = ?")
|
|
params.append(entity)
|
|
sql = "SELECT * FROM activity"
|
|
if where:
|
|
sql += " WHERE " + " AND ".join(where)
|
|
count_sql = sql.replace("SELECT *", "SELECT COUNT(*)")
|
|
sql += " ORDER BY id DESC"
|
|
sql, page_params = _paging(sql, params, limit, offset)
|
|
with self.lock:
|
|
rows = self.conn.execute(sql, page_params).fetchall()
|
|
total = self.conn.execute(count_sql, params).fetchone()[0]
|
|
return [dict(row) for row in rows], int(total)
|
|
|
|
def list_notes(self, deal_id, limit=None, offset=0):
|
|
self.get("deals", deal_id)
|
|
sql, page_params = _paging(
|
|
"SELECT * FROM notes WHERE deal_id = ? ORDER BY id", [deal_id], limit, offset
|
|
)
|
|
with self.lock:
|
|
rows = self.conn.execute(
|
|
sql, page_params
|
|
).fetchall()
|
|
total = self.conn.execute(
|
|
"SELECT COUNT(*) FROM notes WHERE deal_id = ?", (deal_id,)
|
|
).fetchone()[0]
|
|
return [dict(row) for row in rows], int(total)
|
|
|
|
def add_note(self, deal_id, body, log_action=None):
|
|
self.get("deals", deal_id)
|
|
with self.transaction():
|
|
cursor = self.conn.execute(
|
|
"INSERT INTO notes (deal_id, body, created_at) VALUES (?, ?, ?)",
|
|
(deal_id, body, now_iso()),
|
|
)
|
|
if log_action:
|
|
created = self.conn.execute(
|
|
"SELECT * FROM notes WHERE id = ?", (cursor.lastrowid,)
|
|
).fetchone()
|
|
self._append_activity(activity_params(log_action, "notes", dict(created)))
|
|
row = self.conn.execute("SELECT * FROM notes WHERE id = ?", (cursor.lastrowid,)).fetchone()
|
|
return dict(row)
|
|
|
|
def pipeline(self):
|
|
with self.lock:
|
|
rows = self.conn.execute(
|
|
"SELECT stage, COUNT(*) AS count, COALESCE(SUM(amount), 0) AS amount"
|
|
" FROM deals GROUP BY stage"
|
|
).fetchall()
|
|
totals = {stage: {"count": 0, "amount": 0.0} for stage in STAGES}
|
|
for row in rows:
|
|
if row["stage"] in totals:
|
|
totals[row["stage"]] = {"count": int(row["count"]), "amount": float(row["amount"])}
|
|
return totals
|