简体   繁体   中英

How to take a DB/Table dump (.sql file) using gorm in a golang application?

I am using a Golang Application and the Gorm ORM to connect to a Database. How can I take a table dump (.sql file) through the ORM? Is it even possible?

If it is possible, is it possible to use a where clause (like in mysqldump --where="..." ).

It's not possible, mysqldump is a separate utility command-line tool like mysqlimport, mysqladmin etc. It's not a MySQL query.

But You should be able to run this raw query using gorm to store query results to file https://dev.mysql.com/doc/refman/8.0/en/select-into.html

There is no Function for dump in GORM.

But you can get table data into struct object. And you can save it as json or in any format for your backup reference.

Since, GORM internally uses sql. You can try with this logic.

Refer this link: https://gist.github.com/xigh/58e138f856bd0946dc748b0f0dc44b02

func main() {

    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)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM