Cornucopia is a code generator that takes small snippets of SQL and turns them into Rust functions.
We'll turn our
crates/db folder into a crate so we can keep all our database logic in one place.
Run the following
cornucopia into your project
cd into your
In a folder called
db/queries create a file called
users.sql and add the following content.
--: User() --! get_users : User SELECT id, email FROM users;
Cornucopia will use the above definition to generate a Rust function called
get_users to access the database. Note cornucopia checks the query at code generation time against Postgres.
crates/db/build.rs file and add the following content. This file we compile our .sql files into rust code whenever they change.
use env; use Path;
Add the following code to
crates/db/src/lib.rs will we use this to convert our
DATABASE_URL env var into something cornucopia can use for connection pooling.
use FromStr; use Arc; use SystemTime; pub use Params; pub use ; use ; use ServerName; pub use Error as TokioPostgresError; pub use User; ; include!;
You should now have a folder structure something like this.
Make sure you're in the
First add the client side dependencies to our project
Make sure everything builds.
Add the following code to the bottom of your
cargo test -- --nocapture and you should see