From 20560419614e22fbb58567cdb0b88b54caf679f4 Mon Sep 17 00:00:00 2001 From: Matthew Lemon Date: Thu, 18 Apr 2024 11:06:32 +0100 Subject: Adds code from ded-go-core - no database D2S test app code removed (nginx error). Adds all go code from `ded-go-core` using the basic Gov.UK UI for a test page for DED. --- internal/models/organisations.go | 85 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 internal/models/organisations.go (limited to 'internal/models/organisations.go') diff --git a/internal/models/organisations.go b/internal/models/organisations.go new file mode 100644 index 0000000..88f7bc9 --- /dev/null +++ b/internal/models/organisations.go @@ -0,0 +1,85 @@ +package models + +import ( + "database/sql" + "errors" + "time" +) + +type Organisation struct { + ID int + Name string + Created time.Time +} + +type OrganisationModel struct { + DB *sql.DB +} + +func (m *OrganisationModel) Insert(name string) (int, error) { + stmt := `INSERT INTO organisations (name, created) + VALUEs (?, UTC_TIMESTAMP())` + + result, err := m.DB.Exec(stmt, name) + if err != nil { + return 0, err + } + + id, err := result.LastInsertId() + if err != nil { + return 0, err + } + return int(id), nil +} + +func (m *OrganisationModel) Get(id int) (Organisation, error) { + stmt := `SELECT id, name, created FROM organisations + WHERE id = ?` + + row := m.DB.QueryRow(stmt, id) + + var o Organisation + + err := row.Scan(&o.ID, &o.Name, &o.Created) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return Organisation{}, ErrNoRecord + } else { + return Organisation{}, err + } + } + return o, nil +} + +// Ten most recent... +func (m *OrganisationModel) Latest() ([]Organisation, error) { + // Pick out the last 10 + stmt := `SELECT id, name, created FROM organisations + ORDER BY id DESC LIMIT 10` + + rows, err := m.DB.Query(stmt) + if err != nil { + return nil, err + } + + defer rows.Close() + + var organisations []Organisation + + for rows.Next() { + var o Organisation + + err = rows.Scan(&o.ID, &o.Name, &o.Created) + if err != nil { + return nil, err + } + + organisations = append(organisations, o) + } + + if err = rows.Err(); err != nil { + return nil, err + } + + return organisations, err +} -- cgit v1.2.3