Coverage for fastblocks / actions / gather / models.py: 34%

308 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Model gathering functionality to discover and collect SQLModel and Pydantic models.""" 

2 

3import inspect 

4import typing as t 

5from contextlib import suppress 

6from importlib import import_module 

7from pathlib import Path 

8 

9from oneiric.core.resolution import Resolver 

10 

11# Migration from ACB to Oneiric 

12depends = Resolver() 

13 

14# ACB compatibility imports - these will be migrated in future phases 

15try: 

16 # MIGRATED: Removed ACB import - using Oneiric equivalent 

17 # MIGRATED: Removed ACB import - debug import debug 

18 pass 

19except ImportError: 

20 # Fallback for Oneiric-only mode 

21 def debug(msg: str) -> None: 

22 """Debug function fallback.""" 

23 print(f"[DEBUG] {msg}") 

24 

25 def get_adapters(): 

26 """Adapter fallback - returns empty list.""" 

27 return [] 

28 

29 def root_path() -> Path: 

30 """Root path fallback - returns current directory.""" 

31 return Path.cwd() 

32 

33 

34from anyio import Path as AsyncPath 

35 

36from .strategies import GatherStrategy, gather_with_strategy 

37 

38 

39class ModelGatherResult: 

40 def __init__( 

41 self, 

42 *, 

43 sql_models: dict[str, type] | None = None, 

44 nosql_models: dict[str, type] | None = None, 

45 adapter_models: dict[str, dict[str, type]] | None = None, 

46 admin_models: list[type] | None = None, 

47 model_metadata: dict[str, dict[str, t.Any]] | None = None, 

48 errors: list[Exception] | None = None, 

49 ) -> None: 

50 self.sql_models = sql_models if sql_models is not None else {} 

51 self.nosql_models = nosql_models if nosql_models is not None else {} 

52 self.adapter_models = adapter_models if adapter_models is not None else {} 

53 self.admin_models = admin_models if admin_models is not None else [] 

54 self.model_metadata = model_metadata if model_metadata is not None else {} 

55 self.errors = errors if errors is not None else [] 

56 

57 @property 

58 def total_models(self) -> int: 

59 adapter_count = sum(len(models) for models in self.adapter_models.values()) 

60 return len(self.sql_models) + len(self.nosql_models) + adapter_count 

61 

62 @property 

63 def has_errors(self) -> bool: 

64 return len(self.errors) > 0 

65 

66 def get_all_models(self) -> dict[str, type]: 

67 all_models = {} 

68 all_models.update(self.sql_models) 

69 all_models.update(self.nosql_models) 

70 for adapter_models in self.adapter_models.values(): 

71 all_models.update(adapter_models) 

72 return all_models 

73 

74 

75async def gather_models( 

76 *, 

77 sources: list[str] | None = None, 

78 patterns: list[str] | None = None, 

79 include_base: bool = True, 

80 include_adapters: bool = True, 

81 include_admin: bool = True, 

82 base_classes: list[type] | None = None, 

83 strategy: GatherStrategy | None = None, 

84) -> ModelGatherResult: 

85 config = _prepare_model_gather_config(sources, patterns, base_classes, strategy) 

86 result = ModelGatherResult() 

87 

88 tasks = _build_model_gather_tasks(config, include_base, include_adapters) 

89 gather_result = await gather_with_strategy( 

90 tasks, 

91 config["strategy"], 

92 cache_key=f"models:{':'.join(config['sources'])}:{':'.join(config['patterns'])}", 

93 ) 

94 

95 _process_model_gather_results(gather_result, config["sources"], result) 

96 

97 if include_admin: 

98 admin_models = await _gather_admin_models(result.get_all_models()) 

99 result.admin_models = admin_models 

100 

101 result.errors.extend(gather_result.errors) 

102 debug( 

103 f"Gathered {result.total_models} models from {len(config['sources'])} sources", 

104 ) 

105 

106 return result 

107 

108 

109def _prepare_model_gather_config( 

110 sources: list[str] | None, 

111 patterns: list[str] | None, 

112 base_classes: list[type] | None, 

113 strategy: GatherStrategy | None, 

114) -> dict[str, t.Any]: 

115 return { 

116 "sources": sources if sources is not None else ["base", "adapters"], 

117 "patterns": patterns 

118 if patterns is not None 

119 else ["models.py", "_models.py", "_models_*.py"], 

120 "base_classes": base_classes 

121 if base_classes is not None 

122 else _get_default_model_base_classes(), 

123 "strategy": strategy if strategy is not None else GatherStrategy(), 

124 } 

125 

126 

127def _get_default_model_base_classes() -> list[type]: 

128 base_classes = [] 

129 with suppress(ImportError): 

130 from sqlmodel import SQLModel # type: ignore[import-untyped] 

131 

132 base_classes.append(SQLModel) 

133 with suppress(ImportError): 

134 from pydantic import BaseModel # type: ignore[import-untyped] 

135 

136 base_classes.append(t.cast(t.Any, BaseModel)) 

137 

138 return base_classes 

139 

140 

141def _build_model_gather_tasks( 

142 config: dict[str, t.Any], 

143 include_base: bool, 

144 include_adapters: bool, 

145) -> list[t.Coroutine[t.Any, t.Any, t.Any]]: 

146 tasks = [] 

147 sources = config["sources"] 

148 patterns = config["patterns"] 

149 base_classes = config["base_classes"] 

150 

151 if "base" in sources and include_base: 

152 tasks.append(_gather_base_models(patterns, base_classes)) 

153 

154 if "adapters" in sources and include_adapters: 

155 tasks.append(_gather_adapter_models(patterns, base_classes)) 

156 

157 if "custom" in sources: 

158 tasks.append(_gather_custom_models(patterns, base_classes)) 

159 

160 return tasks 

161 

162 

163def _process_model_gather_results( 

164 gather_result: t.Any, 

165 sources: list[str], 

166 result: ModelGatherResult, 

167) -> None: 

168 for i, success in enumerate(gather_result.success): 

169 source_type = _get_model_source_type_by_index(i, sources) 

170 _process_single_model_source_result(success, source_type, result) 

171 

172 

173def _get_model_source_type_by_index(index: int, sources: list[str]) -> str: 

174 source_mapping = [("base", "base"), ("adapters", "adapters"), ("custom", "custom")] 

175 for i, (source_name, source_type) in enumerate(source_mapping): 

176 if i == index and source_name in sources: 

177 return source_type 

178 

179 return "unknown" 

180 

181 

182def _process_single_model_source_result( 

183 success: dict[str, t.Any], 

184 source_type: str, 

185 result: ModelGatherResult, 

186) -> None: 

187 if source_type in ("base", "custom"): 

188 result.sql_models.update(success.get("sql", {})) 

189 result.nosql_models.update(success.get("nosql", {})) 

190 result.model_metadata.update(success.get("metadata", {})) 

191 elif source_type == "adapters": 

192 _process_adapter_models(success, result) 

193 

194 

195def _process_adapter_models( 

196 success: dict[str, t.Any], 

197 result: ModelGatherResult, 

198) -> None: 

199 result.adapter_models.update(success.get("adapter_models", {})) 

200 

201 for models in success.get("adapter_models", {}).values(): 

202 for model_name, model_class in models.items(): 

203 if _is_sql_model(model_class): 

204 result.sql_models[model_name] = model_class 

205 else: 

206 result.nosql_models[model_name] = model_class 

207 

208 result.model_metadata.update(success.get("metadata", {})) 

209 

210 

211async def _gather_base_models( 

212 patterns: list[str], 

213 base_classes: list[type], 

214) -> dict[str, t.Any]: 

215 base_models: dict[str, dict[str, t.Any]] = { 

216 "sql": {}, 

217 "nosql": {}, 

218 "metadata": {}, 

219 } 

220 

221 models_file_path = Path(root_path) / "models.py" 

222 await _process_base_models_file(models_file_path, base_classes, base_models) 

223 

224 await _process_base_models_directory( 

225 Path(root_path) / "models", 

226 base_classes, 

227 base_models, 

228 ) 

229 

230 return base_models 

231 

232 

233async def _process_base_models_file( 

234 models_file: Path, 

235 base_classes: list[type], 

236 base_models: dict[str, t.Any], 

237) -> None: 

238 if not await AsyncPath(models_file).exists(): 

239 return 

240 

241 try: 

242 models = await _extract_models_from_file(models_file, base_classes) 

243 _add_models_to_base_collection(models, str(models_file), base_models) 

244 debug(f"Found {len(models)} base models in models.py") 

245 except Exception as e: 

246 debug(f"Error gathering base models from models.py: {e}") 

247 

248 

249async def _process_base_models_directory( 

250 models_dir: Path, 

251 base_classes: list[type], 

252 base_models: dict[str, t.Any], 

253) -> None: 

254 if not ( 

255 await AsyncPath(models_dir).exists() and await AsyncPath(models_dir).is_dir() 

256 ): 

257 return 

258 

259 async for file_path in AsyncPath(models_dir).rglob("*.py"): 

260 if file_path.name.startswith("_"): 

261 continue 

262 

263 try: 

264 models = await _extract_models_from_file(Path(file_path), base_classes) 

265 _add_models_to_base_collection(models, str(file_path), base_models) 

266 

267 if models: 

268 debug( 

269 f"Found {len(models)} models in {file_path.relative_to(root_path)}", 

270 ) 

271 except Exception as e: 

272 debug(f"Error gathering models from {file_path}: {e}") 

273 

274 

275def _add_models_to_base_collection( 

276 models: dict[str, type], 

277 source_path: str, 

278 base_models: dict[str, t.Any], 

279) -> None: 

280 for model_name, model_class in models.items(): 

281 if _is_sql_model(model_class): 

282 base_models["sql"][model_name] = model_class 

283 else: 

284 base_models["nosql"][model_name] = model_class 

285 

286 base_models["metadata"][model_name] = { 

287 "source": source_path, 

288 "type": "sql" if _is_sql_model(model_class) else "nosql", 

289 "location": "base", 

290 } 

291 

292 

293async def _gather_adapter_models( 

294 patterns: list[str], 

295 base_classes: list[type], 

296) -> dict[str, t.Any]: 

297 adapter_models: dict[str, dict[str, t.Any]] = { 

298 "adapter_models": {}, 

299 "metadata": {}, 

300 } 

301 

302 for adapter in get_adapters(): 

303 found_models = await _gather_single_adapter_models( 

304 adapter, 

305 patterns, 

306 base_classes, 

307 adapter_models, 

308 ) 

309 

310 if found_models: 

311 adapter_models["adapter_models"][adapter.name] = found_models 

312 

313 return adapter_models 

314 

315 

316async def _gather_single_adapter_models( 

317 adapter: t.Any, 

318 patterns: list[str], 

319 base_classes: list[type], 

320 adapter_models: dict[str, t.Any], 

321) -> dict[str, type]: 

322 adapter_name = adapter.name 

323 adapter_path = adapter.path.parent 

324 found_models = {} 

325 

326 for pattern in patterns: 

327 if "*" in pattern: 

328 found_models.update( 

329 await _gather_models_with_glob_pattern( 

330 adapter_path, 

331 pattern, 

332 base_classes, 

333 adapter_name, 

334 adapter_models, 

335 ), 

336 ) 

337 else: 

338 found_models.update( 

339 await _gather_models_with_exact_pattern( 

340 adapter_path, 

341 pattern, 

342 base_classes, 

343 adapter_name, 

344 adapter_models, 

345 ), 

346 ) 

347 

348 return found_models 

349 

350 

351async def _gather_models_with_glob_pattern( 

352 adapter_path: t.Any, 

353 pattern: str, 

354 base_classes: list[type], 

355 adapter_name: str, 

356 adapter_models: dict[str, t.Any], 

357) -> dict[str, type]: 

358 found_models = {} 

359 

360 async for file_path in AsyncPath(adapter_path).glob(pattern): 

361 if await file_path.is_file(): 

362 try: 

363 models = await _extract_models_from_file(Path(file_path), base_classes) 

364 found_models.update(models) 

365 _store_adapter_model_metadata( 

366 models, 

367 adapter_name, 

368 str(file_path), 

369 adapter_models, 

370 ) 

371 

372 if models: 

373 debug( 

374 f"Found {len(models)} models in {adapter_name}/{file_path.name}", 

375 ) 

376 

377 except Exception as e: 

378 debug( 

379 f"Error gathering models from {adapter_name}/{file_path.name}: {e}", 

380 ) 

381 

382 return found_models 

383 

384 

385async def _gather_models_with_exact_pattern( 

386 adapter_path: t.Any, 

387 pattern: str, 

388 base_classes: list[type], 

389 adapter_name: str, 

390 adapter_models: dict[str, t.Any], 

391) -> dict[str, type]: 

392 found_models = {} 

393 file_path = adapter_path / pattern 

394 

395 if await AsyncPath(file_path).exists(): 

396 try: 

397 models = await _extract_models_from_file(Path(file_path), base_classes) 

398 found_models.update(models) 

399 _store_adapter_model_metadata( 

400 models, 

401 adapter_name, 

402 str(file_path), 

403 adapter_models, 

404 ) 

405 

406 if models: 

407 debug(f"Found {len(models)} models in {adapter_name}/{pattern}") 

408 

409 except Exception as e: 

410 debug(f"Error gathering models from {adapter_name}/{pattern}: {e}") 

411 

412 return found_models 

413 

414 

415def _store_adapter_model_metadata( 

416 models: dict[str, type], 

417 adapter_name: str, 

418 source_path: str, 

419 adapter_models: dict[str, t.Any], 

420) -> None: 

421 for model_name, model_class in models.items(): 

422 adapter_models["metadata"][f"{adapter_name}.{model_name}"] = { 

423 "source": source_path, 

424 "type": "sql" if _is_sql_model(model_class) else "nosql", 

425 "location": "adapter", 

426 "adapter": adapter_name, 

427 } 

428 

429 

430async def _gather_custom_models( 

431 patterns: list[str], 

432 base_classes: list[type], 

433) -> dict[str, t.Any]: 

434 custom_models: dict[str, dict[str, t.Any]] = { 

435 "sql": {}, 

436 "nosql": {}, 

437 "metadata": {}, 

438 } 

439 

440 custom_paths = [ 

441 Path(root_path) / "app" / "models.py", 

442 Path(root_path) / "src" / "models.py", 

443 Path(root_path) / "custom" / "models.py", 

444 ] 

445 

446 for custom_path in custom_paths: 

447 if await AsyncPath(custom_path).exists(): 

448 await _process_custom_models_file(custom_path, base_classes, custom_models) 

449 

450 return custom_models 

451 

452 

453async def _process_custom_models_file( 

454 custom_path: Path, 

455 base_classes: list[type], 

456 custom_models: dict[str, t.Any], 

457) -> None: 

458 try: 

459 models = await _extract_models_from_file(custom_path, base_classes) 

460 _add_custom_models_to_collection(models, str(custom_path), custom_models) 

461 

462 if models: 

463 debug(f"Found {len(models)} custom models in {custom_path}") 

464 

465 except Exception as e: 

466 debug(f"Error gathering custom models from {custom_path}: {e}") 

467 

468 

469def _add_custom_models_to_collection( 

470 models: dict[str, type], 

471 source_path: str, 

472 custom_models: dict[str, t.Any], 

473) -> None: 

474 for model_name, model_class in models.items(): 

475 if _is_sql_model(model_class): 

476 custom_models["sql"][model_name] = model_class 

477 else: 

478 custom_models["nosql"][model_name] = model_class 

479 

480 custom_models["metadata"][model_name] = { 

481 "source": source_path, 

482 "type": "sql" if _is_sql_model(model_class) else "nosql", 

483 "location": "custom", 

484 } 

485 

486 

487async def _extract_models_from_file( 

488 file_path: Path, 

489 base_classes: list[type], 

490) -> dict[str, type]: 

491 module_path = _get_module_path_from_file(file_path) 

492 debug(f"Extracting models from {file_path} -> {module_path}") 

493 

494 try: 

495 with suppress(ModuleNotFoundError, ImportError): 

496 module = import_module(module_path) 

497 return _extract_models_from_module(module, base_classes) 

498 except Exception as e: 

499 debug(f"Error extracting models from {file_path}: {e}") 

500 raise 

501 

502 return {} 

503 

504 

505def _get_module_path_from_file(file_path: Path) -> str: 

506 try: 

507 relative_path = file_path.relative_to(root_path) 

508 return str(relative_path).replace("/", ".").removesuffix(".py") 

509 except ValueError: 

510 return file_path.stem 

511 

512 

513def _extract_models_from_module( 

514 module: t.Any, 

515 base_classes: list[type], 

516) -> dict[str, type]: 

517 models = {} 

518 

519 for attr_name in dir(module): 

520 if attr_name.startswith("_"): 

521 continue 

522 

523 attr = getattr(module, attr_name) 

524 

525 if _is_valid_model_class(attr, module, base_classes): 

526 models[attr_name] = attr 

527 

528 return models 

529 

530 

531def _is_valid_model_class(attr: t.Any, module: t.Any, base_classes: list[type]) -> bool: 

532 if not (inspect.isclass(attr) and attr.__module__ == module.__name__): 

533 return False 

534 for base_class in base_classes: 

535 if issubclass(attr, base_class) and attr != base_class: 

536 return True 

537 

538 return hasattr(attr, "__table__") 

539 

540 

541async def _gather_admin_models( 

542 all_models: dict[str, type], 

543) -> list[type]: 

544 admin_models = [ 

545 model_class 

546 for model_class in all_models.values() 

547 if ( 

548 hasattr(model_class, "__admin__") 

549 or hasattr(model_class, "can_create") 

550 or hasattr(model_class, "can_edit") 

551 or hasattr(model_class, "__table__") 

552 ) 

553 ] 

554 

555 debug(f"Found {len(admin_models)} admin-enabled models") 

556 

557 return admin_models 

558 

559 

560def _is_sql_model(model_class: type) -> bool: 

561 if hasattr(model_class, "__table__"): 

562 return True 

563 if hasattr(model_class, "__tablename__"): 

564 return True 

565 return bool(model_class.__module__ and "sql" in model_class.__module__.lower()) 

566 

567 

568async def create_models_namespace( 

569 gather_result: ModelGatherResult, 

570) -> t.Any: 

571 class SQLNamespace: 

572 pass 

573 

574 class NoSQLNamespace: 

575 pass 

576 

577 class ModelsNamespace: 

578 def __init__(self) -> None: 

579 self.sql = SQLNamespace() 

580 self.nosql = NoSQLNamespace() 

581 self._all_models: dict[str, t.Any] = {} 

582 

583 def get_admin_models(self) -> list[type]: 

584 return gather_result.admin_models 

585 

586 def __getattr__(self, name: str) -> t.Any: 

587 if name in self._all_models: 

588 return self._all_models[name] 

589 msg = f"Model '{name}' not found" 

590 raise AttributeError(msg) 

591 

592 models = ModelsNamespace() 

593 

594 for model_name, model_class in gather_result.sql_models.items(): 

595 setattr(models.sql, model_name, model_class) 

596 models._all_models[model_name] = model_class 

597 

598 for model_name, model_class in gather_result.nosql_models.items(): 

599 setattr(models.nosql, model_name, model_class) 

600 models._all_models[model_name] = model_class 

601 

602 debug(f"Created models namespace with {len(models._all_models)} models") 

603 

604 return models 

605 

606 

607async def validate_models( 

608 models: dict[str, type], 

609) -> dict[str, t.Any]: 

610 validation: dict[str, t.Any] = { 

611 "valid_models": [], 

612 "invalid_models": [], 

613 "warnings": [], 

614 "total_checked": len(models), 

615 } 

616 

617 for model_name, model_class in models.items(): 

618 try: 

619 _validate_single_model(model_name, model_class, validation) 

620 except Exception as e: 

621 validation["invalid_models"].append( 

622 { 

623 "model": model_name, 

624 "error": str(e), 

625 }, 

626 ) 

627 

628 return validation 

629 

630 

631def _validate_single_model( 

632 model_name: str, 

633 model_class: type, 

634 validation: dict[str, t.Any], 

635) -> None: 

636 issues: list[str] = [] 

637 

638 _check_model_definition(model_class, issues) 

639 

640 _check_duplicate_model_name(model_name, validation) 

641 

642 is_valid = _check_model_inheritance(model_class, issues) 

643 

644 _categorize_model_validation_result(model_name, is_valid, issues, validation) 

645 

646 

647def _check_model_definition(model_class: type, issues: list[str]) -> None: 

648 if ( 

649 not hasattr(model_class, "__table__") 

650 and not hasattr( 

651 model_class, 

652 "__tablename__", 

653 ) 

654 and not hasattr(model_class, "__collection__") 

655 ): 

656 issues.append("Missing table/collection definition") 

657 

658 

659def _check_duplicate_model_name(model_name: str, validation: dict[str, t.Any]) -> None: 

660 if model_name in validation["valid_models"]: 

661 validation["warnings"].append(f"Duplicate model name: {model_name}") 

662 

663 

664def _check_model_inheritance(model_class: type, issues: list[str]) -> bool: 

665 if not any(hasattr(model_class, attr) for attr in ("__bases__", "__mro__")): 

666 issues.append("Invalid model inheritance") 

667 return False 

668 return True 

669 

670 

671def _categorize_model_validation_result( 

672 model_name: str, 

673 is_valid: bool, 

674 issues: list[str], 

675 validation: dict[str, t.Any], 

676) -> None: 

677 if is_valid and not issues: 

678 validation["valid_models"].append(model_name) 

679 else: 

680 validation["invalid_models"].append( 

681 { 

682 "model": model_name, 

683 "issues": issues, 

684 }, 

685 ) 

686 

687 

688def get_model_info( 

689 model_class: type, 

690 metadata: dict[str, t.Any] | None = None, 

691) -> dict[str, t.Any]: 

692 info: dict[str, t.Any] = { 

693 "name": model_class.__name__, 

694 "module": model_class.__module__, 

695 "type": "sql" if _is_sql_model(model_class) else "nosql", 

696 "attributes": [], 

697 "relationships": [], 

698 } 

699 

700 if metadata: 

701 info.update(metadata) 

702 

703 for attr_name in dir(model_class): 

704 if not attr_name.startswith("_"): 

705 attr = getattr(model_class, attr_name) 

706 if hasattr(attr, "__class__") and "Column" in attr.__class__.__name__: 

707 info["attributes"].append(attr_name) 

708 elif ( 

709 hasattr(attr, "__class__") and "Relationship" in attr.__class__.__name__ 

710 ): 

711 info["relationships"].append(attr_name) 

712 

713 if hasattr(model_class, "__table__"): 

714 info["table_name"] = model_class.__table__.name 

715 elif hasattr(model_class, "__tablename__"): 

716 info["table_name"] = model_class.__tablename__ 

717 elif hasattr(model_class, "__collection__"): 

718 info["collection_name"] = model_class.__collection__ 

719 

720 return info 

721 

722 

723# Migration status indicator 

724# Note: Partial migration - ACB adapter and debug systems still in use 

725_using_oneiric = True # Oneiric resolver available 

726_requires_further_migration = True # ACB systems need migration