Add & use OrmError (#36)

* Add & use OrmError

* Rename to SeaErr
This commit is contained in:
Billy Chan 2021-06-30 21:08:41 +08:00 committed by GitHub
parent f6ea8a7b3f
commit 2a1173c174
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 203 additions and 241 deletions

View File

@ -1,7 +1,7 @@
use super::*;
use sea_orm::{entity::*, query::*, DbConn};
use sea_orm::{entity::*, error::*, query::*, DbConn};
pub async fn all_about_operation(db: &DbConn) -> Result<(), ExecErr> {
pub async fn all_about_operation(db: &DbConn) -> Result<(), SeaErr> {
insert_and_update(db).await?;
println!("===== =====\n");
@ -15,7 +15,7 @@ pub async fn all_about_operation(db: &DbConn) -> Result<(), ExecErr> {
Ok(())
}
pub async fn insert_and_update(db: &DbConn) -> Result<(), ExecErr> {
pub async fn insert_and_update(db: &DbConn) -> Result<(), SeaErr> {
let pear = fruit::ActiveModel {
name: Set("pear".to_owned()),
..Default::default()
@ -25,10 +25,7 @@ pub async fn insert_and_update(db: &DbConn) -> Result<(), ExecErr> {
println!();
println!("Inserted: last_insert_id = {}\n", res.last_insert_id);
let pear: Option<fruit::Model> = Fruit::find_by_id(res.last_insert_id)
.one(db)
.await
.map_err(|_| ExecErr)?;
let pear: Option<fruit::Model> = Fruit::find_by_id(res.last_insert_id).one(db).await?;
println!();
println!("Pear: {:?}\n", pear);
@ -44,7 +41,7 @@ pub async fn insert_and_update(db: &DbConn) -> Result<(), ExecErr> {
Ok(())
}
pub async fn save_active_model(db: &DbConn) -> Result<(), ExecErr> {
pub async fn save_active_model(db: &DbConn) -> Result<(), SeaErr> {
let banana = fruit::ActiveModel {
name: Set("Banana".to_owned()),
..Default::default()
@ -82,7 +79,7 @@ mod form {
}
}
async fn save_custom_active_model(db: &DbConn) -> Result<(), ExecErr> {
async fn save_custom_active_model(db: &DbConn) -> Result<(), SeaErr> {
let pineapple = form::ActiveModel {
id: Unset(None),
name: Set("Pineapple".to_owned()),

View File

@ -1,7 +1,7 @@
use super::*;
use sea_orm::{entity::*, query::*, DbConn, FromQueryResult};
use sea_orm::{entity::*, error::*, query::*, DbConn, FromQueryResult};
pub async fn all_about_select(db: &DbConn) -> Result<(), QueryErr> {
pub async fn all_about_select(db: &DbConn) -> Result<(), SeaErr> {
find_all(db).await?;
println!("===== =====\n");
@ -41,7 +41,7 @@ pub async fn all_about_select(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_all(db: &DbConn) -> Result<(), QueryErr> {
async fn find_all(db: &DbConn) -> Result<(), SeaErr> {
print!("find all cakes: ");
let cakes: Vec<cake::Model> = Cake::find().all(db).await?;
@ -63,7 +63,7 @@ async fn find_all(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_together(db: &DbConn) -> Result<(), QueryErr> {
async fn find_together(db: &DbConn) -> Result<(), SeaErr> {
print!("find cakes and fruits: ");
let both = Cake::find().find_also_related(Fruit).all(db).await?;
@ -82,7 +82,7 @@ impl Cake {
}
}
async fn find_one(db: &DbConn) -> Result<(), QueryErr> {
async fn find_one(db: &DbConn) -> Result<(), SeaErr> {
print!("find one by primary key: ");
let cheese: Option<cake::Model> = Cake::find_by_id(1).one(db).await?;
@ -112,7 +112,7 @@ async fn find_one(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn count_fruits_by_cake(db: &DbConn) -> Result<(), QueryErr> {
async fn count_fruits_by_cake(db: &DbConn) -> Result<(), SeaErr> {
#[derive(Debug, FromQueryResult)]
struct SelectResult {
name: String,
@ -138,7 +138,7 @@ async fn count_fruits_by_cake(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_many_to_many(db: &DbConn) -> Result<(), QueryErr> {
async fn find_many_to_many(db: &DbConn) -> Result<(), SeaErr> {
print!("find cakes and fillings: ");
let both: Vec<(cake::Model, Vec<filling::Model>)> =
@ -178,7 +178,7 @@ async fn find_many_to_many(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn all_about_select_json(db: &DbConn) -> Result<(), QueryErr> {
async fn all_about_select_json(db: &DbConn) -> Result<(), SeaErr> {
find_all_json(&db).await?;
println!("===== =====\n");
@ -192,7 +192,7 @@ async fn all_about_select_json(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_all_json(db: &DbConn) -> Result<(), QueryErr> {
async fn find_all_json(db: &DbConn) -> Result<(), SeaErr> {
print!("find all cakes: ");
let cakes = Cake::find().into_json().all(db).await?;
@ -208,7 +208,7 @@ async fn find_all_json(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_together_json(db: &DbConn) -> Result<(), QueryErr> {
async fn find_together_json(db: &DbConn) -> Result<(), SeaErr> {
print!("find cakes and fruits: ");
let cakes_fruits = Cake::find()
@ -225,7 +225,7 @@ async fn find_together_json(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn count_fruits_by_cake_json(db: &DbConn) -> Result<(), QueryErr> {
async fn count_fruits_by_cake_json(db: &DbConn) -> Result<(), SeaErr> {
print!("count fruits by cake: ");
let count = Cake::find()
@ -243,7 +243,7 @@ async fn count_fruits_by_cake_json(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_all_stream(db: &DbConn) -> Result<(), QueryErr> {
async fn find_all_stream(db: &DbConn) -> Result<(), SeaErr> {
use async_std::task::sleep;
use futures::TryStreamExt;
use std::time::Duration;
@ -291,7 +291,7 @@ async fn find_all_stream(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_first_page(db: &DbConn) -> Result<(), QueryErr> {
async fn find_first_page(db: &DbConn) -> Result<(), SeaErr> {
println!("fruits first page: ");
let page = fruit::Entity::find().paginate(db, 2).fetch_page(0).await?;
for fruit in page {
@ -301,7 +301,7 @@ async fn find_first_page(db: &DbConn) -> Result<(), QueryErr> {
Ok(())
}
async fn find_num_pages(db: &DbConn) -> Result<(), QueryErr> {
async fn find_num_pages(db: &DbConn) -> Result<(), SeaErr> {
println!("fruits number of page: ");
let num_pages = fruit::Entity::find().paginate(db, 2).num_pages().await?;
println!("{:?}", num_pages);

View File

@ -37,11 +37,11 @@ pub fn expand_derive_active_model(ident: Ident, data: Data) -> syn::Result<Token
}
impl ActiveModel {
pub async fn save(self, db: &sea_orm::DatabaseConnection) -> Result<Self, sea_orm::ExecErr> {
pub async fn save(self, db: &sea_orm::DatabaseConnection) -> Result<Self, sea_orm::SeaErr> {
sea_orm::save_active_model::<Self, Entity>(self, db).await
}
pub async fn delete(self, db: &sea_orm::DatabaseConnection) -> Result<sea_orm::DeleteResult, sea_orm::ExecErr> {
pub async fn delete(self, db: &sea_orm::DatabaseConnection) -> Result<sea_orm::DeleteResult, sea_orm::SeaErr> {
sea_orm::delete_active_model::<Self, Entity>(self, db).await
}
}

View File

@ -30,7 +30,7 @@ pub fn expand_derive_from_query_result(ident: Ident, data: Data) -> syn::Result<
Ok(quote!(
impl sea_orm::FromQueryResult for #ident {
fn from_query_result(row: &sea_orm::QueryResult, pre: &str) -> Result<Self, sea_orm::TypeErr> {
fn from_query_result(row: &sea_orm::QueryResult, pre: &str) -> Result<Self, sea_orm::SeaErr> {
Ok(Self {
#(#field: row.try_get(pre, #name)?),*
})

View File

@ -47,7 +47,7 @@ pub fn expand_derive_model(ident: Ident, data: Data) -> syn::Result<TokenStream>
}
impl sea_orm::FromQueryResult for #ident {
fn from_query_result(row: &sea_orm::QueryResult, pre: &str) -> Result<Self, sea_orm::TypeErr> {
fn from_query_result(row: &sea_orm::QueryResult, pre: &str) -> Result<Self, sea_orm::SeaErr> {
Ok(Self {
#(#field: row.try_get(pre, <<Self as ModelTrait>::Entity as EntityTrait>::Column::#name.as_str().into())?),*
})

View File

@ -1,9 +1,8 @@
use crate::{ExecErr, ExecResult, QueryErr, QueryResult, Statement, Transaction};
use crate::{error::*, ExecResult, QueryResult, Statement, Transaction};
use sea_query::{
MysqlQueryBuilder, PostgresQueryBuilder, QueryStatementBuilder, SchemaStatementBuilder,
SqliteQueryBuilder,
};
use std::{error::Error, fmt};
pub enum DatabaseConnection {
#[cfg(feature = "sqlx-mysql")]
@ -29,17 +28,6 @@ pub enum SchemaBuilderBackend {
Sqlite,
}
#[derive(Debug)]
pub struct ConnectionErr;
impl Error for ConnectionErr {}
impl fmt::Display for ConnectionErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl Default for DatabaseConnection {
fn default() -> Self {
Self::Disconnected
@ -89,7 +77,7 @@ impl DatabaseConnection {
}
}
pub async fn execute(&self, stmt: Statement) -> Result<ExecResult, ExecErr> {
pub async fn execute(&self, stmt: Statement) -> Result<ExecResult, SeaErr> {
match self {
#[cfg(feature = "sqlx-mysql")]
DatabaseConnection::SqlxMySqlPoolConnection(conn) => conn.execute(stmt).await,
@ -101,7 +89,7 @@ impl DatabaseConnection {
}
}
pub async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, QueryErr> {
pub async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, SeaErr> {
match self {
#[cfg(feature = "sqlx-mysql")]
DatabaseConnection::SqlxMySqlPoolConnection(conn) => conn.query_one(stmt).await,
@ -113,7 +101,7 @@ impl DatabaseConnection {
}
}
pub async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, QueryErr> {
pub async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, SeaErr> {
match self {
#[cfg(feature = "sqlx-mysql")]
DatabaseConnection::SqlxMySqlPoolConnection(conn) => conn.query_all(stmt).await,

View File

@ -1,7 +1,7 @@
use crate::{
DatabaseConnection, EntityTrait, ExecErr, ExecResult, ExecResultHolder, Iden, Iterable,
MockDatabaseConnection, MockDatabaseTrait, ModelTrait, QueryErr, QueryResult, QueryResultRow,
Statement, Transaction, TypeErr,
error::*, DatabaseConnection, EntityTrait, ExecResult, ExecResultHolder, Iden, Iterable,
MockDatabaseConnection, MockDatabaseTrait, ModelTrait, QueryResult, QueryResultRow, Statement,
Transaction,
};
use sea_query::{Value, ValueType};
use std::collections::BTreeMap;
@ -68,14 +68,14 @@ impl MockDatabase {
}
impl MockDatabaseTrait for MockDatabase {
fn execute(&mut self, counter: usize, statement: Statement) -> Result<ExecResult, ExecErr> {
fn execute(&mut self, counter: usize, statement: Statement) -> Result<ExecResult, SeaErr> {
self.transaction_log.push(Transaction::one(statement));
if counter < self.exec_results.len() {
Ok(ExecResult {
result: ExecResultHolder::Mock(std::mem::take(&mut self.exec_results[counter])),
})
} else {
Err(ExecErr)
Err(SeaErr::Execution)
}
}
@ -83,7 +83,7 @@ impl MockDatabaseTrait for MockDatabase {
&mut self,
counter: usize,
statement: Statement,
) -> Result<Vec<QueryResult>, QueryErr> {
) -> Result<Vec<QueryResult>, SeaErr> {
self.transaction_log.push(Transaction::one(statement));
if counter < self.query_results.len() {
Ok(std::mem::take(&mut self.query_results[counter])
@ -93,7 +93,7 @@ impl MockDatabaseTrait for MockDatabase {
})
.collect())
} else {
Err(QueryErr)
Err(SeaErr::Query)
}
}
@ -103,7 +103,7 @@ impl MockDatabaseTrait for MockDatabase {
}
impl MockRow {
pub fn try_get<T>(&self, col: &str) -> Result<T, TypeErr>
pub fn try_get<T>(&self, col: &str) -> Result<T, SeaErr>
where
T: ValueType,
{

View File

@ -10,11 +10,13 @@ pub use mock::*;
pub use statement::*;
pub use transaction::*;
use crate::SeaErr;
#[derive(Debug, Default)]
pub struct Database;
impl Database {
pub async fn connect(string: &str) -> Result<DatabaseConnection, ConnectionErr> {
pub async fn connect(string: &str) -> Result<DatabaseConnection, SeaErr> {
#[cfg(feature = "sqlx-mysql")]
if crate::SqlxMySqlConnector::accepts(string) {
return Ok(crate::SqlxMySqlConnector::connect(string).await?);
@ -27,6 +29,6 @@ impl Database {
if crate::MockDatabaseConnector::accepts(string) {
return Ok(crate::MockDatabaseConnector::connect(string).await?);
}
Err(ConnectionErr)
Err(SeaErr::Connection)
}
}

View File

@ -1,6 +1,6 @@
use crate::{
debug_print, ConnectionErr, DatabaseConnection, ExecErr, ExecResult, MockDatabase, QueryErr,
QueryResult, Statement, Transaction,
debug_print, error::*, DatabaseConnection, ExecResult, MockDatabase, QueryResult, Statement,
Transaction,
};
use std::sync::{
atomic::{AtomicUsize, Ordering},
@ -15,9 +15,9 @@ pub struct MockDatabaseConnection {
}
pub trait MockDatabaseTrait: Send {
fn execute(&mut self, counter: usize, stmt: Statement) -> Result<ExecResult, ExecErr>;
fn execute(&mut self, counter: usize, stmt: Statement) -> Result<ExecResult, SeaErr>;
fn query(&mut self, counter: usize, stmt: Statement) -> Result<Vec<QueryResult>, QueryErr>;
fn query(&mut self, counter: usize, stmt: Statement) -> Result<Vec<QueryResult>, SeaErr>;
fn drain_transaction_log(&mut self) -> Vec<Transaction>;
}
@ -27,7 +27,7 @@ impl MockDatabaseConnector {
string.starts_with("mock://")
}
pub async fn connect(_string: &str) -> Result<DatabaseConnection, ConnectionErr> {
pub async fn connect(_string: &str) -> Result<DatabaseConnection, SeaErr> {
Ok(DatabaseConnection::MockDatabaseConnection(
MockDatabaseConnection::new(MockDatabase::new()),
))
@ -49,20 +49,20 @@ impl MockDatabaseConnection {
&self.mocker
}
pub async fn execute(&self, statement: Statement) -> Result<ExecResult, ExecErr> {
pub async fn execute(&self, statement: Statement) -> Result<ExecResult, SeaErr> {
debug_print!("{}", statement);
let counter = self.counter.fetch_add(1, Ordering::SeqCst);
self.mocker.lock().unwrap().execute(counter, statement)
}
pub async fn query_one(&self, statement: Statement) -> Result<Option<QueryResult>, QueryErr> {
pub async fn query_one(&self, statement: Statement) -> Result<Option<QueryResult>, SeaErr> {
debug_print!("{}", statement);
let counter = self.counter.fetch_add(1, Ordering::SeqCst);
let result = self.mocker.lock().unwrap().query(counter, statement)?;
Ok(result.into_iter().next())
}
pub async fn query_all(&self, statement: Statement) -> Result<Vec<QueryResult>, QueryErr> {
pub async fn query_all(&self, statement: Statement) -> Result<Vec<QueryResult>, SeaErr> {
debug_print!("{}", statement);
let counter = self.counter.fetch_add(1, Ordering::SeqCst);
self.mocker.lock().unwrap().query(counter, statement)

View File

@ -4,8 +4,6 @@ mod mock;
mod sqlx_mysql;
#[cfg(feature = "sqlx-sqlite")]
mod sqlx_sqlite;
#[cfg(feature = "sqlx-dep")]
mod sqlx_types;
#[cfg(feature = "mock")]
pub use mock::*;
@ -13,5 +11,3 @@ pub use mock::*;
pub use sqlx_mysql::*;
#[cfg(feature = "sqlx-sqlite")]
pub use sqlx_sqlite::*;
#[cfg(feature = "sqlx-dep")]
pub use sqlx_types::*;

View File

@ -6,7 +6,7 @@ use sqlx::{
sea_query::sea_query_driver_mysql!();
use sea_query_driver_mysql::bind_query;
use crate::{debug_print, executor::*, ConnectionErr, DatabaseConnection, Statement};
use crate::{debug_print, error::*, executor::*, DatabaseConnection, Statement};
pub struct SqlxMySqlConnector;
@ -19,13 +19,13 @@ impl SqlxMySqlConnector {
string.starts_with("mysql://")
}
pub async fn connect(string: &str) -> Result<DatabaseConnection, ConnectionErr> {
pub async fn connect(string: &str) -> Result<DatabaseConnection, SeaErr> {
if let Ok(pool) = MySqlPool::connect(string).await {
Ok(DatabaseConnection::SqlxMySqlPoolConnection(
SqlxMySqlPoolConnection { pool },
))
} else {
Err(ConnectionErr)
Err(SeaErr::Connection)
}
}
}
@ -37,7 +37,7 @@ impl SqlxMySqlConnector {
}
impl SqlxMySqlPoolConnection {
pub async fn execute(&self, stmt: Statement) -> Result<ExecResult, ExecErr> {
pub async fn execute(&self, stmt: Statement) -> Result<ExecResult, SeaErr> {
debug_print!("{}", stmt);
let query = sqlx_query(&stmt);
@ -46,10 +46,10 @@ impl SqlxMySqlPoolConnection {
return Ok(res.into());
}
}
Err(ExecErr)
Err(SeaErr::Execution)
}
pub async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, QueryErr> {
pub async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, SeaErr> {
debug_print!("{}", stmt);
let query = sqlx_query(&stmt);
@ -60,11 +60,11 @@ impl SqlxMySqlPoolConnection {
Ok(None)
}
} else {
Err(QueryErr)
Err(SeaErr::Query)
}
}
pub async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, QueryErr> {
pub async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, SeaErr> {
debug_print!("{}", stmt);
let query = sqlx_query(&stmt);
@ -73,7 +73,7 @@ impl SqlxMySqlPoolConnection {
return Ok(rows.into_iter().map(|r| r.into()).collect());
}
}
Err(QueryErr)
Err(SeaErr::Query)
}
}

View File

@ -6,7 +6,7 @@ use sqlx::{
sea_query::sea_query_driver_sqlite!();
use sea_query_driver_sqlite::bind_query;
use crate::{debug_print, executor::*, ConnectionErr, DatabaseConnection, Statement};
use crate::{debug_print, error::*, executor::*, DatabaseConnection, Statement};
pub struct SqlxSqliteConnector;
@ -19,13 +19,13 @@ impl SqlxSqliteConnector {
string.starts_with("sqlite:")
}
pub async fn connect(string: &str) -> Result<DatabaseConnection, ConnectionErr> {
pub async fn connect(string: &str) -> Result<DatabaseConnection, SeaErr> {
if let Ok(pool) = SqlitePool::connect(string).await {
Ok(DatabaseConnection::SqlxSqlitePoolConnection(
SqlxSqlitePoolConnection { pool },
))
} else {
Err(ConnectionErr)
Err(SeaErr::Connection)
}
}
}
@ -37,7 +37,7 @@ impl SqlxSqliteConnector {
}
impl SqlxSqlitePoolConnection {
pub async fn execute(&self, stmt: Statement) -> Result<ExecResult, ExecErr> {
pub async fn execute(&self, stmt: Statement) -> Result<ExecResult, SeaErr> {
debug_print!("{}", stmt);
let query = sqlx_query(&stmt);
@ -46,10 +46,10 @@ impl SqlxSqlitePoolConnection {
return Ok(res.into());
}
}
Err(ExecErr)
Err(SeaErr::Execution)
}
pub async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, QueryErr> {
pub async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, SeaErr> {
debug_print!("{}", stmt);
let query = sqlx_query(&stmt);
@ -60,11 +60,11 @@ impl SqlxSqlitePoolConnection {
Ok(None)
}
} else {
Err(QueryErr)
Err(SeaErr::Query)
}
}
pub async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, QueryErr> {
pub async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, SeaErr> {
debug_print!("{}", stmt);
let query = sqlx_query(&stmt);
@ -73,7 +73,7 @@ impl SqlxSqlitePoolConnection {
return Ok(rows.into_iter().map(|r| r.into()).collect());
}
}
Err(QueryErr)
Err(SeaErr::Query)
}
}

View File

@ -1,13 +0,0 @@
use crate::{ExecErr, TypeErr};
impl From<sqlx::Error> for TypeErr {
fn from(_: sqlx::Error) -> TypeErr {
TypeErr
}
}
impl From<sqlx::Error> for ExecErr {
fn from(_: sqlx::Error) -> ExecErr {
ExecErr
}
}

View File

@ -1,5 +1,5 @@
use crate::{
DatabaseConnection, DeleteResult, EntityTrait, ExecErr, Iterable, PrimaryKeyToColumn,
error::*, DatabaseConnection, DeleteResult, EntityTrait, Iterable, PrimaryKeyToColumn,
PrimaryKeyTrait, Value,
};
use std::fmt::Debug;
@ -66,8 +66,8 @@ pub trait ActiveModelTrait: Clone + Debug {
fn default() -> Self;
// below is not yet possible. right now we define these methods in DeriveActiveModel
// fn save(self, db: &DatabaseConnection) -> impl Future<Output = Result<Self, ExecErr>>;
// fn delete(self, db: &DatabaseConnection) -> impl Future<Output = Result<DeleteResult, ExecErr>>;
// fn save(self, db: &DatabaseConnection) -> impl Future<Output = Result<Self, SeaErr>>;
// fn delete(self, db: &DatabaseConnection) -> impl Future<Output = Result<DeleteResult, SeaErr>>;
}
/// Behaviors for users to override
@ -188,7 +188,7 @@ where
/// Insert the model if primary key is unset, update otherwise.
/// Only works if the entity has auto increment primary key.
pub async fn save_active_model<A, E>(mut am: A, db: &DatabaseConnection) -> Result<A, ExecErr>
pub async fn save_active_model<A, E>(mut am: A, db: &DatabaseConnection) -> Result<A, SeaErr>
where
A: ActiveModelBehavior + ActiveModelTrait<Entity = E>,
E::Model: IntoActiveModel<A>,
@ -212,7 +212,7 @@ where
Ok(am)
}
async fn insert_and_select_active_model<A, E>(am: A, db: &DatabaseConnection) -> Result<A, ExecErr>
async fn insert_and_select_active_model<A, E>(am: A, db: &DatabaseConnection) -> Result<A, SeaErr>
where
A: ActiveModelTrait<Entity = E>,
E::Model: IntoActiveModel<A>,
@ -224,17 +224,17 @@ where
if <E::PrimaryKey as PrimaryKeyTrait>::auto_increment() && res.last_insert_id != 0 {
let find = E::find_by_id(res.last_insert_id).one(db);
let res = find.await;
let model: Option<E::Model> = res.map_err(|_| ExecErr)?;
let model: Option<E::Model> = res?;
match model {
Some(model) => Ok(model.into_active_model()),
None => Err(ExecErr),
None => Err(SeaErr::Execution),
}
} else {
Ok(A::default())
}
}
async fn update_active_model<A, E>(am: A, db: &DatabaseConnection) -> Result<A, ExecErr>
async fn update_active_model<A, E>(am: A, db: &DatabaseConnection) -> Result<A, SeaErr>
where
A: ActiveModelTrait<Entity = E>,
E: EntityTrait,
@ -246,7 +246,7 @@ where
pub async fn delete_active_model<A, E>(
mut am: A,
db: &DatabaseConnection,
) -> Result<DeleteResult, ExecErr>
) -> Result<DeleteResult, SeaErr>
where
A: ActiveModelBehavior + ActiveModelTrait<Entity = E>,
E: EntityTrait,

View File

@ -1,4 +1,4 @@
use crate::{EntityTrait, QueryFilter, QueryResult, Related, Select, TypeErr};
use crate::{EntityTrait, SeaErr, QueryFilter, QueryResult, Related, Select};
pub use sea_query::Value;
use std::fmt::Debug;
@ -19,11 +19,11 @@ pub trait ModelTrait: Clone + Debug {
}
pub trait FromQueryResult {
fn from_query_result(res: &QueryResult, pre: &str) -> Result<Self, TypeErr>
fn from_query_result(res: &QueryResult, pre: &str) -> Result<Self, SeaErr>
where
Self: Sized;
fn from_query_result_optional(res: &QueryResult, pre: &str) -> Result<Option<Self>, TypeErr>
fn from_query_result_optional(res: &QueryResult, pre: &str) -> Result<Option<Self>, SeaErr>
where
Self: Sized,
{

View File

@ -1,7 +1,7 @@
pub use crate::{
ActiveModelBehavior, ActiveModelTrait, ColumnDef, ColumnTrait, ColumnType, DeriveActiveModel,
DeriveActiveModelBehavior, DeriveColumn, DeriveEntity, DeriveModel, DerivePrimaryKey,
EntityName, EntityTrait, EnumIter, Iden, IdenStatic, ModelTrait, PrimaryKeyToColumn,
PrimaryKeyTrait, QueryFilter, QueryResult, Related, RelationDef, RelationTrait, Select,
TypeErr, Value,
error::*, ActiveModelBehavior, ActiveModelTrait, ColumnDef, ColumnTrait, ColumnType,
DeriveActiveModel, DeriveActiveModelBehavior, DeriveColumn, DeriveEntity, DeriveModel,
DerivePrimaryKey, EntityName, EntityTrait, EnumIter, Iden, IdenStatic, ModelTrait,
PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult, Related, RelationDef,
RelationTrait, Select, Value,
};

41
src/error.rs Normal file
View File

@ -0,0 +1,41 @@
use std::{error, fmt};
#[derive(Debug)]
pub enum SeaErr {
Connection,
Execution,
Query,
#[cfg(feature = "sqlx-dep")]
Sqlx(sqlx::Error),
}
impl fmt::Display for SeaErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Connection => write!(f, "{:?}", "Connection Error"),
Self::Execution => write!(f, "{:?}", "Execution Error"),
Self::Query => write!(f, "{:?}", "Query Error"),
#[cfg(feature = "sqlx-dep")]
Self::Sqlx(e) => write!(f, "{:?}", e),
}
}
}
impl error::Error for SeaErr {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::Connection => None,
Self::Execution => None,
Self::Query => None,
#[cfg(feature = "sqlx-dep")]
Self::Sqlx(e) => Some(e),
}
}
}
#[cfg(feature = "sqlx-dep")]
impl From<sqlx::Error> for SeaErr {
fn from(sqlx_err: sqlx::Error) -> Self {
Self::Sqlx(sqlx_err)
}
}

View File

@ -1,5 +1,5 @@
use crate::{
ActiveModelTrait, DatabaseConnection, DeleteMany, DeleteOne, EntityTrait, ExecErr, Statement,
error::*, ActiveModelTrait, DatabaseConnection, DeleteMany, DeleteOne, EntityTrait, Statement,
};
use sea_query::DeleteStatement;
use std::future::Future;
@ -21,7 +21,7 @@ where
pub fn exec(
self,
db: &'a DatabaseConnection,
) -> impl Future<Output = Result<DeleteResult, ExecErr>> + 'a {
) -> impl Future<Output = Result<DeleteResult, SeaErr>> + 'a {
// so that self is dropped before entering await
exec_delete_only(self.query, db)
}
@ -34,7 +34,7 @@ where
pub fn exec(
self,
db: &'a DatabaseConnection,
) -> impl Future<Output = Result<DeleteResult, ExecErr>> + 'a {
) -> impl Future<Output = Result<DeleteResult, SeaErr>> + 'a {
// so that self is dropped before entering await
exec_delete_only(self.query, db)
}
@ -48,7 +48,7 @@ impl Deleter {
pub fn exec(
self,
db: &DatabaseConnection,
) -> impl Future<Output = Result<DeleteResult, ExecErr>> + '_ {
) -> impl Future<Output = Result<DeleteResult, SeaErr>> + '_ {
let builder = db.get_query_builder_backend();
exec_delete(builder.build(&self.query), db)
}
@ -57,7 +57,7 @@ impl Deleter {
async fn exec_delete_only(
query: DeleteStatement,
db: &DatabaseConnection,
) -> Result<DeleteResult, ExecErr> {
) -> Result<DeleteResult, SeaErr> {
Deleter::new(query).exec(db).await
}
@ -65,7 +65,7 @@ async fn exec_delete_only(
async fn exec_delete(
statement: Statement,
db: &DatabaseConnection,
) -> Result<DeleteResult, ExecErr> {
) -> Result<DeleteResult, SeaErr> {
let result = db.execute(statement).await?;
Ok(DeleteResult {
rows_affected: result.rows_affected(),

View File

@ -1,5 +1,3 @@
use std::{error::Error, fmt};
#[derive(Debug)]
pub struct ExecResult {
pub(crate) result: ExecResultHolder,
@ -15,9 +13,6 @@ pub(crate) enum ExecResultHolder {
Mock(crate::MockExecResult),
}
#[derive(Debug)]
pub struct ExecErr;
// ExecResult //
impl ExecResult {
@ -50,13 +45,3 @@ impl ExecResult {
}
}
}
// ExecErr //
impl Error for ExecErr {}
impl fmt::Display for ExecErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}

View File

@ -1,4 +1,4 @@
use crate::{ActiveModelTrait, DatabaseConnection, ExecErr, Insert, QueryTrait, Statement};
use crate::{error::*, ActiveModelTrait, DatabaseConnection, Insert, QueryTrait, Statement};
use sea_query::InsertStatement;
use std::future::Future;
@ -19,7 +19,7 @@ where
pub fn exec(
self,
db: &DatabaseConnection,
) -> impl Future<Output = Result<InsertResult, ExecErr>> + '_ {
) -> impl Future<Output = Result<InsertResult, SeaErr>> + '_ {
// so that self is dropped before entering await
Inserter::new(self.into_query()).exec(db)
}
@ -33,7 +33,7 @@ impl Inserter {
pub fn exec(
self,
db: &DatabaseConnection,
) -> impl Future<Output = Result<InsertResult, ExecErr>> + '_ {
) -> impl Future<Output = Result<InsertResult, SeaErr>> + '_ {
let builder = db.get_query_builder_backend();
exec_insert(builder.build(&self.query), db)
}
@ -43,7 +43,7 @@ impl Inserter {
async fn exec_insert(
statement: Statement,
db: &DatabaseConnection,
) -> Result<InsertResult, ExecErr> {
) -> Result<InsertResult, SeaErr> {
let result = db.execute(statement).await?;
// TODO: Postgres instead use query_one + returning clause
Ok(InsertResult {

View File

@ -1,4 +1,4 @@
use crate::{DatabaseConnection, QueryErr, SelectorTrait};
use crate::{error::*, DatabaseConnection, SelectorTrait};
use async_stream::stream;
use futures::Stream;
use sea_query::{Alias, Expr, SelectStatement};
@ -23,7 +23,7 @@ where
S: SelectorTrait + 'db,
{
/// Fetch a specific page
pub async fn fetch_page(&self, page: usize) -> Result<Vec<S::Item>, QueryErr> {
pub async fn fetch_page(&self, page: usize) -> Result<Vec<S::Item>, SeaErr> {
let query = self
.query
.clone()
@ -36,18 +36,18 @@ where
let mut buffer = Vec::with_capacity(rows.len());
for row in rows.into_iter() {
// TODO: Error handling
buffer.push(S::from_raw_query_result(row).map_err(|_e| QueryErr)?);
buffer.push(S::from_raw_query_result(row)?);
}
Ok(buffer)
}
/// Fetch the current page
pub async fn fetch(&self) -> Result<Vec<S::Item>, QueryErr> {
pub async fn fetch(&self) -> Result<Vec<S::Item>, SeaErr> {
self.fetch_page(self.page).await
}
/// Get the total number of pages
pub async fn num_pages(&self) -> Result<usize, QueryErr> {
pub async fn num_pages(&self) -> Result<usize, SeaErr> {
let builder = self.db.get_query_builder_backend();
let stmt = builder.build(
SelectStatement::new()
@ -61,9 +61,7 @@ where
Some(res) => res,
None => return Ok(0),
};
let num_rows = result
.try_get::<i32>("", "num_rows")
.map_err(|_e| QueryErr)? as usize;
let num_rows = result.try_get::<i32>("", "num_rows")? as usize;
let num_pages = (num_rows / self.page_size) + (num_rows % self.page_size > 0) as usize;
Ok(num_pages)
}
@ -79,7 +77,7 @@ where
}
/// Fetch one page and increment the page counter
pub async fn fetch_and_next(&mut self) -> Result<Option<Vec<S::Item>>, QueryErr> {
pub async fn fetch_and_next(&mut self) -> Result<Option<Vec<S::Item>>, SeaErr> {
let vec = self.fetch().await?;
self.next();
let opt = if !vec.is_empty() { Some(vec) } else { None };
@ -87,7 +85,7 @@ where
}
/// Convert self into an async stream
pub fn into_stream(mut self) -> PinBoxStream<'db, Result<Vec<S::Item>, QueryErr>> {
pub fn into_stream(mut self) -> PinBoxStream<'db, Result<Vec<S::Item>, SeaErr>> {
Box::pin(stream! {
loop {
if let Some(vec) = self.fetch_and_next().await? {
@ -105,7 +103,7 @@ where
mod tests {
use crate::entity::prelude::*;
use crate::tests_cfg::*;
use crate::{DatabaseConnection, MockDatabase, QueryErr, Transaction};
use crate::{DatabaseConnection, MockDatabase, Transaction};
use futures::TryStreamExt;
use sea_query::{Alias, Expr, SelectStatement, Value};
@ -150,7 +148,7 @@ mod tests {
}
#[async_std::test]
async fn fetch_page() -> Result<(), QueryErr> {
async fn fetch_page() -> Result<(), SeaErr> {
let (db, pages) = setup();
let paginator = fruit::Entity::find().paginate(&db, 2);
@ -180,7 +178,7 @@ mod tests {
}
#[async_std::test]
async fn fetch() -> Result<(), QueryErr> {
async fn fetch() -> Result<(), SeaErr> {
let (db, pages) = setup();
let mut paginator = fruit::Entity::find().paginate(&db, 2);
@ -214,7 +212,7 @@ mod tests {
}
#[async_std::test]
async fn num_pages() -> Result<(), QueryErr> {
async fn num_pages() -> Result<(), SeaErr> {
let (db, num_rows) = setup_num_rows();
let num_rows = num_rows as usize;
@ -246,7 +244,7 @@ mod tests {
}
#[async_std::test]
async fn next_and_cur_page() -> Result<(), QueryErr> {
async fn next_and_cur_page() -> Result<(), SeaErr> {
let (db, _) = setup();
let mut paginator = fruit::Entity::find().paginate(&db, 2);
@ -262,7 +260,7 @@ mod tests {
}
#[async_std::test]
async fn fetch_and_next() -> Result<(), QueryErr> {
async fn fetch_and_next() -> Result<(), SeaErr> {
let (db, pages) = setup();
let mut paginator = fruit::Entity::find().paginate(&db, 2);
@ -297,7 +295,7 @@ mod tests {
}
#[async_std::test]
async fn into_stream() -> Result<(), QueryErr> {
async fn into_stream() -> Result<(), SeaErr> {
let (db, pages) = setup();
let mut fruit_stream = fruit::Entity::find().paginate(&db, 2).into_stream();

View File

@ -1,4 +1,5 @@
use std::{error::Error, fmt};
use crate::SeaErr;
use std::fmt;
#[derive(Debug)]
pub struct QueryResult {
@ -14,14 +15,8 @@ pub(crate) enum QueryResultRow {
Mock(crate::MockRow),
}
#[derive(Debug)]
pub struct QueryErr;
#[derive(Debug)]
pub struct TypeErr;
pub trait TryGetable {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TypeErr>
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, SeaErr>
where
Self: Sized;
}
@ -29,7 +24,7 @@ pub trait TryGetable {
// QueryResult //
impl QueryResult {
pub fn try_get<T>(&self, pre: &str, col: &str) -> Result<T, TypeErr>
pub fn try_get<T>(&self, pre: &str, col: &str) -> Result<T, SeaErr>
where
T: TryGetable,
{
@ -50,38 +45,12 @@ impl fmt::Debug for QueryResultRow {
}
}
// QueryErr //
impl Error for QueryErr {}
impl fmt::Display for QueryErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl From<TypeErr> for QueryErr {
fn from(_: TypeErr) -> QueryErr {
QueryErr
}
}
// TypeErr //
impl Error for TypeErr {}
impl fmt::Display for TypeErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
// TryGetable //
macro_rules! try_getable_all {
( $type: ty ) => {
impl TryGetable for $type {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TypeErr> {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, SeaErr> {
let column = format!("{}{}", pre, col);
match &res.row {
#[cfg(feature = "sqlx-mysql")]
@ -101,7 +70,7 @@ macro_rules! try_getable_all {
}
impl TryGetable for Option<$type> {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TypeErr> {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, SeaErr> {
let column = format!("{}{}", pre, col);
match &res.row {
#[cfg(feature = "sqlx-mysql")]
@ -134,7 +103,7 @@ macro_rules! try_getable_all {
macro_rules! try_getable_mysql {
( $type: ty ) => {
impl TryGetable for $type {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TypeErr> {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, SeaErr> {
let column = format!("{}{}", pre, col);
match &res.row {
#[cfg(feature = "sqlx-mysql")]
@ -153,7 +122,7 @@ macro_rules! try_getable_mysql {
}
impl TryGetable for Option<$type> {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TypeErr> {
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, SeaErr> {
let column = format!("{}{}", pre, col);
match &res.row {
#[cfg(feature = "sqlx-mysql")]

View File

@ -1,7 +1,7 @@
use crate::{
query::combine, DatabaseConnection, EntityTrait, FromQueryResult, Iterable, JsonValue,
ModelTrait, Paginator, PrimaryKeyToColumn, QueryErr, QueryResult, Select, SelectTwo,
SelectTwoMany, TypeErr,
error::*, query::combine, DatabaseConnection, EntityTrait, FromQueryResult, Iterable,
JsonValue, ModelTrait, Paginator, PrimaryKeyToColumn, QueryResult, Select, SelectTwo,
SelectTwoMany,
};
use sea_query::SelectStatement;
use std::marker::PhantomData;
@ -18,7 +18,7 @@ where
pub trait SelectorTrait {
type Item: Sized;
fn from_raw_query_result(res: QueryResult) -> Result<Self::Item, TypeErr>;
fn from_raw_query_result(res: QueryResult) -> Result<Self::Item, SeaErr>;
}
pub struct SelectModel<M>
@ -43,7 +43,7 @@ where
{
type Item = M;
fn from_raw_query_result(res: QueryResult) -> Result<Self::Item, TypeErr> {
fn from_raw_query_result(res: QueryResult) -> Result<Self::Item, SeaErr> {
M::from_query_result(&res, "")
}
}
@ -55,7 +55,7 @@ where
{
type Item = (M, Option<N>);
fn from_raw_query_result(res: QueryResult) -> Result<Self::Item, TypeErr> {
fn from_raw_query_result(res: QueryResult) -> Result<Self::Item, SeaErr> {
Ok((
M::from_query_result(&res, combine::SELECT_A)?,
N::from_query_result_optional(&res, combine::SELECT_B)?,
@ -85,11 +85,11 @@ where
}
}
pub async fn one(self, db: &DatabaseConnection) -> Result<Option<E::Model>, QueryErr> {
pub async fn one(self, db: &DatabaseConnection) -> Result<Option<E::Model>, SeaErr> {
self.into_model::<E::Model>().one(db).await
}
pub async fn all(self, db: &DatabaseConnection) -> Result<Vec<E::Model>, QueryErr> {
pub async fn all(self, db: &DatabaseConnection) -> Result<Vec<E::Model>, SeaErr> {
self.into_model::<E::Model>().all(db).await
}
@ -129,14 +129,14 @@ where
pub async fn one(
self,
db: &DatabaseConnection,
) -> Result<Option<(E::Model, Option<F::Model>)>, QueryErr> {
) -> Result<Option<(E::Model, Option<F::Model>)>, SeaErr> {
self.into_model::<E::Model, F::Model>().one(db).await
}
pub async fn all(
self,
db: &DatabaseConnection,
) -> Result<Vec<(E::Model, Option<F::Model>)>, QueryErr> {
) -> Result<Vec<(E::Model, Option<F::Model>)>, SeaErr> {
self.into_model::<E::Model, F::Model>().all(db).await
}
}
@ -168,14 +168,14 @@ where
pub async fn one(
self,
db: &DatabaseConnection,
) -> Result<Option<(E::Model, Option<F::Model>)>, QueryErr> {
) -> Result<Option<(E::Model, Option<F::Model>)>, SeaErr> {
self.into_model::<E::Model, F::Model>().one(db).await
}
pub async fn all(
self,
db: &DatabaseConnection,
) -> Result<Vec<(E::Model, Vec<F::Model>)>, QueryErr> {
) -> Result<Vec<(E::Model, Vec<F::Model>)>, SeaErr> {
let rows = self.into_model::<E::Model, F::Model>().all(db).await?;
Ok(consolidate_query_result::<E, F>(rows))
}
@ -185,7 +185,7 @@ impl<S> Selector<S>
where
S: SelectorTrait,
{
pub async fn one(mut self, db: &DatabaseConnection) -> Result<Option<S::Item>, QueryErr> {
pub async fn one(mut self, db: &DatabaseConnection) -> Result<Option<S::Item>, SeaErr> {
let builder = db.get_query_builder_backend();
self.query.limit(1);
let row = db.query_one(builder.build(&self.query)).await?;
@ -195,7 +195,7 @@ where
}
}
pub async fn all(self, db: &DatabaseConnection) -> Result<Vec<S::Item>, QueryErr> {
pub async fn all(self, db: &DatabaseConnection) -> Result<Vec<S::Item>, SeaErr> {
let builder = db.get_query_builder_backend();
let rows = db.query_all(builder.build(&self.query)).await?;
let mut models = Vec::new();

View File

@ -1,5 +1,5 @@
use crate::{
ActiveModelTrait, DatabaseConnection, EntityTrait, ExecErr, Statement, UpdateMany, UpdateOne,
error::*, ActiveModelTrait, DatabaseConnection, EntityTrait, Statement, UpdateMany, UpdateOne,
};
use sea_query::UpdateStatement;
use std::future::Future;
@ -18,7 +18,10 @@ impl<'a, A: 'a> UpdateOne<A>
where
A: ActiveModelTrait,
{
pub fn exec(self, db: &'a DatabaseConnection) -> impl Future<Output = Result<A, ExecErr>> + 'a {
pub fn exec(
self,
db: &'a DatabaseConnection,
) -> impl Future<Output = Result<A, SeaErr>> + 'a {
// so that self is dropped before entering await
exec_update_and_return_original(self.query, self.model, db)
}
@ -31,7 +34,7 @@ where
pub fn exec(
self,
db: &'a DatabaseConnection,
) -> impl Future<Output = Result<UpdateResult, ExecErr>> + 'a {
) -> impl Future<Output = Result<UpdateResult, SeaErr>> + 'a {
// so that self is dropped before entering await
exec_update_only(self.query, db)
}
@ -45,7 +48,7 @@ impl Updater {
pub fn exec(
self,
db: &DatabaseConnection,
) -> impl Future<Output = Result<UpdateResult, ExecErr>> + '_ {
) -> impl Future<Output = Result<UpdateResult, SeaErr>> + '_ {
let builder = db.get_query_builder_backend();
exec_update(builder.build(&self.query), db)
}
@ -54,7 +57,7 @@ impl Updater {
async fn exec_update_only(
query: UpdateStatement,
db: &DatabaseConnection,
) -> Result<UpdateResult, ExecErr> {
) -> Result<UpdateResult, SeaErr> {
Updater::new(query).exec(db).await
}
@ -62,7 +65,7 @@ async fn exec_update_and_return_original<A>(
query: UpdateStatement,
model: A,
db: &DatabaseConnection,
) -> Result<A, ExecErr>
) -> Result<A, SeaErr>
where
A: ActiveModelTrait,
{
@ -74,7 +77,7 @@ where
async fn exec_update(
statement: Statement,
db: &DatabaseConnection,
) -> Result<UpdateResult, ExecErr> {
) -> Result<UpdateResult, SeaErr> {
let result = db.execute(statement).await?;
Ok(UpdateResult {
rows_affected: result.rows_affected(),

View File

@ -43,8 +43,8 @@
//!
//! ## Select
//! ```
//! # use sea_orm::{DbConn, entity::*, query::*, tests_cfg::*};
//! # async fn function(db: &DbConn) -> Result<(), QueryErr> {
//! # use sea_orm::{DbConn, error::*, entity::*, query::*, tests_cfg::*};
//! # async fn function(db: &DbConn) -> Result<(), SeaErr> {
//! #
//! // find all models
//! let cakes: Vec<cake::Model> = Cake::find().all(db).await?;
@ -73,8 +73,8 @@
//! ```
//! ## Insert
//! ```
//! # use sea_orm::{DbConn, entity::*, query::*, tests_cfg::*};
//! # async fn function(db: &DbConn) -> Result<(), ExecErr> {
//! # use sea_orm::{DbConn, error::*, entity::*, query::*, tests_cfg::*};
//! # async fn function(db: &DbConn) -> Result<(), SeaErr> {
//! #
//! let apple = fruit::ActiveModel {
//! name: Set("Apple".to_owned()),
@ -94,7 +94,7 @@
//! # Ok(())
//! # }
//! #
//! # async fn function2(db: &DbConn) -> Result<(), ExecErr> {
//! # async fn function2(db: &DbConn) -> Result<(), SeaErr> {
//! # let apple = fruit::ActiveModel {
//! # name: Set("Apple".to_owned()),
//! # ..Default::default() // no need to set primary key
@ -113,16 +113,16 @@
//! ```
//! ## Update
//! ```
//! # use sea_orm::{DbConn, entity::*, query::*, tests_cfg::*};
//! # use sea_orm::{DbConn, error::*, entity::*, query::*, tests_cfg::*};
//! #
//! use sea_orm::sea_query::{Expr, Value};
//!
//! # async fn function(db: &DbConn) -> Result<(), QueryErr> {
//! # async fn function(db: &DbConn) -> Result<(), SeaErr> {
//! let pear: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await?;
//! # Ok(())
//! # }
//! #
//! # async fn function2(db: &DbConn) -> Result<(), ExecErr> {
//! # async fn function2(db: &DbConn) -> Result<(), SeaErr> {
//! # let pear: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await.unwrap();
//!
//! let mut pear: fruit::ActiveModel = pear.unwrap().into();
@ -143,9 +143,9 @@
//! ```
//! ## Save
//! ```
//! # use sea_orm::{DbConn, entity::*, query::*, tests_cfg::*};
//! # use sea_orm::{DbConn, error::*, entity::*, query::*, tests_cfg::*};
//! #
//! # async fn function(db: &DbConn) -> Result<(), ExecErr> {
//! # async fn function(db: &DbConn) -> Result<(), SeaErr> {
//! let banana = fruit::ActiveModel {
//! id: Unset(None),
//! name: Set("Banana".to_owned()),
@ -165,14 +165,14 @@
//! ```
//! ## Delete
//! ```
//! # use sea_orm::{DbConn, entity::*, query::*, tests_cfg::*};
//! # use sea_orm::{DbConn, error::*, entity::*, query::*, tests_cfg::*};
//! #
//! # async fn function(db: &DbConn) -> Result<(), QueryErr> {
//! # async fn function(db: &DbConn) -> Result<(), SeaErr> {
//! let orange: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await?;
//! # Ok(())
//! # }
//! #
//! # async fn function2(db: &DbConn) -> Result<(), ExecErr> {
//! # async fn function2(db: &DbConn) -> Result<(), SeaErr> {
//! # let orange: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await.unwrap();
//! let orange: fruit::ActiveModel = orange.unwrap().into();
//!
@ -198,6 +198,7 @@
mod database;
mod driver;
pub mod entity;
pub mod error;
mod executor;
pub mod query;
#[doc(hidden)]
@ -207,6 +208,7 @@ mod util;
pub use database::*;
pub use driver::*;
pub use entity::*;
pub use error::*;
pub use executor::*;
pub use query::*;

View File

@ -1,9 +1,9 @@
use crate::{FromQueryResult, QueryResult, QueryResultRow, TypeErr};
use crate::{FromQueryResult, SeaErr, QueryResult, QueryResultRow};
use serde_json::Map;
pub use serde_json::Value as JsonValue;
impl FromQueryResult for JsonValue {
fn from_query_result(res: &QueryResult, pre: &str) -> Result<Self, TypeErr> {
fn from_query_result(res: &QueryResult, pre: &str) -> Result<Self, SeaErr> {
match &res.row {
#[cfg(feature = "sqlx-mysql")]
QueryResultRow::SqlxMySql(row) => {

View File

@ -20,4 +20,4 @@ pub use select::*;
pub use traits::*;
pub use update::*;
pub use crate::executor::{ExecErr, InsertResult, QueryErr, UpdateResult};
pub use crate::executor::{InsertResult, UpdateResult};

View File

@ -1,4 +1,4 @@
use sea_orm::{entity::*, query::*, sea_query, tests_cfg::*, DbConn};
use sea_orm::{entity::*, error::*, sea_query, tests_cfg::*, DbConn};
mod setup;
@ -31,7 +31,7 @@ async fn setup_schema(db: &DbConn) {
println!("Create table cake: {:?}", result);
}
async fn crud_cake(db: &DbConn) -> Result<(), ExecErr> {
async fn crud_cake(db: &DbConn) -> Result<(), SeaErr> {
let apple = cake::ActiveModel {
name: Set("Apple Pie".to_owned()),
..Default::default()
@ -57,10 +57,7 @@ async fn crud_cake(db: &DbConn) -> Result<(), ExecErr> {
println!();
println!("Updated: {:?}", apple);
let apple = cake::Entity::find_by_id(1)
.one(db)
.await
.map_err(|_| ExecErr)?;
let apple = cake::Entity::find_by_id(1).one(db).await?;
assert_eq!(
Some(cake::Model {
@ -77,10 +74,7 @@ async fn crud_cake(db: &DbConn) -> Result<(), ExecErr> {
println!();
println!("Deleted: {:?}", result);
let apple = cake::Entity::find_by_id(1)
.one(db)
.await
.map_err(|_| ExecErr)?;
let apple = cake::Entity::find_by_id(1).one(db).await?;
assert_eq!(None, apple);