Document which features are required, and add vtab usage examples (#669)

This commit is contained in:
Thom Chiovoloni 2020-04-05 22:15:27 -07:00 committed by GitHub
parent 6edf72857e
commit 6617db59fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 164 additions and 97 deletions

View File

@ -1,4 +1,4 @@
//! Online SQLite backup API. //! `feature = "backup"` Online SQLite backup API.
//! //!
//! To create a `Backup`, you must have two distinct `Connection`s - one //! To create a `Backup`, you must have two distinct `Connection`s - one
//! for the source (which can be used while the backup is running) and one for //! for the source (which can be used while the backup is running) and one for
@ -43,7 +43,9 @@ use crate::error::{error_from_handle, error_from_sqlite_code};
use crate::{Connection, DatabaseName, Result}; use crate::{Connection, DatabaseName, Result};
impl Connection { impl Connection {
/// Back up the `name` database to the given destination path. /// `feature = "backup"` Back up the `name` database to the given
/// destination path.
///
/// If `progress` is not `None`, it will be called periodically /// If `progress` is not `None`, it will be called periodically
/// until the backup completes. /// until the backup completes.
/// ///
@ -81,9 +83,9 @@ impl Connection {
} }
} }
/// Restore the given source path into the `name` database. /// `feature = "backup"` Restore the given source path into the
/// If `progress` is not `None`, it will be called periodically /// `name` database. If `progress` is not `None`, it will be
/// until the restore completes. /// called periodically until the restore completes.
/// ///
/// For more fine-grained control over the restore process (e.g., /// For more fine-grained control over the restore process (e.g.,
/// to sleep periodically during the restore or to restore from an /// to sleep periodically during the restore or to restore from an
@ -128,7 +130,7 @@ impl Connection {
} }
} }
/// Possible successful results of calling `Backup::step`. /// `feature = "backup"` Possible successful results of calling `Backup::step`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum StepResult { pub enum StepResult {
/// The backup is complete. /// The backup is complete.
@ -147,11 +149,11 @@ pub enum StepResult {
Locked, Locked,
} }
/// Struct specifying the progress of a backup. The percentage completion can /// `feature = "backup"` Struct specifying the progress of a backup. The
/// be calculated as `(pagecount - remaining) / pagecount`. The progress of a /// percentage completion can be calculated as `(pagecount - remaining) /
/// backup is as of the last call to `step` - if the source database is /// pagecount`. The progress of a backup is as of the last call to `step` - if
/// modified after a call to `step`, the progress value will become outdated /// the source database is modified after a call to `step`, the progress value
/// and potentially incorrect. /// will become outdated and potentially incorrect.
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub struct Progress { pub struct Progress {
/// Number of pages in the source database that still need to be backed up. /// Number of pages in the source database that still need to be backed up.
@ -160,7 +162,7 @@ pub struct Progress {
pub pagecount: c_int, pub pagecount: c_int,
} }
/// A handle to an online backup. /// `feature = "backup"` A handle to an online backup.
pub struct Backup<'a, 'b> { pub struct Backup<'a, 'b> {
phantom_from: PhantomData<&'a ()>, phantom_from: PhantomData<&'a ()>,
phantom_to: PhantomData<&'b ()>, phantom_to: PhantomData<&'b ()>,

View File

@ -1,4 +1,4 @@
//! Incremental BLOB I/O. //! `feature = "blob"` Incremental BLOB I/O.
//! //!
//! Note that SQLite does not provide API-level access to change the size of a //! Note that SQLite does not provide API-level access to change the size of a
//! BLOB; that must be performed through SQL statements. //! BLOB; that must be performed through SQL statements.
@ -60,7 +60,7 @@ use super::ffi;
use super::types::{ToSql, ToSqlOutput}; use super::types::{ToSql, ToSqlOutput};
use crate::{Connection, DatabaseName, Result}; use crate::{Connection, DatabaseName, Result};
/// Handle to an open BLOB. /// `feature = "blob"` Handle to an open BLOB.
pub struct Blob<'conn> { pub struct Blob<'conn> {
conn: &'conn Connection, conn: &'conn Connection,
blob: *mut ffi::sqlite3_blob, blob: *mut ffi::sqlite3_blob,
@ -68,8 +68,8 @@ pub struct Blob<'conn> {
} }
impl Connection { impl Connection {
/// Open a handle to the BLOB located in `row_id`, `column`, `table` in /// `feature = "blob"` Open a handle to the BLOB located in `row_id`, `column`,
/// database `db`. /// `table` in database `db`.
/// ///
/// # Failure /// # Failure
/// ///
@ -238,7 +238,7 @@ impl Drop for Blob<'_> {
} }
} }
/// BLOB of length N that is filled with zeroes. /// `feature = "blob"` BLOB of length N that is filled with zeroes.
/// ///
/// Zeroblobs are intended to serve as placeholders for BLOBs whose content is /// Zeroblobs are intended to serve as placeholders for BLOBs whose content is
/// later written using incremental BLOB I/O routines. /// later written using incremental BLOB I/O routines.

