From ed04207b200bc9565a58246fca6dc35212b8fcc6 Mon Sep 17 00:00:00 2001 From: "Radu Macocian (admac)" Date: Fri, 12 Jun 2026 17:12:50 +0200 Subject: [PATCH] fixed db init --- db/history/history.go | 46 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/db/history/history.go b/db/history/history.go index 9870e24..2b5f338 100644 --- a/db/history/history.go +++ b/db/history/history.go @@ -1,6 +1,7 @@ package history import ( + "log/slog" "net" "net/url" @@ -11,6 +12,7 @@ import ( type DbClient struct { Cfg config.DbConfig + Logger slog.Logger } type Conversation struct { @@ -27,24 +29,52 @@ func (client DbClient) init() error { const createMessageTable = ` CREATE TABLE IF NOT EXISTS messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - role TEXT NOT NULL - content TEXT NOT NULL - conversation_id UUID + role TEXT NOT NULL, + content TEXT NOT NULL, + conversation_id UUID, created_at TIMESTAMPTZ NOT NULL DEFAULT now() )` const createToolCallTable = ` CREATE TABLE IF NOT EXISTS tool_calls ( id UUID PRIMARY KEY, - type TEXT NOT NULL - functionName TEXT NOT NULL - functionArgs TEXT NOT NULL - message_id UUID + type TEXT NOT NULL, + functionName TEXT NOT NULL, + functionArgs TEXT NOT NULL, + message_id UUID, created_at TIMESTAMPTZ NOT NULL DEFAULT now() )` conn := pgx.MustOpen(client.connectionString()) defer conn.Close() - + tables := []struct { + tableName string + script string + }{ + {"conversations", createConversationTable}, + {"messages", createMessageTable}, + {"tool_calls", createToolCallTable}, + } + + for _, table := range tables { + var exists bool + if err := conn.QueryRow(`SELECT EXISTS + (SELECT 1 FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name =$1)`, table.tableName).Scan(&exists); err != nil { + client.Logger.Error("Error while checking table", "table", table.tableName) + return err + } + if exists { + client.Logger.Debug("Table found", "table", table.tableName) + } else { + client.Logger.Debug("Table not found. Creating", "table", table.tableName) + if _, err := conn.Exec(table.script); err != nil { + client.Logger.Error("Could not create table", "table", table.tableName) + return err + } + } + } + if _, err := conn.Exec(createToolCallTable); err != nil { return err }