-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpostgres_connection.go
180 lines (149 loc) · 4.52 KB
/
postgres_connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/FreePeak/db-mcp-server/pkg/db"
)
func main() {
// Example 1: Direct PostgreSQL 17 connection
connectDirectly()
// Example 2: Using the DB Manager with configuration file
connectWithManager()
}
func connectDirectly() {
fmt.Println("=== Example 1: Direct PostgreSQL 17 Connection ===")
// Create configuration for PostgreSQL 17
config := db.Config{
Type: "postgres",
Host: getEnv("POSTGRES_HOST", "localhost"),
Port: 5432,
User: getEnv("POSTGRES_USER", "postgres"),
Password: getEnv("POSTGRES_PASSWORD", "postgres"),
Name: getEnv("POSTGRES_DB", "postgres"),
// PostgreSQL 17 specific options
SSLMode: db.SSLPrefer,
ApplicationName: "db-mcp-example",
ConnectTimeout: 10,
TargetSessionAttrs: "any", // Works with PostgreSQL 10+
// Additional options
Options: map[string]string{
"client_encoding": "UTF8",
},
// Connection pool settings
MaxOpenConns: 10,
MaxIdleConns: 5,
ConnMaxLifetime: 5 * time.Minute,
ConnMaxIdleTime: 5 * time.Minute,
}
// Create database connection
database, err := db.NewDatabase(config)
if err != nil {
log.Fatalf("Failed to create database instance: %v", err)
}
// Connect to the database
fmt.Println("Connecting to PostgreSQL...")
if err := database.Connect(); err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
defer database.Close()
fmt.Println("Successfully connected to PostgreSQL")
fmt.Println("Connection string (masked): ", database.ConnectionString())
// Query PostgreSQL version to verify compatibility
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var version string
err = database.QueryRow(ctx, "SELECT version()").Scan(&version)
if err != nil {
log.Fatalf("Failed to query PostgreSQL version: %v", err)
}
fmt.Printf("Connected to: %s\n", version)
// Run a sample query with PostgreSQL-style placeholders
rows, err := database.Query(ctx, "SELECT datname FROM pg_database WHERE datistemplate = $1", false)
if err != nil {
log.Fatalf("Query failed: %v", err)
}
defer rows.Close()
fmt.Println("\nAvailable databases:")
for rows.Next() {
var dbName string
if err := rows.Scan(&dbName); err != nil {
log.Printf("Failed to scan row: %v", err)
continue
}
fmt.Printf("- %s\n", dbName)
}
if err = rows.Err(); err != nil {
log.Printf("Error during row iteration: %v", err)
}
fmt.Println()
}
func connectWithManager() {
fmt.Println("=== Example 2: Using DB Manager with Configuration ===")
// Create a database manager
manager := db.NewDBManager()
// Create sample configuration with PostgreSQL 17 settings
config := []byte(`{
"connections": [
{
"id": "postgres17",
"type": "postgres",
"host": "localhost",
"port": 5432,
"name": "postgres",
"user": "postgres",
"password": "postgres",
"ssl_mode": "prefer",
"application_name": "db-mcp-example",
"connect_timeout": 10,
"target_session_attrs": "any",
"options": {
"client_encoding": "UTF8"
},
"max_open_conns": 10,
"max_idle_conns": 5,
"conn_max_lifetime_seconds": 300,
"conn_max_idle_time_seconds": 60
}
]
}`)
// Update with environment variables
// In a real application, you would load this from a file
// and use proper environment variable substitution
// Load configuration
if err := manager.LoadConfig(config); err != nil {
log.Fatalf("Failed to load database config: %v", err)
}
// Connect to databases
fmt.Println("Connecting to all configured databases...")
if err := manager.Connect(); err != nil {
log.Fatalf("Failed to connect to databases: %v", err)
}
defer manager.CloseAll()
// Get a specific database connection
database, err := manager.GetDatabase("postgres17")
if err != nil {
log.Fatalf("Failed to get database: %v", err)
}
fmt.Println("Successfully connected to PostgreSQL via manager")
fmt.Println("Connection string (masked): ", database.ConnectionString())
// Query PostgreSQL version to verify compatibility
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var version string
err = database.QueryRow(ctx, "SELECT version()").Scan(&version)
if err != nil {
log.Fatalf("Failed to query PostgreSQL version: %v", err)
}
fmt.Printf("Connected to: %s\n", version)
fmt.Println()
}
// Helper function to get environment variable with fallback
func getEnv(key, fallback string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return fallback
}