PackageManager just because
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
2.0 KiB

  1. package Database
  2. import (
  3. "database/sql"
  4. "time"
  5. )
  6. type FilesystemHashRow struct {
  7. Path string
  8. Hash string
  9. UpdatedAt time.Time
  10. }
  11. func FindOrCreateFileHash(rows []FilesystemHashRow) error {
  12. var (
  13. stmtString string
  14. stmt *sql.Stmt
  15. values []interface{} = []interface{}{}
  16. e error
  17. )
  18. stmtString = "INSERT OR REPLACE INTO filesystem_hash (id, path, hash, updated_at) VALUES "
  19. for _, row := range rows {
  20. stmtString += `(
  21. (SELECT id FROM filesystem_hash WHERE path = ?),
  22. ?,
  23. ?,
  24. ?
  25. ),`
  26. values = append(values, row.Path, row.Path, row.Hash, row.UpdatedAt.Unix())
  27. }
  28. stmtString = stmtString[0 : len(stmtString)-1]
  29. stmt, e = DB.Prepare(stmtString)
  30. if e != nil {
  31. return e
  32. }
  33. _, e = stmt.Exec(values...)
  34. return e
  35. }
  36. func FindModifiedFiles(hashes []string) (map[int]string, error) {
  37. var (
  38. stmtString string
  39. stmt *sql.Stmt
  40. values []interface{} = []interface{}{}
  41. result *sql.Rows
  42. dirtyFiles map[int]string = make(map[int]string)
  43. counter int = 0
  44. e error
  45. )
  46. stmtString = "SELECT id, path FROM filesystem_hash WHERE hash NOT IN ("
  47. for _, row := range hashes {
  48. stmtString += "?,"
  49. values = append(values, row)
  50. }
  51. stmtString = stmtString[0:len(stmtString)-1] + ")"
  52. stmt, e = DB.Prepare(stmtString)
  53. if e != nil {
  54. return dirtyFiles, e
  55. }
  56. result, e = stmt.Query(values...)
  57. if e != nil {
  58. return dirtyFiles, e
  59. }
  60. defer result.Close()
  61. for result.Next() {
  62. var id string
  63. var path string
  64. e = result.Scan(&id, &path)
  65. if e != nil {
  66. return dirtyFiles, e
  67. }
  68. dirtyFiles[counter] = path
  69. counter++
  70. }
  71. e = result.Err()
  72. return dirtyFiles, e
  73. }
  74. func GetMostRecentTimestamp() (time.Time, error) {
  75. var (
  76. stmt *sql.Stmt
  77. result *sql.Row
  78. lastUpdatedAt int64
  79. e error
  80. )
  81. stmt, e = DB.Prepare(`
  82. SELECT updated_at FROM filesystem_hash
  83. ORDER BY updated_at DESC
  84. LIMIT 1;
  85. `)
  86. if e != nil {
  87. return time.Now(), e
  88. }
  89. result = stmt.QueryRow()
  90. result.Scan(&lastUpdatedAt)
  91. return time.Unix(lastUpdatedAt, 0), nil
  92. }