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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use crate::cents::Cents;

#[derive(Debug, PartialEq, Clone, sqlx::FromRow)]
pub struct LineItem {
    pub id: i64,
    pub order_id: i64,
    pub sku: String,
    pub url: String,
    pub name: String,
    pub quantity: i32,
    pub price: Cents,
    pub taxrate: i32,
    pub total: Cents,
}

pub async fn fetch<'e>(
    id: i64,
    conn: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<LineItem>, sqlx::Error> {
    sqlx::query_as("SELECT * FROM line_items WHERE id = $1")
        .bind(id)
        .fetch_optional(conn)
        .await
}

pub async fn by_order_id<'e>(
    order_id: i64,
    conn: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<LineItem>, sqlx::Error> {
    sqlx::query_as("SELECT * FROM line_items WHERE order_id = $1 ORDER BY id")
        .bind(order_id)
        .fetch_all(conn)
        .await
}

#[derive(Debug)]
pub struct NewLineItem<'a> {
    pub order_id: i64,
    pub sku: &'a str,
    pub url: &'a str,
    pub name: &'a str,
    pub quantity: i32,
    pub price: Cents,
    pub taxrate: i32,
    pub total: Cents,
}

pub async fn insert<'e>(
    line_item: &NewLineItem<'_>,
    conn: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<LineItem, sqlx::Error> {
    // deconstruct to not miss new properties in the future
    let NewLineItem {
        order_id,
        sku,
        url,
        name,
        quantity,
        price,
        taxrate,
        total,
    } = line_item;

    sqlx::query_as(
        "
            INSERT INTO line_items (
                order_id,
                sku,
                url,
                name,
                quantity,
                price,
                taxrate,
                total
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8
            )
            RETURNING *
        ",
    )
    .bind(order_id)
    .bind(sku)
    .bind(url)
    .bind(name)
    .bind(quantity)
    .bind(price)
    .bind(taxrate)
    .bind(total)
    .fetch_one(conn)
    .await
}