barreleye_common/models/
network.rs

1use crate::Db;
2use eyre::Result;
3use sea_orm::{
4	entity::prelude::*,
5	sea_query::{func::Func, Expr},
6	Condition, Set,
7};
8use serde::{Deserialize, Serialize};
9use serde_json::json;
10
11use crate::{
12	models::{BasicModel, PrimaryId},
13	utils, Blockchain, Env, IdPrefix,
14};
15
16#[derive(Default, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, DeriveEntityModel)]
17#[sea_orm(table_name = "networks")]
18#[serde(rename_all = "camelCase")]
19pub struct Model {
20	#[sea_orm(primary_key)]
21	#[serde(skip_serializing, skip_deserializing)]
22	pub network_id: PrimaryId,
23	pub id: String,
24	pub name: String,
25	pub tag: String,
26	pub env: Env,
27	pub blockchain: Blockchain,
28	pub chain_id: i64,
29	pub block_time_ms: i64,
30	pub rpc_endpoints: Json,
31	pub rps: i32,
32	pub is_active: bool,
33	#[sea_orm(nullable)]
34	#[serde(skip_serializing)]
35	pub updated_at: Option<DateTime>,
36	pub created_at: DateTime,
37}
38
39pub use ActiveModel as NetworkActiveModel;
40pub use Model as Network;
41
42#[derive(Copy, Clone, Debug, EnumIter)]
43pub enum Relation {}
44
45impl RelationTrait for Relation {
46	fn def(&self) -> RelationDef {
47		panic!("No RelationDef")
48	}
49}
50
51impl ActiveModelBehavior for ActiveModel {}
52
53impl BasicModel for Model {
54	type ActiveModel = ActiveModel;
55}
56
57impl Model {
58	pub fn new_model(
59		name: &str,
60		tag: &str,
61		env: Env,
62		blockchain: Blockchain,
63		chain_id: i64,
64		block_time_ms: i64,
65		rpc_endpoints: Vec<String>,
66		rps: i32,
67	) -> ActiveModel {
68		ActiveModel {
69			id: Set(utils::new_unique_id(IdPrefix::Network)),
70			name: Set(name.to_string()),
71			tag: Set(tag.to_string()),
72			env: Set(env),
73			blockchain: Set(blockchain),
74			chain_id: Set(chain_id),
75			block_time_ms: Set(block_time_ms),
76			rpc_endpoints: Set(json!(rpc_endpoints)),
77			is_active: Set(true),
78			rps: Set(rps),
79			..Default::default()
80		}
81	}
82
83	pub async fn get_all_by_env(db: &Db, env: Env) -> Result<Vec<Self>> {
84		Ok(Entity::find().filter(Column::Env.eq(env)).all(db.get()).await?)
85	}
86
87	pub async fn get_all_by_network_ids(db: &Db, network_ids: Vec<PrimaryId>) -> Result<Vec<Self>> {
88		Ok(Entity::find().filter(Column::NetworkId.is_in(network_ids)).all(db.get()).await?)
89	}
90
91	pub async fn get_by_name(db: &Db, name: &str) -> Result<Option<Self>> {
92		Ok(Entity::find()
93			.filter(
94				Condition::all()
95					.add(Func::lower(Expr::col(Column::Name)).equals(name.trim().to_lowercase())),
96			)
97			.one(db.get())
98			.await?)
99	}
100
101	pub async fn get_by_env_blockchain_and_chain_id(
102		db: &Db,
103		env: Env,
104		blockchain: Blockchain,
105		chain_id: i64,
106	) -> Result<Option<Self>> {
107		Ok(Entity::find()
108			.filter(Column::Env.eq(env))
109			.filter(Column::Blockchain.eq(blockchain))
110			.filter(Column::ChainId.eq(chain_id))
111			.one(db.get())
112			.await?)
113	}
114}