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 (
"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)
}

View File

@@ -1,6 +1,7 @@
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,
@@ -150,7 +152,7 @@ drop view if exists foodYearly;
drop view if exists foodRecent;
create view foodView as
select rowid,
select id,
date,
food,
description,
@@ -196,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;
@@ -218,7 +219,7 @@ set per100 = coalesce(
limit 1
)
)
where rowid = new.rowid;
where id = new.id;
end;
create table settings(

View File

@@ -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)
}

View File

@@ -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;
@@ -101,7 +105,8 @@
// }
function setInputVal(food: main.Food) {
name = food.food;
per100 = String(food.per100)
per100 = String(food.per100);
amount = String(food.amount);
hiLiteIndex = null;
foodSearch = [];
}
@@ -113,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} /> -->
@@ -132,6 +149,8 @@
contenteditable="true"
autofocus
on:keydown={update}
on:focusin={handleFocusIn}
on:focusout={handleFocusOut}
bind:this={nameElement}
/>
<td
@@ -161,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)}
/>
<FoodSearchEntry itemLabel={f.food} highlighted={i == hiLiteIndex} on:click={() => setInputVal(f)} />
{/each}
</ul>
{/if}

View File

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

View File

@@ -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"];
}

34
main.go
View File

@@ -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,37 +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()
err = db.Init(foodDDL)
if err != nil {
Error.Printf("Error initializing database: %++v", err)
os.Exit(1)
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

Binary file not shown.

View File

@@ -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)
}