Exemplo n.º 1
0
func readSqlTemplate(file string) map[string]string {
	lines, err := util.ReadLines(file)
	if err != nil {
		log.Panicf("ERR: fail to read sql template file, %s, %s", file, err)
	}
	sqlTemp := make(map[string]string)
	const k1 = "%d."
	const k2 = "_%s"
	for _, line := range lines {
		start := strings.Index(line, k1)
		end := strings.Index(line, k2)
		table := line[start+len(k1) : end]
		sqlTemp[table] = line
		log.Printf("INF: table=%s", table)
	}
	return sqlTemp
}
Exemplo n.º 2
0
func loadSqlFile(ctx *cli.Context) {
	filename := ctx.String("filename")
	key := "petLog_"
	if strings.Index(filename, key) == -1 {
		log.Printf("WAR: substr '%s' not in filename", key)
		return
	}

	re, _ := regexp.Compile("petLog_([0-9]+)")
	slice := re.FindStringSubmatch(filename)
	if len(slice) < 2 {
		log.Printf("WAR, not match, %s", filename)
		return
	}
	log.Printf("INF: filename=%s, dbIdx=%s", filename, slice[1])
	dbIdx, err := strconv.Atoi(slice[1])
	if err != nil {
		log.Printf("WAR: Atoi fail, %s, %s", slice[1], err)
		return
	}
	dbname := fmt.Sprintf("petLog_%d", dbIdx)
	lines, err := util.ReadLines(filename)
	if err != nil {
		log.Printf("WAR: fail to read file, %s,, %s", filename, err)
		return
	}

	jsonconf := prod.NewJsonConf(ctx.String("json"))
	user := jsonconf.Default_db_user
	passwd := jsonconf.Default_db_pw
	port := jsonconf.Default_db_port

	var host string
	for _, conf := range jsonconf.Route_list {
		if conf.UinStartInt <= dbIdx && dbIdx <= conf.UinEndInt {
			host = conf.Db_host
			break
		}
	}
	if host == "" {
		fmt.Printf("WAR: uin=%d, host not found", dbIdx)
		return
	}

	dns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=gbk", user, passwd, host, port, dbname)
	conn, err := sql.Open("mysql", dns)
	if err != nil {
		log.Panicf("ERR: sql.Open, %s, %s", dns, err)
	}

	for _, line := range lines {
		sqlstr := line
		stmt, err := conn.Prepare(sqlstr)
		if err != nil {
			log.Panicf("ERR, conn.Prepare, %s, sql=%s", err, sqlstr)
		}
		_, err = stmt.Exec()
		if err != nil {
			log.Panicf("ERR, stmt.Exec, %s, sql=%s", err, sqlstr)
		}
		stmt.Close()
	}
	log.Printf("INF: execute, host=%s, filename=%s, lines=%d", host, filename, len(lines))
	conn.Close()
}