auto.go

57 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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
package engines

import (
	"log"
	"os"
	"time"

	"congo.gg/pkg/database"
)

// NewAuto creates a database based on environment variables:
//
//   - DB_URL + DB_TOKEN: Remote libSQL replica (syncs with Turso/libSQL server)
//   - DB_PATH: Local file-based SQLite database
//   - Neither: In-memory database (for development/testing)
//
// When using remote mode, DB_PATH can optionally specify the local replica path.
// If not set, it defaults to "/data/replica.db".
//
// Fatal if the configured mode fails. Memory mode cannot fail.
func NewAuto() *database.Database {
	dbURL := os.Getenv("DB_URL")
	dbToken := os.Getenv("DB_TOKEN")
	dbPath := os.Getenv("DB_PATH")

	// Remote mode: DB_URL and DB_TOKEN are set
	if dbURL != "" && dbToken != "" {
		replicaPath := dbPath
		if replicaPath == "" {
			replicaPath = "/data/replica.db"
		}
		log.Printf("database: using remote replica (url=%s, replica=%s)", dbURL, replicaPath)
		db, err := NewRemote(replicaPath, dbURL, dbToken, WithSyncInterval(time.Minute))
		if err != nil {
			log.Fatal("database: ", err)
		}
		return db
	}

	// Local file mode: DB_PATH is set
	if dbPath != "" {
		log.Printf("database: using local file (%s)", dbPath)
		db, err := NewLocal(dbPath)
		if err != nil {
			log.Fatal("database: ", err)
		}
		return db
	}

	// Memory mode: no env vars set
	log.Println("database: using in-memory (no DB_URL or DB_PATH set)")
	db, err := NewMemory()
	if err != nil {
		log.Fatal("database: ", err)
	}
	return db
}