Switch to sqlx

While diesel has a native rust interface, writing more complex queries
is easier when you can just pass a SQL query string.
This commit is contained in:
Simon Bruder 2024-07-11 17:25:01 +02:00
parent b0f542077d
commit 00d7647187
Signed by: simon
GPG key ID: 347FF8699CDA0776
46 changed files with 1329 additions and 812 deletions

2
.envrc
View file

@ -3,3 +3,5 @@
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-License-Identifier: AGPL-3.0-or-later
use flake use flake
export SQLX_OFFLINE=true

View file

@ -3,8 +3,6 @@ Upstream-Name: i7y
Upstream-Contact: Simon Bruder <simon@sbruder.de> Upstream-Contact: Simon Bruder <simon@sbruder.de>
Source: Source:
# Sample paragraph, commented out: Files: .sqlx/query-*.json
# Copyright: 2024 Simon Bruder <simon@sbruder.de>
# Files: src/* License: AGPL-3.0-or-later
# Copyright: $YEAR $NAME <$CONTACT>
# License: ...

View file

@ -0,0 +1,42 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO items (name, parent, class) VALUES ($1, $2, $3) RETURNING *",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "class",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Varchar",
"Uuid",
"Uuid"
]
},
"nullable": [
false,
true,
true,
false
]
},
"hash": "05452db872d5ae8574a979b07d19c2b0791f3f2c4c0ae4777b2a2c309410d0ec"
}

View file

@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM items WHERE id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": []
},
"hash": "08cce122c8eb9b390e5411cc08d2e735de7230a596fa2f2ba472bed6a9b4a75c"
}

View file

@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM items WHERE id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "class",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
true,
true,
false
]
},
"hash": "1e9045f52c002a19b815351fee1c7ee7520478ff4f5886b4523fb0dc4df0e204"
}

View file

@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM items WHERE parent = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "class",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
true,
true,
false
]
},
"hash": "2e9619ce6db1047e2f5447c4925f28fd05f18706f70220b6ebb7354d2a0a9e3b"
}

View file

@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM item_classes WHERE id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
false,
true
]
},
"hash": "308962c26250f9312287a3f2f21e5da76e4cf488eedd4704019b4f14b6fbafb2"
}

View file

@ -0,0 +1,36 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE item_classes SET name = $2, parent = $3 WHERE id = $1 RETURNING *",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Varchar",
"Uuid"
]
},
"nullable": [
false,
false,
true
]
},
"hash": "408a171b46d5c615ff846547f463dc0b18360644234fb01b24c4c047bebb3a10"
}

View file

@ -0,0 +1,38 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM items",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "class",
"type_info": "Uuid"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
true,
false
]
},
"hash": "467dcd7fd379750cbf30a190d06dc1b3e61b1bd7ef288fbf6fbedec52c276434"
}

View file

@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM item_classes WHERE id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": []
},
"hash": "7a811ef54e617ed88ef9c7be88b48ca0da2204c64200ffa77a51f0c580f9ab87"
}

View file

@ -0,0 +1,35 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO item_classes (name, parent) VALUES ($1, $2) RETURNING *",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Varchar",
"Uuid"
]
},
"nullable": [
false,
false,
true
]
},
"hash": "7e2e1460a2c946ba909c50d4cf1beacf50ebf5fbfead379340f9f72614958e78"
}

View file

@ -0,0 +1,43 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE items SET name = $2, parent = $3, class = $4 WHERE id = $1 RETURNING *",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "class",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Varchar",
"Uuid",
"Uuid"
]
},
"nullable": [
false,
true,
true,
false
]
},
"hash": "85528d16361a6e736773e8f8aba4c85cfc7db545724d94c1a467b2c0c74b6b6e"
}

View file

@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM items WHERE class = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "class",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
true,
true,
false
]
},
"hash": "94958a3a57c3178e6b0de5723b1fbc5433e972b5522b367098afe6cb90a30bf2"
}

View file

@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT unnest(parents) as \"parents!\" FROM item_tree WHERE id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "parents!",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
null
]
},
"hash": "97d6a7ee24e75dc5a9dc41a581e1013767fe36575c28574733c5ab5cbf557fb5"
}

View file

@ -0,0 +1,26 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id as \"id!\", parents as \"parents!\" FROM item_tree",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id!",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "parents!",
"type_info": "UuidArray"
}
],
"parameters": {
"Left": []
},
"nullable": [
true,
true
]
},
"hash": "a6f646089b4424deffc0b1a454bcfa2f2a497180e2517a937471f81a1f9c5538"
}

View file

@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM item_classes WHERE parent = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
false,
true
]
},
"hash": "c552c0a40bc8995cb95726a85f1d0c0b86eb2322035e6a720e2e6d425072a8c1"
}

