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
import (
"log/slog"
"net"
"net/url"
@@ -11,6 +12,7 @@ import (
type DbClient struct {
Cfg config.DbConfig
Logger slog.Logger
}
type Conversation struct {
@@ -27,23 +29,51 @@ 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