quex-driver 0.1.2

Low-level async database drivers used by quex.
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
use std::ptr::NonNull;
use std::sync::Arc;

use quex_mariadb_sys as ffi;

use super::connection::Connection;
use super::error::{Error, ExecuteResult, Result};
use super::rows::{Metadata, ResultSet};
use super::runtime::{
    DriveOperation, DriveOutput, ParamBindings, StmtHandle, enable_stmt_max_length,
    ensure_mysql_thread_ready, ensure_mysql_thread_ready_for_drop,
};
use super::value::{ParamRefSlice, ParamSource, Value, ValueRef, values_as_refs};

/// A mysql or mariadb prepared statement.
///
/// This statement owns a native statement handle until it is dropped.
pub struct Statement<'a> {
    pub(crate) conn: &'a mut Connection,
    pub(crate) stmt: StmtHandle,
    pub(crate) result_metadata: Option<Arc<Metadata>>,
}

impl<'a> Statement<'a> {
    /// Runs the statement with owned values and returns rows.
    pub async fn execute(&mut self, params: &[Value]) -> Result<ResultSet> {
        let refs = values_as_refs(params);
        self.execute_ref(&refs).await
    }

    /// Runs the statement with borrowed values and returns rows.
    pub async fn execute_ref(&mut self, params: &[ValueRef<'_>]) -> Result<ResultSet> {
        self.execute_source(&ParamRefSlice(params)).await
    }

    /// Runs the statement with a custom parameter source and returns rows.
    pub async fn execute_source<P>(&mut self, params: &P) -> Result<ResultSet>
    where
        P: ParamSource + ?Sized,
    {
        ensure_mysql_thread_ready()?;
        // SAFETY: The statement handle is live and parameter buffers live through execution.
        unsafe {
            let stmt = self.stmt;
            let expected = ffi::mysql_stmt_param_count(stmt.as_ptr()) as usize;
            if expected != params.len() {
                return Err(Error::new(format!(
                    "statement expects {} parameters but got {}",
                    expected,
                    params.len()
                )));
            }

            let mut bindings = ParamBindings::new(params);
            if expected != 0
                && ffi::mysql_stmt_bind_param(stmt.as_ptr(), bindings.binds.as_mut_ptr()) != 0
            {
                return Err(Error::from_stmt(
                    stmt.as_ptr(),
                    "mysql_stmt_bind_param failed",
                ));
            }

            let mut output = DriveOutput::stmt_execute();
            self.conn
                .drive(DriveOperation::StmtExecute { stmt }, &mut output)
                .await?;

            if output.stmt_execute_code() != 0 {
                return Err(Error::from_stmt(stmt.as_ptr(), "mysql_stmt_execute failed"));
            }

            if ffi::mysql_stmt_field_count(stmt.as_ptr()) == 0 {
                return Ok(ResultSet::empty());
            }

            enable_stmt_max_length(stmt.as_ptr())?;
            let mut output = DriveOutput::stmt_store_result();
            self.conn
                .drive(DriveOperation::StmtStoreResult { stmt }, &mut output)
                .await?;

            if output.stmt_store_result_code() != 0 {
                return Err(Error::from_stmt(
                    stmt.as_ptr(),
                    "mysql_stmt_store_result failed",
                ));
            }

            let metadata = match &self.result_metadata {
                Some(metadata) => Arc::clone(metadata),
                None => {
                    let meta = NonNull::new(ffi::mysql_stmt_result_metadata(stmt.as_ptr()))
                        .ok_or_else(|| {
                            Error::from_stmt(
                                stmt.as_ptr(),
                                "statement returned rows but no result metadata",
                            )
                        })?;
                    let metadata = Arc::new(Metadata::from_result(meta));
                    ffi::mysql_free_result(meta.as_ptr());
                    self.result_metadata = Some(Arc::clone(&metadata));
                    metadata
                }
            };

            ResultSet::statement(self.stmt, metadata)
        }
    }

    /// Runs the statement with owned values when no rows are expected.
    pub async fn exec(&mut self, params: &[Value]) -> Result<ExecuteResult> {
        let refs = values_as_refs(params);
        self.exec_ref(&refs).await
    }

    /// Runs the statement with borrowed values when no rows are expected.
    pub async fn exec_ref(&mut self, params: &[ValueRef<'_>]) -> Result<ExecuteResult> {
        self.exec_source(&ParamRefSlice(params)).await
    }

    /// Runs the statement with a custom parameter source when no rows are
    /// expected.
    pub async fn exec_source<P>(&mut self, params: &P) -> Result<ExecuteResult>
    where
        P: ParamSource + ?Sized,
    {
        ensure_mysql_thread_ready()?;
        // SAFETY: The statement handle is live and parameter buffers live through execution.
        unsafe {
            let stmt = self.stmt;
            let expected = ffi::mysql_stmt_param_count(stmt.as_ptr()) as usize;
            if expected != params.len() {
                return Err(Error::new(format!(
                    "statement expects {} parameters but got {}",
                    expected,
                    params.len()
                )));
            }

            let mut bindings = ParamBindings::new(params);
            if expected != 0
                && ffi::mysql_stmt_bind_param(stmt.as_ptr(), bindings.binds.as_mut_ptr()) != 0
            {
                return Err(Error::from_stmt(
                    stmt.as_ptr(),
                    "mysql_stmt_bind_param failed",
                ));
            }

            let mut output = DriveOutput::stmt_execute();
            self.conn
                .drive(DriveOperation::StmtExecute { stmt }, &mut output)
                .await?;

            if output.stmt_execute_code() != 0 {
                return Err(Error::from_stmt(stmt.as_ptr(), "mysql_stmt_execute failed"));
            }

            if ffi::mysql_stmt_field_count(stmt.as_ptr()) != 0 {
                return Err(Error::new("statement returned rows; use execute instead"));
            }

            Ok(ExecuteResult {
                rows_affected: ffi::mysql_stmt_affected_rows(stmt.as_ptr()) as u64,
                last_insert_id: ffi::mysql_stmt_insert_id(stmt.as_ptr()) as u64,
            })
        }
    }
}

/// A mysql or mariadb prepared statement cached on its connection.
pub struct CachedStatement<'a> {
    pub(crate) conn: &'a mut Connection,
    pub(crate) key: Box<str>,
}

impl CachedStatement<'_> {
    /// Runs the cached statement with owned values and returns rows.
    pub async fn execute(&mut self, params: &[Value]) -> Result<ResultSet> {
        let refs = values_as_refs(params);
        self.execute_ref(&refs).await
    }

