forked from launchbadge/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.rs
391 lines (341 loc) · 13.6 KB
/
worker.rs
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
use std::borrow::Cow;
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use either::Either;
use futures_channel::oneshot;
use sqlx_rt::{AsyncMutex, AsyncMutexGuard};
use crate::describe::Describe;
use crate::error::Error;
use crate::sqlite::connection::collation::create_collation;
use crate::sqlite::connection::describe::describe;
use crate::sqlite::connection::establish::EstablishParams;
use crate::sqlite::connection::ConnectionState;
use crate::sqlite::connection::{execute, ConnectionHandleRaw};
use crate::sqlite::{Sqlite, SqliteArguments, SqliteQueryResult, SqliteRow, SqliteStatement};
use crate::transaction::{
begin_ansi_transaction_sql, commit_ansi_transaction_sql, rollback_ansi_transaction_sql,
};
// Each SQLite connection has a dedicated thread.
// TODO: Tweak this so that we can use a thread pool per pool of SQLite3 connections to reduce
// OS resource usage. Low priority because a high concurrent load for SQLite3 is very
// unlikely.
pub(crate) struct ConnectionWorker {
command_tx: flume::Sender<Command>,
/// The `sqlite3` pointer. NOTE: access is unsynchronized!
pub(crate) handle_raw: ConnectionHandleRaw,
/// Mutex for locking access to the database.
pub(crate) shared: Arc<WorkerSharedState>,
}
pub(crate) struct WorkerSharedState {
pub(crate) cached_statements_size: AtomicUsize,
pub(crate) conn: AsyncMutex<ConnectionState>,
}
enum Command {
Prepare {
query: Box<str>,
tx: oneshot::Sender<Result<SqliteStatement<'static>, Error>>,
},
Describe {
query: Box<str>,
tx: oneshot::Sender<Result<Describe<Sqlite>, Error>>,
},
Execute {
query: Box<str>,
arguments: Option<SqliteArguments<'static>>,
persistent: bool,
tx: flume::Sender<Result<Either<SqliteQueryResult, SqliteRow>, Error>>,
},
Begin {
tx: oneshot::Sender<Result<(), Error>>,
},
Commit {
tx: oneshot::Sender<Result<(), Error>>,
},
Rollback {
tx: Option<oneshot::Sender<Result<(), Error>>>,
},
CreateCollation {
create_collation:
Box<dyn FnOnce(&mut ConnectionState) -> Result<(), Error> + Send + Sync + 'static>,
},
UnlockDb,
ClearCache {
tx: oneshot::Sender<()>,
},
Ping {
tx: oneshot::Sender<()>,
},
Shutdown {
tx: oneshot::Sender<()>,
},
}
impl ConnectionWorker {
pub(crate) async fn establish(params: EstablishParams) -> Result<Self, Error> {
let (establish_tx, establish_rx) = oneshot::channel();
thread::Builder::new()
.name(params.thread_name.clone())
.spawn(move || {
let (command_tx, command_rx) = flume::bounded(params.command_channel_size);
let conn = match params.establish() {
Ok(conn) => conn,
Err(e) => {
establish_tx.send(Err(e)).ok();
return;
}
};
let shared = Arc::new(WorkerSharedState {
cached_statements_size: AtomicUsize::new(0),
// note: must be fair because in `Command::UnlockDb` we unlock the mutex
// and then immediately try to relock it; an unfair mutex would immediately
// grant us the lock even if another task is waiting.
conn: AsyncMutex::new(conn),
});
let mut conn = shared.conn.try_lock().unwrap();
if establish_tx
.send(Ok(Self {
command_tx,
handle_raw: conn.handle.to_raw(),
shared: Arc::clone(&shared),
}))
.is_err()
{
return;
}
for cmd in command_rx {
match cmd {
Command::Prepare { query, tx } => {
tx.send(prepare(&mut conn, &query).map(|prepared| {
update_cached_statements_size(
&conn,
&shared.cached_statements_size,
);
prepared
}))
.ok();
}
Command::Describe { query, tx } => {
tx.send(describe(&mut conn, &query)).ok();
}
Command::Execute {
query,
arguments,
persistent,
tx,
} => {
let iter = match execute::iter(&mut conn, &query, arguments, persistent)
{
Ok(iter) => iter,
Err(e) => {
tx.send(Err(e)).ok();
continue;
}
};
for res in iter {
if tx.send(res).is_err() {
break;
}
}
update_cached_statements_size(&conn, &shared.cached_statements_size);
}
Command::Begin { tx } => {
let depth = conn.transaction_depth;
let res =
conn.handle
.exec(begin_ansi_transaction_sql(depth))
.map(|_| {
conn.transaction_depth += 1;
});
tx.send(res).ok();
}
Command::Commit { tx } => {
let depth = conn.transaction_depth;
let res = if depth > 0 {
conn.handle
.exec(commit_ansi_transaction_sql(depth))
.map(|_| {
conn.transaction_depth -= 1;
})
} else {
Ok(())
};
tx.send(res).ok();
}
Command::Rollback { tx } => {
let depth = conn.transaction_depth;
let res = if depth > 0 {
conn.handle
.exec(rollback_ansi_transaction_sql(depth))
.map(|_| {
conn.transaction_depth -= 1;
})
} else {
Ok(())
};
if let Some(tx) = tx {
tx.send(res).ok();
}
}
Command::CreateCollation { create_collation } => {
if let Err(e) = (create_collation)(&mut conn) {
log::warn!("error applying collation in background worker: {}", e);
}
}
Command::ClearCache { tx } => {
conn.statements.clear();
update_cached_statements_size(&conn, &shared.cached_statements_size);
tx.send(()).ok();
}
Command::UnlockDb => {
drop(conn);
conn = futures_executor::block_on(shared.conn.lock());
}
Command::Ping { tx } => {
tx.send(()).ok();
}
Command::Shutdown { tx } => {
// drop the connection references before sending confirmation
// and ending the command loop
drop(conn);
drop(shared);
let _ = tx.send(());
return;
}
}
}
})?;
establish_rx.await.map_err(|_| Error::WorkerCrashed)?
}
pub(crate) async fn prepare(&mut self, query: &str) -> Result<SqliteStatement<'static>, Error> {
self.oneshot_cmd(|tx| Command::Prepare {
query: query.into(),
tx,
})
.await?
}
pub(crate) async fn describe(&mut self, query: &str) -> Result<Describe<Sqlite>, Error> {
self.oneshot_cmd(|tx| Command::Describe {
query: query.into(),
tx,
})
.await?
}
pub(crate) async fn execute(
&mut self,
query: &str,
args: Option<SqliteArguments<'_>>,
chan_size: usize,
persistent: bool,
) -> Result<flume::Receiver<Result<Either<SqliteQueryResult, SqliteRow>, Error>>, Error> {
let (tx, rx) = flume::bounded(chan_size);
self.command_tx
.send_async(Command::Execute {
query: query.into(),
arguments: args.map(SqliteArguments::into_static),
persistent,
tx,
})
.await
.map_err(|_| Error::WorkerCrashed)?;
Ok(rx)
}
pub(crate) async fn begin(&mut self) -> Result<(), Error> {
self.oneshot_cmd(|tx| Command::Begin { tx }).await?
}
pub(crate) async fn commit(&mut self) -> Result<(), Error> {
self.oneshot_cmd(|tx| Command::Commit { tx }).await?
}
pub(crate) async fn rollback(&mut self) -> Result<(), Error> {
self.oneshot_cmd(|tx| Command::Rollback { tx: Some(tx) })
.await?
}
pub(crate) fn start_rollback(&mut self) -> Result<(), Error> {
self.command_tx
.send(Command::Rollback { tx: None })
.map_err(|_| Error::WorkerCrashed)
}
pub(crate) async fn ping(&mut self) -> Result<(), Error> {
self.oneshot_cmd(|tx| Command::Ping { tx }).await
}
async fn oneshot_cmd<F, T>(&mut self, command: F) -> Result<T, Error>
where
F: FnOnce(oneshot::Sender<T>) -> Command,
{
let (tx, rx) = oneshot::channel();
self.command_tx
.send_async(command(tx))
.await
.map_err(|_| Error::WorkerCrashed)?;
rx.await.map_err(|_| Error::WorkerCrashed)
}
pub fn create_collation(
&mut self,
name: &str,
compare: impl Fn(&str, &str) -> std::cmp::Ordering + Send + Sync + 'static,
) -> Result<(), Error> {
let name = name.to_string();
self.command_tx
.send(Command::CreateCollation {
create_collation: Box::new(move |conn| {
create_collation(&mut conn.handle, &name, compare)
}),
})
.map_err(|_| Error::WorkerCrashed)?;
Ok(())
}
pub(crate) async fn clear_cache(&mut self) -> Result<(), Error> {
self.oneshot_cmd(|tx| Command::ClearCache { tx }).await
}
pub(crate) async fn unlock_db(
&mut self,
) -> Result<AsyncMutexGuard<'_, ConnectionState>, Error> {
let (guard, res) = futures_util::future::join(
// we need to join the wait queue for the lock before we send the message
self.shared.conn.lock(),
self.command_tx.send_async(Command::UnlockDb),
)
.await;
res.map_err(|_| Error::WorkerCrashed)?;
Ok(guard)
}
/// Send a command to the worker to shut down the processing thread.
///
/// A `WorkerCrashed` error may be returned if the thread has already stopped.
pub(crate) fn shutdown(&mut self) -> impl Future<Output = Result<(), Error>> {
let (tx, rx) = oneshot::channel();
let send_res = self
.command_tx
.send(Command::Shutdown { tx })
.map_err(|_| Error::WorkerCrashed);
async move {
send_res?;
// wait for the response
rx.await.map_err(|_| Error::WorkerCrashed)
}
}
}
fn prepare(conn: &mut ConnectionState, query: &str) -> Result<SqliteStatement<'static>, Error> {
// prepare statement object (or checkout from cache)
let statement = conn.statements.get(query, true)?;
let mut parameters = 0;
let mut columns = None;
let mut column_names = None;
while let Some(statement) = statement.prepare_next(&mut conn.handle)? {
parameters += statement.handle.bind_parameter_count();
// the first non-empty statement is chosen as the statement we pull columns from
if !statement.columns.is_empty() && columns.is_none() {
columns = Some(Arc::clone(statement.columns));
column_names = Some(Arc::clone(statement.column_names));
}
}
Ok(SqliteStatement {
sql: Cow::Owned(query.to_string()),
columns: columns.unwrap_or_default(),
column_names: column_names.unwrap_or_default(),
parameters,
})
}
fn update_cached_statements_size(conn: &ConnectionState, size: &AtomicUsize) {
size.store(conn.statements.len(), Ordering::Release);
}