|
3 | 3 | from pathlib import Path |
4 | 4 | from typing import List, Optional, Sequence, Union |
5 | 5 |
|
| 6 | +from sqlalchemy import select |
| 7 | +from sqlalchemy.exc import IntegrityError |
6 | 8 | from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker |
7 | 9 | from sqlalchemy.orm import selectinload |
8 | 10 | from sqlalchemy.orm.interfaces import LoaderOption |
9 | 11 |
|
| 12 | +from basic_memory import db |
10 | 13 | from basic_memory.models.knowledge import Entity, Observation, Relation |
11 | 14 | from basic_memory.repository.repository import Repository |
12 | 15 |
|
@@ -96,3 +99,153 @@ async def find_by_permalinks(self, permalinks: List[str]) -> Sequence[Entity]: |
96 | 99 |
|
97 | 100 | result = await self.execute_query(query) |
98 | 101 | return list(result.scalars().all()) |
| 102 | + |
| 103 | + async def upsert_entity(self, entity: Entity) -> Entity: |
| 104 | + """Insert or update entity using a hybrid approach. |
| 105 | + |
| 106 | + This method provides a cleaner alternative to the try/catch approach |
| 107 | + for handling permalink and file_path conflicts. It first tries direct |
| 108 | + insertion, then handles conflicts intelligently. |
| 109 | + |
| 110 | + Args: |
| 111 | + entity: The entity to insert or update |
| 112 | + |
| 113 | + Returns: |
| 114 | + The inserted or updated entity |
| 115 | + """ |
| 116 | + |
| 117 | + async with db.scoped_session(self.session_maker) as session: |
| 118 | + # Set project_id if applicable and not already set |
| 119 | + self._set_project_id_if_needed(entity) |
| 120 | + |
| 121 | + # Check for existing entity with same file_path first |
| 122 | + existing_by_path = await session.execute( |
| 123 | + select(Entity).where( |
| 124 | + Entity.file_path == entity.file_path, |
| 125 | + Entity.project_id == entity.project_id |
| 126 | + ) |
| 127 | + ) |
| 128 | + existing_path_entity = existing_by_path.scalar_one_or_none() |
| 129 | + |
| 130 | + if existing_path_entity: |
| 131 | + # Update existing entity with same file path |
| 132 | + for key, value in { |
| 133 | + 'title': entity.title, |
| 134 | + 'entity_type': entity.entity_type, |
| 135 | + 'entity_metadata': entity.entity_metadata, |
| 136 | + 'content_type': entity.content_type, |
| 137 | + 'permalink': entity.permalink, |
| 138 | + 'checksum': entity.checksum, |
| 139 | + 'updated_at': entity.updated_at, |
| 140 | + }.items(): |
| 141 | + setattr(existing_path_entity, key, value) |
| 142 | + |
| 143 | + await session.flush() |
| 144 | + # Return with relationships loaded |
| 145 | + query = ( |
| 146 | + select(Entity) |
| 147 | + .where(Entity.file_path == entity.file_path) |
| 148 | + .options(*self.get_load_options()) |
| 149 | + ) |
| 150 | + result = await session.execute(query) |
| 151 | + found = result.scalar_one_or_none() |
| 152 | + if not found: # pragma: no cover |
| 153 | + raise RuntimeError(f"Failed to retrieve entity after update: {entity.file_path}") |
| 154 | + return found |
| 155 | + |
| 156 | + # No existing entity with same file_path, try insert |
| 157 | + try: |
| 158 | + # Simple insert for new entity |
| 159 | + session.add(entity) |
| 160 | + await session.flush() |
| 161 | + |
| 162 | + # Return with relationships loaded |
| 163 | + query = ( |
| 164 | + select(Entity) |
| 165 | + .where(Entity.file_path == entity.file_path) |
| 166 | + .options(*self.get_load_options()) |
| 167 | + ) |
| 168 | + result = await session.execute(query) |
| 169 | + found = result.scalar_one_or_none() |
| 170 | + if not found: # pragma: no cover |
| 171 | + raise RuntimeError(f"Failed to retrieve entity after insert: {entity.file_path}") |
| 172 | + return found |
| 173 | + |
| 174 | + except IntegrityError: |
| 175 | + # Could be either file_path or permalink conflict |
| 176 | + await session.rollback() |
| 177 | + |
| 178 | + # Check if it's a file_path conflict (race condition) |
| 179 | + existing_by_path_check = await session.execute( |
| 180 | + select(Entity).where( |
| 181 | + Entity.file_path == entity.file_path, |
| 182 | + Entity.project_id == entity.project_id |
| 183 | + ) |
| 184 | + ) |
| 185 | + race_condition_entity = existing_by_path_check.scalar_one_or_none() |
| 186 | + |
| 187 | + if race_condition_entity: |
| 188 | + # Race condition: file_path conflict detected after our initial check |
| 189 | + # Update the existing entity instead |
| 190 | + for key, value in { |
| 191 | + 'title': entity.title, |
| 192 | + 'entity_type': entity.entity_type, |
| 193 | + 'entity_metadata': entity.entity_metadata, |
| 194 | + 'content_type': entity.content_type, |
| 195 | + 'permalink': entity.permalink, |
| 196 | + 'checksum': entity.checksum, |
| 197 | + 'updated_at': entity.updated_at, |
| 198 | + }.items(): |
| 199 | + setattr(race_condition_entity, key, value) |
| 200 | + |
| 201 | + await session.flush() |
| 202 | + # Return the updated entity with relationships loaded |
| 203 | + query = ( |
| 204 | + select(Entity) |
| 205 | + .where(Entity.file_path == entity.file_path) |
| 206 | + .options(*self.get_load_options()) |
| 207 | + ) |
| 208 | + result = await session.execute(query) |
| 209 | + found = result.scalar_one_or_none() |
| 210 | + if not found: # pragma: no cover |
| 211 | + raise RuntimeError(f"Failed to retrieve entity after race condition update: {entity.file_path}") |
| 212 | + return found |
| 213 | + else: |
| 214 | + # Must be permalink conflict - generate unique permalink |
| 215 | + return await self._handle_permalink_conflict(entity, session) |
| 216 | + |
| 217 | + async def _handle_permalink_conflict(self, entity: Entity, session: AsyncSession) -> Entity: |
| 218 | + """Handle permalink conflicts by generating a unique permalink.""" |
| 219 | + base_permalink = entity.permalink |
| 220 | + suffix = 1 |
| 221 | + |
| 222 | + # Find a unique permalink |
| 223 | + while True: |
| 224 | + test_permalink = f"{base_permalink}-{suffix}" |
| 225 | + existing = await session.execute( |
| 226 | + select(Entity).where( |
| 227 | + Entity.permalink == test_permalink, |
| 228 | + Entity.project_id == entity.project_id |
| 229 | + ) |
| 230 | + ) |
| 231 | + if existing.scalar_one_or_none() is None: |
| 232 | + # Found unique permalink |
| 233 | + entity.permalink = test_permalink |
| 234 | + break |
| 235 | + suffix += 1 |
| 236 | + |
| 237 | + # Insert with unique permalink (no conflict possible now) |
| 238 | + session.add(entity) |
| 239 | + await session.flush() |
| 240 | + |
| 241 | + # Return the inserted entity with relationships loaded |
| 242 | + query = ( |
| 243 | + select(Entity) |
| 244 | + .where(Entity.file_path == entity.file_path) |
| 245 | + .options(*self.get_load_options()) |
| 246 | + ) |
| 247 | + result = await session.execute(query) |
| 248 | + found = result.scalar_one_or_none() |
| 249 | + if not found: # pragma: no cover |
| 250 | + raise RuntimeError(f"Failed to retrieve entity after insert: {entity.file_path}") |
| 251 | + return found |
0 commit comments