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 query;
63mod schema;
64mod sql;
65mod types;
66
67#[cfg(feature = "sqlite")]
68mod connection;
69
70pub use query::*;
71pub use schema::*;
72pub use sql::*;
73pub use types::*;
74
75/// Serializes a timestamp in the RFC 3339 format used by JSON API clients.
76pub struct Rfc3339Timestamp<'a>(pub &'a time::OffsetDateTime);
77
78impl serde::Serialize for Rfc3339Timestamp<'_> {
79    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
80    where
81        S: serde::Serializer,
82    {
83        time::serde::rfc3339::serialize(self.0, serializer)
84    }
85}
86
87/// Serializes an optional timestamp in RFC 3339 when it has a value.
88pub struct OptionalRfc3339Timestamp<'a>(pub &'a Option<time::OffsetDateTime>);
89
90impl serde::Serialize for OptionalRfc3339Timestamp<'_> {
91    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
92    where
93        S: serde::Serializer,
94    {
95        time::serde::rfc3339::option::serialize(self.0, serializer)
96    }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum WriteMode {
101    Create,
102    Update { id: i64 },
103    Patch { id: i64 },
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct ValidationErrors {
108    pub detail: String,
109}
110
111impl From<serde_json::Error> for ValidationErrors {
112    fn from(error: serde_json::Error) -> Self {
113        Self {
114            detail: error.to_string(),
115        }
116    }
117}
118
119pub enum ValidatedWrite<M: Model> {
120    Create(InsertQuery<M>),
121    Update(UpdateQuery<M>),
122}
123
124impl<M: Model> ValidatedWrite<M> {
125    pub fn set<T, V>(self, field: ModelField<M, T>, value: V) -> Self
126    where
127        V: QueryValue<T>,
128    {
129        match self {
130            Self::Create(query) => Self::Create(query.set(field, value)),
131            Self::Update(query) => Self::Update(query.set(field, value)),
132        }
133    }
134}
135
136pub trait ModelWriteSerializer {
137    type Model: Model;
138
139    fn is_valid(
140        data: serde_json::Value,
141        mode: WriteMode,
142    ) -> Result<ValidatedWrite<Self::Model>, ValidationErrors>;
143}
144
145/// A JSON patch value. `Missing` means that the property was not sent;
146/// `Value(None)` represents an explicit JSON null.
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
148pub enum PatchField<T> {
149    #[default]
150    Missing,
151    Value(T),
152}
153
154impl<T> PatchField<T> {
155    pub const fn is_missing(&self) -> bool {
156        matches!(self, Self::Missing)
157    }
158}
159
160impl<'de, T> serde::Deserialize<'de> for PatchField<T>
161where
162    T: serde::Deserialize<'de>,
163{
164    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
165    where
166        D: serde::Deserializer<'de>,
167    {
168        T::deserialize(deserializer).map(Self::Value)
169    }
170}
171
172/// Deserializes an RFC 3339 timestamp sent by JSON API clients.
173pub fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<time::OffsetDateTime, D::Error>
174where
175    D: serde::Deserializer<'de>,
176{
177    time::serde::rfc3339::deserialize(deserializer)
178}
179
180/// Deserializes an optional RFC 3339 timestamp sent by JSON API clients.
181pub fn deserialize_optional_rfc3339<'de, D>(
182    deserializer: D,
183) -> Result<Option<time::OffsetDateTime>, D::Error>
184where
185    D: serde::Deserializer<'de>,
186{
187    time::serde::rfc3339::option::deserialize(deserializer)
188}
189
190/// Deserializes an RFC 3339 timestamp while preserving patch-field presence.
191pub fn deserialize_patch_rfc3339<'de, D>(
192    deserializer: D,
193) -> Result<PatchField<time::OffsetDateTime>, D::Error>
194where
195    D: serde::Deserializer<'de>,
196{
197    deserialize_rfc3339(deserializer).map(PatchField::Value)
198}
199
200/// Deserializes an optional RFC 3339 timestamp while preserving patch-field presence.
201pub fn deserialize_patch_optional_rfc3339<'de, D>(
202    deserializer: D,
203) -> Result<PatchField<Option<time::OffsetDateTime>>, D::Error>
204where
205    D: serde::Deserializer<'de>,
206{
207    deserialize_optional_rfc3339(deserializer).map(PatchField::Value)
208}
209
210#[cfg(feature = "sqlite")]
211pub use connection::*;
212
213#[cfg(all(feature = "postgres", feature = "sqlite"))]
214compile_error!("features `postgres` and `sqlite` are mutually exclusive");
215
216#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
217compile_error!("enable exactly one database backend: `postgres` or `sqlite`");
218
219#[cfg(test)]
220mod tests;