Skip to content

Commit

Permalink
Update to just remove table intead of migrating to avoid downtime
Browse files Browse the repository at this point in the history
  • Loading branch information
crspeller committed Jun 13, 2024
1 parent 417500d commit e01926c
Showing 1 changed file with 7 additions and 17 deletions.
24 changes: 7 additions & 17 deletions server/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,27 +57,17 @@ func (p *Plugin) execBuilder(b builder) (sql.Result, error) {

func (p *Plugin) SetupTables() error {
if _, err := p.db.Exec(`
CREATE TABLE IF NOT EXISTS LLM_Threads (
RootPostID TEXT NOT NULL REFERENCES Posts(ID) PRIMARY KEY,
CREATE TABLE IF NOT EXISTS LLM_PostMeta (
RootPostID TEXT NOT NULL REFERENCES Posts(ID) ON DELETE CASCADE PRIMARY KEY,
Title TEXT NOT NULL
);
`); err != nil {
return fmt.Errorf("can't create llm titles table: %w", err)
}

// Fix existing tables to add on delete cascade to llm_threads_rootpostid_fkey and call it llm_threads_rootpostid_fkey_cascade
// This fixes data retention issues when a post is deleted
if _, err := p.db.Exec(`
DO
$$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'llm_threads_rootpostid_fkey_cascade') THEN
ALTER TABLE LLM_Threads DROP CONSTRAINT IF EXISTS llm_threads_rootpostid_fkey;
ALTER TABLE LLM_Threads ADD CONSTRAINT llm_threads_rootpostid_fkey_cascade FOREIGN KEY (RootPostID) REFERENCES Posts(ID) ON DELETE CASCADE;
END IF;
END
$$;
`); err != nil {
// This fixes data retention issues when a post is deleted for an older version of the postmeta table.
// Migrate from the old table using `"INSERT INTO LLM_PostMeta(RootPostID, Title) SELECT RootPostID, Title from LLM_Threads"`
if _, err := p.db.Exec(`ALTER TABLE IF EXISTS LLM_Threads DROP CONSTRAINT IF EXISTS llm_threads_rootpostid_fkey;`); err != nil {
return fmt.Errorf("failed to migrate constraint: %w", err)
}

Expand All @@ -93,7 +83,7 @@ func (p *Plugin) saveTitleAsync(threadID, title string) {
}

func (p *Plugin) saveTitle(threadID, title string) error {
_, err := p.execBuilder(p.builder.Insert("LLM_Threads").
_, err := p.execBuilder(p.builder.Insert("LLM_PostMeta").
Columns("RootPostID", "Title").
Values(threadID, title).
Suffix("ON CONFLICT (RootPostID) DO UPDATE SET Title = ?", title))
Expand Down Expand Up @@ -124,7 +114,7 @@ func (p *Plugin) getAIThreads(dmChannelIDs []string) ([]AIThread, error) {
Where(sq.Eq{"ChannelID": dmChannelIDs}).
Where(sq.Eq{"RootId": ""}).
Where(sq.Eq{"DeleteAt": 0}).
LeftJoin("LLM_Threads as t ON t.RootPostID = p.Id").
LeftJoin("LLM_PostMeta as t ON t.RootPostID = p.Id").
OrderBy("CreateAt DESC").
Limit(60).
Offset(0),
Expand Down

0 comments on commit e01926c

Please sign in to comment.