You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
865 B

1 year ago
  1. package mysql
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "git.aiterp.net/rpdata2/rpdata2-take2/ports/mysql/mysqlgen"
  7. "git.aiterp.net/rpdata2/rpdata2-take2/tag"
  8. "time"
  9. )
  10. type Database struct {
  11. db *sql.DB
  12. q *mysqlgen.Queries
  13. }
  14. func (db *Database) Tags() tag.Repository {
  15. return &tagRepository{
  16. db: db.db,
  17. q: db.q,
  18. }
  19. }
  20. func Connect(host string, port int, username, password, database string) (*Database, error) {
  21. db, err := sql.Open("mysql", fmt.Sprintf(
  22. "%s:%s@(%s:%d)/%s?parseTime=true", username, password, host, port, database,
  23. ))
  24. if err != nil {
  25. return nil, err
  26. }
  27. db.SetMaxOpenConns(10)
  28. db.SetMaxIdleConns(10)
  29. db.SetConnMaxIdleTime(time.Minute)
  30. err = db.Ping()
  31. if err != nil {
  32. return nil, err
  33. }
  34. q, err := mysqlgen.Prepare(context.Background(), db)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return &Database{db: db, q: q}, nil
  39. }