|
| 1 | +// Copyright (c) 2026 Tulir Asokan |
| 2 | +// |
| 3 | +// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | +// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | +// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 | + |
| 7 | +package sql_store_upgrade |
| 8 | + |
| 9 | +import ( |
| 10 | + "context" |
| 11 | + |
| 12 | + "go.mau.fi/util/dbutil" |
| 13 | +) |
| 14 | + |
| 15 | +var DropCryptoMessageIndexForRewrite = false |
| 16 | + |
| 17 | +func init() { |
| 18 | + const rewritePostgres = ` |
| 19 | + ALTER TABLE crypto_message_index DROP CONSTRAINT crypto_message_index_pkey; |
| 20 | + ALTER TABLE crypto_message_index DROP COLUMN sender_key; |
| 21 | + ALTER TABLE crypto_message_index ADD PRIMARY KEY (session_id, "index"); |
| 22 | + ` |
| 23 | + const createNewSQLite = ` |
| 24 | + CREATE TABLE new_crypto_message_index ( |
| 25 | + session_id CHAR(43), |
| 26 | + "index" INTEGER, |
| 27 | + event_id TEXT NOT NULL, |
| 28 | + timestamp BIGINT NOT NULL, |
| 29 | + PRIMARY KEY (session_id, "index") |
| 30 | + ); |
| 31 | + ` |
| 32 | + const migrateSQLite = ` |
| 33 | + INSERT INTO new_crypto_message_index (session_id, "index", event_id, timestamp) |
| 34 | + SELECT session_id, "index", event_id, timestamp FROM crypto_message_index; |
| 35 | + ` |
| 36 | + const dropSQLite = ` |
| 37 | + DROP TABLE crypto_message_index; |
| 38 | + ALTER TABLE new_crypto_message_index RENAME TO crypto_message_index; |
| 39 | + ` |
| 40 | + Table.Register(-1, 20, 20, "Remove sender_key from crypto_message_index", dbutil.TxnModeOn, func(ctx context.Context, db *dbutil.Database) (err error) { |
| 41 | + switch db.Dialect { |
| 42 | + case dbutil.Postgres: |
| 43 | + _, err = db.Exec(ctx, rewritePostgres) |
| 44 | + case dbutil.SQLite: |
| 45 | + if DropCryptoMessageIndexForRewrite { |
| 46 | + _, err = db.Exec(ctx, createNewSQLite+dropSQLite) |
| 47 | + } else { |
| 48 | + _, err = db.Exec(ctx, createNewSQLite+migrateSQLite+dropSQLite) |
| 49 | + } |
| 50 | + default: |
| 51 | + err = dbutil.ErrUnsupportedDialect |
| 52 | + } |
| 53 | + return |
| 54 | + }) |
| 55 | +} |
0 commit comments