Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package sqlite
// #include <stdlib.h>
import "C"
import (
"fmt"
"runtime"
"unsafe"
)
Expand Down Expand Up @@ -131,3 +132,23 @@ func (b *Backup) Remaining() int {
func (b *Backup) PageCount() int {
return int(C.sqlite3_backup_pagecount(b.ptr))
}

// Serialize returns a byte slice containing the complete contents of the
// named database (use "" or "main" for the main database). The returned
// slice is a Go-owned copy; the caller may use it freely.
//
// https://www.sqlite.org/c3ref/serialize.html
func (c *Conn) Serialize(dbName string) ([]byte, error) {
cname := cmain
if dbName != "" && dbName != "main" {
cname = C.CString(dbName)
defer C.free(unsafe.Pointer(cname))
}
var size C.sqlite3_int64
p := C.sqlite3_serialize(c.conn, cname, &size, 0)
if p == nil {
return nil, fmt.Errorf("sqlite.Conn.Serialize: out of memory or unsupported")
}
defer C.sqlite3_free(unsafe.Pointer(p))
return C.GoBytes(unsafe.Pointer(p), C.int(size)), nil
}
36 changes: 36 additions & 0 deletions backup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package sqlite_test

import (
"os"
"testing"

"github.com/go-llsqlite/crawshaw"
Expand All @@ -35,6 +36,41 @@ func initSrc(t *testing.T) *sqlite.Conn {
return conn
}

func TestSerialize(t *testing.T) {
conn := initSrc(t)
defer conn.Close()

data, err := conn.Serialize("")
if err != nil {
t.Fatal(err)
}

f, err := os.CreateTemp("", "serialize-test-*.sqlite3")
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
t.Fatal(err)
}
f.Close()

conn2, err := sqlite.OpenConn(f.Name(), 0)
if err != nil {
t.Fatal(err)
}
defer conn2.Close()

count, err := sqlitex.ResultInt(conn2.Prep(`SELECT count(*) FROM t;`))
if err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatalf("expected 2 rows in serialized DB, got %d", count)
}
}

func TestBackup(t *testing.T) {
conn := initSrc(t)
defer conn.Close()
Expand Down
Loading