postgres

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 19, 2026 License: GPL-3.0 Imports: 12 Imported by: 0

Documentation

Overview

Package postgres provides a PostgreSQL-backed implementation of the three-layer Glyphoxa memory architecture (L1 session log, L2 semantic index, L3 knowledge graph).

All three layers share a single pgxpool.Pool connection pool. The pgvector extension must be available in the target database; Migrate installs it automatically via CREATE EXTENSION IF NOT EXISTS.

Usage:

schema, _ := postgres.NewSchemaName("public")
store, err := postgres.NewStore(ctx, dsn, 1536, schema, "my_campaign")
if err != nil { … }

// L1
_ = store.WriteEntry(ctx, sessionID, entry)

// L2
_ = store.IndexChunk(ctx, chunk)

// L3
_ = store.AddEntity(ctx, entity)

// GraphRAG
results, _ := store.QueryWithContext(ctx, "who is the blacksmith's ally?", scope)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Migrate

func Migrate(ctx context.Context, pool *pgxpool.Pool, embeddingDimensions int, schema SchemaName) error

Migrate creates or ensures all required database tables and extensions exist within the given schema. It is idempotent (CREATE TABLE IF NOT EXISTS / CREATE INDEX IF NOT EXISTS) and safe to call on every application start.

embeddingDimensions must match the vector model configured for your deployment (e.g., 1536 for OpenAI text-embedding-3-small, 768 for nomic-embed-text). Changing this value after the first migration requires a manual schema update.

Types

type RecapStoreImpl added in v0.1.0

type RecapStoreImpl struct {
	// contains filtered or unexported fields
}

RecapStoreImpl is the PostgreSQL-backed implementation of memory.RecapStore. Obtain one via Store.RecapStore rather than constructing directly. All methods are safe for concurrent use.

func (*RecapStoreImpl) GetRecap added in v0.1.0

func (r *RecapStoreImpl) GetRecap(ctx context.Context, sessionID string) (*memory.Recap, error)

GetRecap implements memory.RecapStore.

func (*RecapStoreImpl) SaveRecap added in v0.1.0

func (r *RecapStoreImpl) SaveRecap(ctx context.Context, recap memory.Recap) error

SaveRecap implements memory.RecapStore.

type SchemaName added in v0.0.9

type SchemaName struct {
	// contains filtered or unexported fields
}

SchemaName is a validated PostgreSQL schema identifier. Construction via NewSchemaName is the only way to obtain one, ensuring that unvalidated strings never reach SQL.

func NewSchemaName added in v0.0.9

func NewSchemaName(raw string) (SchemaName, error)

NewSchemaName validates raw against PostgreSQL identifier rules and returns a SchemaName. Returns an error if raw does not match ^[a-z][a-z0-9_]{0,62}$.

func (SchemaName) String added in v0.0.9

func (s SchemaName) String() string

String returns the raw schema name.

func (SchemaName) TableRef added in v0.0.9

func (s SchemaName) TableRef(table string) string

TableRef returns a fully-qualified, properly quoted table reference (e.g., "public"."session_entries").

type SemanticIndexImpl

type SemanticIndexImpl struct {
	// contains filtered or unexported fields
}

SemanticIndexImpl is the L2 memory layer backed by a PostgreSQL chunks table with a pgvector HNSW index for fast approximate nearest-neighbour search.

Obtain one via Store.L2 rather than constructing directly. All methods are safe for concurrent use.

func (*SemanticIndexImpl) IndexChunk

func (s *SemanticIndexImpl) IndexChunk(ctx context.Context, chunk memory.Chunk) error

IndexChunk implements memory.SemanticIndex. It upserts a pre-embedded memory.Chunk into the chunks table. If a chunk with the same ID already exists it is completely replaced.

func (*SemanticIndexImpl) Search

func (s *SemanticIndexImpl) Search(ctx context.Context, embedding []float32, topK int, filter memory.ChunkFilter) ([]memory.ChunkResult, error)

Search implements memory.SemanticIndex. It finds the topK chunks whose embeddings are closest (cosine distance) to the supplied query embedding, optionally filtered by filter.

Results are ordered by ascending cosine distance (most similar first).

