forked from LiamDotPro/Go-Multitenancy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Database.go
76 lines (57 loc) · 1.8 KB
/
Database.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
package main
import (
"encoding/gob"
"fmt"
"github.com/LiamDotPro/Go-Multitenancy/tenants"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/wader/gormstore"
"os"
"time"
)
var Connection *gorm.DB
var Store *gormstore.Store
func startDatabaseServices() {
// Database Connection string
db, err := gorm.Open(os.Getenv("dialect"), os.Getenv("connectionString"))
if err != nil {
fmt.Println(err)
panic("failed to connect database")
}
// Turn logging for the database on.
db.LogMode(true)
// Make Master connection available globally.
Connection = db
// Now Setup store - Tenant Store
// Password is passed as byte key method
Store = gormstore.NewOptions(db, gormstore.Options{
TableName: "sessions",
SkipCreateTable: false,
}, []byte(os.Getenv("sessionsPassword")))
// Register session types for consuming in sessions
gob.Register(HostProfile{})
gob.Register(ClientProfile{})
// Always attempt to migrate changes to the master tenant schema
if err := migrateMasterTenantDatabase(); err != nil {
fmt.Print("There was an error while trying to migrate the tenant tables..")
os.Exit(1)
}
// attempt to migrate any tenant table changes to all clients.
AutoMigrateTenantTableChanges()
// Makes quit Available
quit := make(chan struct{})
// Every hour remove dead sessions.
go Store.PeriodicCleanup(1*time.Hour, quit)
}
// Simply migrates all of the tenant tables
func AutoMigrateTenantTableChanges() {
var TenantInformation [] tenants.TenantConnectionInformation
Connection.Find(&tenants.TenantConnectionInformation{})
for _, element := range TenantInformation {
conn, _ := element.GetConnection()
if err := migrateTenantTables(conn); err != nil {
fmt.Print("An error occurred while attempting to migrate tenant tables")
os.Exit(1)
}
}
}