persistence

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package persistence provides database storage implementations.

Index

Constants

View Source
const (
	TrackingTypeBranch = "branch"
	TrackingTypeTag    = "tag"
	TrackingTypeCommit = "commit"
)

Tracking type constants.

Variables

View Source
var (
	TaskNameCode = TaskName("code")
	TaskNameText = TaskName("text")
)

TaskName values.

View Source
var ErrBM25InitializationFailed = errors.New("failed to initialize VectorChord BM25 repository")

ErrBM25InitializationFailed indicates VectorChord BM25 initialization failed.

View Source
var ErrSQLiteBM25InitializationFailed = errors.New("failed to initialize SQLite FTS5 BM25 store")

ErrSQLiteBM25InitializationFailed indicates SQLite FTS5 initialization failed.

View Source
var ErrVectorInitializationFailed = errors.New("failed to initialize VectorChord vector repository")

ErrVectorInitializationFailed indicates VectorChord vector initialization failed.

Functions

func AutoMigrate

func AutoMigrate(db database.Database) error

AutoMigrate runs GORM auto migration for all models.

func CosineSimilarity

func CosineSimilarity(a, b []float64) float64

CosineSimilarity computes the cosine similarity between two vectors. Returns a value between -1 (opposite) and 1 (identical). Returns 0 if either vector has zero magnitude.

func PreMigrate

func PreMigrate(db database.Database) error

PreMigrate handles one-time schema conversions from the Python-era database. It converts PostgreSQL enum columns to text so GORM AutoMigrate can manage them. Safe to run repeatedly — it checks whether the enum types still exist before acting.

func ValidateSchema

func ValidateSchema(db database.Database) error

ValidateSchema verifies every GORM model field has a corresponding column in the database. Returns an error listing any missing columns.

Types

type AssociationMapper

type AssociationMapper struct{}

AssociationMapper maps between domain Association and persistence EnrichmentAssociationModel.

func (AssociationMapper) ToDomain

ToDomain converts an EnrichmentAssociationModel to a domain Association.

func (AssociationMapper) ToModel

ToModel converts a domain Association to an EnrichmentAssociationModel.

type AssociationStore

AssociationStore implements enrichment.AssociationStore using GORM.

func NewAssociationStore

func NewAssociationStore(db database.Database) AssociationStore

NewAssociationStore creates a new AssociationStore.

func (AssociationStore) Delete

Delete removes an association.

func (AssociationStore) Save

Save creates or updates an association.

type BranchMapper

type BranchMapper struct{}

BranchMapper maps between domain Branch and persistence BranchModel.

func (BranchMapper) ToDomain

func (m BranchMapper) ToDomain(e BranchModel) repository.Branch

ToDomain converts a BranchModel to a domain Branch.

func (BranchMapper) ToModel

ToModel converts a domain Branch to a BranchModel.

type BranchModel

type BranchModel struct {
	RepoID        int64           `gorm:"column:repo_id;primaryKey;index"`
	Repo          RepositoryModel `gorm:"foreignKey:RepoID;references:ID;constraint:OnDelete:CASCADE"`
	Name          string          `gorm:"column:name;primaryKey;index;size:255"`
	HeadCommitSHA string          `gorm:"column:head_commit_sha;index;size:64"`
	IsDefault     bool            `gorm:"column:is_default;default:false"`
	CreatedAt     time.Time       `gorm:"column:created_at"`
	UpdatedAt     time.Time       `gorm:"column:updated_at"`
}

BranchModel represents a Git branch in the database.

func (BranchModel) TableName

func (BranchModel) TableName() string

TableName returns the table name.

type BranchStore

type BranchStore struct {
	database.Repository[repository.Branch, BranchModel]
}

BranchStore implements repository.BranchStore using GORM.

func NewBranchStore

func NewBranchStore(db database.Database) BranchStore

NewBranchStore creates a new BranchStore.

func (BranchStore) Delete

func (s BranchStore) Delete(ctx context.Context, branch repository.Branch) error

Delete removes a branch.

func (BranchStore) Save

Save creates or updates a branch.

func (BranchStore) SaveAll

func (s BranchStore) SaveAll(ctx context.Context, branches []repository.Branch) ([]repository.Branch, error)

SaveAll creates or updates multiple branches.

type ChunkLineRangeMapper

type ChunkLineRangeMapper struct{}

ChunkLineRangeMapper maps between domain LineRange and persistence ChunkLineRangeModel.

func (ChunkLineRangeMapper) ToDomain

ToDomain converts a ChunkLineRangeModel to a domain LineRange.

func (ChunkLineRangeMapper) ToModel

ToModel converts a domain LineRange to a ChunkLineRangeModel.

type ChunkLineRangeModel

