Coverage for src/romfarmer/catalog/database.py: 0%
147 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""Database models and schema using SQLAlchemy."""
3from datetime import datetime
5from sqlalchemy import (
6 Boolean,
7 Column,
8 DateTime,
9 ForeignKey,
10 Index,
11 Integer,
12 String,
13 Text,
14 create_engine,
15)
16from sqlalchemy.orm import (
17 Session,
18 declarative_base,
19 relationship,
20 sessionmaker,
21)
22from sqlalchemy.pool import StaticPool
24Base = declarative_base()
27class DatFile(Base):
28 """DAT file metadata."""
30 __tablename__ = "dat_files"
32 id = Column(Integer, primary_key=True)
33 name = Column(String(255), nullable=False, unique=True, index=True)
34 description = Column(Text)
35 version = Column(String(100))
36 author = Column(String(255))
37 date = Column(String(50))
39 # Tracking
40 imported_at = Column(DateTime, default=datetime.utcnow, nullable=False)
41 updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
43 # Statistics
44 total_games = Column(Integer, default=0)
45 total_size = Column(Integer, default=0)
47 # Relationships
48 games = relationship("DatGame", back_populates="dat_file", cascade="all, delete-orphan")
50 def __repr__(self) -> str:
51 return f"<DatFile(name='{self.name}', version='{self.version}')>"
54class DatGame(Base):
55 """Game entry from DAT file."""
57 __tablename__ = "dat_games"
59 id = Column(Integer, primary_key=True)
60 dat_file_id = Column(Integer, ForeignKey("dat_files.id"), nullable=False, index=True)
62 # Game information
63 name = Column(String(512), nullable=False, index=True)
64 description = Column(Text)
65 category = Column(String(100), index=True)
67 # ROM information
68 rom_name = Column(String(512), nullable=False, index=True)
69 size = Column(Integer, nullable=False)
70 crc = Column(String(8), nullable=False, index=True)
71 md5 = Column(String(32), index=True)
72 sha1 = Column(String(40), index=True)
74 # Relationships
75 dat_file = relationship("DatFile", back_populates="games")
77 # Indexes for common queries
78 __table_args__ = (
79 Index("idx_dat_crc", "dat_file_id", "crc"),
80 Index("idx_dat_name", "dat_file_id", "name"),
81 )
83 def __repr__(self) -> str:
84 return f"<DatGame(name='{self.name}', crc='{self.crc}')>"
87class RomFile(Base):
88 """ROM file in collection."""
90 __tablename__ = "rom_files"
92 id = Column(Integer, primary_key=True)
94 # File information
95 path = Column(String(1024), nullable=False, unique=True, index=True)
96 filename = Column(String(512), nullable=False, index=True)
97 size = Column(Integer, nullable=False)
99 # Parsed metadata
100 name = Column(String(512), nullable=False, index=True)
101 regions = Column(String(255)) # Comma-separated
102 languages = Column(String(255)) # Comma-separated
103 kind = Column(String(50), index=True)
105 # Tags and attributes
106 revision = Column(String(50))
107 version = Column(String(50))
108 tags = Column(Text) # JSON array
110 # Multi-disc information
111 disc_number = Column(Integer)
112 disc_total = Column(Integer)
113 disc_name = Column(String(255))
115 # Hashes
116 crc32 = Column(String(8), index=True)
117 md5 = Column(String(32), index=True)
118 sha1 = Column(String(40), index=True)
120 # DAT matching
121 dat_file_id = Column(Integer, ForeignKey("dat_files.id"), index=True)
122 dat_game_id = Column(Integer, ForeignKey("dat_games.id"), index=True)
123 verified = Column(Boolean, default=False)
124 verification_date = Column(DateTime)
126 # Tracking
127 scanned_at = Column(DateTime, default=datetime.utcnow, nullable=False)
128 updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
130 # Relationships
131 dat_file = relationship("DatFile")
132 dat_game = relationship("DatGame")
134 # Indexes for common queries
135 __table_args__ = (
136 Index("idx_rom_region_kind", "regions", "kind"),
137 Index("idx_rom_crc", "crc32"),
138 Index("idx_rom_verified", "verified", "dat_file_id"),
139 )
141 def __repr__(self) -> str:
142 return f"<RomFile(name='{self.name}', path='{self.path}')>"
145class OrganizationLog(Base):
146 """Log of organization operations."""
148 __tablename__ = "organization_logs"
150 id = Column(Integer, primary_key=True)
152 # Operation information
153 operation_type = Column(String(50), nullable=False) # organize, validate, etc.
154 profile_name = Column(String(100))
155 source_path = Column(String(1024))
156 dest_path = Column(String(1024))
158 # Statistics
159 total_files = Column(Integer, default=0)
160 processed_files = Column(Integer, default=0)
161 skipped_files = Column(Integer, default=0)
162 error_files = Column(Integer, default=0)
164 # Timing
165 started_at = Column(DateTime, default=datetime.utcnow, nullable=False)
166 completed_at = Column(DateTime)
167 duration_seconds = Column(Integer)
169 # Status
170 status = Column(String(20), nullable=False) # running, completed, failed
171 error_message = Column(Text)
173 def __repr__(self) -> str:
174 return f"<OrganizationLog(type='{self.operation_type}', status='{self.status}')>"
177class RomGroomerDatabase:
178 """
179 Database manager for ROM Farmer catalog.
181 Provides high-level interface for database operations with
182 connection pooling, transaction management, and query helpers.
183 """
185 def __init__(self, db_path: str = ":memory:", echo: bool = False):
186 """
187 Initialize database connection.
189 Args:
190 db_path: Path to SQLite database file (or :memory: for in-memory)
191 echo: Echo SQL statements to stdout
192 """
193 if db_path == ":memory:":
194 # Use StaticPool for in-memory databases
195 self.engine = create_engine(
196 f"sqlite:///{db_path}",
197 connect_args={"check_same_thread": False},
198 poolclass=StaticPool,
199 echo=echo,
200 )
201 else:
202 self.engine = create_engine(
203 f"sqlite:///{db_path}",
204 echo=echo,
205 )
207 self.SessionLocal = sessionmaker(bind=self.engine, expire_on_commit=False)
209 # Create all tables
210 Base.metadata.create_all(self.engine)
212 def get_session(self) -> Session:
213 """Get a new database session."""
214 return self.SessionLocal()
216 def close(self) -> None:
217 """Close database connection."""
218 self.engine.dispose()
220 # DAT file operations
222 def add_dat_file(self, session: Session, dat: DatFile) -> DatFile:
223 """Add or update DAT file."""
224 existing = session.query(DatFile).filter_by(name=dat.name).first()
225 if existing:
226 # Update existing
227 for key, value in dat.__dict__.items():
228 if not key.startswith("_"):
229 setattr(existing, key, value)
230 existing.updated_at = datetime.utcnow()
231 return existing
232 else:
233 session.add(dat)
234 return dat
236 def get_dat_file(self, session: Session, name: str) -> DatFile | None:
237 """Get DAT file by name."""
238 return session.query(DatFile).filter_by(name=name).first()
240 def list_dat_files(self, session: Session) -> list[DatFile]:
241 """List all DAT files."""
242 return session.query(DatFile).order_by(DatFile.name).all()
244 def add_dat_game(self, session: Session, game: DatGame) -> DatGame:
245 """Add DAT game entry."""
246 session.add(game)
247 return game
249 def find_game_by_crc(
250 self, session: Session, crc: str, dat_file_id: int | None = None
251 ) -> DatGame | None:
252 """
253 Find game by ROM CRC.
255 Args:
256 session: Database session
257 crc: CRC32 checksum (hex string)
258 dat_file_id: Optional DAT file ID to search within
260 Returns:
261 First matching game, or None
262 """
263 from sqlalchemy.orm import joinedload
265 query = (
266 session.query(DatGame).options(joinedload(DatGame.dat_file)).filter_by(crc=crc.lower())
267 )
268 if dat_file_id:
269 query = query.filter_by(dat_file_id=dat_file_id)
270 return query.first()
272 def find_games_by_name(
273 self, session: Session, name: str, dat_file_id: int | None = None
274 ) -> list[DatGame]:
275 """
276 Find games by name (partial match).
278 Args:
279 session: Database session
280 name: Game name to search for
281 dat_file_id: Optional DAT file ID to search within
283 Returns:
284 List of matching games
285 """
286 from sqlalchemy.orm import joinedload
288 query = (
289 session.query(DatGame)
290 .options(joinedload(DatGame.dat_file))
291 .filter(DatGame.name.like(f"%{name}%"))
292 )
293 if dat_file_id:
294 query = query.filter_by(dat_file_id=dat_file_id)
295 return query.all()
297 def get_dat_games(
298 self, session: Session, dat_file_id: int, limit: int | None = None
299 ) -> list[DatGame]:
300 """
301 Get games for a DAT file.
303 Args:
304 session: Database session
305 dat_file_id: DAT file ID
306 limit: Optional limit on number of results
308 Returns:
309 List of games
310 """
311 query = session.query(DatGame).filter_by(dat_file_id=dat_file_id).order_by(DatGame.name)
312 if limit:
313 query = query.limit(limit)
314 return query.all()
316 # ROM file operations
318 def add_rom_file(self, session: Session, rom: RomFile) -> RomFile:
319 """Add or update ROM file."""
320 existing = session.query(RomFile).filter_by(path=rom.path).first()
321 if existing:
322 # Update existing
323 for key, value in rom.__dict__.items():
324 if not key.startswith("_"):
325 setattr(existing, key, value)
326 existing.updated_at = datetime.utcnow()
327 return existing
328 else:
329 session.add(rom)
330 return rom
332 def get_rom_file(self, session: Session, path: str) -> RomFile | None:
333 """Get ROM file by path."""
334 return session.query(RomFile).filter_by(path=path).first()
336 def find_rom_by_crc(self, session: Session, crc: str) -> list[RomFile]:
337 """Find ROM files by CRC."""
338 return session.query(RomFile).filter_by(crc32=crc).all()
340 def find_rom_by_name(self, session: Session, name: str) -> list[RomFile]:
341 """Find ROM files by name (partial match)."""
342 return session.query(RomFile).filter(RomFile.name.like(f"%{name}%")).all()
344 # Query helpers
346 def get_statistics(self, session: Session) -> dict:
347 """Get database statistics."""
348 return {
349 "total_dat_files": session.query(DatFile).count(),
350 "total_dat_games": session.query(DatGame).count(),
351 "total_rom_files": session.query(RomFile).count(),
352 "verified_roms": session.query(RomFile).filter_by(verified=True).count(),
353 "total_operations": session.query(OrganizationLog).count(),
354 }