Skip to main content

che_orm/
lib.rs

1//! `che-orm` — экспериментальная типизированная ORM для Rust.
2//!
3//! Runtime сейчас ориентирован на SQLite: [`Database`] предоставляет async
4//! pool и high-level CRUD/query facade, а [`Model`] derive генерирует metadata,
5//! row decoding и insert values. SQL можно также использовать отдельно через
6//! [`SqlCompiler`].
7//!
8//! Основной рабочий сценарий:
9//!
10//! ```ignore
11//! use che_orm::{Database, Model};
12//!
13//! # #[derive(Debug, Model)]
14//! # #[orm(table = "users")]
15//! # struct User {
16//! #     #[orm(primary_key)]
17//! #     id: i64,
18//! #     name: String,
19//! # }
20//! # #[tokio::main]
21//! # async fn run() -> Result<(), che_orm::OrmError> {
22//! let database = Database::connect_in_memory()?;
23//! database.create_table::<User>().await?;
24//! let user = database
25//!     .create::<User>()
26//!     .set(User::NAME, "Alice")
27//!     .execute()
28//!     .await?;
29//! let loaded = database.get::<User>(user.id).await?;
30//! assert!(loaded.is_some());
31//! # Ok(())
32//! # }
33//! ```
34//!
35//! Fixed string choices use [`DbEnum`]. It owns the JSON and database value,
36//! so a variant has one canonical representation everywhere:
37//!
38//! ```ignore
39//! # use che_orm::DbEnum;
40//! #[derive(Debug, Clone, Copy, DbEnum)]
41//! enum TaskStatus {
42//!     Draft,
43//!     #[db_enum(rename = "in_progress")]
44//!     InProgress,
45//! }
46//! ```
47//!
48//! Do not derive `serde::Serialize` or `serde::Deserialize` for a `DbEnum`;
49//! the derive generates both implementations.
50
51#![allow(clippy::type_complexity, clippy::new_without_default)]
52
53extern crate self as che_orm;
54
55pub use che_orm_macros::{DbEnum, Model, ModelSerializer};
56
57pub use rusqlite;
58pub use serde;
59pub use serde_json;
60pub use time;
61
62mod image;
63pub mod migration;
64mod query;
65mod schema;
66mod sql;
67mod types;
68
69#[cfg(feature = "sqlite")]
70mod connection;
71
72pub use image::ImageField;
73pub use migration::*;
74pub use query::*;
75pub use schema::*;
76pub use sql::*;
77pub use types::*;
78
79/// Serializes a timestamp in the RFC 3339 format used by JSON API clients.
80pub struct Rfc3339Timestamp<'a>(pub &'a time::OffsetDateTime);
81
82impl serde::Serialize for Rfc3339Timestamp<'_> {
83    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
84    where
85        S: serde::Serializer,
86    {
87        time::serde::rfc3339::serialize(self.0, serializer)
88    }
89}
90
91/// Serializes an optional timestamp in RFC 3339 when it has a value.
92pub struct OptionalRfc3339Timestamp<'a>(pub &'a Option<time::OffsetDateTime>);
93
94impl serde::Serialize for OptionalRfc3339Timestamp<'_> {
95    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
96    where
97        S: serde::Serializer,
98    {
99        time::serde::rfc3339::option::serialize(self.0, serializer)
100    }
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum WriteMode {
105    Create,
106    Update { id: i64 },
107    Patch { id: i64 },
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct ValidationErrors {
112    pub detail: String,
113}
114
115impl From<serde_json::Error> for ValidationErrors {
116    fn from(error: serde_json::Error) -> Self {
117        Self {
118            detail: error.to_string(),
119        }
120    }
121}
122
123pub enum ValidatedWrite<M: Model> {
124    Create(InsertQuery<M>),
125    Update(UpdateQuery<M>),
126}
127
128impl<M: Model> ValidatedWrite<M> {
129    pub fn set<T, V>(self, field: ModelField<M, T>, value: V) -> Self
130    where
131        V: QueryValue<T>,
132    {
133        match self {
134            Self::Create(query) => Self::Create(query.set(field, value)),
135            Self::Update(query) => Self::Update(query.set(field, value)),
136        }
137    }
138}
139
140pub trait ModelWriteSerializer {
141    type Model: Model;
142
143    fn is_valid(
144        data: serde_json::Value,
145        mode: WriteMode,
146    ) -> Result<ValidatedWrite<Self::Model>, ValidationErrors>;
147}
148
149/// A JSON patch value. `Missing` means that the property was not sent;
150/// `Value(None)` represents an explicit JSON null.
151#[derive(Debug, Clone, Default, PartialEq, Eq)]
152pub enum PatchField<T> {
153    #[default]
154    Missing,
155    Value(T),
156}
157
158impl<T> PatchField<T> {
159    pub const fn is_missing(&self) -> bool {
160        matches!(self, Self::Missing)
161    }
162}
163
164impl<'de, T> serde::Deserialize<'de> for PatchField<T>
165where
166    T: serde::Deserialize<'de>,
167{
168    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
169    where
170        D: serde::Deserializer<'de>,
171    {
172        T::deserialize(deserializer).map(Self::Value)
173    }
174}
175
176/// Deserializes an RFC 3339 timestamp sent by JSON API clients.
177pub fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<time::OffsetDateTime, D::Error>
178where
179    D: serde::Deserializer<'de>,
180{
181    time::serde::rfc3339::deserialize(deserializer)
182}
183
184/// Deserializes an optional RFC 3339 timestamp sent by JSON API clients.
185pub fn deserialize_optional_rfc3339<'de, D>(
186    deserializer: D,
187) -> Result<Option<time::OffsetDateTime>, D::Error>
188where
189    D: serde::Deserializer<'de>,
190{
191    time::serde::rfc3339::option::deserialize(deserializer)
192}
193
194/// Deserializes an RFC 3339 timestamp while preserving patch-field presence.
195pub fn deserialize_patch_rfc3339<'de, D>(
196    deserializer: D,
197) -> Result<PatchField<time::OffsetDateTime>, D::Error>
198where
199    D: serde::Deserializer<'de>,
200{
201    deserialize_rfc3339(deserializer).map(PatchField::Value)
202}
203
204/// Deserializes an optional RFC 3339 timestamp while preserving patch-field presence.
205pub fn deserialize_patch_optional_rfc3339<'de, D>(
206    deserializer: D,
207) -> Result<PatchField<Option<time::OffsetDateTime>>, D::Error>
208where
209    D: serde::Deserializer<'de>,
210{
211    deserialize_optional_rfc3339(deserializer).map(PatchField::Value)
212}
213
214#[cfg(feature = "sqlite")]
215pub use connection::*;
216
217#[cfg(all(feature = "postgres", feature = "sqlite"))]
218compile_error!("features `postgres` and `sqlite` are mutually exclusive");
219
220#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
221compile_error!("enable exactly one database backend: `postgres` or `sqlite`");
222
223#[cfg(test)]
224mod tests;