mysql.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package dbutils
  15. import (
  16. "strings"
  17. "yunion.io/x/pkg/errors"
  18. )
  19. type SDBConfig struct {
  20. Hostport string
  21. Database string
  22. Username string
  23. Password string
  24. }
  25. func (cfg SDBConfig) Validate() error {
  26. errs := make([]error, 0)
  27. if len(cfg.Hostport) == 0 {
  28. errs = append(errs, errors.Error("empty host port"))
  29. }
  30. if len(cfg.Username) == 0 {
  31. errs = append(errs, errors.Error("empty username"))
  32. }
  33. if len(cfg.Database) == 0 {
  34. errs = append(errs, errors.Error("empty database"))
  35. }
  36. return errors.NewAggregate(errs)
  37. }
  38. func ParseMySQLConnStr(connStr string) SDBConfig {
  39. // fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?%s", user, passwd, host, port, dburl, query.Encode())
  40. cfg := SDBConfig{}
  41. index := strings.Index(connStr, "@tcp(")
  42. if index > 0 {
  43. userpass := connStr[:index]
  44. hostdb := connStr[index+len("@tcp("):]
  45. index = strings.Index(userpass, ":")
  46. if index > 0 {
  47. cfg.Username = userpass[:index]
  48. cfg.Password = userpass[index+1:]
  49. } else if index < 0 {
  50. cfg.Username = userpass
  51. }
  52. index = strings.Index(hostdb, ")/")
  53. if index > 0 {
  54. cfg.Hostport = hostdb[:index]
  55. dbstr := hostdb[index+len(")/"):]
  56. index = strings.Index(dbstr, "?")
  57. if index > 0 {
  58. cfg.Database = dbstr[:index]
  59. } else if index < 0 {
  60. cfg.Database = dbstr
  61. }
  62. }
  63. }
  64. return cfg
  65. }