예제 #1
0
// Get the table data
func dumpTableData(w io.Writer, db mysql.Conn, table string) {
	fmt.Fprintf(w, "\n--\n-- Dumping data for table `%s`\n--\n\n", table)

	rowCnt, _, err := db.QueryFirst(getSelectCountQueryFor(db, table))
	checkError(err)
	if rowCnt.Int(0) == 0 {
		fmt.Fprintf(w, "--\n-- Empty table\n--\n\n")
		return
	} else {
		fmt.Fprintf(w, "--\n-- %d rows\n--\n\n", rowCnt.Int(0))
	}

	fmt.Fprintf(w, "LOCK TABLES `%s` WRITE;\n", table)
	query := fmt.Sprintf("INSERT INTO `%s` VALUES", table)
	rows := make([]string, 0)

	res, err := db.Start(getSelectQueryFor(db, table))
	checkError(err)
	row := res.MakeRow()

	for {
		err = res.ScanRow(row)
		if err == io.EOF {
			break
		}
		checkError(err)

		vals := make([]string, 0)
		for k, col := range row {
			val := "NULL"
			if col != nil {
				val = fmt.Sprintf("'%s'", db.EscapeString(row.Str(k)))
			}
			vals = append(vals, val)
		}

		rows = append(rows, fmt.Sprintf("( %s )", strings.Join(vals, ", ")))
		if len(rows) >= 100 {
			fmt.Fprintf(w, "%s\n%s;\n", query, strings.Join(rows, ",\n"))
			rows = make([]string, 0)
		}
	}

	if len(rows) > 0 {
		fmt.Fprintf(w, "%s\n%s;\n", query, strings.Join(rows, ",\n"))
	}

	fmt.Fprintf(w, "\nUNLOCK TABLES;\n")
}