squire 0.0.1-alpha.3

Safe and idiomatic SQLite bindings
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
use core::{ffi::c_int, marker::PhantomData};
use sqlite::{SQLITE_PREPARE_DONT_LOG, SQLITE_PREPARE_NO_VTAB, SQLITE_PREPARE_PERSISTENT, sqlite3};

use crate::{
    bind::{Bind, Index},
    column::{Column, Columns},
    connection::Connection,
    error::{Error, ErrorLocation, ErrorMessage, Result},
    ffi,
    param::Parameters,
    row::Row,
    types::RowId,
};

/// A [prepared statement][]; an SQL statement that SQLite has compiled and made
/// ready to [bind](Self::bind()) and [execute](Execution).
///
/// [prepared statement]: https://sqlite.org/c3ref/stmt.html
#[derive(Debug)]
#[repr(transparent)]
pub struct Statement<'c> {
    inner: ffi::Statement<'c>,
}

impl<'c> Statement<'c> {
    #[inline]
    #[must_use]
    pub(crate) const fn new(inner: ffi::Statement<'c>) -> Self {
        Self { inner }
    }

    /// Compile SQL `query` text into a [prepared statement](Self) that SQLite
    /// can execute.
    ///
    /// See [`PrepareOptions`] for the flags `prepare` understands. By default,
    /// SQLite will prepare the statement _transiently_, using limited memory
    /// that SQLite uses for short-lived operations (“lookaside allocator”). Use
    /// [`PrepareOptions::persistent()`] if the statement will be executed again
    /// over the program run.
    #[must_use]
    pub fn prepare(
        connection: &'c Connection,
        query: impl AsRef<str>,
        options: PrepareOptions,
    ) -> Result<Self, (ErrorMessage, Option<ErrorLocation>)> {
        ffi::Statement::prepare(
            connection.internal_ref(),
            query.as_ref(),
            options.into_inner(),
        )
        .map(|(statement, _)| Self::new(statement))
    }

    pub fn binding(&mut self) -> Binding<'c, '_> {
        Binding { statement: self }
    }

    pub fn bind<'s, P>(&'s mut self, parameters: P) -> Result<Binding<'c, 's>>
    where
        P: Parameters<'s>,
    {
        let indexes =
            P::resolve(self).ok_or(Error::resolve("cannot resolve bind parameter indexes"))?;

        let mut binding = self.binding();
        parameters.bind(&mut binding, indexes)?;
        Ok(binding)
    }
    pub fn query<'s, P>(&'s mut self, parameters: P) -> Result<Execution<'c, 's>>
    where
        P: Parameters<'s>,
    {
        self.bind(parameters).map(Binding::done)
    }

    pub fn execute<P>(&mut self, parameters: P) -> Result<isize>
    where
        P: for<'a> Parameters<'a>,
    {
        self.query(parameters)?.run()
    }

    pub fn insert<P>(&mut self, parameters: P) -> Result<Option<RowId>>
    where
        P: for<'a> Parameters<'a>,
    {
        self.query(parameters)?.insert()
    }

    /// Inspect the [columns](StatementColumns) returned by this statement.
    pub fn columns<'s>(&'s self) -> StatementColumns<'c, 's> {
        StatementColumns::new(self)
    }

    /// Inspect the [parameters](StatementParameters) declared by this statement.
    pub fn parameters<'s>(&'s self) -> StatementParameters<'c, 's> {
        StatementParameters::new(self)
    }

    /// Access the [`ffi::Statement`] underlying this [`Statement`].
    #[inline]
    pub(crate) fn internal_ref(&self) -> &ffi::Statement<'c> {
        &self.inner
    }

    /// Mutate the [`ffi::Statement`] underlying this [`Statement`].
    #[inline]
    pub(crate) fn internal_mut(&mut self) -> &mut ffi::Statement<'c> {
        &mut self.inner
    }
}

