package mysqlite

import (
	"fmt"
	"zombiezen.com/go/sqlite"
)

// Db holds a connection to a SQLite database.
type Db struct {
	Db *sqlite.Conn
}

// OpenDb opens a new connection to a SQLite database.
// The databaseSource specifies the database to use. Set it to `:memory:` to use
// an in-memory database.
// Any database that was successfully opened should afterwards be closed using Db.Close
func OpenDb(databaseSource string) (*Db, error) {
	conn, err := sqlite.OpenConn(databaseSource)
	if err != nil {
		return nil, err
	}
	return &Db{Db: conn}, nil
}

// Close closes the database.
func (d *Db) Close() error {
	return d.Db.Close()
}

// MustClose closes the database. If an error occurs, it panics instead of
// returning the error.
func (d *Db) MustClose() {
	err := d.Close()
	if err != nil {
		panic(fmt.Sprintf("error closing db: %v", err))
	}
}