1package wiki
2
3import (
4 "database/sql"
5 "fmt"
6 "time"
7)
8
9type Store struct {
10 db *sql.DB
11}
12
13type Page struct {
14 Title string
15 Content string
16 Author string
17 Updated int64
18}
19
20func New(db *sql.DB) *Store { return &Store{db: db} }
21
22func (s *Store) Get(title string) (Page, error) {
23 row := s.db.QueryRow(`SELECT title, content, author, updated FROM wiki_pages WHERE title=?`, title)
24 var p Page
25 err := row.Scan(&p.Title, &p.Content, &p.Author, &p.Updated)
26 if err == sql.ErrNoRows {
27 return Page{}, fmt.Errorf("wiki page not found: %s", title)
28 }
29 return p, err
30}
31
32func (s *Store) Set(title, content, author string) error {
33 now := time.Now().Unix()
34 _, err := s.db.Exec(`
35 INSERT INTO wiki_pages (title, content, author, updated)
36 VALUES (?, ?, ?, ?)
37 ON CONFLICT(title) DO UPDATE SET
38 content=excluded.content,
39 author=excluded.author,
40 updated=excluded.updated`,
41 title, content, author, now,
42 )
43 return err
44}
45
46func (s *Store) List() ([]Page, error) {
47 rows, err := s.db.Query(`SELECT title, content, author, updated FROM wiki_pages ORDER BY title`)
48 if err != nil {
49 return nil, err
50 }
51 defer rows.Close()
52
53 var pages []Page
54 for rows.Next() {
55 var p Page
56 err := rows.Scan(&p.Title, &p.Content, &p.Author, &p.Updated)
57 if err != nil {
58 return nil, err
59 }
60 pages = append(pages, p)
61 }
62 return pages, rows.Err()
63}