cartel-sqlite 0.24.0

SQLite driver for the dope runtime
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
pub(crate) use crate::sys::Step;
use crate::{
    api::{self, stmt},
    catalogs, config, sys,
};
use api::{exec, work};
pub(crate) use controls::Controls;
use guard::open;
pub(crate) use progress::Progress;
use std::{marker, mem, ptr, result};
use stmt::access::Access;
use work::guard;

pub(crate) mod access;
mod binder;
mod bound;
mod control;
mod controls;
mod progress;
mod storage;
pub(crate) use binder::Binder;
pub(crate) use bound::Bound;
pub(crate) use control::Control;
pub(crate) use storage::Storage;
pub(crate) mod target;

pub(crate) enum Inventory {
    Empty,
    Populated,
}

pub(crate) struct Engine<'connection, I: catalogs::Catalog> {
    statements: Set<'connection, I>,
    connection: &'connection crate::sys::Connection,
}

impl<'connection, I: catalogs::Catalog> Engine<'connection, I> {
    pub(crate) fn transaction(&self) -> sys::Tx {
        self.connection.transaction()
    }

    pub(crate) fn controls(&mut self) -> Controls<'_, 'connection> {
        Controls::new(&mut self.statements)
    }

    pub(crate) fn retire(self) -> Retirement<'connection> {
        self.statements.retire()
    }
}

pub(crate) struct Prepare<'connection, I: catalogs::Catalog> {
    statements: Prefix<'connection, I>,
    connection: &'connection crate::sys::Connection,
    capacity: config::Capacity,
    used: usize,
}

impl<'connection, I: catalogs::Catalog> Prepare<'connection, I> {
    /// # Safety
    /// The sole opening admission retains this database and its fresh, empty
    /// catalog storage together until every prepared statement is released.
    pub(crate) unsafe fn new(
        db: &'connection crate::sys::Connection,
        storage: &'connection mut Storage<I>,
        bytes: config::Capacity,
    ) -> Self {
        Self {
            statements: Prefix {
                slots: storage.slots(),
                live: 0,
                marker: marker::PhantomData,
            },
            connection: db,
            capacity: bytes,
            used: 0,
        }
    }

    pub(crate) fn advance(
        mut self,
        guard: &guard::Guard<'connection, open::Open>,
    ) -> result::Result<Progress<Self, Engine<'connection, I>>, (Self, crate::Error)> {
        match self.insert(guard) {
            Ok(true) => {
                // SAFETY: insertion completed the exact catalog's entire backing slice.
                let stmts = unsafe { self.statements.finish() };
                Ok(Progress::Ready(Engine {
                    statements: stmts,
                    connection: self.connection,
                }))
            }
            Ok(false) => Ok(Progress::Pending(self)),
            Err(error) => Err((self, error)),
        }
    }

    fn insert(
        &mut self,
        guard: &guard::Guard<'connection, open::Open>,
    ) -> result::Result<bool, crate::Error> {
        let index = self.statements.live;
        let call = guard.call(self.connection);
        let prepare = |sql, params, columns| {
            call.check(Prepared::new(
                call.inner(),
                guard.work(),
                sql,
                params,
                columns,
            ))
        };
        // Native authorization runs during preparation; transaction authority
        // belongs only to these fixed controls, never to catalog SQL.
        let stmt = if let Some(control) = Control::ALL.get(index) {
            guard
                .work()
                .control()
                .run(|| prepare(control.sql(), 0, 0))?
        } else {
            // SAFETY: the branded storage has exactly the controls and I's entries;
            // this preparation still owns its next vacant position.
            let meta = unsafe { I::STATEMENTS.get_unchecked(index - Control::ALL.len()) };
            prepare(meta.sql(), meta.parameters(), meta.columns())?
        };
        let bytes = stmt.bytes();
        let required = self.used + bytes;
        let limit = self.capacity.get();
        if required > limit {
            return Err(crate::Error::StatementBytes {
                required,
                available: limit,
            });
        }
        // SAFETY: pending preparation retains its bounded initialized prefix and
        // the next empty slot; completion consumes it before another insertion.
        let slot = unsafe { self.statements.slots.get_unchecked_mut(index) };
        *slot = Some(stmt);
        self.used = required;
        self.statements.live = index + 1;
        Ok(self.statements.live == self.statements.slots.len())
    }

    pub(crate) fn retire_one(&mut self) -> Inventory {
        self.statements.retire_one()
    }
}