View File

@ -1,4 +1,4 @@
//! Add, remove, or modify a collation //! `feature = "collation"` Add, remove, or modify a collation
use std::cmp::Ordering; use std::cmp::Ordering;
use std::os::raw::{c_char, c_int, c_void}; use std::os::raw::{c_char, c_int, c_void};
use std::panic::{catch_unwind, UnwindSafe}; use std::panic::{catch_unwind, UnwindSafe};
@ -14,7 +14,7 @@ unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
} }
impl Connection { impl Connection {
/// Add or modify a collation. /// `feature = "collation"` Add or modify a collation.
pub fn create_collation<C>(&self, collation_name: &str, x_compare: C) -> Result<()> pub fn create_collation<C>(&self, collation_name: &str, x_compare: C) -> Result<()>
where where
C: Fn(&str, &str) -> Ordering + Send + UnwindSafe + 'static, C: Fn(&str, &str) -> Ordering + Send + UnwindSafe + 'static,
@ -24,7 +24,7 @@ impl Connection {
.create_collation(collation_name, x_compare) .create_collation(collation_name, x_compare)
} }
/// Collation needed callback /// `feature = "collation"` Collation needed callback
pub fn collation_needed( pub fn collation_needed(
&self, &self,
x_coll_needed: fn(&Connection, &str) -> Result<()>, x_coll_needed: fn(&Connection, &str) -> Result<()>,
@ -32,7 +32,7 @@ impl Connection {
self.db.borrow_mut().collation_needed(x_coll_needed) self.db.borrow_mut().collation_needed(x_coll_needed)
} }
/// Remove collation. /// `feature = "collation"` Remove collation.
pub fn remove_collation(&self, collation_name: &str) -> Result<()> { pub fn remove_collation(&self, collation_name: &str) -> Result<()> {
self.db.borrow_mut().remove_collation(collation_name) self.db.borrow_mut().remove_collation(collation_name)
} }

View File

@ -1,4 +1,4 @@
//! Create or redefine SQL functions. //! `feature = "functions"` Create or redefine SQL functions.
//! //!
//! # Example //! # Example
//! //!
@ -115,7 +115,8 @@ unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
drop(Box::from_raw(p as *mut T)); drop(Box::from_raw(p as *mut T));
} }
/// Context is a wrapper for the SQLite function evaluation context. /// `feature = "functions"` Context is a wrapper for the SQLite function
/// evaluation context.
pub struct Context<'a> { pub struct Context<'a> {
ctx: *mut sqlite3_context, ctx: *mut sqlite3_context,
args: &'a [*mut sqlite3_value], args: &'a [*mut sqlite3_value],
@ -205,7 +206,8 @@ impl Context<'_> {
} }
} }
/// Aggregate is the callback interface for user-defined aggregate function. /// `feature = "functions"` Aggregate is the callback interface for user-defined
/// aggregate function.
/// ///
/// `A` is the type of the aggregation context and `T` is the type of the final /// `A` is the type of the aggregation context and `T` is the type of the final
/// result. Implementations should be stateless. /// result. Implementations should be stateless.
@ -231,8 +233,8 @@ where
fn finalize(&self, _: Option<A>) -> Result<T>; fn finalize(&self, _: Option<A>) -> Result<T>;
} }
/// WindowAggregate is the callback interface for user-defined aggregate window /// `feature = "window"` WindowAggregate is the callback interface for
/// function. /// user-defined aggregate window function.
#[cfg(feature = "window")] #[cfg(feature = "window")]
pub trait WindowAggregate<A, T>: Aggregate<A, T> pub trait WindowAggregate<A, T>: Aggregate<A, T>
where where
@ -270,7 +272,8 @@ impl Default for FunctionFlags {
} }
impl Connection { impl Connection {
/// Attach a user-defined scalar function to this database connection. /// `feature = "functions"` Attach a user-defined scalar function to
/// this database connection.
/// ///
/// `fn_name` is the name the function will be accessible from SQL. /// `fn_name` is the name the function will be accessible from SQL.
/// `n_arg` is the number of arguments to the function. Use `-1` for a /// `n_arg` is the number of arguments to the function. Use `-1` for a
@ -321,7 +324,8 @@ impl Connection {
.create_scalar_function(fn_name, n_arg, flags, x_func) .create_scalar_function(fn_name, n_arg, flags, x_func)
} }
/// Attach a user-defined aggregate function to this database connection. /// `feature = "functions"` Attach a user-defined aggregate function to this
/// database connection.
/// ///
/// # Failure /// # Failure
/// ///
@ -343,6 +347,11 @@ impl Connection {
.create_aggregate_function(fn_name, n_arg, flags, aggr) .create_aggregate_function(fn_name, n_arg, flags, aggr)
} }
/// `feature = "window"` Attach a user-defined aggregate window function to
/// this database connection.
///
/// See https://sqlite.org/windowfunctions.html#udfwinfunc for more
/// information.
#[cfg(feature = "window")] #[cfg(feature = "window")]
pub fn create_window_function<A, W, T>( pub fn create_window_function<A, W, T>(
&self, &self,
@ -361,7 +370,8 @@ impl Connection {
.create_window_function(fn_name, n_arg, flags, aggr) .create_window_function(fn_name, n_arg, flags, aggr)
} }
/// Removes a user-defined function from this database connection. /// `feature = "functions"` Removes a user-defined function from this
/// database connection.
/// ///
/// `fn_name` and `n_arg` should match the name and number of arguments /// `fn_name` and `n_arg` should match the name and number of arguments
/// given to `create_scalar_function` or `create_aggregate_function`. /// given to `create_scalar_function` or `create_aggregate_function`.

View File

@ -1,4 +1,4 @@
//! Commit, Data Change and Rollback Notification Callbacks //! `feature = "hooks"` Commit, Data Change and Rollback Notification Callbacks
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
use std::os::raw::{c_char, c_int, c_void}; use std::os::raw::{c_char, c_int, c_void};
@ -9,7 +9,7 @@ use crate::ffi;
use crate::{Connection, InnerConnection}; use crate::{Connection, InnerConnection};
/// Action Codes /// `feature = "hooks"` Action Codes
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
#[repr(i32)] #[repr(i32)]
pub enum Action { pub enum Action {
@ -31,8 +31,8 @@ impl From<i32> for Action {
} }
impl Connection { impl Connection {
/// Register a callback function to be invoked whenever a transaction is /// `feature = "hooks"` Register a callback function to be invoked whenever
/// committed. /// a transaction is committed.
/// ///
/// The callback returns `true` to rollback. /// The callback returns `true` to rollback.
pub fn commit_hook<F>(&self, hook: Option<F>) pub fn commit_hook<F>(&self, hook: Option<F>)
@ -42,8 +42,8 @@ impl Connection {
self.db.borrow_mut().commit_hook(hook); self.db.borrow_mut().commit_hook(hook);
} }
/// Register a callback function to be invoked whenever a transaction is /// `feature = "hooks"` Register a callback function to be invoked whenever
/// committed. /// a transaction is committed.
/// ///
/// The callback returns `true` to rollback. /// The callback returns `true` to rollback.
pub fn rollback_hook<F>(&self, hook: Option<F>) pub fn rollback_hook<F>(&self, hook: Option<F>)
@ -53,8 +53,8 @@ impl Connection {
self.db.borrow_mut().rollback_hook(hook); self.db.borrow_mut().rollback_hook(hook);
} }
/// Register a callback function to be invoked whenever a row is updated, /// `feature = "hooks"` Register a callback function to be invoked whenever
/// inserted or deleted in a rowid table. /// a row is updated, inserted or deleted in a rowid table.
/// ///
/// The callback parameters are: /// The callback parameters are:
/// ///

View File

@ -653,8 +653,8 @@ impl Connection {
r.map_err(move |err| (self, err)) r.map_err(move |err| (self, err))
} }
/// Enable loading of SQLite extensions. Strongly consider using /// `feature = "load_extension"` Enable loading of SQLite extensions.
/// `LoadExtensionGuard` instead of this function. /// Strongly consider using `LoadExtensionGuard` instead of this function.
/// ///
/// ## Example /// ## Example
/// ///
@ -676,7 +676,7 @@ impl Connection {
self.db.borrow_mut().enable_load_extension(1) self.db.borrow_mut().enable_load_extension(1)
} }
/// Disable loading of SQLite extensions. /// `feature = "load_extension"` Disable loading of SQLite extensions.
/// ///
/// See `load_extension_enable` for an example. /// See `load_extension_enable` for an example.
/// ///
@ -688,9 +688,9 @@ impl Connection {
self.db.borrow_mut().enable_load_extension(0) self.db.borrow_mut().enable_load_extension(0)
} }
/// Load the SQLite extension at `dylib_path`. `dylib_path` is passed /// `feature = "load_extension"` Load the SQLite extension at `dylib_path`.
/// through to `sqlite3_load_extension`, which may attempt OS-specific /// `dylib_path` is passed through to `sqlite3_load_extension`, which may
/// modifications if the file cannot be loaded directly. /// attempt OS-specific modifications if the file cannot be loaded directly.
/// ///
/// If `entry_point` is `None`, SQLite will attempt to find the entry /// If `entry_point` is `None`, SQLite will attempt to find the entry
/// point. If it is not `None`, the entry point will be passed through /// point. If it is not `None`, the entry point will be passed through

View File

@ -1,4 +1,4 @@
//! Run-Time Limits //! `feature = "limits"` Run-Time Limits
use std::os::raw::c_int; use std::os::raw::c_int;
@ -8,13 +8,14 @@ pub use crate::ffi::Limit;
use crate::Connection; use crate::Connection;
impl Connection { impl Connection {
/// Returns the current value of a limit. /// `feature = "limits"` Returns the current value of a limit.
pub fn limit(&self, limit: Limit) -> i32 { pub fn limit(&self, limit: Limit) -> i32 {
let c = self.db.borrow(); let c = self.db.borrow();
unsafe { ffi::sqlite3_limit(c.db(), limit as c_int, -1) } unsafe { ffi::sqlite3_limit(c.db(), limit as c_int, -1) }
} }
/// Changes the limit to `new_val`, returning the prior value of the limit. /// `feature = "limits"` Changes the limit to `new_val`, returning the prior
/// value of the limit.
pub fn set_limit(&self, limit: Limit, new_val: i32) -> i32 { pub fn set_limit(&self, limit: Limit, new_val: i32) -> i32 {
let c = self.db.borrow_mut(); let c = self.db.borrow_mut();
unsafe { ffi::sqlite3_limit(c.db(), limit as c_int, new_val) } unsafe { ffi::sqlite3_limit(c.db(), limit as c_int, new_val) }

View File

@ -1,6 +1,7 @@
use crate::{Connection, Result}; use crate::{Connection, Result};
/// RAII guard temporarily enabling SQLite extensions to be loaded. /// `feature = "load_extension"` RAII guard temporarily enabling SQLite
/// extensions to be loaded.
/// ///
/// ## Example /// ## Example
/// ///

View File

@ -1,4 +1,4 @@
//! [Session Extension](https://sqlite.org/sessionintro.html) //! `feature = "session"` [Session Extension](https://sqlite.org/sessionintro.html)
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
use std::ffi::CStr; use std::ffi::CStr;
@ -20,7 +20,7 @@ use crate::{errmsg_to_string, str_to_cstring, Connection, DatabaseName, Result};
// https://sqlite.org/session.html // https://sqlite.org/session.html
/// An instance of this object is a session that can be used to record changes /// `feature = "session"` An instance of this object is a session that can be used to record changes
/// to a database. /// to a database.
pub struct Session<'conn> { pub struct Session<'conn> {
phantom: PhantomData<&'conn ()>, phantom: PhantomData<&'conn ()>,
@ -211,7 +211,7 @@ impl Drop for Session<'_> {
} }
} }
/// Invert a changeset /// `feature = "session"` Invert a changeset
pub fn invert_strm(input: &mut dyn Read, output: &mut dyn Write) -> Result<()> { pub fn invert_strm(input: &mut dyn Read, output: &mut dyn Write) -> Result<()> {
let input_ref = &input; let input_ref = &input;
let output_ref = &output; let output_ref = &output;
@ -226,7 +226,7 @@ pub fn invert_strm(input: &mut dyn Read, output: &mut dyn Write) -> Result<()> {
Ok(()) Ok(())
} }
/// Combine two changesets /// `feature = "session"` Combine two changesets
pub fn concat_strm( pub fn concat_strm(
input_a: &mut dyn Read, input_a: &mut dyn Read,
input_b: &mut dyn Read, input_b: &mut dyn Read,
@ -248,7 +248,7 @@ pub fn concat_strm(
Ok(()) Ok(())
} }
/// Changeset or Patchset /// `feature = "session"` Changeset or Patchset
pub struct Changeset { pub struct Changeset {
cs: *mut c_void, cs: *mut c_void,
n: c_int, n: c_int,
@ -296,7 +296,8 @@ impl Drop for Changeset {
} }
} }
/// Cursor for iterating over the elements of a changeset or patchset. /// `feature = "session"` Cursor for iterating over the elements of a changeset
/// or patchset.
pub struct ChangesetIter<'changeset> { pub struct ChangesetIter<'changeset> {
phantom: PhantomData<&'changeset ()>, phantom: PhantomData<&'changeset ()>,
it: *mut ffi::sqlite3_changeset_iter, it: *mut ffi::sqlite3_changeset_iter,
@ -347,6 +348,7 @@ impl FallibleStreamingIterator for ChangesetIter<'_> {
} }
} }
/// `feature = "session"`
pub struct Operation<'item> { pub struct Operation<'item> {
table_name: &'item str, table_name: &'item str,
number_of_columns: i32, number_of_columns: i32,
@ -380,7 +382,7 @@ impl Drop for ChangesetIter<'_> {
} }
} }
/// An item passed to a conflict-handler by `Connection::apply`, /// `feature = "session"` An item passed to a conflict-handler by `Connection::apply`,
/// or an item generated by `ChangesetIter::next`. /// or an item generated by `ChangesetIter::next`.
// TODO enum ? Delete, Insert, Update, ... // TODO enum ? Delete, Insert, Update, ...
pub struct ChangesetItem { pub struct ChangesetItem {
@ -493,7 +495,7 @@ impl ChangesetItem {
} }
} }
/// Used to combine two or more changesets or /// `feature = "session"` Used to combine two or more changesets or
/// patchsets /// patchsets
pub struct Changegroup { pub struct Changegroup {
cg: *mut ffi::sqlite3_changegroup, cg: *mut ffi::sqlite3_changegroup,
@ -558,7 +560,7 @@ impl Drop for Changegroup {
} }
impl Connection { impl Connection {
/// Apply a changeset to a database /// `feature = "session"` Apply a changeset to a database
pub fn apply<F, C>(&self, cs: &Changeset, filter: Option<F>, conflict: C) -> Result<()> pub fn apply<F, C>(&self, cs: &Changeset, filter: Option<F>, conflict: C) -> Result<()>
where where
F: Fn(&str) -> bool + Send + RefUnwindSafe + 'static, F: Fn(&str) -> bool + Send + RefUnwindSafe + 'static,
@ -592,7 +594,7 @@ impl Connection {
Ok(()) Ok(())
} }
/// Apply a changeset to a database /// `feature = "session"` Apply a changeset to a database
pub fn apply_strm<F, C>( pub fn apply_strm<F, C>(
&self, &self,
input: &mut dyn Read, input: &mut dyn Read,
@ -633,7 +635,7 @@ impl Connection {
} }
} }
/// Constants passed to the conflict handler /// `feature = "session"` Constants passed to the conflict handler
#[repr(i32)] #[repr(i32)]
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum ConflictType { pub enum ConflictType {
@ -657,7 +659,7 @@ impl From<i32> for ConflictType {
} }
} }
/// Constants returned by the conflict handler /// `feature = "session"` Constants returned by the conflict handler
#[repr(i32)] #[repr(i32)]
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum ConflictAction { pub enum ConflictAction {

View File

@ -1,4 +1,4 @@
//! Tracing and profiling functions. Error and warning log. //! `feature = "trace"` Tracing and profiling functions. Error and warning log.
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use std::mem; use std::mem;
@ -11,7 +11,7 @@ use super::ffi;
use crate::error::error_from_sqlite_code; use crate::error::error_from_sqlite_code;
use crate::{Connection, Result}; use crate::{Connection, Result};
/// Set up the process-wide SQLite error logging callback. /// `feature = "trace"` Set up the process-wide SQLite error logging callback.
/// ///
/// # Safety /// # Safety
/// ///
@ -56,7 +56,8 @@ pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> Result<()> {
} }
} }
/// Write a message into the error log established by `config_log`. /// `feature = "trace"` Write a message into the error log established by
/// `config_log`.
pub fn log(err_code: c_int, msg: &str) { pub fn log(err_code: c_int, msg: &str) {
let msg = CString::new(msg).expect("SQLite log messages cannot contain embedded zeroes"); let msg = CString::new(msg).expect("SQLite log messages cannot contain embedded zeroes");
unsafe { unsafe {
@ -65,8 +66,8 @@ pub fn log(err_code: c_int, msg: &str) {
} }
impl Connection { impl Connection {
/// Register or clear a callback function that can be used for tracing the /// `feature = "trace"` Register or clear a callback function that can be
/// execution of SQL statements. /// used for tracing the execution of SQL statements.
/// ///
/// Prepared statement placeholders are replaced/logged with their assigned /// Prepared statement placeholders are replaced/logged with their assigned
/// values. There can only be a single tracer defined for each database /// values. There can only be a single tracer defined for each database
@ -90,8 +91,8 @@ impl Connection {
} }
} }
/// Register or clear a callback function that can be used for profiling /// `feature = "trace"` Register or clear a callback function that can be
/// the execution of SQL statements. /// used for profiling the execution of SQL statements.
/// ///
/// There can only be a single profiler defined for each database /// There can only be a single profiler defined for each database
/// connection. Setting a new profiler clears the old one. /// connection. Setting a new profiler clears the old one.

View File

@ -13,13 +13,14 @@ pub enum FromSqlError {
/// requested type. /// requested type.
OutOfRange(i64), OutOfRange(i64),
/// Error returned when reading an `i128` from a blob with a size /// `feature = "i128_blob"` Error returned when reading an `i128` from a
/// other than 16. Only available when the `i128_blob` feature is enabled. /// blob with a size other than 16. Only available when the `i128_blob`
/// feature is enabled.
#[cfg(feature = "i128_blob")] #[cfg(feature = "i128_blob")]
InvalidI128Size(usize), InvalidI128Size(usize),
/// Error returned when reading a `uuid` from a blob with a size /// `feature = "uuid"` Error returned when reading a `uuid` from a blob with
/// other than 16. Only available when the `uuid` feature is enabled. /// a size other than 16. Only available when the `uuid` feature is enabled.
#[cfg(feature = "uuid")] #[cfg(feature = "uuid")]
InvalidUuidSize(usize), InvalidUuidSize(usize),

View File

@ -14,10 +14,12 @@ pub enum ToSqlOutput<'a> {
/// An owned SQLite-representable value. /// An owned SQLite-representable value.
Owned(Value), Owned(Value),
/// A BLOB of the given length that is filled with zeroes. /// `feature = "blob"` A BLOB of the given length that is filled with
/// zeroes.
#[cfg(feature = "blob")] #[cfg(feature = "blob")]
ZeroBlob(i32), ZeroBlob(i32),
/// `feature = "array"`
#[cfg(feature = "array")] #[cfg(feature = "array")]
Array(Array), Array(Array),
} }

View File

@ -1,6 +1,30 @@
//! Array Virtual Table. //! `feature = "array"` Array Virtual Table: https://www.sqlite.org/carray.html
//!
//! Note: `rarray`, not `carray` is the name of the table valued function we
//! define.
//! //!
//! Port of [carray](http://www.sqlite.org/cgi/src/finfo?name=ext/misc/carray.c) C extension. //! Port of [carray](http://www.sqlite.org/cgi/src/finfo?name=ext/misc/carray.c) C extension.
//!
//! # Example
//!
//! ```rust,no_run
//! # use rusqlite::{types::Value, Connection, Result, params};
//! # use std::rc::Rc;
//! fn example(db: &Connection) -> Result<()> {
//! // Note: This should be done once (usually when opening the DB).
//! rusqlite::vtab::array::load_module(&db)?;
//! let v = [1i64, 2, 3, 4];
//! // Note: A `Rc<Vec<Value>>` must be used as the parameter.
//! let values = Rc::new(v.iter().copied().map(Value::from).collect::<Vec<Value>>());
//! let mut stmt = db.prepare("SELECT value from rarray(?);")?;
//! let rows = stmt.query_map(params![values], |row| row.get::<_, i64>(0))?;
//! for value in rows {
//! println!("{}", value?);
//! }
//! Ok(())
//! }
//! ```
use std::default::Default; use std::default::Default;
use std::os::raw::{c_char, c_int, c_void}; use std::os::raw::{c_char, c_int, c_void};
use std::rc::Rc; use std::rc::Rc;
@ -29,7 +53,7 @@ impl ToSql for Array {
} }
} }
/// Register the "rarray" module. /// `feature = "array"` Register the "rarray" module.
pub fn load_module(conn: &Connection) -> Result<()> { pub fn load_module(conn: &Connection) -> Result<()> {
let aux: Option<()> = None; let aux: Option<()> = None;
conn.create_module("rarray", &ARRAY_MODULE, aux) conn.create_module("rarray", &ARRAY_MODULE, aux)

View File

@ -1,6 +1,25 @@
//! CSV Virtual Table. //! `feature = "csvtab"` CSV Virtual Table: https://www.sqlite.org/csv.html
//! //!
//! Port of [csv](http://www.sqlite.org/cgi/src/finfo?name=ext/misc/csv.c) C extension. //! Port of [csv](http://www.sqlite.org/cgi/src/finfo?name=ext/misc/csv.c) C extension.
//!
//! # Example
//!
//! ```rust,no_run
//! # use rusqlite::{Connection, Result};
//! fn example() -> Result<()> {
//! // Note: This should be done once (usually when opening the DB).
//! let db = Connection::open_in_memory()?;
//! rusqlite::vtab::csvtab::load_module(&db)?;
//! // Assum3e my_csv.csv
//! let schema = "
//! CREATE VIRTUAL TABLE my_csv_data
//! USING csv(filename = 'my_csv.csv')
//! ";
//! db.execute_batch(schema)?;
//! // Now the `my_csv_data` (virtual) table can be queried as normal...
//! Ok(())
//! }
//! ```
use std::fs::File; use std::fs::File;
use std::os::raw::c_int; use std::os::raw::c_int;
use std::path::Path; use std::path::Path;
@ -15,7 +34,7 @@ use crate::vtab::{
}; };
use crate::{Connection, Error, Result}; use crate::{Connection, Error, Result};
/// Register the "csv" module. /// `feature = "csvtab"` Register the "csv" module.
/// ```sql /// ```sql
/// CREATE VIRTUAL TABLE vtab USING csv( /// CREATE VIRTUAL TABLE vtab USING csv(
/// filename=FILENAME -- Name of file containing CSV content /// filename=FILENAME -- Name of file containing CSV content

View File

@ -1,4 +1,4 @@
//! Create virtual tables. //! `feature = "vtab"` Create virtual tables.
//! //!
//! Follow these steps to create your own virtual table: //! Follow these steps to create your own virtual table:
//! 1. Write implemenation of `VTab` and `VTabCursor` traits. //! 1. Write implemenation of `VTab` and `VTabCursor` traits.
@ -57,7 +57,7 @@ use crate::{str_to_cstring, Connection, Error, InnerConnection, Result};
// ffi::sqlite3_vtab => VTab // ffi::sqlite3_vtab => VTab
// ffi::sqlite3_vtab_cursor => VTabCursor // ffi::sqlite3_vtab_cursor => VTabCursor
/// Virtual table module /// `feature = "vtab"` Virtual table module
/// ///
/// (See [SQLite doc](https://sqlite.org/c3ref/module.html)) /// (See [SQLite doc](https://sqlite.org/c3ref/module.html))
#[repr(C)] #[repr(C)]
@ -77,7 +77,7 @@ fn zeroed_module() -> ffi::sqlite3_module {
unsafe { std::mem::MaybeUninit::zeroed().assume_init() } unsafe { std::mem::MaybeUninit::zeroed().assume_init() }
} }
/// Create a read-only virtual table implementation. /// `feature = "vtab"` Create a read-only virtual table implementation.
/// ///
/// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations). /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
pub fn read_only_module<T: CreateVTab>(version: c_int) -> Module<T> { pub fn read_only_module<T: CreateVTab>(version: c_int) -> Module<T> {
@ -115,7 +115,7 @@ pub fn read_only_module<T: CreateVTab>(version: c_int) -> Module<T> {
} }
} }
/// Create an eponymous only virtual table implementation. /// `feature = "vtab"` Create an eponymous only virtual table implementation.
/// ///
/// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations). /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
pub fn eponymous_only_module<T: VTab>(version: c_int) -> Module<T> { pub fn eponymous_only_module<T: VTab>(version: c_int) -> Module<T> {
@ -154,6 +154,7 @@ pub fn eponymous_only_module<T: VTab>(version: c_int) -> Module<T> {
} }
} }
/// `feature = "vtab"`
pub struct VTabConnection(*mut ffi::sqlite3); pub struct VTabConnection(*mut ffi::sqlite3);
impl VTabConnection { impl VTabConnection {
@ -179,7 +180,7 @@ impl VTabConnection {
} }
} }
/// Virtual table instance trait. /// `feature = "vtab"` Virtual table instance trait.
/// ///
/// Implementations must be like: /// Implementations must be like:
/// ```rust,ignore /// ```rust,ignore
@ -214,7 +215,7 @@ pub trait VTab: Sized {
fn open(&self) -> Result<Self::Cursor>; fn open(&self) -> Result<Self::Cursor>;
} }
/// Non-eponymous virtual table instance trait. /// `feature = "vtab"` Non-eponymous virtual table instance trait.
/// ///
/// (See [SQLite doc](https://sqlite.org/c3ref/vtab.html)) /// (See [SQLite doc](https://sqlite.org/c3ref/vtab.html))
pub trait CreateVTab: VTab { pub trait CreateVTab: VTab {
@ -243,7 +244,7 @@ pub trait CreateVTab: VTab {
} }
} }
///Index constraint operator. /// `feature = "vtab"` Index constraint operator.
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
#[allow(non_snake_case, non_camel_case_types)] #[allow(non_snake_case, non_camel_case_types)]
pub enum IndexConstraintOp { pub enum IndexConstraintOp {
@ -286,8 +287,8 @@ impl From<u8> for IndexConstraintOp {
} }
} }
/// Pass information into and receive the reply from the `VTab.best_index` /// `feature = "vtab"` Pass information into and receive the reply from the
/// method. /// `VTab.best_index` method.
/// ///
/// (See [SQLite doc](http://sqlite.org/c3ref/index_info.html)) /// (See [SQLite doc](http://sqlite.org/c3ref/index_info.html))
pub struct IndexInfo(*mut ffi::sqlite3_index_info); pub struct IndexInfo(*mut ffi::sqlite3_index_info);
@ -358,6 +359,7 @@ impl IndexInfo {
// TODO sqlite3_vtab_collation (http://sqlite.org/c3ref/vtab_collation.html) // TODO sqlite3_vtab_collation (http://sqlite.org/c3ref/vtab_collation.html)
} }
/// `feature = "vtab"`
pub struct IndexConstraintIter<'a> { pub struct IndexConstraintIter<'a> {
iter: slice::Iter<'a, ffi::sqlite3_index_constraint>, iter: slice::Iter<'a, ffi::sqlite3_index_constraint>,
} }
@ -374,7 +376,7 @@ impl<'a> Iterator for IndexConstraintIter<'a> {
} }
} }
/// WHERE clause constraint /// `feature = "vtab"` WHERE clause constraint.
pub struct IndexConstraint<'a>(&'a ffi::sqlite3_index_constraint); pub struct IndexConstraint<'a>(&'a ffi::sqlite3_index_constraint);
impl IndexConstraint<'_> { impl IndexConstraint<'_> {
@ -394,7 +396,7 @@ impl IndexConstraint<'_> {
} }
} }
/// Information about what parameters to pass to `VTabCursor.filter`. /// `feature = "vtab"` Information about what parameters to pass to `VTabCursor.filter`.
pub struct IndexConstraintUsage<'a>(&'a mut ffi::sqlite3_index_constraint_usage); pub struct IndexConstraintUsage<'a>(&'a mut ffi::sqlite3_index_constraint_usage);
impl IndexConstraintUsage<'_> { impl IndexConstraintUsage<'_> {
@ -409,6 +411,7 @@ impl IndexConstraintUsage<'_> {
} }
} }
/// `feature = "vtab"`
pub struct OrderByIter<'a> { pub struct OrderByIter<'a> {
iter: slice::Iter<'a, ffi::sqlite3_index_info_sqlite3_index_orderby>, iter: slice::Iter<'a, ffi::sqlite3_index_info_sqlite3_index_orderby>,
} }
@ -425,7 +428,7 @@ impl<'a> Iterator for OrderByIter<'a> {
} }
} }
/// A column of the ORDER BY clause. /// `feature = "vtab"` A column of the ORDER BY clause.
pub struct OrderBy<'a>(&'a ffi::sqlite3_index_info_sqlite3_index_orderby); pub struct OrderBy<'a>(&'a ffi::sqlite3_index_info_sqlite3_index_orderby);
impl OrderBy<'_> { impl OrderBy<'_> {
@ -440,7 +443,7 @@ impl OrderBy<'_> {
} }
} }
/// Virtual table cursor trait. /// `feature = "vtab"` Virtual table cursor trait.
/// ///
/// Implementations must be like: /// Implementations must be like:
/// ```rust,ignore /// ```rust,ignore
@ -474,7 +477,7 @@ pub trait VTabCursor: Sized {
fn rowid(&self) -> Result<i64>; fn rowid(&self) -> Result<i64>;
} }
/// Context is used by `VTabCursor.column` to specify the cell value. /// `feature = "vtab"` Context is used by `VTabCursor.column` to specify the cell value.
pub struct Context(*mut ffi::sqlite3_context); pub struct Context(*mut ffi::sqlite3_context);
impl Context { impl Context {
@ -487,8 +490,8 @@ impl Context {
// TODO sqlite3_vtab_nochange (http://sqlite.org/c3ref/vtab_nochange.html) // TODO sqlite3_vtab_nochange (http://sqlite.org/c3ref/vtab_nochange.html)
} }
/// Wrapper to `VTabCursor.filter` arguments, the values requested by /// `feature = "vtab"` Wrapper to `VTabCursor.filter` arguments, the values
/// `VTab.best_index`. /// requested by `VTab.best_index`.
pub struct Values<'a> { pub struct Values<'a> {
args: &'a [*mut ffi::sqlite3_value], args: &'a [*mut ffi::sqlite3_value],
} }
@ -576,7 +579,7 @@ impl<'a> Iterator for ValueIter<'a> {
} }
impl Connection { impl Connection {
/// Register a virtual table implementation. /// `feature = "vtab"` Register a virtual table implementation.
/// ///
/// Step 3 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations). /// Step 3 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
pub fn create_module<T: VTab>( pub fn create_module<T: VTab>(
@ -624,7 +627,8 @@ impl InnerConnection {
} }
} }
/// Escape double-quote (`"`) character occurences by doubling them (`""`). /// `feature = "vtab"` Escape double-quote (`"`) character occurences by
/// doubling them (`""`).
pub fn escape_double_quote(identifier: &str) -> Cow<'_, str> { pub fn escape_double_quote(identifier: &str) -> Cow<'_, str> {
if identifier.contains('"') { if identifier.contains('"') {
// escape quote by doubling them // escape quote by doubling them
@ -633,7 +637,7 @@ pub fn escape_double_quote(identifier: &str) -> Cow<'_, str> {
Borrowed(identifier) Borrowed(identifier)
} }
} }
/// Dequote string /// `feature = "vtab"` Dequote string
pub fn dequote(s: &str) -> &str { pub fn dequote(s: &str) -> &str {
if s.len() < 2 { if s.len() < 2 {
return s; return s;
@ -646,7 +650,7 @@ pub fn dequote(s: &str) -> &str {
_ => s, _ => s,
} }
} }
/// The boolean can be one of: /// `feature = "vtab"` The boolean can be one of:
/// ```text /// ```text
/// 1 yes true on /// 1 yes true on
/// 0 no false off /// 0 no false off

View File

@ -1,4 +1,4 @@
//! generate series virtual table. //! `feature = "series"` Generate series virtual table: https://www.sqlite.org/series.html
//! //!
//! Port of C [generate series "function"](http://www.sqlite.org/cgi/src/finfo?name=ext/misc/series.c). //! Port of C [generate series "function"](http://www.sqlite.org/cgi/src/finfo?name=ext/misc/series.c).
use std::default::Default; use std::default::Default;
@ -12,7 +12,7 @@ use crate::vtab::{
}; };
use crate::{Connection, Result}; use crate::{Connection, Result};
/// Register the "generate_series" module. /// `feature = "series"` Register the "generate_series" module.
pub fn load_module(conn: &Connection) -> Result<()> { pub fn load_module(conn: &Connection) -> Result<()> {
let aux: Option<()> = None; let aux: Option<()> = None;
conn.create_module("generate_series", &SERIES_MODULE, aux) conn.create_module("generate_series", &SERIES_MODULE, aux)