Skip to content

Commit

Permalink
renamed Result and Error
Browse files Browse the repository at this point in the history
  • Loading branch information
eboody committed Dec 15, 2024
1 parent b7b83c7 commit b01ae44
Show file tree
Hide file tree
Showing 12 changed files with 70 additions and 71 deletions.
4 changes: 2 additions & 2 deletions core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub type CoreResult<T, E = CoreError> = std::result::Result<T, E>;

#[derive(Debug, thiserror::Error)]
pub enum Error {
pub enum CoreError {
#[error(transparent)]
SqlxError(#[from] sqlx::Error),

Expand Down
17 changes: 6 additions & 11 deletions core/src/insert.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use crate::Result;
use crate::CoreResult;
use futures::future::BoxFuture;
pub use sqlmo::query::OnConflict;
use sqlmo::{Dialect, Insert, ToSql, Union, Select, Cte, SelectColumn};
use sqlmo::{Cte, Dialect, Insert, Select, SelectColumn, ToSql, Union};

/// Represents an insert query.
/// We had to turn this into a model because we need to pass in the on_conflict configuration.
pub struct Insertion<'a, Acquire, Model, DB: sqlx::Database> {
pub acquire: Acquire,
pub model: Model,
pub closure: Box<dyn 'static + Send + FnOnce(Acquire, Model, String) -> BoxFuture<'a, Result<Model>>>,
pub closure: Box<dyn 'static + Send + FnOnce(Acquire, Model, String) -> BoxFuture<'a, CoreResult<Model>>>,
pub insert: Insert,
pub _db: std::marker::PhantomData<DB>,
}
Expand All @@ -23,17 +23,15 @@ impl<'a, Acquire, Model, DB: sqlx::Database> Insertion<'a, Acquire, Model, DB> {
impl<'a, Acquire, Model: crate::model::Model<DB>, DB: sqlx::Database> std::future::IntoFuture
for Insertion<'a, Acquire, Model, DB>
{
type Output = Result<Model>;
type Output = CoreResult<Model>;
type IntoFuture = BoxFuture<'a, Self::Output>;

fn into_future(self) -> Self::IntoFuture {
// hack to get around the fact that postgres drops the return
// value in ON CONFLICT DO NOTHING case
let q = if matches!(self.insert.on_conflict, OnConflict::Ignore) {
let insert_as_select = Select {
ctes: vec![
Cte::new("inserted", self.insert)
],
ctes: vec![Cte::new("inserted", self.insert)],
columns: vec![SelectColumn::raw("*")],
from: Some("inserted".into()),
..Select::default()
Expand All @@ -48,10 +46,7 @@ impl<'a, Acquire, Model: crate::model::Model<DB>, DB: sqlx::Database> std::futur
};
let union = Union {
all: true,
queries: vec![
insert_as_select,
select_existing
]
queries: vec![insert_as_select, select_existing],
};
union.to_sql(Dialect::Postgres)
} else {
Expand Down
38 changes: 21 additions & 17 deletions core/src/join.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::model::Model;
use async_trait::async_trait;
use serde::de::Error;
use serde::Deserialize;
use serde::{Serialize, Serializer};
use sqlmo::query::Join as JoinQueryFragment;
use sqlmo::query::SelectColumn;
use sqlx::{Database, Decode, Encode, Type};
use std::ops::{Deref, DerefMut};
use serde::de::Error;

pub trait JoinMeta {
type IdType: Clone + Send + Eq + PartialEq + std::hash::Hash;
Expand All @@ -31,7 +31,7 @@ impl<T: JoinMeta> JoinMeta for Join<T> {

#[async_trait]
pub trait Loadable<DB, T: JoinMeta> {
async fn load<'s, 'e, E>(&'s mut self, db: E) -> crate::error::Result<&'s T>
async fn load<'s, 'e, E>(&'s mut self, db: E) -> crate::error::CoreResult<&'s T>
where
T::IdType: 'e + Send + Sync,
E: 'e + sqlx::Executor<'e, Database = DB>;
Expand Down Expand Up @@ -131,7 +131,7 @@ where
async fn load<'s, 'e, E: sqlx::Executor<'e, Database = DB> + 'e>(
&'s mut self,
conn: E,
) -> crate::error::Result<&'s T>
) -> crate::error::CoreResult<&'s T>
where
T::IdType: 'e + Send + Sync,
{
Expand Down Expand Up @@ -228,20 +228,24 @@ impl<T: JoinMeta + Serialize> Serialize for Join<T> {
}

impl<'de, T> Deserialize<'de> for Join<T>
where
T: JoinMeta + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
T: JoinMeta + Deserialize<'de>,
D: serde::Deserializer<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let data = Option::<T>::deserialize(deserializer)?;

let (id_type, join_data) = match data {
Some(value) => (T::_id(&value), JoinData::QueryResult(value)),
None => return Err(D::Error::custom("Invalid value"))
};

Ok(Join { id: id_type, data: join_data })
}
let data = Option::<T>::deserialize(deserializer)?;

let (id_type, join_data) = match data {
Some(value) => (T::_id(&value), JoinData::QueryResult(value)),
None => return Err(D::Error::custom("Invalid value")),
};

Ok(Join {
id: id_type,
data: join_data,
})
}
}

2 changes: 1 addition & 1 deletion core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub use self::error::{Error, Result};
pub use self::error::{CoreError, CoreResult};
pub use self::query_builder::SelectQueryBuilder;
pub use futures::future::BoxFuture;
pub use join::Join;
Expand Down
14 changes: 7 additions & 7 deletions core/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
/// - `ormlite::TableMeta`, which you typically don't use directly, but provides table metadata
/// (e.g. table name)
///
use crate::Result;
use crate::CoreResult;
use crate::SelectQueryBuilder;
use futures::future::BoxFuture;

Expand All @@ -31,7 +31,7 @@ where
DB: sqlx::Database,
{
type Model;
fn insert<'e, A>(self, conn: A) -> BoxFuture<'e, Result<Self::Model>>
fn insert<'e, A>(self, conn: A) -> BoxFuture<'e, CoreResult<Self::Model>>
where
A: 'e + Send + sqlx::Acquire<'e, Database = DB>;
}
Expand All @@ -44,11 +44,11 @@ where
{
type Model;

fn insert<'e: 'a, E>(self, db: E) -> BoxFuture<'a, Result<Self::Model>>
fn insert<'e: 'a, E>(self, db: E) -> BoxFuture<'a, CoreResult<Self::Model>>
where
E: 'e + sqlx::Executor<'e, Database = DB>;

fn update<'e: 'a, E>(self, db: E) -> BoxFuture<'a, Result<Self::Model>>
fn update<'e: 'a, E>(self, db: E) -> BoxFuture<'a, CoreResult<Self::Model>>
where
E: 'e + sqlx::Executor<'e, Database = DB>;

Expand Down Expand Up @@ -77,16 +77,16 @@ where

/// `Model` objects can't track what fields are updated, so this method will update all fields.
/// If you want to update only some fields, use `update_partial` instead.
fn update_all_fields<'e, E>(self, db: E) -> BoxFuture<'e, Result<Self>>
fn update_all_fields<'e, E>(self, db: E) -> BoxFuture<'e, CoreResult<Self>>
where
E: 'e + Send + sqlx::Executor<'e, Database = DB>;

fn delete<'e, E>(self, db: E) -> BoxFuture<'e, Result<()>>
fn delete<'e, E>(self, db: E) -> BoxFuture<'e, CoreResult<()>>
where
E: 'e + sqlx::Executor<'e, Database = DB>;

/// Get by primary key.
fn fetch_one<'e, 'a, Arg, E>(id: Arg, db: E) -> BoxFuture<'e, Result<Self>>
fn fetch_one<'e, 'a, Arg, E>(id: Arg, db: E) -> BoxFuture<'e, CoreResult<Self>>
where
'a: 'e,
E: 'e + sqlx::Executor<'e, Database = DB>,
Expand Down
18 changes: 9 additions & 9 deletions core/src/query_builder/select.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::error::{Error, Result};
use crate::error::{CoreError, CoreResult};
use crate::model::Model;
use crate::query_builder::args::QueryBuilderArgs;
use crate::query_builder::{util, Placeholder};
Expand Down Expand Up @@ -55,7 +55,7 @@ where
DB: sqlx::Database + DatabaseMetadata,
DB::Arguments<'args>: IntoArguments<'args, DB>,
{
pub async fn fetch_all<'executor, E>(self, db: E) -> Result<Vec<M>>
pub async fn fetch_all<'executor, E>(self, db: E) -> CoreResult<Vec<M>>
where
E: Executor<'executor, Database = DB>,
{
Expand All @@ -64,10 +64,10 @@ where
util::query_as_with_recast_lifetime::<DB, M>(z, args)
.fetch_all(db)
.await
.map_err(Error::from)
.map_err(CoreError::from)
}

pub async fn fetch_one<'executor, E>(self, db: E) -> Result<M>
pub async fn fetch_one<'executor, E>(self, db: E) -> CoreResult<M>
where
E: Executor<'executor, Database = DB>,
{
Expand All @@ -76,10 +76,10 @@ where
util::query_as_with_recast_lifetime::<DB, M>(z, args)
.fetch_one(db)
.await
.map_err(Error::from)
.map_err(CoreError::from)
}

pub async fn fetch_optional<'executor, E>(self, db: E) -> Result<Option<M>>
pub async fn fetch_optional<'executor, E>(self, db: E) -> CoreResult<Option<M>>
where
E: Executor<'executor, Database = DB>,
{
Expand All @@ -88,7 +88,7 @@ where
util::query_as_with_recast_lifetime::<DB, M>(z, args)
.fetch_optional(db)
.await
.map_err(Error::from)
.map_err(CoreError::from)
}

pub fn with(mut self, name: &str, query: &str) -> Self {
Expand Down Expand Up @@ -208,12 +208,12 @@ where
self
}

pub fn into_query_and_args(mut self) -> Result<(String, QueryBuilderArgs<'args, DB>)> {
pub fn into_query_and_args(mut self) -> CoreResult<(String, QueryBuilderArgs<'args, DB>)> {
let q = self.query.to_sql(DB::dialect());
let args = self.arguments;
let (q, placeholder_count) = util::replace_placeholders(&q, &mut self.gen)?;
if placeholder_count != args.len() {
return Err(Error::OrmliteError(format!(
return Err(CoreError::OrmliteError(format!(
"Failing to build query. {} placeholders were found in the query, but \
{} arguments were provided.",
placeholder_count,
Expand Down
12 changes: 6 additions & 6 deletions core/src/query_builder/util.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::query_builder::args::QueryBuilderArgs;
use crate::{Error, Result};
use crate::{CoreError, CoreResult};
use sqlparser::dialect::GenericDialect;
use sqlparser::tokenizer::{Token, Tokenizer};
use sqlx::query::QueryAs;

pub fn replace_placeholders<T: Iterator<Item = String>>(
sql: &str,
placeholder_generator: &mut T,
) -> Result<(String, usize)> {
) -> CoreResult<(String, usize)> {
let mut placeholder_count = 0usize;
let dialect = GenericDialect {};
// note this lib is inefficient because it's copying strings everywhere, instead
Expand All @@ -33,7 +33,7 @@ pub fn replace_placeholders<T: Iterator<Item = String>>(
if let Some(next_tok) = next_tok {
match next_tok {
Token::Number(text, _) => {
let n = text.parse::<usize>().map_err(|_| Error::OrmliteError(
let n = text.parse::<usize>().map_err(|_| CoreError::OrmliteError(
format!("Failed to parse number after a $ during query tokenization. Value was: {text}"
)))?;
buf.push_str(&format!("${next_tok}"));
Expand Down Expand Up @@ -72,10 +72,10 @@ where
mod tests {
use super::*;

use crate::Result;
use crate::CoreResult;

#[test]
fn test_replace_placeholders() -> Result<()> {
fn test_replace_placeholders() -> CoreResult<()> {
let mut placeholder_generator = vec!["$1", "$2", "$3"].into_iter().map(|s| s.to_string());
let (sql, placeholder_count) = replace_placeholders(
"SELECT * FROM users WHERE id = ? OR id = ? OR id = ?",
Expand All @@ -87,7 +87,7 @@ mod tests {
}

#[test]
fn test_leave_placeholders_alone() -> Result<()> {
fn test_leave_placeholders_alone() -> CoreResult<()> {
let mut placeholder_generator = vec!["$1", "$2", "$3"].into_iter().map(|s| s.to_string());
let (sql, placeholder_count) =
replace_placeholders("SELECT * FROM users WHERE email = $1", &mut placeholder_generator)?;
Expand Down
4 changes: 2 additions & 2 deletions macro/src/codegen/from_row.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::codegen::common::{from_row_bounds, OrmliteCodegen};
use crate::MetadataCache;
use ormlite_attr::{ColumnMeta, Type};
use ormlite_attr::Ident;
use ormlite_attr::TableMeta;
use ormlite_attr::{ColumnMeta, Type};
use proc_macro2::TokenStream;
use quote::quote;

Expand Down Expand Up @@ -58,7 +58,7 @@ pub fn impl_FromRow(db: &dyn OrmliteCodegen, attr: &TableMeta, cache: &MetadataC
)*
_ => {
return Err(::ormlite::SqlxError::Decode(
Box::new(::ormlite::Error::OrmliteError(format!("Unknown column prefix: {}", prefix))),
Box::new(::ormlite::CoreError::OrmliteError(format!("Unknown column prefix: {}", prefix))),
));
}
}
Expand Down
12 changes: 6 additions & 6 deletions macro/src/codegen/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub fn impl_Model__insert(db: &dyn OrmliteCodegen, attr: &ModelMeta, metadata_ca
let mut stream = q.fetch(&mut *conn);
let mut model: Self = ::ormlite::__private::StreamExt::try_next(&mut stream)
.await?
.ok_or_else(|| ::ormlite::Error::from(::ormlite::SqlxError::RowNotFound))?;
.ok_or_else(|| ::ormlite::CoreError::from(::ormlite::SqlxError::RowNotFound))?;
::ormlite::__private::StreamExt::try_next(&mut stream).await?;
#(
#late_bind
Expand All @@ -86,7 +86,7 @@ pub fn impl_ModelBuilder__insert(db: &dyn OrmliteCodegen, attr: &TableMeta) -> T
let bind_parameters = attr.database_columns().map(generate_conditional_bind);

quote! {
fn insert<'e: 'a, E>(self, db: E) -> #box_future<'a, ::ormlite::Result<Self::Model>>
fn insert<'e: 'a, E>(self, db: E) -> #box_future<'a, ::ormlite::CoreResult<Self::Model>>
where
E: 'e +::ormlite::Executor<'e, Database = #db>,
{
Expand All @@ -104,7 +104,7 @@ pub fn impl_ModelBuilder__insert(db: &dyn OrmliteCodegen, attr: &TableMeta) -> T
let mut stream = q.fetch(db);
let model = ::ormlite::__private::StreamExt::try_next(&mut stream)
.await?
.ok_or_else(|| ::ormlite::Error::from(::ormlite::SqlxError::RowNotFound))?;
.ok_or_else(|| ::ormlite::CoreError::from(::ormlite::SqlxError::RowNotFound))?;
::ormlite::__private::StreamExt::try_next(&mut stream).await?;
Ok(model)
})
Expand Down Expand Up @@ -162,7 +162,7 @@ pub fn impl_Insert(db: &dyn OrmliteCodegen, meta: &TableMeta, model: &Ident, ret
impl ::ormlite::model::Insert<#db> for #model {
type Model = #returns;

fn insert<'a, A>(self, db: A) -> #box_future<'a, ::ormlite::Result<Self::Model>>
fn insert<'a, A>(self, db: A) -> #box_future<'a, ::ormlite::CoreResult<Self::Model>>
where
A: 'a + Send + ::ormlite::Acquire<'a, Database = #db>,
{
Expand All @@ -175,7 +175,7 @@ pub fn impl_Insert(db: &dyn OrmliteCodegen, meta: &TableMeta, model: &Ident, ret
let mut stream = q.fetch(&mut *conn);
let mut model = ::ormlite::__private::StreamExt::try_next(&mut stream)
.await?
.ok_or_else(|| ::ormlite::Error::from(::ormlite::SqlxError::RowNotFound))?;
.ok_or_else(|| ::ormlite::CoreError::from(::ormlite::SqlxError::RowNotFound))?;
::ormlite::__private::StreamExt::try_next(&mut stream).await?;
#(#late_bind)*
Ok(model)
Expand Down Expand Up @@ -217,7 +217,7 @@ pub fn insert_join(c: &ColumnMeta) -> TokenStream {
.on_conflict(::ormlite::query_builder::OnConflict::Ignore)
.await {
Ok(model) => Join::_query_result(model),
Err(::ormlite::Error::SqlxError(::ormlite::SqlxError::RowNotFound)) => {
Err(::ormlite::CoreError::SqlxError(::ormlite::SqlxError::RowNotFound)) => {
let preexisting = #preexisting;
Join::_query_result(preexisting)
},
Expand Down
Loading

0 comments on commit b01ae44

Please sign in to comment.