    /// Runs the cached statement with borrowed values and returns rows.
    pub async fn execute_ref(&mut self, params: &[ValueRef<'_>]) -> Result<ResultSet> {
        self.execute_source(&ParamRefSlice(params)).await
    }

    /// Runs the cached statement with a custom parameter source and returns rows.
    pub async fn execute_source<P>(&mut self, params: &P) -> Result<ResultSet>
    where
        P: ParamSource + ?Sized,
    {
        ensure_mysql_thread_ready()?;
        let key = self.key.clone();
        let (stmt, param_count) = {
            let entry = self
                .conn
                .statement_cache
                .get(key.as_ref())
                .ok_or_else(|| Error::new("cached statement missing"))?;
            (entry.stmt, entry.param_count)
        };

        if param_count != params.len() {
            return Err(Error::new(format!(
                "statement expects {} parameters but got {}",
                param_count,
                params.len()
            )));
        }

        {
            let entry = self
                .conn
                .statement_cache
                .get_mut(key.as_ref())
                .ok_or_else(|| Error::new("cached statement missing"))?;
            // SAFETY: stmt is a live cached statement owned by the connection.
            unsafe {
                if ffi::mysql_stmt_reset(stmt.as_ptr()) != 0 {
                    return Err(Error::from_stmt(stmt.as_ptr(), "mysql_stmt_reset failed"));
                }
            }
            entry.scratch.bind_source(params)?;
            // SAFETY: Bound buffers in scratch live until statement execution completes.
            unsafe {
                if param_count != 0
                    && ffi::mysql_stmt_bind_param(stmt.as_ptr(), entry.scratch.binds.as_mut_ptr())
                        != 0
                {
                    return Err(Error::from_stmt(
                        stmt.as_ptr(),
                        "mysql_stmt_bind_param failed",
                    ));
                }
            }
        }

        let mut output = DriveOutput::stmt_execute();
        self.conn
            .drive(DriveOperation::StmtExecute { stmt }, &mut output)
            .await?;

        if output.stmt_execute_code() != 0 {
            // SAFETY: stmt is live and contains diagnostics for the failed execute call.
            return Err(unsafe { Error::from_stmt(stmt.as_ptr(), "mysql_stmt_execute failed") });
        }

        // SAFETY: stmt is live after execution and field count is query metadata.
        if unsafe { ffi::mysql_stmt_field_count(stmt.as_ptr()) } == 0 {
            return Ok(ResultSet::empty());
        }

        enable_stmt_max_length(stmt.as_ptr())?;
        let mut output = DriveOutput::stmt_store_result();
        self.conn
            .drive(DriveOperation::StmtStoreResult { stmt }, &mut output)
            .await?;

        if output.stmt_store_result_code() != 0 {
            // SAFETY: stmt is live and contains diagnostics for the failed store-result call.
            return Err(unsafe {
                Error::from_stmt(stmt.as_ptr(), "mysql_stmt_store_result failed")
            });
        }

        let metadata = match self
            .conn
            .statement_cache
            .get(key.as_ref())
            .and_then(|entry| entry.result_metadata.clone())
        {
            Some(metadata) => metadata,
            None => {
                // SAFETY: stmt is live and has result metadata after a row-producing execution.
                let meta = NonNull::new(unsafe { ffi::mysql_stmt_result_metadata(stmt.as_ptr()) })
                    .ok_or_else(|| unsafe {
                        // SAFETY: stmt is live and contains diagnostics for missing metadata.
                        Error::from_stmt(
                            stmt.as_ptr(),
                            "statement returned rows but no result metadata",
                        )
                    })?;
                let metadata = Arc::new(Metadata::from_result(meta));
                // SAFETY: meta was returned by mysql_stmt_result_metadata and is freed once here.
                unsafe {
                    ffi::mysql_free_result(meta.as_ptr());
                }
                self.conn
                    .statement_cache
                    .get_mut(key.as_ref())
                    .expect("cached statement missing")
                    .result_metadata = Some(Arc::clone(&metadata));
                metadata
            }
        };

        ResultSet::statement(stmt, metadata)
    }

    /// Runs the cached statement with owned values when no rows are expected.
    pub async fn exec(&mut self, params: &[Value]) -> Result<ExecuteResult> {
        let refs = values_as_refs(params);
        self.exec_ref(&refs).await
    }

    /// Runs the cached statement with borrowed values when no rows are expected.
    pub async fn exec_ref(&mut self, params: &[ValueRef<'_>]) -> Result<ExecuteResult> {
        self.exec_source(&ParamRefSlice(params)).await
    }

    /// Runs the cached statement with a custom parameter source when no rows are
    /// expected.
    pub async fn exec_source<P>(&mut self, params: &P) -> Result<ExecuteResult>
    where
        P: ParamSource + ?Sized,
    {
        ensure_mysql_thread_ready()?;
        let key = self.key.clone();
        let (stmt, param_count) = {
            let entry = self
                .conn
                .statement_cache
                .get(key.as_ref())
                .ok_or_else(|| Error::new("cached statement missing"))?;
            (entry.stmt, entry.param_count)
        };

        if param_count != params.len() {
            return Err(Error::new(format!(
                "statement expects {} parameters but got {}",
                param_count,
                params.len()
            )));
        }

        {
            let entry = self
                .conn
                .statement_cache
                .get_mut(key.as_ref())
                .ok_or_else(|| Error::new("cached statement missing"))?;
            // SAFETY: stmt is a live cached statement owned by the connection.
            unsafe {
                if ffi::mysql_stmt_reset(stmt.as_ptr()) != 0 {
                    return Err(Error::from_stmt(stmt.as_ptr(), "mysql_stmt_reset failed"));
                }
            }
            entry.scratch.bind_source(params)?;
            // SAFETY: Bound buffers in scratch live until statement execution completes.
            unsafe {
                if param_count != 0
                    && ffi::mysql_stmt_bind_param(stmt.as_ptr(), entry.scratch.binds.as_mut_ptr())
                        != 0
                {
                    return Err(Error::from_stmt(
                        stmt.as_ptr(),
                        "mysql_stmt_bind_param failed",
                    ));
                }
            }
        }

        let mut output = DriveOutput::stmt_execute();
        self.conn
            .drive(DriveOperation::StmtExecute { stmt }, &mut output)
            .await?;

        if output.stmt_execute_code() != 0 {
            // SAFETY: stmt is live and contains diagnostics for the failed execute call.
            return Err(unsafe { Error::from_stmt(stmt.as_ptr(), "mysql_stmt_execute failed") });
        }

        // SAFETY: stmt is live after execution and field count is query metadata.
        if unsafe { ffi::mysql_stmt_field_count(stmt.as_ptr()) } != 0 {
            return Err(Error::new("statement returned rows; use execute instead"));
        }

        // SAFETY: stmt is live after a successful non-row execution.
        let rows_affected = unsafe { ffi::mysql_stmt_affected_rows(stmt.as_ptr()) as u64 };
        // SAFETY: stmt is live after a successful non-row execution.
        let last_insert_id = unsafe { ffi::mysql_stmt_insert_id(stmt.as_ptr()) as u64 };
        Ok(ExecuteResult {
            rows_affected,
            last_insert_id,
        })
    }
}

impl Drop for Statement<'_> {
    fn drop(&mut self) {
        if !ensure_mysql_thread_ready_for_drop() {
            return;
        }
        // SAFETY: This statement is uniquely owned and closed exactly once here.
        unsafe {
            ffi::mysql_stmt_close(self.stmt.as_ptr());
        }
    }
}

#[cfg(test)]
mod tests {
    use std::env;
    use std::thread;

