Insert transaction

This commit is contained in:
wjsjwr 2024-12-25 22:40:16 +08:00
parent 66c3895715
commit 835bce5dcb
11 changed files with 405 additions and 77 deletions

View File

@ -499,7 +499,7 @@
</routine>
<schema id="191" parent="1" name="main">
<Current>1</Current>
<LastIntrospectionLocalTimestamp>2024-12-23.15:02:12</LastIntrospectionLocalTimestamp>
<LastIntrospectionLocalTimestamp>2024-12-25.12:45:04</LastIntrospectionLocalTimestamp>
</schema>
<argument id="192" parent="16">
<ArgumentDirection>R</ArgumentDirection>
@ -1597,75 +1597,141 @@
<table id="557" parent="191" name="sqlite_sequence">
<System>1</System>
</table>
<table id="558" parent="191" name="user"/>
<column id="559" parent="555" name="version">
<table id="558" parent="191" name="transaction"/>
<table id="559" parent="191" name="user"/>
<column id="560" parent="555" name="version">
<NotNull>1</NotNull>
<Position>1</Position>
<StoredType>varchar|0s</StoredType>
</column>
<column id="560" parent="555" name="applied_at">
<column id="561" parent="555" name="applied_at">
<NotNull>1</NotNull>
<Position>2</Position>
<StoredType>bigint|0s</StoredType>
</column>
<index id="561" parent="555" name="sqlite_autoindex_seaql_migrations_1">
<index id="562" parent="555" name="sqlite_autoindex_seaql_migrations_1">
<ColNames>version</ColNames>
<NameSurrogate>1</NameSurrogate>
<Unique>1</Unique>
</index>
<key id="562" parent="555">
<key id="563" parent="555">
<ColNames>version</ColNames>
<Primary>1</Primary>
<UnderlyingIndexName>sqlite_autoindex_seaql_migrations_1</UnderlyingIndexName>
</key>
<column id="563" parent="556" name="type">
<column id="564" parent="556" name="type">
<Position>1</Position>
<StoredType>TEXT|0s</StoredType>
</column>
<column id="564" parent="556" name="name">
<column id="565" parent="556" name="name">
<Position>2</Position>
<StoredType>TEXT|0s</StoredType>
</column>
<column id="565" parent="556" name="tbl_name">
<column id="566" parent="556" name="tbl_name">
<Position>3</Position>
<StoredType>TEXT|0s</StoredType>
</column>
<column id="566" parent="556" name="rootpage">
<column id="567" parent="556" name="rootpage">
<Position>4</Position>
<StoredType>INT|0s</StoredType>
</column>
<column id="567" parent="556" name="sql">
<column id="568" parent="556" name="sql">
<Position>5</Position>
<StoredType>TEXT|0s</StoredType>
</column>
<column id="568" parent="557" name="name">
<column id="569" parent="557" name="name">
<Position>1</Position>
</column>
<column id="569" parent="557" name="seq">
<column id="570" parent="557" name="seq">
<Position>2</Position>
</column>
<column id="570" parent="558" name="id">
<column id="571" parent="558" name="id">
<AutoIncrement>1</AutoIncrement>
<NotNull>1</NotNull>
<Position>1</Position>
<StoredType>integer|0s</StoredType>
</column>
<column id="571" parent="558" name="name">
<column id="572" parent="558" name="code">
<NotNull>1</NotNull>
<Position>2</Position>
<StoredType>varchar|0s</StoredType>
</column>
<column id="572" parent="558" name="password">
<column id="573" parent="558" name="name">
<NotNull>1</NotNull>
<Position>3</Position>
<StoredType>varchar|0s</StoredType>
</column>
<column id="573" parent="558" name="session_token">
<column id="574" parent="558" name="buy">
<NotNull>1</NotNull>
<Position>4</Position>
<StoredType>real|0s</StoredType>
</column>
<column id="575" parent="558" name="volume">
<NotNull>1</NotNull>
<Position>5</Position>
<StoredType>integer|0s</StoredType>
</column>
<column id="576" parent="558" name="net_buy">
<NotNull>1</NotNull>
<Position>6</Position>
<StoredType>real|0s</StoredType>
</column>
<column id="577" parent="558" name="sell">
<NotNull>1</NotNull>
<Position>7</Position>
<StoredType>real|0s</StoredType>
</column>
<column id="578" parent="558" name="net_sell">
<NotNull>1</NotNull>
<Position>8</Position>
<StoredType>real|0s</StoredType>
</column>
<column id="579" parent="558" name="sold_volume">
<NotNull>1</NotNull>
<Position>9</Position>
<StoredType>integer|0s</StoredType>
</column>
<column id="580" parent="558" name="split_pieces">
<NotNull>1</NotNull>
<Position>10</Position>
<StoredType>jsonb_text|0s</StoredType>
</column>
<column id="581" parent="558" name="gain">
<NotNull>1</NotNull>
<Position>11</Position>
<StoredType>real|0s</StoredType>
</column>
<column id="582" parent="558" name="net_gain">
<NotNull>1</NotNull>
<Position>12</Position>
<StoredType>real|0s</StoredType>
</column>
<key id="583" parent="558">
<ColNames>id</ColNames>
<Primary>1</Primary>
</key>
<column id="584" parent="559" name="id">
<AutoIncrement>1</AutoIncrement>
<NotNull>1</NotNull>
<Position>1</Position>
<StoredType>integer|0s</StoredType>
</column>
<column id="585" parent="559" name="name">
<NotNull>1</NotNull>
<Position>2</Position>
<StoredType>varchar|0s</StoredType>
</column>
<column id="586" parent="559" name="password">
<NotNull>1</NotNull>
<Position>3</Position>
<StoredType>varchar|0s</StoredType>
</column>
<column id="587" parent="559" name="session_token">
<NotNull>1</NotNull>
<Position>4</Position>
<StoredType>varchar|0s</StoredType>
</column>
<key id="574" parent="558">
<key id="588" parent="559">
<ColNames>id</ColNames>
<Primary>1</Primary>
</key>

