upgradedb.go (view raw)
1//
2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
3//
4// Permission to use, copy, modify, and distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19 "database/sql"
20 "os"
21 "strings"
22 "time"
23)
24
25var myVersion = 42
26
27type dbexecer interface {
28 Exec(query string, args ...interface{}) (sql.Result, error)
29}
30
31func doordie(db dbexecer, s string, args ...interface{}) {
32 _, err := db.Exec(s, args...)
33 if err != nil {
34 elog.Fatalf("can't run %s: %s", s, err)
35 }
36}
37
38func upgradedb() {
39 db := opendatabase()
40 dbversion := 0
41 getconfig("dbversion", &dbversion)
42 getconfig("servername", &serverName)
43
44 if dbversion < 40 {
45 elog.Fatal("database is too old to upgrade")
46 }
47 switch dbversion {
48 case 40:
49 doordie(db, "PRAGMA journal_mode=WAL")
50 blobdb := openblobdb()
51 doordie(blobdb, "PRAGMA journal_mode=WAL")
52 doordie(db, "update config set value = 41 where key = 'dbversion'")
53 fallthrough
54 case 41:
55 tx, err := db.Begin()
56 if err != nil {
57 elog.Fatal(err)
58 }
59 rows, err := tx.Query("select honkid, noise from honks where format = 'markdown' and precis <> ''")
60 if err != nil {
61 elog.Fatal(err)
62 }
63 m := make(map[int64]string)
64 var dummy Honk
65 for rows.Next() {
66 err = rows.Scan(&dummy.ID, &dummy.Noise)
67 if err != nil {
68 elog.Fatal(err)
69 }
70 precipitate(&dummy)
71 m[dummy.ID] = dummy.Noise
72 }
73 rows.Close()
74 for id, noise := range m {
75 _, err = tx.Exec("update honks set noise = ? where honkid = ?", noise, id)
76 if err != nil {
77 elog.Fatal(err)
78 }
79 }
80 err = tx.Commit()
81 if err != nil {
82 elog.Fatal(err)
83 }
84 doordie(db, "update config set value = 42 where key = 'dbversion'")
85 fallthrough
86 case 42:
87
88 default:
89 elog.Fatalf("can't upgrade unknown version %d", dbversion)
90 }
91 os.Exit(0)
92}