-
Notifications
You must be signed in to change notification settings - Fork 0
/
reference.go
110 lines (95 loc) · 2.33 KB
/
reference.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* Copyright 2022-2024 Thorsten A. Knieling
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
package common
import (
"regexp"
"strconv"
"strings"
"github.com/tknie/errorrepo"
)
const referenceRegexp = `(?m)((\w*)://)?(([\w<>]+)(:(\S+))?@)?(tcp\()?(\w[\w.]*):(\d+)\)?(/(\w+))?\??(.*)`
type ReferenceType byte
const (
NoType ReferenceType = iota
MysqlType
PostgresType
AdabasType
OracleType
)
var referenceTypeName = []string{"No valid Type", "Mysql", "Postgres", "Adabas", "Oracle"}
func (rt ReferenceType) String() string {
return referenceTypeName[rt]
}
type Reference struct {
Driver ReferenceType
Host string
Port int
User string
Database string
Options []string
}
// NewReference new reference of database link
func NewReference(url string) (*Reference, string, error) {
var re = regexp.MustCompile(referenceRegexp)
match := re.FindStringSubmatch(url)
if len(match) < 10 {
return nil, "", errorrepo.NewError("DB000018", len(match))
}
p, err := strconv.Atoi(match[9])
if err != nil {
return nil, "", errorrepo.NewError("DB000019", err)
}
ref := &Reference{Driver: ParseTypeName(match[2]),
Host: match[8], Port: p, User: match[4], Database: match[11]}
/*for i, match := range re.FindStringSubmatch(url) {
fmt.Println(match, "found at index", i)
}*/
passwd := match[6]
switch {
case ref.Driver == NoType && strings.Contains(url, "@tcp("):
ref.Driver = MysqlType
case ref.Driver == AdabasType && ref.Database == "":
ref.Database = "4"
}
if len(match) == 13 && match[12] != "" {
ref.Options = strings.Split(match[12], "&")
}
return ref, passwd, nil
}
func (ref *Reference) OptionString() string {
options := ""
for _, o := range ref.Options {
if options == "" {
options += "?"
} else {
options += "&"
}
options += o
}
return options
}
// ParseTypeName parse type string to internal type
func ParseTypeName(t string) ReferenceType {
switch strings.ToLower(t) {
case "postgres":
return PostgresType
case "mysql":
return MysqlType
case "acj", "adatcp":
return AdabasType
case "oracle":
return OracleType
}
return NoType
}
func (r *Reference) SetType(t string) {
r.Driver = ParseTypeName(t)
}