-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
executable file
·217 lines (169 loc) · 6.45 KB
/
db.py
File metadata and controls
executable file
·217 lines (169 loc) · 6.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import sqlite3
import logging
from datetime import datetime
from typing import Optional, Dict, List
import os
from dotenv import load_dotenv
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
DATABASE_PATH = os.getenv('DATABASE_PATH', 'slack_agent.db')
def init_database():
"""Initialize the SQLite database with the required schema."""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
# schema required
cursor.execute('''
CREATE TABLE IF NOT EXISTS tasks (
thread_ts TEXT PRIMARY KEY,
linear_task_id TEXT,
title TEXT,
brain_dump TEXT,
draft TEXT,
tone TEXT,
status TEXT DEFAULT 'waiting_dump',
created_at TEXT,
updated_at TEXT
)
''')
# Only keep the primary key index (thread_ts)
conn.commit()
conn.close()
logger.info("Database initialized successfully")
except Exception as e:
logger.error(f"Error initializing database: {e}")
raise
def create_task(thread_ts: str, linear_task_id: str, title: str) -> bool:
"""Create a new task in the database."""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute('''
INSERT INTO tasks (thread_ts, linear_task_id, title, status, created_at, updated_at)
VALUES (?, ?, ?, 'waiting_dump', ?, ?)
''', (thread_ts, linear_task_id, title, now, now))
conn.commit()
conn.close()
logger.info(f"Created task: {title} (thread_ts: {thread_ts}, linear_id: {linear_task_id})")
return True
except Exception as e:
logger.error(f"Error creating task: {e}")
return False
def get_task_by_thread_ts(thread_ts: str) -> Optional[Dict]:
"""Get a task by its thread timestamp."""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
cursor.execute('SELECT * FROM tasks WHERE thread_ts = ?', (thread_ts,))
row = cursor.fetchone()
conn.close()
if row:
return {
'thread_ts': row[0],
'linear_task_id': row[1],
'title': row[2],
'brain_dump': row[3],
'draft': row[4],
'tone': row[5],
'status': row[6],
'created_at': row[7],
'updated_at': row[8]
}
return None
except Exception as e:
logger.error(f"Error getting task by thread_ts {thread_ts}: {e}")
return None
def update_brain_dump(thread_ts: str, brain_dump: str) -> bool:
"""Update the brain dump for a task."""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute('''
UPDATE tasks
SET brain_dump = ?, updated_at = ?
WHERE thread_ts = ?
''', (brain_dump, now, thread_ts))
conn.commit()
conn.close()
logger.info(f"Updated brain dump for thread_ts: {thread_ts}")
return True
except Exception as e:
logger.error(f"Error updating brain dump: {e}")
return False
def update_task_status(thread_ts: str, status: str) -> bool:
"""Update the status of a task."""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute('''
UPDATE tasks
SET status = ?, updated_at = ?
WHERE thread_ts = ?
''', (status, now, thread_ts))
conn.commit()
conn.close()
logger.info(f"Updated task status to '{status}' for thread_ts: {thread_ts}")
return True
except Exception as e:
logger.error(f"Error updating task status: {e}")
return False
def update_draft(thread_ts: str, draft: str, tone: str = None) -> bool:
"""Update the draft and optionally the tone for a task."""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
now = datetime.now().isoformat()
if tone:
cursor.execute('''
UPDATE tasks
SET draft = ?, tone = ?, updated_at = ?
WHERE thread_ts = ?
''', (draft, tone, now, thread_ts))
else:
cursor.execute('''
UPDATE tasks
SET draft = ?, updated_at = ?
WHERE thread_ts = ?
''', (draft, now, thread_ts))
conn.commit()
conn.close()
logger.info(f"Updated draft for thread_ts: {thread_ts}")
return True
except Exception as e:
logger.error(f"Error updating draft: {e}")
return False
def append_brain_dump(thread_ts: str, new_content: str) -> bool:
"""Append new content to existing brain dump."""
try:
task = get_task_by_thread_ts(thread_ts)
if not task:
logger.error(f"Task not found for thread_ts: {thread_ts}")
return False
existing_dump = task.get('brain_dump', '') or ''
updated_dump = existing_dump + '\n' + new_content if existing_dump else new_content
return update_brain_dump(thread_ts, updated_dump)
except Exception as e:
logger.error(f"Error appending brain dump: {e}")
return False
def delete_task(thread_ts: str) -> bool:
"""Delete a task by thread_ts. Used primarily for testing cleanup."""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
cursor.execute('DELETE FROM tasks WHERE thread_ts = ?', (thread_ts,))
conn.commit()
conn.close()
logger.info(f"Deleted task with thread_ts: {thread_ts}")
return True
except Exception as e:
logger.error(f"Error deleting task: {e}")
return False
# Initialize database when module is imported
if __name__ == "__main__":
init_database()
logger.info("Database module initialized")