From 7eab5041269cc2aef5974a06d4e63836833955aa Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Tue, 17 Mar 2020 13:41:56 +1000 Subject: [PATCH] add field_at_index() sql func --- rslib/Cargo.toml | 4 ++-- rslib/src/search/searcher.rs | 2 -- rslib/src/storage/sqlite.rs | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/rslib/Cargo.toml b/rslib/Cargo.toml index 7250b185c..58e5d5c90 100644 --- a/rslib/Cargo.toml +++ b/rslib/Cargo.toml @@ -40,10 +40,10 @@ serde_repr = "0.1.5" num_enum = "0.4.2" [target.'cfg(target_vendor="apple")'.dependencies] -rusqlite = { version = "0.21.0", features = ["trace"] } +rusqlite = { version = "0.21.0", features = ["trace", "functions"] } [target.'cfg(not(target_vendor="apple"))'.dependencies] -rusqlite = { version = "0.21.0", features = ["trace", "bundled"] } +rusqlite = { version = "0.21.0", features = ["trace", "functions", "bundled"] } [target.'cfg(linux)'.dependencies] reqwest = { version = "0.10.1", features = ["json", "native-tls-vendored"] } diff --git a/rslib/src/search/searcher.rs b/rslib/src/search/searcher.rs index 188aff410..9a2c67e96 100644 --- a/rslib/src/search/searcher.rs +++ b/rslib/src/search/searcher.rs @@ -216,7 +216,6 @@ fn write_note_type(ctx: &mut SearchContext, _notetype: &str) { } // fixme: need note type manager -// fixme: need field_at_index() fn write_single_field(ctx: &mut SearchContext, field: &str, val: &str) { let _ = field; let fields = vec![(0, 0)]; // fixme: get list of (ntid, ordinal) @@ -240,7 +239,6 @@ fn write_single_field(ctx: &mut SearchContext, field: &str, val: &str) { write!(ctx.sql, ")").unwrap(); } -// fixme: need field_at_index() fn write_dupes(ctx: &mut SearchContext, ntid: &ObjID, text: &str) { let csum = field_checksum(text); write!( diff --git a/rslib/src/storage/sqlite.rs b/rslib/src/storage/sqlite.rs index 886a8f801..967e79727 100644 --- a/rslib/src/storage/sqlite.rs +++ b/rslib/src/storage/sqlite.rs @@ -36,11 +36,26 @@ fn open_or_create_collection_db(path: &Path) -> Result { db.pragma_update(None, "cache_size", &(-40 * 1024))?; db.pragma_update(None, "legacy_file_format", &false)?; db.pragma_update(None, "journal", &"wal")?; + db.set_prepared_statement_cache_capacity(50); + add_field_index_function(&db)?; + Ok(db) } +/// Adds sql function field_at_index(flds, index) +/// to split provided fields and return field at zero-based index. +/// If out of range, returns empty string. +fn add_field_index_function(db: &Connection) -> Result<()> { + db.create_scalar_function("field_at_index", 2, true, |ctx| { + let mut fields = ctx.get_raw(0).as_str()?.split('\x1f'); + let idx: u16 = ctx.get(1)?; + Ok(fields.nth(idx as usize).unwrap_or("").to_string()) + }) + .map_err(Into::into) +} + /// Fetch schema version from database. /// Return (must_create, version) fn schema_version(db: &Connection) -> Result<(bool, u8)> {