Skip to content

Commit

Permalink
sqlite3_opt_serialize: fix 'go vet' warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
charlievieth committed Nov 9, 2024
1 parent 71019cd commit 71665d6
Showing 1 changed file with 20 additions and 34 deletions.
54 changes: 20 additions & 34 deletions sqlite3_opt_serialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,19 @@

package sqlite3

/*
#ifndef USE_LIBSQLITE3
#include <sqlite3-binding.h>
#else
#include <sqlite3.h>
#endif
#include <stdlib.h>
#include <stdint.h>
*/
// #ifndef USE_LIBSQLITE3
// #include <sqlite3-binding.h>
// #else
// #include <sqlite3.h>
// #endif /* USE_LIBSQLITE3 */
// #include <stdlib.h>
// #include <stdint.h>
import "C"

import (
"errors"
"fmt"
"math"
"reflect"
"unsafe"
)

Expand All @@ -28,29 +26,23 @@ func (c *SQLiteConn) Serialize(schema string) ([]byte, error) {
if schema == "" {
schema = "main"
}
var zSchema *C.char
zSchema = C.CString(schema)
zSchema := C.CString(schema)
defer C.free(unsafe.Pointer(zSchema))

var sz C.sqlite3_int64
ptr := C.sqlite3_serialize(c.db, zSchema, &sz, 0)
if ptr == nil {
return nil, fmt.Errorf("serialize failed")
return nil, errors.New(`sqlite3: failed to serialize: "` + schema + `"`)
}
defer C.sqlite3_free(unsafe.Pointer(ptr))

if sz > C.sqlite3_int64(math.MaxInt) {
return nil, fmt.Errorf("serialized database is too large (%d bytes)", sz)
if int64(sz) > math.MaxInt {
return nil, fmt.Errorf("sqlite3: serialized database is too large (%d bytes)", int64(sz))
}

cBuf := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(ptr)),
Len: int(sz),
Cap: int(sz),
}))

res := make([]byte, int(sz))
copy(res, cBuf)
buf := unsafe.Slice((*byte)(unsafe.Pointer(ptr)), sz)
res := make([]byte, len(buf))
copy(res, buf)
return res, nil
}

Expand All @@ -62,19 +54,13 @@ func (c *SQLiteConn) Deserialize(b []byte, schema string) error {
if schema == "" {
schema = "main"
}
var zSchema *C.char
zSchema = C.CString(schema)
zSchema := C.CString(schema)
defer C.free(unsafe.Pointer(zSchema))

tmpBuf := (*C.uchar)(C.sqlite3_malloc64(C.sqlite3_uint64(len(b))))
cBuf := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(tmpBuf)),
Len: len(b),
Cap: len(b),
}))
copy(cBuf, b)

rc := C.sqlite3_deserialize(c.db, zSchema, tmpBuf, C.sqlite3_int64(len(b)),
tmp := (*C.uchar)(C.sqlite3_malloc64(C.sqlite3_uint64(len(b))))
buf := unsafe.Slice((*byte)(unsafe.Pointer(tmp)), len(b))
copy(buf, b)
rc := C.sqlite3_deserialize(c.db, zSchema, tmp, C.sqlite3_int64(len(b)),
C.sqlite3_int64(len(b)), C.SQLITE_DESERIALIZE_FREEONCLOSE)
if rc != C.SQLITE_OK {
return fmt.Errorf("deserialize failed with return %v", rc)
Expand Down

0 comments on commit 71665d6

Please sign in to comment.