How to get Rust sqlx sqlite query to work?

Viewed 4417

main.rs:

#[async_std::main]
async fn main() -> Result<(),sqlx::Error> {
    use sqlx::Connect;
    let mut conn = sqlx::SqliteConnection::connect("sqlite:///home/ace/hello_world/test.db").await?;
    let row = sqlx::query!("SELECT * FROM tbl").fetch_all(&conn).await?;
    println!("{}{}",row.0,row.1);
    Ok(())
}

Cargo.toml:

[package]
name = "hello_world"
version = "0.1.0"
authors = ["ace"]
edition = "2018"

[dependencies]
async-std = {version = "1", features = ["attributes"]}
sqlx = { version="0.3.5", default-features=false, features=["runtime-async-std","macros","sqlite"] }

bash session:

ace@SLAB:~/hello_world$ sqlite test.db
SQLite version 2.8.17
Enter ".help" for instructions
sqlite> create table tbl ( num integer, chr varchar );
sqlite> insert into tbl values (1,'ok');
sqlite> .quit
ace@SLAB:~/hello_world$ pwd
/home/ace/hello_world
ace@SLAB:~/hello_world$ export DATABASE_URL=sqlite:///home/ace/hello_world/test.db
ace@SLAB:~/hello_world$ cargo run
   Compiling hello_world v0.1.0 (/home/ace/hello_world)
error: failed to connect to database: file is not a database
 --> src/main.rs:8:12
  |
8 |     let row = sqlx::query!("SELECT * FROM tbl").fetch_all(&conn).await?;
  |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

error: could not compile `hello_world`.

To learn more, run the command again with --verbose.
ace@SLAB:~/hello_world$ rustc --version
rustc 1.44.0 (49cae5576 2020-06-01)
ace@SLAB:~/hello_world$ uname -r
5.4.0-33-generic
ace@SLAB:~/hello_world$ cat /etc/os-release | head -2
NAME="Ubuntu"
VERSION="20.04 LTS (Focal Fossa)"
ace@SLAB:~/hello_world$ 

Also tried using DATABASE_URL "sqlite::memory:" (both in environment variable and in main.rs) with system table "sqlite_master". Got different error:

error[E0277]: the trait bound `&sqlx_core::sqlite::connection::SqliteConnection: sqlx_core::executor::RefExecutor<'_>` is not satisfied

... but it must have gotten partway to success because when I used table name "Xsqlite_master" with memory db, it complained that there was no such table.

Tried "sqlite://home"(etc) and every other number of slashes, zero through 4. Tried several hundred other things. :(

Thank you!

1 Answers

There maybe several more things to try:

  1. Try sqlite3 /home/ace/hello_world/test.db to double verify that the DB does exist. Make sure tbl table is defined there .schema tbl
  2. Try DB path with a single slash i.e. sqlite:/home/ace/hello_world/test.db
  3. Lastly try using the query function not the macro https://docs.rs/sqlx/0.3.5/sqlx/fn.query.html to see if it works.
Related