changeset 33:5f515c91737f

Finally commit fortunes handler code
author Lewin Bormann <lbo@spheniscida.de>
date Sat, 10 Dec 2016 13:44:23 +0100
parents 511fd45de3ea
children d35d389fa9fb
files handler_fortune.go sql/fortune.go
diffstat 2 files changed, 75 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/handler_fortune.go	Sat Dec 10 13:44:23 2016 +0100
@@ -0,0 +1,19 @@
+package main
+
+import "context"
+
+func fortuneHandler(ctx context.Context, msg message) (replyContent, error) {
+	f, err := backend.Fortunes()
+
+	if err != nil {
+		return replyContent{text: "_Konnte Datenbankanfrage nicht initialisieren:_ " + err.Error()}, err
+	}
+
+	fortune, err := f.SelectFortune()
+
+	if err != nil {
+		return replyContent{text: "_Konnte keinen Glückskeks auswählen:_ " + err.Error()}, err
+	}
+
+	return replyContent{text: fortune}, nil
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sql/fortune.go	Sat Dec 10 13:44:23 2016 +0100
@@ -0,0 +1,56 @@
+package sql
+
+import "log"
+
+// prepared statements
+const (
+	// parameters: n/a
+	// outputs: id INTEGER, fortune TEXT
+	selectFortune = `SELECT id, fortune FROM fortunes WHERE used = (SELECT min(used) FROM fortunes) ORDER BY random() LIMIT 1`
+	// parameters: 1 = fortune ID
+	// outputs: n/a
+	updateFortune = `UPDATE fortunes SET used = used + 1 WHERE id = $1`
+)
+
+type Fortunes struct {
+	db *Storage
+}
+
+func newFortunes(s *Storage) (Fortunes, error) {
+	f := Fortunes{db: s}
+	return f, f.prewarm()
+}
+
+func (f Fortunes) prewarm() error {
+	return f.db.prewarm([]string{
+		selectFortune,
+		updateFortune,
+	})
+}
+
+func (f Fortunes) SelectFortune() (string, error) {
+	var id uint64
+	var fortune string
+
+	// Get fortune...
+	if stmt, ok := f.db.prepared[selectFortune]; ok {
+		row := stmt.QueryRow()
+
+		err := row.Scan(&id, &fortune)
+
+		if err != nil {
+			log.Println("Couldn't get fortune:", err)
+			return "Ich kenne noch keine guten Sprüche!", nil
+		}
+	}
+
+	if stmt, ok := f.db.prepared[updateFortune]; ok {
+		_, err := stmt.Exec(id)
+
+		if err != nil {
+			log.Println("Couldn't update fortune:", err)
+		}
+	}
+
+	return fortune, nil
+}