View File

@ -1,5 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AnalysisUIOptions">
<option name="ANALYZE_INJECTED_CODE" value="false" />
</component>
<component name="AutoImportSettings">
<option name="autoReloadType" value="ALL" />
</component>
@ -7,12 +10,17 @@
<cargoProject FILE="$PROJECT_DIR$/bookkeeper/Cargo.toml" />
</component>
<component name="ChangeListManager">
<list default="true" id="76b3b902-7a5c-4bcd-9c1b-8241d748fb44" name="更改" comment="">
<change afterPath="$PROJECT_DIR$/.idea/dataSources.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/encodings.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/finance-consumer.iml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/modules.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<list default="true" id="76b3b902-7a5c-4bcd-9c1b-8241d748fb44" name="更改" comment="Add bookkeeper">
<change beforePath="$PROJECT_DIR$/.idea/dataSources/244cc0b1-ac8c-4e66-a440-fb727301f139.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/dataSources/244cc0b1-ac8c-4e66-a440-fb727301f139.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/Cargo.lock" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/Cargo.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/Cargo.toml" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/Cargo.toml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/Rocket.toml" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/Rocket.toml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/entity/src/lib.rs" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/entity/src/lib.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/entity/src/prelude.rs" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/entity/src/prelude.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/entity/src/user.rs" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/entity/src/user.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/migration/src/m20220101_000001_create_table.rs" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/migration/src/m20220101_000001_create_table.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/bookkeeper/src/main.rs" beforeDir="false" afterPath="$PROJECT_DIR$/bookkeeper/src/main.rs" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -26,10 +34,10 @@
<component name="MacroExpansionManager">
<option name="directoryName" value="JuSRXtPJ" />
</component>
<component name="ProjectColorInfo"><![CDATA[{
"customColor": "",
"associatedIndex": 1
}]]></component>
<component name="ProjectColorInfo">{
&quot;customColor&quot;: &quot;&quot;,
&quot;associatedIndex&quot;: 1
}</component>
<component name="ProjectId" id="2qcZUdy9HWaLbbMnHbhagjG9xXe" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
@ -48,7 +56,9 @@
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"org.rust.cargo.project.model.PROJECT_DISCOVERY": "true",
"org.rust.cargo.project.model.impl.CargoExternalSystemProjectAware.subscribe.first.balloon": "",
"org.rust.first.attach.projects": "true",
"run.code.analysis.last.selected.profile": "pProject Default",
"settings.editor.selected.configurable": "preferences.customizations",
"vue.rearranger.settings.migration": "true"
}
@ -121,8 +131,18 @@
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1734963841379</updated>
<workItem from="1734963842818" duration="1987000" />
<workItem from="1734963842818" duration="2161000" />
<workItem from="1735129640321" duration="7878000" />
</task>
<task id="LOCAL-00001" summary="Add bookkeeper">
<option name="closed" value="true" />
<created>1734969594691</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1734969594691</updated>
</task>
<option name="localTasksCounter" value="2" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
@ -139,4 +159,8 @@
</map>
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="Add bookkeeper" />
<option name="LAST_COMMIT_MESSAGE" value="Add bookkeeper" />
</component>
</project>

