Skip to content

Instantly share code, notes, and snippets.

@itsbalamurali
Created January 6, 2018 10:18
Show Gist options
  • Save itsbalamurali/dd27b4c85e3996b54de5c48f2d846c83 to your computer and use it in GitHub Desktop.
Save itsbalamurali/dd27b4c85e3996b54de5c48f2d846c83 to your computer and use it in GitHub Desktop.
Reverse your MySQL Schema to Golang Structs
package main
import (
"fmt"
"log"
"os"
"strconv"
"github.com/Shelnutt2/db2struct"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
//Program to reverse engineer your mysql database into gorm models
func main() {
user := "root"
pass := "root"
host := "localhost"
database := "blahblah"
port := 3306
packagename := "models"
fmt.Println("Connecting to mysql server " + host + ":" + strconv.Itoa(port))
db, err := gorm.Open("mysql", user+":"+pass+"@/"+database+"?charset=utf8&parseTime=True&loc=Local")
if err != nil {
log.Fatalln("Failed to connect database")
}
defer db.Close()
//Get all the tables from Database
rows, err := db.Raw("SHOW TABLES").Rows()
defer rows.Close()
for rows.Next() {
var table string
rows.Scan(&table)
columnDataTypes, err := db2struct.GetColumnsFromMysqlTable(user, pass, host, port, database, table)
if err != nil {
fmt.Println("Error in selecting column data information from mysql information schema")
return
}
// Generate struct string based on columnDataTypes
struc, err := db2struct.Generate(*columnDataTypes, table, table, packagename, false, true, false)
if err != nil {
fmt.Println("Error in creating struct from json: " + err.Error())
return
}
file, err := os.Create(packagename + "/" + table + ".go")
if err != nil {
log.Fatal("Cannot create file", err)
}
defer file.Close()
fmt.Fprintf(file, string(struc))
log.Println("Wrote " + table + ".go to disk")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment