forked from asternic/wuzapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
100 lines (83 loc) · 2.25 KB
/
Copy pathdb.go
File metadata and controls
100 lines (83 loc) · 2.25 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
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
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
_ "modernc.org/sqlite"
)
type DatabaseConfig struct {
Type string
Host string
Port string
User string
Password string
Name string
Path string
SSLMode string
}
func InitializeDatabase(exPath string) (*sqlx.DB, error) {
config := getDatabaseConfig(exPath)
if config.Type == "postgres" {
return initializePostgres(config)
}
return initializeSQLite(config)
}
func getDatabaseConfig(exPath string) DatabaseConfig {
dbUser := os.Getenv("DB_USER")
dbPassword := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
dbSSL := os.Getenv("DB_SSLMODE")
sslMode := dbSSL
if dbSSL == "true" {
sslMode = "require"
} else if dbSSL == "false" || dbSSL == "" {
sslMode = "disable"
}
if dbUser != "" && dbPassword != "" && dbName != "" && dbHost != "" && dbPort != "" {
return DatabaseConfig{
Type: "postgres",
Host: dbHost,
Port: dbPort,
User: dbUser,
Password: dbPassword,
Name: dbName,
SSLMode: sslMode,
}
}
return DatabaseConfig{
Type: "sqlite",
Path: filepath.Join(exPath, "dbdata"),
}
}
func initializePostgres(config DatabaseConfig) (*sqlx.DB, error) {
dsn := fmt.Sprintf(
"user=%s password=%s dbname=%s host=%s port=%s sslmode=%s",
config.User, config.Password, config.Name, config.Host, config.Port, config.SSLMode,
)
db, err := sqlx.Open("postgres", dsn)
if err != nil {
return nil, fmt.Errorf("failed to open postgres connection: %w", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("failed to ping postgres database: %w", err)
}
return db, nil
}
func initializeSQLite(config DatabaseConfig) (*sqlx.DB, error) {
if err := os.MkdirAll(config.Path, 0751); err != nil {
return nil, fmt.Errorf("could not create dbdata directory: %w", err)
}
dbPath := filepath.Join(config.Path, "users.db")
db, err := sqlx.Open("sqlite", dbPath+"?_pragma=foreign_keys(1)&_busy_timeout=3000")
if err != nil {
return nil, fmt.Errorf("failed to open sqlite database: %w", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("failed to ping sqlite database: %w", err)
}
return db, nil
}