@@ -4,6 +4,7 @@ use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
4
4
use diesel_async:: sync_connection_wrapper:: SyncConnectionWrapper ;
5
5
use diesel_async:: { AsyncConnection , RunQueryDsl , SimpleAsyncConnection } ;
6
6
use diesel_migrations:: { embed_migrations, EmbeddedMigrations , MigrationHarness } ;
7
+ use futures_util:: FutureExt ;
7
8
8
9
// ordinary diesel model setup
9
10
@@ -15,7 +16,7 @@ table! {
15
16
}
16
17
17
18
#[ allow( dead_code) ]
18
- #[ derive( Debug , Queryable , Selectable ) ]
19
+ #[ derive( Debug , Queryable , QueryableByName , Selectable ) ]
19
20
#[ diesel( table_name = users) ]
20
21
struct User {
21
22
id : i32 ,
47
48
. map_err ( |e| Box :: new ( e) as Box < dyn std:: error:: Error > )
48
49
}
49
50
51
+ async fn transaction (
52
+ async_conn : & mut SyncConnectionWrapper < InnerConnection > ,
53
+ old_name : & str ,
54
+ new_name : & str ,
55
+ ) -> Result < Vec < User > , diesel:: result:: Error > {
56
+ async_conn
57
+ . transaction :: < Vec < User > , diesel:: result:: Error , _ > ( |c| {
58
+ Box :: pin ( async {
59
+ if old_name. is_empty ( ) {
60
+ Ok ( Vec :: new ( ) )
61
+ } else {
62
+ diesel:: sql_query (
63
+ r#"
64
+ update
65
+ users
66
+ set
67
+ name = ?2
68
+ where
69
+ name == ?1
70
+ returning *
71
+ "# ,
72
+ )
73
+ . bind :: < diesel:: sql_types:: Text , _ > ( old_name)
74
+ . bind :: < diesel:: sql_types:: Text , _ > ( new_name)
75
+ . load ( c)
76
+ . await
77
+ }
78
+ } )
79
+ } )
80
+ . await
81
+ }
82
+
50
83
#[ tokio:: main]
51
84
async fn main ( ) -> Result < ( ) , Box < dyn std:: error:: Error > > {
52
85
let db_url = std:: env:: var ( "DATABASE_URL" ) . expect ( "Env var `DATABASE_URL` not set" ) ;
@@ -86,5 +119,32 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
86
119
. await ?;
87
120
println ! ( "{data:?}" ) ;
88
121
122
+ // let changed = transaction(&mut sync_wrapper, "iLuke", "JustLuke").await?;
123
+ // println!("Changed {changed:?}");
124
+
125
+ // create an async connection for the migrations
126
+ let mut conn_a: SyncConnectionWrapper < InnerConnection > = establish ( & db_url) . await ?;
127
+ let mut conn_b: SyncConnectionWrapper < InnerConnection > = establish ( & db_url) . await ?;
128
+
129
+ tokio:: spawn ( async move {
130
+ loop {
131
+ let changed = transaction ( & mut conn_a, "iLuke" , "JustLuke" ) . await ;
132
+ println ! ( "Changed {changed:?}" ) ;
133
+ std:: thread:: sleep ( std:: time:: Duration :: from_secs ( 1 ) ) ;
134
+ }
135
+ } ) ;
136
+
137
+ tokio:: spawn ( async move {
138
+ loop {
139
+ let changed = transaction ( & mut conn_b, "JustLuke" , "iLuke" ) . await ;
140
+ println ! ( "Changed {changed:?}" ) ;
141
+ std:: thread:: sleep ( std:: time:: Duration :: from_secs ( 1 ) ) ;
142
+ }
143
+ } ) ;
144
+
145
+ loop {
146
+ std:: thread:: sleep ( std:: time:: Duration :: from_secs ( 1 ) ) ;
147
+ }
148
+
89
149
Ok ( ( ) )
90
150
}
0 commit comments