Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Notes fields to Caves & Cavers #28

Merged
merged 2 commits into from
Sep 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ func (db *Database) AddTrip(date, location, names, notes string) error {
return nil
}

func (db *Database) AddLocation(name, region, country string, srt bool) error {
query := `INSERT INTO locations (name, region, country, srt) VALUES (?,?,?,?)`
func (db *Database) AddLocation(name, region, country, notes string, srt bool) error {
query := `INSERT INTO locations (name, region, country, srt, notes) VALUES (?,?,?,?,?)`
params := []interface{}{name, region, country, srt}

if err := db.conn.Begin(); err != nil {
Expand All @@ -113,8 +113,8 @@ func (db *Database) AddLocation(name, region, country string, srt bool) error {
return nil
}

func (db *Database) AddPerson(name, club string) error {
query := `INSERT INTO people (name, club) VALUES (?,?)`
func (db *Database) AddPerson(name, club, notes string) error {
query := `INSERT INTO people (name, club, notes) VALUES (?,?,?)`
params := []interface{}{name, club}

if err := db.conn.Begin(); err != nil {
Expand Down Expand Up @@ -353,7 +353,8 @@ func (db *Database) GetPerson(personID string) (*model.Caver, error) {
SELECT COUNT(1)
FROM trip_groups
WHERE trip_groups.caverid = people.id
) AS 'count'
) AS 'count',
people.notes AS 'notes'
FROM people
WHERE people.id = ?`

Expand All @@ -378,7 +379,7 @@ func (db *Database) GetPerson(personID string) (*model.Caver, error) {
break
}

err = result.Scan(&person.ID, &person.Name, &person.Club, &person.Count)
err = result.Scan(&person.ID, &person.Name, &person.Club, &person.Count, &person.Notes)
if err != nil {
db.log.Error(err)
return people[0], err
Expand Down Expand Up @@ -491,7 +492,8 @@ func (db *Database) GetLocation(caveID string) (*model.Cave, error) {
SELECT COUNT(1)
FROM trips
WHERE trips.caveid = locations.id
) AS 'visits'
) AS 'visits',
locations.notes AS 'notes'
FROM locations
WHERE id = ?`
result, err := db.conn.Prepare(query, caveID)
Expand All @@ -503,8 +505,6 @@ func (db *Database) GetLocation(caveID string) (*model.Cave, error) {

caves := make([]*model.Cave, 0)
for {
//var caverIDstr string
//var stamp int64
var cave model.Cave

rowExists, err := result.Step()
Expand All @@ -517,7 +517,7 @@ func (db *Database) GetLocation(caveID string) (*model.Cave, error) {
break
}

err = result.Scan(&cave.ID, &cave.Name, &cave.Region, &cave.Country, &cave.SRT, &cave.Visits)
err = result.Scan(&cave.ID, &cave.Name, &cave.Region, &cave.Country, &cave.SRT, &cave.Visits, &cave.Notes)
if err != nil {
db.log.Error(err)
return caves[0], err
Expand Down Expand Up @@ -671,9 +671,9 @@ func (db *Database) ModifyTrip(id, date, location, names, notes string) error {
return nil
}

func (db *Database) ModifyPerson(id, name, club string) error {
query := `UPDATE people SET name = ?, club = ? WHERE id = ?`
params := []interface{}{name, club, id}
func (db *Database) ModifyPerson(id, name, club, notes string) error {
query := `UPDATE people SET name = ?, club = ?, notes = ? WHERE id = ?`
params := []interface{}{name, club, notes, id}

if err := db.conn.Begin(); err != nil {
return err
Expand All @@ -698,9 +698,9 @@ func (db *Database) ModifyPerson(id, name, club string) error {
return nil
}

func (db *Database) ModifyLocation(id, name, region, country string, srt bool) error {
query := `UPDATE locations SET name = ?, region = ?, country = ?, srt = ? WHERE id = ?`
params := []interface{}{name, region, country, srt, id}
func (db *Database) ModifyLocation(id, name, region, country, notes string, srt bool) error {
query := `UPDATE locations SET name = ?, region = ?, country = ?, srt = ?, notes = ? WHERE id = ?`
params := []interface{}{name, region, country, srt, notes, id}

if err := db.conn.Begin(); err != nil {
return err
Expand Down
3 changes: 3 additions & 0 deletions internal/gui/cavers.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ func (c *cavers) setKeybinding(g *Gui) {
g.setGlobalKeybinding(event)

switch event.Key() {
case tcell.KeyEnter:
g.state.navigate.update("detail")
g.inspectCaver()
case tcell.KeyCtrlR:
c.setEntries(g)
}
Expand Down
3 changes: 3 additions & 0 deletions internal/gui/caves.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ func (c *caves) setKeybinding(g *Gui) {
g.setGlobalKeybinding(event)

switch event.Key() {
case tcell.KeyEnter:
g.state.navigate.update("detail")
g.inspectCave()
case tcell.KeyCtrlR:
c.setEntries(g)
}
Expand Down
8 changes: 8 additions & 0 deletions internal/gui/cud.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ func (g *Gui) createLocationForm() {
AddFormItem(regionField).
AddFormItem(countryField).
AddCheckBox("SRT", "", false, nil).
AddInputField("Notes", "", inputWidth, nil, nil).
AddButton("Add", func() {
g.createLocation(form)
}).
Expand All @@ -124,6 +125,7 @@ func (g *Gui) createLocation(form *tview.Form) {
form.GetFormItemByLabel("Name").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Region").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Country").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Notes").(*tview.InputField).GetText(),
form.GetFormItemByLabel("SRT").(*tview.CheckBox).IsChecked(),
)
if err != nil { // NOTE: Needs fixing
Expand Down Expand Up @@ -161,6 +163,7 @@ func (g *Gui) createPersonForm() {
form.
AddInputField("Name", "", inputWidth, nil, nil).
AddFormItem(clubField).
AddInputField("Notes", "", inputWidth, nil, nil).
AddButton("Add", func() {
g.createPerson(form)
}).
Expand All @@ -175,6 +178,7 @@ func (g *Gui) createPerson(form *tview.Form) {
err := g.db.AddPerson(
form.GetFormItemByLabel("Name").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Club").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Notes").(*tview.InputField).GetText(),
)
if err != nil { // NOTE: Needs fixing
g.warning(err.Error(), `form`, []string{`OK`}, func() {return})
Expand Down Expand Up @@ -283,6 +287,7 @@ func (g *Gui) modifyPersonForm() {
form.
AddInputField("Name", selectedPerson.Name, inputWidth, nil, nil).
AddFormItem(clubField).
AddInputField("Notes", selectedPerson.Notes, inputWidth, nil, nil).
AddButton("Apply", func() {
g.modifyPerson(selectedPerson.ID, form)
}).
Expand All @@ -298,6 +303,7 @@ func (g *Gui) modifyPerson(id string, form *tview.Form) {
id,
form.GetFormItemByLabel("Name").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Club").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Notes").(*tview.InputField).GetText(),
)
if err != nil {
g.warning(err.Error(), `form`, []string{`OK`}, func() {return})
Expand Down Expand Up @@ -359,6 +365,7 @@ func (g *Gui) modifyLocationForm() {
AddFormItem(regionField).
AddFormItem(countryField).
AddCheckBox("SRT", "", selectedLocation.SRT, nil).
AddInputField("Notes", selectedLocation.Notes, inputWidth, nil, nil).
AddButton("Apply", func() {
g.modifyLocation(selectedLocation.ID, form)
}).
Expand All @@ -375,6 +382,7 @@ func (g *Gui) modifyLocation(id string, form *tview.Form) {
form.GetFormItemByLabel("Name").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Region").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Country").(*tview.InputField).GetText(),
form.GetFormItemByLabel("Notes").(*tview.InputField).GetText(),
form.GetFormItemByLabel("SRT").(*tview.CheckBox).IsChecked(),
)
if err != nil {
Expand Down
28 changes: 14 additions & 14 deletions internal/gui/inspector.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (

var inspectorFormat = map[string]string{
`trips` : "\tDate: %s\n\tCave: %s\n\tCavers: %s\n\tNotes: %s",
`cavers`: "\tName: %s\n\tClub: %s\n\tCount: %d",
`caves` : "\tName: %s\n\tRegion: %s\n\tCountry: %s\n\tSRT: %v\n\tVisits: %d",
`cavers`: "\tName: %s\n\tClub: %s\n\tCount: %d\n\tNotes: %s",
`caves` : "\tName: %s\n\tRegion: %s\n\tCountry: %s\n\tSRT: %s\n\tVisits: %d\n\tNotes: %s",
}

func (g *Gui) displayInspect(data, page string) {
Expand Down Expand Up @@ -51,40 +51,40 @@ func (g *Gui) inspectTrip() {
g.displayInspect(g.formatTrip(trip), "trips")
}

/*func (g *Gui) inspectCave() {
func (g *Gui) inspectCave() {
selected := g.selectedLocation()

cave, err := g.db.GetLocation(selected.ID)
if err != nil {
return
}

g.inspectorPanel().setEntry(g.formatCave(cave))
g.displayInspect(g.formatCave(cave), "caves")
}

func (g *Gui) inspectPerson() {
func (g *Gui) inspectCaver() {
selected := g.selectedPerson()

caver, err := g.db.GetPerson(selected.ID)
if err != nil {
return
}

g.inspectorPanel().setEntry(g.formatPerson(caver))
}*/
g.displayInspect(g.formatPerson(caver), "cavers")
}

//
// Formatting Functions
//
func (g *Gui) formatTrip(trip *model.Log) string {
return fmt.Sprintf(inspectorFormat[`trips`], trip.Date, trip.Cave, trip.Names, trip.Notes)
func (g *Gui) formatTrip(t *model.Log) string {
return fmt.Sprintf(inspectorFormat[`trips`], t.Date, t.Cave, t.Names, t.Notes)
}

/*func (g *Gui) formatCave(l *model.Cave) string {
return fmt.Sprintf(inspectorFormat[`caves`], l.Name, l.Region, l.Country, l.SRT, l.Visits)
func (g *Gui) formatCave(c *model.Cave) string {
return fmt.Sprintf(inspectorFormat[`caves`], c.Name, c.Region, c.Country, yesOrNo(c.SRT), c.Visits, c.Notes)
}

func (g *Gui) formatPerson(p *model.Caver) string {
return fmt.Sprintf(inspectorFormat[`cavers`], p.Name, p.Club, p.Count)
}*/
func (g *Gui) formatPerson(c *model.Caver) string {
return fmt.Sprintf(inspectorFormat[`cavers`], c.Name, c.Club, c.Count, c.Notes)
}

2 changes: 2 additions & 0 deletions internal/model/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ type Cave struct {
Country string
SRT bool
Visits int64
Notes string
}

type Caver struct {
ID string
Name string
Club string
Count int64
Notes string
}

type Log struct {
Expand Down
46 changes: 40 additions & 6 deletions scripts/make-db.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,33 @@
HOME = os.environ["HOME"]
NEWPATH = f"{HOME}/.config/cave-logger"

def runTableMigration(dbFile):
"""
This function migrates old databases to the new spec.
"""
print(f"Checking existing database for new spec")

conn = sqlite3.connect(dbFile)
c = conn.cursor()

def check(cols):
for col_info in cols:
if "notes" in col_info:
return True
return False
#END

for t in ("locations","people"):
c.execute(f"PRAGMA table_info({t});")
if not check(c.fetchall()):
stmt = f"ALTER TABLE {t} ADD notes TEXT;"
c.execute(stmt)
print(f"Added notes column to {t}")

conn.commit()
conn.close()
#END

try:
os.makedirs(NEWPATH, 0o755)
except FileExistsError:
Expand All @@ -21,6 +48,7 @@
if files:
db = False
cfg = False
runMigration = False
for f in files:
if '.db' in f:
db = f
Expand All @@ -32,10 +60,13 @@
fn = json.load(f)['database']['filename']
if db in fn:
print("Found pre-existing configs aborting...")
sys.exit()
runMigration = True
except KeyError:
pass

if runMigration:
runTableMigration(f"{HOME}/{fn}")
sys.exit()

sqliteFile = str(uuid.uuid4()) + '.db'
tables = [
Expand All @@ -46,13 +77,13 @@
},
{
"name" : "locations",
"cols" : ["id","name","region","country","srt"],
"types": ["INTEGER PRIMARY KEY AUTOINCREMENT","TEXT","TEXT","TEXT","INTEGER"]
"cols" : ["id","name","region","country","srt","notes"],
"types": ["INTEGER PRIMARY KEY AUTOINCREMENT","TEXT","TEXT","TEXT","INTEGER","TEXT"]
},
{
"name" : "people",
"cols" : ["id","name","club"],
"types": ["INTEGER PRIMARY KEY AUTOINCREMENT","TEXT","TEXT"]
"cols" : ["id","name","club","notes"],
"types": ["INTEGER PRIMARY KEY AUTOINCREMENT","TEXT","TEXT","TEXT"]
},
{
"name" : "trip_groups",
Expand Down Expand Up @@ -87,12 +118,14 @@
print("Created {} database tables".format(len(tables)))
conn.close()


CONFIG_FN = '{}/config.json'.format(NEWPATH)
with open(CONFIG_FN, 'w') as c:
config = {
'database': {
'filename': '/'.join([".config/cave-logger", sqliteFile]),
'created' : NOW
'created' : NOW,
'spec': "1.1.0"
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not really needed but might prove useful in the future.

},
'colors': {
'primitiveBackground': '',
Expand All @@ -110,3 +143,4 @@
}
json.dump(config, c, indent=2)
print("Wrote database name to config file")