type ChunkLineRangeModel struct {
	ID           int64           `gorm:"column:id;primaryKey;autoIncrement"`
	EnrichmentID int64           `gorm:"column:enrichment_id;not null;uniqueIndex"`
	Enrichment   EnrichmentModel `gorm:"foreignKey:EnrichmentID;references:ID;constraint:OnDelete:CASCADE"`
	StartLine    int             `gorm:"column:start_line;not null"`
	EndLine      int             `gorm:"column:end_line;not null"`
}

ChunkLineRangeModel records the source-file line range of a chunk enrichment.

func (ChunkLineRangeModel) TableName

func (ChunkLineRangeModel) TableName() string

TableName returns the table name.

type ChunkLineRangeStore

type ChunkLineRangeStore struct {
	database.Repository[chunk.LineRange, ChunkLineRangeModel]
}

ChunkLineRangeStore implements chunk.LineRangeStore using GORM.

func NewChunkLineRangeStore

func NewChunkLineRangeStore(db database.Database) ChunkLineRangeStore

NewChunkLineRangeStore creates a new ChunkLineRangeStore.

func (ChunkLineRangeStore) Delete

Delete removes a chunk line range.

func (ChunkLineRangeStore) Save

Save creates or updates a chunk line range.

type CommitIndexMapper

type CommitIndexMapper struct{}

CommitIndexMapper maps between domain CommitIndex and persistence CommitIndexModel.

func (CommitIndexMapper) ToDomain

ToDomain converts a CommitIndexModel to a domain CommitIndex. Note: snippets are loaded separately as they come from different tables.

func (CommitIndexMapper) ToModel

ToModel converts a domain CommitIndex to a CommitIndexModel.

type CommitIndexModel

type CommitIndexModel struct {
	CommitSHA             string         `gorm:"column:commit_sha;primaryKey"`
	Commit                CommitModel    `gorm:"foreignKey:CommitSHA;references:CommitSHA;constraint:-"`
	Status                string         `gorm:"column:status;index"`
	IndexedAt             sql.NullTime   `gorm:"column:indexed_at"`
	ErrorMessage          sql.NullString `gorm:"column:error_message"`
	FilesProcessed        int            `gorm:"column:files_processed;default:0"`
	ProcessingTimeSeconds float64        `gorm:"column:processing_time_seconds;default:0.0"`
	CreatedAt             time.Time      `gorm:"column:created_at;not null"`
	UpdatedAt             time.Time      `gorm:"column:updated_at;not null"`
}

CommitIndexModel represents the commit indexing status.

func (CommitIndexModel) TableName

func (CommitIndexModel) TableName() string

TableName returns the table name.

type CommitIndexStore

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

CommitIndexStore implements snippet.CommitIndexStore using GORM.

func NewCommitIndexStore

func NewCommitIndexStore(db database.Database) CommitIndexStore

NewCommitIndexStore creates a new CommitIndexStore.

func (CommitIndexStore) Delete

func (s CommitIndexStore) Delete(ctx context.Context, commitSHA string) error

Delete removes a commit index.

func (CommitIndexStore) Exists

func (s CommitIndexStore) Exists(ctx context.Context, commitSHA string) (bool, error)

Exists checks if a commit index exists.

func (CommitIndexStore) Get

func (s CommitIndexStore) Get(ctx context.Context, commitSHA string) (snippet.CommitIndex, error)

Get returns a commit index by SHA.

func (CommitIndexStore) Save

Save persists a commit index.

type CommitMapper

type CommitMapper struct{}

CommitMapper maps between domain Commit and persistence CommitModel.

func (CommitMapper) ToDomain

func (m CommitMapper) ToDomain(e CommitModel) repository.Commit

ToDomain converts a CommitModel to a domain Commit.

func (CommitMapper) ToModel

ToModel converts a domain Commit to a CommitModel.

type CommitModel

type CommitModel struct {
	CommitSHA       string          `gorm:"column:commit_sha;primaryKey;size:64"`
	RepoID          int64           `gorm:"column:repo_id;index"`
	Repo            RepositoryModel `gorm:"foreignKey:RepoID;references:ID;constraint:OnDelete:CASCADE"`
	Date            time.Time       `gorm:"column:date"`
	Message         string          `gorm:"column:message;type:text"`
	ParentCommitSHA *string         `gorm:"column:parent_commit_sha;index;size:64"`
	Author          string          `gorm:"column:author;index;size:255"`
	CreatedAt       time.Time       `gorm:"column:created_at"`
	UpdatedAt       time.Time       `gorm:"column:updated_at"`
}

CommitModel represents a Git commit in the database.

func (CommitModel) TableName

func (CommitModel) TableName() string

TableName returns the table name.

type CommitStore

type CommitStore struct {
	database.Repository[repository.Commit, CommitModel]
}

