Created
February 6, 2021 06:55
-
-
Save kogai/1e4584f08288fb055a53fd8ef16e2d2f to your computer and use it in GitHub Desktop.
Rust dieselでString以外の型のModel定義
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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