impl<'c> ffi::Connected for Statement<'c> {
    fn as_connection_ptr(&self) -> *mut sqlite3 {
        unsafe { self.internal_ref().connection_ptr() }
    }
}

impl<'c, 's> ffi::Connected for &'s mut Statement<'c> {
    fn as_connection_ptr(&self) -> *mut sqlite3 {
        unsafe { self.internal_ref().connection_ptr() }
    }
}

pub trait Execute<'c, 's>: ffi::Connected
where
    'c: 's,
{
    fn cursor<'e>(&'e self) -> &'e Statement<'c>
    where
        's: 'e;

    fn cursor_mut<'e>(&'e mut self) -> &'e mut Statement<'c>
    where
        's: 'e;

    fn reset(&mut self) -> Result<(), ()>;
}

impl<'c, 's> Execute<'c, 's> for Statement<'c>
where
    'c: 's,
{
    fn cursor<'e>(&'e self) -> &'e Statement<'c>
    where
        's: 'e,
    {
        self
    }

    fn cursor_mut<'e>(&'e mut self) -> &'e mut Statement<'c>
    where
        's: 'e,
    {
        self
    }

    #[inline(always)]
    fn reset(&mut self) -> Result<(), ()> {
        Ok(())
    }
}

impl<'c, 's> Execute<'c, 's> for &'s mut Statement<'c> {
    fn cursor<'e>(&'e self) -> &'e Statement<'c>
    where
        's: 'e,
    {
        self
    }

    fn cursor_mut<'e>(&'e mut self) -> &'e mut Statement<'c>
    where
        's: 'e,
    {
        self
    }

    #[inline(always)]
    fn reset(&mut self) -> Result<(), ()> {
        unsafe { self.internal_mut().reset() }
    }
}

/// Controls the behavior of [preparing](Statement::prepare()) a [`Statement`].
#[derive(PartialEq, Eq, Default, Clone, Copy)]
pub struct PrepareOptions(u32);

impl PrepareOptions {
    const DONT_LOG: u32 = SQLITE_PREPARE_DONT_LOG as u32;
    const NO_VTAB: u32 = SQLITE_PREPARE_NO_VTAB as u32;
    const PERSISTENT: u32 = SQLITE_PREPARE_PERSISTENT as u32;

    pub const fn transient() -> Self {
        Self(0)
    }

    pub const fn persistent() -> Self {
        Self(Self::PERSISTENT)
    }

    pub const fn allow_virtual_tables(&self, allowed: bool) -> Self {
        if allowed {
            Self(self.0 & !Self::NO_VTAB)
        } else {
            Self(self.0 | Self::NO_VTAB)
        }
    }

    pub const fn log(&self, allowed: bool) -> Self {
        if allowed {
            Self(self.0 & !Self::DONT_LOG)
        } else {
            Self(self.0 | Self::DONT_LOG)
        }
    }

    pub const fn into_inner(self) -> u32 {
        self.0
    }
}

#[derive(Debug)]
#[repr(transparent)]
pub struct Binding<'c, 's>
where
    'c: 's,
{
    statement: &'s mut Statement<'c>,
}

impl<'c, 's> Binding<'c, 's>
where
    'c: 's,
{
    pub fn set<B>(&mut self, index: Index, value: B) -> Result<()>
    where
        B: Bind<'s>,
    {
        unsafe {
            self.statement
                .internal_mut()
                .bind(index, value.into_bind_value()?)
        }
    }

    pub fn ready<'b>(&'b mut self) -> Execution<'c, 's, &'b mut Self> {
        Execution::new(self)
    }

    pub fn done(self) -> Execution<'c, 's> {
        Execution::new(self)
    }
}

impl<'c, 's> ffi::Connected for Binding<'c, 's>
where
    'c: 's,
{
    fn as_connection_ptr(&self) -> *mut sqlite3 {
        self.statement.as_connection_ptr()
    }
}

