summaryrefslogtreecommitdiffstats
path: root/internal/models/organisations.go
blob: 88f7bc99b8ded5cf6ba9eeecbdbcd3cae90f341e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
}