CommitStore implements repository.CommitStore using GORM.

func NewCommitStore

func NewCommitStore(db database.Database) CommitStore

NewCommitStore creates a new CommitStore.

func (CommitStore) Delete

func (s CommitStore) Delete(ctx context.Context, commit repository.Commit) error

Delete removes a commit.

func (CommitStore) Save

Save creates or updates a commit.

func (CommitStore) SaveAll

func (s CommitStore) SaveAll(ctx context.Context, commits []repository.Commit) ([]repository.Commit, error)

SaveAll creates or updates multiple commits.

type EmbeddingModel

type EmbeddingModel struct {
	ID        int64     `gorm:"column:id;primaryKey;autoIncrement"`
	SnippetID string    `gorm:"column:snippet_id;index"`
	Type      string    `gorm:"column:type;index"`
	Embedding []float64 `gorm:"column:embedding;type:json"`
	CreatedAt time.Time `gorm:"column:created_at;not null"`
	UpdatedAt time.Time `gorm:"column:updated_at;not null"`
}

EmbeddingModel represents a vector embedding in the database.

func (EmbeddingModel) TableName

func (EmbeddingModel) TableName() string

TableName returns the table name.

type EnrichmentAssociationModel

type EnrichmentAssociationModel struct {
	ID           int64           `gorm:"column:id;primaryKey;autoIncrement"`
	EnrichmentID int64           `gorm:"column:enrichment_id;not null;index;uniqueIndex:idx_enrichment_assoc"`
	Enrichment   EnrichmentModel `gorm:"foreignKey:EnrichmentID;references:ID;constraint:OnDelete:CASCADE"`
	EntityType   string          `gorm:"column:entity_type;size:50;not null;index:idx_enrichment_entity;uniqueIndex:idx_enrichment_assoc"`
	EntityID     string          `gorm:"column:entity_id;size:255;not null;index:idx_enrichment_entity;uniqueIndex:idx_enrichment_assoc"`
	CreatedAt    time.Time       `gorm:"column:created_at;not null"`
	UpdatedAt    time.Time       `gorm:"column:updated_at;not null"`
}

EnrichmentAssociationModel links enrichments to entities.

func (EnrichmentAssociationModel) TableName

func (EnrichmentAssociationModel) TableName() string

TableName returns the table name.

type EnrichmentMapper

type EnrichmentMapper struct{}

EnrichmentMapper maps between domain Enrichment and persistence EnrichmentModel.

func (EnrichmentMapper) ToDomain

ToDomain converts an EnrichmentModel to a domain Enrichment.

func (EnrichmentMapper) ToModel

ToModel converts a domain Enrichment to an EnrichmentModel.

type EnrichmentModel

type EnrichmentModel struct {
	ID        int64     `gorm:"column:id;primaryKey;autoIncrement"`
	Type      string    `gorm:"column:type;not null;index"`
	Subtype   string    `gorm:"column:subtype;not null;index"`
	Content   string    `gorm:"column:content;type:text;not null"`
	Language  string    `gorm:"column:language;size:50"`
	CreatedAt time.Time `gorm:"column:created_at;not null"`
	UpdatedAt time.Time `gorm:"column:updated_at;not null"`
}

EnrichmentModel represents an enrichment in the database.

func (EnrichmentModel) TableName

func (EnrichmentModel) TableName() string

TableName returns the table name.

type EnrichmentStore

type EnrichmentStore struct {
	database.Repository[enrichment.Enrichment, EnrichmentModel]
}

EnrichmentStore implements enrichment.EnrichmentStore using GORM.

func NewEnrichmentStore

func NewEnrichmentStore(db database.Database) EnrichmentStore

NewEnrichmentStore creates a new EnrichmentStore.

func (EnrichmentStore) Count

func (s EnrichmentStore) Count(ctx context.Context, options ...repository.Option) (int64, error)

Count returns the number of enrichments matching the given options.

func (EnrichmentStore) Delete

Delete removes an enrichment.

func (EnrichmentStore) Find

Find retrieves enrichments matching the given options. Supports commit SHA filtering via enrichment.WithCommitSHA / WithCommitSHAs options, which join through enrichment_associations.

func (EnrichmentStore) Save

Save creates or updates an enrichment.

type FileMapper

type FileMapper struct{}

FileMapper maps between domain File and persistence FileModel.

func (FileMapper) ToDomain

func (m FileMapper) ToDomain(e FileModel) repository.File

ToDomain converts a FileModel to a domain File.

func (FileMapper) ToModel

func (m FileMapper) ToModel(f repository.File) FileModel

ToModel converts a domain File to a FileModel.

type FileModel

