memory.go

25 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
package engines

import (
	"database/sql"
	"fmt"

	"congo.gg/pkg/database"
	_ "github.com/tursodatabase/go-libsql"
)

// NewMemory creates a new in-memory database.
// Useful for testing and development.
// Data is lost when the connection is closed.
func NewMemory() (*database.Database, error) {
	db, err := sql.Open("libsql", ":memory:")
	if err != nil {
		return nil, fmt.Errorf("open memory database: %w", err)
	}

	// Must use single connection — each connection to :memory: gets its own
	// empty database, so multiple connections would lose data.
	db.SetMaxOpenConns(1)

	return &database.Database{DB: db}, nil
}