-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
66 lines (55 loc) · 1.42 KB
/
db.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
package main
import (
"database/sql"
"fmt"
"os"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
var db *sql.DB // kansje bad practise, men lettest
func init() {
if err := godotenv.Load(); err != nil {
fmt.Println("Error loading .env file")
}
}
func Connect() {
connStr := fmt.Sprintf("postgresql://%s:%[email protected]/job-scraper?sslmode=require", os.Getenv("NEONUSER"), os.Getenv("NEONPASS"))
var err error
db, err = sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
var version string
if err := db.QueryRow("select version()").Scan(&version); err != nil {
panic(err)
}
fmt.Printf("version=%s\n", version)
}
func cleanDB() {
fmt.Println("Cleaning DB.")
_, err := db.Exec("TRUNCATE TABLE technology_counts")
if err != nil {
fmt.Println("Error emptying technology_counts", err)
}
_, err = db.Exec("ALTER SEQUENCE technology_counts_id_seq RESTART WITH 1;")
if err != nil {
fmt.Println("Error resetting technology_counts", err)
}
}
func uploadToDB(tech string, count int) {
if db == nil {
fmt.Println("Database connection is not established.")
return
}
stmt, err := db.Prepare("INSERT INTO technology_counts (tech, count) VALUES ($1, $2)")
if err != nil {
fmt.Println("Error preparing SQL statement:", err)
return
}
defer stmt.Close()
_, err = stmt.Exec(tech, count)
if err != nil {
fmt.Println("Error executing SQL statement:", err)
return
}
}