type FileModel struct {
	ID        int64       `gorm:"column:id;autoIncrement"`
	CommitSHA string      `gorm:"column:commit_sha;primaryKey;uniqueIndex:idx_commit_path;size:64"`
	Commit    CommitModel `gorm:"foreignKey:CommitSHA;references:CommitSHA;constraint:-"`
	Path      string      `gorm:"column:path;primaryKey;uniqueIndex:idx_commit_path;size:1024"`
	BlobSHA   string      `gorm:"column:blob_sha;index;size:64"`
	MimeType  string      `gorm:"column:mime_type;index;size:255"`
	Extension string      `gorm:"column:extension;index;size:255"`
	Size      int64       `gorm:"column:size"`
	CreatedAt time.Time   `gorm:"column:created_at"`
}

FileModel represents a Git file in the database.

func (FileModel) TableName

func (FileModel) TableName() string

TableName returns the table name.

type FileStore

type FileStore struct {
	database.Repository[repository.File, FileModel]
}

FileStore implements repository.FileStore using GORM.

func NewFileStore

func NewFileStore(db database.Database) FileStore

NewFileStore creates a new FileStore.

func (FileStore) Delete

func (s FileStore) Delete(ctx context.Context, file repository.File) error

Delete removes a file.

func (FileStore) Save

Save creates or updates a file.

func (FileStore) SaveAll

func (s FileStore) SaveAll(ctx context.Context, files []repository.File) ([]repository.File, error)

SaveAll creates or updates multiple files.

type Filter

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

Filter represents a single query filter condition.

func NewBetweenFilter

func NewBetweenFilter(field string, low, high any) Filter

NewBetweenFilter creates a new BETWEEN Filter.

func NewFilter

func NewFilter(field string, operator FilterOperator, value any) Filter

NewFilter creates a new Filter.

func (Filter) Field

func (f Filter) Field() string

Field returns the filter field name.

func (Filter) Operator

func (f Filter) Operator() FilterOperator

Operator returns the filter operator.

func (Filter) Value

func (f Filter) Value() any

Value returns the filter value.

type FilterOperator

type FilterOperator int

FilterOperator represents SQL comparison operators.

const (
	OpEqual FilterOperator = iota
	OpNotEqual
	OpGreaterThan
	OpGreaterThanOrEqual
	OpLessThan
	OpLessThanOrEqual
	OpLike
	OpILike
	OpIn
	OpNotIn
	OpIsNull
	OpIsNotNull
	OpBetween
)

FilterOperator values.

func (FilterOperator) String

func (o FilterOperator) String() string

String returns the SQL representation of the operator.

type Float64Slice

type Float64Slice []float64

Float64Slice is a custom type for JSON serialization of []float64 in SQLite.

func (*Float64Slice) Scan

func (f *Float64Slice) Scan(value any) error

Scan implements sql.Scanner for reading JSON from SQLite.

func (Float64Slice) Value

func (f Float64Slice) Value() (driver.Value, error)

Value implements driver.Valuer for writing JSON to SQLite.

type OrderBy

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

OrderBy represents a sort specification.

func NewOrderBy

func NewOrderBy(field string, direction SortDirection) OrderBy

NewOrderBy creates a new OrderBy.

func (OrderBy) Direction

func (o OrderBy) Direction() SortDirection

Direction returns the sort direction.

func (OrderBy) Field

func (o OrderBy) Field() string

Field returns the field name.

type PgEmbeddingModel

type PgEmbeddingModel struct {
	ID        int64             `gorm:"column:id;primaryKey;autoIncrement"`
	SnippetID string            `gorm:"column:snippet_id;uniqueIndex"`
	Embedding database.PgVector `gorm:"column:embedding;type:vector"`
}

PgEmbeddingModel is a GORM model for PostgreSQL vector embedding tables.

type Query

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

Query represents a database query with filters, ordering, and pagination.

func NewQuery

func NewQuery() Query

NewQuery creates a new empty Query.

func (Query) Apply

func (q Query) Apply(db *gorm.DB) *gorm.DB

Apply applies the query to a GORM database session.

func (Query) Equal

func (q Query) Equal(field string, value any) Query

Equal adds an equality filter.

func (Query) Filters

func (q Query) Filters() []Filter

Filters returns all filter conditions.

func (Query) GreaterThan

func (q Query) GreaterThan(field string, value any) Query

GreaterThan adds a greater-than filter.

func (Query) GreaterThanOrEqual

func (q Query) GreaterThanOrEqual(field string, value any) Query

GreaterThanOrEqual adds a greater-than-or-equal filter.

func (Query) ILike

func (q Query) ILike(field string, pattern string) Query

ILike adds a case-insensitive LIKE filter.

func (Query) In

func (q Query) In(field string, values any) Query

In adds an IN filter.

func (Query) IsNotNull

func (q Query) IsNotNull(field string) Query

