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

Time:01-10

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="...").

CodePudding user response:

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

CodePudding user response:

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)
        }
    }
}
  •  Tags:  
  • Related