| 1 |
package message |
| 2 |
|
| 3 |
import ( |
| 4 |
"database/sql" |
| 5 |
"fmt" |
| 6 |
"path/filepath" |
| 7 |
"sync" |
| 8 |
"time" |
| 9 |
|
| 10 |
_ "github.com/mattn/go-sqlite3" // SQLite driver |
| 11 |
"heckel.io/ntfy/v2/db" |
| 12 |
"heckel.io/ntfy/v2/db/schema" |
| 13 |
"heckel.io/ntfy/v2/util" |
| 14 |
) |
| 15 |
|
| 16 |
// SQLite runtime query constants |
| 17 |
const ( |
| 18 |
sqliteInsertMessageQuery = ` |
| 19 |
INSERT INTO messages (mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_deleted, sender, user, content_type, encoding, published) |
| 20 |
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| 21 |
` |
| 22 |
sqliteSelectScheduledMessageIDsBySeqIDQuery = `SELECT mid FROM messages WHERE topic = ? AND sequence_id = ? AND published = 0` |
| 23 |
sqliteDeleteScheduledBySequenceIDQuery = `DELETE FROM messages WHERE topic = ? AND sequence_id = ? AND published = 0` |
| 24 |
sqliteUpdateMessagesForTopicExpiryQuery = `UPDATE messages SET expires = ? WHERE topic = ?` |
| 25 |
sqliteSelectMessagesByIDQuery = ` |
| 26 |
SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, user, content_type, encoding |
| 27 |
FROM messages |
| 28 |
WHERE mid = ? |
| 29 |
` |
| 30 |
sqliteSelectMessagesSinceTimeQuery = ` |
| 31 |
SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, user, content_type, encoding |
| 32 |
FROM messages |
| 33 |
WHERE topic = ? AND time >= ? AND published = 1 |
| 34 |
ORDER BY time, id |
| 35 |
` |
| 36 |
sqliteSelectMessagesSinceTimeIncludeScheduledQuery = ` |
| 37 |
SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, user, content_type, encoding |
| 38 |
FROM messages |
| 39 |
WHERE topic = ? AND time >= ? |
| 40 |
ORDER BY time, id |
| 41 |
` |
| 42 |
sqliteSelectMessagesSinceIDQuery = ` |
| 43 |
SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, user, content_type, encoding |
| 44 |
FROM messages |
| 45 |
WHERE topic = ? AND id > COALESCE((SELECT id FROM messages WHERE mid = ?), 0) AND published = 1 |
| 46 |
ORDER BY time, id |
| 47 |
` |
| 48 |
sqliteSelectMessagesSinceIDIncludeScheduledQuery = ` |
| 49 |
SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, user, content_type, encoding |
| 50 |
FROM messages |
| 51 |
WHERE topic = ? AND (id > COALESCE((SELECT id FROM messages WHERE mid = ?), 0) OR published = 0) |
| 52 |
ORDER BY time, id |
| 53 |
` |
| 54 |
sqliteSelectMessagesLatestQuery = ` |
| 55 |
SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, user, content_type, encoding |
| 56 |
FROM messages |
| 57 |
WHERE topic = ? AND published = 1 |
| 58 |
ORDER BY time DESC, id DESC |
| 59 |
LIMIT 1 |
| 60 |
` |
| 61 |
sqliteSelectMessagesDueQuery = ` |
| 62 |
SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, user, content_type, encoding |
| 63 |
FROM messages |
| 64 |
WHERE time <= ? AND published = 0 |
| 65 |
ORDER BY time, id |
| 66 |
` |
| 67 |
sqliteUpdateMessagePublishedQuery = `UPDATE messages SET published = 1 WHERE mid = ?` |
| 68 |
sqliteSelectMessagesCountQuery = `SELECT COUNT(*) FROM messages` |
| 69 |
sqliteSelectTopicsQuery = `SELECT topic FROM messages GROUP BY topic` |
| 70 |
|
| 71 |
sqliteDeleteExpiredMessagesQuery = `DELETE FROM messages WHERE mid IN (SELECT mid FROM messages WHERE expires <= ? AND published = 1 LIMIT ?)` |
| 72 |
sqliteMarkExpiredAttachmentsDeletedQuery = `UPDATE messages SET attachment_deleted = 1 WHERE mid IN (SELECT mid FROM messages WHERE attachment_expires > 0 AND attachment_expires <= ? AND attachment_deleted = 0 LIMIT ?)` |
| 73 |
sqliteSelectAttachmentsSizeBySenderQuery = `SELECT IFNULL(SUM(attachment_size), 0) FROM messages WHERE user = '' AND sender = ? AND attachment_expires >= ?` |
| 74 |
sqliteSelectAttachmentsSizeByUserIDQuery = `SELECT IFNULL(SUM(attachment_size), 0) FROM messages WHERE user = ? AND attachment_expires >= ?` |
| 75 |
sqliteSelectAttachmentsWithSizesQuery = `SELECT mid, attachment_size FROM messages WHERE attachment_expires > ? AND attachment_deleted = 0` |
| 76 |
|
| 77 |
sqliteSelectStatsQuery = `SELECT value FROM stats WHERE key = 'messages'` |
| 78 |
sqliteUpdateStatsQuery = `UPDATE stats SET value = ? WHERE key = 'messages'` |
| 79 |
sqliteUpdateMessageTimeQuery = `UPDATE messages SET time = ? WHERE mid = ?` |
| 80 |
) |
| 81 |
|
| 82 |
var sqliteQueries = queries{ |
| 83 |
insertMessage: sqliteInsertMessageQuery, |
| 84 |
selectScheduledMessageIDsBySeqID: sqliteSelectScheduledMessageIDsBySeqIDQuery, |
| 85 |
deleteScheduledBySequenceID: sqliteDeleteScheduledBySequenceIDQuery, |
| 86 |
updateMessagesForTopicExpiry: sqliteUpdateMessagesForTopicExpiryQuery, |
| 87 |
selectMessagesByID: sqliteSelectMessagesByIDQuery, |
| 88 |
selectMessagesSinceTime: sqliteSelectMessagesSinceTimeQuery, |
| 89 |
selectMessagesSinceTimeScheduled: sqliteSelectMessagesSinceTimeIncludeScheduledQuery, |
| 90 |
selectMessagesSinceID: sqliteSelectMessagesSinceIDQuery, |
| 91 |
selectMessagesSinceIDScheduled: sqliteSelectMessagesSinceIDIncludeScheduledQuery, |
| 92 |
selectMessagesLatest: sqliteSelectMessagesLatestQuery, |
| 93 |
selectMessagesDue: sqliteSelectMessagesDueQuery, |
| 94 |
deleteExpiredMessages: sqliteDeleteExpiredMessagesQuery, |
| 95 |
updateMessagePublished: sqliteUpdateMessagePublishedQuery, |
| 96 |
selectMessagesCount: sqliteSelectMessagesCountQuery, |
| 97 |
selectTopics: sqliteSelectTopicsQuery, |
| 98 |
markExpiredAttachmentsDeleted: sqliteMarkExpiredAttachmentsDeletedQuery, |
| 99 |
selectAttachmentsSizeBySender: sqliteSelectAttachmentsSizeBySenderQuery, |
| 100 |
selectAttachmentsSizeByUserID: sqliteSelectAttachmentsSizeByUserIDQuery, |
| 101 |
selectAttachmentsWithSizes: sqliteSelectAttachmentsWithSizesQuery, |
| 102 |
selectStats: sqliteSelectStatsQuery, |
| 103 |
updateStats: sqliteUpdateStatsQuery, |
| 104 |
updateMessageTime: sqliteUpdateMessageTimeQuery, |
| 105 |
} |
| 106 |
|
| 107 |
// NewSQLiteStore creates a SQLite file-backed cache |
| 108 |
func NewSQLiteStore(filename, startupQueries string, cacheDuration time.Duration, batchSize int, batchTimeout time.Duration, nop bool) (*Cache, error) { |
| 109 |
parentDir := filepath.Dir(filename) |
| 110 |
if !util.FileExists(parentDir) { |
| 111 |
return nil, fmt.Errorf("cache database directory %s does not exist or is not accessible", parentDir) |
| 112 |
} |
| 113 |
d, err := sql.Open("sqlite3", filename) |
| 114 |
if err != nil { |
| 115 |
return nil, err |
| 116 |
} |
| 117 |
if err := runSQLiteStartupQueries(d, startupQueries); err != nil { |
| 118 |
return nil, err |
| 119 |
} |
| 120 |
if err := schema.Migrate(d, schema.SQLite, schemaStore, sqliteCurrentSchemaVersion, sqliteCreateTables, sqliteMigrations(cacheDuration)); err != nil { |
| 121 |
return nil, err |
| 122 |
} |
| 123 |
return newCache(db.New(&db.Host{DB: d}, nil), sqliteQueries, &sync.Mutex{}, batchSize, batchTimeout, nop), nil |
| 124 |
} |
| 125 |
|
| 126 |
// NewMemStore creates an in-memory cache |
| 127 |
func NewMemStore() (*Cache, error) { |
| 128 |
return NewSQLiteStore(createMemoryFilename(), "", 0, 0, 0, false) |
| 129 |
} |
| 130 |
|
| 131 |
// NewNopStore creates an in-memory cache that discards all messages; |
| 132 |
// it is always empty and can be used if caching is entirely disabled |
| 133 |
func NewNopStore() (*Cache, error) { |
| 134 |
return NewSQLiteStore(createMemoryFilename(), "", 0, 0, 0, true) |
| 135 |
} |
| 136 |
|
| 137 |
// createMemoryFilename creates a unique memory filename to use for the SQLite backend. |
| 138 |
// From mattn/go-sqlite3: "Each connection to ":memory:" opens a brand new in-memory |
| 139 |
// sql database, so if the stdlib's sql engine happens to open another connection and |
| 140 |
// you've only specified ":memory:", that connection will see a brand new database. |
| 141 |
// A workaround is to use "file::memory:?cache=shared" (or "file:foobar?mode=memory&cache=shared"). |
| 142 |
// Every connection to this string will point to the same in-memory database." |
| 143 |
func createMemoryFilename() string { |
| 144 |
return fmt.Sprintf("file:%s?mode=memory&cache=shared", util.RandomString(10)) |
| 145 |
} |