Create multiple records in a single transaction for better performance. Args: items: List of model instances to create db_session: SQLAlchemy session actor: Optional user performing the action Returns: List of created model ins
(cls, items: List["SqlalchemyBase"], db_session: "Session", actor: Optional["User"] = None)
| 391 | @classmethod |
| 392 | @handle_db_timeout |
| 393 | def batch_create(cls, items: List["SqlalchemyBase"], db_session: "Session", actor: Optional["User"] = None) -> List["SqlalchemyBase"]: |
| 394 | """ |
| 395 | Create multiple records in a single transaction for better performance. |
| 396 | Args: |
| 397 | items: List of model instances to create |
| 398 | db_session: SQLAlchemy session |
| 399 | actor: Optional user performing the action |
| 400 | Returns: |
| 401 | List of created model instances |
| 402 | """ |
| 403 | logger.debug(f"Batch creating {len(items)} {cls.__name__} items with actor={actor}") |
| 404 | if not items: |
| 405 | return [] |
| 406 | |
| 407 | # Set created/updated by fields if actor is provided |
| 408 | if actor: |
| 409 | for item in items: |
| 410 | item._set_created_and_updated_by_fields(actor.id) |
| 411 | |
| 412 | try: |
| 413 | with db_session as session: |
| 414 | session.add_all(items) |
| 415 | session.flush() # Flush to generate IDs but don't commit yet |
| 416 | |
| 417 | # Collect IDs to fetch the complete objects after commit |
| 418 | item_ids = [item.id for item in items] |
| 419 | |
| 420 | session.commit() |
| 421 | |
| 422 | # Re-query the objects to get them with relationships loaded |
| 423 | query = select(cls).where(cls.id.in_(item_ids)) |
| 424 | if hasattr(cls, "created_at"): |
| 425 | query = query.order_by(cls.created_at) |
| 426 | |
| 427 | return list(session.execute(query).scalars()) |
| 428 | |
| 429 | except (DBAPIError, IntegrityError) as e: |
| 430 | cls._handle_dbapi_error(e) |
| 431 | |
| 432 | @handle_db_timeout |
| 433 | def delete(self, db_session: "Session", actor: Optional["User"] = None) -> "SqlalchemyBase": |
no test coverage detected