Complete these tasks to reinforce what you learned in this module.
Connect to Postgres using DATABASE_URL (env var, default e.g. postgres://postgres:postgres@localhost/postgres). Run a simple query that returns one row and one column, e.g. SELECT 1 AS num or SELECT current_database() AS name. Fetch the result and print it (e.g. with query_as::<_, (i32,)> or a single-column struct). Use #[tokio::main] and handle errors.
PgPoolOptions::connect. Use sqlx::query_as with a type that matches one column (e.g. a single-element tuple); call fetch_one and handle the result.// Task 1: Connect and scalar query. See tasks/TASKS.md.
// Requires Postgres and DATABASE_URL (or default).
fn main() {
todo!("Connect with sqlx, run SELECT 1, print result");
}
Assume a table users with columns id (int), name (text). Create a struct with FromRow, run SELECT id, name FROM users LIMIT 5, fetch all rows, and print them. If the table doesn’t exist, the task can create a temp table and one row for demonstration, then query it.
FromRow on a struct whose fields match the columns. Use query_as with that struct and fetch_all to get a Vec. If you don’t have a table, create a temp table and insert a row first.// Task 2: Query and map to struct. See tasks/TASKS.md.
fn main() {
todo!("Query users (or temp table), FromRow, fetch_all, print");
}