files.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import io
  2. import logging
  3. from typing import BinaryIO, Optional, Union
  4. from uuid import UUID
  5. import asyncpg
  6. from fastapi import HTTPException
  7. from core.base import Handler, R2RException
  8. from .base import PostgresConnectionManager
  9. logger = logging.getLogger()
  10. class PostgresFilesHandler(Handler):
  11. """PostgreSQL implementation of the FileHandler."""
  12. TABLE_NAME = "files"
  13. connection_manager: PostgresConnectionManager
  14. async def create_tables(self) -> None:
  15. """Create the necessary tables for file storage."""
  16. query = f"""
  17. CREATE TABLE IF NOT EXISTS {self._get_table_name(PostgresFilesHandler.TABLE_NAME)} (
  18. document_id UUID PRIMARY KEY,
  19. name TEXT NOT NULL,
  20. oid OID NOT NULL,
  21. size BIGINT NOT NULL,
  22. type TEXT,
  23. created_at TIMESTAMPTZ DEFAULT NOW(),
  24. updated_at TIMESTAMPTZ DEFAULT NOW()
  25. );
  26. -- Create trigger for updating the updated_at timestamp
  27. CREATE OR REPLACE FUNCTION {self.project_name}.update_files_updated_at()
  28. RETURNS TRIGGER AS $$
  29. BEGIN
  30. NEW.updated_at = CURRENT_TIMESTAMP;
  31. RETURN NEW;
  32. END;
  33. $$ LANGUAGE plpgsql;
  34. DROP TRIGGER IF EXISTS update_files_updated_at
  35. ON {self._get_table_name(PostgresFilesHandler.TABLE_NAME)};
  36. CREATE TRIGGER update_files_updated_at
  37. BEFORE UPDATE ON {self._get_table_name(PostgresFilesHandler.TABLE_NAME)}
  38. FOR EACH ROW
  39. EXECUTE FUNCTION {self.project_name}.update_files_updated_at();
  40. """
  41. await self.connection_manager.execute_query(query)
  42. async def upsert_file(
  43. self,
  44. document_id: UUID,
  45. file_name: str,
  46. file_oid: int,
  47. file_size: int,
  48. file_type: Optional[str] = None,
  49. ) -> None:
  50. """Add or update a file entry in storage."""
  51. query = f"""
  52. INSERT INTO {self._get_table_name(PostgresFilesHandler.TABLE_NAME)}
  53. (document_id, name, oid, size, type)
  54. VALUES ($1, $2, $3, $4, $5)
  55. ON CONFLICT (document_id) DO UPDATE SET
  56. name = EXCLUDED.name,
  57. oid = EXCLUDED.oid,
  58. size = EXCLUDED.size,
  59. type = EXCLUDED.type,
  60. updated_at = NOW();
  61. """
  62. await self.connection_manager.execute_query(
  63. query, [document_id, file_name, file_oid, file_size, file_type]
  64. )
  65. async def store_file(
  66. self,
  67. document_id: UUID,
  68. file_name: str,
  69. file_content: io.BytesIO,
  70. file_type: Optional[str] = None,
  71. ) -> None:
  72. """Store a new file in the database."""
  73. size = file_content.getbuffer().nbytes
  74. async with ( # type: ignore
  75. self.connection_manager.pool.get_connection() as conn
  76. ):
  77. async with conn.transaction():
  78. oid = await conn.fetchval("SELECT lo_create(0)")
  79. await self._write_lobject(conn, oid, file_content)
  80. await self.upsert_file(
  81. document_id, file_name, oid, size, file_type
  82. )
  83. async def _write_lobject(
  84. self, conn, oid: int, file_content: io.BytesIO
  85. ) -> None:
  86. """Write content to a large object."""
  87. lobject = await conn.fetchval("SELECT lo_open($1, $2)", oid, 0x20000)
  88. try:
  89. chunk_size = 8192 # 8 KB chunks
  90. while True:
  91. if chunk := file_content.read(chunk_size):
  92. await conn.execute(
  93. "SELECT lowrite($1, $2)", lobject, chunk
  94. )
  95. else:
  96. break
  97. await conn.execute("SELECT lo_close($1)", lobject)
  98. except Exception as e:
  99. await conn.execute("SELECT lo_unlink($1)", oid)
  100. raise HTTPException(
  101. status_code=500,
  102. detail=f"Failed to write to large object: {e}",
  103. )
  104. async def retrieve_file(
  105. self, document_id: UUID
  106. ) -> Optional[tuple[str, BinaryIO, int]]:
  107. """Retrieve a file from storage."""
  108. query = f"""
  109. SELECT name, oid, size
  110. FROM {self._get_table_name(PostgresFilesHandler.TABLE_NAME)}
  111. WHERE document_id = $1
  112. """
  113. result = await self.connection_manager.fetchrow_query(
  114. query, [document_id]
  115. )
  116. if not result:
  117. raise R2RException(
  118. status_code=404,
  119. message=f"File for document {document_id} not found",
  120. )
  121. file_name, oid, size = (
  122. result["name"],
  123. result["oid"],
  124. result["size"],
  125. )
  126. async with self.connection_manager.pool.get_connection() as conn: # type: ignore
  127. file_content = await self._read_lobject(conn, oid)
  128. return file_name, io.BytesIO(file_content), size
  129. async def _read_lobject(self, conn, oid: int) -> bytes:
  130. """Read content from a large object."""
  131. file_data = io.BytesIO()
  132. chunk_size = 8192
  133. async with conn.transaction():
  134. try:
  135. lo_exists = await conn.fetchval(
  136. "SELECT EXISTS(SELECT 1 FROM pg_largeobject WHERE loid = $1)",
  137. oid,
  138. )
  139. if not lo_exists:
  140. raise R2RException(
  141. status_code=404,
  142. message=f"Large object {oid} not found.",
  143. )
  144. lobject = await conn.fetchval(
  145. "SELECT lo_open($1, 262144)", oid
  146. )
  147. if lobject is None:
  148. raise R2RException(
  149. status_code=404,
  150. message=f"Failed to open large object {oid}.",
  151. )
  152. while True:
  153. chunk = await conn.fetchval(
  154. "SELECT loread($1, $2)", lobject, chunk_size
  155. )
  156. if not chunk:
  157. break
  158. file_data.write(chunk)
  159. except asyncpg.exceptions.UndefinedObjectError as e:
  160. raise R2RException(
  161. status_code=404,
  162. message=f"Failed to read large object {oid}: {e}",
  163. )
  164. finally:
  165. await conn.execute("SELECT lo_close($1)", lobject)
  166. return file_data.getvalue()
  167. async def delete_file(self, document_id: UUID) -> bool:
  168. """Delete a file from storage."""
  169. query = f"""
  170. SELECT oid FROM {self._get_table_name(PostgresFilesHandler.TABLE_NAME)}
  171. WHERE document_id = $1
  172. """
  173. async with self.connection_manager.pool.get_connection() as conn: # type: ignore
  174. async with conn.transaction():
  175. oid = await conn.fetchval(query, document_id)
  176. if not oid:
  177. raise R2RException(
  178. status_code=404,
  179. message=f"File for document {document_id} not found",
  180. )
  181. await self._delete_lobject(conn, oid)
  182. delete_query = f"""
  183. DELETE FROM {self._get_table_name(PostgresFilesHandler.TABLE_NAME)}
  184. WHERE document_id = $1
  185. """
  186. await conn.execute(delete_query, document_id)
  187. return True
  188. async def _delete_lobject(self, conn, oid: int) -> None:
  189. """Delete a large object."""
  190. await conn.execute("SELECT lo_unlink($1)", oid)
  191. async def get_files_overview(
  192. self,
  193. offset: int,
  194. limit: int,
  195. filter_document_ids: Optional[list[UUID]] = None,
  196. filter_file_names: Optional[list[str]] = None,
  197. ) -> list[dict]:
  198. """Get an overview of stored files."""
  199. conditions = []
  200. params: list[Union[str, list[str], int]] = []
  201. query = f"""
  202. SELECT document_id, name, oid, size, type, created_at, updated_at
  203. FROM {self._get_table_name(PostgresFilesHandler.TABLE_NAME)}
  204. """
  205. if filter_document_ids:
  206. conditions.append(f"document_id = ANY(${len(params) + 1})")
  207. params.append([str(doc_id) for doc_id in filter_document_ids])
  208. if filter_file_names:
  209. conditions.append(f"name = ANY(${len(params) + 1})")
  210. params.append(filter_file_names)
  211. if conditions:
  212. query += " WHERE " + " AND ".join(conditions)
  213. query += f" ORDER BY created_at DESC OFFSET ${len(params) + 1} LIMIT ${len(params) + 2}"
  214. params.extend([offset, limit])
  215. results = await self.connection_manager.fetch_query(query, params)
  216. if not results:
  217. raise R2RException(
  218. status_code=404,
  219. message="No files found with the given filters",
  220. )
  221. return [
  222. {
  223. "document_id": row["document_id"],
  224. "file_name": row["name"],
  225. "file_oid": row["oid"],
  226. "file_size": row["size"],
  227. "file_type": row["type"],
  228. "created_at": row["created_at"],
  229. "updated_at": row["updated_at"],
  230. }
  231. for row in results
  232. ]