github.com/ncruces/go-sqlite3@v0.15.1-0.20240520133447-53eef1510ff0/vfs/memdb/api.go (about) 1 // Package memdb implements the "memdb" SQLite VFS. 2 // 3 // The "memdb" [vfs.VFS] allows the same in-memory database to be shared 4 // among multiple database connections in the same process, 5 // as long as the database name begins with "/". 6 // 7 // Importing package memdb registers the VFS: 8 // 9 // import _ "github.com/ncruces/go-sqlite3/vfs/memdb" 10 package memdb 11 12 import ( 13 "sync" 14 15 "github.com/ncruces/go-sqlite3/vfs" 16 ) 17 18 func init() { 19 vfs.Register("memdb", memVFS{}) 20 } 21 22 var ( 23 memoryMtx sync.Mutex 24 // +checklocks:memoryMtx 25 memoryDBs = map[string]*memDB{} 26 ) 27 28 // Create creates a shared memory database, 29 // using data as its initial contents. 30 // The new database takes ownership of data, 31 // and the caller should not use data after this call. 32 func Create(name string, data []byte) { 33 memoryMtx.Lock() 34 defer memoryMtx.Unlock() 35 36 db := &memDB{ 37 refs: 1, 38 name: name, 39 size: int64(len(data)), 40 } 41 42 // Convert data from WAL to rollback journal. 43 if len(data) >= 20 && data[18] == 2 && data[19] == 2 { 44 data[18] = 1 45 data[19] = 1 46 } 47 48 sectors := divRoundUp(db.size, sectorSize) 49 db.data = make([]*[sectorSize]byte, sectors) 50 for i := range db.data { 51 sector := data[i*sectorSize:] 52 if len(sector) >= sectorSize { 53 db.data[i] = (*[sectorSize]byte)(sector) 54 } else { 55 db.data[i] = new([sectorSize]byte) 56 copy((*db.data[i])[:], sector) 57 } 58 } 59 60 memoryDBs[name] = db 61 } 62 63 // Delete deletes a shared memory database. 64 func Delete(name string) { 65 memoryMtx.Lock() 66 defer memoryMtx.Unlock() 67 delete(memoryDBs, name) 68 }