Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
99 lines (82 loc) · 2.85 KB
/
Copy pathdatabase.py
File metadata and controls
99 lines (82 loc) · 2.85 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
#!/usr/bin/env python3
"""Database connection management module for mk-feed-bot."""
import sqlite3
import threading
from contextlib import contextmanager
class DatabaseConnection:
"""Thread-safe singleton database connection manager."""
_instance = None
_lock = threading.Lock()
_local = threading.local()
def __new__(cls):
"""Ensure singleton instance creation."""
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.setup()
return cls._instance
def setup(self):
"""Initialize database connection settings."""
self._lock = threading.Lock()
@contextmanager
def get_connection(self):
"""Get a thread-safe database connection.
Yields:
sqlite3.Connection: Database connection object
Raises:
Exception: Any database-related exception
"""
if not hasattr(self._local, 'connection'):
self._local.connection = sqlite3.connect('feed-bot.sqlite')
self._local.connection.row_factory = sqlite3.Row
try:
yield self._local.connection
except Exception as exc:
self._local.connection.rollback()
raise exc
self._local.connection.commit()
@contextmanager
def get_cursor(self):
"""Get a database cursor within a connection context.
Yields:
sqlite3.Cursor: Database cursor object
"""
with self.get_connection() as conn:
cursor = conn.cursor()
try:
yield cursor
finally:
cursor.close()
def close_all(self):
"""Close all database connections."""
if hasattr(self._local, 'connection'):
self._local.connection.close()
del self._local.connection
# Global instance
DB = DatabaseConnection()
def init_database():
"""Initialize database tables."""
with DB.get_cursor() as cursor:
cursor.execute('''
CREATE TABLE IF NOT EXISTS "news" (
"id" INTEGER NOT NULL UNIQUE,
"source" TEXT NOT NULL DEFAULT 'feed',
"publishedAt" INTEGER NOT NULL,
"link" TEXT NOT NULL UNIQUE,
"title" TEXT NOT NULL,
"body" TEXT,
"sentiment" DECIMAL(1,2),
"noteId" TEXT,
"notedAt" INTEGER,
PRIMARY KEY("id" AUTOINCREMENT)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS "feeds" (
"id" INTEGER NOT NULL UNIQUE,
"url" TEXT NOT NULL UNIQUE,
"title" TEXT,
PRIMARY KEY("id" AUTOINCREMENT)
)
''')