barreleye_common/models/
labeled_address.rs

1use eyre::Result;
2use sea_orm::entity::{prelude::*, *};
3use sea_orm_migration::prelude::OnConflict;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7	models::{label, BasicModel, PrimaryId},
8	utils, Db, IdPrefix,
9};
10
11#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, DeriveEntityModel)]
12#[sea_orm(table_name = "labeled_addresses")]
13#[serde(rename_all = "camelCase")]
14pub struct Model {
15	#[sea_orm(primary_key)]
16	#[serde(skip_serializing, skip_deserializing)]
17	pub labeled_address_id: PrimaryId,
18	#[serde(skip_serializing)]
19	pub label_id: PrimaryId,
20	pub id: String,
21	pub address: String,
22	#[sea_orm(nullable)]
23	#[serde(skip_serializing)]
24	pub updated_at: Option<DateTime>,
25	pub created_at: DateTime,
26}
27
28pub use ActiveModel as LabeledAddressActiveModel;
29pub use Model as LabeledAddress;
30
31#[derive(Copy, Clone, Debug, EnumIter)]
32pub enum Relation {
33	Label,
34}
35
36impl RelationTrait for Relation {
37	fn def(&self) -> RelationDef {
38		match self {
39			Self::Label => Entity::belongs_to(label::Entity)
40				.from(Column::LabelId)
41				.to(label::Column::LabelId)
42				.into(),
43		}
44	}
45}
46
47impl ActiveModelBehavior for ActiveModel {}
48
49impl BasicModel for Model {
50	type ActiveModel = ActiveModel;
51}
52
53impl Model {
54	pub fn new_model(label_id: PrimaryId, address: &str) -> ActiveModel {
55		ActiveModel {
56			label_id: Set(label_id),
57			id: Set(utils::new_unique_id(IdPrefix::LabeledAddress)),
58			address: Set(address.to_string()),
59			..Default::default()
60		}
61	}
62
63	pub async fn create_many(db: &Db, data: Vec<ActiveModel>) -> Result<PrimaryId> {
64		let insert_result = Entity::insert_many(data)
65			.on_conflict(
66				OnConflict::columns([Column::LabelId, Column::Address])
67					// @TODO this should be a `.do_nothing()`, but: `https://github.com/SeaQL/sea-orm/issues/899`
68					.update_column(Column::LabeledAddressId)
69					.to_owned(),
70			)
71			.exec(db.get())
72			.await?;
73
74		Ok(insert_result.last_insert_id)
75	}
76
77	pub async fn get_all_by_label_ids(db: &Db, label_ids: Vec<PrimaryId>) -> Result<Vec<Self>> {
78		Ok(Entity::find().filter(Column::LabelId.is_in(label_ids)).all(db.get()).await?)
79	}
80
81	pub async fn get_by_address(db: &Db, address: &str) -> Result<Option<Self>> {
82		Ok(Entity::find().filter(Column::Address.eq(address)).one(db.get()).await?)
83	}
84
85	pub async fn get_all_by_label_id_and_addresses(
86		db: &Db,
87		label_id: PrimaryId,
88		addresses: Vec<String>,
89	) -> Result<Vec<Self>> {
90		Ok(Entity::find()
91			.filter(Column::LabelId.eq(label_id))
92			.filter(Column::Address.is_in(addresses))
93			.all(db.get())
94			.await?)
95	}
96}