matrix-bridge-telegram 0.1.0

A bridge between Matrix and Telegram written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use std::sync::Arc;

#[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
use diesel::RunQueryDsl;
#[cfg(feature = "mysql")]
use diesel::mysql::MysqlConnection;
#[cfg(feature = "postgres")]
use diesel::pg::PgConnection;
#[cfg(any(feature = "postgres", feature = "mysql"))]
use diesel::r2d2::{self, ConnectionManager};

use crate::config::{DatabaseConfig as ConfigDatabaseConfig, DbType as ConfigDbType};
use crate::db::stores::{
    InMemoryMessageStore, InMemoryPortalStore, InMemoryReactionStore, InMemoryTelegramFileStore,
    InMemoryUserStore,
};
use crate::db::{
    DatabaseError, MessageStore, PortalStore, ReactionStore, TelegramFileStore, UserStore,
};

#[cfg(feature = "postgres")]
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
#[cfg(feature = "mysql")]
pub type MysqlPool = r2d2::Pool<ConnectionManager<MysqlConnection>>;

#[cfg(feature = "sqlite")]
use diesel::Connection;
#[cfg(feature = "sqlite")]
use diesel::sqlite::SqliteConnection;

#[derive(Clone)]
pub struct DatabaseManager {
    #[cfg(feature = "postgres")]
    postgres_pool: Option<Pool>,
    #[cfg(feature = "mysql")]
    mysql_pool: Option<MysqlPool>,
    #[cfg(feature = "sqlite")]
    sqlite_path: Option<String>,
    user_store: Arc<dyn UserStore>,
    portal_store: Arc<dyn PortalStore>,
    message_store: Arc<dyn MessageStore>,
    reaction_store: Arc<dyn ReactionStore>,
    telegram_file_store: Arc<dyn TelegramFileStore>,
    db_type: DbType,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DbType {
    Postgres,
    Sqlite,
    Mysql,
}

impl From<ConfigDbType> for DbType {
    fn from(value: ConfigDbType) -> Self {
        match value {
            ConfigDbType::Postgres => DbType::Postgres,
            ConfigDbType::Sqlite => DbType::Sqlite,
            ConfigDbType::Mysql => DbType::Mysql,
        }
    }
}

impl DatabaseManager {
    pub async fn new(config: &ConfigDatabaseConfig) -> Result<Self, DatabaseError> {
        let db_type = DbType::from(config.db_type());

        match db_type {
            #[cfg(feature = "postgres")]
            DbType::Postgres => {
                let connection_string = config.connection_string();
                let max_connections = config.max_connections();
                let min_connections = config.min_connections();

                let manager = ConnectionManager::<PgConnection>::new(connection_string);

                let builder = r2d2::Pool::builder()
                    .max_size(max_connections.unwrap_or(10))
                    .min_idle(Some(min_connections.unwrap_or(1)));

                let pool = builder
                    .build(manager)
                    .map_err(|e| DatabaseError::Connection(e.to_string()))?;

                let user_store = Arc::new(InMemoryUserStore::new());
                let portal_store = Arc::new(InMemoryPortalStore::new());
                let message_store = Arc::new(InMemoryMessageStore::new());
                let reaction_store = Arc::new(InMemoryReactionStore::new());
                let telegram_file_store = Arc::new(InMemoryTelegramFileStore::new());

                Ok(Self {
                    postgres_pool: Some(pool),
                    #[cfg(feature = "mysql")]
                    mysql_pool: None,
                    #[cfg(feature = "sqlite")]
                    sqlite_path: None,
                    user_store,
                    portal_store,
                    message_store,
                    reaction_store,
                    telegram_file_store,
                    db_type,
                })
            }
            #[cfg(feature = "sqlite")]
            DbType::Sqlite => {
                let path = config.sqlite_path().unwrap();
                let path_arc = Arc::new(path.clone());

                let user_store = Arc::new(InMemoryUserStore::new());
                let portal_store = Arc::new(InMemoryPortalStore::new());
                let message_store = Arc::new(InMemoryMessageStore::new());
                let reaction_store = Arc::new(InMemoryReactionStore::new());
                let telegram_file_store = Arc::new(InMemoryTelegramFileStore::new());

                Ok(Self {
                    #[cfg(feature = "postgres")]
                    postgres_pool: None,
                    #[cfg(feature = "mysql")]
                    mysql_pool: None,
                    sqlite_path: Some(path),
                    user_store,
                    portal_store,
                    message_store,
                    reaction_store,
                    telegram_file_store,
                    db_type,
                })
            }
            #[cfg(feature = "mysql")]
            DbType::Mysql => {
                let connection_string = config.connection_string();
                let max_connections = config.max_connections();
                let min_connections = config.min_connections();

                let manager = ConnectionManager::<MysqlConnection>::new(connection_string);

                let builder = r2d2::Pool::builder()
                    .max_size(max_connections.unwrap_or(10))
                    .min_idle(Some(min_connections.unwrap_or(1)));

                let pool = builder
                    .build(manager)
                    .map_err(|e| DatabaseError::Connection(e.to_string()))?;

                let user_store = Arc::new(InMemoryUserStore::new());
                let portal_store = Arc::new(InMemoryPortalStore::new());
                let message_store = Arc::new(InMemoryMessageStore::new());
                let reaction_store = Arc::new(InMemoryReactionStore::new());
                let telegram_file_store = Arc::new(InMemoryTelegramFileStore::new());

                Ok(Self {
                    #[cfg(feature = "postgres")]
                    postgres_pool: None,
                    mysql_pool: Some(pool),
                    #[cfg(feature = "sqlite")]
                    sqlite_path: None,
                    user_store,
                    portal_store,
                    message_store,
                    reaction_store,
                    telegram_file_store,
                    db_type,
                })
            }
            #[cfg(not(feature = "postgres"))]
            DbType::Postgres => {
                return Err(DatabaseError::Connection(
                    "PostgreSQL feature not enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "sqlite"))]
            DbType::Sqlite => {
                return Err(DatabaseError::Connection(
                    "SQLite feature not enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "mysql"))]
            DbType::Mysql => {
                return Err(DatabaseError::Connection(
                    "MySQL feature not enabled".to_string(),
                ));
            }
        }
    }

    #[cfg(feature = "sqlite")]
    pub fn new_in_memory() -> Result<Self, DatabaseError> {
        use std::sync::Arc;

        let user_store = Arc::new(InMemoryUserStore::new());
        let portal_store = Arc::new(InMemoryPortalStore::new());
        let message_store = Arc::new(InMemoryMessageStore::new());
        let reaction_store = Arc::new(InMemoryReactionStore::new());
        let telegram_file_store = Arc::new(InMemoryTelegramFileStore::new());

        Ok(Self {
            #[cfg(feature = "postgres")]
            postgres_pool: None,
            #[cfg(feature = "mysql")]
            mysql_pool: None,
            sqlite_path: Some(":memory:".to_string()),
            user_store,
            portal_store,
            message_store,
            reaction_store,
            telegram_file_store,
            db_type: DbType::Sqlite,
        })
    }

    pub async fn migrate(&self) -> Result<(), DatabaseError> {
        match self.db_type {
            #[cfg(feature = "postgres")]
            DbType::Postgres => {
                let pool = self.postgres_pool.as_ref().unwrap();
                return Self::migrate_postgres(pool).await;
            }
            #[cfg(feature = "sqlite")]
            DbType::Sqlite => {
                let path = self.sqlite_path.as_ref().unwrap();
                return Self::migrate_sqlite(path).await;
            }
            #[cfg(feature = "mysql")]
            DbType::Mysql => {
                let pool = self.mysql_pool.as_ref().unwrap();
                return Self::migrate_mysql(pool).await;
            }
            #[cfg(not(feature = "postgres"))]
            DbType::Postgres => {
                return Err(DatabaseError::Migration(
                    "PostgreSQL feature not enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "sqlite"))]
            DbType::Sqlite => {
                return Err(DatabaseError::Migration(
                    "SQLite feature not enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "mysql"))]
            DbType::Mysql => {
                return Err(DatabaseError::Migration(
                    "MySQL feature not enabled".to_string(),
                ));
            }
        }
    }

    #[cfg(feature = "postgres")]
    async fn migrate_postgres(pool: &Pool) -> Result<(), DatabaseError> {
        let pool = pool.clone();
        tokio::task::spawn_blocking(move || {
            let mut conn = pool
                .get()
                .map_err(|e| DatabaseError::Connection(e.to_string()))?;

            let statements = [
                r#"
                CREATE TABLE IF NOT EXISTS user_mappings (
                    id BIGSERIAL PRIMARY KEY,
                    matrix_user_id TEXT NOT NULL UNIQUE,
                    telegram_user_id BIGINT NOT NULL UNIQUE,
                    telegram_username TEXT,
                    telegram_first_name TEXT,
                    telegram_last_name TEXT,
                    telegram_phone TEXT,
                    telegram_avatar TEXT,
                    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
                    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS portal (
                    id BIGSERIAL PRIMARY KEY,
                    matrix_room_id TEXT NOT NULL UNIQUE,
                    telegram_chat_id BIGINT NOT NULL UNIQUE,
                    telegram_chat_type TEXT NOT NULL,
                    telegram_chat_title TEXT,
                    telegram_chat_username TEXT,
                    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
                    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS message_mappings (
                    id BIGSERIAL PRIMARY KEY,
                    telegram_message_id BIGINT NOT NULL,
                    telegram_chat_id BIGINT NOT NULL,
                    matrix_room_id TEXT NOT NULL,
                    matrix_event_id TEXT NOT NULL,
                    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
                    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
                    UNIQUE(telegram_chat_id, telegram_message_id)
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS reaction_mappings (
                    id BIGSERIAL PRIMARY KEY,
                    telegram_message_id BIGINT NOT NULL,
                    telegram_chat_id BIGINT NOT NULL,
                    telegram_user_id BIGINT NOT NULL,
                    reaction_emoji TEXT NOT NULL,
                    matrix_event_id TEXT NOT NULL,
                    matrix_room_id TEXT NOT NULL,
                    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
                    UNIQUE(telegram_chat_id, telegram_message_id, telegram_user_id, reaction_emoji)
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS telegram_files (
                    id BIGSERIAL PRIMARY KEY,
                    telegram_file_id TEXT NOT NULL,
                    telegram_file_unique_id TEXT NOT NULL UNIQUE,
                    mxc_url TEXT NOT NULL,
                    mime_type TEXT,
                    file_name TEXT,
                    file_size BIGINT,
                    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS processed_events (
                    id BIGSERIAL PRIMARY KEY,
                    event_id TEXT NOT NULL UNIQUE,
                    event_type TEXT NOT NULL,
                    source TEXT NOT NULL,
                    processed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
                )
                "#,
                "CREATE INDEX IF NOT EXISTS idx_user_mappings_matrix_id ON user_mappings(matrix_user_id)",
                "CREATE INDEX IF NOT EXISTS idx_user_mappings_telegram_id ON user_mappings(telegram_user_id)",
                "CREATE INDEX IF NOT EXISTS idx_portal_matrix_room ON portal(matrix_room_id)",
                "CREATE INDEX IF NOT EXISTS idx_portal_telegram_chat ON portal(telegram_chat_id)",
                "CREATE INDEX IF NOT EXISTS idx_message_mappings_telegram ON message_mappings(telegram_chat_id, telegram_message_id)",
                "CREATE INDEX IF NOT EXISTS idx_message_mappings_matrix ON message_mappings(matrix_room_id, matrix_event_id)",
                "CREATE INDEX IF NOT EXISTS idx_reaction_mappings_telegram ON reaction_mappings(telegram_chat_id, telegram_message_id)",
                "CREATE INDEX IF NOT EXISTS idx_telegram_files_unique ON telegram_files(telegram_file_unique_id)",
                "CREATE INDEX IF NOT EXISTS idx_processed_events_event_id ON processed_events(event_id)",
            ];

            for statement in statements {
                diesel::sql_query(statement)
                    .execute(&mut conn)
                    .map_err(|e| DatabaseError::Migration(e.to_string()))?;
            }

            Ok(())
        })
        .await
        .map_err(|e| DatabaseError::Migration(format!("migration task failed: {e}")))?
    }

    #[cfg(feature = "mysql")]
    async fn migrate_mysql(pool: &MysqlPool) -> Result<(), DatabaseError> {
        let pool = pool.clone();
        tokio::task::spawn_blocking(move || {
            let mut conn = pool
                .get()
                .map_err(|e| DatabaseError::Connection(e.to_string()))?;

            let statements = [
                r#"
                CREATE TABLE IF NOT EXISTS user_mappings (
                    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    matrix_user_id VARCHAR(255) NOT NULL UNIQUE,
                    telegram_user_id BIGINT NOT NULL UNIQUE,
                    telegram_username VARCHAR(255) NULL,
                    telegram_first_name VARCHAR(255) NULL,
                    telegram_last_name VARCHAR(255) NULL,
                    telegram_phone VARCHAR(32) NULL,
                    telegram_avatar TEXT NULL,
                    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
                    updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS portal (
                    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    matrix_room_id VARCHAR(255) NOT NULL UNIQUE,
                    telegram_chat_id BIGINT NOT NULL UNIQUE,
                    telegram_chat_type VARCHAR(32) NOT NULL,
                    telegram_chat_title VARCHAR(255) NULL,
                    telegram_chat_username VARCHAR(255) NULL,
                    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
                    updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS message_mappings (
                    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    telegram_message_id BIGINT NOT NULL,
                    telegram_chat_id BIGINT NOT NULL,
                    matrix_room_id VARCHAR(255) NOT NULL,
                    matrix_event_id VARCHAR(255) NOT NULL,
                    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
                    updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
                    UNIQUE KEY uk_telegram_message (telegram_chat_id, telegram_message_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS reaction_mappings (
                    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    telegram_message_id BIGINT NOT NULL,
                    telegram_chat_id BIGINT NOT NULL,
                    telegram_user_id BIGINT NOT NULL,
                    reaction_emoji VARCHAR(64) NOT NULL,
                    matrix_event_id VARCHAR(255) NOT NULL,
                    matrix_room_id VARCHAR(255) NOT NULL,
                    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
                    UNIQUE KEY uk_telegram_reaction (telegram_chat_id, telegram_message_id, telegram_user_id, reaction_emoji)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS telegram_files (
                    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    telegram_file_id VARCHAR(255) NOT NULL,
                    telegram_file_unique_id VARCHAR(255) NOT NULL UNIQUE,
                    mxc_url VARCHAR(1024) NOT NULL,
                    mime_type VARCHAR(128) NULL,
                    file_name VARCHAR(255) NULL,
                    file_size BIGINT NULL,
                    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                "#,
            ];

            for statement in statements {
                diesel::sql_query(statement)
                    .execute(&mut conn)
                    .map_err(|e| DatabaseError::Migration(e.to_string()))?;
            }

            Ok(())
        })
        .await
        .map_err(|e| DatabaseError::Migration(format!("migration task failed: {e}")))?
    }

    #[cfg(feature = "sqlite")]
    async fn migrate_sqlite(path: &str) -> Result<(), DatabaseError> {
        let path = path.to_string();
        tokio::task::spawn_blocking(move || {
            let conn_string = format!("sqlite://{}", path);
            let mut conn = SqliteConnection::establish(&conn_string)
                .map_err(|e| DatabaseError::Connection(e.to_string()))?;

            let statements = [
                r#"
                CREATE TABLE IF NOT EXISTS user_mappings (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    matrix_user_id TEXT NOT NULL UNIQUE,
                    telegram_user_id INTEGER NOT NULL UNIQUE,
                    telegram_username TEXT,
                    telegram_first_name TEXT,
                    telegram_last_name TEXT,
                    telegram_phone TEXT,
                    telegram_avatar TEXT,
                    created_at TEXT NOT NULL DEFAULT (datetime('now')),
                    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS portal (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    matrix_room_id TEXT NOT NULL UNIQUE,
                    telegram_chat_id INTEGER NOT NULL UNIQUE,
                    telegram_chat_type TEXT NOT NULL,
                    telegram_chat_title TEXT,
                    telegram_chat_username TEXT,
                    created_at TEXT NOT NULL DEFAULT (datetime('now')),
                    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS message_mappings (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    telegram_message_id INTEGER NOT NULL,
                    telegram_chat_id INTEGER NOT NULL,
                    matrix_room_id TEXT NOT NULL,
                    matrix_event_id TEXT NOT NULL,
                    created_at TEXT NOT NULL DEFAULT (datetime('now')),
                    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
                    UNIQUE(telegram_chat_id, telegram_message_id)
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS reaction_mappings (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    telegram_message_id INTEGER NOT NULL,
                    telegram_chat_id INTEGER NOT NULL,
                    telegram_user_id INTEGER NOT NULL,
                    reaction_emoji TEXT NOT NULL,
                    matrix_event_id TEXT NOT NULL,
                    matrix_room_id TEXT NOT NULL,
                    created_at TEXT NOT NULL DEFAULT (datetime('now')),
                    UNIQUE(telegram_chat_id, telegram_message_id, telegram_user_id, reaction_emoji)
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS telegram_files (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    telegram_file_id TEXT NOT NULL,
                    telegram_file_unique_id TEXT NOT NULL UNIQUE,
                    mxc_url TEXT NOT NULL,
                    mime_type TEXT,
                    file_name TEXT,
                    file_size INTEGER,
                    created_at TEXT NOT NULL DEFAULT (datetime('now'))
                )
                "#,
                r#"
                CREATE TABLE IF NOT EXISTS processed_events (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    event_id TEXT NOT NULL UNIQUE,
                    event_type TEXT NOT NULL,
                    source TEXT NOT NULL,
                    processed_at TEXT NOT NULL DEFAULT (datetime('now'))
                )
                "#,
                "CREATE INDEX IF NOT EXISTS idx_user_mappings_matrix_id ON user_mappings(matrix_user_id)",
                "CREATE INDEX IF NOT EXISTS idx_user_mappings_telegram_id ON user_mappings(telegram_user_id)",
                "CREATE INDEX IF NOT EXISTS idx_portal_matrix_room ON portal(matrix_room_id)",
                "CREATE INDEX IF NOT EXISTS idx_portal_telegram_chat ON portal(telegram_chat_id)",
                "CREATE INDEX IF NOT EXISTS idx_message_mappings_telegram ON message_mappings(telegram_chat_id, telegram_message_id)",
                "CREATE INDEX IF NOT EXISTS idx_message_mappings_matrix ON message_mappings(matrix_room_id, matrix_event_id)",
                "CREATE INDEX IF NOT EXISTS idx_reaction_mappings_telegram ON reaction_mappings(telegram_chat_id, telegram_message_id)",
                "CREATE INDEX IF NOT EXISTS idx_telegram_files_unique ON telegram_files(telegram_file_unique_id)",
                "CREATE INDEX IF NOT EXISTS idx_processed_events_event_id ON processed_events(event_id)",
            ];

            for statement in statements {
                diesel::sql_query(statement)
                    .execute(&mut conn)
                    .map_err(|e| DatabaseError::Migration(e.to_string()))?;
            }

            Ok(())
        })
        .await
        .map_err(|e| DatabaseError::Migration(format!("migration task failed: {e}")))?
    }

    pub fn user_store(&self) -> Arc<dyn UserStore> {
        self.user_store.clone()
    }

    pub fn portal_store(&self) -> Arc<dyn PortalStore> {
        self.portal_store.clone()
    }

    pub fn message_store(&self) -> Arc<dyn MessageStore> {
        self.message_store.clone()
    }

    pub fn reaction_store(&self) -> Arc<dyn ReactionStore> {
        self.reaction_store.clone()
    }

    pub fn telegram_file_store(&self) -> Arc<dyn TelegramFileStore> {
        self.telegram_file_store.clone()
    }

    #[cfg(feature = "postgres")]
    pub fn pool(&self) -> Option<&Pool> {
        self.postgres_pool.as_ref()
    }

    pub fn db_type(&self) -> DbType {
        self.db_type
    }
}