Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "flag"
- "fmt"
- "io/ioutil"
- "database/sql"
- _ "github.com/go-sql-driver/mysql"
- "gopkg.in/yaml.v2"
- )
- // DbCredentials represents MySQL credentials. It is also part of yaml config`
- type DbCredentials struct {
- Driver string
- User string
- Pass string
- Port int
- Host string
- Name string
- }
- // Index is part of yaml configuration
- type Index struct {
- MinSize int `yaml:"min_size"`
- IndexSum []string `yaml:"index_sum"`
- }
- // Config is a root structure of yaml of config
- type Config struct {
- Parameters DbCredentials
- Indexes map[string]Index
- }
- func dbConnection(credentials *DbCredentials) (db *sql.DB) {
- dns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", credentials.User, credentials.Pass, credentials.Host, credentials.Port, credentials.Name)
- db, err := sql.Open("mysql", dns)
- if err != nil {
- panic(err.Error())
- }
- return db
- }
- func parseConfig(configPath string) Config {
- configData, err := ioutil.ReadFile(configPath)
- if err != nil {
- panic("Cannot read config file from "+configPath)
- }
- conf := Config{}
- if err = yaml.Unmarshal([]byte(configData), &conf); err != nil {
- panic(err)
- }
- return conf
- }
- func countIndex(db *sql.DB, name string) int {
- rows, err := db.Query("SELECT COUNT(*) FROM "+name)
- if err != nil {
- panic(err)
- }
- defer rows.Close();
- for rows.Next() {
- var num int
- if err := rows.Scan(&num); err != nil {
- panic(err)
- }
- return num
- }
- panic("Index not found")
- }
- func checkIndexes(db *sql.DB, indexes *map[string]Index) {
- count := map[string]int{}
- for k, v := range *indexes {
- count[k] = countIndex(db, k)
- if v.MinSize > 0 && count[k] < v.MinSize {
- panic(fmt.Sprintf("Index %s is too small. Expected size: atleast %d. Given %d",
- k, v.MinSize, count[k]))
- }
- }
- var sum int
- for k, v := range *indexes {
- if len(v.IndexSum) <= 0 {
- continue
- }
- sum = 0
- for _, item := range v.IndexSum {
- if val, ok := count[item]; ok {
- sum += val
- continue
- }
- panic(fmt.Sprintf("Index %s required to compute sum for %s is not defined.",
- item, k))
- }
- if sum != count[k] {
- panic(fmt.Sprintf("Sum for index %s is invalid", k))
- }
- }
- }
- func main() {
- var configPath string
- flag.StringVar(&configPath, "config", "config.yml", "Path to configuration file")
- flag.Parse()
- config := parseConfig(configPath)
- var db *sql.DB = dbConnection(&config.Parameters)
- defer db.Close()
- checkIndexes(db, &config.Indexes)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement