asg017 / sqlite-regex

A fast regular expression SQLite extension, written in Rust
Apache License 2.0
166 stars 7 forks source link

How to use it in rust? #10

Open spa5k opened 1 year ago

spa5k commented 1 year ago

Same as title

asg017 commented 1 year ago

Hey, there's not a great answer for this yet, which sucks, planning to make that easier. If you're using rusqlite, you can use load_extension() to load a pre-compiled version of sqlite-regex, but that's not ideal since you'll have to separately manage the loadable extension file.

One day you'll be able to easily statically compile sqlite-regex into C/C++/Rust/Go, which you can only do now if you compile it yourself. I'll also add sqlite-regex to crates.io, which maybe an optional wrapper to easily integrate with rusqlite.

spa5k commented 1 year ago

Yeah it's a big problem since you can't just precompile the files and place them in directory like in node modules in node.

Sytten commented 1 year ago

Also interested in that. Generally the preferred way would be to compile statically and call libsqlite3_sys::sqlite3_auto_extension at runtime. We will do experiments and report back.

asg017 commented 1 year ago

Here's one way you can do it:

Cargo.toml:

[package]
name = "sqlite-regex-test"
version = "0.1.0"
edition = "2021"

[dependencies]
rusqlite = {version="0.29.0", features=["bundled"]}
sqlite-regex = {git="https://github.com/asg017/sqlite-regex.git"}

And lib/main.rs:

use rusqlite::{ffi::sqlite3_auto_extension, Connection, Result};
use sqlite_regex::sqlite3_regex_init;

fn main() -> Result<()> {
    unsafe {
        let sqlite3_regex_init = std::mem::transmute(sqlite3_regex_init as *const ());
        sqlite3_auto_extension(Some(sqlite3_regex_init));
    }

    let db = Connection::open_in_memory()?;

    let (version, result): (String, i32) =
        db.query_row("SELECT regex_version(), ? regexp 'a'", ["alex"], |row| {
            Ok((row.get(0)?, row.get(1)?))
        })?;
    println!("version={version} result={result}");

    Ok(())
}

Requires some slightly sketch and unsafe transmuting, but works in a pinch! I'll publish this crate to https://crates.io eventually.

asg017 commented 1 year ago

sqlite-regex is now published on crates.io, at https://crates.io/crates/sqlite-regex

The above example works with this replacement in Cargo.toml:

sqlite-regex = "0.2.3-alpha.9"