|
|
import os |
|
|
import sqlite3 |
|
|
import queue |
|
|
import threading |
|
|
from datetime import datetime |
|
|
from contextlib import contextmanager |
|
|
|
|
|
class SQLiteConnectionPool: |
|
|
def __init__(self, database, max_connections=5): |
|
|
|
|
|
db_path = os.path.abspath(os.path.expanduser(database)) |
|
|
|
|
|
db_dir = os.path.dirname(db_path) |
|
|
if db_dir: |
|
|
os.makedirs(db_dir, exist_ok=True) |
|
|
|
|
|
self.database = db_path |
|
|
self.max_connections = max_connections |
|
|
self.connections = queue.Queue(maxsize=max_connections) |
|
|
self.lock = threading.Lock() |
|
|
|
|
|
|
|
|
for _ in range(max_connections): |
|
|
conn = sqlite3.connect(self.database, check_same_thread=False) |
|
|
|
|
|
conn.row_factory = sqlite3.Row |
|
|
self.connections.put(conn) |
|
|
|
|
|
@contextmanager |
|
|
def get_connection(self): |
|
|
connection = self.connections.get() |
|
|
try: |
|
|
yield connection |
|
|
finally: |
|
|
self.connections.put(connection) |
|
|
|
|
|
def close_all(self): |
|
|
while not self.connections.empty(): |
|
|
conn = self.connections.get() |
|
|
conn.close() |
|
|
|
|
|
|
|
|
class DatabaseManager: |
|
|
def __init__(self, pool): |
|
|
self.pool = pool |
|
|
self.create_tables() |
|
|
|
|
|
def create_tables(self): |
|
|
with self.pool.get_connection() as conn: |
|
|
cursor = conn.cursor() |
|
|
|
|
|
|
|
|
cursor.execute(''' |
|
|
CREATE TABLE IF NOT EXISTS context_records ( |
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT, |
|
|
api_key TEXT NOT NULL, |
|
|
chat_id TEXT NOT NULL, |
|
|
parent_id TEXT NOT NULL, |
|
|
sha256_hash TEXT NOT NULL, |
|
|
created_at TIMESTAMP, |
|
|
updated_at TIMESTAMP |
|
|
) |
|
|
''') |
|
|
|
|
|
conn.commit() |
|
|
|
|
|
def insert_context_record(self, api_key, chat_id, parent_id, sha256_hash): |
|
|
with self.pool.get_connection() as conn: |
|
|
cursor = conn.cursor() |
|
|
try: |
|
|
cursor.execute( |
|
|
'INSERT INTO context_records (api_key, chat_id, parent_id, sha256_hash, created_at) VALUES (?, ?, ?, ?, ?)', |
|
|
(api_key, chat_id, parent_id, sha256_hash, datetime.now()) |
|
|
) |
|
|
conn.commit() |
|
|
return cursor.lastrowid |
|
|
except sqlite3.Error as e: |
|
|
print(f"Error inserting context_records: {e}") |
|
|
return None |
|
|
|
|
|
def update_context_record_by_chat_id(self, api_key, chat_id, parent_id, sha256_hash): |
|
|
with self.pool.get_connection() as conn: |
|
|
cursor = conn.cursor() |
|
|
try: |
|
|
cursor.execute( |
|
|
'update context_records set parent_id = ?, sha256_hash = ?, updated_at = ? where api_key = ? and chat_id = ?', |
|
|
(parent_id, sha256_hash, datetime.now(), api_key, chat_id) |
|
|
) |
|
|
conn.commit() |
|
|
return cursor.lastrowid |
|
|
except sqlite3.Error as e: |
|
|
print(f"Error inserting context_records: {e}") |
|
|
return None |
|
|
|
|
|
def get_context_record_by_sha256_hash(self, sha256_hash): |
|
|
with self.pool.get_connection() as conn: |
|
|
cursor = conn.cursor() |
|
|
cursor.execute('SELECT * FROM context_records WHERE sha256_hash = ?', (sha256_hash,)) |
|
|
result = cursor.fetchone() |
|
|
return dict(result) if result else None |
|
|
|
|
|
|
|
|
def main(): |
|
|
|
|
|
|
|
|
pool = SQLiteConnectionPool('~/tmp/merlin-sqlite.db', max_connections=5) |
|
|
db = DatabaseManager(pool) |
|
|
|
|
|
try: |
|
|
|
|
|
db.create_tables() |
|
|
|
|
|
|
|
|
def worker(user_number): |
|
|
username = f"user_{user_number}" |
|
|
email = f"{username}@example.com" |
|
|
|
|
|
|
|
|
user_id = db.insert_user(username, email) |
|
|
if user_id: |
|
|
|
|
|
db.insert_order(user_id, 100.50 * user_number) |
|
|
db.insert_order(user_id, 200.75 * user_number) |
|
|
|
|
|
|
|
|
orders = db.get_user_orders(username) |
|
|
print(f"Orders for {username}:") |
|
|
for order in orders: |
|
|
print(f"Amount: {order['amount']}, Date: {order['order_date']}") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
finally: |
|
|
|
|
|
pool.close_all() |
|
|
|
|
|
|
|
|
def batch_insert_example(db): |
|
|
with db.pool.get_connection() as conn: |
|
|
cursor = conn.cursor() |
|
|
try: |
|
|
|
|
|
cursor.execute('BEGIN TRANSACTION') |
|
|
|
|
|
|
|
|
users_data = [ |
|
|
('user1', 'user1@example.com', datetime.now()), |
|
|
('user2', 'user2@example.com', datetime.now()), |
|
|
('user3', 'user3@example.com', datetime.now()) |
|
|
] |
|
|
|
|
|
|
|
|
cursor.executemany( |
|
|
'INSERT INTO users (username, email, created_at) VALUES (?, ?, ?)', |
|
|
users_data |
|
|
) |
|
|
|
|
|
|
|
|
conn.commit() |
|
|
except sqlite3.Error as e: |
|
|
print(f"Error in batch insert: {e}") |
|
|
conn.rollback() |
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|