Last active
December 20, 2018 07:09
-
-
Save ajaxray/9b135c81f4fed2131bac7f514d52b86d to your computer and use it in GitHub Desktop.
Parse a MySQL dump and prints table/field definitions as CSV (including Table/field comments)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"regexp" | |
"strings" | |
) | |
// groups: 1 = table name, 2 = fields and indexes, 3 = storage engine info | |
// See: https://regex101.com/r/Fg6x6m/1 | |
var regTableBlock = regexp.MustCompile(`(?ms)CREATE TABLE \x60(\w*)\x60 \(\n(.*?)^\) (.*?);`) | |
// groups: 1 = field name, 2 = field definision, 3 = field comment if any | |
// See: https://regex101.com/r/ca3yfD/1 | |
var regFields = regexp.MustCompile(`(?m)^\s*\x60(\w*)\x60\s*(.*?)(?:COMMENT \'(.*)\')?,$`) | |
// groups: 1 = table comment | |
var regComment = regexp.MustCompile(`(?m)COMMENT='(.*)';$`) | |
func main() { | |
flag.Usage = func() { | |
fmt.Printf("Usage: %s <input-mysql-dump>.sql\n", os.Args[0]) | |
os.Exit(0) | |
} | |
flag.Parse() | |
args := flag.Args() | |
b, err := ioutil.ReadFile(args[0]) | |
fatalIfError(err, fmt.Sprintf("Failed to open the source file. [%s]", err)) | |
str := string(b) | |
fmt.Println("Name, Definition, Comment") | |
tables := regTableBlock.FindAllStringSubmatch(str, -1) | |
for i := range tables { | |
printTableRow(tables[i]) | |
printFieldRows(tables[i][2]) | |
fmt.Println(",,") | |
} | |
} | |
func printTableRow(tableInfo []string) { | |
comment := "" | |
commentMatch := regComment.FindStringSubmatch(tableInfo[0]) | |
if len(commentMatch) > 0 { | |
comment = commentMatch[1] | |
tableInfo[3] = strings.Replace(tableInfo[3]+";", commentMatch[0], "", 1) | |
} | |
fmt.Printf("\"TABLE: %s\",\"%s\",\"%s\"\n", tableInfo[1], tableInfo[3], comment) | |
} | |
func printFieldRows(fieldRows string) { | |
fields := regFields.FindAllStringSubmatch(fieldRows, -1) | |
for i := range fields { | |
comment := "" | |
if len(fields) > 2 { | |
comment = fields[i][3] | |
} | |
fmt.Printf("\"%s\",\"%s\",\"%s\"\n", fields[i][1], fields[i][2], comment) | |
} | |
} | |
func fatalIfError(err error, message string) { | |
if err != nil { | |
fmt.Printf("ERROR: %s \n", message) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment