migration/
m20251124_00001_tickets_create_ticket_stats.rs1use sea_orm_migration::prelude::*;
2
3#[derive(DeriveMigrationName)]
4pub struct Migration;
5
6#[async_trait::async_trait]
7impl MigrationTrait for Migration {
8 async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
9 manager
10 .create_table(
11 Table::create()
12 .table(TicketStatistics::Table)
13 .if_not_exists()
14 .col(
15 ColumnDef::new(TicketStatistics::Id)
16 .integer()
17 .not_null()
18 .auto_increment()
19 .primary_key(),
20 )
21 .col(
22 ColumnDef::new(TicketStatistics::ChannelId)
23 .string_len(64)
24 .not_null()
25 .unique_key(),
26 )
27 .col(ColumnDef::new(TicketStatistics::LastUpdated).timestamp().null())
28 .col(
29 ColumnDef::new(TicketStatistics::WinningTickets)
30 .not_null()
31 .integer()
32 .default(0),
33 )
34 .col(
35 ColumnDef::new(TicketStatistics::RedeemedValue)
36 .binary_len(12)
37 .not_null()
38 .default(vec![0u8; 12]),
39 )
40 .col(
41 ColumnDef::new(TicketStatistics::NeglectedValue)
42 .binary_len(12)
43 .not_null()
44 .default(vec![0u8; 12]),
45 )
46 .col(
47 ColumnDef::new(TicketStatistics::RejectedValue)
48 .binary_len(12)
49 .not_null()
50 .default(vec![0u8; 12]),
51 )
52 .to_owned(),
53 )
54 .await?;
55
56 let conn = manager.get_connection();
57
58 conn.execute_unprepared(
59 r#"
60 CREATE TRIGGER IF NOT EXISTS trig_ticket_stats_update_timestamp
61 AFTER UPDATE
62 ON ticket_statistics
63 FOR EACH ROW
64 WHEN OLD.last_updated IS NULL OR NEW.last_updated < OLD.last_updated --- avoid infinite loop
65 BEGIN
66 UPDATE ticket_statistics SET last_updated=CURRENT_TIMESTAMP WHERE id=OLD.id;
67 END;
68 "#,
69 )
70 .await?;
71
72 Ok(())
73 }
74
75 async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
76 let conn = manager.get_connection();
77
78 conn.execute_unprepared("DROP TRIGGER trig_ticket_stats_update_timestamp;")
79 .await?;
80
81 manager
82 .drop_table(Table::drop().table(TicketStatistics::Table).to_owned())
83 .await
84 }
85}
86
87#[derive(DeriveIden)]
88enum TicketStatistics {
89 Table,
90 Id,
91 ChannelId,
92 LastUpdated,
93 WinningTickets,
94 RedeemedValue,
95 NeglectedValue,
96 RejectedValue,
97}