Created
June 19, 2019 18:04
-
-
Save xigh/58e138f856bd0946dc748b0f0dc44b02 to your computer and use it in GitHub Desktop.
dump #sql tables in #golang
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 ( | |
"database/sql" | |
"flag" | |
"fmt" | |
"log" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
var ( | |
dbUser = flag.String("user", "user", "username") | |
dbPass = flag.String("pass", "pass", "password") | |
dbHost = flag.String("host", "tcp(127.0.0.1:3306)", "hostname") | |
dbName = flag.String("name", "base", "database") | |
) | |
func showTables(db *sql.DB) ([]string, error) { | |
rows0, err := db.Query("show tables") | |
if err != nil { | |
return nil, err | |
} | |
defer rows0.Close() | |
n := 0 | |
tables := make([]string, 0) | |
for rows0.Next() { | |
var s string | |
n++ | |
err = rows0.Scan(&s) | |
if err != nil { | |
return nil, fmt.Errorf("rows.Scan %d failed: %v", n, err) | |
} | |
tables = append(tables, s) | |
} | |
return tables, nil | |
} | |
type Desc struct { | |
Name string | |
Type string | |
Null string | |
Key *string | |
Default *string | |
Extra *string | |
} | |
func describe(db *sql.DB, table string) (map[string]*Desc, error) { | |
rows0, err := db.Query("describe " + table) | |
if err != nil { | |
return nil, err | |
} | |
defer rows0.Close() | |
n := 0 | |
descs := make(map[string]*Desc) | |
for rows0.Next() { | |
var d Desc | |
n++ | |
err = rows0.Scan(&d.Name, &d.Type, &d.Null, &d.Key, &d.Default, &d.Extra) | |
if err != nil { | |
return nil, fmt.Errorf("rows.Scan %d failed: %v", n, err) | |
} | |
descs[d.Name] = &d | |
} | |
return descs, nil | |
} | |
func main() { | |
flag.Parse() | |
dbSrc := fmt.Sprintf("%s:%s@%s/%s?parseTime=true", *dbUser, *dbPass, *dbHost, *dbName) | |
db, err := sql.Open("mysql", dbSrc) | |
if err != nil { | |
log.Fatalf("sql.Open failed: %v", err) | |
} | |
defer db.Close() | |
// sql.Open() does not establish any connections to the database ... | |
err = db.Ping() | |
if err != nil { | |
log.Fatalf("db.Ping failed: %v", err) | |
} | |
tables, err := showTables(db) | |
if err != nil { | |
log.Fatalf("showTables failed: %v\n", err) | |
} | |
for _, table := range tables { | |
ds, err := describe(db, table) | |
if err != nil { | |
log.Fatalf("describe failed: %v\n", err) | |
} | |
fmt.Printf("%s:\n", table) | |
for _, d := range ds { | |
fmt.Printf("\t%-20s %s\n", d.Name, d.Type) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment