├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── example ├── .env ├── Cargo.toml ├── README.md ├── diesel.toml ├── migrations │ ├── .gitkeep │ └── 2018-12-28-070340_add_users │ │ ├── down.sql │ │ └── up.sql └── src │ ├── main.rs │ ├── routes.rs │ └── schema.rs ├── rust-toolchain ├── rustfmt.toml └── src ├── builder.rs ├── db.rs ├── dsl.rs ├── error.rs ├── executor.rs └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | *.sqlite 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "actix-diesel" 3 | description = "Integrate Diesel into Actix (and Actix Web) cleanly and efficiently." 4 | repository = "https://github.com/mehcode/actix-diesel" 5 | license = "MIT/Apache-2.0" 6 | version = "0.3.1-alpha.0" 7 | keywords = ["web", "actix", "async", "diesel", "database"] 8 | categories = ["asynchronous", "web-programming::http-server", "database"] 9 | readme = "README.md" 10 | authors = ["Ryan Leckey "] 11 | edition = "2018" 12 | 13 | [dependencies] 14 | diesel = { version = "1.4.1", features = [ "r2d2" ] } 15 | actix = "0.7.9" 16 | num_cpus = "1.9.0" 17 | once_cell = "0.1.7" 18 | futures = "0.1.25" 19 | derive_more = "0.13.0" 20 | r2d2 = "0.8.3" 21 | actix-web = { version = "0.7.18", optional = true } 22 | failure = { version = "0.1.5", optional = true } 23 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Ryan Leckey 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Ryan Leckey 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Actix Diesel 2 | > Integrate Diesel into Actix (and Actix Web) cleanly and efficiently. 3 | 4 | This crate allows for a simple async interface to `diesel` powered by `actix`. It's main goal is to provide 5 | `actix-web` users an elegant interface to `diesel` however it can be used without the web portions. 6 | 7 | ## Usage 8 | 9 | See [the example](./example) for detailed usage information. 10 | 11 | ```rust 12 | async fn index(state: State) -> Result> { 13 | Ok(await!(users::table.load_async(&state.db))?) 14 | } 15 | ``` 16 | 17 | ## License 18 | 19 | Licensed under either of 20 | 21 | * Apache License, Version 2.0 22 | ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 23 | * MIT license 24 | ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 25 | 26 | at your option. 27 | 28 | ## Contribution 29 | 30 | Unless you explicitly state otherwise, any contribution intentionally submitted 31 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 32 | dual licensed as above, without any additional terms or conditions. 33 | -------------------------------------------------------------------------------- /example/.env: -------------------------------------------------------------------------------- 1 | DATABASE_URL=file:example.sqlite 2 | RUST_LOG=warn,actix=warn,actix_web=info,actix_net::server::server=info 3 | -------------------------------------------------------------------------------- /example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "example" 3 | version = "0.1.1" 4 | authors = ["Ryan Leckey "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | diesel = { version = "1.4.1", features = [ "sqlite" ] } 9 | actix-web = "0.7.18" 10 | actix-diesel = { path = "..", features = [ "actix-web" ] } 11 | pretty_env_logger = "0.3.0" 12 | failure = "0.1.5" 13 | actix-web-async-await = "0.2.0" 14 | serde = { version = "1.0.85", features = [ "derive" ] } 15 | dotenv = "0.13.0" 16 | futures = "0.1" 17 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Actix / Diesel Example 2 | 3 | ## Building 4 | 5 | > This build uses a [frozen version](../rust-toolchain) of the `nightly` toolchain. 6 | 7 | ``` 8 | cargo build 9 | cargo install diesel_cli --no-default-features --features sqlite 10 | diesel migration run 11 | ``` 12 | 13 | ## Running 14 | 15 | ``` 16 | cargo run 17 | ``` 18 | 19 | `POST` to the service to write a record to the DB. 20 | 21 | ``` 22 | curl +X POST 127.0.0.1:8080/foo 23 | ``` 24 | -------------------------------------------------------------------------------- /example/diesel.toml: -------------------------------------------------------------------------------- 1 | [print_schema] 2 | file = "src/schema.rs" 3 | -------------------------------------------------------------------------------- /example/migrations/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mehcode/actix-diesel/e17db6430964702d217015048ab7000a1f97d36b/example/migrations/.gitkeep -------------------------------------------------------------------------------- /example/migrations/2018-12-28-070340_add_users/down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE users; 2 | -------------------------------------------------------------------------------- /example/migrations/2018-12-28-070340_add_users/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE users ( 2 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 3 | name TEXT NOT NULL 4 | ); 5 | -------------------------------------------------------------------------------- /example/src/main.rs: -------------------------------------------------------------------------------- 1 | #![feature(async_await, await_macro, futures_api)] 2 | #![allow(proc_macro_derive_resolution_fallback)] 3 | 4 | #[macro_use] 5 | extern crate diesel; 6 | 7 | use actix_diesel::Database; 8 | use actix_web::{http::Method, middleware, server, App}; 9 | use actix_web_async_await::{compat, compat2}; 10 | use diesel::sqlite::SqliteConnection; 11 | use failure::Error; 12 | use std::time::Duration; 13 | 14 | mod routes; 15 | mod schema; 16 | 17 | use self::routes::*; 18 | 19 | pub struct AppState { 20 | db: Database, 21 | } 22 | 23 | fn main() -> Result<(), Error> { 24 | dotenv::dotenv()?; 25 | pretty_env_logger::try_init_timed()?; 26 | 27 | let db = Database::builder() 28 | // Maximum number of connections managed by the pool (default: 10) 29 | .pool_max_size(10) 30 | // Minimum idle connection count maintained by the pool (default: None {max_size}) 31 | .pool_min_idle(Some(0)) 32 | // Maximum lifetime of connections in the pool (default: 30 minutes) 33 | .pool_max_lifetime(Some(Duration::from_secs(30 * 60))) 34 | .open("file:example.sqlite"); 35 | 36 | server::new(move || { 37 | App::with_state(AppState { db: db.clone() }) 38 | .middleware(middleware::Logger::default()) 39 | .route("/", Method::GET, compat(fetch_all)) 40 | .route("/{name}", Method::GET, compat2(fetch_one)) 41 | .route("/{name}", Method::POST, compat2(create)) 42 | }) 43 | .bind("127.0.0.1:8080")? 44 | .run(); 45 | 46 | Ok(()) 47 | } 48 | -------------------------------------------------------------------------------- /example/src/routes.rs: -------------------------------------------------------------------------------- 1 | use crate::{schema::users, AppState}; 2 | use actix_diesel::{dsl::AsyncRunQueryDsl, AsyncError}; 3 | use actix_web::{ 4 | error::{ErrorInternalServerError, ErrorNotFound}, 5 | HttpResponse, Json, Path, Responder, Result, State, 6 | }; 7 | use actix_web_async_await::await; 8 | use diesel::{prelude::*, result::Error}; 9 | use futures::future::Future; 10 | use serde::Serialize; 11 | 12 | #[derive(Serialize, Queryable)] 13 | struct User { 14 | id: i32, 15 | name: String, 16 | } 17 | 18 | pub async fn fetch_all(state: State) -> Result { 19 | let results = await!(users::table.load_async::(&state.db))?; 20 | 21 | Ok(Json(results)) 22 | } 23 | 24 | pub async fn fetch_one(state: State, name: Path) -> Result { 25 | let result = await!(users::table 26 | .filter(users::name.eq(name.into_inner())) 27 | .get_result_async::(&state.db) 28 | .map_err(|err| match err { 29 | AsyncError::Execute(Error::NotFound) => ErrorNotFound(err), 30 | _ => ErrorInternalServerError(err), 31 | }))?; 32 | 33 | Ok(Json(result)) 34 | } 35 | 36 | #[derive(Insertable)] 37 | #[table_name = "users"] 38 | struct CreateUser { 39 | name: String, 40 | } 41 | 42 | pub async fn create(state: State, name: Path) -> Result { 43 | await!(diesel::insert_into(users::table) 44 | .values(CreateUser { 45 | name: name.into_inner() 46 | }) 47 | .execute_async(&state.db))?; 48 | 49 | Ok(HttpResponse::Created()) 50 | } 51 | -------------------------------------------------------------------------------- /example/src/schema.rs: -------------------------------------------------------------------------------- 1 | table! { 2 | users (id) { 3 | id -> Integer, 4 | name -> Text, 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly-2019-02-13 -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2018" 2 | unstable_features = true 3 | required_version = "1.0.1" 4 | version = "Two" 5 | merge_imports = true 6 | -------------------------------------------------------------------------------- /src/builder.rs: -------------------------------------------------------------------------------- 1 | use crate::{executor::Executor, Database}; 2 | use actix::SyncArbiter; 3 | use diesel::{ 4 | r2d2::{ConnectionManager, CustomizeConnection, Error as R2D2Error, Pool}, 5 | Connection, 6 | }; 7 | use once_cell::sync::OnceCell; 8 | use std::{ 9 | fmt::{self, Debug}, 10 | marker::PhantomData, 11 | sync::Arc, 12 | time::Duration, 13 | }; 14 | 15 | pub struct Builder 16 | where 17 | C: Connection, 18 | { 19 | pub(crate) phantom: PhantomData, 20 | pub(crate) pool_max_size: Option, 21 | pub(crate) pool_min_idle: Option>, 22 | pub(crate) pool_max_lifetime: Option>, 23 | pub(crate) on_acquire: Option Result<(), R2D2Error> + Send + Sync>>, 24 | pub(crate) on_release: Option>, 25 | } 26 | 27 | impl Builder 28 | where 29 | C: Connection, 30 | { 31 | #[inline] 32 | pub fn pool_max_size(&mut self, max_size: u32) -> &mut Self { 33 | self.pool_max_size = Some(max_size); 34 | self 35 | } 36 | 37 | #[inline] 38 | pub fn pool_min_idle(&mut self, min_idle: Option) -> &mut Self { 39 | self.pool_min_idle = Some(min_idle); 40 | self 41 | } 42 | 43 | #[inline] 44 | pub fn pool_max_lifetime(&mut self, max_lifetime: Option) -> &mut Self { 45 | self.pool_max_lifetime = Some(max_lifetime); 46 | self 47 | } 48 | 49 | #[inline] 50 | pub fn on_acquire( 51 | &mut self, 52 | on_acquire: impl Fn(&mut C) -> Result<(), R2D2Error> + 'static + Send + Sync, 53 | ) -> &mut Self { 54 | self.on_acquire = Some(Box::new(on_acquire)); 55 | self 56 | } 57 | 58 | #[inline] 59 | pub fn on_release(&mut self, on_release: impl Fn(C) + 'static + Send + Sync) -> &mut Self { 60 | self.on_release = Some(Box::new(on_release)); 61 | self 62 | } 63 | 64 | pub fn open(&mut self, url: impl Into) -> Database { 65 | let manager = ConnectionManager::::new(url); 66 | let mut p = Pool::builder(); 67 | 68 | if let Some(max_size) = self.pool_max_size { 69 | p = p.max_size(max_size); 70 | } 71 | 72 | if let Some(min_idle) = self.pool_min_idle { 73 | p = p.min_idle(min_idle); 74 | } 75 | 76 | if let Some(max_lifetime) = self.pool_max_lifetime { 77 | p = p.max_lifetime(max_lifetime); 78 | } 79 | 80 | if self.on_acquire.is_some() || self.on_release.is_some() { 81 | p = p.connection_customizer(Box::new(FnConnectionCustomizer { 82 | on_acquire: self.on_acquire.take(), 83 | on_release: self.on_release.take(), 84 | })); 85 | } 86 | 87 | let pool = p.build_unchecked(manager); 88 | 89 | Database { 90 | pool, 91 | cell: Arc::new(OnceCell::new()), 92 | init: |pool| SyncArbiter::start(num_cpus::get(), move || Executor(pool.clone())), 93 | } 94 | } 95 | } 96 | 97 | struct FnConnectionCustomizer { 98 | on_acquire: Option Result<(), R2D2Error> + Send + Sync>>, 99 | on_release: Option>, 100 | } 101 | 102 | impl Debug for FnConnectionCustomizer { 103 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 104 | f.write_str("FnConnectionCustomizer") 105 | } 106 | } 107 | 108 | impl CustomizeConnection for FnConnectionCustomizer { 109 | #[inline] 110 | fn on_acquire(&self, conn: &mut C) -> Result<(), R2D2Error> { 111 | if let Some(on_acquire) = &self.on_acquire { 112 | (on_acquire)(conn) 113 | } else { 114 | Ok(()) 115 | } 116 | } 117 | 118 | #[inline] 119 | fn on_release(&self, conn: C) { 120 | if let Some(on_release) = &self.on_release { 121 | (on_release)(conn) 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/db.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | executor::{Execute, Executor}, 3 | AsyncError, Builder, 4 | }; 5 | use actix::Addr; 6 | use diesel::{ 7 | r2d2::{ConnectionManager, Pool}, 8 | Connection, 9 | }; 10 | use futures::Future; 11 | use once_cell::sync::OnceCell; 12 | use std::{fmt::Debug, marker::PhantomData, sync::Arc}; 13 | 14 | pub struct Database 15 | where 16 | C: Connection, 17 | { 18 | pub(crate) cell: Arc>>>, 19 | pub(crate) pool: Pool>, 20 | pub(crate) init: fn(Pool>) -> Addr>, 21 | } 22 | 23 | impl Clone for Database 24 | where 25 | C: Connection, 26 | { 27 | fn clone(&self) -> Self { 28 | Database { 29 | cell: self.cell.clone(), 30 | init: self.init.clone(), 31 | pool: self.pool.clone(), 32 | } 33 | } 34 | } 35 | 36 | impl Database 37 | where 38 | C: Connection, 39 | { 40 | #[inline] 41 | pub fn open(url: impl Into) -> Database { 42 | Self::builder().open(url) 43 | } 44 | 45 | #[inline] 46 | pub fn builder() -> Builder { 47 | Builder { 48 | phantom: PhantomData, 49 | pool_max_size: None, 50 | pool_min_idle: None, 51 | pool_max_lifetime: None, 52 | on_acquire: None, 53 | on_release: None, 54 | } 55 | } 56 | 57 | /// Executes the given function inside a database transaction. 58 | #[inline] 59 | pub fn transaction(&self, f: F) -> impl Future> 60 | where 61 | F: 'static + FnOnce(&C) -> Result + Send, 62 | R: 'static + Send, 63 | E: 'static + From + Debug + Send + Sync, 64 | { 65 | self.get(move |conn| conn.transaction(move || f(conn))) 66 | } 67 | 68 | /// Executes the given function with a connection retrieved from the pool. 69 | /// 70 | /// This is non-blocking and uses a `SyncArbiter` to provide a thread pool. 71 | pub fn get(&self, f: F) -> impl Future> 72 | where 73 | F: 'static + FnOnce(&C) -> Result + Send, 74 | R: 'static + Send, 75 | E: 'static + Debug + Send + Sync, 76 | { 77 | self.cell 78 | .get_or_init(|| (self.init)(self.pool.clone())) 79 | .send(Execute(f, PhantomData)) 80 | .then(|res| -> Result> { 81 | match res { 82 | Ok(res) => match res { 83 | Ok(res) => match res { 84 | Ok(value) => Ok(value), 85 | Err(err) => Err(AsyncError::Execute(err)), 86 | }, 87 | 88 | Err(err) => Err(AsyncError::Timeout(err)), 89 | }, 90 | 91 | Err(err) => Err(AsyncError::Delivery(err)), 92 | } 93 | }) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/dsl.rs: -------------------------------------------------------------------------------- 1 | use crate::{AsyncError, Database}; 2 | use diesel::{ 3 | dsl::Limit, 4 | query_dsl::{limit_dsl::LimitDsl, load_dsl::ExecuteDsl, LoadQuery}, 5 | result::{Error, OptionalExtension}, 6 | Connection, RunQueryDsl, 7 | }; 8 | use futures::Future; 9 | 10 | pub trait AsyncRunQueryDsl: RunQueryDsl 11 | where 12 | Conn: Connection, 13 | { 14 | fn execute_async( 15 | self, 16 | db: &Database, 17 | ) -> Box>> 18 | where 19 | Conn: Connection, 20 | Self: ExecuteDsl; 21 | 22 | fn load_async( 23 | self, 24 | db: &Database, 25 | ) -> Box, Error = AsyncError>> 26 | where 27 | U: Send, 28 | Self: LoadQuery; 29 | 30 | fn get_result_async( 31 | self, 32 | db: &Database, 33 | ) -> Box>> 34 | where 35 | U: Send, 36 | Self: LoadQuery; 37 | 38 | fn get_optional_result_async( 39 | self, 40 | db: &Database, 41 | ) -> Box, Error = AsyncError>> 42 | where 43 | U: Send, 44 | Self: LoadQuery; 45 | 46 | fn get_results_async( 47 | self, 48 | db: &Database, 49 | ) -> Box, Error = AsyncError>> 50 | where 51 | U: Send, 52 | Self: LoadQuery; 53 | 54 | fn first_async( 55 | self, 56 | db: &Database, 57 | ) -> Box>> 58 | where 59 | U: Send, 60 | Self: LimitDsl, 61 | Limit: LoadQuery; 62 | } 63 | 64 | impl AsyncRunQueryDsl for T 65 | where 66 | T: RunQueryDsl + Send, 67 | Conn: Connection, 68 | { 69 | #[inline] 70 | fn execute_async( 71 | self, 72 | db: &Database, 73 | ) -> Box>> 74 | where 75 | Conn: Connection, 76 | Self: ExecuteDsl, 77 | { 78 | Box::new(db.get(move |conn| self.execute(conn))) 79 | } 80 | 81 | #[inline] 82 | fn load_async( 83 | self, 84 | db: &Database, 85 | ) -> Box, Error = AsyncError>> 86 | where 87 | U: Send, 88 | Self: LoadQuery, 89 | { 90 | Box::new(db.get(move |conn| self.load(conn))) 91 | } 92 | 93 | #[inline] 94 | fn get_results_async( 95 | self, 96 | db: &Database, 97 | ) -> Box, Error = AsyncError>> 98 | where 99 | U: Send, 100 | Self: LoadQuery, 101 | { 102 | Box::new(db.get(move |conn| self.get_results(conn))) 103 | } 104 | 105 | #[inline] 106 | fn get_result_async( 107 | self, 108 | db: &Database, 109 | ) -> Box>> 110 | where 111 | U: Send, 112 | Self: LoadQuery, 113 | { 114 | Box::new(db.get(move |conn| self.get_result(conn))) 115 | } 116 | 117 | #[inline] 118 | fn get_optional_result_async( 119 | self, 120 | db: &Database, 121 | ) -> Box, Error = AsyncError>> 122 | where 123 | U: Send, 124 | Self: LoadQuery, 125 | { 126 | Box::new(db.get(move |conn| self.get_result(conn).optional())) 127 | } 128 | 129 | #[inline] 130 | fn first_async( 131 | self, 132 | db: &Database, 133 | ) -> Box>> 134 | where 135 | U: Send, 136 | Self: LimitDsl, 137 | Limit: LoadQuery, 138 | { 139 | Box::new(db.get(move |conn| self.first(conn))) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use derive_more::Display; 2 | use std::{error::Error as StdError, fmt::Debug}; 3 | 4 | #[derive(Debug, Display)] 5 | pub enum AsyncError 6 | where 7 | E: 'static + Debug + Send + Sync, 8 | { 9 | // Error occured when attempting to deliver the query to the Database actor 10 | #[display(fmt = "{}", _0)] 11 | Delivery(actix::MailboxError), 12 | 13 | // Timed out trying to checkout a connection 14 | #[display(fmt = "{}", _0)] 15 | Timeout(r2d2::Error), 16 | 17 | // An error occurred when interacting with the database 18 | #[display(fmt = "{:?}", _0)] 19 | Execute(E), 20 | } 21 | 22 | impl StdError for AsyncError where E: 'static + Debug + Send + Sync {} 23 | 24 | #[cfg(feature = "actix-web")] 25 | impl actix_web::ResponseError for AsyncError where E: 'static + Debug + Send + Sync {} 26 | 27 | #[cfg(feature = "failure")] 28 | impl AsyncError { 29 | /// Attempts to downcast this Error to a particular Fail type. 30 | #[inline] 31 | pub fn downcast(self) -> Result { 32 | match self { 33 | AsyncError::Execute(err) => err.downcast().map_err(AsyncError::Execute), 34 | err => Err(err), 35 | } 36 | } 37 | 38 | /// Attempts to downcast this Error to a particular Fail type by reference. 39 | #[inline] 40 | pub fn downcast_ref(&self) -> Option<&T> { 41 | match self { 42 | AsyncError::Execute(err) => err.downcast_ref(), 43 | _ => None, 44 | } 45 | } 46 | 47 | /// Attempts to downcast this Error to a particular Fail type by mutable reference. 48 | #[inline] 49 | pub fn downcast_mut(&mut self) -> Option<&mut T> { 50 | match self { 51 | AsyncError::Execute(err) => err.downcast_mut(), 52 | _ => None, 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/executor.rs: -------------------------------------------------------------------------------- 1 | use actix::{Actor, Handler, Message, SyncContext}; 2 | use diesel::{ 3 | r2d2::{ConnectionManager, Pool}, 4 | Connection, 5 | }; 6 | use std::{fmt::Debug, marker::PhantomData}; 7 | 8 | #[derive(Debug)] 9 | pub(crate) struct Executor(pub(crate) Pool>) 10 | where 11 | C: Connection; 12 | 13 | impl Actor for Executor 14 | where 15 | C: Connection, 16 | { 17 | type Context = SyncContext; 18 | } 19 | 20 | pub(crate) struct Execute(pub(crate) F, pub(crate) PhantomData<(C, R)>) 21 | where 22 | R: 'static + Send, 23 | E: 'static + Debug + Send + Sync, 24 | C: Connection, 25 | F: FnOnce(&C) -> Result; 26 | 27 | impl Message for Execute 28 | where 29 | R: Send, 30 | E: Debug + Send + Sync, 31 | C: Connection, 32 | F: FnOnce(&C) -> Result, 33 | { 34 | type Result = Result, r2d2::Error>; 35 | } 36 | 37 | impl Handler> for Executor 38 | where 39 | R: Send, 40 | E: Debug + Send + Sync, 41 | C: Connection, 42 | F: FnOnce(&C) -> Result, 43 | { 44 | type Result = Result, r2d2::Error>; 45 | 46 | fn handle(&mut self, msg: Execute, _: &mut Self::Context) -> Self::Result { 47 | let conn = match self.0.get() { 48 | Ok(conn) => conn, 49 | Err(err) => return Err(err), 50 | }; 51 | 52 | Ok((msg.0)(&*conn)) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod builder; 2 | mod db; 3 | pub mod dsl; 4 | mod error; 5 | mod executor; 6 | 7 | pub use self::{builder::Builder, db::Database, error::AsyncError, error::AsyncError as Error}; 8 | --------------------------------------------------------------------------------