11use chrono:: NaiveDateTime ;
2+ use diesel:: prelude:: * ;
3+ use diesel:: {
4+ deserialize:: { self , FromSql } ,
5+ expression:: { bound:: Bound , AsExpression } ,
6+ pg:: Pg ,
7+ sql_types:: Integer ,
8+ } ;
29
310use crate :: models:: { ApiToken , User , Version } ;
411use crate :: schema:: * ;
512
6- #[ derive( Debug , Clone , Copy ) ]
13+ #[ derive( Debug , Clone , Copy , FromSqlRow ) ]
714#[ repr( u32 ) ]
815pub enum VersionAction {
916 Publish = 0 ,
1017 Yank = 1 ,
1118 Unyank = 2 ,
1219}
1320
21+ impl Into < i32 > for VersionAction {
22+ fn into ( self ) -> i32 {
23+ match self {
24+ VersionAction :: Publish => 0 ,
25+ VersionAction :: Yank => 1 ,
26+ VersionAction :: Unyank => 2 ,
27+ }
28+ }
29+ }
30+
31+ impl FromSql < Integer , Pg > for VersionAction {
32+ fn from_sql ( bytes : Option < & [ u8 ] > ) -> deserialize:: Result < Self > {
33+ match <i32 as FromSql < Integer , Pg > >:: from_sql ( bytes) ? {
34+ 0 => Ok ( VersionAction :: Publish ) ,
35+ 1 => Ok ( VersionAction :: Yank ) ,
36+ 2 => Ok ( VersionAction :: Unyank ) ,
37+ n => Err ( format ! ( "unknown version action: {}" , n) . into ( ) ) ,
38+ }
39+ }
40+ }
41+
42+ impl AsExpression < Integer > for VersionAction {
43+ type Expression = Bound < Integer , i32 > ;
44+
45+ fn as_expression ( self ) -> Self :: Expression {
46+ Bound :: new ( self . into ( ) )
47+ }
48+ }
49+
50+ impl < ' a > AsExpression < Integer > for & ' a VersionAction {
51+ type Expression = Bound < Integer , i32 > ;
52+
53+ fn as_expression ( self ) -> Self :: Expression {
54+ Bound :: new ( ( * self ) . into ( ) )
55+ }
56+ }
57+
1458#[ derive( Debug , Clone , Copy , Queryable , Identifiable , Associations ) ]
1559#[ belongs_to( Version ) ]
1660#[ belongs_to( User , foreign_key = "owner_id" ) ]
@@ -20,7 +64,38 @@ pub struct VersionOwnerAction {
2064 pub id : i32 ,
2165 pub version_id : i32 ,
2266 pub owner_id : i32 ,
23- pub owner_token_id : i32 ,
67+ pub owner_token_id : Option < i32 > ,
2468 pub action : VersionAction ,
2569 pub time : NaiveDateTime ,
2670}
71+
72+ #[ derive( Copy , Clone , Debug , Insertable ) ]
73+ #[ table_name = "version_owner_actions" ]
74+ pub struct NewVersionOwnerAction {
75+ pub version_id : i32 ,
76+ pub owner_id : i32 ,
77+ pub owner_token_id : Option < i32 > ,
78+ pub action : VersionAction ,
79+ }
80+
81+ impl NewVersionOwnerAction {
82+ pub fn new (
83+ version_id : i32 ,
84+ owner_id : i32 ,
85+ owner_token_id : Option < i32 > ,
86+ action : VersionAction ,
87+ ) -> Self {
88+ Self {
89+ version_id,
90+ owner_id,
91+ owner_token_id,
92+ action,
93+ }
94+ }
95+
96+ pub fn save ( & self , conn : & PgConnection ) -> QueryResult < VersionOwnerAction > {
97+ diesel:: insert_into ( version_owner_actions:: table)
98+ . values ( self )
99+ . get_result ( conn)
100+ }
101+ }
0 commit comments