postgres.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """PostgreSQL adapter for query-planning-owned tables only."""
  2. from __future__ import annotations
  3. from typing import Any
  4. from uuid import UUID
  5. import psycopg2.extras
  6. from query_planning.domain import KnowledgeNeedDraft
  7. Json = psycopg2.extras.Json
  8. psycopg2.extras.register_uuid()
  9. class PostgresQueryPlanningStore:
  10. def __init__(self, conn: Any) -> None:
  11. self.conn = conn
  12. def _id(self, sql: str, params: tuple[Any, ...]) -> UUID:
  13. with self.conn.cursor() as cur:
  14. cur.execute(sql, params)
  15. row = cur.fetchone()
  16. if row is None:
  17. raise RuntimeError("query planning insert returned no id")
  18. return row[0]
  19. def create_plan(self, **kwargs: Any) -> UUID:
  20. return self._id(
  21. """
  22. INSERT INTO creation_knowledge.query_plans(
  23. generator_kind, status, input_snapshot, generator_config,
  24. max_queries, generated_count, normalized_count, unique_count,
  25. selected_count, dropped_count, metadata
  26. )
  27. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  28. RETURNING id
  29. """,
  30. (
  31. kwargs["generator_kind"],
  32. kwargs["status"],
  33. Json(kwargs.get("input_snapshot") or {}),
  34. Json(kwargs.get("generator_config") or {}),
  35. kwargs.get("max_queries"),
  36. kwargs["generated_count"],
  37. kwargs["normalized_count"],
  38. kwargs["unique_count"],
  39. kwargs["selected_count"],
  40. kwargs["dropped_count"],
  41. Json(kwargs.get("metadata") or {}),
  42. ),
  43. )
  44. def add_knowledge_need(self, *, plan_id: UUID, need: KnowledgeNeedDraft) -> UUID:
  45. return self._id(
  46. """
  47. INSERT INTO creation_knowledge.knowledge_needs(
  48. plan_id, need_key, decision_context, unknown_information,
  49. source_ref, priority, metadata
  50. )
  51. VALUES (%s, %s, %s, %s, %s, %s, %s)
  52. RETURNING id
  53. """,
  54. (
  55. plan_id,
  56. need.need_key,
  57. need.decision_context,
  58. need.unknown_information,
  59. Json(need.source_ref),
  60. need.priority,
  61. Json(need.metadata),
  62. ),
  63. )
  64. def link_plan_batch(self, *, plan_id: UUID, batch_id: UUID) -> None:
  65. with self.conn.cursor() as cur:
  66. cur.execute(
  67. """
  68. INSERT INTO creation_knowledge.query_plan_batches(plan_id, batch_id)
  69. VALUES (%s, %s)
  70. ON CONFLICT DO NOTHING
  71. """,
  72. (plan_id, batch_id),
  73. )
  74. def link_query_need(self, *, query_id: UUID, knowledge_need_id: UUID) -> None:
  75. with self.conn.cursor() as cur:
  76. cur.execute(
  77. """
  78. INSERT INTO creation_knowledge.query_knowledge_need_links(
  79. query_id, knowledge_need_id
  80. )
  81. VALUES (%s, %s)
  82. ON CONFLICT DO NOTHING
  83. """,
  84. (query_id, knowledge_need_id),
  85. )