IsNotNull adds an IS NOT NULL filter.

func (Query) IsNull

func (q Query) IsNull(field string) Query

IsNull adds an IS NULL filter.

func (Query) LessThan

func (q Query) LessThan(field string, value any) Query

LessThan adds a less-than filter.

func (Query) LessThanOrEqual

func (q Query) LessThanOrEqual(field string, value any) Query

LessThanOrEqual adds a less-than-or-equal filter.

func (Query) Like

func (q Query) Like(field string, pattern string) Query

Like adds a LIKE filter.

func (Query) Limit

func (q Query) Limit(limit int) Query

Limit sets the result limit.

func (Query) LimitValue

func (q Query) LimitValue() int

LimitValue returns the limit value (0 means no limit).

func (Query) NotEqual

func (q Query) NotEqual(field string, value any) Query

NotEqual adds a not-equal filter.

func (Query) NotIn

func (q Query) NotIn(field string, values any) Query

NotIn adds a NOT IN filter.

func (Query) Offset

func (q Query) Offset(offset int) Query

Offset sets the result offset.

func (Query) OffsetValue

func (q Query) OffsetValue() int

OffsetValue returns the offset value.

func (Query) Order

func (q Query) Order(field string, direction SortDirection) Query

Order adds an ordering specification.

func (Query) OrderAsc

func (q Query) OrderAsc(field string) Query

OrderAsc adds ascending ordering.

func (Query) OrderDesc

func (q Query) OrderDesc(field string) Query

OrderDesc adds descending ordering.

func (Query) Orders

func (q Query) Orders() []OrderBy

Orders returns all ordering specifications.

func (Query) Paginate

func (q Query) Paginate(page, pageSize int) Query

Paginate sets both limit and offset for pagination.

func (Query) Where

func (q Query) Where(field string, operator FilterOperator, value any) Query

Where adds a filter condition.

func (Query) WhereBetween

func (q Query) WhereBetween(field string, low, high any) Query

WhereBetween adds a BETWEEN filter.

type RepositoryMapper

type RepositoryMapper struct{}

RepositoryMapper maps between domain Repository and persistence RepositoryModel.

func (RepositoryMapper) ToDomain

ToDomain converts a RepositoryModel to a domain Repository.

func (RepositoryMapper) ToModel

ToModel converts a domain Repository to a RepositoryModel.

type RepositoryModel

type RepositoryModel struct {
	ID                 int64      `gorm:"primaryKey;autoIncrement"`
	SanitizedRemoteURI string     `gorm:"column:sanitized_remote_uri;index;uniqueIndex;size:1024"`
	RemoteURI          string     `gorm:"column:remote_uri;size:1024"`
	ClonedPath         *string    `gorm:"column:cloned_path;size:1024"`
	LastScannedAt      *time.Time `gorm:"column:last_scanned_at"`
	NumCommits         int        `gorm:"column:num_commits;default:0"`
	NumBranches        int        `gorm:"column:num_branches;default:0"`
	NumTags            int        `gorm:"column:num_tags;default:0"`
	TrackingType       string     `gorm:"column:tracking_type;index;size:255"`
	TrackingName       string     `gorm:"column:tracking_name;index;size:255"`
	CreatedAt          time.Time  `gorm:"column:created_at"`
	UpdatedAt          time.Time  `gorm:"column:updated_at"`
}

RepositoryModel represents a Git repository in the database.

func (RepositoryModel) TableName

func (RepositoryModel) TableName() string

TableName returns the table name.

type RepositoryStore

type RepositoryStore struct {
	database.Repository[repository.Repository, RepositoryModel]
}

RepositoryStore implements repository.RepositoryStore using GORM.

func NewRepositoryStore

func NewRepositoryStore(db database.Database) RepositoryStore

NewRepositoryStore creates a new RepositoryStore.

func (RepositoryStore) Delete

Delete removes a repository.

func (RepositoryStore) Save

Save creates or updates a repository.

type SQLiteBM25Store

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

SQLiteBM25Store implements search.BM25Store using SQLite FTS5.

func NewSQLiteBM25Store

func NewSQLiteBM25Store(db database.Database, logger zerolog.Logger) (*SQLiteBM25Store, error)

NewSQLiteBM25Store creates a new SQLiteBM25Store, eagerly initializing the FTS5 table and row ID counter.

func (*SQLiteBM25Store) DeleteBy

func (s *SQLiteBM25Store) DeleteBy(ctx context.Context, options ...repository.Option) error

DeleteBy removes documents matching the given options.

func (*SQLiteBM25Store) Find

func (s *SQLiteBM25Store) Find(ctx context.Context, options ...repository.Option) ([]search.Result, error)

Find performs BM25 keyword search using options.

func (*SQLiteBM25Store) Index

