-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_connection.go
More file actions
68 lines (56 loc) · 1.43 KB
/
db_connection.go
File metadata and controls
68 lines (56 loc) · 1.43 KB
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
package main
import (
"database/sql"
"fmt"
"os"
"path/filepath"
_ "modernc.org/sqlite"
)
var (
// Global database connection - initialized once and reused
dbConnection *sql.DB
)
// initDBConnection initializes the global database connection
// This should be called once at application startup
func initDBConnection() error {
if dbConnection != nil {
return nil // Already initialized
}
dbPath, err := getDBPath()
if err != nil {
return fmt.Errorf("failed to get DB path: %w", err)
}
dbDir := filepath.Dir(dbPath)
if err := os.MkdirAll(dbDir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create DB directory: %w", err)
}
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
// Create sessions table if it doesn't exist
if err := ensureSessionsTable(db); err != nil {
db.Close()
return fmt.Errorf("failed to create sessions table: %w", err)
}
dbConnection = db
return nil
}
// getDB returns the global database connection
// Panics if called before initDBConnection
func getDB() *sql.DB {
if dbConnection == nil {
panic("database connection not initialized - call initDBConnection first")
}
return dbConnection
}
// closeDBConnection closes the global database connection
// Should be called on application exit
func closeDBConnection() error {
if dbConnection == nil {
return nil
}
err := dbConnection.Close()
dbConnection = nil
return err
}