1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use chrono::NaiveDate;
use sqlx::executor::RefExecutor;
use sqlx::postgres::PgQueryAs;
use sqlx::Postgres;
#[derive(Debug, PartialEq, sqlx::FromRow)]
pub struct Invoice {
pub invoice_id: i64,
pub order_id: i64,
pub invoice_date: NaiveDate,
pub payment_transaction_id: String,
pub payment_instructions: Option<String>,
}
#[derive(Debug)]
pub struct NewInvoice<'a> {
pub order_id: i64,
pub invoice_date: NaiveDate,
pub payment_transaction_id: &'a str,
pub payment_instructions: Option<&'a str>,
}
pub async fn fetch<'e>(
id: i64,
conn: impl RefExecutor<'e, Database = Postgres> + Send + 'e,
) -> Result<Option<Invoice>, sqlx::Error> {
sqlx::query_as("SELECT * FROM invoices WHERE invoice_id = $1")
.bind(id)
.fetch_optional(conn)
.await
}
pub async fn by_order_id<'e>(
order_id: i64,
conn: impl RefExecutor<'e, Database = Postgres> + Send + 'e,
) -> Result<Option<Invoice>, sqlx::Error> {
sqlx::query_as("SELECT * FROM invoices WHERE order_id = $1")
.bind(order_id)
.fetch_optional(conn)
.await
}
pub async fn insert<'e>(
invoice: &NewInvoice<'_>,
conn: impl RefExecutor<'e, Database = Postgres> + Send + 'e,
) -> Result<Invoice, sqlx::Error> {
let NewInvoice {
order_id,
invoice_date,
payment_transaction_id,
payment_instructions,
} = invoice;
sqlx::query_as(
"
INSERT INTO invoices (
order_id,
invoice_date,
payment_transaction_id,
payment_instructions
) VALUES (
$1, $2, $3, $4
) RETURNING *
",
)
.bind(order_id)
.bind(invoice_date)
.bind(payment_transaction_id)
.bind(payment_instructions)
.fetch_one(conn)
.await
}