kemoverse/db.py

101 lines
2.7 KiB
Python

import sqlite3
import configparser
import os
import sys
import argparse
def get_config_file_path():
"""Get config file path from command line arguments or default"""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--config', default='config.ini', help='Path to config file (default: config.ini)')
args, _ = parser.parse_known_args()
return args.config
def get_db_path():
"""Get database path from config with error handling"""
config_file = get_config_file_path()
if not os.path.exists(config_file):
print(f"Error: {config_file} not found!")
if config_file == 'config.ini':
print("Please copy example_config.ini to config.ini and configure it.")
print(f"Or use --config /path/to/your/config.ini to specify a different location.")
sys.exit(1)
config = configparser.ConfigParser()
try:
config.read(config_file)
except configparser.Error as e:
print(f"Error reading {config_file}: {e}")
sys.exit(1)
if 'application' not in config:
print(f"Error: [application] section missing in {config_file}")
sys.exit(1)
if 'DatabaseLocation' not in config['application']:
print(f"Error: DatabaseLocation missing in {config_file}")
sys.exit(1)
return config['application']['DatabaseLocation']
# Connect to SQLite database (or create it if it doesn't exist)
db_path = get_db_path()
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create tables
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
has_rolled BOOLEAN NOT NULL DEFAULT 0
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS characters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
rarity INTEGER NOT NULL,
weight REAL NOT NULL,
file_id TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS pulls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
character_id INTEGER,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (character_id) REFERENCES characters(id)
)
''')
cursor.execute("""
CREATE TABLE IF NOT EXISTS config (
key TEXT PRIMARY KEY,
value TEXT
)
""")
""" # Insert example characters into the database if they don't already exist
characters = [
('Murakami-san', 1, 0.35),
('Mastodon-kun', 2, 0.25),
('Pleroma-tan', 3, 0.2),
('Misskey-tan', 4, 0.15),
('Syuilo-mama', 5, 0.05)
]
cursor.executemany('''
INSERT OR IGNORE INTO characters (name, rarity, weight) VALUES (?, ?, ?)
''', characters)
"""
# Commit changes and close
conn.commit()
conn.close()