110
bookkeeper/Cargo.lock generated
View File

@ -372,6 +372,12 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.6.0"
@ -423,7 +429,9 @@ dependencies = [
"entity",
"migration",
"rocket",
"rust_decimal",
"sea-orm",
"sea-orm-rocket",
]
[[package]]
@ -713,14 +721,34 @@ dependencies = [
"serde",
]
[[package]]
name = "devise"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50c7580b072f1c8476148f16e0a0d5dedddab787da98d86c5082c5e9ed8ab595"
dependencies = [
"devise_codegen 0.3.1",
"devise_core 0.3.1",
]
[[package]]
name = "devise"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1d90b0c4c777a2cad215e3c7be59ac7c15adf45cf76317009b7d096d46f651d"
dependencies = [
"devise_codegen",
"devise_core",
"devise_codegen 0.4.2",
"devise_core 0.4.2",
]
[[package]]
name = "devise_codegen"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "123c73e7a6e51b05c75fe1a1b2f4e241399ea5740ed810b0e3e6cacd9db5e7b2"
dependencies = [
"devise_core 0.3.1",
"quote",
]
[[package]]
@ -729,19 +757,32 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71b28680d8be17a570a2334922518be6adc3f58ecc880cbb404eaeb8624fd867"
dependencies = [
"devise_core",
"devise_core 0.4.2",
"quote",
]
[[package]]
name = "devise_core"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841ef46f4787d9097405cac4e70fb8644fc037b526e8c14054247c0263c400d0"
dependencies = [
"bitflags 1.3.2",
"proc-macro2",
"proc-macro2-diagnostics 0.9.1",
"quote",
"syn 1.0.109",
]
[[package]]
name = "devise_core"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b035a542cf7abf01f2e3c4d5a7acbaebfefe120ae4efc7bde3df98186e4b8af7"
dependencies = [
"bitflags",
"bitflags 2.6.0",
"proc-macro2",
"proc-macro2-diagnostics",
"proc-macro2-diagnostics 0.10.1",
"quote",
"syn 2.0.90",
]
@ -1790,7 +1831,7 @@ dependencies = [
"heck 0.4.1",
"itertools",
"proc-macro2",
"proc-macro2-diagnostics",
"proc-macro2-diagnostics 0.10.1",
"quote",
"syn 2.0.90",
]
@ -1844,7 +1885,7 @@ checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467"
dependencies = [
"inlinable_string",
"pear_codegen",
"yansi",
"yansi 1.0.1",
]
[[package]]
@ -1854,7 +1895,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147"
dependencies = [
"proc-macro2",
"proc-macro2-diagnostics",
"proc-macro2-diagnostics 0.10.1",
"quote",
"syn 2.0.90",
]
@ -1994,6 +2035,19 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "proc-macro2-diagnostics"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bf29726d67464d49fa6224a1d07936a8c08bb3fba727c7493f6cf1616fdaada"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
"version_check",
"yansi 0.5.1",
]
[[package]]
name = "proc-macro2-diagnostics"
version = "0.10.1"
@ -2004,7 +2058,7 @@ dependencies = [
"quote",
"syn 2.0.90",
"version_check",
"yansi",
"yansi 1.0.1",
]
[[package]]
@ -2078,7 +2132,7 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834"
dependencies = [
"bitflags",
"bitflags 2.6.0",
]
[[package]]
@ -2233,7 +2287,7 @@ dependencies = [
"tokio-util",
"ubyte",
"version_check",
"yansi",
"yansi 1.0.1",
]
[[package]]
@ -2242,7 +2296,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "575d32d7ec1a9770108c879fc7c47815a80073f96ca07ff9525a94fcede1dd46"
dependencies = [
"devise",
"devise 0.4.2",
"glob",
"indexmap",
"proc-macro2",
@ -2328,7 +2382,7 @@ version = "0.38.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
dependencies = [
"bitflags",
"bitflags 2.6.0",
"errno",
"libc",
"linux-raw-sys",
@ -2488,6 +2542,26 @@ dependencies = [
"tracing-subscriber",
]
[[package]]
name = "sea-orm-rocket"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be1e2cd44db4886bcaee4271e895f7d25f41e4bd4c3dffa5b4a286667593c5bb"
dependencies = [
"rocket",
"sea-orm-rocket-codegen",
]
[[package]]
name = "sea-orm-rocket-codegen"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbd35bf98426401976aa90ed163a1cbe9228b6037e59489b25348691437860e1"
dependencies = [
"devise 0.3.1",
"quote",
]
[[package]]
name = "sea-query"
version = "0.32.1"
@ -2844,7 +2918,7 @@ dependencies = [
"atoi",
"base64",
"bigdecimal",
"bitflags",
"bitflags 2.6.0",
"byteorder",
"bytes",
"chrono",
@ -2891,7 +2965,7 @@ dependencies = [
"atoi",
"base64",
"bigdecimal",
"bitflags",
"bitflags 2.6.0",
"byteorder",
"chrono",
"crc",
@ -3776,6 +3850,12 @@ dependencies = [
"tap",
]
[[package]]
name = "yansi"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
[[package]]
name = "yansi"
version = "1.0.1"

View File

@ -8,6 +8,8 @@ chrono = "0.4.39"
rocket = "0.5.1"
migration = { path = "migration" }
entity ={ path = "entity"}
rust_decimal = "1.36.0"
sea-orm-rocket = "0.5.4"
[workspace]
members = [".", "entity", "migration"]

View File

@ -3,6 +3,9 @@
address = "0.0.0.0"
limits = { form = "64 kB", json = "1 MiB" }
[default.databases.bookkeeper]
url = "sqlite://bookkeeper.db"
## set only when compiled in debug mode, i.e, `cargo build`
[debug]
port = 8000
@ -17,4 +20,4 @@ port = 9001
[release]
port = 9999
ip_header = false
secret_key = "hPrYyЭRiMyµ5sBB1π+CMæ1køFsåqKvBiQJxBVHQk="
secret_key = "hPrYyЭRiMyµ5sBB1π+CMæ1køFsåqKvBiQJxBVHQk="

View File

@ -1,6 +1,6 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
#[macro_use]
extern crate rocket;
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.2
pub mod prelude;
pub mod transaction;
pub mod user;

View File

@ -1,3 +1,4 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.2
pub use super::transaction::Entity as Transaction;
pub use super::user::Entity as User;

View File

@ -0,0 +1,29 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.2
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "transaction")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub code: i32,
pub name: String,
pub date: Date,
pub buy: Decimal,
pub volume: i32,
pub net_buy: Decimal,
pub sell_date: Option<Date>,
pub sell: Option<Decimal>,
pub net_sell: Option<Decimal>,
pub sold_volume: Option<i32>,
#[sea_orm(column_type = "JsonBinary", nullable)]
pub split_pieces: Option<Json>,
pub gain: Option<Decimal>,
pub net_gain: Option<Decimal>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}

View File

@ -1,9 +1,8 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
use rocket::serde::{Deserialize, Serialize};
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.2
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Deserialize, Serialize, FromForm)]
#[serde(crate = "rocket::serde")]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key)]

