You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.6 KiB
71 lines
1.6 KiB
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
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
|
|
}
|