impl<'c, 's> Execute<'c, 's> for Binding<'c, 's>
where
    'c: 's,
{
    fn cursor<'e>(&'e self) -> &'e Statement<'c>
    where
        's: 'e,
    {
        &self.statement
    }

    fn cursor_mut<'e>(&'e mut self) -> &'e mut Statement<'c>
    where
        's: 'e,
    {
        &mut self.statement
    }

    fn reset(&mut self) -> Result<(), ()> {
        let inner = self.statement.internal_mut();

        inner.clear()?;
        unsafe { inner.reset() }
    }
}

impl<'c, 's, 'b> ffi::Connected for &'b mut Binding<'c, 's> {
    fn as_connection_ptr(&self) -> *mut sqlite3 {
        self.statement.as_connection_ptr()
    }
}

impl<'c, 's, 'b> Execute<'c, 's> for &'b mut Binding<'c, 's>
where
    'c: 's,
    's: 'b,
{
    fn cursor<'e>(&'e self) -> &'e Statement<'c>
    where
        's: 'e,
    {
        &self.statement
    }

    fn cursor_mut<'e>(&'e mut self) -> &'e mut Statement<'c>
    where
        's: 'e,
    {
        &mut self.statement
    }

    fn reset(&mut self) -> Result<(), ()> {
        let inner = self.statement.internal_mut();

        unsafe { inner.reset() }
    }
}

#[derive(Debug)]
#[repr(transparent)]
pub struct Execution<'c, 's, S = Binding<'c, 's>>
where
    S: Execute<'c, 's>,
    'c: 's,
{
    inner: S,
    _lifetime: PhantomData<&'s mut Statement<'c>>,
}

impl<'c, 's, S> Execution<'c, 's, S>
where
    S: Execute<'c, 's>,
    'c: 's,
{
    #[inline]
    const fn new(inner: S) -> Self {
        Self {
            inner,
            _lifetime: PhantomData,
        }
    }

    pub fn row(&mut self) -> Result<Option<Row<'c, 's, '_, S>>> {
        let more = unsafe { self.cursor().internal_ref().row() }?;
        Ok(if more { Some(Row::new(self)) } else { None })
    }

    pub fn next<C>(mut self) -> Result<Option<C>>
    where
        C: for<'r> Columns<'r>,
    {
        if let Some(indexes) = C::resolve(self.cursor()) {
            match self.row() {
                Ok(Some(mut row)) => Ok(Some(row.unpack(indexes)?)),
                Ok(None) => Ok(None),
                Err(err) => Err(err),
            }
        } else {
            Err(Error::resolve("failed to resolve column indexes"))
        }
    }

    pub fn run(self) -> Result<isize> {
        unsafe { self.cursor().internal_ref().execute() }
    }

    pub fn insert(self) -> Result<Option<RowId>> {
        unsafe { self.cursor().internal_ref().execute() }
    }

    #[inline]
    pub(crate) fn cursor<'e>(&'e self) -> &'e Statement<'c>
    where
        'c: 'e,
        Self: 'e,
    {
        self.inner.cursor()
    }
}

impl<'c, 's, S> ffi::Connected for Execution<'c, 's, S>
where
    S: Execute<'c, 's>,
    'c: 's,
{
    #[inline]
    fn as_connection_ptr(&self) -> *mut sqlite3 {
        self.inner.as_connection_ptr()
    }
}

impl<'c, 's, S> Drop for Execution<'c, 's, S>
where
    S: Execute<'c, 's>,
    'c: 's,
{
    fn drop(&mut self) {
        let _ = self.inner.reset();
    }
}

#[derive(Debug)]
pub struct StatementColumns<'c, 's>
where
    'c: 's,
{
    statement: &'s Statement<'c>,
}