type SessionStoreImpl

type SessionStoreImpl struct {
	// contains filtered or unexported fields
}

SessionStoreImpl is the L1 memory layer backed by a PostgreSQL session_entries table with a GIN full-text search index.

Obtain one via Store.L1 rather than constructing directly. All methods are safe for concurrent use.

func (*SessionStoreImpl) EndSession added in v0.1.0

func (s *SessionStoreImpl) EndSession(ctx context.Context, sessionID string) error

EndSession sets the ended_at timestamp for a session.

func (*SessionStoreImpl) EntryCount added in v0.0.3

func (s *SessionStoreImpl) EntryCount(ctx context.Context, sessionID string) (int, error)

EntryCount implements memory.SessionStore. It returns the total number of transcript entries for sessionID.

func (*SessionStoreImpl) GetRecent

func (s *SessionStoreImpl) GetRecent(ctx context.Context, sessionID string, duration time.Duration) ([]memory.TranscriptEntry, error)

GetRecent implements memory.SessionStore. It returns all entries for sessionID whose timestamp is no earlier than time.Now()-duration, ordered chronologically (oldest first).

func (*SessionStoreImpl) ListSessions added in v0.1.0

func (s *SessionStoreImpl) ListSessions(ctx context.Context, limit int) ([]memory.SessionInfo, error)

ListSessions implements memory.SessionStore. It returns sessions for the store's campaign, ordered by started_at descending (newest first).

func (*SessionStoreImpl) Search

Search implements memory.SessionStore. It performs a PostgreSQL full-text search over the text column and applies optional filters from opts.

The query is passed to plainto_tsquery so no special operator syntax is required.

func (*SessionStoreImpl) StartSession added in v0.1.0

func (s *SessionStoreImpl) StartSession(ctx context.Context, sessionID string) error

StartSession records a new session in the sessions metadata table.

func (*SessionStoreImpl) WriteEntry

func (s *SessionStoreImpl) WriteEntry(ctx context.Context, sessionID string, entry memory.TranscriptEntry) error

WriteEntry implements memory.SessionStore. It appends entry to the session_entries table under sessionID.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the central PostgreSQL-backed memory store for Glyphoxa. It holds a single pgxpool.Pool and exposes the three-layer memory architecture:

All operations are safe for concurrent use.

The store is scoped to a single campaign via campaignID (set at construction) and uses fully-qualified table names via schema to support multi-tenant schema-per-tenant isolation.

func NewStore

func NewStore(ctx context.Context, dsn string, embeddingDimensions int, schema SchemaName, campaignID string) (*Store, error)

NewStore creates a new Store, establishes a connection pool to the PostgreSQL database at dsn, registers pgvector types on every connection, and runs Migrate to ensure all required tables and extensions exist.

schema is the PostgreSQL schema to use ("public" for full-mode, "tenant_xxx" for multi-tenant). campaignID scopes all queries to a single campaign and is stored on the struct — callers never pass it per-method.

embeddingDimensions must match the output dimension of the embedding model used to produce memory.Chunk.Embedding values (e.g., 1536 for OpenAI text-embedding-3-small). Changing this value after the first migration requires a manual schema change.

func (*Store) AddEntity

func (s *Store) AddEntity(ctx context.Context, entity memory.Entity) error

AddEntity implements memory.KnowledgeGraph. It upserts an entity into the entities table. If an entity with the same (campaign_id, id) already exists it is completely replaced and its updated_at timestamp is refreshed.

func (*Store) AddRelationship

func (s *Store) AddRelationship(ctx context.Context, rel memory.Relationship) error

AddRelationship implements memory.KnowledgeGraph. It upserts a directed edge between two entities. If the edge (campaign_id, SourceID, TargetID, RelType) already exists it is completely replaced.

func (*Store) Close

func (s *Store) Close()

Close releases all connections held by the underlying connection pool. It should be called when the Store is no longer needed, typically via defer.

func (*Store) DeleteEntity

func (s *Store) DeleteEntity(ctx context.Context, id string) error

DeleteEntity implements memory.KnowledgeGraph. It removes the entity and all its associated relationships (via ON DELETE CASCADE). Deleting a non-existent entity is not an error.

