summaryrefslogtreecommitdiff
path: root/internal/storage/sql_provider_backend_mysql.go
blob: b0382ed7d82dabc7630fdbb001c3ca0211989349 (plain)
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
package storage

import (
	"crypto/x509"
	"fmt"
	"path"
	"time"

	"github.com/go-sql-driver/mysql"

	"github.com/authelia/authelia/v4/internal/configuration/schema"
)

// MySQLProvider is a MySQL provider.
type MySQLProvider struct {
	SQLProvider
}

// NewMySQLProvider a MySQL provider.
func NewMySQLProvider(config *schema.Configuration, caCertPool *x509.CertPool) (provider *MySQLProvider) {
	provider = &MySQLProvider{
		SQLProvider: NewSQLProvider(config, providerMySQL, providerMySQL, dsnMySQL(config.Storage.MySQL)),
	}

	// All providers have differing SELECT existing table statements.
	provider.sqlSelectExistingTables = queryMySQLSelectExistingTables

	// Specific alterations to this provider.
	provider.sqlFmtRenameTable = queryFmtMySQLRenameTable

	return provider
}

func dsnMySQL(config *schema.MySQLStorageConfiguration) (dataSourceName string) {
	dsnConfig := mysql.NewConfig()

	switch {
	case path.IsAbs(config.Host):
		dsnConfig.Net = sqlNetworkTypeUnixSocket
		dsnConfig.Addr = config.Host
	case config.Port == 0:
		dsnConfig.Net = sqlNetworkTypeTCP
		dsnConfig.Addr = fmt.Sprintf("%s:%d", config.Host, 3306)
	default:
		dsnConfig.Net = sqlNetworkTypeTCP
		dsnConfig.Addr = fmt.Sprintf("%s:%d", config.Host, config.Port)
	}

	switch config.Port {
	case 0:
		dsnConfig.Addr = config.Host
	default:
		dsnConfig.Addr = fmt.Sprintf("%s:%d", config.Host, config.Port)
	}

	dsnConfig.DBName = config.Database
	dsnConfig.User = config.Username
	dsnConfig.Passwd = config.Password
	dsnConfig.Timeout = config.Timeout
	dsnConfig.MultiStatements = true
	dsnConfig.ParseTime = true
	dsnConfig.Loc = time.Local

	return dsnConfig.FormatDSN()
}