func (s *SQLiteBM25Store) Index(ctx context.Context, request search.IndexRequest) error

Index adds documents to the BM25 index.

type SQLiteEmbeddingModel

type SQLiteEmbeddingModel struct {
	ID        int64        `gorm:"column:id;primaryKey;autoIncrement"`
	SnippetID string       `gorm:"column:snippet_id;uniqueIndex"`
	Embedding Float64Slice `gorm:"column:embedding;type:json"`
}

SQLiteEmbeddingModel represents a vector embedding in SQLite.

type SQLiteEmbeddingStore

type SQLiteEmbeddingStore struct {
	database.Repository[search.Embedding, SQLiteEmbeddingModel]
	// contains filtered or unexported fields
}

SQLiteEmbeddingStore implements search.EmbeddingStore for SQLite. Stores embeddings as JSON and performs cosine similarity search in-memory.

func NewSQLiteEmbeddingStore

func NewSQLiteEmbeddingStore(db database.Database, taskName TaskName, logger zerolog.Logger) (*SQLiteEmbeddingStore, error)

NewSQLiteEmbeddingStore creates a new SQLiteEmbeddingStore.

func (*SQLiteEmbeddingStore) SaveAll

func (s *SQLiteEmbeddingStore) SaveAll(ctx context.Context, embeddings []search.Embedding) error

SaveAll persists pre-computed embeddings using batched upsert.

func (*SQLiteEmbeddingStore) Search

func (s *SQLiteEmbeddingStore) Search(ctx context.Context, options ...repository.Option) ([]search.Result, error)

Search performs vector similarity search using pre-computed embedding from options.

type SimilarityMatch

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

SimilarityMatch holds a snippet ID and its similarity score.

func NewSimilarityMatch

func NewSimilarityMatch(snippetID string, similarity float64) SimilarityMatch

NewSimilarityMatch creates a new SimilarityMatch.

func TopKSimilar

func TopKSimilar(query []float64, vectors []StoredVector, k int) []SimilarityMatch

TopKSimilar finds the top-k most similar vectors to the query. Returns results sorted by similarity in descending order (highest similarity first).

func TopKSimilarFiltered

func TopKSimilarFiltered(query []float64, vectors []StoredVector, k int, allowedIDs map[string]struct{}) []SimilarityMatch

TopKSimilarFiltered finds the top-k most similar vectors, filtering by allowed snippet IDs.

func (SimilarityMatch) Similarity

func (m SimilarityMatch) Similarity() float64

Similarity returns the similarity score.

func (SimilarityMatch) SnippetID

func (m SimilarityMatch) SnippetID() string

SnippetID returns the snippet identifier.

type SortDirection

type SortDirection int

SortDirection represents sort direction.

const (
	SortAsc SortDirection = iota
	SortDesc
)

SortDirection values.

func (SortDirection) String

func (s SortDirection) String() string

String returns the SQL representation.

type StatusStore

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

StatusStore implements task.StatusStore using GORM.

func NewStatusStore

func NewStatusStore(db database.Database) StatusStore

NewStatusStore creates a new StatusStore.

func (StatusStore) Count

func (s StatusStore) Count(ctx context.Context) (int64, error)

Count returns the total number of task statuses.

func (StatusStore) Delete

func (s StatusStore) Delete(ctx context.Context, status task.Status) error

Delete removes a task status.

func (StatusStore) DeleteByTrackable

func (s StatusStore) DeleteByTrackable(ctx context.Context, trackableType task.TrackableType, trackableID int64) error

DeleteByTrackable removes task statuses for a trackable entity.

func (StatusStore) FindByTrackable

func (s StatusStore) FindByTrackable(ctx context.Context, trackableType task.TrackableType, trackableID int64) ([]task.Status, error)

FindByTrackable retrieves task statuses for a trackable entity.

func (StatusStore) Get

func (s StatusStore) Get(ctx context.Context, id string) (task.Status, error)

Get retrieves a task status by ID.

func (StatusStore) LoadWithHierarchy

func (s StatusStore) LoadWithHierarchy(ctx context.Context, trackableType task.TrackableType, trackableID int64) ([]task.Status, error)

LoadWithHierarchy loads all task statuses for a trackable entity with their parent-child relationships reconstructed.

func (StatusStore) Save

func (s StatusStore) Save(ctx context.Context, status task.Status) (task.Status, error)

Save creates a new task status or updates an existing one.

func (StatusStore) SaveBulk

func (s StatusStore) SaveBulk(ctx context.Context, statuses []task.Status) ([]task.Status, error)

SaveBulk creates or updates multiple task statuses.

type StoredVector

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

StoredVector holds an embedding vector with its snippet ID.

func NewStoredVector

func NewStoredVector(snippetID string, embedding []float64) StoredVector