    use super::super::options::ConnectOptions;
    use super::super::value::Value;
    use super::*;

    fn mysql_test_options() -> ConnectOptions {
        let mut options = ConnectOptions::new();
        if let Ok(host) = env::var("QUEX_TEST_MYSQL_HOST") {
            options = options.host(host);
        }
        if let Ok(port) = env::var("QUEX_TEST_MYSQL_PORT") {
            options = options.port(port.parse().expect("valid mysql test port"));
        }
        if let Ok(user) = env::var("QUEX_TEST_MYSQL_USER") {
            options = options.user(user);
        }
        if let Ok(password) = env::var("QUEX_TEST_MYSQL_PASSWORD") {
            options = options.password(password);
        }
        if let Ok(database) = env::var("QUEX_TEST_MYSQL_DATABASE") {
            options = options.database(database);
        }
        if let Ok(unix_socket) = env::var("QUEX_TEST_MYSQL_SOCKET") {
            options = options.unix_socket(unix_socket);
        }
        options
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[ignore = "requires a local MariaDB instance and QUEX_TEST_MYSQL_* env if defaults are unsuitable"]
    async fn mysql_statement_moves_across_tokio_tasks_before_execute_and_drop() {
        let conn = Box::new(
            Connection::connect(mysql_test_options())
                .await
                .expect("connect"),
        );
        let conn_ptr = Box::into_raw(conn);

        let create_thread = thread::current().id();
        let stmt = unsafe {
            (&mut *conn_ptr)
                .prepare("select ? as id, ? as name")
                .await
                .expect("prepare")
        };

        let (execute_thread, rows) = tokio::spawn(async move {
            tokio::task::yield_now().await;
            let execute_thread = thread::current().id();
            let mut stmt = stmt;
            let rows = stmt
                .execute(&[Value::I64(11), Value::String("Ada".into())])
                .await
                .expect("execute");
            (execute_thread, rows)
        })
        .await
        .expect("join statement task");

        assert_ne!(
            execute_thread, create_thread,
            "statement execute stayed on the creator thread"
        );

        let drop_thread = tokio::spawn(async move {
            tokio::task::yield_now().await;
            let drop_thread = thread::current().id();
            drop(rows);
            drop_thread
        })
        .await
        .expect("join rows drop task");

        assert_ne!(
            drop_thread, execute_thread,
            "rows drop stayed on the execute thread"
        );

        unsafe {
            drop(Box::from_raw(conn_ptr));
        }
    }
}