Dump database

This commit is contained in:
kolaente 2020-06-19 22:19:22 +02:00
parent 47e9328f2e
commit 2874e9cddd
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
2 changed files with 50 additions and 5 deletions

View File

@ -18,9 +18,11 @@ package cmd
import (
"archive/zip"
"bytes"
"code.vikunja.io/api/pkg/db"
"code.vikunja.io/api/pkg/files"
"code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/version"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"io"
@ -28,6 +30,8 @@ import (
"time"
)
const compressionUsed = zip.Deflate
func init() {
rootCmd.AddCommand(dumpCmd)
}
@ -54,9 +58,33 @@ var dumpCmd = &cobra.Command{
if err != nil {
log.Criticalf("Error saving config file: %s", err)
}
log.Info("Dumped config file")
// Version
var buf bytes.Buffer
buf.Write([]byte(version.Version))
// Database
db.Dump()
data, err := db.Dump()
if err != nil {
log.Criticalf("Error saving database data: %s", err)
}
for t, d := range data {
header := &zip.FileHeader{
Name: "database/" + t + ".json",
Method: compressionUsed,
}
w, err := dumpWriter.CreateHeader(header)
if err != nil {
log.Criticalf("Error writing database table %s: %s", t, err)
}
_, err = w.Write(d)
if err != nil {
log.Criticalf("Error writing database table %s: %s", t, err)
}
}
log.Info("Dumped database")
// Files
files.Dump()
},
@ -80,13 +108,11 @@ func writeFileToZip(filename string, writer *zip.Writer) error {
return err
}
// Using FileInfoHeader() above only uses the basename of the file. If we want
// to preserve the folder structure we can overwrite this with the full path.
header.Name = info.Name()
// Change to deflate to gain better compression
// see http://golang.org/pkg/archive/zip/#pkg-constants
header.Method = zip.Deflate
header.Method = compressionUsed
w, err := writer.CreateHeader(header)
if err != nil {

View File

@ -16,8 +16,27 @@
package db
import "encoding/json"
// Dump dumps all database tables
func Dump() (err error) {
func Dump() (data map[string][]byte, err error) {
tables, err := x.DBMetas()
if err != nil {
return
}
data = make(map[string][]byte, len(tables))
for _, table := range tables {
entries := []map[string]interface{}{}
err := x.Table(table.Name).Find(&entries)
if err != nil {
return nil, err
}
data[table.Name], err = json.Marshal(entries)
if err != nil {
return nil, err
}
}
return
}