Skip to main content

che_orm/
lib.rs

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