readysite / pkg / database / engines / auto.go
1.5 KB
auto.go
package engines

import (
	"log"
	"os"
	"time"

	"github.com/readysite/readysite/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".
//
// Example environment configurations:
//
//	# Remote (production with Turso)
//	DB_URL=libsql://mydb.turso.io
//	DB_TOKEN=eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9...
//	DB_PATH=/data/replica.db  # optional, defaults to /data/replica.db
//
//	# Local file (development)
//	DB_PATH=/data/app.db
//
//	# Memory (testing) - no env vars needed
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)
		return NewRemote(replicaPath, dbURL, dbToken, WithSyncInterval(time.Minute))
	}

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

	// Memory mode: no env vars set
	log.Println("database: using in-memory (no DB_URL or DB_PATH set)")
	return NewMemory()
}
← Back