|
| 1 | +#![allow(dead_code)] |
| 2 | +use anyhow::Result; |
| 3 | +use http::{Request, Response}; |
| 4 | +use spin_sdk::{ |
| 5 | + http_component, |
| 6 | + pg3::{Date, Decode}, |
| 7 | +}; |
| 8 | + |
| 9 | +// The environment variable set in `spin.toml` that points to the |
| 10 | +// address of the Pg server that the component will write to |
| 11 | +const DB_URL_ENV: &str = "DB_URL"; |
| 12 | + |
| 13 | +#[derive(Debug, Clone)] |
| 14 | +struct Article { |
| 15 | + id: i32, |
| 16 | + title: String, |
| 17 | + content: String, |
| 18 | + authorname: String, |
| 19 | + published: Date, |
| 20 | + coauthor: Option<String>, |
| 21 | +} |
| 22 | + |
| 23 | +impl TryFrom<&pg::Row> for Article { |
| 24 | + type Error = anyhow::Error; |
| 25 | + |
| 26 | + fn try_from(row: &pg::Row) -> Result<Self, Self::Error> { |
| 27 | + let id = i32::decode(&row[0])?; |
| 28 | + let title = String::decode(&row[1])?; |
| 29 | + let content = String::decode(&row[2])?; |
| 30 | + let authorname = String::decode(&row[3])?; |
| 31 | + let published = Date::decode(&row[4])?; |
| 32 | + let coauthor = Option::<String>::decode(&row[5])?; |
| 33 | + |
| 34 | + Ok(Self { |
| 35 | + id, |
| 36 | + title, |
| 37 | + content, |
| 38 | + authorname, |
| 39 | + published, |
| 40 | + coauthor, |
| 41 | + }) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +#[http_component] |
| 46 | +fn process(req: Request<()>) -> Result<Response<String>> { |
| 47 | + match req.uri().path() { |
| 48 | + "/read" => read(req), |
| 49 | + "/write" => write(req), |
| 50 | + "/pg_backend_pid" => pg_backend_pid(req), |
| 51 | + _ => Ok(http::Response::builder() |
| 52 | + .status(404) |
| 53 | + .body("Not found".into())?), |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +fn read(_req: Request<()>) -> Result<Response<String>> { |
| 58 | + let address = std::env::var(DB_URL_ENV)?; |
| 59 | + let conn = pg::Connection::open(&address)?; |
| 60 | + |
| 61 | + let sql = "SELECT id, title, content, authorname, coauthor FROM articletest"; |
| 62 | + let rowset = conn.query(sql, &[])?; |
| 63 | + |
| 64 | + let column_summary = rowset |
| 65 | + .columns |
| 66 | + .iter() |
| 67 | + .map(format_col) |
| 68 | + .collect::<Vec<_>>() |
| 69 | + .join(", "); |
| 70 | + |
| 71 | + let mut response_lines = vec![]; |
| 72 | + |
| 73 | + for row in rowset.rows { |
| 74 | + let article = Article::try_from(&row)?; |
| 75 | + |
| 76 | + println!("article: {:#?}", article); |
| 77 | + response_lines.push(format!("article: {:#?}", article)); |
| 78 | + } |
| 79 | + |
| 80 | + // use it in business logic |
| 81 | + |
| 82 | + let response = format!( |
| 83 | + "Found {} article(s) as follows:\n{}\n\n(Column info: {})\n", |
| 84 | + response_lines.len(), |
| 85 | + response_lines.join("\n"), |
| 86 | + column_summary, |
| 87 | + ); |
| 88 | + |
| 89 | + Ok(http::Response::builder().status(200).body(response)?) |
| 90 | +} |
| 91 | + |
| 92 | +fn write(_req: Request<()>) -> Result<Response<String>> { |
| 93 | + let address = std::env::var(DB_URL_ENV)?; |
| 94 | + let conn = pg::Connection::open(&address)?; |
| 95 | + |
| 96 | + let sql = |
| 97 | + "INSERT INTO articletest (title, content, authorname, published) VALUES ('aaa', 'bbb', 'ccc', '2024-01-01')"; |
| 98 | + let nrow_executed = conn.execute(sql, &[])?; |
| 99 | + |
| 100 | + println!("nrow_executed: {}", nrow_executed); |
| 101 | + |
| 102 | + let sql = "SELECT COUNT(id) FROM articletest"; |
| 103 | + let rowset = conn.query(sql, &[])?; |
| 104 | + let row = &rowset.rows[0]; |
| 105 | + let count = i64::decode(&row[0])?; |
| 106 | + let response = format!("Count: {}\n", count); |
| 107 | + |
| 108 | + Ok(http::Response::builder().status(200).body(response)?) |
| 109 | +} |
| 110 | + |
| 111 | +fn pg_backend_pid(_req: Request<()>) -> Result<Response<String>> { |
| 112 | + let address = std::env::var(DB_URL_ENV)?; |
| 113 | + let conn = pg::Connection::open(&address)?; |
| 114 | + let sql = "SELECT pg_backend_pid()"; |
| 115 | + |
| 116 | + let get_pid = || { |
| 117 | + let rowset = conn.query(sql, &[])?; |
| 118 | + let row = &rowset.rows[0]; |
| 119 | + |
| 120 | + i32::decode(&row[0]) |
| 121 | + }; |
| 122 | + |
| 123 | + assert_eq!(get_pid()?, get_pid()?); |
| 124 | + |
| 125 | + let response = format!("pg_backend_pid: {}\n", get_pid()?); |
| 126 | + |
| 127 | + Ok(http::Response::builder().status(200).body(response)?) |
| 128 | +} |
| 129 | + |
| 130 | +fn format_col(column: &pg::Column) -> String { |
| 131 | + format!("{}:{:?}", column.name, column.data_type) |
| 132 | +} |
0 commit comments