func (*Store) DeleteRelationship

func (s *Store) DeleteRelationship(ctx context.Context, sourceID, targetID, relType string) error

DeleteRelationship implements memory.KnowledgeGraph. It removes the directed edge identified by (sourceID, targetID, relType). Deleting a non-existent edge is not an error.

func (*Store) FindEntities

func (s *Store) FindEntities(ctx context.Context, filter memory.EntityFilter) ([]memory.Entity, error)

FindEntities implements memory.KnowledgeGraph. It returns all entities matching filter. All non-zero filter fields are applied as AND conditions.

func (*Store) FindPath

func (s *Store) FindPath(ctx context.Context, fromID, toID string, maxDepth int) ([]memory.Entity, error)

FindPath implements memory.KnowledgeGraph. It returns the shortest sequence of entities (including fromID and toID) connecting fromID to toID following edges in both directions (bidirectional), up to maxDepth hops.

Returns an empty (non-nil) slice when no path exists within maxDepth.

func (*Store) GetEntity

func (s *Store) GetEntity(ctx context.Context, id string) (*memory.Entity, error)

GetEntity implements memory.KnowledgeGraph. It retrieves an entity by ID. Returns (nil, nil) when the entity does not exist.

func (*Store) GetRelationships

func (s *Store) GetRelationships(ctx context.Context, entityID string, opts ...memory.RelQueryOpt) ([]memory.Relationship, error)

GetRelationships implements memory.KnowledgeGraph. It returns relationships associated with entityID. By default only outgoing edges are returned; use memory.WithIncoming to include inbound edges and memory.WithRelTypes to filter by edge type.

func (*Store) IdentitySnapshot

func (s *Store) IdentitySnapshot(ctx context.Context, npcID string) (*memory.NPCIdentity, error)

IdentitySnapshot implements memory.KnowledgeGraph. It assembles a compact memory.NPCIdentity for npcID containing the NPC's entity record, all its direct relationships, and the entities those relationships reference.

func (*Store) L1

func (s *Store) L1() *SessionStoreImpl

L1 returns the L1 session log implementation which satisfies memory.SessionStore.

func (*Store) L2

func (s *Store) L2() *SemanticIndexImpl

L2 returns the L2 semantic index implementation which satisfies memory.SemanticIndex.

func (*Store) Neighbors

func (s *Store) Neighbors(ctx context.Context, entityID string, depth int, opts ...memory.TraversalOpt) ([]memory.Entity, error)

Neighbors implements memory.KnowledgeGraph. It performs a bidirectional breadth-first traversal from entityID up to depth hops using a PostgreSQL recursive CTE and returns all reachable entities (the start entity is excluded).

func (*Store) QueryWithContext

func (s *Store) QueryWithContext(ctx context.Context, query string, graphScope []string) ([]memory.ContextResult, error)

QueryWithContext implements memory.GraphRAGQuerier. It performs a graph-augmented retrieval query combining L3 entity data with L2 chunk text in a single SQL round-trip using PostgreSQL full-text search.

func (*Store) QueryWithEmbedding

func (s *Store) QueryWithEmbedding(ctx context.Context, embedding []float32, topK int, graphScope []string) ([]memory.ContextResult, error)

QueryWithEmbedding implements memory.GraphRAGQuerier. It performs a graph-augmented retrieval query using pgvector cosine similarity.

func (*Store) RecapStore added in v0.1.0

func (s *Store) RecapStore() *RecapStoreImpl

RecapStore returns the RecapStore implementation.

func (*Store) UpdateEntity

func (s *Store) UpdateEntity(ctx context.Context, id string, attrs map[string]any) error

UpdateEntity implements memory.KnowledgeGraph. It merges attrs into the entity's Attributes map using PostgreSQL's jsonb || operator and refreshes updated_at. Returns an error when the entity does not exist.

func (*Store) VisibleSubgraph

func (s *Store) VisibleSubgraph(ctx context.Context, npcID string) ([]memory.Entity, []memory.Relationship, error)

VisibleSubgraph implements memory.KnowledgeGraph. It returns the NPC entity itself, all entities it has direct relationships with, and those relationships (both outgoing and incoming edges).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL