go-sqlcipher/backup.go

75 lines
1.8 KiB
Go
Raw Permalink Normal View History

2014-08-18 11:56:31 +04:00
// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
2014-08-18 12:00:59 +04:00
2014-01-30 14:45:09 +04:00
package sqlite3
/*
#ifndef USE_LIBSQLITE3
#include <sqlite3-binding.h>
#else
#include <sqlite3.h>
#endif
2014-01-30 14:45:09 +04:00
#include <stdlib.h>
*/
import "C"
import (
"runtime"
2014-01-30 14:45:09 +04:00
"unsafe"
)
type SQLiteBackup struct {
2014-01-30 14:45:09 +04:00
b *C.sqlite3_backup
}
func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error) {
2014-01-30 14:45:09 +04:00
destptr := C.CString(dest)
defer C.free(unsafe.Pointer(destptr))
srcptr := C.CString(src)
defer C.free(unsafe.Pointer(srcptr))
if b := C.sqlite3_backup_init(c.db, destptr, conn.db, srcptr); b != nil {
bb := &SQLiteBackup{b: b}
runtime.SetFinalizer(bb, (*SQLiteBackup).Finish)
return bb, nil
2014-01-30 14:45:09 +04:00
}
return nil, c.lastError()
}
2014-07-11 18:31:28 +04:00
// Backs up for one step. Calls the underlying `sqlite3_backup_step` function.
// This function returns a boolean indicating if the backup is done and
// an error signalling any other error. Done is returned if the underlying C
// function returns SQLITE_DONE (Code 101)
func (b *SQLiteBackup) Step(p int) (bool, error) {
2014-05-27 05:35:20 +04:00
ret := C.sqlite3_backup_step(b.b, C.int(p))
2014-08-18 11:52:06 +04:00
if ret == C.SQLITE_DONE {
2014-07-11 18:31:28 +04:00
return true, nil
} else if ret != 0 && ret != C.SQLITE_LOCKED && ret != C.SQLITE_BUSY {
2014-07-11 18:31:28 +04:00
return false, Error{Code: ErrNo(ret)}
2014-05-27 05:35:20 +04:00
}
2014-07-11 18:31:28 +04:00
return false, nil
2014-01-30 14:45:09 +04:00
}
func (b *SQLiteBackup) Remaining() int {
2014-01-30 14:45:09 +04:00
return int(C.sqlite3_backup_remaining(b.b))
}
func (b *SQLiteBackup) PageCount() int {
2014-01-30 14:45:09 +04:00
return int(C.sqlite3_backup_pagecount(b.b))
}
func (b *SQLiteBackup) Finish() error {
return b.Close()
}
func (b *SQLiteBackup) Close() error {
2014-05-27 05:35:20 +04:00
ret := C.sqlite3_backup_finish(b.b)
if ret != 0 {
return Error{Code: ErrNo(ret)}
}
b.b = nil
runtime.SetFinalizer(b, nil)
2014-05-27 05:35:20 +04:00
return nil
2014-01-30 14:45:09 +04:00
}