Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spin 3 postgres support #39

Merged
merged 2 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ name = "spin_sdk"
[dependencies]
anyhow = "1"
async-trait = "0.1.74"
chrono = "0.4.38"
form_urlencoded = "1.0"
spin-executor = { version = "3.0.1", path = "crates/executor" }
spin-macro = { version = "3.0.1", path = "crates/macro" }
Expand Down Expand Up @@ -52,6 +53,7 @@ members = [
"examples/key-value",
"examples/mysql",
"examples/postgres",
"examples/postgres-v3",
"examples/redis-outbound",
"examples/mqtt-outbound",
"examples/variables",
Expand Down
2 changes: 2 additions & 0 deletions examples/postgres-v3/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "wasm32-wasi"
17 changes: 17 additions & 0 deletions examples/postgres-v3/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "rust-outbound-pg-v3"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
# Useful crate to handle errors.
anyhow = "1"
# General-purpose crate with common HTTP types.
http = "1.0.0"
# The Spin SDK.
spin-sdk = { path = "../.." }
# For handling date/time types
chrono = "0.4.38"
69 changes: 69 additions & 0 deletions examples/postgres-v3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Spin Outbound PostgreSQL example

This example shows how to access a PostgreSQL database from Spin component.

## Spin up

From example root:

```
createdb spin_dev
psql -d spin_dev -f db/testdata.sql
RUST_LOG=spin=trace spin build --up
```

Curl the read route:

```
$ curl -i localhost:3000/read
HTTP/1.1 200 OK
transfer-encoding: chunked
date: Wed, 06 Nov 2024 20:17:03 GMT

Found 2 article(s) as follows:
article: Article {
id: 1,
title: "My Life as a Goat",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This brought a smile to my morning!

content: "I went to Nepal to live as a goat, and it was much better than being a butler.",
authorname: "E. Blackadder",
published: Date(
2024-11-05,
),
coauthor: None,
}
article: Article {
id: 2,
title: "Magnificent Octopus",
content: "Once upon a time there was a lovely little sausage.",
authorname: "S. Baldrick",
published: Date(
2024-11-06,
),
coauthor: None,
}

(Column info: id:DbDataType::Int32, title:DbDataType::Str, content:DbDataType::Str, authorname:DbDataType::Str, published:DbDataType::Date, coauthor:DbDataType::Str)
```

Curl the write route:

```
$ curl -i localhost:3000/write
HTTP/1.1 200 OK
content-length: 9
date: Sun, 25 Sep 2022 15:46:22 GMT

Count: 3
```

Curl the write_datetime_info route to experiment with date time types:
```
$ curl -i localhost:3000/write_datetime_info
HTTP/1.1 200 OK
content-length: 9
date: Sun, 25 Sep 2022 15:46:22 GMT

Count: 4
```

Read endpoint should now also show a row with publisheddate, publishedtime, publisheddatetime and readtime values.
25 changes: 25 additions & 0 deletions examples/postgres-v3/db/testdata.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
CREATE TABLE articletest (
id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title varchar(40) NOT NULL,
content text NOT NULL,
authorname varchar(40) NOT NULL ,
publisheddate date NOT NULL,
publishedtime time,
publisheddatetime timestamp,
readtime bigint,
coauthor text
);

INSERT INTO articletest (title, content, authorname, publisheddate) VALUES
(
'My Life as a Goat',
'I went to Nepal to live as a goat, and it was much better than being a butler.',
'E. Blackadder',
'2024-11-05'
),
(
'Magnificent Octopus',
'Once upon a time there was a lovely little sausage.',
'S. Baldrick',
'2024-11-06'
);
17 changes: 17 additions & 0 deletions examples/postgres-v3/spin.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
spin_manifest_version = 2

[application]
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
name = "rust-outbound-pg-v3-example"
version = "0.1.0"

[[trigger.http]]
route = "/..."
component = "outbound-pg"

[component.outbound-pg]
environment = { DB_URL = "host=localhost user=postgres dbname=spin_dev" }
source = "../../target/wasm32-wasi/release/rust_outbound_pg_v3.wasm"
allowed_outbound_hosts = ["postgres://localhost"]
[component.outbound-pg.build]
command = "cargo build --target wasm32-wasi --release"
164 changes: 164 additions & 0 deletions examples/postgres-v3/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
#![allow(dead_code)]
use anyhow::Result;
use http::{Request, Response};
use spin_sdk::{http_component, pg3, pg3::Decode};

// The environment variable set in `spin.toml` that points to the
// address of the Pg server that the component will write to
const DB_URL_ENV: &str = "DB_URL";

#[derive(Debug, Clone)]
struct Article {
id: i32,
title: String,
content: String,
authorname: String,
published_date: chrono::NaiveDate,
published_time: Option<chrono::NaiveTime>,
published_datetime: Option<chrono::NaiveDateTime>,
read_time: Option<i64>,
coauthor: Option<String>,
}

impl TryFrom<&pg3::Row> for Article {
type Error = anyhow::Error;

fn try_from(row: &pg3::Row) -> Result<Self, Self::Error> {
let id = i32::decode(&row[0])?;
let title = String::decode(&row[1])?;
let content = String::decode(&row[2])?;
let authorname = String::decode(&row[3])?;
let published_date = chrono::NaiveDate::decode(&row[4])?;
let published_time = Option::<chrono::NaiveTime>::decode(&row[5])?;
let published_datetime = Option::<chrono::NaiveDateTime>::decode(&row[6])?;
let read_time = Option::<i64>::decode(&row[7])?;
let coauthor = Option::<String>::decode(&row[8])?;

Ok(Self {
id,
title,
content,
authorname,
published_date,
published_time,
published_datetime,
read_time,
coauthor,
})
}
}

#[http_component]
fn process(req: Request<()>) -> Result<Response<String>> {
match req.uri().path() {
"/read" => read(req),
"/write" => write(req),
"/write_datetime_info" => write_datetime_info(req),
"/pg_backend_pid" => pg_backend_pid(req),
_ => Ok(http::Response::builder()
.status(404)
.body("Not found".into())?),
}
}

fn read(_req: Request<()>) -> Result<Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg3::Connection::open(&address)?;

let sql = "SELECT id, title, content, authorname, publisheddate, publishedtime, publisheddatetime, readtime, coauthor FROM articletest";
let rowset = conn.query(sql, &[])?;

let column_summary = rowset
.columns
.iter()
.map(format_col)
.collect::<Vec<_>>()
.join(", ");

let mut response_lines = vec![];

for row in rowset.rows {
let article = Article::try_from(&row)?;

println!("article: {:#?}", article);
response_lines.push(format!("article: {:#?}", article));
}

// use it in business logic

let response = format!(
"Found {} article(s) as follows:\n{}\n\n(Column info: {})\n",
response_lines.len(),
response_lines.join("\n"),
column_summary,
);

Ok(http::Response::builder().status(200).body(response)?)
}

