fixed db init

This commit is contained in:
Radu Macocian (admac)
2026-06-12 17:12:50 +02:00
parent 4f989aa512
commit ed04207b20
+37 -7
View File
@@ -1,6 +1,7 @@
package history package history
import ( import (
"log/slog"
"net" "net"
"net/url" "net/url"
@@ -11,6 +12,7 @@ import (
type DbClient struct { type DbClient struct {
Cfg config.DbConfig Cfg config.DbConfig
Logger slog.Logger
} }
type Conversation struct { type Conversation struct {
@@ -27,23 +29,51 @@ func (client DbClient) init() error {
const createMessageTable = ` const createMessageTable = `
CREATE TABLE IF NOT EXISTS messages ( CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
role TEXT NOT NULL role TEXT NOT NULL,
content TEXT NOT NULL content TEXT NOT NULL,
conversation_id UUID conversation_id UUID,
created_at TIMESTAMPTZ NOT NULL DEFAULT now() created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)` )`
const createToolCallTable = ` const createToolCallTable = `
CREATE TABLE IF NOT EXISTS tool_calls ( CREATE TABLE IF NOT EXISTS tool_calls (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
type TEXT NOT NULL type TEXT NOT NULL,
functionName TEXT NOT NULL functionName TEXT NOT NULL,
functionArgs TEXT NOT NULL functionArgs TEXT NOT NULL,
message_id UUID message_id UUID,
created_at TIMESTAMPTZ NOT NULL DEFAULT now() created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)` )`
conn := pgx.MustOpen(client.connectionString()) conn := pgx.MustOpen(client.connectionString())
defer conn.Close() 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 { if _, err := conn.Exec(createToolCallTable); err != nil {
return err return err