NewStoredVector creates a new StoredVector.

func (StoredVector) Embedding

func (v StoredVector) Embedding() []float64

Embedding returns the embedding vector (copy).

func (StoredVector) SnippetID

func (v StoredVector) SnippetID() string

SnippetID returns the snippet identifier.

type TagMapper

type TagMapper struct{}

TagMapper maps between domain Tag and persistence TagModel.

func (TagMapper) ToDomain

func (m TagMapper) ToDomain(e TagModel) repository.Tag

ToDomain converts a TagModel to a domain Tag.

func (TagMapper) ToModel

func (m TagMapper) ToModel(t repository.Tag) TagModel

ToModel converts a domain Tag to a TagModel.

type TagModel

type TagModel struct {
	RepoID          int64           `gorm:"column:repo_id;primaryKey;index"`
	Repo            RepositoryModel `gorm:"foreignKey:RepoID;references:ID;constraint:OnDelete:CASCADE"`
	Name            string          `gorm:"column:name;primaryKey;index;size:255"`
	TargetCommitSHA string          `gorm:"column:target_commit_sha;index;size:64"`
	Message         *string         `gorm:"column:message;type:text"`
	TaggerName      *string         `gorm:"column:tagger_name;size:255"`
	TaggerEmail     *string         `gorm:"column:tagger_email;size:255"`
	TaggedAt        *time.Time      `gorm:"column:tagged_at"`
	CreatedAt       time.Time       `gorm:"column:created_at"`
	UpdatedAt       time.Time       `gorm:"column:updated_at"`
}

TagModel represents a Git tag in the database.

func (TagModel) TableName

func (TagModel) TableName() string

TableName returns the table name.

type TagStore

type TagStore struct {
	database.Repository[repository.Tag, TagModel]
}

TagStore implements repository.TagStore using GORM.

func NewTagStore

func NewTagStore(db database.Database) TagStore

NewTagStore creates a new TagStore.

func (TagStore) Delete

func (s TagStore) Delete(ctx context.Context, tag repository.Tag) error

Delete removes a tag.

func (TagStore) Save

func (s TagStore) Save(ctx context.Context, tag repository.Tag) (repository.Tag, error)

Save creates or updates a tag.

func (TagStore) SaveAll

func (s TagStore) SaveAll(ctx context.Context, tags []repository.Tag) ([]repository.Tag, error)

SaveAll creates or updates multiple tags.

type TaskMapper

type TaskMapper struct{}

TaskMapper maps between domain Task and persistence TaskModel.

func (TaskMapper) ToDomain

func (m TaskMapper) ToDomain(e TaskModel) (task.Task, error)

ToDomain converts a TaskModel to a domain Task.

func (TaskMapper) ToModel

func (m TaskMapper) ToModel(t task.Task) (TaskModel, error)

ToModel converts a domain Task to a TaskModel.

type TaskModel

type TaskModel struct {
	ID        int64           `gorm:"column:id;primaryKey;autoIncrement"`
	DedupKey  string          `gorm:"column:dedup_key;type:varchar(255);uniqueIndex;not null"`
	Type      string          `gorm:"column:type;type:varchar(255);index;not null"`
	Payload   json.RawMessage `gorm:"column:payload;type:jsonb"`
	Priority  int             `gorm:"column:priority;not null"`
	CreatedAt time.Time       `gorm:"column:created_at;autoCreateTime"`
	UpdatedAt time.Time       `gorm:"column:updated_at;autoUpdateTime"`
}

TaskModel represents a task in the database.

func (TaskModel) TableName

func (TaskModel) TableName() string

TableName returns the table name.

type TaskName

type TaskName string

TaskName represents the type of embeddings (code or text).

type TaskStatusMapper

type TaskStatusMapper struct{}

TaskStatusMapper maps between domain Status and persistence TaskStatusModel.

func (TaskStatusMapper) ToDomain

ToDomain converts a TaskStatusModel to a domain Status.

func (TaskStatusMapper) ToModel

ToModel converts a domain Status to a TaskStatusModel.

type TaskStatusModel

type TaskStatusModel struct {
	ID            string    `gorm:"column:id;type:varchar(255);primaryKey;index;not null"`
	CreatedAt     time.Time `gorm:"column:created_at;not null"`
	UpdatedAt     time.Time `gorm:"column:updated_at;not null"`
	Operation     string    `gorm:"column:operation;type:varchar(255);index;not null"`
	TrackableID   *int64    `gorm:"column:trackable_id;index:idx_trackable"`
	TrackableType *string   `gorm:"column:trackable_type;type:varchar(255);index:idx_trackable"`
	ParentID      *string   `gorm:"column:parent;type:varchar(255);index"`
	Message       string    `gorm:"column:message;type:text;default:''"`
	State         string    `gorm:"column:state;type:varchar(255);default:''"`
	Error         string    `gorm:"column:error;type:text;default:''"`
	Total         int       `gorm:"column:total;default:0"`
	Current       int       `gorm:"column:current;default:0"`
}

