package main import ( "context" "database/sql" "errors" "fmt" _ "github.com/mattn/go-sqlite3" "log" "os" "path" ) var __version = 1 type LogCtx struct { db *sql.DB version int } func Init(db_location string) (*LogCtx, error) { db, err := sql.Open("sqlite3", db_location) if err != nil { return nil, fmt.Errorf("Could not connect to DB. %w", err) } if err := db.Ping(); err != nil { return nil, fmt.Errorf("Could not ping DB. %w", err) } ctx := context.Background() tx, err := db.BeginTx(ctx, nil) if err != nil { return nil, err } // Optionally add the version table if _, err := tx.Exec(` create table if not exists eng_log_version (id integer not null); `); err != nil { tx.Rollback() return nil, fmt.Errorf("Could not create eng_log_version. %w", err) } // Optionally add the log table if _, err := tx.Exec(` create table if not exists log (id integer not null primary key, title string) `); err != nil { tx.Rollback() return nil, fmt.Errorf("Could not create log. %w", err) } var version int // Check the version if err := tx.QueryRow("SELECT IFNULL((SELECT id FROM eng_log_version LIMIT 1), 0)").Scan(&version); err != nil { tx.Rollback() return nil, fmt.Errorf("Could not query for eng_log_version id. %w", err) } if version == 0 { _, err := tx.Exec("INSERT INTO eng_log_version (id) VALUES (?)", __version) if err != nil { tx.Rollback() return nil, fmt.Errorf("Could not insert log-version. %w", err) } version = __version } else if version != __version { tx.Rollback() return nil, errors.New(fmt.Sprintf("Wrong version. Expected %d got %d", __version, version)) } tx.Commit() return &LogCtx{db, version}, nil } func (db *LogCtx) AddEntry(title string) int { return 1 } func main() { home_dir, err := os.UserHomeDir() if err != nil { log.Fatal(err.Error()) } var db_path = path.Join(home_dir, ".dev-log.sql") if _, err := os.Stat(db_path); errors.Is(err, os.ErrNotExist) { _, err := os.Create(db_path) if err != nil { log.Fatal(err.Error()) } } _, err = Init(db_path) if err != nil { log.Fatal(err.Error()) } }