Compare commits
11 Commits
2.0.0
...
24546a4ef5
| Author | SHA1 | Date | |
|---|---|---|---|
| 24546a4ef5 | |||
| b89e27d5b4 | |||
| cbee5bd204 | |||
| ec5310a1f3 | |||
| ec1c196752 | |||
| 6064d9847c | |||
| 235a90b0a7 | |||
| 4abddac94f | |||
| f12c353905 | |||
| 2586f0749f | |||
| 1387eecc96 |
5
app.go
5
app.go
@@ -2,7 +2,8 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// App struct
|
||||
@@ -139,5 +140,5 @@ func (a *App) SetSetting(key string, value int64) WailsGenericAck {
|
||||
|
||||
//region other
|
||||
func (a *App) Close() {
|
||||
os.Exit(0)
|
||||
runtime.Quit(a.ctx)
|
||||
}
|
||||
22
db.go
22
db.go
@@ -4,6 +4,7 @@ import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/mattn/go-sqlite3"
|
||||
@@ -21,6 +22,22 @@ func (db *DB) Open() error {
|
||||
return fmt.Errorf("database path not set")
|
||||
}
|
||||
|
||||
file, err := os.Open(db.path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
log.Printf("Database file does not exist at %s, creating", db.path)
|
||||
file, err := os.Create(db.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create database file: %v", err)
|
||||
}
|
||||
log.Printf("Database created at %s", db.path)
|
||||
file.Close()
|
||||
} else {
|
||||
return fmt.Errorf("failed to open database file: %v", err)
|
||||
}
|
||||
}
|
||||
file.Close()
|
||||
|
||||
sql.Register("spellfixlite", &sqlite3.SQLiteDriver{
|
||||
Extensions: []string{"spellfix"},
|
||||
})
|
||||
@@ -95,6 +112,11 @@ func (db *DB) Init(ddl string) error {
|
||||
_, err = db.writeConn.Exec(ddl)
|
||||
if err != nil {
|
||||
Error.Printf("%++v", err)
|
||||
log.Printf("%#v", "Rolling back")
|
||||
_, err2 := db.writeConn.Exec("ROLLBACK;")
|
||||
if err2 != nil {
|
||||
Error.Printf("Error rollingback! %++v", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
16
food.ddl
16
food.ddl
@@ -1,6 +1,7 @@
|
||||
begin transaction;
|
||||
begin;
|
||||
|
||||
create table weight (
|
||||
id integer primary key,
|
||||
date datetime default (datetime('now', '+2 hours')),
|
||||
weight real not null
|
||||
);
|
||||
@@ -18,7 +19,7 @@ drop view if exists weightMonthly;
|
||||
drop view if exists weightYearly;
|
||||
|
||||
create view weightView as
|
||||
select rowid,
|
||||
select id,
|
||||
date,
|
||||
round(weight, 2) as weight
|
||||
from weight
|
||||
@@ -53,6 +54,7 @@ group by strftime('%Y', date)
|
||||
order by date desc;
|
||||
|
||||
create table food(
|
||||
id integer primary key,
|
||||
date datetime default (datetime('now', '+2 hours')),
|
||||
food varchar not null,
|
||||
description varchar,
|
||||
@@ -124,7 +126,6 @@ where not exists (
|
||||
);
|
||||
end;
|
||||
|
||||
-- Spellfix search example
|
||||
with search_results as (
|
||||
select word, score, f.rowid, f.*
|
||||
from foodfix
|
||||
@@ -134,7 +135,7 @@ with search_results as (
|
||||
select rowid, food, score, date, description, amount, per100, energy
|
||||
from search_results
|
||||
group by food
|
||||
order by score asc, date desc
|
||||
order by score asc, date desc;
|
||||
|
||||
create index dailyIdx on food(strftime('%Y-%m-%d', date));
|
||||
create index weeklyIdx on food(strftime('%Y-%W', date));
|
||||
@@ -151,7 +152,7 @@ drop view if exists foodYearly;
|
||||
drop view if exists foodRecent;
|
||||
|
||||
create view foodView as
|
||||
select rowid,
|
||||
select id,
|
||||
date,
|
||||
food,
|
||||
description,
|
||||
@@ -197,8 +198,7 @@ group by strftime('%Y', date)
|
||||
order by date desc;
|
||||
|
||||
create view foodRecent as
|
||||
select rowid,
|
||||
*
|
||||
select *
|
||||
from food
|
||||
order by date desc
|
||||
limit 10;
|
||||
@@ -219,7 +219,7 @@ set per100 = coalesce(
|
||||
limit 1
|
||||
)
|
||||
)
|
||||
where rowid = new.rowid;
|
||||
where id = new.id;
|
||||
end;
|
||||
|
||||
create table settings(
|
||||
|
||||
@@ -11,7 +11,7 @@ type (
|
||||
db *DB
|
||||
}
|
||||
Food struct {
|
||||
Rowid int64 `json:"rowid"`
|
||||
Id int64 `json:"id"`
|
||||
Date string `json:"date"`
|
||||
Food string `json:"food"`
|
||||
Descripton string `json:"description"`
|
||||
@@ -31,7 +31,7 @@ type (
|
||||
}
|
||||
)
|
||||
|
||||
const foodColumns = "rowid, date, food, description, amount, per100, energy"
|
||||
const foodColumns = "id, date, food, description, amount, per100, energy"
|
||||
const foodAggregatedColumns = "period, amount, avgPer100, energy"
|
||||
|
||||
func (s *FoodService) GetRecent() ([]Food, error) {
|
||||
@@ -48,7 +48,7 @@ func (s *FoodService) GetRecent() ([]Food, error) {
|
||||
|
||||
for row.Next() {
|
||||
var food Food
|
||||
err := row.Scan(&food.Rowid, &food.Date, &food.Food, &food.Descripton, &food.Amount, &food.Per100, &food.Energy)
|
||||
err := row.Scan(&food.Id, &food.Date, &food.Food, &food.Descripton, &food.Amount, &food.Per100, &food.Energy)
|
||||
if err != nil {
|
||||
log.Printf("error scanning row: %v", err)
|
||||
continue
|
||||
@@ -68,14 +68,15 @@ func (s *FoodService) GetLastPer100(name string) ([]FoodSearch, error) {
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
with search_results as (
|
||||
select word, score, f.rowid, f.*
|
||||
select word, score, f.rowid, f.*,
|
||||
row_number() over (partition by f.food order by score asc, date desc) as rn
|
||||
from foodfix
|
||||
inner join food f on f.food == word
|
||||
where word MATCH ?
|
||||
)
|
||||
select %s, score
|
||||
from search_results
|
||||
group by food
|
||||
where rn = 1
|
||||
order by score asc, date desc
|
||||
limit %d
|
||||
`, foodColumns, Settings.SearchLimit)
|
||||
@@ -88,7 +89,7 @@ limit %d
|
||||
|
||||
for rows.Next() {
|
||||
var f FoodSearch
|
||||
err := rows.Scan(&f.Rowid, &f.Date, &f.Food.Food, &f.Descripton, &f.Amount, &f.Per100, &f.Energy, &f.Score)
|
||||
err := rows.Scan(&f.Id, &f.Date, &f.Food.Food, &f.Descripton, &f.Amount, &f.Per100, &f.Energy, &f.Score)
|
||||
if err != nil {
|
||||
log.Printf("error scanning row: %v", err)
|
||||
continue
|
||||
@@ -128,20 +129,20 @@ func (s *FoodService) Create(food Food) (Food, error) {
|
||||
}
|
||||
}
|
||||
|
||||
rowid, err := res.LastInsertId()
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return food, fmt.Errorf("error getting last insert id: %v", err)
|
||||
}
|
||||
|
||||
return s.GetByRowid(rowid)
|
||||
return s.GetById(id)
|
||||
}
|
||||
|
||||
func (s *FoodService) Update(food Food) (Food, error) {
|
||||
if s.db == nil || !s.db.Ready {
|
||||
return food, fmt.Errorf("cannot update food, db is nil or is not ready")
|
||||
}
|
||||
if food.Rowid <= 0 {
|
||||
return food, fmt.Errorf("cannot update food, rowid is less than or equal to 0")
|
||||
if food.Id <= 0 {
|
||||
return food, fmt.Errorf("cannot update food, id is less than or equal to 0")
|
||||
}
|
||||
if food.Food == "" {
|
||||
return food, fmt.Errorf("cannot update food, food is empty")
|
||||
@@ -151,28 +152,28 @@ func (s *FoodService) Update(food Food) (Food, error) {
|
||||
}
|
||||
|
||||
if food.Per100 > 0 {
|
||||
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ?, per100 = ? WHERE rowid = ?", food.Food, food.Descripton, food.Amount, food.Per100, food.Rowid)
|
||||
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ?, per100 = ? WHERE Id = ?", food.Food, food.Descripton, food.Amount, food.Per100, food.Id)
|
||||
if err != nil {
|
||||
return food, fmt.Errorf("error updating food: %v", err)
|
||||
}
|
||||
} else {
|
||||
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ? WHERE rowid = ?", food.Food, food.Descripton, food.Amount, food.Rowid)
|
||||
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ? WHERE Id = ?", food.Food, food.Descripton, food.Amount, food.Id)
|
||||
if err != nil {
|
||||
return food, fmt.Errorf("error updating food: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return s.GetByRowid(food.Rowid)
|
||||
return s.GetById(food.Id)
|
||||
}
|
||||
|
||||
func (s *FoodService) GetByRowid(rowid int64) (Food, error) {
|
||||
func (s *FoodService) GetById(id int64) (Food, error) {
|
||||
var res Food
|
||||
if s.db == nil || !s.db.Ready {
|
||||
return res, fmt.Errorf("cannot get food by rowid, db is nil or is not ready")
|
||||
return res, fmt.Errorf("cannot get food by id, db is nil or is not ready")
|
||||
}
|
||||
|
||||
row := s.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from foodView WHERE rowid = ?", foodColumns), rowid)
|
||||
err := row.Scan(&res.Rowid, &res.Date, &res.Food, &res.Descripton, &res.Amount, &res.Per100, &res.Energy)
|
||||
row := s.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from foodView WHERE id = ?", foodColumns), id)
|
||||
err := row.Scan(&res.Id, &res.Date, &res.Food, &res.Descripton, &res.Amount, &res.Per100, &res.Energy)
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("error scanning row: %v", err)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
food: "",
|
||||
amount: 0,
|
||||
description: "",
|
||||
rowid: 0,
|
||||
id: 0,
|
||||
date: "",
|
||||
per100: 0,
|
||||
energy: 0,
|
||||
@@ -30,9 +30,24 @@
|
||||
name = name.trim();
|
||||
if (!name) {
|
||||
foodSearch = [];
|
||||
} else {
|
||||
updateAutocomplete();
|
||||
}
|
||||
}
|
||||
|
||||
function updateAutocomplete() {
|
||||
if (!per100Edited)
|
||||
GetLastPer100(name.trim()).then((res) => {
|
||||
// Prevent search when there's nothing to search
|
||||
// Sometimes we get search results after deleting name
|
||||
if (res.success && res.data && name) {
|
||||
foodSearch = res.data;
|
||||
} else {
|
||||
foodSearch = [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
|
||||
name = name.trim();
|
||||
amount = amount.trim();
|
||||
@@ -69,17 +84,6 @@
|
||||
nameElement.focus();
|
||||
foodSearch = [];
|
||||
}
|
||||
|
||||
if (!per100Edited)
|
||||
GetLastPer100(name.trim()).then((res) => {
|
||||
// Prevent search when there's nothing to search
|
||||
// Sometimes we get search results after deleting name
|
||||
if (res.success && res.data && name) {
|
||||
foodSearch = res.data;
|
||||
} else {
|
||||
foodSearch = [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let hiLiteIndex: number | null = null;
|
||||
@@ -99,8 +103,10 @@
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
function setInputVal(val: string) {
|
||||
name = val;
|
||||
function setInputVal(food: main.Food) {
|
||||
name = food.food;
|
||||
per100 = String(food.per100);
|
||||
amount = String(food.amount);
|
||||
hiLiteIndex = null;
|
||||
foodSearch = [];
|
||||
}
|
||||
@@ -112,6 +118,18 @@
|
||||
autocompleteList.style.left = `${left}px`;
|
||||
}
|
||||
}
|
||||
|
||||
let timeout: number;
|
||||
function handleFocusOut() {
|
||||
timeout = setTimeout(() => {
|
||||
foodSearch = [];
|
||||
}, 100);
|
||||
}
|
||||
|
||||
function handleFocusIn() {
|
||||
clearTimeout(timeout);
|
||||
updateAutocomplete();
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- <svelte:window on:keydown={navigateList} /> -->
|
||||
@@ -131,6 +149,8 @@
|
||||
contenteditable="true"
|
||||
autofocus
|
||||
on:keydown={update}
|
||||
on:focusin={handleFocusIn}
|
||||
on:focusout={handleFocusOut}
|
||||
bind:this={nameElement}
|
||||
/>
|
||||
<td
|
||||
@@ -160,11 +180,7 @@
|
||||
{#if foodSearch.length > 0}
|
||||
<ul bind:this={autocompleteList} class="z-50 fixed top-0 left-0 w-3/12 border border-x-gray-800">
|
||||
{#each foodSearch as f, i}
|
||||
<FoodSearchEntry
|
||||
itemLabel={f.food}
|
||||
highlighted={i == hiLiteIndex}
|
||||
on:click={() => setInputVal(f.food)}
|
||||
/>
|
||||
<FoodSearchEntry itemLabel={f.food} highlighted={i == hiLiteIndex} on:click={() => setInputVal(f)} />
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
let item: main.Weight = {
|
||||
weight: 0,
|
||||
rowid: 0,
|
||||
id: 0,
|
||||
date: ''
|
||||
}
|
||||
let weight: string | null = null
|
||||
|
||||
@@ -33,7 +33,7 @@ export namespace main {
|
||||
}
|
||||
}
|
||||
export class Food {
|
||||
rowid: number;
|
||||
id: number;
|
||||
date: string;
|
||||
food: string;
|
||||
description: string;
|
||||
@@ -47,7 +47,7 @@ export namespace main {
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.rowid = source["rowid"];
|
||||
this.id = source["id"];
|
||||
this.date = source["date"];
|
||||
this.food = source["food"];
|
||||
this.description = source["description"];
|
||||
@@ -57,7 +57,7 @@ export namespace main {
|
||||
}
|
||||
}
|
||||
export class FoodSearch {
|
||||
rowid: number;
|
||||
id: number;
|
||||
date: string;
|
||||
food: string;
|
||||
description: string;
|
||||
@@ -72,7 +72,7 @@ export namespace main {
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.rowid = source["rowid"];
|
||||
this.id = source["id"];
|
||||
this.date = source["date"];
|
||||
this.food = source["food"];
|
||||
this.description = source["description"];
|
||||
@@ -267,7 +267,7 @@ export namespace main {
|
||||
}
|
||||
}
|
||||
export class Weight {
|
||||
rowid: number;
|
||||
id: number;
|
||||
date: string;
|
||||
weight: number;
|
||||
|
||||
@@ -277,7 +277,7 @@ export namespace main {
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.rowid = source["rowid"];
|
||||
this.id = source["id"];
|
||||
this.date = source["date"];
|
||||
this.weight = source["weight"];
|
||||
}
|
||||
|
||||
38
main.go
38
main.go
@@ -24,7 +24,7 @@ func init() {
|
||||
logFile, err := os.Create("main.log")
|
||||
if err != nil {
|
||||
log.Printf("Error creating log file: %v", err)
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
logger := io.MultiWriter(os.Stdout, logFile)
|
||||
log.SetOutput(logger)
|
||||
@@ -42,33 +42,59 @@ var (
|
||||
|
||||
//go:embed food.ddl
|
||||
var foodDDL string
|
||||
//go:embed spellfix.dll
|
||||
var spellfixDll []byte
|
||||
|
||||
// TODO: Embed food.ddl and create DB if no exists
|
||||
// TODO: Add averages to graphs (ie. R2) https://stackoverflow.com/questions/60622195/how-to-draw-a-linear-regression-line-in-chart-js
|
||||
func main() {
|
||||
_, err := os.Open("spellfix.dll")
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
Error.Printf("Error looking for spellfix.dll: %v", err)
|
||||
return
|
||||
}
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
log.Printf("No spellfix.dll found, creating...")
|
||||
file, err := os.Create("spellfix.dll")
|
||||
if err != nil {
|
||||
Error.Printf("Error creating spellfix.dll: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = file.Write(spellfixDll)
|
||||
if err != nil {
|
||||
Error.Printf("Error writing spellfix.dll: %v", err)
|
||||
return
|
||||
}
|
||||
file.Close()
|
||||
}
|
||||
|
||||
dbpath := flag.String("db", "food.db", "Path to the database file")
|
||||
flag.Parse()
|
||||
|
||||
db := DB{path: *dbpath}
|
||||
err := db.Open()
|
||||
err = db.Open()
|
||||
if err != nil {
|
||||
Error.Printf("%++v", err)
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
defer db.Close()
|
||||
db.Init(foodDDL)
|
||||
err = db.Init(foodDDL)
|
||||
if err != nil {
|
||||
Error.Printf("Error initializing database: %++v", err)
|
||||
return
|
||||
}
|
||||
|
||||
settingsService = &SettingsService{db: &db}
|
||||
err = settingsService.LoadSettings()
|
||||
if err != nil {
|
||||
Error.Printf("%++v", err)
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
log.Printf("Loaded settings as: %++v", Settings)
|
||||
|
||||
foodService = &FoodService{db: &db}
|
||||
weightService = &WeightService{db: &db}
|
||||
|
||||
|
||||
// Create an instance of the app structure
|
||||
app := NewApp()
|
||||
|
||||
|
||||
BIN
spellfix.dll
Normal file
BIN
spellfix.dll
Normal file
Binary file not shown.
@@ -10,7 +10,7 @@ type (
|
||||
db *DB
|
||||
}
|
||||
Weight struct {
|
||||
Rowid int64 `json:"rowid"`
|
||||
Id int64 `json:"id"`
|
||||
Date string `json:"date"`
|
||||
Weight float32 `json:"weight"`
|
||||
}
|
||||
@@ -20,7 +20,7 @@ type (
|
||||
}
|
||||
)
|
||||
|
||||
const weightcolumns = "rowid, date, weight"
|
||||
const weightcolumns = "id, date, weight"
|
||||
const weightAggregatedColumns = "period, amount"
|
||||
|
||||
func (w *WeightService) GetRecent() ([]Weight, error) {
|
||||
@@ -37,7 +37,7 @@ func (w *WeightService) GetRecent() ([]Weight, error) {
|
||||
|
||||
for row.Next() {
|
||||
var weight Weight
|
||||
err := row.Scan(&weight.Rowid, &weight.Date, &weight.Weight)
|
||||
err := row.Scan(&weight.Id, &weight.Date, &weight.Weight)
|
||||
if err != nil {
|
||||
log.Printf("error scanning row: %v", err)
|
||||
continue
|
||||
@@ -62,22 +62,22 @@ func (w *WeightService) Create(weight Weight) (Weight, error) {
|
||||
return weight, fmt.Errorf("error inserting weight: %v", err)
|
||||
}
|
||||
|
||||
rowid, err := res.LastInsertId()
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return weight, fmt.Errorf("error getting last insert id: %v", err)
|
||||
}
|
||||
|
||||
return w.GetByRowid(rowid)
|
||||
return w.GetById(id)
|
||||
}
|
||||
|
||||
func (w *WeightService) GetByRowid(rowid int64) (Weight, error) {
|
||||
func (w *WeightService) GetById(id int64) (Weight, error) {
|
||||
var res Weight
|
||||
if w.db == nil || !w.db.Ready {
|
||||
return res, fmt.Errorf("cannot get weight by rowid, db is nil or is not ready")
|
||||
return res, fmt.Errorf("cannot get weight by id, db is nil or is not ready")
|
||||
}
|
||||
|
||||
row := w.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from weightView WHERE rowid = ?", weightcolumns), rowid)
|
||||
err := row.Scan(&res.Rowid, &res.Date, &res.Weight)
|
||||
row := w.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from weightView WHERE id = ?", weightcolumns), id)
|
||||
err := row.Scan(&res.Id, &res.Date, &res.Weight)
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("error scanning row: %v", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user