Files
sqlite3/vfs/memdb/api.go

60 lines
1.3 KiB
Go
Raw Normal View History

2023-06-01 18:11:37 +01:00
// Package memdb implements the "memdb" SQLite VFS.
2023-05-31 15:47:28 +01:00
//
2023-06-01 18:11:37 +01:00
// The "memdb" [vfs.VFS] allows the same in-memory database to be shared
2023-05-31 15:47:28 +01:00
// among multiple database connections in the same process,
// as long as the database name begins with "/".
//
2023-06-01 18:11:37 +01:00
// Importing package memdb registers the VFS.
2023-05-31 15:47:28 +01:00
//
2023-06-01 18:11:37 +01:00
// import _ "github.com/ncruces/go-sqlite3/vfs/memdb"
package memdb
2023-05-31 15:47:28 +01:00
import (
"sync"
2023-06-01 18:11:37 +01:00
"github.com/ncruces/go-sqlite3/vfs"
2023-05-31 15:47:28 +01:00
)
func init() {
2023-06-01 18:11:37 +01:00
vfs.Register("memdb", memVFS{})
2023-05-31 15:47:28 +01:00
}
var (
memoryMtx sync.Mutex
2023-06-02 03:32:13 +01:00
// +checklocks:memoryMtx
2023-06-01 18:11:37 +01:00
memoryDBs = map[string]*memDB{}
2023-05-31 15:47:28 +01:00
)
// Create creates a shared memory database,
// using data as its initial contents.
// The new database takes ownership of data,
// and the caller should not use data after this call.
func Create(name string, data []byte) {
memoryMtx.Lock()
defer memoryMtx.Unlock()
2023-06-01 18:11:37 +01:00
db := new(memDB)
2023-05-31 15:47:28 +01:00
db.size = int64(len(data))
sectors := divRoundUp(db.size, sectorSize)
db.data = make([]*[sectorSize]byte, sectors)
for i := range db.data {
sector := data[i*sectorSize:]
if len(sector) >= sectorSize {
db.data[i] = (*[sectorSize]byte)(sector)
} else {
db.data[i] = new([sectorSize]byte)
copy((*db.data[i])[:], sector)
}
}
memoryDBs[name] = db
}
// Delete deletes a shared memory database.
func Delete(name string) {
memoryMtx.Lock()
defer memoryMtx.Unlock()
delete(memoryDBs, name)
}