9 Commits

Author SHA1 Message Date
24546a4ef5 Migrate the rest of everything from rowid to id 2024-10-25 16:37:37 +02:00
b89e27d5b4 Add primary keys to tables 2024-10-25 15:16:10 +02:00
cbee5bd204 Ensure only last rows are queried for search 2024-09-11 09:04:39 +02:00
ec5310a1f3 Embed spellfix.dll 2024-09-04 23:57:13 +02:00
ec1c196752 Fix issue with focusout preventing onclick from autocomplete 2024-08-15 22:09:13 +02:00
6064d9847c Improve the autocomplete UX a little 2024-08-15 18:17:08 +02:00
235a90b0a7 Replace os.exit with wails quit
Exit would prevent defers from running which meant db would be left
dangling
2024-08-15 02:47:32 +02:00
4abddac94f Make search a little more responseive, hopefully 2024-08-14 12:52:11 +02:00
f12c353905 Add spellfix.dll 2024-08-14 12:49:31 +02:00
9 changed files with 104 additions and 64 deletions

5
app.go
View File

@@ -2,7 +2,8 @@ package main
import ( import (
"context" "context"
"os"
"github.com/wailsapp/wails/v2/pkg/runtime"
) )
// App struct // App struct
@@ -139,5 +140,5 @@ func (a *App) SetSetting(key string, value int64) WailsGenericAck {
//region other //region other
func (a *App) Close() { func (a *App) Close() {
os.Exit(0) runtime.Quit(a.ctx)
} }

View File

@@ -1,6 +1,7 @@
begin; begin;
create table weight ( create table weight (
id integer primary key,
date datetime default (datetime('now', '+2 hours')), date datetime default (datetime('now', '+2 hours')),
weight real not null weight real not null
); );
@@ -18,7 +19,7 @@ drop view if exists weightMonthly;
drop view if exists weightYearly; drop view if exists weightYearly;
create view weightView as create view weightView as
select rowid, select id,
date, date,
round(weight, 2) as weight round(weight, 2) as weight
from weight from weight
@@ -53,6 +54,7 @@ group by strftime('%Y', date)
order by date desc; order by date desc;
create table food( create table food(
id integer primary key,
date datetime default (datetime('now', '+2 hours')), date datetime default (datetime('now', '+2 hours')),
food varchar not null, food varchar not null,
description varchar, description varchar,
@@ -150,7 +152,7 @@ drop view if exists foodYearly;
drop view if exists foodRecent; drop view if exists foodRecent;
create view foodView as create view foodView as
select rowid, select id,
date, date,
food, food,
description, description,
@@ -196,8 +198,7 @@ group by strftime('%Y', date)
order by date desc; order by date desc;
create view foodRecent as create view foodRecent as
select rowid, select *
*
from food from food
order by date desc order by date desc
limit 10; limit 10;
@@ -218,7 +219,7 @@ set per100 = coalesce(
limit 1 limit 1
) )
) )
where rowid = new.rowid; where id = new.id;
end; end;
create table settings( create table settings(

View File

@@ -11,7 +11,7 @@ type (
db *DB db *DB
} }
Food struct { Food struct {
Rowid int64 `json:"rowid"` Id int64 `json:"id"`
Date string `json:"date"` Date string `json:"date"`
Food string `json:"food"` Food string `json:"food"`
Descripton string `json:"description"` 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" const foodAggregatedColumns = "period, amount, avgPer100, energy"
func (s *FoodService) GetRecent() ([]Food, error) { func (s *FoodService) GetRecent() ([]Food, error) {
@@ -48,7 +48,7 @@ func (s *FoodService) GetRecent() ([]Food, error) {
for row.Next() { for row.Next() {
var food Food 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 { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -68,14 +68,15 @@ func (s *FoodService) GetLastPer100(name string) ([]FoodSearch, error) {
query := fmt.Sprintf(` query := fmt.Sprintf(`
with search_results as ( 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 from foodfix
inner join food f on f.food == word inner join food f on f.food == word
where word MATCH ? where word MATCH ?
) )
select %s, score select %s, score
from search_results from search_results
group by food where rn = 1
order by score asc, date desc order by score asc, date desc
limit %d limit %d
`, foodColumns, Settings.SearchLimit) `, foodColumns, Settings.SearchLimit)
@@ -88,7 +89,7 @@ limit %d
for rows.Next() { for rows.Next() {
var f FoodSearch 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 { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -128,20 +129,20 @@ func (s *FoodService) Create(food Food) (Food, error) {
} }
} }
rowid, err := res.LastInsertId() id, err := res.LastInsertId()
if err != nil { if err != nil {
return food, fmt.Errorf("error getting last insert id: %v", err) 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) { func (s *FoodService) Update(food Food) (Food, error) {
if s.db == nil || !s.db.Ready { if s.db == nil || !s.db.Ready {
return food, fmt.Errorf("cannot update food, db is nil or is not ready") return food, fmt.Errorf("cannot update food, db is nil or is not ready")
} }
if food.Rowid <= 0 { if food.Id <= 0 {
return food, fmt.Errorf("cannot update food, rowid is less than or equal to 0") return food, fmt.Errorf("cannot update food, id is less than or equal to 0")
} }
if food.Food == "" { if food.Food == "" {
return food, fmt.Errorf("cannot update food, food is empty") 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 { 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 { if err != nil {
return food, fmt.Errorf("error updating food: %v", err) return food, fmt.Errorf("error updating food: %v", err)
} }
} else { } 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 { if err != nil {
return food, fmt.Errorf("error updating food: %v", err) 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 var res Food
if s.db == nil || !s.db.Ready { 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) row := s.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from foodView WHERE id = ?", foodColumns), id)
err := row.Scan(&res.Rowid, &res.Date, &res.Food, &res.Descripton, &res.Amount, &res.Per100, &res.Energy) err := row.Scan(&res.Id, &res.Date, &res.Food, &res.Descripton, &res.Amount, &res.Per100, &res.Energy)
if err != nil { if err != nil {
return res, fmt.Errorf("error scanning row: %v", err) return res, fmt.Errorf("error scanning row: %v", err)
} }

View File

@@ -9,7 +9,7 @@
food: "", food: "",
amount: 0, amount: 0,
description: "", description: "",
rowid: 0, id: 0,
date: "", date: "",
per100: 0, per100: 0,
energy: 0, energy: 0,
@@ -30,9 +30,24 @@
name = name.trim(); name = name.trim();
if (!name) { if (!name) {
foodSearch = []; 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 }) { async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
name = name.trim(); name = name.trim();
amount = amount.trim(); amount = amount.trim();
@@ -69,17 +84,6 @@
nameElement.focus(); nameElement.focus();
foodSearch = []; 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; let hiLiteIndex: number | null = null;
@@ -101,7 +105,8 @@
// } // }
function setInputVal(food: main.Food) { function setInputVal(food: main.Food) {
name = food.food; name = food.food;
per100 = String(food.per100) per100 = String(food.per100);
amount = String(food.amount);
hiLiteIndex = null; hiLiteIndex = null;
foodSearch = []; foodSearch = [];
} }
@@ -113,6 +118,18 @@
autocompleteList.style.left = `${left}px`; autocompleteList.style.left = `${left}px`;
} }
} }
let timeout: number;
function handleFocusOut() {
timeout = setTimeout(() => {
foodSearch = [];
}, 100);
}
function handleFocusIn() {
clearTimeout(timeout);
updateAutocomplete();
}
</script> </script>
<!-- <svelte:window on:keydown={navigateList} /> --> <!-- <svelte:window on:keydown={navigateList} /> -->
@@ -132,6 +149,8 @@
contenteditable="true" contenteditable="true"
autofocus autofocus
on:keydown={update} on:keydown={update}
on:focusin={handleFocusIn}
on:focusout={handleFocusOut}
bind:this={nameElement} bind:this={nameElement}
/> />
<td <td
@@ -161,11 +180,7 @@
{#if foodSearch.length > 0} {#if foodSearch.length > 0}
<ul bind:this={autocompleteList} class="z-50 fixed top-0 left-0 w-3/12 border border-x-gray-800"> <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} {#each foodSearch as f, i}
<FoodSearchEntry <FoodSearchEntry itemLabel={f.food} highlighted={i == hiLiteIndex} on:click={() => setInputVal(f)} />
itemLabel={f.food}
highlighted={i == hiLiteIndex}
on:click={() => setInputVal(f)}
/>
{/each} {/each}
</ul> </ul>
{/if} {/if}

View File

@@ -6,7 +6,7 @@
let item: main.Weight = { let item: main.Weight = {
weight: 0, weight: 0,
rowid: 0, id: 0,
date: '' date: ''
} }
let weight: string | null = null let weight: string | null = null

View File

@@ -33,7 +33,7 @@ export namespace main {
} }
} }
export class Food { export class Food {
rowid: number; id: number;
date: string; date: string;
food: string; food: string;
description: string; description: string;
@@ -47,7 +47,7 @@ export namespace main {
constructor(source: any = {}) { constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source); if ('string' === typeof source) source = JSON.parse(source);
this.rowid = source["rowid"]; this.id = source["id"];
this.date = source["date"]; this.date = source["date"];
this.food = source["food"]; this.food = source["food"];
this.description = source["description"]; this.description = source["description"];
@@ -57,7 +57,7 @@ export namespace main {
} }
} }
export class FoodSearch { export class FoodSearch {
rowid: number; id: number;
date: string; date: string;
food: string; food: string;
description: string; description: string;
@@ -72,7 +72,7 @@ export namespace main {
constructor(source: any = {}) { constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source); if ('string' === typeof source) source = JSON.parse(source);
this.rowid = source["rowid"]; this.id = source["id"];
this.date = source["date"]; this.date = source["date"];
this.food = source["food"]; this.food = source["food"];
this.description = source["description"]; this.description = source["description"];
@@ -267,7 +267,7 @@ export namespace main {
} }
} }
export class Weight { export class Weight {
rowid: number; id: number;
date: string; date: string;
weight: number; weight: number;
@@ -277,7 +277,7 @@ export namespace main {
constructor(source: any = {}) { constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source); if ('string' === typeof source) source = JSON.parse(source);
this.rowid = source["rowid"]; this.id = source["id"];
this.date = source["date"]; this.date = source["date"];
this.weight = source["weight"]; this.weight = source["weight"];
} }

34
main.go
View File

@@ -24,7 +24,7 @@ func init() {
logFile, err := os.Create("main.log") logFile, err := os.Create("main.log")
if err != nil { if err != nil {
log.Printf("Error creating log file: %v", err) log.Printf("Error creating log file: %v", err)
os.Exit(1) return
} }
logger := io.MultiWriter(os.Stdout, logFile) logger := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(logger) log.SetOutput(logger)
@@ -42,37 +42,59 @@ var (
//go:embed food.ddl //go:embed food.ddl
var foodDDL string var foodDDL string
//go:embed spellfix.dll
var spellfixDll []byte
// TODO: Embed food.ddl and create DB if no exists // 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 // TODO: Add averages to graphs (ie. R2) https://stackoverflow.com/questions/60622195/how-to-draw-a-linear-regression-line-in-chart-js
func main() { 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") dbpath := flag.String("db", "food.db", "Path to the database file")
flag.Parse() flag.Parse()
db := DB{path: *dbpath} db := DB{path: *dbpath}
err := db.Open() err = db.Open()
if err != nil { if err != nil {
Error.Printf("%++v", err) Error.Printf("%++v", err)
os.Exit(1) return
} }
defer db.Close() defer db.Close()
err = db.Init(foodDDL) err = db.Init(foodDDL)
if err != nil { if err != nil {
Error.Printf("Error initializing database: %++v", err) Error.Printf("Error initializing database: %++v", err)
os.Exit(1) return
} }
settingsService = &SettingsService{db: &db} settingsService = &SettingsService{db: &db}
err = settingsService.LoadSettings() err = settingsService.LoadSettings()
if err != nil { if err != nil {
Error.Printf("%++v", err) Error.Printf("%++v", err)
os.Exit(1) return
} }
log.Printf("Loaded settings as: %++v", Settings) log.Printf("Loaded settings as: %++v", Settings)
foodService = &FoodService{db: &db} foodService = &FoodService{db: &db}
weightService = &WeightService{db: &db} weightService = &WeightService{db: &db}
// Create an instance of the app structure // Create an instance of the app structure
app := NewApp() app := NewApp()

BIN
spellfix.dll Normal file

Binary file not shown.

View File

@@ -10,7 +10,7 @@ type (
db *DB db *DB
} }
Weight struct { Weight struct {
Rowid int64 `json:"rowid"` Id int64 `json:"id"`
Date string `json:"date"` Date string `json:"date"`
Weight float32 `json:"weight"` Weight float32 `json:"weight"`
} }
@@ -20,7 +20,7 @@ type (
} }
) )
const weightcolumns = "rowid, date, weight" const weightcolumns = "id, date, weight"
const weightAggregatedColumns = "period, amount" const weightAggregatedColumns = "period, amount"
func (w *WeightService) GetRecent() ([]Weight, error) { func (w *WeightService) GetRecent() ([]Weight, error) {
@@ -37,7 +37,7 @@ func (w *WeightService) GetRecent() ([]Weight, error) {
for row.Next() { for row.Next() {
var weight Weight var weight Weight
err := row.Scan(&weight.Rowid, &weight.Date, &weight.Weight) err := row.Scan(&weight.Id, &weight.Date, &weight.Weight)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -62,22 +62,22 @@ func (w *WeightService) Create(weight Weight) (Weight, error) {
return weight, fmt.Errorf("error inserting weight: %v", err) return weight, fmt.Errorf("error inserting weight: %v", err)
} }
rowid, err := res.LastInsertId() id, err := res.LastInsertId()
if err != nil { if err != nil {
return weight, fmt.Errorf("error getting last insert id: %v", err) 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 var res Weight
if w.db == nil || !w.db.Ready { 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) row := w.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from weightView WHERE id = ?", weightcolumns), id)
err := row.Scan(&res.Rowid, &res.Date, &res.Weight) err := row.Scan(&res.Id, &res.Date, &res.Weight)
if err != nil { if err != nil {
return res, fmt.Errorf("error scanning row: %v", err) return res, fmt.Errorf("error scanning row: %v", err)
} }