View File

@ -7,18 +7,41 @@ pub struct Migration;
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(pk_auto(User::Id))
.col(string(User::Name))
.col(string(User::Password))
.col(string(User::SessionToken))
.to_owned(),
)
.await
manager.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(pk_auto(User::Id))
.col(string(User::Name))
.col(string(User::Password))
.col(string(User::SessionToken))
.to_owned(),
)
.await?;
manager.create_table(
Table::create()
.table(Transaction::Table)
.if_not_exists()
.col(pk_auto(Transaction::Id))
.col(integer(Transaction::Code))
.col(string(Transaction::Name))
.col(date(Transaction::Date))
.col(decimal(Transaction::Buy))
.col(integer(Transaction::Volume))
.col(decimal(Transaction::NetBuy))
.col(date_null(Transaction::SellDate))
.col(decimal_null(Transaction::Sell))
.col(decimal_null(Transaction::NetSell))
.col(integer_null(Transaction::SoldVolume))
.col(json_binary_null(Transaction::SplitPieces))
.col(decimal_null(Transaction::Gain))
.col(decimal_null(Transaction::NetGain))
.to_owned(),
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
@ -27,7 +50,13 @@ impl MigrationTrait for Migration {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
.await?;
manager
.drop_table(Table::drop().table(Transaction::Table).to_owned())
.await?;
Ok(())
}
}
@ -39,3 +68,22 @@ enum User {
Password,
SessionToken,
}
#[derive(DeriveIden)]
enum Transaction {
Table,
Id,
Code,
Name,
Date,
Buy,
Volume,
NetBuy,
Sell,
SellDate,
NetSell,
SoldVolume,
SplitPieces,
Gain,
NetGain,
}