struct Set<'connection, I: catalogs::Catalog> {
    slots: &'connection mut [Slot<'connection>],
    marker: marker::PhantomData<I>,
}

struct Prefix<'connection, I: catalogs::Catalog> {
    slots: &'connection mut [Slot<'connection>],
    live: usize,
    marker: marker::PhantomData<I>,
}

/// Consumed catalog ownership; no statement can be queried after this transition.
pub(crate) struct Retirement<'connection> {
    slots: &'connection mut [Slot<'connection>],
}

pub(super) type Slot<'connection> = Option<Prepared<'connection>>;

impl<'connection, I: catalogs::Catalog> Set<'connection, I> {
    fn lease<Q: catalogs::TypedQuery>(
        &mut self,
        key: catalogs::Statement<I, Q>,
    ) -> &mut Prepared<'connection>
    where
        I: catalogs::HasQuery<Q>,
    {
        let slot = key.slot();
        let index = config::CONTROL_STATEMENT_ITEMS + slot;
        // SAFETY: admission binds this key to I, and this completed owner retains
        // every initialized control and catalog slot until consuming retirement.
        unsafe {
            self.slots
                .get_unchecked_mut(index)
                .as_mut_slice()
                .get_unchecked_mut(0)
        }
    }

    fn retire(mut self) -> Retirement<'connection> {
        Retirement {
            slots: mem::take(&mut self.slots),
        }
    }
}

impl<I: catalogs::Catalog> Drop for Set<'_, I> {
    fn drop(&mut self) {
        Retirement {
            slots: mem::take(&mut self.slots),
        }
        .retire_all();
    }
}

impl<'connection, I: catalogs::Catalog> Prefix<'connection, I> {
    /// # Safety
    /// Every slot in this exact retained backing has been initialized.
    unsafe fn finish(mut self) -> Set<'connection, I> {
        let slots = mem::take(&mut self.slots);
        self.live = 0;
        Set {
            slots,
            marker: marker::PhantomData,
        }
    }

    fn retire_one(&mut self) -> Inventory {
        // SAFETY: preparation advances only this backing's exact initialized prefix.
        let live = unsafe { self.slots.get_unchecked_mut(..self.live) };
        let Some((slot, rest)) = live.split_last_mut() else {
            return Inventory::Empty;
        };
        self.live = rest.len();
        *slot = None;
        match self.live {
            0 => Inventory::Empty,
            _ => Inventory::Populated,
        }
    }
}

impl<I: catalogs::Catalog> Drop for Prefix<'_, I> {
    fn drop(&mut self) {
        let slots = mem::take(&mut self.slots);
        // SAFETY: this owner retains precisely its initialized prefix and backing.
        let slots = unsafe { slots.get_unchecked_mut(..self.live) };
        Retirement { slots }.retire_all();
    }
}

impl Retirement<'_> {
    pub(crate) fn retire_one(&mut self) -> Inventory {
        if let Some((slot, rest)) = mem::take(&mut self.slots).split_last_mut() {
            self.slots = rest;
            *slot = None;
        }
        self.inventory()
    }

    pub(crate) fn retire_all(&mut self) {
        for slot in mem::take(&mut self.slots).iter_mut().rev() {
            *slot = None;
        }
    }

    pub(crate) const fn inventory(&self) -> Inventory {
        if self.slots.is_empty() {
            Inventory::Empty
        } else {
            Inventory::Populated
        }
    }
}

impl Drop for Retirement<'_> {
    fn drop(&mut self) {
        self.retire_all();
    }
}

