github.com/cayleygraph/cayley@v0.7.7/cmd/cayley/command/dump.go (about) 1 package command 2 3 import ( 4 "compress/gzip" 5 "fmt" 6 "io" 7 "os" 8 "path/filepath" 9 "strings" 10 11 "github.com/cayleygraph/cayley/clog" 12 "github.com/cayleygraph/cayley/graph" 13 "github.com/cayleygraph/quad" 14 ) 15 16 func writerQuadsTo(path string, typ string, qr quad.Reader) error { 17 var f *os.File 18 if path == "-" { 19 f = os.Stdout 20 clog.Infof("writing quads to stdout") 21 } else { 22 var err error 23 f, err = os.Create(path) 24 if err != nil { 25 return fmt.Errorf("could not create file %q: %v", path, err) 26 } 27 defer f.Close() 28 fmt.Printf("writing quads to file %q\n", path) 29 } 30 31 var w io.Writer = f 32 ext := filepath.Ext(path) 33 if ext == ".gz" { 34 ext = filepath.Ext(strings.TrimSuffix(path, ext)) 35 gzip := gzip.NewWriter(f) 36 defer gzip.Close() 37 w = gzip 38 } 39 var format *quad.Format 40 if typ == "" { 41 format = quad.FormatByExt(ext) 42 if format == nil { 43 typ = "nquads" 44 } 45 } 46 if format == nil { 47 format = quad.FormatByName(typ) 48 } 49 if format == nil { 50 return fmt.Errorf("unsupported format: %q", typ) 51 } else if format.Writer == nil { 52 return fmt.Errorf("encoding in %s format is not supported", typ) 53 } 54 qw := format.Writer(w) 55 defer qw.Close() 56 57 n, err := quad.Copy(qw, qr) 58 if err != nil { 59 return err 60 } else if err = qw.Close(); err != nil { 61 return err 62 } 63 if path != "-" { 64 fmt.Printf("%d entries were written\n", n) 65 } 66 return nil 67 } 68 69 func dumpDatabase(h *graph.Handle, path string, typ string) error { 70 //TODO: add possible support for exporting specific queries only 71 qr := graph.NewQuadStoreReader(h.QuadStore) 72 defer qr.Close() 73 return writerQuadsTo(path, typ, qr) 74 }