Skip to content

Instantly share code, notes, and snippets.

@kogai
Created February 6, 2021 06:55
Show Gist options
  • Select an option

  • Save kogai/1e4584f08288fb055a53fd8ef16e2d2f to your computer and use it in GitHub Desktop.

Select an option

Save kogai/1e4584f08288fb055a53fd8ef16e2d2f to your computer and use it in GitHub Desktop.
Rust dieselでString以外の型のModel定義
use super::merchants::Merchant;
use crate::schema::charge_logs;
use chrono::NaiveDateTime;
use diesel::{
deserialize::{self, FromSql},
expression::Expression,
pg::Pg,
serialize::{self, Output, ToSql},
sql_types::Bpchar,
AsExpression, Associations, Identifiable, Insertable, Queryable,
};
use std::io::Write;
#[derive(Debug, PartialEq, FromSqlRow, AsExpression)]
pub enum CurrencyCode {
USD,
Unsupported(String),
}
impl Expression for CurrencyCode {
type SqlType = Bpchar;
}
impl ToSql<Bpchar, Pg> for CurrencyCode {
fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
let t = match *self {
CurrencyCode::USD => "usd",
CurrencyCode::Unsupported(_) => "---",
};
<&str as ToSql<Bpchar, Pg>>::to_sql(&t, out)
}
}
impl FromSql<Bpchar, Pg> for CurrencyCode {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
match (<String as FromSql<Bpchar, Pg>>::from_sql(bytes)?).as_ref() {
"usd" => Ok(CurrencyCode::USD),
x => Ok(CurrencyCode::Unsupported(x.to_owned())),
}
}
}
#[derive(Queryable, Insertable, Identifiable, Associations, Debug)]
#[belongs_to(Merchant, foreign_key = "charge_id")]
#[primary_key(created_at)]
#[table_name = "charge_logs"]
pub struct ChargeLog {
pub created_at: NaiveDateTime,
pub amount: i32,
pub currency_code: CurrencyCode,
pub charge_id: String,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment