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
//! # Virtual Table implementation

use rusqlite::vtab::{read_only_module, CreateVTab, IndexConstraintOp, VTab, VTabCursor};

use crate::mem;

#[repr(C)]
struct FdbTab<'vtab> {
    /// Base class. Must be first
    base: rusqlite::vtab::sqlite3_vtab,
    /* Virtual table implementations will typically add additional fields */
    table: mem::Table<'vtab>,
}

/// Register the module
pub fn load_module(
    conn: &rusqlite::Connection,
    db: mem::Database<'static>,
) -> rusqlite::Result<()> {
    conn.create_module("fdb", read_only_module::<FdbTab>(), Some(db))
}

struct BufferedIter<'vtab> {
    /// The backing iterator
    iter: mem::iter::TableRowIter<'vtab>,
    /// The item at the front
    next: Option<mem::Row<'vtab>>,
    /// The rowid
    rowid: i64,
}

impl<'vtab> BufferedIter<'vtab> {
    pub fn new(mut iter: mem::iter::TableRowIter<'vtab>) -> Self {
        let next = iter.next();
        Self {
            iter,
            next,
            rowid: 0,
        }
    }

    #[inline]
    pub fn eof(&self) -> bool {
        self.next.is_none()
    }

    pub fn next(&mut self) {
        self.next = self.iter.next();
        self.rowid += 1;
    }
}

#[repr(C)]
struct FdbTabCursor<'vtab> {
    /// Base class. Must be first
    base: rusqlite::vtab::sqlite3_vtab_cursor,
    /* Virtual table implementations will typically add additional fields */
    table: mem::Table<'vtab>,
    iter: BufferedIter<'vtab>,
}

unsafe impl<'vtab> VTabCursor for FdbTabCursor<'vtab> {
    fn filter(
        &mut self,
        idx_num: std::os::raw::c_int,
        _idx_str: Option<&str>,
        args: &rusqlite::vtab::Values<'_>,
    ) -> rusqlite::Result<()> {
        self.iter = BufferedIter::new(if idx_num == 1 {
            // Filter by first column
            let idx_value = args.get::<u32>(0)?;
            self.table.bucket_index_iter(idx_value)
        } else {
            self.table.row_iter()
        });
        Ok(())
    }

    fn next(&mut self) -> rusqlite::Result<()> {
        self.iter.next(); // Just drop the next one
        Ok(())
    }

    fn eof(&self) -> bool {
        self.iter.eof()
    }

    fn column(
        &self,
        ctx: &mut rusqlite::vtab::Context,
        i: std::os::raw::c_int,
    ) -> rusqlite::Result<()> {
        // Get the row
        let row = self.iter.next.ok_or_else(|| {
            rusqlite::Error::ModuleError(format!(
                "FDB: no data for col {} past the end of the table",
                i
            ))
        })?;

        // Get the field
        let field = row.field_at(i as usize).ok_or_else(|| {
            rusqlite::Error::ModuleError(format!("FDB: column {} out of bounds", i))
        })?;

        // Return the result
        ctx.set_result(&field)?;

        Ok(())
    }

    fn rowid(&self) -> rusqlite::Result<i64> {
        Ok(self.iter.rowid)
    }
}

unsafe impl<'vtab> VTab<'vtab> for FdbTab<'vtab> {
    type Aux = mem::Database<'vtab>;

    type Cursor = FdbTabCursor<'vtab>;

    fn connect(
        _db: &mut rusqlite::vtab::VTabConnection,
        aux: Option<&Self::Aux>,
        args: &[&[u8]],
    ) -> rusqlite::Result<(String, Self)> {
        match *args {
            [] => Err(rusqlite::Error::InvalidParameterCount(0, 1)),
            [mod_name, db_name, table_name] => {
                let name = std::str::from_utf8(table_name).map_err(|e| {
                    rusqlite::Error::ModuleError(format!("FDB: Table name is invalid UTF-8: {}", e))
                })?;

                let table = aux
                    .ok_or_else(|| {
                        rusqlite::Error::ModuleError(format!(
                            "Missing 'aux' for FDB vtab ({:?},{:?},{:?})",
                            mod_name, db_name, table_name
                        ))
                    })?
                    .tables()
                    .map_err(|e| {
                        rusqlite::Error::ModuleError(format!("FDB: Failed to get [Tables]: {}", e))
                    })?
                    .by_name(name)
                    .ok_or_else(|| {
                        rusqlite::Error::ModuleError(format!("FDB: Unknown table {:?}", name))
                    })?
                    .map_err(|e| {
                        rusqlite::Error::ModuleError(format!("FDB: Failed to get [Tables]: {}", e))
                    })?;

                let mut schema = String::from("CREATE TABLE x(");
                for (index, col) in table.column_iter().enumerate() {
                    if index > 0 {
                        schema.push_str(", ");
                    }
                    schema.push_str(col.name().as_ref());
                    schema.push(' ');
                    schema.push_str(col.value_type().to_sqlite_type());
                }
                schema.push_str(");");

                let vtab = FdbTab {
                    base: rusqlite::vtab::sqlite3_vtab::default(),
                    table,
                };

                Ok((schema, vtab))
            }
            _ => Err(rusqlite::Error::InvalidParameterCount(args.len(), 1)),
        }
    }

    fn best_index(&self, info: &mut rusqlite::vtab::IndexInfo) -> rusqlite::Result<()> {
        let mut argv_index = 0;
        for (c, mut u) in info.constraints_and_usages() {
            if c.column() == 0
                && c.is_usable()
                && c.operator() == IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_EQ
            {
                argv_index += 1;
                u.set_argv_index(argv_index);
            }
        }

        match argv_index {
            0 => {
                info.set_estimated_cost(1_000_000.0);
            }
            _ => {
                info.set_estimated_cost(1_000.0);
                info.set_idx_num(1);
            }
        }

        Ok(())
    }

    fn open(&'vtab self) -> rusqlite::Result<Self::Cursor> {
        Ok(FdbTabCursor {
            base: rusqlite::vtab::sqlite3_vtab_cursor::default(),
            table: self.table,
            iter: BufferedIter::new(self.table.row_iter()),
        })
    }
}

impl<'vtab> CreateVTab<'vtab> for FdbTab<'vtab> {
    fn create(
        db: &mut rusqlite::vtab::VTabConnection,
        aux: Option<&Self::Aux>,
        args: &[&[u8]],
    ) -> rusqlite::Result<(String, Self)> {
        Self::connect(db, aux, args)
    }

    fn destroy(&self) -> rusqlite::Result<()> {
        Ok(())
    }
}