diff options
author | Julien Dessaux | 2021-09-08 16:22:16 +0200 |
---|---|---|
committer | Julien Dessaux | 2021-09-08 16:22:16 +0200 |
commit | dbd75fe2287d86c36892439b83b58288c34e700d (patch) | |
tree | 9a752a3cc48f199c6188550eaafb2bdbdfba568f /pkg/database | |
parent | Renamed TrainStop to simply Stop (diff) | |
download | trains-dbd75fe2287d86c36892439b83b58288c34e700d.tar.gz trains-dbd75fe2287d86c36892439b83b58288c34e700d.tar.bz2 trains-dbd75fe2287d86c36892439b83b58288c34e700d.zip |
Added database function to get a train stop name from its id
Diffstat (limited to 'pkg/database')
-rw-r--r-- | pkg/database/stop.go | 15 | ||||
-rw-r--r-- | pkg/database/stop_test.go | 21 |
2 files changed, 36 insertions, 0 deletions
diff --git a/pkg/database/stop.go b/pkg/database/stop.go index 519b9aa..47f9ce1 100644 --- a/pkg/database/stop.go +++ b/pkg/database/stop.go @@ -13,6 +13,21 @@ func (env *DBEnv) CountStops() (i int, err error) { return } +func (env *DBEnv) GetStop(id string) (*model.Stop, error) { + query := `SELECT name FROM stops WHERE id = $1;` + stop := model.Stop{Id: id} + err := env.db.QueryRow( + query, + id, + ).Scan( + &stop.Name, + ) + if err != nil { + return nil, newQueryError("Could not run database query", err) + } + return &stop, nil +} + func (env *DBEnv) ReplaceAndImportStops(trainStops []model.Stop) error { pre_query := `DELETE FROM stops;` query := ` diff --git a/pkg/database/stop_test.go b/pkg/database/stop_test.go index 7329ac7..d3db75e 100644 --- a/pkg/database/stop_test.go +++ b/pkg/database/stop_test.go @@ -31,6 +31,27 @@ func TestCountStops(t *testing.T) { assert.Equal(t, i, len(trainStops)) } +func TestGetStop(t *testing.T) { + trainStops := []model.Stop{ + model.Stop{Id: "id1", Name: "name1"}, + model.Stop{Id: "id2", Name: "name2"}, + } + // test db setup + db, err := InitDB("sqlite3", "file::memory:?_foreign_keys=on") + require.NoError(t, err) + err = db.Migrate() + require.NoError(t, err) + err = db.ReplaceAndImportStops(trainStops) + // normal check + stop, err := db.GetStop("id1") + require.NoError(t, err) + assert.Equal(t, stop, &trainStops[0]) + // error check + stop, err = db.GetStop("non_existent") + require.Error(t, err) + assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(&QueryError{}), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(&QueryError{})) +} + func TestReplaceAndImportStops(t *testing.T) { // test db setup db, err := InitDB("sqlite3", "file::memory:?_foreign_keys=on") |