-
Notifications
You must be signed in to change notification settings - Fork 13
/
rdbms.go
94 lines (77 loc) · 2.13 KB
/
rdbms.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
// ClueGetter - Does things with mail
//
// Copyright 2016 Dolf Schimmel, Freeaqingme.
//
// This Source Code Form is subject to the terms of the two-clause BSD license.
// For its contents, please refer to the LICENSE file.
//
package core
import (
"database/sql"
"database/sql/driver"
"fmt"
"time"
_ "github.com/Freeaqingme/golang-sql-driver-mysql"
)
var Rdbms *sql.DB
func rdbmsStart() {
dsn := rdbmsGetDsn(false)
display_dsn := rdbmsGetDsn(true)
err_msg := "Could not connect to %s. Got error: %s"
rdbms, err := sql.Open(Config.ClueGetter.Rdbms_Driver, dsn)
if err != nil {
Log.Fatal(fmt.Sprintf(err_msg, display_dsn, err))
}
Rdbms = rdbms
err = Rdbms.Ping()
if err != nil {
Log.Fatal(fmt.Sprintf(err_msg, display_dsn, err))
}
statsInitCounter("RdbmsQueries")
statsInitCounter("RdbmsErrors")
var version string
Rdbms.QueryRow("SELECT VERSION()").Scan(&version)
Log.Info(fmt.Sprintf("Successfully connected to %s: %s", display_dsn, version))
}
func rdbmsStop() {
Rdbms.Close()
Log.Info("Disconnected from RDBMS %s", rdbmsGetDsn(true))
}
func rdbmsGetDsn(display bool) string {
cfg := Config.ClueGetter
dsn_options := "sql_notes=false&parseTime=true&strict=true&SESSION tx_isolation='READ-UNCOMMITTED'"
password := cfg.Rdbms_Password
if display && cfg.Rdbms_Password != "" {
password = "***"
}
return fmt.Sprintf("%s:%s@%s(%s)/%s?%s",
cfg.Rdbms_User, password, cfg.Rdbms_Protocol,
cfg.Rdbms_Address, cfg.Rdbms_Database, dsn_options)
}
// TODO: Make method of RdbmsClient
func RdbmsRowsInTable(table string) (count int) {
err := Rdbms.QueryRow(`
SELECT TABLE_ROWS FROM information_schema.tables
WHERE TABLE_SCHEMA = database() AND TABLE_NAME = ?
`, table).Scan(&count)
if err != nil {
Log.Fatal(err)
}
return count
}
type NullTime struct {
time.Time
Valid bool // Valid is true if Time is not NULL
}
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}