remdb 0.2.6__py3-none-any.whl → 0.3.118__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of remdb might be problematic. Click here for more details.

Files changed (104) hide show
  1. rem/__init__.py +129 -2
  2. rem/agentic/README.md +76 -0
  3. rem/agentic/__init__.py +15 -0
  4. rem/agentic/agents/__init__.py +16 -2
  5. rem/agentic/agents/sse_simulator.py +500 -0
  6. rem/agentic/context.py +28 -22
  7. rem/agentic/llm_provider_models.py +301 -0
  8. rem/agentic/mcp/tool_wrapper.py +29 -3
  9. rem/agentic/otel/setup.py +92 -4
  10. rem/agentic/providers/phoenix.py +32 -43
  11. rem/agentic/providers/pydantic_ai.py +168 -24
  12. rem/agentic/schema.py +358 -21
  13. rem/agentic/tools/rem_tools.py +3 -3
  14. rem/api/README.md +238 -1
  15. rem/api/deps.py +255 -0
  16. rem/api/main.py +154 -37
  17. rem/api/mcp_router/resources.py +1 -1
  18. rem/api/mcp_router/server.py +26 -5
  19. rem/api/mcp_router/tools.py +454 -7
  20. rem/api/middleware/tracking.py +172 -0
  21. rem/api/routers/admin.py +494 -0
  22. rem/api/routers/auth.py +124 -0
  23. rem/api/routers/chat/completions.py +152 -16
  24. rem/api/routers/chat/models.py +7 -3
  25. rem/api/routers/chat/sse_events.py +526 -0
  26. rem/api/routers/chat/streaming.py +608 -45
  27. rem/api/routers/dev.py +81 -0
  28. rem/api/routers/feedback.py +148 -0
  29. rem/api/routers/messages.py +473 -0
  30. rem/api/routers/models.py +78 -0
  31. rem/api/routers/query.py +360 -0
  32. rem/api/routers/shared_sessions.py +406 -0
  33. rem/auth/middleware.py +126 -27
  34. rem/cli/commands/README.md +237 -64
  35. rem/cli/commands/ask.py +15 -11
  36. rem/cli/commands/cluster.py +1300 -0
  37. rem/cli/commands/configure.py +170 -97
  38. rem/cli/commands/db.py +396 -139
  39. rem/cli/commands/experiments.py +278 -96
  40. rem/cli/commands/process.py +22 -15
  41. rem/cli/commands/scaffold.py +47 -0
  42. rem/cli/commands/schema.py +97 -50
  43. rem/cli/main.py +37 -6
  44. rem/config.py +2 -2
  45. rem/models/core/core_model.py +7 -1
  46. rem/models/core/rem_query.py +5 -2
  47. rem/models/entities/__init__.py +21 -0
  48. rem/models/entities/domain_resource.py +38 -0
  49. rem/models/entities/feedback.py +123 -0
  50. rem/models/entities/message.py +30 -1
  51. rem/models/entities/session.py +83 -0
  52. rem/models/entities/shared_session.py +180 -0
  53. rem/models/entities/user.py +10 -3
  54. rem/registry.py +373 -0
  55. rem/schemas/agents/rem.yaml +7 -3
  56. rem/services/content/providers.py +94 -140
  57. rem/services/content/service.py +115 -24
  58. rem/services/dreaming/affinity_service.py +2 -16
  59. rem/services/dreaming/moment_service.py +2 -15
  60. rem/services/embeddings/api.py +24 -17
  61. rem/services/embeddings/worker.py +16 -16
  62. rem/services/phoenix/EXPERIMENT_DESIGN.md +3 -3
  63. rem/services/phoenix/client.py +252 -19
  64. rem/services/postgres/README.md +159 -15
  65. rem/services/postgres/__init__.py +2 -1
  66. rem/services/postgres/diff_service.py +531 -0
  67. rem/services/postgres/pydantic_to_sqlalchemy.py +427 -129
  68. rem/services/postgres/repository.py +132 -0
  69. rem/services/postgres/schema_generator.py +291 -9
  70. rem/services/postgres/service.py +6 -6
  71. rem/services/rate_limit.py +113 -0
  72. rem/services/rem/README.md +14 -0
  73. rem/services/rem/parser.py +44 -9
  74. rem/services/rem/service.py +36 -2
  75. rem/services/session/compression.py +17 -1
  76. rem/services/session/reload.py +1 -1
  77. rem/services/user_service.py +98 -0
  78. rem/settings.py +169 -22
  79. rem/sql/background_indexes.sql +21 -16
  80. rem/sql/migrations/001_install.sql +387 -54
  81. rem/sql/migrations/002_install_models.sql +2320 -393
  82. rem/sql/migrations/003_optional_extensions.sql +326 -0
  83. rem/sql/migrations/004_cache_system.sql +548 -0
  84. rem/utils/__init__.py +18 -0
  85. rem/utils/constants.py +97 -0
  86. rem/utils/date_utils.py +228 -0
  87. rem/utils/embeddings.py +17 -4
  88. rem/utils/files.py +167 -0
  89. rem/utils/mime_types.py +158 -0
  90. rem/utils/model_helpers.py +156 -1
  91. rem/utils/schema_loader.py +284 -21
  92. rem/utils/sql_paths.py +146 -0
  93. rem/utils/sql_types.py +3 -1
  94. rem/utils/vision.py +9 -14
  95. rem/workers/README.md +14 -14
  96. rem/workers/__init__.py +2 -1
  97. rem/workers/db_maintainer.py +74 -0
  98. rem/workers/unlogged_maintainer.py +463 -0
  99. {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/METADATA +598 -171
  100. {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/RECORD +102 -73
  101. {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/WHEEL +1 -1
  102. rem/sql/002_install_models.sql +0 -1068
  103. rem/sql/install_models.sql +0 -1038
  104. {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/entry_points.txt +0 -0
@@ -15,6 +15,9 @@ Available Tools:
15
15
  - ask_rem_agent: Natural language to REM query conversion via agent
16
16
  - ingest_into_rem: Full file ingestion pipeline (read + store + parse + chunk)
17
17
  - read_resource: Access MCP resources (for Claude Desktop compatibility)
18
+ - register_metadata: Register response metadata for SSE MetadataEvent
19
+ - list_schema: List all schemas (tables, agents) in the database with row counts
20
+ - get_schema: Get detailed schema for a table (columns, types, indexes)
18
21
  """
19
22
 
20
23
  from functools import wraps
@@ -53,7 +56,7 @@ def init_services(postgres_service: PostgresService, rem_service: RemService):
53
56
  """
54
57
  _service_cache["postgres"] = postgres_service
55
58
  _service_cache["rem"] = rem_service
56
- logger.info("MCP tools initialized with service instances")
59
+ logger.debug("MCP tools initialized with service instances")
57
60
 
58
61
 
59
62
  async def get_rem_service() -> RemService:
@@ -79,7 +82,7 @@ async def get_rem_service() -> RemService:
79
82
  _service_cache["postgres"] = postgres_service
80
83
  _service_cache["rem"] = rem_service
81
84
 
82
- logger.info("MCP tools: lazy initialized services")
85
+ logger.debug("MCP tools: lazy initialized services")
83
86
  return rem_service
84
87
 
85
88
 
@@ -399,14 +402,14 @@ async def ask_rem_agent(
399
402
  )
400
403
 
401
404
  # Run agent (errors handled by decorator)
402
- logger.info(f"Running ask_rem agent for query: {query[:100]}...")
405
+ logger.debug(f"Running ask_rem agent for query: {query[:100]}...")
403
406
  result = await agent_runtime.run(query)
404
407
 
405
408
  # Extract output
406
409
  from rem.agentic.serialization import serialize_agent_result
407
410
  query_output = serialize_agent_result(result.output)
408
411
 
409
- logger.info("Agent execution completed successfully")
412
+ logger.debug("Agent execution completed successfully")
410
413
 
411
414
  return {
412
415
  "response": str(result.output),
@@ -422,6 +425,7 @@ async def ingest_into_rem(
422
425
  tags: list[str] | None = None,
423
426
  is_local_server: bool = False,
424
427
  user_id: str | None = None,
428
+ resource_type: str | None = None,
425
429
  ) -> dict[str, Any]:
426
430
  """
427
431
  Ingest file into REM, creating searchable resources and embeddings.
@@ -448,6 +452,11 @@ async def ingest_into_rem(
448
452
  tags: Optional tags for file
449
453
  is_local_server: True if running as local/stdio MCP server
450
454
  user_id: Optional user identifier (defaults to authenticated user or "default")
455
+ resource_type: Optional resource type for storing chunks (case-insensitive).
456
+ Supports flexible naming:
457
+ - "resource", "resources", "Resource" → Resource (default)
458
+ - "domain-resource", "domain_resource", "DomainResource",
459
+ "domain-resources" → DomainResource (curated internal knowledge)
451
460
 
452
461
  Returns:
453
462
  Dict with:
@@ -478,6 +487,13 @@ async def ingest_into_rem(
478
487
  file_uri="https://example.com/whitepaper.pdf",
479
488
  tags=["research", "whitepaper"]
480
489
  )
490
+
491
+ # Ingest as curated domain knowledge
492
+ ingest_into_rem(
493
+ file_uri="s3://bucket/internal/procedures.pdf",
494
+ resource_type="domain-resource",
495
+ category="procedures"
496
+ )
481
497
  """
482
498
  from ...services.content import ContentService
483
499
 
@@ -493,9 +509,10 @@ async def ingest_into_rem(
493
509
  category=category,
494
510
  tags=tags,
495
511
  is_local_server=is_local_server,
512
+ resource_type=resource_type,
496
513
  )
497
514
 
498
- logger.info(
515
+ logger.debug(
499
516
  f"MCP ingestion complete: {result['file_name']} "
500
517
  f"(status: {result['processing_status']}, "
501
518
  f"resources: {result['resources_created']})"
@@ -550,7 +567,7 @@ async def read_resource(uri: str) -> dict[str, Any]:
550
567
  # Check system status
551
568
  read_resource(uri="rem://status")
552
569
  """
553
- logger.info(f"📖 Reading resource: {uri}")
570
+ logger.debug(f"Reading resource: {uri}")
554
571
 
555
572
  # Import here to avoid circular dependency
556
573
  from .resources import load_resource
@@ -558,7 +575,7 @@ async def read_resource(uri: str) -> dict[str, Any]:
558
575
  # Load resource using the existing resource handler (errors handled by decorator)
559
576
  result = await load_resource(uri)
560
577
 
561
- logger.info(f"Resource loaded successfully: {uri}")
578
+ logger.debug(f"Resource loaded successfully: {uri}")
562
579
 
563
580
  # If result is already a dict, return it
564
581
  if isinstance(result, dict):
@@ -582,3 +599,433 @@ async def read_resource(uri: str) -> dict[str, Any]:
582
599
  "uri": uri,
583
600
  "data": {"content": result},
584
601
  }
602
+
603
+
604
+ async def register_metadata(
605
+ confidence: float | None = None,
606
+ references: list[str] | None = None,
607
+ sources: list[str] | None = None,
608
+ flags: list[str] | None = None,
609
+ # Risk assessment fields (used by mental health agents like Siggy)
610
+ risk_level: str | None = None,
611
+ risk_score: int | None = None,
612
+ risk_reasoning: str | None = None,
613
+ recommended_action: str | None = None,
614
+ # Generic extension - any additional key-value pairs
615
+ extra: dict[str, Any] | None = None,
616
+ ) -> dict[str, Any]:
617
+ """
618
+ Register response metadata to be emitted as an SSE MetadataEvent.
619
+
620
+ Call this tool BEFORE generating your final response to provide structured
621
+ metadata that will be sent to the client alongside your natural language output.
622
+ This allows you to stream conversational responses while still providing
623
+ machine-readable confidence scores, references, and other metadata.
624
+
625
+ **Design Pattern**: Agents can call this once before their final response to
626
+ register metadata that the streaming layer will emit as a MetadataEvent.
627
+ This decouples structured metadata from the response format.
628
+
629
+ Args:
630
+ confidence: Confidence score (0.0-1.0) for the response quality.
631
+ - 0.9-1.0: High confidence, answer is well-supported
632
+ - 0.7-0.9: Medium confidence, some uncertainty
633
+ - 0.5-0.7: Low confidence, significant gaps
634
+ - <0.5: Very uncertain, may need clarification
635
+ references: List of reference identifiers (file paths, document IDs,
636
+ entity labels) that support the response.
637
+ sources: List of source descriptions (e.g., "REM database",
638
+ "search results", "user context").
639
+ flags: Optional flags for the response (e.g., "needs_review",
640
+ "uncertain", "incomplete", "crisis_alert").
641
+
642
+ risk_level: Risk level indicator (e.g., "green", "orange", "red").
643
+ Used by mental health agents for C-SSRS style assessment.
644
+ risk_score: Numeric risk score (e.g., 0-6 for C-SSRS).
645
+ risk_reasoning: Brief explanation of risk assessment.
646
+ recommended_action: Suggested next steps based on assessment.
647
+
648
+ extra: Dict of arbitrary additional metadata. Use this for any
649
+ domain-specific fields not covered by the standard parameters.
650
+ Example: {"topics_detected": ["anxiety", "sleep"], "session_count": 5}
651
+
652
+ Returns:
653
+ Dict with:
654
+ - status: "success"
655
+ - _metadata_event: True (marker for streaming layer)
656
+ - All provided fields merged into response
657
+
658
+ Examples:
659
+ # High confidence answer with references
660
+ register_metadata(
661
+ confidence=0.95,
662
+ references=["sarah-chen", "q3-report-2024"],
663
+ sources=["REM database lookup"]
664
+ )
665
+
666
+ # Mental health risk assessment (Siggy-style)
667
+ register_metadata(
668
+ confidence=0.9,
669
+ risk_level="green",
670
+ risk_score=0,
671
+ risk_reasoning="No risk indicators detected in message",
672
+ sources=["mental_health_resources"]
673
+ )
674
+
675
+ # Orange risk with recommended action
676
+ register_metadata(
677
+ risk_level="orange",
678
+ risk_score=2,
679
+ risk_reasoning="Passive ideation detected - 'feeling hopeless'",
680
+ recommended_action="Schedule care team check-in within 24-48 hours",
681
+ flags=["care_team_alert"]
682
+ )
683
+
684
+ # Custom domain-specific metadata
685
+ register_metadata(
686
+ confidence=0.8,
687
+ extra={
688
+ "topics_detected": ["medication", "side_effects"],
689
+ "drug_mentioned": "sertraline",
690
+ "sentiment": "concerned"
691
+ }
692
+ )
693
+ """
694
+ logger.debug(
695
+ f"Registering metadata: confidence={confidence}, "
696
+ f"risk_level={risk_level}, refs={len(references or [])}, "
697
+ f"sources={len(sources or [])}"
698
+ )
699
+
700
+ result = {
701
+ "status": "success",
702
+ "_metadata_event": True, # Marker for streaming layer
703
+ "confidence": confidence,
704
+ "references": references,
705
+ "sources": sources,
706
+ "flags": flags,
707
+ }
708
+
709
+ # Add risk assessment fields if provided
710
+ if risk_level is not None:
711
+ result["risk_level"] = risk_level
712
+ if risk_score is not None:
713
+ result["risk_score"] = risk_score
714
+ if risk_reasoning is not None:
715
+ result["risk_reasoning"] = risk_reasoning
716
+ if recommended_action is not None:
717
+ result["recommended_action"] = recommended_action
718
+
719
+ # Merge any extra fields
720
+ if extra:
721
+ result["extra"] = extra
722
+
723
+ return result
724
+
725
+
726
+ @mcp_tool_error_handler
727
+ async def list_schema(
728
+ include_system: bool = False,
729
+ user_id: str | None = None,
730
+ ) -> dict[str, Any]:
731
+ """
732
+ List all schemas (tables) in the REM database.
733
+
734
+ Returns metadata about all available tables including their names,
735
+ row counts, and descriptions. Use this to discover what data is
736
+ available before constructing queries.
737
+
738
+ Args:
739
+ include_system: If True, include PostgreSQL system tables (pg_*, information_schema).
740
+ Default False shows only REM application tables.
741
+ user_id: Optional user identifier (defaults to authenticated user or "default")
742
+
743
+ Returns:
744
+ Dict with:
745
+ - status: "success" or "error"
746
+ - tables: List of table metadata dicts with:
747
+ - name: Table name
748
+ - schema: Schema name (usually "public")
749
+ - estimated_rows: Approximate row count
750
+ - description: Table comment if available
751
+
752
+ Examples:
753
+ # List all REM schemas
754
+ list_schema()
755
+
756
+ # Include system tables
757
+ list_schema(include_system=True)
758
+ """
759
+ rem_service = await get_rem_service()
760
+ user_id = AgentContext.get_user_id_or_default(user_id, source="list_schema")
761
+
762
+ # Query information_schema for tables
763
+ schema_filter = ""
764
+ if not include_system:
765
+ schema_filter = """
766
+ AND table_schema = 'public'
767
+ AND table_name NOT LIKE 'pg_%'
768
+ AND table_name NOT LIKE '_pg_%'
769
+ """
770
+
771
+ query = f"""
772
+ SELECT
773
+ t.table_schema,
774
+ t.table_name,
775
+ pg_catalog.obj_description(
776
+ (quote_ident(t.table_schema) || '.' || quote_ident(t.table_name))::regclass,
777
+ 'pg_class'
778
+ ) as description,
779
+ (
780
+ SELECT reltuples::bigint
781
+ FROM pg_class c
782
+ JOIN pg_namespace n ON n.oid = c.relnamespace
783
+ WHERE c.relname = t.table_name
784
+ AND n.nspname = t.table_schema
785
+ ) as estimated_rows
786
+ FROM information_schema.tables t
787
+ WHERE t.table_type = 'BASE TABLE'
788
+ {schema_filter}
789
+ ORDER BY t.table_schema, t.table_name
790
+ """
791
+
792
+ # Access postgres service directly from cache
793
+ postgres_service = _service_cache.get("postgres")
794
+ if not postgres_service:
795
+ postgres_service = rem_service._postgres
796
+
797
+ rows = await postgres_service.fetch(query)
798
+
799
+ tables = []
800
+ for row in rows:
801
+ tables.append({
802
+ "name": row["table_name"],
803
+ "schema": row["table_schema"],
804
+ "estimated_rows": int(row["estimated_rows"]) if row["estimated_rows"] else 0,
805
+ "description": row["description"],
806
+ })
807
+
808
+ logger.info(f"Listed {len(tables)} schemas for user {user_id}")
809
+
810
+ return {
811
+ "tables": tables,
812
+ "count": len(tables),
813
+ }
814
+
815
+
816
+ @mcp_tool_error_handler
817
+ async def get_schema(
818
+ table_name: str,
819
+ include_indexes: bool = True,
820
+ include_constraints: bool = True,
821
+ columns: list[str] | None = None,
822
+ user_id: str | None = None,
823
+ ) -> dict[str, Any]:
824
+ """
825
+ Get detailed schema information for a specific table.
826
+
827
+ Returns column definitions, data types, constraints, and indexes.
828
+ Use this to understand table structure before writing SQL queries.
829
+
830
+ Args:
831
+ table_name: Name of the table to inspect (e.g., "resources", "moments")
832
+ include_indexes: Include index information (default True)
833
+ include_constraints: Include constraint information (default True)
834
+ columns: Optional list of specific columns to return. If None, returns all columns.
835
+ user_id: Optional user identifier (defaults to authenticated user or "default")
836
+
837
+ Returns:
838
+ Dict with:
839
+ - status: "success" or "error"
840
+ - table_name: Name of the table
841
+ - columns: List of column definitions with:
842
+ - name: Column name
843
+ - type: PostgreSQL data type
844
+ - nullable: Whether NULL is allowed
845
+ - default: Default value if any
846
+ - description: Column comment if available
847
+ - indexes: List of indexes (if include_indexes=True)
848
+ - constraints: List of constraints (if include_constraints=True)
849
+ - primary_key: Primary key column(s)
850
+
851
+ Examples:
852
+ # Get full schema for resources table
853
+ get_schema(table_name="resources")
854
+
855
+ # Get only specific columns
856
+ get_schema(
857
+ table_name="resources",
858
+ columns=["id", "name", "created_at"]
859
+ )
860
+
861
+ # Get schema without indexes
862
+ get_schema(
863
+ table_name="moments",
864
+ include_indexes=False
865
+ )
866
+ """
867
+ rem_service = await get_rem_service()
868
+ user_id = AgentContext.get_user_id_or_default(user_id, source="get_schema")
869
+
870
+ # Access postgres service
871
+ postgres_service = _service_cache.get("postgres")
872
+ if not postgres_service:
873
+ postgres_service = rem_service._postgres
874
+
875
+ # Verify table exists
876
+ exists_query = """
877
+ SELECT EXISTS (
878
+ SELECT 1 FROM information_schema.tables
879
+ WHERE table_schema = 'public' AND table_name = $1
880
+ )
881
+ """
882
+ exists = await postgres_service.fetchval(exists_query, table_name)
883
+ if not exists:
884
+ return {
885
+ "status": "error",
886
+ "error": f"Table '{table_name}' not found in public schema",
887
+ }
888
+
889
+ # Get columns
890
+ columns_filter = ""
891
+ if columns:
892
+ placeholders = ", ".join(f"${i+2}" for i in range(len(columns)))
893
+ columns_filter = f"AND column_name IN ({placeholders})"
894
+
895
+ columns_query = f"""
896
+ SELECT
897
+ c.column_name,
898
+ c.data_type,
899
+ c.udt_name,
900
+ c.is_nullable,
901
+ c.column_default,
902
+ c.character_maximum_length,
903
+ c.numeric_precision,
904
+ pg_catalog.col_description(
905
+ (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass,
906
+ c.ordinal_position
907
+ ) as description
908
+ FROM information_schema.columns c
909
+ WHERE c.table_schema = 'public'
910
+ AND c.table_name = $1
911
+ {columns_filter}
912
+ ORDER BY c.ordinal_position
913
+ """
914
+
915
+ params = [table_name]
916
+ if columns:
917
+ params.extend(columns)
918
+
919
+ column_rows = await postgres_service.fetch(columns_query, *params)
920
+
921
+ column_defs = []
922
+ for row in column_rows:
923
+ # Build a more readable type string
924
+ data_type = row["data_type"]
925
+ if row["character_maximum_length"]:
926
+ data_type = f"{data_type}({row['character_maximum_length']})"
927
+ elif row["udt_name"] in ("int4", "int8", "float4", "float8"):
928
+ # Use common type names
929
+ type_map = {"int4": "integer", "int8": "bigint", "float4": "real", "float8": "double precision"}
930
+ data_type = type_map.get(row["udt_name"], data_type)
931
+ elif row["udt_name"] == "vector":
932
+ data_type = "vector"
933
+
934
+ column_defs.append({
935
+ "name": row["column_name"],
936
+ "type": data_type,
937
+ "nullable": row["is_nullable"] == "YES",
938
+ "default": row["column_default"],
939
+ "description": row["description"],
940
+ })
941
+
942
+ result = {
943
+ "table_name": table_name,
944
+ "columns": column_defs,
945
+ "column_count": len(column_defs),
946
+ }
947
+
948
+ # Get primary key
949
+ pk_query = """
950
+ SELECT a.attname as column_name
951
+ FROM pg_index i
952
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
953
+ WHERE i.indrelid = $1::regclass
954
+ AND i.indisprimary
955
+ ORDER BY array_position(i.indkey, a.attnum)
956
+ """
957
+ pk_rows = await postgres_service.fetch(pk_query, table_name)
958
+ result["primary_key"] = [row["column_name"] for row in pk_rows]
959
+
960
+ # Get indexes
961
+ if include_indexes:
962
+ indexes_query = """
963
+ SELECT
964
+ i.relname as index_name,
965
+ am.amname as index_type,
966
+ ix.indisunique as is_unique,
967
+ ix.indisprimary as is_primary,
968
+ array_agg(a.attname ORDER BY array_position(ix.indkey, a.attnum)) as columns
969
+ FROM pg_index ix
970
+ JOIN pg_class i ON i.oid = ix.indexrelid
971
+ JOIN pg_class t ON t.oid = ix.indrelid
972
+ JOIN pg_am am ON am.oid = i.relam
973
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
974
+ WHERE t.relname = $1
975
+ GROUP BY i.relname, am.amname, ix.indisunique, ix.indisprimary
976
+ ORDER BY i.relname
977
+ """
978
+ index_rows = await postgres_service.fetch(indexes_query, table_name)
979
+ result["indexes"] = [
980
+ {
981
+ "name": row["index_name"],
982
+ "type": row["index_type"],
983
+ "unique": row["is_unique"],
984
+ "primary": row["is_primary"],
985
+ "columns": row["columns"],
986
+ }
987
+ for row in index_rows
988
+ ]
989
+
990
+ # Get constraints
991
+ if include_constraints:
992
+ constraints_query = """
993
+ SELECT
994
+ con.conname as constraint_name,
995
+ con.contype as constraint_type,
996
+ array_agg(a.attname ORDER BY array_position(con.conkey, a.attnum)) as columns,
997
+ pg_get_constraintdef(con.oid) as definition
998
+ FROM pg_constraint con
999
+ JOIN pg_class t ON t.oid = con.conrelid
1000
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(con.conkey)
1001
+ WHERE t.relname = $1
1002
+ GROUP BY con.conname, con.contype, con.oid
1003
+ ORDER BY con.contype, con.conname
1004
+ """
1005
+ constraint_rows = await postgres_service.fetch(constraints_query, table_name)
1006
+
1007
+ # Map constraint types to readable names
1008
+ type_map = {
1009
+ "p": "PRIMARY KEY",
1010
+ "u": "UNIQUE",
1011
+ "f": "FOREIGN KEY",
1012
+ "c": "CHECK",
1013
+ "x": "EXCLUSION",
1014
+ }
1015
+
1016
+ result["constraints"] = []
1017
+ for row in constraint_rows:
1018
+ # contype is returned as bytes (char type), decode it
1019
+ con_type = row["constraint_type"]
1020
+ if isinstance(con_type, bytes):
1021
+ con_type = con_type.decode("utf-8")
1022
+ result["constraints"].append({
1023
+ "name": row["constraint_name"],
1024
+ "type": type_map.get(con_type, con_type),
1025
+ "columns": row["columns"],
1026
+ "definition": row["definition"],
1027
+ })
1028
+
1029
+ logger.info(f"Retrieved schema for table '{table_name}' with {len(column_defs)} columns")
1030
+
1031
+ return result