impl<'c, 's> StatementColumns<'c, 's>
where
    'c: 's,
{
    const fn new(statement: &'s Statement<'c>) -> Self {
        Self { statement }
    }

    pub fn name(&self, column: Column) -> Option<&str> {
        self.statement
            .internal_ref()
            .column_name(column)
            .map(|name| unsafe { str::from_utf8_unchecked(name.to_bytes()) })
    }

    pub fn index(&self, name: impl AsRef<str>) -> Option<Column> {
        let name = name.as_ref();

        for index in self.iter() {
            if let Some(n) = self.name(index)
                && name == n
            {
                return Some(index);
            }
        }

        None
    }

    pub fn iter(&self) -> impl Iterator<Item = Column> {
        StatementColumnIter::new(self.count())
    }

    pub fn len(&self) -> usize {
        self.count() as usize
    }

    fn count(&self) -> c_int {
        self.statement.internal_ref().column_count()
    }
}

impl<'c, 's> IntoIterator for StatementColumns<'c, 's>
where
    'c: 's,
{
    type Item = Column;
    type IntoIter = StatementColumnIter;

    fn into_iter(self) -> Self::IntoIter {
        StatementColumnIter::new(self.count())
    }
}

#[derive(Debug)]
pub struct StatementColumnIter {
    current: c_int,
    count: c_int,
}

impl StatementColumnIter {
    const fn new(count: c_int) -> Self {
        Self { current: 0, count }
    }
}

impl Iterator for StatementColumnIter {
    type Item = Column;

    fn next(&mut self) -> Option<Self::Item> {
        let current = self.current;

        if current < self.count {
            self.current = self.current + 1;
            Some(Column::new(current))
        } else {
            None
        }
    }
}

#[derive(Debug)]
pub struct StatementParameters<'c, 's>
where
    'c: 's,
{
    statement: &'s Statement<'c>,
}

impl<'c, 's> StatementParameters<'c, 's>
where
    'c: 's,
{
    const fn new(statement: &'s Statement<'c>) -> Self {
        Self { statement }
    }

    pub fn name(&self, index: Index) -> Option<&str> {
        self.statement
            .internal_ref()
            .parameter_name(index)
            .map(|name| unsafe { str::from_utf8_unchecked(name.to_bytes()) })
    }

    pub fn index(&self, name: impl AsRef<str>) -> Option<Index> {
        let name = name.as_ref();

        for index in self.iter() {
            if let Some(n) = self.name(index)
                && name == n
            {
                return Some(index);
            }
        }

        None
    }

    pub fn iter(&self) -> impl Iterator<Item = Index> {
        StatementParameterIter::new(self)
    }

    pub fn len(&self) -> usize {
        self.count() as usize
    }

    fn count(&self) -> c_int {
        self.statement.internal_ref().parameter_count()
    }

    fn max(&self) -> Option<Index> {
        Index::new(self.count()).ok()
    }
}

impl<'c, 's> IntoIterator for StatementParameters<'c, 's>
where
    'c: 's,
{
    type Item = Index;
    type IntoIter = StatementParameterIter;

    fn into_iter(self) -> Self::IntoIter {
        StatementParameterIter::new(&self)
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(transparent)]
pub struct StatementParameterIter {
    state: StatementParameterIterState,
}

impl StatementParameterIter {
    fn new<'c, 's>(parameters: &StatementParameters<'c, 's>) -> Self
    where
        'c: 's,
    {
        let state = match parameters.max() {
            Some(max) => StatementParameterIterState::Next {
                current: Index::INITIAL,
                max,
            },
            None => StatementParameterIterState::Done,
        };

        Self { state }
    }
}

impl Iterator for StatementParameterIter {
    type Item = Index;

    fn next(&mut self) -> Option<Self::Item> {
        match self.state {
            StatementParameterIterState::Next { current, max } => {
                self.state = if current < max {
                    StatementParameterIterState::Next {
                        current: current.next(),
                        max,
                    }
                } else {
                    StatementParameterIterState::Done
                };

                Some(current)
            }
            StatementParameterIterState::Done => None,
        }
    }
}

#[derive(Copy, Clone, Debug)]
enum StatementParameterIterState {
    Next { current: Index, max: Index },
    Done,
}