View file

@ -0,0 +1,32 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM item_classes",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
false,
true
]
},
"hash": "dc197bce5f03ab1ab08391f54f960e63e935172b25e5a6835d51e786fb2f854e"
}

View file

@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM items WHERE id = ANY (SELECT unnest(parents) FROM item_tree WHERE id = $1)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "parent",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "class",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
true,
true,
false
]
},
"hash": "e45160a73a18d870f592989349057d6852d2d3f63dc055442125a6a92950729d"
}

940
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -14,10 +14,6 @@ actix-files = "0.6.6"
actix-web = "4.8.0" actix-web = "4.8.0"
barcoders = { version = "2.0.0", default-features = false, features = ["std"] } barcoders = { version = "2.0.0", default-features = false, features = ["std"] }
datamatrix = "0.3.1" datamatrix = "0.3.1"
diesel = { version = "2.2.1", features = ["uuid"] }
diesel-async = { git = "https://github.com/weiznich/diesel_async.git", version = "0.4.1", features = ["postgres", "deadpool", "async-connection-wrapper"] }
diesel-derive-enum = { version = "2.1.0", features = ["postgres"] }
diesel_migrations = { version = "2.2.0", features = ["postgres"] }
env_logger = "0.11.3" env_logger = "0.11.3"
log = "0.4.21" log = "0.4.21"
maud = { version = "0.26.0", features = ["actix-web"] } maud = { version = "0.26.0", features = ["actix-web"] }
@ -25,5 +21,9 @@ mime = "0.3.17"
printpdf = "0.7.0" printpdf = "0.7.0"
rust-fontconfig = "0.1.7" rust-fontconfig = "0.1.7"
serde = { version = "1.0.203", features = ["serde_derive"] } serde = { version = "1.0.203", features = ["serde_derive"] }
sqlx = { version = "0.7.4", features = ["runtime-tokio", "postgres", "uuid"] }
thiserror = "1.0.61" thiserror = "1.0.61"
uuid = { version = "1.9.0", features = ["serde", "v4"] } uuid = { version = "1.9.0", features = ["serde", "v4"] }
[profile.dev.package.sqlx-macros]
opt-level = 3

View file

@ -1,73 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,12 +0,0 @@
# SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli
[print_schema]
custom_type_derives = ["diesel::query_builder::QueryId"]
[migrations_directory]
dir = "migrations"

View file

@ -91,10 +91,10 @@
cargo-deny cargo-deny
cargo-watch cargo-watch
clippy clippy
diesel-cli
postgresql.lib postgresql.lib
postgresql postgresql
reuse reuse
sqlx-cli
]); ]);
shellHook = '' shellHook = ''

View file

View file

@ -1,10 +0,0 @@
-- SPDX-FileCopyrightText: 2017 Sage Griffin <sage@sagetheprogrammer.com>
--
-- SPDX-License-Identifier: Apache-2.0 OR MIT
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();

View file

@ -1,41 +0,0 @@
-- SPDX-FileCopyrightText: 2017 Sage Griffin <sage@sagetheprogrammer.com>
-- SPDX-FileCopyrightText: 2016 Robert Maloney <robertjamesmaloney@gmail.com>
--
-- SPDX-License-Identifier: Apache-2.0 OR MIT
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

View file

