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.

backup.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file.
  5. package sqlite3
  6. /*
  7. #ifndef USE_LIBSQLITE3
  8. #include <sqlite3-binding.h>
  9. #else
  10. #include <sqlite3.h>
  11. #endif
  12. #include <stdlib.h>
  13. */
  14. import "C"
  15. import (
  16. "runtime"
  17. "unsafe"
  18. )
  19. // SQLiteBackup implement interface of Backup.
  20. type SQLiteBackup struct {
  21. b *C.sqlite3_backup
  22. }
  23. // Backup make backup from src to dest.
  24. func (destConn *SQLiteConn) Backup(dest string, srcConn *SQLiteConn, src string) (*SQLiteBackup, error) {
  25. destptr := C.CString(dest)
  26. defer C.free(unsafe.Pointer(destptr))
  27. srcptr := C.CString(src)
  28. defer C.free(unsafe.Pointer(srcptr))
  29. if b := C.sqlite3_backup_init(destConn.db, destptr, srcConn.db, srcptr); b != nil {
  30. bb := &SQLiteBackup{b: b}
  31. runtime.SetFinalizer(bb, (*SQLiteBackup).Finish)
  32. return bb, nil
  33. }
  34. return nil, destConn.lastError()
  35. }
  36. // Step to backs up for one step. Calls the underlying `sqlite3_backup_step`
  37. // function. This function returns a boolean indicating if the backup is done
  38. // and an error signalling any other error. Done is returned if the underlying
  39. // C function returns SQLITE_DONE (Code 101)
  40. func (b *SQLiteBackup) Step(p int) (bool, error) {
  41. ret := C.sqlite3_backup_step(b.b, C.int(p))
  42. if ret == C.SQLITE_DONE {
  43. return true, nil
  44. } else if ret != 0 && ret != C.SQLITE_LOCKED && ret != C.SQLITE_BUSY {
  45. return false, Error{Code: ErrNo(ret)}
  46. }
  47. return false, nil
  48. }
  49. // Remaining return whether have the rest for backup.
  50. func (b *SQLiteBackup) Remaining() int {
  51. return int(C.sqlite3_backup_remaining(b.b))
  52. }
  53. // PageCount return count of pages.
  54. func (b *SQLiteBackup) PageCount() int {
  55. return int(C.sqlite3_backup_pagecount(b.b))
  56. }
  57. // Finish close backup.
  58. func (b *SQLiteBackup) Finish() error {
  59. return b.Close()
  60. }
  61. // Close close backup.
  62. func (b *SQLiteBackup) Close() error {
  63. ret := C.sqlite3_backup_finish(b.b)
  64. // sqlite3_backup_finish() never fails, it just returns the
  65. // error code from previous operations, so clean up before
  66. // checking and returning an error
  67. b.b = nil
  68. runtime.SetFinalizer(b, nil)
  69. if ret != 0 {
  70. return Error{Code: ErrNo(ret)}
  71. }
  72. return nil
  73. }