message_cache.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. package server
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. _ "github.com/mattn/go-sqlite3" // SQLite driver
  8. "heckel.io/ntfy/util"
  9. "log"
  10. "strings"
  11. "time"
  12. )
  13. var (
  14. errUnexpectedMessageType = errors.New("unexpected message type")
  15. )
  16. // Messages cache
  17. const (
  18. createMessagesTableQuery = `
  19. BEGIN;
  20. CREATE TABLE IF NOT EXISTS messages (
  21. id INTEGER PRIMARY KEY AUTOINCREMENT,
  22. mid TEXT NOT NULL,
  23. time INT NOT NULL,
  24. topic TEXT NOT NULL,
  25. message TEXT NOT NULL,
  26. title TEXT NOT NULL,
  27. priority INT NOT NULL,
  28. tags TEXT NOT NULL,
  29. click TEXT NOT NULL,
  30. actions TEXT NOT NULL,
  31. attachment_name TEXT NOT NULL,
  32. attachment_type TEXT NOT NULL,
  33. attachment_size INT NOT NULL,
  34. attachment_expires INT NOT NULL,
  35. attachment_url TEXT NOT NULL,
  36. attachment_owner TEXT NOT NULL,
  37. encoding TEXT NOT NULL,
  38. published INT NOT NULL
  39. );
  40. CREATE INDEX IF NOT EXISTS idx_mid ON messages (mid);
  41. CREATE INDEX IF NOT EXISTS idx_topic ON messages (topic);
  42. COMMIT;
  43. `
  44. insertMessageQuery = `
  45. INSERT INTO messages (mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding, published)
  46. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  47. `
  48. updateMessageQuery = `
  49. UPDATE messages
  50. SET time = ?
  51. WHERE topic = ? AND mid = ? AND published = 0
  52. `
  53. pruneMessagesQuery = `DELETE FROM messages WHERE time < ? AND published = 1`
  54. selectRowIDFromMessageID = `SELECT id FROM messages WHERE topic = ? AND mid = ?`
  55. selectMessagesSinceTimeQuery = `
  56. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  57. FROM messages
  58. WHERE topic = ? AND time >= ? AND published = 1
  59. ORDER BY time, id
  60. `
  61. selectMessagesSinceTimeIncludeScheduledQuery = `
  62. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  63. FROM messages
  64. WHERE topic = ? AND time >= ?
  65. ORDER BY time, id
  66. `
  67. selectMessagesSinceIDQuery = `
  68. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  69. FROM messages
  70. WHERE topic = ? AND id > ? AND published = 1
  71. ORDER BY time, id
  72. `
  73. selectMessagesSinceIDIncludeScheduledQuery = `
  74. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  75. FROM messages
  76. WHERE topic = ? AND (id > ? OR published = 0)
  77. ORDER BY time, id
  78. `
  79. selectMessagesDueQuery = `
  80. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  81. FROM messages
  82. WHERE time <= ? AND published = 0
  83. ORDER BY time, id
  84. `
  85. selectMessagesScheduledByTagOrID = `
  86. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  87. FROM messages
  88. WHERE topic = ? AND (tags LIKE ? OR mid = ?) AND published = 0
  89. `
  90. updateMessagePublishedQuery = `UPDATE messages SET published = 1 WHERE mid = ?`
  91. selectMessagesCountQuery = `SELECT COUNT(*) FROM messages`
  92. selectMessageCountForTopicQuery = `SELECT COUNT(*) FROM messages WHERE topic = ?`
  93. selectTopicsQuery = `SELECT topic FROM messages GROUP BY topic`
  94. selectAttachmentsSizeQuery = `SELECT IFNULL(SUM(attachment_size), 0) FROM messages WHERE attachment_owner = ? AND attachment_expires >= ?`
  95. selectAttachmentsExpiredQuery = `SELECT mid FROM messages WHERE attachment_expires > 0 AND attachment_expires < ?`
  96. )
  97. // Schema management queries
  98. const (
  99. currentSchemaVersion = 6
  100. createSchemaVersionTableQuery = `
  101. CREATE TABLE IF NOT EXISTS schemaVersion (
  102. id INT PRIMARY KEY,
  103. version INT NOT NULL
  104. );
  105. `
  106. insertSchemaVersion = `INSERT INTO schemaVersion VALUES (1, ?)`
  107. updateSchemaVersion = `UPDATE schemaVersion SET version = ? WHERE id = 1`
  108. selectSchemaVersionQuery = `SELECT version FROM schemaVersion WHERE id = 1`
  109. // 0 -> 1
  110. migrate0To1AlterMessagesTableQuery = `
  111. BEGIN;
  112. ALTER TABLE messages ADD COLUMN title TEXT NOT NULL DEFAULT('');
  113. ALTER TABLE messages ADD COLUMN priority INT NOT NULL DEFAULT(0);
  114. ALTER TABLE messages ADD COLUMN tags TEXT NOT NULL DEFAULT('');
  115. COMMIT;
  116. `
  117. // 1 -> 2
  118. migrate1To2AlterMessagesTableQuery = `
  119. ALTER TABLE messages ADD COLUMN published INT NOT NULL DEFAULT(1);
  120. `
  121. // 2 -> 3
  122. migrate2To3AlterMessagesTableQuery = `
  123. BEGIN;
  124. ALTER TABLE messages ADD COLUMN click TEXT NOT NULL DEFAULT('');
  125. ALTER TABLE messages ADD COLUMN attachment_name TEXT NOT NULL DEFAULT('');
  126. ALTER TABLE messages ADD COLUMN attachment_type TEXT NOT NULL DEFAULT('');
  127. ALTER TABLE messages ADD COLUMN attachment_size INT NOT NULL DEFAULT('0');
  128. ALTER TABLE messages ADD COLUMN attachment_expires INT NOT NULL DEFAULT('0');
  129. ALTER TABLE messages ADD COLUMN attachment_owner TEXT NOT NULL DEFAULT('');
  130. ALTER TABLE messages ADD COLUMN attachment_url TEXT NOT NULL DEFAULT('');
  131. COMMIT;
  132. `
  133. // 3 -> 4
  134. migrate3To4AlterMessagesTableQuery = `
  135. ALTER TABLE messages ADD COLUMN encoding TEXT NOT NULL DEFAULT('');
  136. `
  137. // 4 -> 5
  138. migrate4To5AlterMessagesTableQuery = `
  139. BEGIN;
  140. CREATE TABLE IF NOT EXISTS messages_new (
  141. id INTEGER PRIMARY KEY AUTOINCREMENT,
  142. mid TEXT NOT NULL,
  143. time INT NOT NULL,
  144. topic TEXT NOT NULL,
  145. message TEXT NOT NULL,
  146. title TEXT NOT NULL,
  147. priority INT NOT NULL,
  148. tags TEXT NOT NULL,
  149. click TEXT NOT NULL,
  150. attachment_name TEXT NOT NULL,
  151. attachment_type TEXT NOT NULL,
  152. attachment_size INT NOT NULL,
  153. attachment_expires INT NOT NULL,
  154. attachment_url TEXT NOT NULL,
  155. attachment_owner TEXT NOT NULL,
  156. encoding TEXT NOT NULL,
  157. published INT NOT NULL
  158. );
  159. CREATE INDEX IF NOT EXISTS idx_mid ON messages_new (mid);
  160. CREATE INDEX IF NOT EXISTS idx_topic ON messages_new (topic);
  161. INSERT
  162. INTO messages_new (
  163. mid, time, topic, message, title, priority, tags, click, attachment_name, attachment_type,
  164. attachment_size, attachment_expires, attachment_url, attachment_owner, encoding, published)
  165. SELECT
  166. id, time, topic, message, title, priority, tags, click, attachment_name, attachment_type,
  167. attachment_size, attachment_expires, attachment_url, attachment_owner, encoding, published
  168. FROM messages;
  169. DROP TABLE messages;
  170. ALTER TABLE messages_new RENAME TO messages;
  171. COMMIT;
  172. `
  173. // 5 -> 6
  174. migrate5To6AlterMessagesTableQuery = `
  175. ALTER TABLE messages ADD COLUMN actions TEXT NOT NULL DEFAULT('');
  176. `
  177. )
  178. type messageCache struct {
  179. db *sql.DB
  180. nop bool
  181. }
  182. // newSqliteCache creates a SQLite file-backed cache
  183. func newSqliteCache(filename string, nop bool) (*messageCache, error) {
  184. db, err := sql.Open("sqlite3", filename)
  185. if err != nil {
  186. return nil, err
  187. }
  188. if err := setupCacheDB(db); err != nil {
  189. return nil, err
  190. }
  191. return &messageCache{
  192. db: db,
  193. nop: nop,
  194. }, nil
  195. }
  196. // newMemCache creates an in-memory cache
  197. func newMemCache() (*messageCache, error) {
  198. return newSqliteCache(createMemoryFilename(), false)
  199. }
  200. // newNopCache creates an in-memory cache that discards all messages;
  201. // it is always empty and can be used if caching is entirely disabled
  202. func newNopCache() (*messageCache, error) {
  203. return newSqliteCache(createMemoryFilename(), true)
  204. }
  205. // createMemoryFilename creates a unique memory filename to use for the SQLite backend.
  206. // From mattn/go-sqlite3: "Each connection to ":memory:" opens a brand new in-memory
  207. // sql database, so if the stdlib's sql engine happens to open another connection and
  208. // you've only specified ":memory:", that connection will see a brand new database.
  209. // A workaround is to use "file::memory:?cache=shared" (or "file:foobar?mode=memory&cache=shared").
  210. // Every connection to this string will point to the same in-memory database."
  211. func createMemoryFilename() string {
  212. return fmt.Sprintf("file:%s?mode=memory&cache=shared", util.RandomString(10))
  213. }
  214. func (c *messageCache) AddMessage(m *message) error {
  215. if m.Event != messageEvent {
  216. return errUnexpectedMessageType
  217. } else if c.nop {
  218. return nil
  219. }
  220. published := m.Time <= time.Now().Unix()
  221. tags := strings.Join(m.Tags, ",")
  222. var attachmentName, attachmentType, attachmentURL, attachmentOwner string
  223. var attachmentSize, attachmentExpires int64
  224. if m.Attachment != nil {
  225. attachmentName = m.Attachment.Name
  226. attachmentType = m.Attachment.Type
  227. attachmentSize = m.Attachment.Size
  228. attachmentExpires = m.Attachment.Expires
  229. attachmentURL = m.Attachment.URL
  230. attachmentOwner = m.Attachment.Owner
  231. }
  232. var actionsStr string
  233. if len(m.Actions) > 0 {
  234. actionsBytes, err := json.Marshal(m.Actions)
  235. if err != nil {
  236. return err
  237. }
  238. actionsStr = string(actionsBytes)
  239. }
  240. _, err := c.db.Exec(
  241. insertMessageQuery,
  242. m.ID,
  243. m.Time,
  244. m.Topic,
  245. m.Message,
  246. m.Title,
  247. m.Priority,
  248. tags,
  249. m.Click,
  250. actionsStr,
  251. attachmentName,
  252. attachmentType,
  253. attachmentSize,
  254. attachmentExpires,
  255. attachmentURL,
  256. attachmentOwner,
  257. m.Encoding,
  258. published,
  259. )
  260. return err
  261. }
  262. func (c *messageCache) UpdateMessage(m *message) error {
  263. if m.Event != messageEvent {
  264. return errUnexpectedMessageType
  265. } else if c.nop {
  266. return nil
  267. }
  268. _, err := c.db.Exec(
  269. updateMessageQuery,
  270. m.Time,
  271. m.Topic,
  272. m.ID,
  273. )
  274. return err
  275. }
  276. func (c *messageCache) Messages(topic string, since sinceMarker, scheduled bool) ([]*message, error) {
  277. if since.IsNone() {
  278. return make([]*message, 0), nil
  279. } else if since.IsID() {
  280. return c.messagesSinceID(topic, since, scheduled)
  281. }
  282. return c.messagesSinceTime(topic, since, scheduled)
  283. }
  284. func (c *messageCache) messagesSinceTime(topic string, since sinceMarker, scheduled bool) ([]*message, error) {
  285. var rows *sql.Rows
  286. var err error
  287. if scheduled {
  288. rows, err = c.db.Query(selectMessagesSinceTimeIncludeScheduledQuery, topic, since.Time().Unix())
  289. } else {
  290. rows, err = c.db.Query(selectMessagesSinceTimeQuery, topic, since.Time().Unix())
  291. }
  292. if err != nil {
  293. return nil, err
  294. }
  295. return readMessages(rows)
  296. }
  297. func (c *messageCache) messagesSinceID(topic string, since sinceMarker, scheduled bool) ([]*message, error) {
  298. idrows, err := c.db.Query(selectRowIDFromMessageID, topic, since.ID())
  299. if err != nil {
  300. return nil, err
  301. }
  302. defer idrows.Close()
  303. if !idrows.Next() {
  304. return c.messagesSinceTime(topic, sinceAllMessages, scheduled)
  305. }
  306. var rowID int64
  307. if err := idrows.Scan(&rowID); err != nil {
  308. return nil, err
  309. }
  310. idrows.Close()
  311. var rows *sql.Rows
  312. if scheduled {
  313. rows, err = c.db.Query(selectMessagesSinceIDIncludeScheduledQuery, topic, rowID)
  314. } else {
  315. rows, err = c.db.Query(selectMessagesSinceIDQuery, topic, rowID)
  316. }
  317. if err != nil {
  318. return nil, err
  319. }
  320. return readMessages(rows)
  321. }
  322. func (c *messageCache) MessagesDue() ([]*message, error) {
  323. rows, err := c.db.Query(selectMessagesDueQuery, time.Now().Unix())
  324. if err != nil {
  325. return nil, err
  326. }
  327. return readMessages(rows)
  328. }
  329. func (c *messageCache) MarkPublished(m *message) error {
  330. _, err := c.db.Exec(updateMessagePublishedQuery, m.ID)
  331. return err
  332. }
  333. func (c *messageCache) MessageCount(topic string) (int, error) {
  334. rows, err := c.db.Query(selectMessageCountForTopicQuery, topic)
  335. if err != nil {
  336. return 0, err
  337. }
  338. defer rows.Close()
  339. var count int
  340. if !rows.Next() {
  341. return 0, errors.New("no rows found")
  342. }
  343. if err := rows.Scan(&count); err != nil {
  344. return 0, err
  345. } else if err := rows.Err(); err != nil {
  346. return 0, err
  347. }
  348. return count, nil
  349. }
  350. func (c *messageCache) Topics() (map[string]*topic, error) {
  351. rows, err := c.db.Query(selectTopicsQuery)
  352. if err != nil {
  353. return nil, err
  354. }
  355. defer rows.Close()
  356. topics := make(map[string]*topic)
  357. for rows.Next() {
  358. var id string
  359. if err := rows.Scan(&id); err != nil {
  360. return nil, err
  361. }
  362. topics[id] = newTopic(id)
  363. }
  364. if err := rows.Err(); err != nil {
  365. return nil, err
  366. }
  367. return topics, nil
  368. }
  369. func (c *messageCache) Prune(olderThan time.Time) error {
  370. _, err := c.db.Exec(pruneMessagesQuery, olderThan.Unix())
  371. return err
  372. }
  373. func (c *messageCache) AttachmentBytesUsed(owner string) (int64, error) {
  374. rows, err := c.db.Query(selectAttachmentsSizeQuery, owner, time.Now().Unix())
  375. if err != nil {
  376. return 0, err
  377. }
  378. defer rows.Close()
  379. var size int64
  380. if !rows.Next() {
  381. return 0, errors.New("no rows found")
  382. }
  383. if err := rows.Scan(&size); err != nil {
  384. return 0, err
  385. } else if err := rows.Err(); err != nil {
  386. return 0, err
  387. }
  388. return size, nil
  389. }
  390. func (c *messageCache) AttachmentsExpired() ([]string, error) {
  391. rows, err := c.db.Query(selectAttachmentsExpiredQuery, time.Now().Unix())
  392. if err != nil {
  393. return nil, err
  394. }
  395. defer rows.Close()
  396. ids := make([]string, 0)
  397. for rows.Next() {
  398. var id string
  399. if err := rows.Scan(&id); err != nil {
  400. return nil, err
  401. }
  402. ids = append(ids, id)
  403. }
  404. if err := rows.Err(); err != nil {
  405. return nil, err
  406. }
  407. return ids, nil
  408. }
  409. func (c *messageCache) MessagesScheduledByTagOrID(topic, selector string) ([]*message, error) {
  410. rows, err := c.db.Query(selectMessagesScheduledByTagOrID, topic, "%"+selector+"%", selector) // Ugly string matching search first, later match exactly
  411. if err != nil {
  412. return nil, err
  413. }
  414. maybeMatchingMessages, err := readMessages(rows)
  415. if err != nil {
  416. return nil, err
  417. }
  418. messages := make([]*message, 0)
  419. for _, m := range maybeMatchingMessages {
  420. if util.InStringList(m.Tags, selector) || m.ID == selector {
  421. messages = append(messages, m)
  422. }
  423. }
  424. return messages, nil
  425. }
  426. func readMessages(rows *sql.Rows) ([]*message, error) {
  427. defer rows.Close()
  428. messages := make([]*message, 0)
  429. for rows.Next() {
  430. var timestamp, attachmentSize, attachmentExpires int64
  431. var priority int
  432. var id, topic, msg, title, tagsStr, click, actionsStr, attachmentName, attachmentType, attachmentURL, attachmentOwner, encoding string
  433. err := rows.Scan(
  434. &id,
  435. &timestamp,
  436. &topic,
  437. &msg,
  438. &title,
  439. &priority,
  440. &tagsStr,
  441. &click,
  442. &actionsStr,
  443. &attachmentName,
  444. &attachmentType,
  445. &attachmentSize,
  446. &attachmentExpires,
  447. &attachmentURL,
  448. &attachmentOwner,
  449. &encoding,
  450. )
  451. if err != nil {
  452. return nil, err
  453. }
  454. var tags []string
  455. if tagsStr != "" {
  456. tags = strings.Split(tagsStr, ",")
  457. }
  458. var actions []*action
  459. if actionsStr != "" {
  460. if err := json.Unmarshal([]byte(actionsStr), &actions); err != nil {
  461. return nil, err
  462. }
  463. }
  464. var att *attachment
  465. if attachmentName != "" && attachmentURL != "" {
  466. att = &attachment{
  467. Name: attachmentName,
  468. Type: attachmentType,
  469. Size: attachmentSize,
  470. Expires: attachmentExpires,
  471. URL: attachmentURL,
  472. Owner: attachmentOwner,
  473. }
  474. }
  475. messages = append(messages, &message{
  476. ID: id,
  477. Time: timestamp,
  478. Event: messageEvent,
  479. Topic: topic,
  480. Message: msg,
  481. Title: title,
  482. Priority: priority,
  483. Tags: tags,
  484. Click: click,
  485. Actions: actions,
  486. Attachment: att,
  487. Encoding: encoding,
  488. })
  489. }
  490. if err := rows.Err(); err != nil {
  491. return nil, err
  492. }
  493. return messages, nil
  494. }
  495. func setupCacheDB(db *sql.DB) error {
  496. // If 'messages' table does not exist, this must be a new database
  497. rowsMC, err := db.Query(selectMessagesCountQuery)
  498. if err != nil {
  499. return setupNewCacheDB(db)
  500. }
  501. rowsMC.Close()
  502. // If 'messages' table exists, check 'schemaVersion' table
  503. schemaVersion := 0
  504. rowsSV, err := db.Query(selectSchemaVersionQuery)
  505. if err == nil {
  506. defer rowsSV.Close()
  507. if !rowsSV.Next() {
  508. return errors.New("cannot determine schema version: cache file may be corrupt")
  509. }
  510. if err := rowsSV.Scan(&schemaVersion); err != nil {
  511. return err
  512. }
  513. rowsSV.Close()
  514. }
  515. // Do migrations
  516. if schemaVersion == currentSchemaVersion {
  517. return nil
  518. } else if schemaVersion == 0 {
  519. return migrateFrom0(db)
  520. } else if schemaVersion == 1 {
  521. return migrateFrom1(db)
  522. } else if schemaVersion == 2 {
  523. return migrateFrom2(db)
  524. } else if schemaVersion == 3 {
  525. return migrateFrom3(db)
  526. } else if schemaVersion == 4 {
  527. return migrateFrom4(db)
  528. } else if schemaVersion == 5 {
  529. return migrateFrom5(db)
  530. }
  531. return fmt.Errorf("unexpected schema version found: %d", schemaVersion)
  532. }
  533. func setupNewCacheDB(db *sql.DB) error {
  534. if _, err := db.Exec(createMessagesTableQuery); err != nil {
  535. return err
  536. }
  537. if _, err := db.Exec(createSchemaVersionTableQuery); err != nil {
  538. return err
  539. }
  540. if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
  541. return err
  542. }
  543. return nil
  544. }
  545. func migrateFrom0(db *sql.DB) error {
  546. log.Print("Migrating cache database schema: from 0 to 1")
  547. if _, err := db.Exec(migrate0To1AlterMessagesTableQuery); err != nil {
  548. return err
  549. }
  550. if _, err := db.Exec(createSchemaVersionTableQuery); err != nil {
  551. return err
  552. }
  553. if _, err := db.Exec(insertSchemaVersion, 1); err != nil {
  554. return err
  555. }
  556. return migrateFrom1(db)
  557. }
  558. func migrateFrom1(db *sql.DB) error {
  559. log.Print("Migrating cache database schema: from 1 to 2")
  560. if _, err := db.Exec(migrate1To2AlterMessagesTableQuery); err != nil {
  561. return err
  562. }
  563. if _, err := db.Exec(updateSchemaVersion, 2); err != nil {
  564. return err
  565. }
  566. return migrateFrom2(db)
  567. }
  568. func migrateFrom2(db *sql.DB) error {
  569. log.Print("Migrating cache database schema: from 2 to 3")
  570. if _, err := db.Exec(migrate2To3AlterMessagesTableQuery); err != nil {
  571. return err
  572. }
  573. if _, err := db.Exec(updateSchemaVersion, 3); err != nil {
  574. return err
  575. }
  576. return migrateFrom3(db)
  577. }
  578. func migrateFrom3(db *sql.DB) error {
  579. log.Print("Migrating cache database schema: from 3 to 4")
  580. if _, err := db.Exec(migrate3To4AlterMessagesTableQuery); err != nil {
  581. return err
  582. }
  583. if _, err := db.Exec(updateSchemaVersion, 4); err != nil {
  584. return err
  585. }
  586. return migrateFrom4(db)
  587. }
  588. func migrateFrom4(db *sql.DB) error {
  589. log.Print("Migrating cache database schema: from 4 to 5")
  590. if _, err := db.Exec(migrate4To5AlterMessagesTableQuery); err != nil {
  591. return err
  592. }
  593. if _, err := db.Exec(updateSchemaVersion, 5); err != nil {
  594. return err
  595. }
  596. return migrateFrom5(db)
  597. }
  598. func migrateFrom5(db *sql.DB) error {
  599. log.Print("Migrating cache database schema: from 5 to 6")
  600. if _, err := db.Exec(migrate5To6AlterMessagesTableQuery); err != nil {
  601. return err
  602. }
  603. if _, err := db.Exec(updateSchemaVersion, 6); err != nil {
  604. return err
  605. }
  606. return nil // Update this when a new version is added
  607. }