fn write_datetime_info(_req: Request<()>) -> Result<Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg3::Connection::open(&address)?;

let date: chrono::NaiveDate = chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
let time: chrono::NaiveTime = chrono::NaiveTime::from_hms_nano_opt(12, 34, 56, 1).unwrap();
let datetime: chrono::NaiveDateTime = chrono::NaiveDateTime::new(date, time);
let readtime = 123i64;

let nrow_executed = conn.execute(
"INSERT INTO articletest(title, content, authorname, publisheddate, publishedtime, publisheddatetime, readtime) VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[ "aaa".to_string().into(), "bbb".to_string().into(), "ccc".to_string().into(), date.into(), time.into(), datetime.into(), readtime.into() ],
);

println!("nrow_executed: {:?}", nrow_executed);

let sql = "SELECT COUNT(id) FROM articletest";
let rowset = conn.query(sql, &[])?;
let row = &rowset.rows[0];
let count = i64::decode(&row[0])?;
let response = format!("Count: {}\n", count);

Ok(http::Response::builder().status(200).body(response)?)
}

fn write(_req: Request<()>) -> Result<Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg3::Connection::open(&address)?;

let sql =
"INSERT INTO articletest (title, content, authorname, published) VALUES ('aaa', 'bbb', 'ccc', '2024-01-01')";
let nrow_executed = conn.execute(sql, &[])?;

println!("nrow_executed: {}", nrow_executed);

let sql = "SELECT COUNT(id) FROM articletest";
let rowset = conn.query(sql, &[])?;
let row = &rowset.rows[0];
let count = i64::decode(&row[0])?;
let response = format!("Count: {}\n", count);

Ok(http::Response::builder().status(200).body(response)?)
}

fn pg_backend_pid(_req: Request<()>) -> Result<Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg3::Connection::open(&address)?;
let sql = "SELECT pg_backend_pid()";

let get_pid = || {
let rowset = conn.query(sql, &[])?;
let row = &rowset.rows[0];

i32::decode(&row[0])
};

assert_eq!(get_pid()?, get_pid()?);

let response = format!("pg_backend_pid: {}\n", get_pid()?);

Ok(http::Response::builder().status(200).body(response)?)
}

fn format_col(column: &pg3::Column) -> String {
format!("{}:{:?}", column.name, column.data_type)
}
Loading
Loading