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