1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3// https://nautechsystems.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
1516use std::str::FromStr;
1718use nautilus_core::{UUID4, UnixNanos};
19use nautilus_model::{
20 enums::AccountType, events::AccountState, identifiers::AccountId, types::Currency,
21};
22use sqlx::{FromRow, Row, postgres::PgRow};
2324pub struct AccountEventModel(pub AccountState);
2526impl<'r> FromRow<'r, PgRow> for AccountEventModel {
27fn from_row(row: &'r PgRow) -> Result<Self, sqlx::Error> {
28let event_id = row.try_get::<&str, _>("id").map(UUID4::from)?;
29let account_id = row.try_get::<&str, _>("account_id").map(AccountId::from)?;
30let account_type = AccountType::from_str(row.try_get::<&str, _>("kind")?).unwrap();
31let is_reported = row.try_get::<bool, _>("is_reported")?;
32let ts_event = row.try_get::<&str, _>("ts_event").map(UnixNanos::from)?;
33let ts_init = row.try_get::<&str, _>("ts_init").map(UnixNanos::from)?;
34let base_currency = row
35 .try_get::<Option<&str>, _>("base_currency")
36 .map(|res| res.map(Currency::from))?;
37let balances: serde_json::Value = row.try_get("balances")?;
38let margins: serde_json::Value = row.try_get("margins")?;
39let account_event = AccountState::new(
40 account_id,
41 account_type,
42 serde_json::from_value(balances).unwrap(),
43 serde_json::from_value(margins).unwrap(),
44 is_reported,
45 event_id,
46 ts_event,
47 ts_init,
48 base_currency,
49 );
50Ok(AccountEventModel(account_event))
51 }
52}