antfly-embedded 0.3.1

Safe Rust binding for local Antfly databases and inference via libantfly
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
// Copyright 2026 Antfly, Inc.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{
    Antfly, AntflyColumn, AntflyQueryResult, AntflyRow, AntflyStatement, AntflyTypeInfo,
    AntflyValue,
};
use crate::sql::SqlError;
use crate::{Database, MIN_THREAD_STACK_SIZE, OpenOptions};
use either::Either;
use futures_core::{future::BoxFuture, stream::BoxStream};
use futures_util::{FutureExt, TryStreamExt};
use serde::Deserialize;
use serde_json::{Value as Json, json};
use sqlx_core::{
    connection::{ConnectOptions, Connection},
    describe::Describe,
    error::{DatabaseError, Error, ErrorKind},
    executor::{Execute, Executor},
    sql_str::SqlStr,
    transaction::{Transaction, TransactionManager},
};
use std::{
    borrow::Cow,
    collections::HashMap,
    fmt,
    path::PathBuf,
    str::FromStr,
    sync::{
        Arc, Mutex, OnceLock, Weak,
        atomic::{AtomicBool, Ordering},
        mpsc,
    },
    time::Duration,
};
use tokio::sync::oneshot;
use url::Url;

impl DatabaseError for SqlError {
    fn message(&self) -> &str {
        &self.message
    }
    fn code(&self) -> Option<Cow<'_, str>> {
        self.sqlstate.as_deref().map(Cow::Borrowed)
    }
    fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
        self
    }
    fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
        self
    }
    fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
        self
    }
    fn kind(&self) -> ErrorKind {
        match self.sqlstate.as_deref() {
            Some("23505") => ErrorKind::UniqueViolation,
            Some("23503") => ErrorKind::ForeignKeyViolation,
            Some("23502") => ErrorKind::NotNullViolation,
            Some("23514") => ErrorKind::CheckViolation,
            _ => ErrorKind::Other,
        }
    }
}
fn native_error(e: SqlError) -> Error {
    if e.sqlstate.is_some() {
        Error::Database(Box::new(e))
    } else {
        Error::Protocol(e.to_string())
    }
}
fn protocol(e: impl fmt::Display) -> Error {
    Error::Protocol(e.to_string())
}
type Job = Box<dyn FnOnce(&Database) + Send>;
#[derive(Clone, Copy)]
enum ResourceKind {
    Session,
    Cursor,
}
struct PendingResource {
    id: u64,
    sender: Option<mpsc::Sender<Job>>,
    kind: ResourceKind,
}
impl PendingResource {
    fn claim(mut self) -> u64 {
        self.sender.take();
        self.id
    }
}
impl Drop for PendingResource {
    fn drop(&mut self) {
        if let Some(sender) = self.sender.take() {
            let id = self.id;
            let kind = self.kind;
            let _ = sender.send(Box::new(move |db| match kind {
                ResourceKind::Session => {
                    let _ = db.sql_session_close(id);
                }
                ResourceKind::Cursor => {
                    let _ = db.sql_cursor_close(id);
                }
            }));
        }
    }
}
// A channel can remain allocated after its worker panics. Track the worker's
// lifetime directly so pool health checks never queue behind native work.
struct WorkerLifetime(Arc<AtomicBool>);
impl Drop for WorkerLifetime {
    fn drop(&mut self) {
        self.0.store(false, Ordering::Release);
    }
}
struct Worker {
    alive: Arc<AtomicBool>,
    sender: Option<mpsc::Sender<Job>>,
    thread: Option<std::thread::JoinHandle<()>>,
}
impl Drop for Worker {
    fn drop(&mut self) {
        // Drain queued resource cleanup before closing the native connection.
        self.sender.take();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}
impl fmt::Debug for Worker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NativeWorker").finish_non_exhaustive()
    }
}
static SHARED_WORKERS: OnceLock<Mutex<HashMap<usize, Weak<Worker>>>> = OnceLock::new();
impl Worker {
    fn open(options: &AntflyConnectOptions) -> Result<Arc<Self>, Error> {
        if let Some(database) = &options.database {
            return Self::open_shared(database);
        }
        let path = if options.path.is_absolute() {
            options.path.clone()
        } else {
            std::env::current_dir()
                .map_err(protocol)?
                .join(&options.path)
        };
        let alive = Arc::new(AtomicBool::new(true));
        let lifetime = WorkerLifetime(Arc::clone(&alive));
        let (sender, receiver) = mpsc::channel::<Job>();
        let (started, start) = mpsc::sync_channel(1);
        let native_options = OpenOptions {
            no_sync: options.no_sync,
            busy_timeout: Some(options.busy_timeout),
            ..Default::default()
        };
        let thread_path = path.clone();
        let thread = std::thread::Builder::new()
            .name("antfly-sqlx".into())
            .stack_size(MIN_THREAD_STACK_SIZE)
            .spawn(move || {
                let _lifetime = lifetime;
                let database = match Database::open(&thread_path, &native_options) {
                    Ok(db) => Ok(db),
                    Err(error) if error.kind() == crate::Error::NotFound => {
                        Database::create(&thread_path, &native_options).or_else(|error| {
                            if thread_path.exists() {
                                Database::open(&thread_path, &native_options)
                            } else {
                                Err(error)
                            }
                        })
                    }
                    Err(e) => Err(e),
                };
                match database {
                    Ok(db) => {
                        if started.send(Ok(())).is_err() {
                            return;
                        }
                        for job in receiver {
                            job(&db)
                        }
                    }
                    Err(e) => {
                        let _ = started.send(Err(e));
                    }
                }
            })
            .map_err(protocol)?;
        start
            .recv()
            .map_err(protocol)?
            .map_err(|e| native_error(e.into()))?;
        let worker = Arc::new(Worker {
            alive,
            sender: Some(sender),
            thread: Some(thread),
        });
        Ok(worker)
    }
    /// One worker per shared handle, so every pooled connection queues on it.
    fn open_shared(database: &Arc<Database>) -> Result<Arc<Self>, Error> {
        let key = Arc::as_ptr(database) as usize;
        let mut registry = SHARED_WORKERS
            .get_or_init(Default::default)
            .lock()
            .map_err(protocol)?;
        if let Some(worker) = registry
            .get(&key)
            .and_then(Weak::upgrade)
            .filter(|worker| worker.alive.load(Ordering::Acquire))
        {
            return Ok(worker);
        }
        let alive = Arc::new(AtomicBool::new(true));
        let lifetime = WorkerLifetime(Arc::clone(&alive));
        let (sender, receiver) = mpsc::channel::<Job>();
        let database = Arc::clone(database);
        let thread = std::thread::Builder::new()
            .name("antfly-sqlx".into())
            .stack_size(MIN_THREAD_STACK_SIZE)
            .spawn(move || {
                let _lifetime = lifetime;
                for job in receiver {
                    job(&database)
                }
            })
            .map_err(protocol)?;
        let worker = Arc::new(Worker {
            alive,
            sender: Some(sender),
            thread: Some(thread),
        });
        registry.insert(key, Arc::downgrade(&worker));
        Ok(worker)
    }
    async fn run<T: Send + 'static>(
        &self,
        operation: impl FnOnce(&Database) -> crate::sql::Result<T> + Send + 'static,
    ) -> Result<T, Error> {
        let (sender, receiver) = oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| protocol("native SQL worker has stopped"))?
            .send(Box::new(move |db| {
                let _ = sender.send(operation(db));
            }))
            .map_err(|_| protocol("native SQL worker has stopped"))?;
        receiver.await.map_err(protocol)?.map_err(native_error)
    }
    fn fire(&self, operation: impl FnOnce(&Database) + Send + 'static) {
        if let Some(sender) = &self.sender {
            let _ = sender.send(Box::new(operation));
        }
    }
    async fn run_resource(
        &self,
        kind: ResourceKind,
        operation: impl FnOnce(&Database) -> crate::sql::Result<u64> + Send + 'static,
    ) -> Result<u64, Error> {
        let jobs = self
            .sender
            .as_ref()
            .ok_or_else(|| protocol("native SQL worker has stopped"))?;
        let cleanup = jobs.clone();
        let (sender, receiver) = oneshot::channel();
        jobs.send(Box::new(move |db| {
            let resource = operation(db).map(|id| PendingResource {
                id,
                sender: Some(cleanup),
                kind,
            });
            // The resource also owns cleanup when cancellation occurs after
            // native open but before the receiving future claims its ID.
            let _ = sender.send(resource);
        }))
        .map_err(|_| protocol("native SQL worker has stopped"))?;
        receiver
            .await
            .map_err(protocol)?
            .map(PendingResource::claim)
            .map_err(native_error)
    }
}
#[derive(Debug, Clone)]
pub struct AntflyConnectOptions {
    pub path: PathBuf,
    pub no_sync: bool,
    pub busy_timeout: Duration,
    /// An already-open handle to run SQL on instead of opening `path`.
    database: Option<Arc<Database>>,
}
impl AntflyConnectOptions {
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            no_sync: false,
            busy_timeout: Duration::from_secs(5),
            database: None,
        }
    }
    pub fn no_sync(mut self, value: bool) -> Self {
        self.no_sync = value;
        self
    }
    /// Maximum wait for another connection to finish a native operation.
    pub fn busy_timeout(mut self, timeout: Duration) -> Self {
        self.busy_timeout = timeout;
        self
    }
    /// Runs SQL on `database` instead of opening `path` (kept for the URL).
    ///
    /// Optional when mixing SQL with documents, search, or inference. Separate
    /// path-opened connections are also supported; native calls coordinate
    /// writer ownership at operation boundaries.
    /// Connections never close a shared handle; its owner does.
    pub fn with_database(mut self, database: Arc<Database>) -> Self {
        self.database = Some(database);
        self
    }
}
impl FromStr for AntflyConnectOptions {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self, Error> {
        Self::from_url(&Url::parse(value).map_err(protocol)?)
    }
}
impl ConnectOptions for AntflyConnectOptions {
    type Connection = AntflyConnection;
    fn from_url(url: &Url) -> Result<Self, Error> {
        if !matches!(url.scheme(), "file" | "antfly")
            || url.host_str().is_some_and(|h| !h.is_empty())
        {
            return Err(protocol(
                "expected antfly:///path/database.aflite or file:/path/database.aflite",
            ));
        }
        let path = Url::parse(&format!("file://{}", url.path()))
            .map_err(protocol)?
            .to_file_path()
            .map_err(|_| protocol("invalid database path"))?;
        let mut options = Self::new(path);
        for (name, value) in url.query_pairs() {
            match (name.as_ref(), value.as_ref()) {
                ("no_sync", "1") => options.no_sync = true,
                ("no_sync", "0") => {}
                ("busy_timeout_ms", value) => {
                    options.busy_timeout = Duration::from_millis(value.parse().map_err(protocol)?);
                }
                _ => return Err(protocol("unknown embedded SQL connection option")),
            }
        }
        Ok(options)
    }
    fn to_url_lossy(&self) -> Url {
        let path = if self.path.is_absolute() {
            self.path.clone()
        } else {
            std::env::current_dir()
                .unwrap_or_else(|_| PathBuf::from("/"))
                .join(&self.path)
        };
        let mut url = Url::from_file_path(path).expect("database path");
        {
            let mut pairs = url.query_pairs_mut();
            if self.no_sync {
                pairs.append_pair("no_sync", "1");
            }
            pairs.append_pair(
                "busy_timeout_ms",
                &OpenOptions::new()
                    .busy_timeout(self.busy_timeout)
                    .busy_timeout_ms()
                    .to_string(),
            );
        }
        url
    }
    async fn connect(&self) -> Result<AntflyConnection, Error> {
        let options = self.clone();
        let worker = tokio::task::spawn_blocking(move || Worker::open(&options))
            .await
            .map_err(protocol)??;
        let session = worker
            .run_resource(ResourceKind::Session, |db| Ok(db.sql_session_open()?))
            .await?;
        Ok(AntflyConnection {
            worker,
            session,
            depth: 0,
            pending: false,
            closed: false,
        })
    }
    fn log_statements(self, _: log::LevelFilter) -> Self {
        self
    }
    fn log_slow_statements(self, _: log::LevelFilter, _: Duration) -> Self {
        self
    }
}
#[derive(Debug)]
pub struct AntflyConnection {
    worker: Arc<Worker>,
    session: u64,
    depth: usize,
    pending: bool,
    closed: bool,
}
impl AntflyConnection {
    async fn control(&mut self, statement: String) -> Result<(), Error> {
        let session = self.session;
        self.pending = true;
        let result = self
            .worker
            .run(move |db| {
                db.sql_json(
                    serde_json::to_vec(&json!({"statement":statement,"session_id":session}))
                        .expect("JSON encoding"),
                )
            })
            .await;
        self.pending = false;
        result.map(|_| ())
    }
    async fn ensure(&mut self) -> Result<(), Error> {
        if self.pending {
            self.control("ROLLBACK".into()).await?;
            self.depth = 0
        }
        Ok(())
    }
    async fn description(
        &mut self,
        statement: SqlStr,
        parameters: Vec<AntflyTypeInfo>,
    ) -> Result<AntflyStatement, Error> {
        self.ensure().await?;
        let body = serde_json::to_vec(
            &json!({"statement":statement.as_str(),"parameter_types":parameters}),
        )
        .map_err(protocol)?;
        let bytes = self
            .worker
            .run(move |db| db.sql_describe_json(body))
            .await?;
        #[derive(Deserialize)]
        struct Description {
            columns: Vec<AntflyColumn>,
            parameter_types: Vec<Option<AntflyTypeInfo>>,
        }
        let mut description: Description = serde_json::from_slice(&bytes).map_err(protocol)?;
        for (index, column) in description.columns.iter_mut().enumerate() {
            column.ordinal = index
        }
        Ok(AntflyStatement {
            sql: statement,
            columns: description.columns,
            parameters: description
                .parameter_types
                .into_iter()
                .map(|t| t.unwrap_or(AntflyTypeInfo("null".into())))
                .collect(),
        })
    }
}
impl Drop for AntflyConnection {
    fn drop(&mut self) {
        if !self.closed {
            let id = self.session;
            self.worker.fire(move |db| {
                let _ = db.sql_session_close(id);
            });
            self.closed = true
        }
    }
}
impl Connection for AntflyConnection {
    type Database = Antfly;
    type Options = AntflyConnectOptions;
    async fn close(mut self) -> Result<(), Error> {
        let id = self.session;
        self.worker
            .run(move |db| Ok(db.sql_session_close(id)?))
            .await?;
        self.closed = true;
        Ok(())
    }
    async fn close_hard(self) -> Result<(), Error> {
        self.close().await
    }
    async fn ping(&mut self) -> Result<(), Error> {
        if self.closed || !self.worker.alive.load(Ordering::Acquire) {
            return Err(protocol("native SQL worker has stopped"));
        }
        // Dropped/canceled transactions still need their queued rollback.
        // An idle in-process connection has no network state to probe.
        self.ensure().await
    }
    async fn begin(&mut self) -> Result<Transaction<'_, Antfly>, Error> {
        Transaction::begin(self, None).await
    }
    fn shrink_buffers(&mut self) {}
    async fn flush(&mut self) -> Result<(), Error> {
        self.ensure().await
    }
    fn should_flush(&self) -> bool {
        self.pending
    }
}
pub struct AntflyTransactionManager;
impl TransactionManager for AntflyTransactionManager {
    type Database = Antfly;
    async fn begin(conn: &mut AntflyConnection, statement: Option<SqlStr>) -> Result<(), Error> {
        conn.ensure().await?;
        if conn.depth != 0 && statement.is_some() {
            return Err(protocol(
                "custom BEGIN is only supported for the outermost transaction",
            ));
        }
        let command = if conn.depth == 0 {
            statement
                .map(|s| s.as_str().to_owned())
                .unwrap_or_else(|| "BEGIN ISOLATION LEVEL READ COMMITTED".into())
        } else {
            format!("SAVEPOINT antfly_sqlx_{}", conn.depth)
        };
        conn.control(command).await?;
        conn.depth += 1;
        Ok(())
    }
    async fn commit(conn: &mut AntflyConnection) -> Result<(), Error> {
        if conn.depth == 0 {
            return Ok(());
        }
        let command = if conn.depth == 1 {
            "COMMIT".into()
        } else {
            format!("RELEASE SAVEPOINT antfly_sqlx_{}", conn.depth - 1)
        };
        conn.control(command).await?;
        conn.depth -= 1;
        Ok(())
    }
    async fn rollback(conn: &mut AntflyConnection) -> Result<(), Error> {
        if conn.depth == 0 {
            return Ok(());
        }
        if conn.depth == 1 {
            conn.control("ROLLBACK".into()).await?
        } else {
            conn.control(format!(
                "ROLLBACK TO SAVEPOINT antfly_sqlx_{}",
                conn.depth - 1
            ))
            .await?;
            conn.control(format!("RELEASE SAVEPOINT antfly_sqlx_{}", conn.depth - 1))
                .await?
        }
        conn.depth -= 1;
        Ok(())
    }
    fn start_rollback(conn: &mut AntflyConnection) {
        if conn.depth == 0 {
            return;
        }
        let session = conn.session;
        let depth = conn.depth;
        conn.depth -= 1;
        conn.worker.fire(move |db| {
            let commands = if depth == 1 {
                vec!["ROLLBACK".to_owned()]
            } else {
                vec![
                    format!("ROLLBACK TO SAVEPOINT antfly_sqlx_{}", depth - 1),
                    format!("RELEASE SAVEPOINT antfly_sqlx_{}", depth - 1),
                ]
            };
            for statement in commands {
                let _ = db.sql_json(
                    serde_json::to_vec(&json!({"statement":statement,"session_id":session}))
                        .unwrap(),
                );
            }
        });
    }
    fn get_transaction_depth(conn: &AntflyConnection) -> usize {
        conn.depth
    }
}
#[derive(Deserialize)]
struct Output {
    columns: Vec<AntflyColumn>,
    rows: Vec<Vec<Json>>,
    sql_nulls: Option<Vec<Vec<bool>>>,
    rows_affected: u64,
}
fn rows(mut output: Output) -> Result<(Vec<AntflyRow>, AntflyQueryResult), Error> {
    for (i, column) in output.columns.iter_mut().enumerate() {
        column.ordinal = i
    }
    let columns: Arc<[AntflyColumn]> = output.columns.into();
    let mut rows = Vec::with_capacity(output.rows.len());
    for (ri, row) in output.rows.into_iter().enumerate() {
        if row.len() != columns.len() {
            return Err(protocol("invalid SQL row width"));
        }
        let values = row
            .into_iter()
            .enumerate()
            .map(|(i, value)| {
                let null = output
                    .sql_nulls
                    .as_ref()
                    .and_then(|flags| flags.get(ri))
                    .and_then(|flags| flags.get(i))
                    .copied()
                    .unwrap_or(value.is_null());
                AntflyValue {
                    kind: columns[i].kind.clone(),
                    value,
                    null,
                }
            })
            .collect();
        rows.push(AntflyRow {
            columns: columns.clone(),
            values,
        });
    }
    Ok((
        rows,
        AntflyQueryResult {
            affected: output.rows_affected,
        },
    ))
}
struct CursorGuard {
    worker: Arc<Worker>,
    id: u64,
}
impl Drop for CursorGuard {
    fn drop(&mut self) {
        let id = self.id;
        self.worker.fire(move |db| {
            let _ = db.sql_cursor_close(id);
        });
    }
}
impl<'c> Executor<'c> for &'c mut AntflyConnection {
    type Database = Antfly;
    fn fetch_many<'e, 'q: 'e, E>(
        self,
        mut query: E,
    ) -> BoxStream<'e, Result<Either<AntflyQueryResult, AntflyRow>, Error>>
    where
        'c: 'e,
        E: 'q + Execute<'q, Antfly>,
    {
        Box::pin(async_stream::try_stream! {
         self.ensure().await?;
         let args=query.take_arguments().map_err(Error::Encode)?.unwrap_or_default().values;let statement=query.sql();let session=self.session;
         let request=serde_json::to_vec(&json!({"statement":statement.as_str(),"parameters":args,"session_id":session})).map_err(protocol)?;
         let cursor_request=request.clone();self.pending=true;
         let opened=self.worker.run_resource(ResourceKind::Cursor, move|db|db.sql_cursor_open_json(cursor_request)).await;
         self.pending=false;
         match opened{
          Ok(id)=>{let cursor=CursorGuard{worker:self.worker.clone(),id};let cursor_statement:Arc<str>=Arc::from(statement.as_str());loop{
           let cursor_statement=Arc::clone(&cursor_statement);
           let bytes=self.worker.run(move|db|db.sql_cursor_fetch_json(id,128).map_err(|error|error.with_statement(&cursor_statement))).await?;
           #[derive(Deserialize)]struct Page{result:Output,exhausted:bool}
           let page:Page=serde_json::from_slice(&bytes).map_err(protocol)?;let (page_rows,result)=rows(page.result)?;
           for row in page_rows{yield Either::Right(row)}if page.exhausted{yield Either::Left(result);break}
          }drop(cursor);},
          Err(Error::Database(error)) if error.code().as_deref()==Some("0A000")=>{self.pending=true;let executed=self.worker.run(move|db|db.sql_json({let mut value:Json=serde_json::from_slice(&request).expect("request");value["limit"]=json!(4096);serde_json::to_vec(&value).expect("request")})).await;self.pending=false;let bytes=executed?;let (output,result)=rows(serde_json::from_slice(&bytes).map_err(protocol)?)?;for row in output{yield Either::Right(row)}yield Either::Left(result);},
          Err(error)=>Err(error)?,
         }
        })
    }
    fn fetch_optional<'e, 'q: 'e, E>(
        self,
        query: E,
    ) -> BoxFuture<'e, Result<Option<AntflyRow>, Error>>
    where
        'c: 'e,
        E: 'q + Execute<'q, Antfly>,
    {
        async move { self.fetch(query).try_next().await }.boxed()
    }
    fn prepare_with<'e>(
        self,
        sql: SqlStr,
        parameters: &'e [AntflyTypeInfo],
    ) -> BoxFuture<'e, Result<AntflyStatement, Error>>
    where
        'c: 'e,
    {
        self.description(sql, parameters.to_vec()).boxed()
    }
    fn describe<'e>(self, sql: SqlStr) -> BoxFuture<'e, Result<Describe<Antfly>, Error>>
    where
        'c: 'e,
    {
        async move {
            let statement = self.description(sql, Vec::new()).await?;
            Ok(Describe {
                nullable: vec![None; statement.columns.len()],
                columns: statement.columns,
                parameters: Some(Either::Left(statement.parameters)),
            })
        }
        .boxed()
    }
}

#[cfg(all(test, feature = "libantfly"))]
mod liveness_tests {
    use super::*;

    #[test]
    fn idle_ping_is_local_and_detects_a_stopped_worker() {
        let (sender, receiver) = mpsc::channel();
        let alive = Arc::new(AtomicBool::new(true));
        let worker = Arc::new(Worker {
            alive: Arc::clone(&alive),
            sender: Some(sender),
            thread: None,
        });
        let mut connection = AntflyConnection {
            worker,
            session: 1,
            depth: 0,
            pending: false,
            closed: false,
        };
        assert!(connection.ping().now_or_never().unwrap().is_ok());
        assert!(matches!(
            receiver.try_recv(),
            Err(mpsc::TryRecvError::Empty)
        ));
        drop(WorkerLifetime(alive));
        assert!(connection.ping().now_or_never().unwrap().is_err());
        connection.closed = true;
    }
}