TaskStatusModel represents task status in the database.

func (TaskStatusModel) TableName

func (TaskStatusModel) TableName() string

TableName returns the table name.

type TaskStore

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

TaskStore implements task.TaskStore using GORM.

func NewTaskStore

func NewTaskStore(db database.Database) TaskStore

NewTaskStore creates a new TaskStore.

func (TaskStore) CountPending

func (s TaskStore) CountPending(ctx context.Context, options ...repository.Option) (int64, error)

CountPending returns the number of pending tasks.

func (TaskStore) Delete

func (s TaskStore) Delete(ctx context.Context, t task.Task) error

Delete removes a task.

func (TaskStore) DeleteAll

func (s TaskStore) DeleteAll(ctx context.Context) error

DeleteAll removes all tasks.

func (TaskStore) Dequeue

func (s TaskStore) Dequeue(ctx context.Context) (task.Task, bool, error)

Dequeue retrieves and removes the highest priority task.

func (TaskStore) DequeueByOperation

func (s TaskStore) DequeueByOperation(ctx context.Context, operation task.Operation) (task.Task, bool, error)

DequeueByOperation retrieves and removes the highest priority task of a specific operation type.

func (TaskStore) Exists

func (s TaskStore) Exists(ctx context.Context, id int64) (bool, error)

Exists checks if a task with the given ID exists.

func (TaskStore) FindAll

func (s TaskStore) FindAll(ctx context.Context) ([]task.Task, error)

FindAll retrieves all tasks.

func (TaskStore) FindPending

func (s TaskStore) FindPending(ctx context.Context, options ...repository.Option) ([]task.Task, error)

FindPending retrieves pending tasks ordered by priority.

func (TaskStore) Get

func (s TaskStore) Get(ctx context.Context, id int64) (task.Task, error)

Get retrieves a task by ID.

func (TaskStore) Save

func (s TaskStore) Save(ctx context.Context, t task.Task) (task.Task, error)

Save creates a new task or updates an existing one. Uses dedup_key for conflict resolution.

func (TaskStore) SaveBulk

func (s TaskStore) SaveBulk(ctx context.Context, tasks []task.Task) ([]task.Task, error)

SaveBulk creates or updates multiple tasks.

type VectorChordBM25Store

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

VectorChordBM25Store implements search.BM25Store using VectorChord PostgreSQL extension.

func NewVectorChordBM25Store

func NewVectorChordBM25Store(db database.Database, logger zerolog.Logger) (*VectorChordBM25Store, error)

NewVectorChordBM25Store creates a new VectorChordBM25Store, eagerly initializing extensions, tokenizer, and tables.

func (*VectorChordBM25Store) DeleteBy

func (s *VectorChordBM25Store) DeleteBy(ctx context.Context, options ...repository.Option) error

DeleteBy removes documents matching the given options.

func (*VectorChordBM25Store) Find

func (s *VectorChordBM25Store) Find(ctx context.Context, options ...repository.Option) ([]search.Result, error)

Find performs BM25 keyword search using options.

func (*VectorChordBM25Store) Index

Index adds documents to the BM25 index.

type VectorChordEmbeddingStore

type VectorChordEmbeddingStore struct {
	database.Repository[search.Embedding, PgEmbeddingModel]
	// contains filtered or unexported fields
}

VectorChordEmbeddingStore implements search.EmbeddingStore using VectorChord PostgreSQL extension.

func NewVectorChordEmbeddingStore

func NewVectorChordEmbeddingStore(ctx context.Context, db database.Database, taskName TaskName, dimension int, logger zerolog.Logger) (*VectorChordEmbeddingStore, bool, error)

NewVectorChordEmbeddingStore creates a new VectorChordEmbeddingStore, eagerly initializing the extension, table, index, and verifying the dimension. The returned bool is true when the table was dropped and recreated due to a dimension mismatch (e.g. the user switched embedding providers).

func (*VectorChordEmbeddingStore) SaveAll

func (s *VectorChordEmbeddingStore) SaveAll(ctx context.Context, embeddings []search.Embedding) error

SaveAll persists pre-computed embeddings using batched upsert, then ensures the vchordrq index exists (it requires data for K-means clustering).

func (*VectorChordEmbeddingStore) Search

func (s *VectorChordEmbeddingStore) Search(ctx context.Context, options ...repository.Option) ([]search.Result, error)

Search performs vector similarity search within a transaction so that the vchordrq.probes session variable is visible to the query.

Jump to

Keyboard shortcuts

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