-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinyorm.go
60 lines (47 loc) · 1.91 KB
/
tinyorm.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
package tinyorm
import (
"errors"
"fmt"
"github.com/BitlyTwiser/tinyORM/pkg/connections"
"github.com/BitlyTwiser/tinyORM/pkg/dialects"
"github.com/BitlyTwiser/tinyORM/pkg/logger"
)
// Connect is the primary entrypoint to tinyorm
// Connect will accept variadic values of connection strings i.e. development, prod etc..
// Each connection string must match a string present within the database.yml.
// If a connection fails whilst connecting to any of the given databases, the failure is tracked and reported.
// If all fail, the application will exit
func Connect(connection string) (dialects.DialectHandler, error) {
// Default to development
if connection == "" {
connection = "development"
}
err := connections.InitDatabaseConnection(connection)
if err != nil {
return nil, logger.Log.LogError("error initializing database connection", err)
}
if handle, found := connections.Connections[connection]; found {
return handle, nil
}
return nil, logger.Log.LogError("error connecting to database", fmt.Errorf("no database was found in database.yml"))
}
// Will connect to and handle multiple concurrent database connections
// Will accept variadic set of values each string denoting a database connection within the database.yml file.
// i.e. Development, Prod, RO etc..
func MultiConnect(databaseConnections ...string) (dialects.MultiTenantDialectHandler, error) {
handlers := dialects.MultiTenantDialectHandler{Handlers: make(map[string]dialects.DialectHandler)}
for _, c := range databaseConnections {
err := connections.InitDatabaseConnection(c)
if err != nil {
logger.Log.LogError(fmt.Sprintf("error connecting to database %s", c), err)
continue
}
if handle, found := connections.Connections[c]; found {
handlers.Set(c, handle)
}
}
if handlers.Empty() {
return handlers, errors.New("no successful connections made to any databases present within the database.yml")
}
return handlers, nil
}