export_content.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "code.osinet.fr/fgm/kurz/infrastructure"
  4. "database/sql"
  5. "fmt"
  6. "github.com/spf13/cobra"
  7. "gopkg.in/yaml.v2"
  8. "time"
  9. )
  10. type MapEntry struct {
  11. Hash uint64
  12. Url string
  13. Date1, Date2, Date3 time.Time
  14. RefCount uint32
  15. }
  16. var cmdExportContent = &cobra.Command{
  17. Use: "content",
  18. Short: "Export the database contents",
  19. Long: "Export the whole list of Kurz URLs in the database",
  20. Run: exportContentHandler,
  21. }
  22. func init() {
  23. cmdExport.AddCommand(cmdExportContent)
  24. }
  25. func exportContentLoader(db *sql.DB) ([]MapEntry, error) {
  26. stmt, err := db.Prepare(`
  27. SELECT Hash, url, Date1, Date2, Date3, RefCount
  28. FROM map
  29. ORDER BY url`)
  30. if err != nil {
  31. panic(err.Error())
  32. }
  33. defer stmt.Close()
  34. rows, err := stmt.Query()
  35. if err != nil {
  36. return nil, err
  37. }
  38. defer rows.Close()
  39. entry := MapEntry{}
  40. var entries []MapEntry
  41. for rows.Next() {
  42. err = rows.Scan(&entry.Hash, &entry.Url, &entry.Date1, &entry.Date2, &entry.Date3, &entry.RefCount)
  43. if err != nil {
  44. return nil, err
  45. }
  46. entries = append(entries, entry)
  47. }
  48. return entries, nil
  49. }
  50. func exportContentHandler(cmd *cobra.Command, args []string) {
  51. dbDriver, dbDsn := infrastructure.ParseDbCred()
  52. db, err := infrastructure.DbDial(dbDriver, dbDsn)
  53. if err != nil {
  54. panic(err)
  55. }
  56. defer db.Close()
  57. entries, err := exportContentLoader(db)
  58. if err != nil {
  59. panic(err.Error())
  60. }
  61. y, err := yaml.Marshal(&entries)
  62. if err != nil {
  63. panic(err.Error())
  64. }
  65. fmt.Println(string(y))
  66. }