@ -3,11 +3,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
use actix_web::{delete, error, get, post, put, web, HttpResponse, Responder}; use actix_web::{delete, error, get, post, put, web, HttpResponse, Responder};
use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
use crate::manage; use crate::manage;
use crate::models::*; use crate::models::*;
use crate::DbPool;
pub fn config(cfg: &mut web::ServiceConfig) { pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(add) cfg.service(add)
@ -20,15 +20,10 @@ pub fn config(cfg: &mut web::ServiceConfig) {
#[put("/item")] #[put("/item")]
async fn add( async fn add(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
new_item: web::Json<NewItem>, new_item: web::Json<NewItem>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
// TODO: Failure to get a connection from the pool should not panic. let item = manage::item::add(&pool, new_item.into_inner())
// Instead, a Result::Err variant should be returned, which then gets turned into an ISE.
// This is not easily possible as getting a connection from a pool returns an r2d2 error
// type, while the databse action returns a diesel error type, which are incompatible.
// This also affects other functions below.
let item = manage::item::add(&mut pool.get().await.unwrap(), new_item.into_inner())
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -36,8 +31,8 @@ async fn add(
} }
#[get("/item")] #[get("/item")]
async fn list(pool: web::Data<DbPool>) -> actix_web::Result<impl Responder> { async fn list(pool: web::Data<PgPool>) -> actix_web::Result<impl Responder> {
let items = manage::item::get_all(&mut pool.get().await.unwrap()) let items = manage::item::get_all(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -45,10 +40,10 @@ async fn list(pool: web::Data<DbPool>) -> actix_web::Result<impl Responder> {
} }
#[get("/item/{id}")] #[get("/item/{id}")]
async fn show(pool: web::Data<DbPool>, path: web::Path<Uuid>) -> actix_web::Result<impl Responder> { async fn show(pool: web::Data<PgPool>, path: web::Path<Uuid>) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item = manage::item::get(&mut pool.get().await.unwrap(), id) let item = manage::item::get(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -57,13 +52,13 @@ async fn show(pool: web::Data<DbPool>, path: web::Path<Uuid>) -> actix_web::Resu
#[post("/item/{id}")] #[post("/item/{id}")]
async fn update( async fn update(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
new_item: web::Json<NewItem>, new_item: web::Json<NewItem>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item = manage::item::update(&mut pool.get().await.unwrap(), id, new_item.into_inner()) let item = manage::item::update(&pool, id, new_item.into_inner())
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -72,12 +67,12 @@ async fn update(
#[delete("/item/{id}")] #[delete("/item/{id}")]
async fn delete( async fn delete(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
manage::item::delete(&mut pool.get().await.unwrap(), id) manage::item::delete(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -86,12 +81,12 @@ async fn delete(
#[get("/item/{id}/parents")] #[get("/item/{id}/parents")]
async fn parents( async fn parents(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let parents = manage::item::get_parents(&mut pool.get().await.unwrap(), id) let parents = manage::item::get_parents(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;

View file

@ -3,11 +3,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
use actix_web::{delete, error, get, post, put, web, HttpResponse, Responder}; use actix_web::{delete, error, get, post, put, web, HttpResponse, Responder};
use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
use crate::manage; use crate::manage;
use crate::models::*; use crate::models::*;
use crate::DbPool;
pub fn config(cfg: &mut web::ServiceConfig) { pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(add) cfg.service(add)
@ -20,20 +20,19 @@ pub fn config(cfg: &mut web::ServiceConfig) {
#[put("/item-class")] #[put("/item-class")]
async fn add( async fn add(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
new_item_class: web::Json<NewItemClass>, new_item_class: web::Json<NewItemClass>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let item_class = let item_class = manage::item_class::add(&pool, new_item_class.into_inner())
manage::item_class::add(&mut pool.get().await.unwrap(), new_item_class.into_inner()) .await
.await .map_err(error::ErrorInternalServerError)?;
.map_err(error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(item_class)) Ok(HttpResponse::Ok().json(item_class))
} }
#[get("/item-class")] #[get("/item-class")]
async fn list(pool: web::Data<DbPool>) -> actix_web::Result<impl Responder> { async fn list(pool: web::Data<PgPool>) -> actix_web::Result<impl Responder> {
let item_classes = manage::item_class::get_all(&mut pool.get().await.unwrap()) let item_classes = manage::item_class::get_all(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -41,10 +40,10 @@ async fn list(pool: web::Data<DbPool>) -> actix_web::Result<impl Responder> {
} }
#[get("/item-class/{id}")] #[get("/item-class/{id}")]
async fn show(pool: web::Data<DbPool>, path: web::Path<Uuid>) -> actix_web::Result<impl Responder> { async fn show(pool: web::Data<PgPool>, path: web::Path<Uuid>) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item_class = manage::item_class::get(&mut pool.get().await.unwrap(), id) let item_class = manage::item_class::get(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -53,12 +52,12 @@ async fn show(pool: web::Data<DbPool>, path: web::Path<Uuid>) -> actix_web::Resu
#[get("/item-class/{id}/items")] #[get("/item-class/{id}/items")]
async fn items( async fn items(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let items = manage::item_class::items(&mut pool.get().await.unwrap(), id) let items = manage::item_class::items(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -67,31 +66,27 @@ async fn items(
#[post("/item-class/{id}")] #[post("/item-class/{id}")]
async fn update( async fn update(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
new_item_class: web::Json<NewItemClass>, new_item_class: web::Json<NewItemClass>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item_class = manage::item_class::update( let item_class = manage::item_class::update(&pool, id, new_item_class.into_inner())
&mut pool.get().await.unwrap(), .await
id, .map_err(error::ErrorInternalServerError)?;
new_item_class.into_inner(),
)
.await
.map_err(error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(item_class)) Ok(HttpResponse::Ok().json(item_class))
} }
#[delete("/item-class/{id}")] #[delete("/item-class/{id}")]
async fn delete( async fn delete(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
manage::item_class::delete(&mut pool.get().await.unwrap(), id) manage::item_class::delete(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;

View file

@ -6,12 +6,12 @@ use std::collections::HashMap;
use actix_web::{error, get, post, web, Responder}; use actix_web::{error, get, post, web, Responder};
use maud::html; use maud::html;
use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
use super::templates::{self, forms, TemplateConfig}; use super::templates::{self, forms, TemplateConfig};
use crate::manage; use crate::manage;
use crate::models::*; use crate::models::*;
use crate::DbPool;
pub fn config(cfg: &mut web::ServiceConfig) { pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(show_item) cfg.service(show_item)
@ -24,24 +24,24 @@ pub fn config(cfg: &mut web::ServiceConfig) {
#[get("/item/{id}")] #[get("/item/{id}")]
async fn show_item( async fn show_item(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item = manage::item::get(&mut pool.get().await.unwrap(), id) let item = manage::item::get(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
let item_classes = manage::item_class::get_all_as_map(&mut pool.get().await.unwrap()) let item_classes = manage::item_class::get_all_as_map(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
let parents = manage::item::get_parents_details(&mut pool.get().await.unwrap(), item.id) let parents = manage::item::get_parents_details(&pool, item.id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
let children = manage::item::get_children(&mut pool.get().await.unwrap(), item.id) let children = manage::item::get_children(&pool, item.id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -100,20 +100,20 @@ async fn show_item(
} }
#[get("/items")] #[get("/items")]
async fn list_items(pool: web::Data<DbPool>) -> actix_web::Result<impl Responder> { async fn list_items(pool: web::Data<PgPool>) -> actix_web::Result<impl Responder> {
let item_list = manage::item::get_all(&mut pool.get().await.unwrap()) let item_list = manage::item::get_all(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
let items = manage::item::get_all_as_map(&mut pool.get().await.unwrap()) let items = manage::item::get_all_as_map(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
let item_classes = manage::item_class::get_all_as_map(&mut pool.get().await.unwrap()) let item_classes = manage::item_class::get_all_as_map(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
let item_tree = manage::item::get_all_parents(&mut pool.get().await.unwrap()) let item_tree = manage::item::get_all_parents(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -212,9 +212,9 @@ async fn add_item() -> actix_web::Result<impl Responder> {
#[post("/items/add")] #[post("/items/add")]
async fn add_item_post( async fn add_item_post(
data: web::Form<NewItem>, data: web::Form<NewItem>,
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let item = manage::item::add(&mut pool.get().await.unwrap(), data.into_inner()) let item = manage::item::add(&pool, data.into_inner())
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
Ok(web::Redirect::to("/item/".to_owned() + &item.id.to_string()).see_other()) Ok(web::Redirect::to("/item/".to_owned() + &item.id.to_string()).see_other())
@ -222,16 +222,16 @@ async fn add_item_post(
#[get("/item/{id}/edit")] #[get("/item/{id}/edit")]
async fn edit_item( async fn edit_item(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item = manage::item::get(&mut pool.get().await.unwrap(), id) let item = manage::item::get(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
let item_class = manage::item_class::get(&mut pool.get().await.unwrap(), item.class) let item_class = manage::item_class::get(&pool, item.class)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -289,13 +289,13 @@ async fn edit_item(
#[post("/item/{id}/edit")] #[post("/item/{id}/edit")]
async fn edit_item_post( async fn edit_item_post(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
data: web::Form<NewItem>, data: web::Form<NewItem>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item = manage::item::update(&mut pool.get().await.unwrap(), id, data.into_inner()) let item = manage::item::update(&pool, id, data.into_inner())
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;

View file

@ -4,12 +4,12 @@
use actix_web::{error, get, post, web, Responder}; use actix_web::{error, get, post, web, Responder};
use maud::html; use maud::html;
use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
use super::templates::{self, forms, TemplateConfig}; use super::templates::{self, forms, TemplateConfig};
use crate::manage; use crate::manage;
use crate::models::*; use crate::models::*;
use crate::DbPool;
pub fn config(cfg: &mut web::ServiceConfig) { pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(show_item_class) cfg.service(show_item_class)
@ -22,27 +22,25 @@ pub fn config(cfg: &mut web::ServiceConfig) {
#[get("/item-class/{id}")] #[get("/item-class/{id}")]
async fn show_item_class( async fn show_item_class(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let mut conn = pool.clone().get().await.unwrap(); let item_class = manage::item_class::get(&pool, id)
let item_class = manage::item_class::get(&mut conn, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
// TODO: Once async closures are stable, use map_or on item_class.parent instead // TODO: Once async closures are stable, use map_or on item_class.parent instead
let parent = match item_class.parent { let parent = match item_class.parent {
Some(id) => manage::item_class::get(&mut conn, id) Some(id) => manage::item_class::get(&pool, id)
.await .await
.map(Some) .map(Some)
.map_err(error::ErrorInternalServerError)?, .map_err(error::ErrorInternalServerError)?,
None => None, None => None,
}; };
let children = manage::item_class::children(&mut conn, id) let children = manage::item_class::children(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -96,8 +94,8 @@ async fn show_item_class(
} }
#[get("/item-classes")] #[get("/item-classes")]
async fn list_item_classes(pool: web::Data<DbPool>) -> actix_web::Result<impl Responder> { async fn list_item_classes(pool: web::Data<PgPool>) -> actix_web::Result<impl Responder> {
let item_classes = manage::item_class::get_all_as_map(&mut pool.get().await.unwrap()) let item_classes = manage::item_class::get_all_as_map(&pool)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -177,9 +175,9 @@ async fn add_item_class() -> actix_web::Result<impl Responder> {
#[post("/item-classes/add")] #[post("/item-classes/add")]
async fn add_item_class_post( async fn add_item_class_post(
data: web::Form<NewItemClass>, data: web::Form<NewItemClass>,
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let item = manage::item_class::add(&mut pool.get().await.unwrap(), data.into_inner()) let item = manage::item_class::add(&pool, data.into_inner())
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
Ok(web::Redirect::to("/item-class/".to_owned() + &item.id.to_string()).see_other()) Ok(web::Redirect::to("/item-class/".to_owned() + &item.id.to_string()).see_other())
@ -187,12 +185,12 @@ async fn add_item_class_post(
#[get("/item-class/{id}/edit")] #[get("/item-class/{id}/edit")]
async fn edit_item_class( async fn edit_item_class(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item_class = manage::item_class::get(&mut pool.get().await.unwrap(), id) let item_class = manage::item_class::get(&pool, id)
.await .await
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
@ -241,16 +239,15 @@ async fn edit_item_class(
#[post("/item-class/{id}/edit")] #[post("/item-class/{id}/edit")]
async fn edit_item_class_post( async fn edit_item_class_post(
pool: web::Data<DbPool>, pool: web::Data<PgPool>,
path: web::Path<Uuid>, path: web::Path<Uuid>,
data: web::Form<NewItemClass>, data: web::Form<NewItemClass>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();
let item_class = let item_class = manage::item_class::update(&pool, id, data.into_inner())
manage::item_class::update(&mut pool.get().await.unwrap(), id, data.into_inner()) .await
.await .map_err(error::ErrorInternalServerError)?;
.map_err(error::ErrorInternalServerError)?;
Ok(web::Redirect::to("/item-class/".to_owned() + &item_class.id.to_string()).see_other()) Ok(web::Redirect::to("/item-class/".to_owned() + &item_class.id.to_string()).see_other())
} }

View file

@ -7,9 +7,3 @@ pub mod frontend;
pub mod label; pub mod label;
pub mod manage; pub mod manage;
pub mod models; pub mod models;
pub mod schema;
use diesel_async::pg::AsyncPgConnection;
use diesel_async::pooled_connection::deadpool::Pool;
type DbPool = Pool<AsyncPgConnection>;

View file

@ -5,41 +5,22 @@
use std::env; use std::env;
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
use diesel::pg::Pg;
use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
use diesel_async::pg::AsyncPgConnection;
use diesel_async::pooled_connection::deadpool::Pool;
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
use diesel_async::AsyncConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use log::{debug, info}; use log::{debug, info};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
// adapted from https://github.com/weiznich/diesel_async/blob/002c67e4d09acd9b38d0fb08ff0efc24954b2558/examples/sync-wrapper/src/main.rs#L36-L48
async fn run_migrations<A: AsyncConnection<Backend = Pg> + 'static>(async_connection: A) {
let mut async_wrapper: AsyncConnectionWrapper<A> =
AsyncConnectionWrapper::from(async_connection);
web::block(move || {
async_wrapper.run_pending_migrations(MIGRATIONS).unwrap();
})
.await
.expect("failed to run migrations");
}
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
env_logger::init(); env_logger::init();
let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new( let pool: sqlx::PgPool = sqlx::Pool::<sqlx::postgres::Postgres>::connect(
env::var("DATABASE_URL").expect("DATABASE_URL must be set"), &env::var("DATABASE_URL").expect("DATABASE_URL must be set"),
); )
let pool: Pool<AsyncPgConnection> = Pool::builder(manager) .await
.build() .expect("failed to connect to database");
.expect("database URL must be valid");
run_migrations(pool.get().await.unwrap()).await; sqlx::migrate!()
.run(&pool)
.await
.expect("failed to run migrations");
let address = env::var("LISTEN_ADDRESS").unwrap_or("::1".to_string()); let address = env::var("LISTEN_ADDRESS").unwrap_or("::1".to_string());
let port = env::var("LISTEN_PORT").map_or(8080, |s| { let port = env::var("LISTEN_PORT").map_or(8080, |s| {

View file

@ -4,132 +4,95 @@
use std::collections::HashMap; use std::collections::HashMap;
use diesel::prelude::*; use sqlx::{query, query_as, query_scalar, PgPool};
use diesel::sql_types;
use diesel_async::pg::AsyncPgConnection;
use diesel_async::RunQueryDsl;
use uuid::Uuid; use uuid::Uuid;
use crate::{models::*, schema}; use crate::models::{Item, NewItem};
pub async fn add( pub async fn add(pool: &PgPool, new_item: NewItem) -> Result<Item, sqlx::Error> {
conn: &mut AsyncPgConnection, query_as!(
new_item: NewItem, Item,
) -> Result<Item, diesel::result::Error> { "INSERT INTO items (name, parent, class) VALUES ($1, $2, $3) RETURNING *",
diesel::insert_into(schema::items::table) new_item.name,
.values(new_item) new_item.parent,
.returning(Item::as_returning()) new_item.class
.get_result(conn) )
.fetch_one(pool)
.await
}
pub async fn get(pool: &PgPool, id: Uuid) -> Result<Item, sqlx::Error> {
query_as!(Item, "SELECT * FROM items WHERE id = $1", id)
.fetch_one(pool)
.await .await
} }
pub async fn get(conn: &mut AsyncPgConnection, id: Uuid) -> Result<Item, diesel::result::Error> { pub async fn get_all(pool: &PgPool) -> Result<Vec<Item>, sqlx::Error> {
schema::items::table query_as!(Item, "SELECT * FROM items").fetch_all(pool).await
.filter(schema::items::id.eq(id))
.select(Item::as_select())
.first(conn)
.await
} }
pub async fn get_all(conn: &mut AsyncPgConnection) -> Result<Vec<Item>, diesel::result::Error> { pub async fn get_all_as_map(pool: &PgPool) -> Result<HashMap<Uuid, Item>, sqlx::Error> {
schema::items::table Ok(get_all(pool)
.select(Item::as_select())
.load(conn)
.await
}
pub async fn get_all_as_map(
conn: &mut AsyncPgConnection,
) -> Result<HashMap<Uuid, Item>, diesel::result::Error> {
Ok(get_all(conn)
.await? .await?
.into_iter() .into_iter()
.map(|i| (i.id, i)) .map(|i| (i.id, i))
.collect()) .collect())
} }
pub async fn update( pub async fn update(pool: &PgPool, id: Uuid, modified_item: NewItem) -> Result<Item, sqlx::Error> {
conn: &mut AsyncPgConnection, query_as!(
id: Uuid, Item,
modified_item: NewItem, "UPDATE items SET name = $2, parent = $3, class = $4 WHERE id = $1 RETURNING *",
) -> Result<Item, diesel::result::Error> { id,
diesel::update(schema::items::table.filter(schema::items::id.eq(id))) modified_item.name,
.set(modified_item) modified_item.parent,
.returning(Item::as_returning()) modified_item.class
.get_result(conn) )
.await .fetch_one(pool)
.await
} }
pub async fn delete(conn: &mut AsyncPgConnection, id: Uuid) -> Result<(), diesel::result::Error> { pub async fn delete(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
let num_deleted = diesel::delete(schema::items::table.filter(schema::items::id.eq(id))) let res = query!("DELETE FROM items WHERE id = $1", id)
.execute(conn) .execute(pool)
.await?; .await?;
assert_eq!(num_deleted, 1); assert_eq!(res.rows_affected(), 1);
Ok(()) Ok(())
} }
/// Helper type for querying parents of items pub async fn get_parents(pool: &PgPool, id: Uuid) -> Result<Vec<Uuid>, sqlx::Error> {
#[derive(Debug, Queryable, Selectable)] // force nullable is required for all columns in views
#[diesel(table_name = schema::item_tree)] query_scalar!(
#[diesel(check_for_backend(diesel::pg::Pg))] r#"SELECT unnest(parents) as "parents!" FROM item_tree WHERE id = $1"#,
struct ItemTreeMapping { id
pub id: Uuid, )
pub parents: Vec<Uuid>, .fetch_all(pool)
.await
} }
pub async fn get_parents( pub async fn get_all_parents(pool: &PgPool) -> Result<HashMap<Uuid, Vec<Uuid>>, sqlx::Error> {
conn: &mut AsyncPgConnection, let mut parents = HashMap::new();
id: Uuid, for row in query!(r#"SELECT id as "id!", parents as "parents!" FROM item_tree"#)
) -> Result<Vec<Uuid>, diesel::result::Error> { .fetch_all(pool)
schema::item_tree::table .await?
.filter(schema::item_tree::id.eq(id)) {
.select(ItemTreeMapping::as_select()) parents.insert(row.id, row.parents);
.first(conn) }
.await Ok(parents)
.map(|itm| itm.parents)
} }
pub async fn get_all_parents( pub async fn get_parents_details(pool: &PgPool, id: Uuid) -> Result<Vec<Item>, sqlx::Error> {
conn: &mut AsyncPgConnection, query_as!(
) -> Result<HashMap<Uuid, Vec<Uuid>>, diesel::result::Error> { Item,
schema::item_tree::table "SELECT * FROM items WHERE id = ANY (SELECT unnest(parents) FROM item_tree WHERE id = $1)",
.select(ItemTreeMapping::as_select()) id
.load(conn) )
.await .fetch_all(pool)
.map(|itms| { .await
itms.into_iter()
.map(|ItemTreeMapping { id, parents }| (id, parents))
.collect::<HashMap<Uuid, Vec<Uuid>>>()
})
} }
pub async fn get_parents_details( pub async fn get_children(pool: &PgPool, id: Uuid) -> Result<Vec<Item>, sqlx::Error> {
conn: &mut AsyncPgConnection, query_as!(Item, "SELECT * FROM items WHERE parent = $1", id)
id: Uuid, .fetch_all(pool)
) -> Result<Vec<Item>, diesel::result::Error> {
define_sql_function!(fn unnest(a: sql_types::Array<sql_types::Uuid>) -> sql_types::Uuid);
schema::items::table
.filter(
schema::items::id.eq_any(
schema::item_tree::table
.filter(schema::item_tree::id.eq(id))
.select(unnest(schema::item_tree::parents))
.into_boxed(),
),
)
.select(Item::as_select())
.load(conn)
.await
}
pub async fn get_children(
conn: &mut AsyncPgConnection,
id: Uuid,
) -> Result<Vec<Item>, diesel::result::Error> {
schema::items::table
.filter(schema::items::parent.eq(id))
.select(Item::as_select())
.load(conn)
.await .await
} }

View file

@ -4,48 +4,36 @@
use std::collections::HashMap; use std::collections::HashMap;
use diesel::prelude::*; use sqlx::{query, query_as, PgPool};
use diesel_async::pg::AsyncPgConnection;
use diesel_async::RunQueryDsl;
use uuid::Uuid; use uuid::Uuid;
use crate::{models::*, schema}; use crate::models::{Item, ItemClass, NewItemClass};
pub async fn add( pub async fn add(pool: &PgPool, new_item_class: NewItemClass) -> Result<ItemClass, sqlx::Error> {
conn: &mut AsyncPgConnection, query_as!(
new_item_class: NewItemClass, ItemClass,
) -> Result<ItemClass, diesel::result::Error> { "INSERT INTO item_classes (name, parent) VALUES ($1, $2) RETURNING *",
diesel::insert_into(schema::item_classes::table) new_item_class.name,
.values(new_item_class) new_item_class.parent
.returning(ItemClass::as_returning()) )
.get_result(conn) .fetch_one(pool)
.await
}
pub async fn get(pool: &PgPool, id: Uuid) -> Result<ItemClass, sqlx::Error> {
query_as!(ItemClass, "SELECT * FROM item_classes WHERE id = $1", id)
.fetch_one(pool)
.await .await
} }
pub async fn get( pub async fn get_all(pool: &PgPool) -> Result<Vec<ItemClass>, sqlx::Error> {
conn: &mut AsyncPgConnection, query_as!(ItemClass, "SELECT * FROM item_classes")
id: Uuid, .fetch_all(pool)
) -> Result<ItemClass, diesel::result::Error> {
schema::item_classes::table
.filter(schema::item_classes::id.eq(id))
.select(ItemClass::as_select())
.first(conn)
.await .await
} }
pub async fn get_all( pub async fn get_all_as_map(pool: &PgPool) -> Result<HashMap<Uuid, ItemClass>, sqlx::Error> {
conn: &mut AsyncPgConnection, Ok(get_all(pool)
) -> Result<Vec<ItemClass>, diesel::result::Error> {
schema::item_classes::table
.select(ItemClass::as_select())
.load(conn)
.await
}
pub async fn get_all_as_map(
conn: &mut AsyncPgConnection,
) -> Result<HashMap<Uuid, ItemClass>, diesel::result::Error> {
Ok(get_all(conn)
.await? .await?
.into_iter() .into_iter()
.map(|ic| (ic.id, ic)) .map(|ic| (ic.id, ic))
@ -53,44 +41,41 @@ pub async fn get_all_as_map(
} }
pub async fn update( pub async fn update(
conn: &mut AsyncPgConnection, pool: &PgPool,
id: Uuid, id: Uuid,
modified_item_class: NewItemClass, modified_item_class: NewItemClass,
) -> Result<ItemClass, diesel::result::Error> { ) -> Result<ItemClass, sqlx::Error> {
diesel::update(schema::item_classes::table.filter(schema::item_classes::id.eq(id))) query_as!(
.set(modified_item_class) ItemClass,
.returning(ItemClass::as_returning()) "UPDATE item_classes SET name = $2, parent = $3 WHERE id = $1 RETURNING *",
.get_result(conn) id,
modified_item_class.name,
modified_item_class.parent
)
.fetch_one(pool)
.await
}
pub async fn items(pool: &PgPool, id: Uuid) -> Result<Vec<Item>, sqlx::Error> {
query_as!(Item, "SELECT * FROM items WHERE class = $1", id)
.fetch_all(pool)
.await .await
} }
pub async fn items( pub async fn delete(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
conn: &mut AsyncPgConnection, let res = query!("DELETE FROM item_classes WHERE id = $1", id)
id: Uuid, .execute(pool)
) -> Result<Vec<Item>, diesel::result::Error> { .await?;
schema::items::table assert_eq!(res.rows_affected(), 1);
.filter(schema::items::class.eq(id))
.select(Item::as_select())
.load(conn)
.await
}
pub async fn delete(conn: &mut AsyncPgConnection, id: Uuid) -> Result<(), diesel::result::Error> {
let num_deleted =
diesel::delete(schema::item_classes::table.filter(schema::item_classes::id.eq(id)))
.execute(conn)
.await?;
assert_eq!(num_deleted, 1);
Ok(()) Ok(())
} }
pub async fn children( pub async fn children(pool: &PgPool, id: Uuid) -> Result<Vec<ItemClass>, sqlx::Error> {
conn: &mut AsyncPgConnection, query_as!(
id: Uuid, ItemClass,
) -> Result<Vec<ItemClass>, diesel::result::Error> { "SELECT * FROM item_classes WHERE parent = $1",
schema::item_classes::table id
.filter(schema::item_classes::parent.eq(id)) )
.select(ItemClass::as_select()) .fetch_all(pool)
.load(conn) .await
.await
} }

View file

@ -2,15 +2,10 @@
// //
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
use diesel::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use uuid::Uuid; use uuid::Uuid;
use crate::schema::*; #[derive(Clone, Debug, Serialize, sqlx::FromRow)]
#[derive(Clone, Debug, Queryable, Selectable, Insertable, Serialize)]
#[diesel(table_name = items)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct Item { pub struct Item {
pub id: Uuid, pub id: Uuid,
pub name: Option<String>, pub name: Option<String>,
@ -18,10 +13,7 @@ pub struct Item {
pub class: Uuid, pub class: Uuid,
} }
#[derive(Debug, Insertable, Deserialize, AsChangeset)] #[derive(Debug, Deserialize)]
#[diesel(table_name = items)]
#[diesel(check_for_backend(diesel::pg::Pg))]
#[diesel(treat_none_as_null = true)]
pub struct NewItem { pub struct NewItem {
#[serde(default)] #[serde(default)]
pub name: Option<String>, pub name: Option<String>,
@ -30,9 +22,7 @@ pub struct NewItem {
pub class: Uuid, pub class: Uuid,
} }
#[derive(Clone, Debug, Queryable, Selectable, Insertable, Serialize)] #[derive(Clone, Debug, Serialize)]
#[diesel(table_name = item_classes)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct ItemClass { pub struct ItemClass {
pub id: Uuid, pub id: Uuid,
pub name: String, pub name: String,
@ -40,10 +30,7 @@ pub struct ItemClass {
pub parent: Option<Uuid>, pub parent: Option<Uuid>,
} }
#[derive(Debug, Insertable, Deserialize, AsChangeset)] #[derive(Debug, Deserialize)]
#[diesel(table_name = item_classes)]
#[diesel(check_for_backend(diesel::pg::Pg))]
#[diesel(treat_none_as_null = true)]
pub struct NewItemClass { pub struct NewItemClass {
pub name: String, pub name: String,
#[serde(default)] #[serde(default)]

View file

@ -1,32 +0,0 @@
// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
diesel::table! {
items (id) {
id -> Uuid,
name -> Nullable<Varchar>,
parent -> Nullable<Uuid>,
class -> Uuid,
}
}
diesel::table! {
item_tree (id) {
id -> Uuid,
parents -> Array<Uuid>,
}
}
diesel::table! {
item_classes (id) {
id -> Uuid,
name -> Varchar,
parent -> Nullable<Uuid>,
}
}
diesel::joinable!(items -> item_classes (class));
diesel::allow_tables_to_appear_in_same_query!(item_classes, items);
diesel::allow_tables_to_appear_in_same_query!(items, item_tree);