View File

@ -1,22 +1,98 @@
#[macro_use]
extern crate rocket;
use std::str::FromStr;
use rocket::form::Form;
use rocket::response::{Flash, Redirect};
use migration::{MigratorTrait};
use sea_orm::ActiveValue::Set;
use sea_orm::{ActiveModelTrait, ConnectOptions, DatabaseConnection};
use sea_orm_rocket::{rocket::figment::Figment, Config, Database, Connection};
use std::time::Duration;
use chrono::{NaiveDate};
use entity::transaction;
use rust_decimal::Decimal;
use rocket::{Build, Rocket};
use rocket::fairing::{self, AdHoc};
#[derive(sea_orm_rocket::Database, Debug)]
#[database("bookkeeper")]
struct Db(SeaOrmPool);
#[derive(Debug, Clone)]
struct SeaOrmPool {
conn: DatabaseConnection,
}
#[async_trait]
impl sea_orm_rocket::Pool for SeaOrmPool {
type Connection = DatabaseConnection;
type Error = sea_orm::DbErr;
async fn init(figment: &Figment) -> Result<Self, Self::Error> {
let config = figment.extract::<Config>().unwrap();
let mut options: ConnectOptions = config.url.into();
options
.max_connections(config.max_connections as u32)
.min_connections(config.min_connections.unwrap_or_default())
.connect_timeout(Duration::from_secs(config.connect_timeout))
.sqlx_logging(config.sqlx_logging);
if let Some(idle_timeout) = config.idle_timeout {
options.idle_timeout(Duration::from_secs(idle_timeout));
}
let conn = sea_orm::Database::connect(options).await?;
Ok(SeaOrmPool { conn })
}
fn borrow(&self) -> &Self::Connection {
&self.conn
}
}
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
use migration::{Migrator, MigratorTrait};
use sea_orm::Database;
#[derive(FromForm)]
struct TransBuy<'r> {
code: usize,
name: &'r str,
buy: &'r str,
volume: usize,
net_buy: &'r str,
date: &'r str,
}
#[post("/buy", data = "<trans_buy>")]
async fn buy(trans_buy: Form<TransBuy<'_>>, conn: Connection<'_, Db>) -> Flash<Redirect> {
let record = transaction::ActiveModel {
code: Set(trans_buy.code as i32),
name: Set(trans_buy.name.to_string()),
buy: Set(Decimal::from_str(trans_buy.buy).unwrap()),
volume: Set(trans_buy.volume as i32),
net_buy: Set(Decimal::from_str(trans_buy.net_buy).unwrap()),
date: Set(NaiveDate::parse_from_str(trans_buy.date, "%Y-%m-%d").unwrap()),
..Default::default()
};
record.insert(conn.into_inner()).await.unwrap();
Flash::success(Redirect::to("/"), "OK!")
}
async fn run_migrations(rocket: Rocket<Build>) -> fairing::Result {
let conn = &Db::fetch(&rocket).unwrap().conn;
let _ = migration::Migrator::up(conn, None).await;
Ok(rocket)
}
#[launch]
async fn rocket() -> _ {
let db = Database::connect("sqlite://bookkeeper.db")
.await
.expect("Failed to setup the database");
Migrator::up(&db, None)
.await
.expect("Failed to run migrations for tests");
rocket::build().mount("/", routes![index])
}
rocket::build()
.attach(Db::init())
.attach(AdHoc::try_on_ignite("Migrations", run_migrations))
.mount("/", routes![index, buy])
}