pub(crate) fn bytes(items: usize) -> Option<usize> {
    let bytes = items.checked_mul(mem::size_of::<Slot<'_>>())?;
    let rounded = bytes.checked_add(storage::ALIGNMENT - 1)?;
    Some((rounded / storage::ALIGNMENT) * storage::ALIGNMENT)
}

const _: () = {
    let word = mem::size_of::<usize>();
    assert!(mem::size_of::<Set<'static, catalogs::Empty>>() == 2 * word);
    assert!(mem::size_of::<Engine<'static, catalogs::Empty>>() == 3 * word);
    assert!(mem::size_of::<Prefix<'static, catalogs::Empty>>() == 3 * word);
    assert!(mem::size_of::<Prepare<'static, catalogs::Empty>>() == 6 * word);
    assert!(mem::size_of::<Retirement<'static>>() == 2 * word);
    assert!(mem::size_of::<Slot<'static>>() == 3 * word);
    assert!(mem::size_of::<Prepared<'static>>() == 3 * word);
};

pub(crate) struct Prepared<'connection> {
    statement: ptr::NonNull<libsqlite3_sys::sqlite3_stmt>,
    work: &'connection work::Work,
    parameters: u32,
    columns: u32,
    connection: marker::PhantomData<&'connection crate::sys::Connection>,
}

impl<'connection> Prepared<'connection> {
    pub(crate) const fn as_non_null(&self) -> ptr::NonNull<libsqlite3_sys::sqlite3_stmt> {
        self.statement
    }

    pub(in crate::engine::api) fn transaction(&self) -> sys::Tx {
        // SAFETY: this prepared owner retains its live statement and original database.
        unsafe { sys::statement_tx(self.statement) }
    }
    pub(crate) fn new(
        db: &'connection crate::sys::Connection,
        work: &'connection work::Work,
        sql: &str,
        params: usize,
        columns: usize,
    ) -> result::Result<Self, crate::Error> {
        let sql = crate::sys::Sql::new(sql)?;
        sql.prepare(
            db,
            libsqlite3_sys::SQLITE_PREPARE_PERSISTENT,
            Err,
            |stmt, tail| {
                let mut prepared = Self {
                    statement: stmt,
                    work,
                    parameters: 0,
                    columns: 0,
                    connection: marker::PhantomData,
                };
                tail.check()?;
                // SAFETY: this prepared owner retains the live statement and database.
                prepared.parameters = unsafe { sys::statement_parameters(stmt, params) }?;
                prepared.columns = unsafe { sys::statement_columns(stmt) };
                if columns != usize::MAX && prepared.columns as usize != columns {
                    return Err(crate::Error::ColumnCount {
                        expected: columns,
                        actual: prepared.columns as usize,
                    });
                }
                Ok(prepared)
            },
        )
    }

    /// Samples only fresh persistent preparations, before binding or stepping.
    /// Persistent preparation excludes lookaside; every counted allocation is
    /// owned by the retained Core arena admitted at no more than i32::MAX bytes.
    fn bytes(&self) -> usize {
        let bytes = unsafe {
            libsqlite3_sys::sqlite3_stmt_status(
                self.statement.as_ptr(),
                libsqlite3_sys::SQLITE_STMTSTATUS_MEMUSED,
                0,
            )
        };
        bytes as usize
    }

    fn params(&self) -> usize {
        self.parameters as usize
    }

    fn columns<const CURRENT: bool>(&self) -> usize {
        if !CURRENT {
            return self.columns as usize;
        }
        // SAFETY: this owner retains the live statement and original database.
        unsafe { sys::statement_columns(self.statement) as usize }
    }

    pub(crate) fn step<A: Access>(
        &mut self,
        access: &A,
        txn: exec::Tx<'_>,
    ) -> result::Result<Step, crate::Error> {
        let code = unsafe { libsqlite3_sys::sqlite3_step(self.statement.as_ptr()) };
        match code {
            libsqlite3_sys::SQLITE_ROW => Ok(Step::Row),
            libsqlite3_sys::SQLITE_DONE => Ok(Step::Done),
            code => {
                // SAFETY: this owner retains the failed statement and connection.
                // The admitted native build repeats this step failure on reset;
                // its built-in cleanup cannot replace it with a new error.
                unsafe { libsqlite3_sys::sqlite3_reset(self.statement.as_ptr()) };
                Err(txn.error(self, access, sys::Action::Step, code))
            }
        }
    }

    fn reset<A: Access>(
        &mut self,
        access: &A,
        txn: exec::Tx<'_>,
    ) -> result::Result<(), crate::Error> {
        let code = unsafe { libsqlite3_sys::sqlite3_reset(self.statement.as_ptr()) };
        self.clear();
        if code == libsqlite3_sys::SQLITE_OK {
            Ok(())
        } else {
            Err(txn.error(self, access, sys::Action::Reset, code))
        }
    }

    fn clear(&mut self) {
        // SAFETY: this owner retains its admitted live, nonnull statement.
        // libsqlite3-sys 0.38.1's native clear only fails its null-handle check.
        unsafe { libsqlite3_sys::sqlite3_clear_bindings(self.statement.as_ptr()) };
    }
}

impl Drop for Prepared<'_> {
    fn drop(&mut self) {
        if let Some(fault) = sys::finalize(self.statement) {
            self.work.finalized(fault);
        }
    }
}