Skip to main content

mtgjson_sdk/queries/
skus.rs

1//! TCGplayer SKU queries backed by the `TcgplayerSkus.parquet` data loaded into DuckDB.
2
3use std::collections::HashMap;
4
5use serde_json::Value;
6
7use crate::error::Result;
8use crate::sql_builder::SqlBuilder;
9
10// ---------------------------------------------------------------------------
11// SkuQuery
12// ---------------------------------------------------------------------------
13
14/// Query interface for TCGplayer SKU data backed by a DuckDB view.
15pub struct SkuQuery<'a> {
16    conn: &'a crate::connection::Connection,
17}
18
19impl<'a> SkuQuery<'a> {
20    /// Create a new `SkuQuery` bound to the given connection.
21    pub fn new(conn: &'a crate::connection::Connection) -> Self {
22        Self { conn }
23    }
24
25    /// Get all SKUs for a card by its UUID.
26    pub fn get(&self, uuid: &str) -> Result<Vec<Value>> {
27        self.conn.ensure_views(&["tcgplayer_skus"])?;
28
29        let (sql, params) = SqlBuilder::new("tcgplayer_skus")
30            .where_eq("uuid", uuid)
31            .build();
32
33        let rows = self.conn.execute(&sql, &params)?;
34        Ok(rows_to_values(rows))
35    }
36
37    /// Find the card/SKU entry for a specific TCGplayer SKU ID.
38    pub fn find_by_sku_id(&self, sku_id: &str) -> Result<Vec<Value>> {
39        self.conn.ensure_views(&["tcgplayer_skus"])?;
40
41        let (sql, params) = SqlBuilder::new("tcgplayer_skus")
42            .where_eq("skuId", sku_id)
43            .build();
44
45        let rows = self.conn.execute(&sql, &params)?;
46        Ok(rows_to_values(rows))
47    }
48
49    /// Find all SKUs for a given TCGplayer product ID.
50    pub fn find_by_product_id(&self, product_id: &str) -> Result<Vec<Value>> {
51        self.conn.ensure_views(&["tcgplayer_skus"])?;
52
53        let (sql, params) = SqlBuilder::new("tcgplayer_skus")
54            .where_eq("productId", product_id)
55            .build();
56
57        let rows = self.conn.execute(&sql, &params)?;
58        Ok(rows_to_values(rows))
59    }
60}
61
62// ---------------------------------------------------------------------------
63// Helpers
64// ---------------------------------------------------------------------------
65
66fn rows_to_values(rows: Vec<HashMap<String, Value>>) -> Vec<Value> {
67    rows.into_iter()
68        .map(|r| serde_json::to_value(r).unwrap_or(Value::Null))
69        .collect()
70}